Skip to content

大模型工具调用与函数调用

工具调用(Tool Use / Function Calling)赋予大模型与外部系统交互的能力,是从"聊天机器人"到"智能体"的关键跃迁。

工具调用

工具调用流程

python
# OpenAI Function Calling 流程
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "北京今天天气如何?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"]
            }
        }
    }]
)

if response.choices[0].message.tool_calls:
    for tc in response.choices[0].message.tool_calls:
        result = get_weather(**json.loads(tc.function.arguments))

多步工具使用

复杂任务需要链式工具调用:搜索 → 分析 → 执行 → 验证。关键挑战是工具选择的准确性和参数生成的正确性。

提升工具调用准确率

工具描述应包含典型用例和边界条件。对于复杂工具链,建议先让模型规划工具使用序列,再逐步执行。

相关资源

最近更新