Python 实现大模型 Function Calling 示例

1. 功能介绍

本示例展示了如何让大模型在接收用户请求后,智能调用自定义 API,获取接口返回数据,并生成最终回复。

2. 运行前准备

2.1 安装依赖

pip install transformers openai flask

2.2 使用 OpenAI GPT-4 API

如果使用 OpenAI,你需要 API Key,可以从 OpenAI 平台 获取。


3. 完整代码

import openai
import json
import requests
from flask import Flask, request, jsonify

# 设置 OpenAI API Key
OPENAI_API_KEY = "your-openai-api-key"

openai.api_key = OPENAI_API_KEY

# Flask 服务器,模拟自定义 API
app = Flask(__name__)

@app.route("/weather", methods=["POST"])
def weather_api():
    """模拟天气 API,返回特定城市的天气"""
    data = request.json
    city = data.get("city", "未知")
    
    # 模拟 API 返回数据
    weather_data = {
        "北京": {"temperature": "22°C", "condition": "晴天"},
        "上海": {"temperature": "25°C", "condition": "多云"},
        "广州": {"temperature": "28°C", "condition": "小雨"}
    }
    
    return jsonify(weather_data.get(city, {"temperature": "未知", "condition": "未知"}))

# **调用大模型进行 Function Calling**
def call_openai_with_function_call(user_query):
    """让大模型智能调用 API 并返回最终回复"""
    
    # **1. 定义自定义函数,提供给大模型**
    functions = [
        {
            "name": "get_weather",
            "description": "获取指定城市的天气信息",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "查询天气的城市"
                    }
                },
                "required": ["city"]
            }
        }
    ]
    
    # **2. 让 GPT-4 调用函数**
    response = openai.ChatCompletion.create(
        model="gpt-4-turbo",
        messages=[{"role": "user", "content": user_query}],
        functions=functions,
        function_call="auto"  # 允许自动调用函数
    )
    
    # **3. 检查模型是否决定调用某个函数**
    response_message = response["choices"][0]["message"]
    
    if "function_call" in response_message:
        function_call = response_message["function_call"]
        
        # **4. 解析调用的函数**
        if function_call["name"] == "get_weather":
            arguments = json.loads(function_call["arguments"])
            city = arguments["city"]
            
            # **5. 发送请求到 API**
            api_response = requests.post("http://127.0.0.1:5000/weather", json={"city": city})
            weather_info = api_response.json()
            
            # **6. 让大模型整理最终回复**
            final_response = openai.ChatCompletion.create(
                model="gpt-4-turbo",
                messages=[
                    {"role": "user", "content": user_query},
                    {"role": "assistant", "content": f"调用 get_weather 获取 {city} 的天气"},
                    {"role": "function", "name": "get_weather", "content": json.dumps(weather_info)}
                ]
            )
            return final_response["choices"][0]["message"]["content"]
    
    # **7. 如果不需要调用 API,直接返回 GPT 生成的结果**
    return response_message["content"]

# **运行 Flask API**
if __name__ == "__main__":
    print("启动 Flask 服务器,监听天气 API...")
    app.run(port=5000)

    # **示例:用户查询天气**
    user_query = "北京的天气如何?"
    result = call_openai_with_function_call(user_query)
    print("最终回复:", result)

4. 代码解析

4.1 自定义 API

  • Flask 用于模拟一个天气查询 API,接收城市名称并返回天气数据。
  • 运行 Flask 服务器,让 GPT 能够调用这个 API。

4.2 Function Calling

  • 通过 functions 参数定义自定义 API 结构。
  • 当用户询问天气时,大模型会自动识别需要调用 get_weather,提取参数 city 并调用 API。
  • API 返回数据后,大模型再整理最终回复并返回给用户。

5. 运行示例

5.1 启动 Flask 服务器

python your_script.py

5.2 运行示例

user_query = "广州的天气如何?"
result = call_openai_with_function_call(user_query)
print(result)

示例输出:

最终回复: 广州的天气是 28°C,小雨。

6. 总结

特点:

  • 让 GPT 具备 API 调用能力
  • 智能解析用户请求,自动调用 API
  • 整理 API 返回数据,并给出完整的自然语言回复

适用于 智能客服、自动化数据查询、插件式 AI 扩展 等场景。🚀

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