function call
函数调用为模型提供了一种强大且灵活的方式,用于与您的代码或外部服务进行交互。这里给出一段示例代码,示例如何调用外部函数获取天气。
# 支持兼容OpenAI Python SDK 终端运行:pip install OpenAI
from openai import OpenAI
import json
## 函数调用接口,这里作为示意函数直接给出返回值
def get_weather(latitude,longtitude):
return 20
## 初始化客户端
client = OpenAI(
api_key= "API_KEY",
base_url= "https://www.sophnet.com/api/open-apis/v1"
)
## 创建tools
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"}
},
"required": ["latitude", "longitude"],
"additionalProperties": False
},
"strict": True
}
}]
## 创建Messages
messages = [{"role": "user", "content": "今日上海天气如何?"}]
## 第一次调用接口
completion = client.chat.completions.create(
model="DeepSeek-R1",
messages=messages,
tools=tools,
)
## 从第一次的结果中获取函数参数
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
## 调用函数获取结果
result = get_weather(args["latitude"], args["longitude"])
## 将第一次的回复以及函数返回值加入到messages中
messages.append(completion.choices[0].message) # append model's function call message
messages.append({ # append result message
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(result)
})
## 第二次调用接口
completion_2 = client.chat.completions.create(
model="DeepSeek-R1",
messages=messages,
tools=tools,
)
# 打印结果
print(completion_2.choices[0].message.content)