Function Calling 入门
Function Calling 入门 | 大模型开发核心技术系列 2.1一、引言在传统的AI应用中模型只能根据训练数据生成文本无法与外部世界交互。但现实是大量的实时信息如天气、股票价格、数据库记录并不存在于模型的训练数据中。Function Calling函数调用技术的出现完美解决了这一问题——它让大型语言模型能够调用外部工具获取实时信息完成各种复杂任务。本文将深入解析 Function Calling 的原理、实现方法和实战技巧。二、Function Calling 概述2.1 什么是 Function CallingFunction Calling 是大型语言模型的一种能力它允许模型在生成回复时主动调用预定义的函数或 API并基于函数返回的结果继续生成回答。简单来说就是让 AI “打电话”给外部系统获取需要的信息。# 传统 AI 对话# 模型只能基于训练数据回答user:今天天气怎么样AI:作为一个 AI我没有实时天气信息。# 使用 Function Calling# 模型可以调用天气 API 获取实时信息user:今天天气怎么样AI:[调用函数 get_weather(location北京)]↓ 返回:{temperature:25,condition:晴}↓ AI:今天北京天气晴朗气温25度非常适合外出。2.2 Function Calling 的价值Function Calling 的核心价值在于打破了 AI 的“信息孤岛”状态。它让 AI 能够连接真实世界获取实时数据执行具体操作。从技术角度看Function Calling 实现了以下突破实时信息获取天气、新闻、股票、数据持久化保存到数据库、业务逻辑执行订单处理、支付、跨系统集成连接多个服务。2.3 发展历程Function Calling 技术经历了几个重要发展阶段。最早期开发者需要用复杂的提示词技巧来“诱导”模型生成函数调用但这种方式极不稳定。随着 OpenAI 在 GPT-4 API 中正式引入 Function Calling 能力这一技术才真正走向成熟。如今Anthropic、Google 等各大厂商都提供了各自的函数调用方案。三、OpenAI Function Calling 详解3.1 基本原理OpenAI 的 Function Calling 基于工具描述Tool Description机制。开发者预先定义好函数的名称、参数和返回格式模型根据用户输入判断是否需要调用函数并生成符合格式的调用请求。# OpenAI Function Calling 完整示例importopenaiimportjson# 1. 定义可用函数functions[{name:get_weather,description:获取指定城市的天气信息,parameters:{type:object,properties:{location:{type:string,description:城市名称如北京、上海},unit:{type:string,enum:[celsius,fahrenheit],description:温度单位}},required:[location]}}]# 2. 发起对话responseopenai.ChatCompletion.create(modelgpt-4,messages[{role:user,content:北京今天天气怎么样}],functionsfunctions)# 3. 检查是否需要调用函数messageresponse.choices[0].messageifmessage.function_call:# 4. 解析函数调用function_namemessage.function_call.name argumentsjson.loads(message.function_call.arguments)# location北京print(f需要调用函数:{function_name})print(f参数:{arguments})3.2 函数定义规范在 OpenAI API 中函数通过 JSON Schema 格式定义。一个完整的函数定义包含以下关键字段# 完整的函数定义示例function_definition{name:calculate_shipping,description:根据收货地址和商品重量计算运费,parameters:{type:object,properties:{destination:{type:string,description:收货地址},weight:{type:number,description:商品重量千克},shipping_method:{type:string,enum:[standard,express,overnight],description:快递方式}},required:[destination,weight]}}3.3 调用流程完整的 Function Calling 流程包含以下步骤# 完整调用流程defchat_with_functions(user_message,functions):# 第一轮模型判断是否需要调用函数response1openai.ChatCompletion.create(modelgpt-4,messages[{role:user,content:user_message}],functionsfunctions)messageresponse1.choices[0].message# 判断是否需要调用函数ifmessage.function_call:# 解析函数调用function_namemessage.function_call.name argsjson.loads(message.function_call.arguments)# 执行函数这里需要开发者实现resultexecute_function(function_name,args)# 第二轮将函数结果返回给模型messages[{role:user,content:user_message},{role:function,name:function_name,content:json.dumps(result)}]# 获取最终回复response2openai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)returnresponse2.choices[0].message.contentelse:# 无需调用函数直接返回returnmessage.content3.4 并行调用当模型需要同时调用多个函数时API 支持并行处理# 并行函数调用responseopenai.ChatCompletion.create(modelgpt-4,messages[{role:user,content:查一下北京今天的天气和上海今天的天气}],functions[func_weather])# message.function_call 可能包含多个函数调用forcallinmessage.function_call:# 逐个执行调用pass四、Function Calling vs 其他方案4.1 提示词诱导 vs 原生支持在 Function Calling 出现之前开发者需要通过精心设计的提示词来“诱导”模型生成函数调用代码# ❌ 旧方式提示词诱导prompt 你是一个 AI 助手。当需要查询天气时请按以下格式输出 [调用天气API]城市北京[/调用] 用户问题今天天气怎么样 # 这种方式非常不稳定模型可能输出格式错误# ✅ 新方式原生 Function Callingfunctions[{name:get_weather,parameters:{...}}]# 模型会严格按照规范生成函数调用4.2 Function Calling vs LangChainLangChain 提供了更抽象的 Agent 框架但底层也是基于 Function Calling# LangChain 方式fromlangchain.agentsimportload_tools,initialize_agent toolsload_tools([serpapi,llm-math],llmllm)agentinitialize_agent(tools,llm,agentzero-shot-react-description)# LangChain 底层会生成 function_call 请求特性原生 Function CallingLangChain控制粒度精细抽象学习成本中等较高灵活性高中等适用场景简单直接复杂工作流五、实战案例5.1 天气查询助手# 天气查询助手完整示例importopenaiimportjson functions[{name:get_weather,description:获取指定城市的天气信息,parameters:{type:object,properties:{city:{type:string,description:城市名称}},required:[city]}}]defget_weather(city):模拟天气 APIweather_db{北京:{temp:25,condition:晴},上海:{temp:28,condition:多云},广州:{temp:32,condition:雷阵雨}}returnweather_db.get(city,{temp:0,condition:未知})defchat_weather(query):messages[{role:user,content:query}]# 第一次调用responseopenai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)msgresponse.choices[0].message# 需要调用函数ifmsg.function_call:func_namemsg.function_call.name argsjson.loads(msg.function_call.arguments)# 执行函数resultget_weather(args[city])# 将结果返回给模型messages.append({role:function,name:func_name,content:json.dumps(result)})# 第二次调用获取最终回复final_responseopenai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)returnfinal_response.choices[0].message.contentreturnmsg.content# 测试print(chat_weather(北京今天天气怎么样))# 输出北京今天天气晴朗气温25度非常适合外出。5.2 订单处理系统# 订单处理函数定义order_functions[{name:check_inventory,description:检查商品库存,parameters:{type:object,properties:{product_id:{type:string}},required:[product_id]}},{name:create_order,description:创建订单,parameters:{type:object,properties:{product_id:{type:string},quantity:{type:integer},address:{type:string}},required:[product_id,quantity]}}]# 用户请求我想要购买 iPhone 15 Pro送到北京市朝阳区# 模型会自动判断先检查库存 - 库存充足 - 创建订单5.3 知识库问答# 结合 RAG 的 Function Callingfunctions[{name:search_knowledge_base,description:搜索知识库获取相关信息,parameters:{type:object,properties:{query:{type:string,description:搜索关键词}},required:[query]}}]# 当用户问题需要专业知识时模型会自动调用搜索函数六、最佳实践6.1 函数描述技巧函数描述是模型能否正确调用的关键# ✅ 好的描述{name:get_flight_info,description:查询航班信息包括起飞时间、到达时间、延误情况等,parameters:{type:object,properties:{departure:出发城市,destination:目的城市,date:出发日期格式YYYY-MM-DD},required:[departure,destination]}}# ❌ 差的描述{name:get_info,description:获取信息,# 描述不清晰模型难以理解}6.2 错误处理生产环境中必须做好错误处理defsafe_function_call(messages,functions):try:responseopenai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)msgresponse.choices[0].messageifmsg.function_call:func_namemsg.function_call.nametry:argsjson.loads(msg.function_call.arguments)resultexecute_function(func_name,args)exceptExceptionase:result{error:str(e)}# 返回错误信息messages.append({role:function,name:func_name,content:json.dumps(result)})# 第二次调用returnopenai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)returnmsgexceptExceptionase:returnf发生错误:{str(e)}6.3 调试技巧调试 Function Calling 时建议开启详细日志defdebug_function_call(messages,functions):# 打印完整请求print( Request )print(fMessages:{messages})print(fFunctions:{functions})responseopenai.ChatCompletion.create(modelgpt-4,messagesmessages,functionsfunctions)# 打印完整响应print( Response )print(fFunction Call:{response.choices[0].message.function_call})returnresponse七、常见问题7.1 模型不调用函数如果模型应该调用函数却没有调用可以尝试以下方法增加函数描述的详细程度、提供更多上下文信息、检查函数参数是否过于复杂。# 如果模型不调用尝试添加 examplesfunctions[{name:get_weather,description:获取天气如用户问北京天气、今天热吗时调用,# 添加使用示例}]7.2 参数解析错误当模型生成的参数格式不正确时可以简化参数定义、使用更明确的类型约束、添加参数示例。7.3 循环调用当函数返回结果后模型继续调用函数时需要设置终止条件# 最多调用 3 次max_calls3foriinrange(max_calls):# ... 调用逻辑ifnotresponse.choices[0].message.function_call:break# 没有新的函数调用退出循环八、总结Function Calling 是大型语言模型连接外部世界的桥梁它让 AI 不再局限于静态知识而是能够获取实时信息、执行具体操作。通过本文的学习你应该已经掌握了 Function Calling 的基本原理、OpenAI API 的使用方法以及实战技巧。在实际开发中良好的函数设计、完善的错误处理和适当的调试技巧是构建稳定 AI 应用的关键。随着技术的演进Function Calling 将变得更加强大和易用为 AI 应用开辟更广阔的空间。参考资料OpenAI Function Calling 官方文档Anthropic Tool Use 文档LangChain Agents 文档
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2445064.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!