Travel_Agent_AI / travel_agent_ai.py
ivanyeh1313's picture
Update travel_agent_ai.py
d0f9871
raw
history blame contribute delete
No virus
2.55 kB
import gradio as gr
import openai
import requests
import json
api_key = "AIzaSyDdiDlKE0XRsJAxR3eNOZNjBUjoexEuXLg"
openai.api_key = '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'
def find_place(input_text):
url = f"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={input_text}&inputtype=textquery&fields=formatted_address,name,rating,opening_hours,geometry&key={api_key}"
response = requests.get(url)
data = json.loads(response.text)
return data
def get_map_and_places(start_location, end_location, mode):
# 使用 Google Maps Directions API 來取得路線資訊
response = requests.get(f"https://maps.googleapis.com/maps/api/directions/json?origin={start_location}&destination={end_location}&mode={mode}&key={api_key}")
data = response.json()
# 取得路線上的所有步驟
steps = data["routes"][0]["legs"][0]["steps"]
# 對於終點,使用 find_place 函數來取得詳細資訊
destination_info = find_place(end_location)
# 建立一個 HTML 字串來顯示地圖和路線
map_html = f"""
<iframe
width="600"
height="450"
style="border:0"
loading="lazy"
allowfullscreen
src="https://www.google.com/maps/embed/v1/directions?key={api_key}&origin={start_location}&destination={end_location}&mode={mode}">
</iframe>
"""
# 執行 OpenAI API 請求並取得回應
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "你現在是資深旅行社導遊,必須以導遊的口吻,幽默的介紹行程以及景點的資訊,並提醒我當地注意事項"},
{"role": "user", "content": f"請根據我的地圖資料,告訴我行程規劃,行程規劃裡需要包含所需時間,推薦的沿路景點以及我的目的地資訊。地圖資料:```路線資料:{steps}```;```目的地:{destination_info}```"},
{"role": "assistant", "content": "身為您的在地導遊,建議您:"},
]
)
# 提取 OpenAI 回應中的內容
answer = response['choices'][0]['message']['content']
# 回傳 HTML 字串、景點詳細資訊和 OpenAI 的回應
return map_html, answer
# 建立 Gradio 介面
iface = gr.Interface(
fn=get_map_and_places,
inputs=[
"text",
"text",
gr.inputs.Dropdown(choices=["driving", "walking", "bicycling", "transit"], label="Mode of Transportation")
],
outputs=["html", "text"]
)
iface.launch()