深圳有名的网站设计公司嘉峪关建设厅官方网站
2026/4/15 22:00:14 网站建设 项目流程
深圳有名的网站设计公司,嘉峪关建设厅官方网站,wordpress 修改 缩进按钮,网站服务器租用恒创大语言模型拥有令人惊叹的语言理解和生成能力#xff0c;却也存在自主决策、与外部系统交互等方面的不足。函数调用#xff08;Function Calling#xff09;技术的出现#xff0c;正是为解决这一难题而生的创新方案#xff0c;它赋予了大语言模型更强的自主能力和与外部世…大语言模型拥有令人惊叹的语言理解和生成能力却也存在自主决策、与外部系统交互等方面的不足。函数调用Function Calling技术的出现正是为解决这一难题而生的创新方案它赋予了大语言模型更强的自主能力和与外部世界连接的能力成为实现真正智能自主 Agent 的关键一环。本期我们精心为各位读者伙伴呈现一篇详实的搭建技术教程全面介绍了如何利用函数调用技术构建 Autonomous AI Agents 。作者从函数调用Function Calling的工作原理和应用场景出发通过构建一个旅游服务助手的实例层层递进地讲解了整个系统的设计思路、技术细节和代码实现。函数调用并非一个新鲜概念。早在 2023 年 7 月 OpenAI 就为其 GPT 模型引入了这一功能现在这一功能也被其他竞争对手采用。比如谷歌的 Gemini API 最近也开始支持函数调用 Anthropic 也在将其整合到 Claude 中。函数调用译者注Function Calling允许模型通过调用特定的函数来执行某些复杂任务。已经成为大语言模型LLMs的关键功能之一能够显著增强大模型应用能力。因此学习这项技术是极其有意义的。基于此我打算撰写一篇详细的教程内容重点为基础介绍因为这类教程已经很多了之外的内容。本教程将专注于实际应用上展示如何构建一个 fully autonomous AI agent译者注能够独立运行和做出决策的、不需要人为干预的 AI agent 。并将其与 Streamlit 集成来实现类似 ChatGPT 的 Web 交互界面。虽然本教程使用 OpenAI 进行演示但本文内容同样适用于其他支持函数调用的大语言模型例如 Gemini。01 函数调用Function Calling的用途有哪些Function Calling 这一技术让开发者能够定义函数也被称为工具tools可以将其视为模型要执行的操作如进行数学运算或下订单并让模型智能地选择并输出一个包含调用这些函数所需参数的 JSON 对象。简单来说这一技术具备以下功能自主决策Autonomous decision making模型能够智能地选择所需工具来回答问题。可靠地解析过程Reliable parsing响应一般以 JSON 格式呈现而非更典型的对话式响应dialogue-like response。乍看之下似乎没什么但正是这种技术使得 LLM 能够通过结构化输入 structured inputs连接到外部系统比如通过 API 进行交互。这种技术为人们带来了各种各样的新机遇、新机会Autonomous AI assistants机器人不仅可以回答用户咨询的问题还能与内部系统译者注企业内部用于处理内部业务流程、数据管理、客户关系等任务的系统交互处理客户下订单和退货等任务。Personal research assistants比方说当我们需要制定旅行计划时可以请这些助理在互联网搜索内容、爬取内容、比较内容并将结果汇总到 Excel 中。IoT voice commands模型可以根据检测到的用户意图来控制设备或给出操作建议例如调节空调温度。02 函数调用功能的运行流程参考 Gemini 的函数调用文档[1]函数调用功能的运行流程如下OpenAI 中此功能的工作原理基本相同图片来源Gemini 的函数调用文档[1]1. 用户向应用程序发出提示词prompt2. 应用程序会传递用户提供的提示词和函数声明Function Declaration(s)即对模型所需工具的描述信息3. 根据函数声明模型会给出工具选取建议和相关的请求参数。注意模型仅会输出建议的工具和请求参数并不会实际调用函数4. 5. 应用程序根据模型响应调用相关 API6. 7. 将 API 的响应内容再次输入模型生成人类可读的内容8. 应用程序将最终响应返回给用户然后再次回到第 1 步如此循环往复上述的介绍内容可能看起来有些许复杂接下来将通过实例详细解释该概念。03 该 Agents 的整体设计和总体架构在深入讲解具体代码之前先简要介绍一下本文介绍的这个 Agents 的整体设计和总体架构。3.1 Solution旅游服务助手在本文我们将为外出旅游的酒店顾客构建一个旅游服务助手该产品可以使用以下工具这些工具使得该服务助手能够访问外部应用程序。get_items 和 purchase_item通过 API 连接到数据库中的产品目录product catalog这两个工具分别用于获取商品列表和进行商品购买rag_pipeline_func通过检索增强生成RAG连接到存储和管理文档数据的存储系统以便从非结构化文本中获取相关信息例如酒店的宣传册3.2 相关技术栈嵌入模型Embedding modelall-MiniLM-L6-v2[2]向量数据库Vector DatabaseHaystack 的 InMemoryDocumentStore[3]大语言模型LLM通过 OpenRouter 访问 GPT-4 Turbo[4]。只要支持函数调用稍作代码修改即可使用其他大语言模型如 Gemini。LLM 框架使用 Haystack[5]因为它易于使用文档详尽并且在 pipeline 的构建方面比较透明。本教程实际上是对该框架使用教程[6]的扩展。现在开始介绍吧04 使用上述技术栈构建一个 Agent 样例4.1 前期准备工作前往 Github[7] 克隆本项目代码。以下内容可以在 Notebookfunction_calling_demo中找到。请创建并激活一个虚拟环境然后运行 pip install -r requirements.txt 安装所需的包。4.2 项目初始化首先连接 OpenRouter。如果有 OpenAI API 密钥也可以使用原始的OpenAIChatGenerator而不重写覆盖api_base_url参数。python 复制代码 import os from dotenv import load_dotenv from haystack.components.generators.chat import OpenAIChatGenerator from haystack.utils import Secret from haystack.dataclasses import ChatMessage from haystack.components.generators.utils import print_streaming_chunk # Set your API key as environment variable before executing this load_dotenv() OPENROUTER_API_KEY os.environ.get(OPENROUTER_API_KEY) chat_generator OpenAIChatGenerator(api_keySecret.from_env_var(OPENROUTER_API_KEY), api_base_urlhttps://openrouter.ai/api/v1, modelopenai/gpt-4-turbo-preview, streaming_callbackprint_streaming_chunk)接下来我们测试 chat_generator 是否能成功调用。ini 复制代码 chat_generator.run(messages[ChatMessage.from_user(Return this text: test)])sql 复制代码 ---------- The response should look like this ---------- {replies: [ChatMessage(contenttest, roleChatRole.ASSISTANT: assistant, nameNone, meta{model: openai/gpt-4-turbo-preview, index: 0, finish_reason: stop, usage: {}})]}4.3 步骤 1选择使用合适的数据存储方案在此我们将在应用程序和两个数据源data sources之间建立连接用于非结构化文本的文档存储系统Document store以及通过 API 连接的应用程序数据库application database via API。使用 Pipeline 给文档编制索引需要给系统提供文本样本sample texts以供模型进行检索增强生成RAG。这些文本将被转换为嵌入embeddings并使用将文档数据存储在内存中的数据存储方案。python 复制代码 from haystack import Pipeline, Document from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.writers import DocumentWriter from haystack.components.embedders import SentenceTransformersDocumentEmbedder # Sample documents documents [ Document(contentCoffee shop opens at 9am and closes at 5pm.), Document(contentGym room opens at 6am and closes at 10pm.) ] # Create the document store document_store InMemoryDocumentStore() # Create a pipeline to turn the texts into embeddings and store them in the document store indexing_pipeline Pipeline() indexing_pipeline.add_component( doc_embedder, SentenceTransformersDocumentEmbedder(modelsentence-transformers/all-MiniLM-L6-v2) ) indexing_pipeline.add_component(doc_writer, DocumentWriter(document_storedocument_store)) indexing_pipeline.connect(doc_embedder.documents, doc_writer.documents) indexing_pipeline.run({doc_embedder: {documents: documents}})上述程序的输出结果应该与输入的示例文档数据保持一致python 复制代码 {doc_writer: {documents_written: 2}}启动 API 服务进程在 db_api.py 文件中创建一个用 Flask 框架构建的 API 服务用于连接 SQLite 数据库。请在终端运行 python db_api.py启动该服务。如果服务成功执行终端将显示图中所示的信息我注意到在 db_api.py 中预置一些初始的基础数据。数据库中的数据样本4.4 步骤 2定义函数Define the functions这一步是在准备真正的函数以供模型在之后的函数调用Function Calling步骤中调用执行。如 02 节 “函数调用功能的运行流程” 中所述的步骤 4-5RAG 函数RAG function其中之一就是 RAG 函数rag_pipeline_func。这个函数的作用是让模型能够搜索之前存储在文档存储中的文本内容并基于搜索结果提供答案。它首先使用 Haystack 这个框架。将 RAG 检索增强生成的检索过程定义为一个 pipeline 。python 复制代码 from haystack.components.embedders import SentenceTransformersTextEmbedder from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack.components.builders import PromptBuilder from haystack.components.generators import OpenAIGenerator template Answer the questions based on the given context. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} Answer: rag_pipe Pipeline() rag_pipe.add_component(embedder, SentenceTransformersTextEmbedder(modelsentence-transformers/all-MiniLM-L6-v2)) rag_pipe.add_component(retriever, InMemoryEmbeddingRetriever(document_storedocument_store)) rag_pipe.add_component(prompt_builder, PromptBuilder(templatetemplate)) # Note to llm: We are using OpenAIGenerator, not the OpenAIChatGenerator, because the latter only accepts List[str] as input and cannot accept prompt_builders str output rag_pipe.add_component(llm, OpenAIGenerator(api_keySecret.from_env_var(OPENROUTER_API_KEY), api_base_urlhttps://openrouter.ai/api/v1, modelopenai/gpt-4-turbo-preview)) rag_pipe.connect(embedder.embedding, retriever.query_embedding) rag_pipe.connect(retriever, prompt_builder.documents) rag_pipe.connect(prompt_builder, llm)测试函数功能是否正常工作。python 复制代码 query “When does the coffee shop open?” rag_pipe.run({embedder: {text: query}, prompt_builder: {question: query}})rag_pipeline_func 函数在被模型调用执行后应该会产生如下输出。请注意模型给出的回答来自于我们之前提供的样本文档数据。python 复制代码 {llm: {replies: [The coffee shop opens at 9am.], meta: [{model: openai/gpt-4-turbo-preview, index: 0, finish_reason: stop, usage: {completion_tokens: 9, prompt_tokens: 60, total_tokens: 69, total_cost: 0.00087}}]}}然后我们可以将 rag_pipe 转化为一个函数在需要时调用 rag_pipeline_func(query) 获取基于 query 的答案而不会返回其他的中间细节信息。python 复制代码 def rag_pipeline_func(query: str): result rag_pipe.run({embedder: {text: query}, prompt_builder: {question: query}}) return {reply: result[llm][replies][0]}定义与数据库进行交互的 API在此处我们定义与数据库进行交互的get_items函数和purchase_itemfunctions函数。python 复制代码 # Flasks default local URL, change it if necessary db_base_url http://127.0.0.1:5000 # Use requests to get the data from the database import requests import json # get_categories is supplied as part of the prompt, it is not used as a tool def get_categories(): response requests.get(f{db_base_url}/category) data response.json() return data def get_items(idsNone,categoriesNone): params { id: ids, category: categories, } response requests.get(f{db_base_url}/item, paramsparams) data response.json() return data def purchase_item(id,quantity): headers { Content-type:application/json, Accept:application/json } data { id: id, quantity: quantity, } response requests.post(f{db_base_url}/item/purchase, jsondata, headersheaders) return response.json()定义工具函数列表现在我们已经成功完成函数的定义接下来需要让模型识别并了解如何使用这些函数为此我们需要为这些函数提供一些描述说明内容。由于我们在此处使用的是 OpenAI所以需要按照 OpenAI 要求的格式[8]来描述这些 tools函数。python 复制代码 tools [ { type: function, function: { name: get_items, description: Get a list of items from the database, parameters: { type: object, properties: { ids: { type: string, description: Comma separated list of item ids to fetch, }, categories: { type: string, description: Comma separated list of item categories to fetch, }, }, required: [], }, } }, { type: function, function: { name: purchase_item, description: Purchase a particular item, parameters: { type: object, properties: { id: { type: string, description: The given product ID, product name is not accepted here. Please obtain the product ID from the database first., }, quantity: { type: integer, description: Number of items to purchase, }, }, required: [], }, } }, { type: function, function: { name: rag_pipeline_func, description: Get information from hotel brochure, parameters: { type: object, properties: { query: { type: string, description: The query to use in the search. Infer this from the users message. It should be a question or a statement, } }, required: [query], }, }, } ]4.5 步骤 3将所有系统组件整合在一起我们现在已经准备好了测试函数调用Function Calling功能所需的所有系统组件这一步骤我们需要做以下几件事为模型提供初始提示词prompt并为其提供上下文提供样例用户消息模拟真实用户的 query 或需求将之前定义的工具函数列表tool list作为tools参数传递给 chat generator 译者注生成对话式回复的语言模型或 AI 系统这是最关键的一步。python 复制代码 # 1. Initial prompt context fYou are an assistant to tourists visiting a hotel. You have access to a database of items (which includes {get_categories()}) that tourists can buy, you also have access to the hotels brochure. If the tourists question cannot be answered from the database, you can refer to the brochure. If the tourists question cannot be answered from the brochure, you can ask the tourist to ask the hotel staff. messages [ ChatMessage.from_system(context), # 2. Sample message from user ChatMessage.from_user(Can I buy a coffee?), ] # 3. Passing the tools list and invoke the chat generator response chat_generator.run(messagesmessages, generation_kwargs {tools: tools}) responsepython 复制代码 ---------- Response ---------- {replies: [ChatMessage(content[{index: 0, id: call_AkTWoiJzx5uJSgKW0WAI1yBB, function: {arguments: {categories:Food and beverages}, name: get_items}, type: function}], roleChatRole.ASSISTANT: assistant, nameNone, meta{model: openai/gpt-4-turbo-preview, index: 0, finish_reason: tool_calls, usage: {}})]}现在让我们来检查一下模型响应内容。需要注意的是函数调用Function Calling所返回的内容不仅包括模型选择调用的函数本身还应该包括为调用该函数所传入的参数。python 复制代码 function_call json.loads(response[replies][0].content)[0] function_name function_call[function][name] function_args json.loads(function_call[function][arguments]) print(Function Name:, function_name) print(Function Arguments:, function_args)python 复制代码 ---------- Response ---------- Function Name: get_items Function Arguments: {‘categories’: ‘Food and beverages’}当模型遇到另一个新问题时会分析该问题结合它已有的上下文信息评估哪一个可用的工具函数最能够帮助回答这个问题。python 复制代码 # Another question messages.append(ChatMessage.from_user(Wheres the coffee shop?)) # Invoke the chat generator, and passing the tools list response chat_generator.run(messagesmessages, generation_kwargs {tools: tools}) function_call json.loads(response[replies][0].content)[0] function_name function_call[function][name] function_args json.loads(function_call[function][arguments]) print(Function Name:, function_name) print(Function Arguments:, function_args)python 复制代码 ---------- Response ---------- Function Name: rag_pipeline_func Function Arguments: {query: Wheres the coffee shop?}请再次注意这一步骤实际上还没有真正调用执行任何函数真正执行函数调用将是我们接下来这个步骤要做的。调用函数这一步骤我们需要将参数输入所选函数python 复制代码 ## Find the correspoding function and call it with the given arguments available_functions {get_items: get_items, purchase_item: purchase_item,rag_pipeline_func: rag_pipeline_func} function_to_call available_functions[function_name] function_response function_to_call(**function_args) print(Function Response:, function_response)python 复制代码 ---------- Response ---------- Function Response: {reply: The provided context does not specify a physical location for the coffee shop, only its operating hours. Therefore, I cannot determine where the coffee shop is located based on the given information.}然后我们可以将来自rag_pipeline_func的模型响应结果作为上下文信息附加到messages变量中从而让模型基于这个附加的上下文生成最终的答复。python 复制代码 messages.append(ChatMessage.from_function(contentjson.dumps(function_response), namefunction_name)) response chat_generator.run(messagesmessages) response_msg response[replies][0] print(response_msg.content)python 复制代码 ---------- Response ---------- For the location of the coffee shop within the hotel, I recommend asking the hotel staff directly. They will be able to guide you to it accurately.现在已经完成了一个完整的用户与 AI 的对话循环4.6 步骤 4将其转化为实时交互式对话interactive chat系统上面的代码展示了函数调用是如何实现的但我们想更进一步将其转化为实时交互式对话interactive chat系统。在本节我展示了两种实现方式较为原始的 input() 方法将对话内容打印到 notebook 中。通过 Streamlit 进行渲染提供类似 ChatGPT 的 UI 体验。input() loop这部分代码是从 Haystack 的教程[9]中复制过来的我们可以通过它快速测试模型。请注意该应用程序是为了演示函数调用Function Calling这一概念而创建的并非意味着此应用程序的健壮性完美例如支持同时对多个项目进行排序、无幻觉等。python 复制代码 import json from haystack.dataclasses import ChatMessage, ChatRole response None messages [ ChatMessage.from_system(context) ] while True: # if OpenAI response is a tool call if response and response[replies][0].meta[finish_reason] tool_calls: function_calls json.loads(response[replies][0].content) for function_call in function_calls: ## Parse function calling information function_name function_call[function][name] function_args json.loads(function_call[function][arguments]) ## Find the correspoding function and call it with the given arguments function_to_call available_functions[function_name] function_response function_to_call(**function_args) ## Append function response to the messages list using ChatMessage.from_function messages.append(ChatMessage.from_function(contentjson.dumps(function_response), namefunction_name)) # Regular Conversation else: # Append assistant messages to the messages list if not messages[-1].is_from(ChatRole.SYSTEM): messages.append(response[replies][0]) user_input input(ENTER YOUR MESSAGE INFO: Type exit or quit to stop\n) if user_input.lower() exit or user_input.lower() quit: break else: messages.append(ChatMessage.from_user(user_input)) response chat_generator.run(messagesmessages, generation_kwargs{tools: tools})在集成开发环境中运行交互式聊天 App尽管基本的交互方式也可以运行使用但拥有一个更加美观友好的用户界面会让用户体验更加出色。Streamlit 界面Streamlit 能够将 Python 脚本和 Web 开发技术优雅地结合转化为可共享使用的 Web 服务应用为这个函数调用交互式应用程序构建了一个全新的 Web 界面。上述代码已被改编成一个 Streamlit 应用位于代码仓库的 streamlit 文件夹中。我们可以通过以下步骤运行该应用如果还未运行请使用python db_api.py启动 API 服务器。将OPENROUTER_API_KEY设置为环境变量例如在 Linux 上或使用git bash时执行export OPENROUTER_API_KEY替换为您的API密钥。在终端中进入 streamlit 文件夹目录切换命令为cd streamlit。运行streamlit run app.py启动 Streamlit。浏览器应该会自动创建一个新的标签页运行该应用程序。基本上我想介绍的内容就是这些了真心希望大家能够喜欢这篇文章。想入门 AI 大模型却找不到清晰方向备考大厂 AI 岗还在四处搜集零散资料别再浪费时间啦2025 年AI 大模型全套学习资料已整理完毕从学习路线到面试真题从工具教程到行业报告一站式覆盖你的所有需求现在全部免费分享扫码免费领取全部内容​一、学习必备100本大模型电子书26 份行业报告 600 套技术PPT帮你看透 AI 趋势想了解大模型的行业动态、商业落地案例大模型电子书这份资料帮你站在 “行业高度” 学 AI1. 100本大模型方向电子书2. 26 份行业研究报告覆盖多领域实践与趋势报告包含阿里、DeepSeek 等权威机构发布的核心内容涵盖职业趋势《AI 职业趋势报告》《中国 AI 人才粮仓模型解析》商业落地《生成式 AI 商业落地白皮书》《AI Agent 应用落地技术白皮书》领域细分《AGI 在金融领域的应用报告》《AI GC 实践案例集》行业监测《2024 年中国大模型季度监测报告》《2025 年中国技术市场发展趋势》。3. 600套技术大会 PPT听行业大咖讲实战PPT 整理自 2024-2025 年热门技术大会包含百度、腾讯、字节等企业的一线实践安全方向《端侧大模型的安全建设》《大模型驱动安全升级腾讯代码安全实践》产品与创新《大模型产品如何创新与创收》《AI 时代的新范式构建 AI 产品》多模态与 Agent《Step-Video 开源模型视频生成进展》《Agentic RAG 的现在与未来》工程落地《从原型到生产AgentOps 加速字节 AI 应用落地》《智能代码助手 CodeFuse 的架构设计》。二、求职必看大厂 AI 岗面试 “弹药库”300 真题 107 道面经直接抱走想冲字节、腾讯、阿里、蔚来等大厂 AI 岗这份面试资料帮你提前 “押题”拒绝临场慌1. 107 道大厂面经覆盖 Prompt、RAG、大模型应用工程师等热门岗位面经整理自 2021-2025 年真实面试场景包含 TPlink、字节、腾讯、蔚来、虾皮、中兴、科大讯飞、京东等企业的高频考题每道题都附带思路解析2. 102 道 AI 大模型真题直击大模型核心考点针对大模型专属考题从概念到实践全面覆盖帮你理清底层逻辑3. 97 道 LLMs 真题聚焦大型语言模型高频问题专门拆解 LLMs 的核心痛点与解决方案比如让很多人头疼的 “复读机问题”三、路线必明 AI 大模型学习路线图1 张图理清核心内容刚接触 AI 大模型不知道该从哪学起这份「AI大模型 学习路线图」直接帮你划重点不用再盲目摸索路线图涵盖 5 大核心板块从基础到进阶层层递进一步步带你从入门到进阶从理论到实战。L1阶段:启航篇丨极速破界AI新时代L1阶段了解大模型的基础知识以及大模型在各个行业的应用和分析学习理解大模型的核心原理、关键技术以及大模型应用场景。L2阶段攻坚篇丨RAG开发实战工坊L2阶段AI大模型RAG应用开发工程主要学习RAG检索增强生成包括Naive RAG、Advanced-RAG以及RAG性能评估还有GraphRAG在内的多个RAG热门项目的分析。L3阶段跃迁篇丨Agent智能体架构设计L3阶段大模型Agent应用架构进阶实现主要学习LangChain、 LIamaIndex框架也会学习到AutoGPT、 MetaGPT等多Agent系统打造Agent智能体。L4阶段精进篇丨模型微调与私有化部署L4阶段大模型的微调和私有化部署更加深入的探讨Transformer架构学习大模型的微调技术利用DeepSpeed、Lamam Factory等工具快速进行模型微调并通过Ollama、vLLM等推理部署框架实现模型的快速部署。L5阶段专题集丨特训篇 【录播课】四、资料领取全套内容免费抱走学 AI 不用再找第二份不管你是 0 基础想入门 AI 大模型还是有基础想冲刺大厂、了解行业趋势这份资料都能满足你现在只需按照提示操作就能免费领取扫码免费领取全部内容​2025 年想抓住 AI 大模型的风口别犹豫这份免费资料就是你的 “起跑线”

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询