import requests
import json
# ===================== 配置 =====================
API_KEY = "sk-**********************************" # 替换为你的 API密钥
API_URL = "https://ai.hcrzx.com/v1/chat/completions"
MODEL = "qwen3.6-plus"
# =================================================
# --------------------- 1. 函数描述(给AI看的) ---------------------
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询某个城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "要查询天气的城市名称,例如:北京"
}
},
"required": ["city"]
}
}
}
]
# --------------------- 2. 调用大模型接口获取匹配到的函数和函数参数---------------------
def chat_with_function_call(user_query: str):
messages = [{"role": "user", "content": user_query}]
# ========== 第一步:发送请求,让AI判断是否需要调用函数 ==========
response = requests.post(
url=API_URL,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": MODEL,
"messages": messages,
"tools": tools,
"tool_choice": "auto", # 自动判断是否调用函数
"enable_thinking": False
}
)
if response.status_code != 200:
print("请求失败:", response.text)
return
res_json = response.json()
print("AI 响应:", json.dumps(res_json, indent=2, ensure_ascii=False))
# --------------------- 运行示例 ---------------------
if __name__ == "__main__":
chat_with_function_call("北京天气怎么样?"){
"choices": [
{
"message": {
"content": "",
"role": "assistant",
"tool_calls": [
{
"function": {
"arguments": "{\"city\": \"北京\"}",
"name": "get_weather"
},
"id": "call_af342ca644b7461082e7cef5",
"index": 0,
"type": "function"
}
]
},
"finish_reason": "tool_calls",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 286,
"completion_tokens": 25,
"total_tokens": 311,
"completion_tokens_details": {
"text_tokens": 25
},
"prompt_tokens_details": {
"text_tokens": 286
}
},
"created": 1778317438,
"system_fingerprint": null,
"model": "qwen3.6-plus",
"id": "chatcmpl-be66386f-c634-92eb-98e2-020fa91563d9"
}