Function Calling实战:让AI调用外部API
AI · python · 技术

Function Calling实战:让AI调用外部API

Function Calling实战

Function Calling让AI不仅能聊天,还能调用外部API执行真实操作。

什么是Function Calling

你告诉AI有哪些函数可用,AI根据用户意图决定调用哪个函数、传什么参数。

用户:"北京明天天气怎么样?"
  ↓
AI判断:需要调用天气API
  ↓
AI返回:{"function": "get_weather", "args": {"city": "北京"}}
  ↓
你的代码执行函数,把结果返回给AI
  ↓
AI:"北京明天晴,最高温28度"

代码实现

import json
from openai import OpenAI

client = OpenAI(api_key="your-key", base_url="https://api.deepseek.com/v1")

# 定义可用函数
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名"}
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_articles",
            "description": "搜索博客文章",
            "parameters": {
                "type": "object",
                "properties": {
                    "keyword": {"type": "string", "description": "搜索关键词"},
                    "limit": {"type": "integer", "description": "返回数量", "default": 5}
                },
                "required": ["keyword"]
            }
        }
    }
]

# 函数实现
def get_weather(city):
    # 实际调用天气API
    return {"city": city, "temp": 25, "weather": "晴"}

def search_articles(keyword, limit=5):
    # 实际搜索文章
    return [{"title": f"关于{keyword}的文章{i+1}"} for i in range(limit)]

# 对话循环
messages = [{"role": "system", "content": "你是博客助手,可以查天气和搜文章"}]

user_input = "北京天气怎么样?顺便搜一下Python的文章"
messages.append({"role": "user", "content": user_input})

# 第一次调用:AI决定调哪个函数
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=messages,
    tools=tools
)

tool_calls = response.choices[0].message.tool_calls
if tool_calls:
    # 执行AI要求的函数
    messages.append(response.choices[0].message)
    for call in tool_calls:
        func_name = call.function.name
        args = json.loads(call.function.arguments)
        
        if func_name == "get_weather":
            result = get_weather(args["city"])
        elif func_name == "search_articles":
            result = search_articles(args["keyword"], args.get("limit", 5))
        
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result, ensure_ascii=False)
        })
    
    # 第二次调用:AI根据函数结果生成最终回答
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=messages,
        tools=tools
    )
    
print(response.choices[0].message.content)

实际应用场景

场景 函数 效果
客服 查订单、退款、物流 自动处理用户请求
数据分析 查数据库、生成SQL 自然语言查数据
运维 重启服务、查日志 自然语言运维
编程 执行代码、运行测试 AI编程助手
日程 创建日程、设提醒 AI秘书

最佳实践

  1. 函数描述要清晰:AI靠description判断该不该调
  2. 参数要有约束:type和required必须准确
  3. 错误处理要完善:函数执行失败要返回错误信息
  4. 权限要控制:危险操作需要人工确认
  5. 结果要简洁:函数返回值不要太长,影响后续推理