1. 用戶查詢
  2. 解析用戶請求
  3. 調用高德地圖API獲取地理坐標
  4. 高德地圖API返回地理坐標
  5. 解析地理坐標
  6. 調用高德地圖API搜索附近興趣點
  7. 高德地圖API返回附近興趣點
  8. 整理并生成回復內容
  9. 返回結果給用戶
  10. 用戶繼續對話或結束

二、完整代碼

# 導入必要的庫和模塊
import openai
import os
from math import *
from icecream import ic
import json
import requests
import logging
# 設置日志記錄配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 加載環境變量
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

# 初始化OpenAI API密鑰和模型
openai.api_key = os.getenv('OPENAI_API_KEY')
openai.api_base = os.getenv('OPENAI_API_URL')
model = os.getenv('MODEL')
amap_key = os.getenv('GAODE_MAP_API_KEY')

# 通過高德地圖API獲取地點的經緯度坐標
# 用于查詢某個地點的地理坐標。
def get_location_coordinate(location, city="長沙"):
"""
根據地點和城市名稱,使用高德地圖API查詢并返回該地點的坐標。

參數:
location (str): 地點名稱。
city (str): 城市名稱,默認為“長沙”。

返回:
dict: 包含地點坐標信息的字典,如果沒有找到則返回None。
"""
url = f"https://restapi.amap.com/v5/place/text?key={amap_key}&keywords={location}&region={city}"
ic(url)
r = requests.get(url)
result = r.json()
if "pois" in result and result["pois"]:
return result["pois"][0]
return None

# 通過高德地圖API查詢給定坐標附近的興趣點(POIs)
#用于查詢地理坐標附近的某些信息(取決于用戶輸入的Keyword)
#這是用的高德地圖的開放接口,在使用本例之前,你需要先去高德地圖開放接口的官網(https://console.amap.com/dev/key/app)申請一個key,免費的。這里就不過多介紹了。
def search_nearby_pois(longitude, latitude, keyword):
"""
根據給定的經緯度和關鍵詞,使用高德地圖API查詢并返回附近的興趣點信息。

參數:
longitude (str): 經度。
latitude (str): 緯度。
keyword (str): 查詢關鍵詞。

返回:
str: 包含查詢結果的字符串,如果沒有找到則返回空字符串。
"""
url = f"https://restapi.amap.com/v5/place/around?key={amap_key}&keywords={keyword}&location={longitude},{latitude}"
ic(url)
r = requests.get(url)
result = r.json()
ans = ""
if "pois" in result and result["pois"]:
for i in range(min(3, len(result["pois"]))):
name = result["pois"][i]["name"]
address = result["pois"][i]["address"]
distance = result["pois"][i]["distance"]
ans += f"{name}\n{address}\n距離:{distance}米\n\n"
return ans

# 使用OpenAI API完成聊天對話
def get_completion(messages, model=model):
"""
根據輸入的消息列表,使用OpenAI API生成并返回聊天對話的回復。

參數:
messages (list): 消息列表,包含系統的和用戶的對話內容。
model (str): 使用的OpenAI模型,默認為環境變量中的MODEL。

返回:
dict: 包含OpenAI生成的回復信息的字典。
"""
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # 模型輸出的隨機性,0 表示隨機性最小
seed=1024, # 隨機種子保持不變,temperature 和 prompt 不變的情況下,輸出就會不變
tool_choice="auto", # 默認值,由系統自動決定,返回function call還是返回文字回復
tools=[{
"type": "function",
"function": {

"name": "get_location_coordinate",
"description": "根據POI名稱,獲得POI的經緯度坐標",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "POI名稱,必須是中文",
},
"city": {
"type": "string",
"description": "POI所在的城市名,必須是中文",
}
},
"required": ["location", "city"],
}
}
},
{
"type": "function",
"function": {
"name": "search_nearby_pois",
"description": "搜索給定坐標附近的poi",
"parameters": {
"type": "object",
"properties": {
"longitude": {
"type": "string",
"description": "中心點的經度",
},
"latitude": {
"type": "string",
"description": "中心點的緯度",
},
"keyword": {
"type": "string",
"description": "目標poi的關鍵字",
}
},
"required": ["longitude", "latitude", "keyword"],
}
}
}],
)
return response.choices[0].message

# 處理工具函數調用
def handle_tool_call(response, messages):
"""
處理聊天對話中的工具函數調用,根據調用的函數名稱和參數執行相應的操作,并將結果添加到消息列表中。

參數:
response (dict): 包含工具函數調用信息的響應字典。
messages (list): 消息列表,用于添加工具函數的調用結果。
"""
if response.tool_calls is not None:
for tool_call in response.tool_calls:
try:
args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError:
logging.error("解析工具函數參數失敗")
continue # 跳過當前循環
logging.info(f"調用: {tool_call.function.name}")
try:
if tool_call.function.name == "get_location_coordinate":
result = get_location_coordinate(**args)
elif tool_call.function.name == "search_nearby_pois":
result = search_nearby_pois(**args)
except Exception as e:
logging.error(f"調用 {tool_call.function.name} 出錯: {e}")
continue # 跳過當前循環
logging.info("函數返回: ")
logging.info(result)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": tool_call.function.name,
"content": str(result)
})

