Python 实现大模型 Function Calling 示例

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 扩展 等场景。🚀

<think>好的,用户现在想了解如何通过函数调用的方式与大型语言模型进行交互,也就是Function Calling的方法和示例。首先,我需要回忆一下相关的知识,确保信息准确。Function Calling允许大模型执行外部函数,比如获取实时数据或与数据库交互,这扩展了模型的能力。 首先,应该解释Function Calling的基本概念,可能引用已有的参考资料,比如用户提供的引用[1]和[2]。然后,分步骤说明如何实现,比如定义函数、构建提示、解析响应和执行函数。用户可能需要具体的示例,所以需要准备一个代码示例,比如获取天气的函数。要注意代码的正确性,使用Python,并且语法正确。 另外,用户的问题可能还涉及到应用场景和注意事项,比如错误处理、权限控制等。需要确保回答结构清晰,分点说明,每个步骤都有例子或说明。同时,生成的相关问题要围绕Function Calling的扩展,比如优化方法、安全措施等。 检查是否遵循了系统级指令,比如数学公式的格式是否正确,使用中文回答,引用标识是否正确添加。最后,确保回答真实可靠,没有编造的信息,引用来源正确。</think>### 通过函数调用与大模型交互的方法 #### 1. **核心原理** 函数调用(Function Calling)通过将外部工具能力与大模型结合,扩展其功能边界。大模型根据用户输入**自动判断何时调用函数**,并将自然语言参数转换为结构化请求,例如: - 用户输入:“北京今天气温多少?” - 模型响应:触发`get_weather(location: str)`函数调用,参数为`{"location": "北京"}`[^2] #### 2. **实现步骤** ##### 步骤1:定义函数清单 ```python functions = [ { "name": "get_stock_price", "description": "获取指定股票实时价格", "parameters": { "type": "object", "properties": { "symbol": {"type": "string", "description": "股票代码,如 AAPL"} }, "required": ["symbol"] } } ] ``` ##### 步骤2:构建提示词 系统提示需包含函数描述: ``` 你是一个财经助手,可以调用以下功能: - get_stock_price:输入股票代码,返回实时价格 ``` ##### 步骤3:解析模型响应 当模型返回函数调用请求时,提取结构化参数: ```json { "function_call": { "name": "get_stock_price", "arguments": "{\"symbol\": \"AAPL\"}" } } ``` ##### 步骤4:执行函数并反馈 ```python def execute_function(function_name, arguments): if function_name == "get_stock_price": return fetch_api(f"https://api.stocks.com/{arguments['symbol']}") ``` #### 3. **完整交互示例** ```python import openai response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "苹果公司当前股价是多少?"}], functions=functions, function_call="auto" ) if response.choices[0].message.get("function_call"): func_args = json.loads(response.choices[0].message.function_call.arguments) result = execute_function(response.function_call.name, func_args) # 将结果返回给模型生成最终回复 ``` #### 4. **关键应用场景** - **实时数据查询**:股票/天气/交通信息 - **业务系统集成**:CRM系统客户数据查询 - **复杂计算委托**:将微积分计算交给SymPy等数学库 - **多模态扩展**:调用图像生成API实现文生图 #### 5. **注意事项** - **错误处理**:需捕获API调用超时/参数错误 - **权限控制**:敏感函数需进行身份验证 - **成本优化**:通过函数描述压缩减少token消耗 - **参数校验**:对模型输出的参数进行类型检查 $$ \text{交互流程} = \text{用户输入} \rightarrow \text{模型解析} \rightarrow \text{函数调用} \rightarrow \text{结果反馈} \rightarrow \text{最终输出} $$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值