Function Calling:让大模型学会使用工具

Function Calling:让大模型学会使用工具

其实从实际来讲,Function Calling并不是让大模型自己调用工具,而是大模型告诉用户自己需要调用哪些工具,然后再由程序去调用工具。

这么做有什么好处呢?模型的知识是有限的,为了让模型的回答更精准,我们需要提供问题相关的上下文,上下文与问题关联性越大,模型的回答就越准确,而Function Calling可以给大模型提供精准的上下文。从另外一个角度讲,大模型本身其实只能回答用户问题,但是引入Function Calling可以拓展模型的能力边界,理想情况下模型的能力可以与程序所具有的能力一样。

Function Calling的框架流程

  1. 用户提问
  2. 模型生成需要使用的工具集
  3. 调用工具并整合结果
  4. 返回工具调用结果给大模型并输出最终结果

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}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值