# 測試聊天對話流程
def test_promopt():
"""
測試聊天助手的功能,模擬用戶查詢長沙證券大廈附近的咖啡店。
"""
prompt = "長沙證券大廈附近的咖啡"
messages = [
{"role": "system", "content": "你是一個地圖通,你可以找到任何地址。"},
{"role": "user", "content": prompt}
]

try:
response = get_completion(messages)
except Exception as e:
logging.error(f"獲取初始響應失敗: {e}")
return

# 處理初始響應
if response.content is None:
response.content = "null"
messages.append(response)

logging.info("=====GPT回復=====")
logging.info(response)

while True:
handle_tool_call(response, messages)

# 檢查是否還有更多響應
try:
response = get_completion(messages)
except Exception as e:
logging.error(f"獲取后續響應失敗: {e}")
break
if response.content is None:
response.content = "null"
messages.append(response)
if not hasattr(response,'tool_calls'): # 如果沒有tool_calls屬性,則表示沒有更多響應
break
logging.info("=====最終回復=====")
logging.info(response.content)

# 主程序入口
if __name__ == '__main__':
test_promopt()

輸出

2024-06-05 22:54:59,119 - INFO - =====GPT回復=====
2024-06-05 22:54:59,120 - INFO - {
"role": "assistant",
"content": "null",
"tool_calls": [
{
"id": "call_aCIvrc4Vdey4RXYiCS5srQpC",
"type": "function",
"function": {
"name": "get_location_coordinate",
"arguments": "{\"location\":\"\u957f\u6c99\u8bc1\u5238\u5927\u53a6\",\"city\":\"\u957f\u6c99\"}"
}
}
]
}
2024-06-05 22:54:59,122 - INFO - 調用: get_location_coordinate
ic| url: 'https://restapi.amap.com/v5/place/text?key=22b2d81ac8d7ed9512e6bf177cf4fc4a&keywords=長沙證券大廈&region=長沙'
2024-06-05 22:55:00,646 - INFO - 函數返回:
2024-06-05 22:55:00,646 - INFO - {'parent': '', 'address': '車站北路459號(烈士公園東地鐵站2號口步行210米)', 'distance': '', 'pcode': '430000', 'adcode': '430102', 'pname': '湖南省', 'cityname': '長沙市', 'type': '商務住宅;樓宇;商務寫字樓', 'typecode': '120201', 'adname': '芙蓉區', 'citycode': '0731', 'name': '證券大廈(車站北路)', 'location': '113.007771,28.210813', 'id': 'B02DB044DJ'}
2024-06-05 22:55:02,727 - INFO - 調用: search_nearby_pois
ic| url: 'https://restapi.amap.com/v5/place/around?key=22b2d81ac8d7ed9512e6bf177cf4fc4a&keywords=咖啡&location=113.007771,28.210813'
2024-06-05 22:55:03,857 - INFO - 函數返回:
2024-06-05 22:55:03,857 - INFO - luckin coffee 瑞幸咖啡(步步高生活廣場店)
車站北路王府步步高生活商場1層1048號
距離:178米

咖啡因(車站路店)
車站北路170號瑞豐家園111門面(近冰火樓)
距離:356米

Wheat Espresso小麥咖啡(夢澤園商務樓店)
晚報大道63號夢澤園商務樓(烈士公園東地鐵站4號口旁)
距離:417米

2024-06-05 22:55:11,315 - INFO - =====最終回復=====
2024-06-05 22:55:11,316 - INFO - 長沙證券大廈附近有幾家咖啡店:
1. luckin coffee 瑞幸咖啡(步步高生活廣場店)
地址:車站北路王府步步高生活商場1層1048號,距離證券大廈約178米。
2. 咖啡因(車站路店)
地址:車站北路170號瑞豐家園111門面(近冰火樓),距離證券大廈約356米。
3. Wheat Espresso小麥咖啡(夢澤園商務樓店)
地址:晚報大道63號夢澤園商務樓(烈士公園東地鐵站4號口旁),距離證券大廈約417米。

結語

通過本文介紹的方法和代碼示例,我們可以輕松地結合OpenAI的大模型和高德地圖API,實現查找某個地址附近咖啡店的功能。這不僅可以提升我們的開發效率,也為我們提供了強大的工具來應對各種實際需求。希望本文能對你有所幫助!

文章轉自微信公眾號@智能體AI

上一篇:

HugggingFace 推理 API、推理端點和推理空間使用介紹

下一篇:

基于深度學習的農作物害蟲檢測系統(YOLOv8/YOLOv7/YOLOv6/YOLOv5+UI界面+訓練數據集)
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費