Function Calling:让大模型学会使用工具
其实从实际来讲,Function Calling并不是让大模型自己调用工具,而是大模型告诉用户自己需要调用哪些工具,然后再由程序去调用工具。
这么做有什么好处呢?模型的知识是有限的,为了让模型的回答更精准,我们需要提供问题相关的上下文,上下文与问题关联性越大,模型的回答就越准确,而Function Calling可以给大模型提供精准的上下文。从另外一个角度讲,大模型本身其实只能回答用户问题,但是引入Function Calling可以拓展模型的能力边界,理想情况下模型的能力可以与程序所具有的能力一样。
Function Calling的框架流程
- 用户提问
- 模型生成需要使用的工具集
- 调用工具并整合结果
- 返回工具调用结果给大模型并输出最终结果
python 编码实现
from openai import OpenAI
import json
"""
1. 初始化 OpenAI 客户端
2. 定义一个函数,向模型发送消息
3. 定义工具函数
4. 定义模型可以调用的工具
5. 向模型发送用户消息
6. 处理模型的响应,包括工具调用
7. 根据工具调用调用相应的函数
8. 将结果发送回模型
9. 打印模型的最终响应
"""
client = OpenAI(
api_key="sk-*********************", #替换成你自己的APIkey
base_url="https://api.deepseek.com",
)
def send_messages(messages):
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
return response.choices[0].message
def get_weather(location):
# 模拟获取天气信息的函数
# 实际应用中可以调用天气API获取实时数据
return f"The weather in {location} is sunny with a temperature of 40℃."
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}]
message = send_messages(messages) # Send the initial user message 模型判断是否需要调用工具,需要调用工具时会返回tool_calls
messages.append(message)
tool = message.tool_calls[0]
if tool.function.name == "get_weather":
location = json.loads(tool.function.arguments)
content = get_weather(location)
messages.append({"role": "tool", "tool_call_id": tool.id, "content": content})
message = send_messages(messages)
print(f"Model>\t {message.content}")