使用Python调用OpenAI的function calling源码

一、第三方库

pip install openai

二、示例代码

# -*- coding: utf-8 -*-  
# @Author :Kan 
# @Date :2025/8/1 9:12  
# @File :1_function_calling.py  
import json  
import random  
from openai import OpenAI  
from datetime import datetime  
  
  
# ================================================================  
# 1. Function Calling(函数调用)  
# ================================================================  
  
class ToolsUsage:  
    tools = [  
        # 工具2 获取指定城市的天气  
        {  
            "type": "function",  
            "function": {  
                "name": "get_current_weather",  
                "description": "获取指定地点的天气信息",  
                "parameters": {  
                    "type": "object",  
                    "properties": {  
                        "location": {"type": "string", "description": "地点名称"}  
                    },  
                    "required": ["location"]  
                }  
            }  
        },  
        # 工具1 获取当前时刻的时间  
        {  
            "type": "function",  
            "function": {  
                "name": "get_current_time",  
                "description": "当你想知道现在的时间时非常有用。",  
                # 因为获取当前时间无需输入参数,因此parameters为空字典  
                "parameters": {},  
            },  
        },  
    ]  
  
    @staticmethod  
    # 天气查询工具。返回结果示例:“北京今天是雨天。”  
    def get_current_weather(location):  
        weather_conditions = ["晴天", "多云", "雨天"]  
        # 随机选择一个天气条件  
        random_weather = random.choice(weather_conditions)  
        # 返回格式化信息  
        return f"{location}今天是{random_weather}。"  
  
    @staticmethod  
    # 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“  
    def get_current_time():  
        current_datetime = datetime.now()  
        # 格式化日期  
        formatted_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")  
        return f"当前时间:{formatted_time}。"  
  
    @staticmethod  
    def execute_tools(func_name, func_args):  
        func_dic = {  
            "get_current_weather": ToolsUsage.get_current_weather,  
            "get_current_time": ToolsUsage.get_current_time,  
        }  
        return func_dic[func_name](**func_args)  
  
  
class ChatAgent:  
    def __init__(self, api_key: str, url: str, model_name: str):  
        self.client = OpenAI(api_key=api_key, base_url=url)  
        self.model_name = model_name  
  
    def request_chat(self, messages: list):  
        response = self.client.chat.completions.create(  
            model=self.model_name,  
            messages=messages,  
            tools=ToolsUsage.tools,  
            extra_body={"enable_thinking": False},  
            tool_choice="auto",  
        )  
        return response  
  
    def execute_chat(self):  
        print("\n")  
        messages = [  
            {  
                # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"  
                "content": input(  
                    "请输入问题:"  
                ),  
                "role": "user",  
            }  
        ]  
        print("-*" * 60)  
        # 模型调用次数  
        i = 1  
        first_response = self.request_chat(messages)  
        assistant_output = first_response.choices[0].message  
        print(f"\n第{i}轮大模型输出信息:{assistant_output}\n")  
        # 不需要调用工具,则直接返回答案  
        if not assistant_output.tool_calls:  
            print(f"无需调用工具,直接回复:{assistant_output.content}")  
            return  
        tool_calls_result = assistant_output.tool_calls  
        # 如果需要调用工具,则进行模型的多轮调用,直到模型判断无需调用工具  
        while tool_calls_result:  
            # 执行工具调用  
            for tool_call in assistant_output.tool_calls:  
                tool_info = {  
                    "content": "",  
                    "role": "tool",  
                    "tool_call_id": assistant_output.tool_calls[0].id,  
                }  
                func_name = tool_call.function.name  
                func_args = json.loads(tool_call.function.arguments)  
                tools_result = ToolsUsage.execute_tools(func_name, func_args)  
                print(f"当前调用工具:{func_name},参数:{func_args},输出信息:{tools_result}\n")  
                tool_info["content"] = tools_result  
                messages.append(tool_info)  
                print("-*" * 60)  
            second_response = self.request_chat(messages)  
            assistant_output = second_response.choices[0].message  
            i += 1  
            print(f"第{i}轮大模型输出信息:{assistant_output}\n")  
            # 指导调用工具为空时终止  
            if not assistant_output.tool_calls:  
                tool_calls_result = None  
        print(f"最终答案:\n {assistant_output.content}")  
  
  
if __name__ == "__main__":  
    api_key = 'xxxxxx'  
    base_url = "http://xxxxxxxx/v1"  
    model = "qwen3"  
    chat_service = ChatAgent(api_key, base_url, model)  
    chat_service.execute_chat()
### 如何在 DeepSeek 中使用函数调用 在 DeepSeek 平台中,为了实现函数调用并确保注册连接能够被正确识别和传递给大型语言模型(LLM),最佳实践涉及几个重要方面[^1]。 #### 函数调用中的连接管理 当通过 PromptFlow 使用函数调用来消费已注册的连接时,推荐的方法是在定义函数接口时明确指定所需的连接参数。这可以通过配置文件或环境变量来完成,从而允许外部注入这些敏感信息而不必硬编码到源码中。对于 LLM 节点来说,这意味着要设置好相应的输入字段以便接收来自上游节点的数据流。 ```json { "connections": { "database_url": "${env.DATABASE_URL}", "api_key": "${secret.API_KEY}" } } ``` #### 注册与传递连接 为了让 LLM 正确处理传入的连接对象,在设计 API 或者框架集成时应考虑采用依赖注入模式。这样做的好处是可以灵活替换不同的数据源而无需修改业务逻辑层代码。具体操作上可以创建一个服务类负责管理和分发各种类型的连接实例给需要它们的工作单元。 ```python class ConnectionService: def __init__(self, config): self.config = config def get_database_connection(self): return DatabaseConnection(self.config['database_url']) def llm_function(connection_service: ConnectionService): db_conn = connection_service.get_database_connection() # 进行业务逻辑处理... ``` #### 数据库交互的最佳实践 结合前文提到的内容进一步探讨如何利用 Function Calling 将大模型与数据库打通。这里的关键在于构建有效的查询语句以及安全高效地执行读写操作。考虑到性能因素,建议尽可能减少不必要的网络往返次数;同时也要注意防止 SQL 注入攻击等潜在风险[^2]。 ```sql SELECT * FROM users WHERE id IN (:ids); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值