在大模型时代,我们不再满足于让 LLM(大型语言模型)仅仅“回答问题”。如何让模型与真实世界交互?Tools(工具调用) 机制正是解决这一痛点的关键技术。今天,我将带你通过一个完整的实战案例,手把手教你使用 OpenAI SDKtools 功能,实现 LLM 对外部 API 的智能调用。


为什么需要 Tools?

传统的 LLM 模型虽然能生成文本,但无法获取实时数据、执行计算或调用外部服务。例如:

  • 用户问:“北京天气怎么样?”
  • 模型只能凭记忆猜测,无法提供准确的实时天气。

而通过 Tools,我们可以告诉模型:“你有权限调用天气查询接口”,它就能自动触发 API 获取最新数据,并给出精准回答!


准备工作:安装依赖

pip install openai requests

第一步:定义工具(Tool)

我们需要向模型描述可用的工具,格式遵循 OpenAI 的 JSON Schema 规范:

from openai import OpenAI

client = OpenAI(
    api_key='sk-a8fe665142db46038952f3e2722c2a91',
    base_url='https://api.deepseek.com/v1'
)

# 定义工具
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取指定城市的当前天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称,如'北京'"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

这里我们定义了一个名为 get_weather 的函数,告诉模型它可以用来查天气,且必须传入 location 参数。


第二步:实现外部工具函数

接下来,我们编写实际调用第三方天气 API 的 Python 函数:

import requests
import json

def get_weather(location: str) -> str:
    url = "https://api.seniverse.com/v3/weather/now.json"
    params = {
        "key": "",//使用自己的密钥
        "location": location,
        "language": "zh-Hans"
    }
    try:
        resp = requests.get(url, params=params, timeout=10)
        data = resp.json()
        if "results" in data:
            city = data["results"][0]["location"]["name"]
            now = data["results"][0]["now"]
            text = now["text"]
            temp = now["temperature"]
            return f"{city}当前天气:{text},气温{temp}度"
        else:
            return "查询失败"
    except Exception as e:
        return f"异常:{e}"

# 测试一下
print(get_weather("抚州"))

第三步:调用 LLM 并触发 Tool

现在是重头戏!我们将用户提问发送给模型,让它决定是否调用工具:

import json

messages = [{"role": "user", "content": "北京天气怎么样"}]

response = client.chat_completions.create(
    model='deepseek-reasoner',
    messages=messages,
    tools=tools,
    tool_choice="auto",
    temperature=0.3
)

response_message = response.choices[0].message

# 打印原始响应
print(response_message)

# 如果模型建议调用工具
if response_message.tool_calls:
    for tool_call in response_message.tool_calls:
        function_name = tool_call.function.name
        function_args = json.loads(tool_call.function.arguments)

        if function_name == "get_weather":
            function_response = get_weather(function_args["location"])
        else:
            function_response = "未知工具"

        # 将工具调用结果加入对话历史
        messages.append({
            "tool_call_id": tool_call.id,
            "role": "tool",
            "name": function_name,
            "content": function_response
        })

else:
    print(response_message.content)

# 最后一次请求,获取最终答案
final_response = client.chat_completions.create(
    model='deepseek-reasoner',
    messages=messages,
    temperature=0.3
)

print(final_response.choices[0].message.content)

这段可能调用两次llm有点难以理解,可以进入这个juejin.cn/post/757504…
这个链接可能对你理解这段代码的执行有所帮助


输出示例

北京当前天气:晴,气温25度

看!模型自动识别出需要查天气,调用了 get_weather 工具,获取了实时数据并整合进最终回复中。


关键点解析

特性说明
tools告诉模型有哪些可用工具
tool_choice="auto"让模型自行判断是否调用工具
tool_calls模型返回的工具调用请求列表
多轮对话先请求工具 → 执行 → 返回结果 → 再次推理

应用场景拓展

除了天气查询,你可以扩展更多工具:

  • 调用数据库查询用户信息
  • 发送邮件通知
  • 调用计算器进行数学运算
  • 集成知识库检索系统

只需按照相同的模式定义 tools 即可!


总结

通过 OpenAI SDK 的 tools 功能,我们实现了 LLM 与外部世界的无缝连接。这不仅是技术上的突破,更是 AI 从“静态回答”迈向“动态决策”的关键一步。

未来,每个应用都可以是一个智能体,自主思考、主动行动。


动手试试吧! 把你的想法封装成工具,让 AI 成为你最强大的助手。

如果你喜欢这篇文章,欢迎点赞、收藏、转发支持!也欢迎留言交流你的工具集成实践

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]