ChatGPT Function Calling实战 电脑版发表于:2025/7/18 14:59  >#ChatGPT Function Calling实战 [TOC] JSON Mode 无法实现复杂的业务逻辑 ------------  Function Calling ------------  tn2>作用: ? ChatGPT 选择合适函数来完成任务 ? 从语义解析函数所需的参数 ? 实现大模型和程序的连接<br/> 入参: ? Tools 列表(函数)、功能描述、函数入参<br/> 使用场景: ? 任何需要通过和外部系统交互的功能 ? ChatOps ### 代码实践 tn2>这里我们使用 OpenAI 的函数调用功能,让 GPT 扮演 Loki 日志分析助手,当用户询问日志问题时,GPT 会自动构造 Loki 查询语句,并请求调用 analyze_loki_log 函数。 ```python from openai import OpenAI client = OpenAI( api_key="你的key", ) query = "查看 app=grafana 且关键字包含 Error 的日志" messages = [ { "role": "system", "content": "你是一个 Loki 日志分析助手,你可以帮助用户分析 Loki 日志,你可以调用多个函数来帮助用户完成任务,并最终尝试分析错误产生的原因", }, { "role": "user", "content": query, }, ] tools = [ { # 工具类型:这里是一个“函数调用” "type": "function", # 具体函数的定义 "function": { # 函数名称(模型调用时会用到这个名字) "name": "analyze_loki_log", # 函数描述(帮助模型理解函数用途,决定何时调用) "description": "从 Loki 获取日志", # 定义函数参数的格式(使用 JSON Schema 规范) "parameters": { # 参数整体类型是一个对象 "type": "object", # 对象中的属性(即参数列表) "properties": { # 定义第一个参数 query_str "query_str": { # 参数类型:字符串 "type": "string", # 参数描述:告诉模型这个参数是 Loki 查询字符串,并给出示例 "description": 'Loki 查询字符串,例如:{app="grafana"} |= "Error"', }, }, # required 表示必填参数列表,这里 query_str 必须传 "required": ["query_str"], }, }, } ] response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, tool_choice="auto", ) response_message = response.choices[0].message tool_calls = response_message.tool_calls print("\nChatGPT want to call function: ", tool_calls) ``` tn2>运行测试一下:  tn2>我们发现它输出了对应需要调用的函数。 接着我们对其进行解析并创建对于的函数让它进行调用试试看。 ```python from openai import OpenAI import json import time client = OpenAI( api_key="你的key" ) def analyze_loki_log(query_str): print("\n函数调用的参数: ", query_str) return json.dumps({"log": "this is error log"}) def run_conversation(): """Query: 查看 app=grafana 且关键字包含 Error 的日志""" # 步骤一:把所有预定义的 function 传给 chatgpt query = input("输入查询指令:") messages = [ { "role": "system", "content": "你是一个 Loki 日志分析助手,你可以帮助用户分析 Loki 日志,你可以调用多个函数来帮助用户完成任务,并最终尝试分析错误产生的原因", }, { "role": "user", "content": query, }, ] tools = [ { "type": "function", "function": { "name": "analyze_loki_log", "description": "从 Loki 获取日志", "parameters": { "type": "object", "properties": { "query_str": { "type": "string", "description": 'Loki 查询字符串,例如:{app="grafana"} |= "Error"', }, }, }, "required": ["query_str"], }, } ] response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, tool_choice="auto", ) response_message = response.choices[0].message tool_calls = response_message.tool_calls print("\nChatGPT want to call function: ", tool_calls) # 步骤二:检查 LLM 是否调用了 function if tool_calls is None: print("not tool_calls") if tool_calls: available_functions = { "analyze_loki_log": analyze_loki_log, } messages.append(response_message) # 步骤三:把每次 function 调用和返回的信息传给 model for tool_call in tool_calls: function_name = tool_call.function.name function_to_call = available_functions[function_name] function_args = json.loads(tool_call.function.arguments) function_response = function_to_call(**function_args) messages.append( { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": function_response, } ) # 步骤四:把 function calling 的结果传给 model,进行对话 response = client.chat.completions.create( model="gpt-4o", messages=messages, ) return response.choices[0].message.content print("LLM Res: ", run_conversation()) ```  tn>小结:Function Calling 就是让大模型不仅能回答问题,还能“调用你写好的函数”帮你干活,比如: 模型说“我需要天气”,你就帮它调用 get_weather(city="北京"),再把结果给它,它再继续回答你。 简单理解:AI 负责想干什么,你的代码负责干这件事。