codefuse-chatbot/web_crawler/data/text/test_langchain_text.jsonl

11 lines
53 KiB
JSON
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"url": "https://www.langchain.asia/", "host_url": "https://www.langchain.asia", "title": "LangChain中文网: 500页超详细中文文档教程助力LLM/chatGPT应用开发 LangChain中文网", "content": "开始\nLangChain中文网: 500页超详细中文文档教程助力LLM/chatGPT应用开发\n\nLangChain 是一个开发由语言模型驱动的应用程序的框架。我们相信最强大和不同的应用程序不仅会通过 API 调用语言模型,\n还会\n\n数据感知\n: 将语言模型连接到其他数据源\n具有代理性质\n: 允许语言模型与其环境交互\n\nLangChain 框架是基于以上原则设计的。\n这是文档的 Python stable 稳定版本。\n关于 Python最新版本 v0.0.206 的文档,请参见\n这里 (opens in a new tab)\n。\n关于 LangChain 的纯概念指南请见\n这里 (opens in a new tab)\n。\n关于 JavaScript 的文档,请参见\n这里 (opens in a new tab)\n。\n关于 COOKBOOK 的文档,请参见\n这里 (opens in a new tab)\n。\n入门指南\n查看以下指南了解如何使用 LangChain 创建语言模型应用程序的详细说明。\n\n入门文档\n\n模块\nLangChain 提供了对几个主要模块的支持。\n针对每个模块我们提供一些入门示例、指南、参考文档和概念指南。\n这些模块按照逐渐增加的复杂性排列如下\n\n模型models\n: LangChain 支持的各种模型类型和模型集成。\n\n提示prompts\n: 包括提示管理、提示优化和提示序列化。\n\n内存memory\n: 内存是在链/代理调用之间保持状态的概念。LangChain 提供了一个标准的内存接口、一组内存实现及使用内存的链/代理示例。\n\n索引indexes\n: 与您自己的文本数据结合使用时,语言模型往往更加强大——此模块涵盖了执行此操作的最佳实践。\n\n链chains\n: 链不仅仅是单个 LLM 调用,还包括一系列调用(无论是调用 LLM 还是不同的实用工具。LangChain 提供了一种标准的链接口、许多与其他工具的集成。LangChain 提供了用于常见应用程序的端到端的链调用。\n\n代理agents\n: 代理涉及 LLM 做出行动决策、执行该行动、查看一个观察结果并重复该过程直到完成。LangChain 提供了一个标准的代理接口,一系列可供选择的代理,以及端到端代理的示例。\n\n用例\n上述模块可以以多种方式使用。LangChain 还提供指导和帮助。以下是 LangChain 支持的一些常见用例。\n\n自治代理autonomous agents\n: 长时间运行的代理会采取多步操作以尝试完成目标。 AutoGPT 和 BabyAGI就是典型代表。\n\n代理模拟agent simulations\n: 将代理置于封闭环境中观察它们如何相互作用,如何对事件作出反应,是观察它们长期记忆能力的有趣方法。\n\n个人助理personal assistants\n: 主要的 LangChain 使用用例。个人助理需要采取行动、记住交互并具有您的有关数据的知识。\n\n问答question answering\n: 第二个重大的 LangChain 使用用例。仅利用这些文档中的信息来构建答案,回答特定文档中的问题。\n\n聊天机器人chatbots\n: 由于语言模型擅长生成文本,因此它们非常适合创建聊天机器人。\n\n查询表格数据tabular\n: 如果您想了解如何使用 LLM 查询存储在表格格式中的数据csv、SQL、数据框等请阅读此页面。\n\n代码理解code\n: 如果您想了解如何使用 LLM 查询来自 GitHub 的源代码,请阅读此页面。\n\n与 API 交互apis\n: 使LLM 能够与 API 交互非常强大,以便为它们提供更实时的信息并允许它们采取行动。\n\n提取extraction\n: 从文本中提取结构化信息。\n\n摘要summarization\n: 将较长的文档汇总为更短、更简洁的信息块。一种数据增强生成的类型。\n\n评估evaluation\n: 生成模型是极难用传统度量方法评估的。\n一种新的评估方式是使用语言模型本身进行评估。\nLangChain 提供一些用于辅助评估的提示/链。\n\n参考文档\nLangChain 的所有参考文档都在这里。LangChain 的所有方法、类、安装方法和集成设置的完整文档。\n\n参考文档\n\nLangChain 生态系统\n其他公司/产品如何与 LangChain 协同工作的指南\n\nLangChain 生态系统\n\n资源集合#\n额外的资源集合我们认为可能是有用的因为您开发您的应用程序\n\nLangChainHub (opens in a new tab)\n: LangChainHub 是一个分享和探索其他 prompts、chains 和 agents 的平台。\nGallery (opens in a new tab)\n: 我们最喜欢的使用 LangChain 的项目合集,有助于找到灵感或了解其他应用程序的实现方式。\nDeployments (opens in a new tab)\n: 部署 LangChain 应用程序的说明、代码片段和模板存储库的合集。\nTracing (opens in a new tab)\n: 使用追踪可视化 LangChain 中链和代理执行的指南。\nModel Laboratory (opens in a new tab)\n: 使用不同的 prompts、models 和 chains 进行实验是开发最佳应用程序的重要组成部分。Model Laboratory 使这个过程变得非常容易。\nDiscord (opens in a new tab)\n: 加入我们的 Discord讨论关于 LangChain 的一切!\nYouTube (opens in a new tab)\n: LangChain 教程和视频的集合。\nProduction Support (opens in a new tab)\n: 随着您将 LangChains 发布到生产环境,我们乐于提供更全面的支持。请填写此表格,我们将设置一个专门的支持 Slack 频道。\n开始\n\n"}
{"url": "https://www.langchain.asia/getting_started/getting_started", "host_url": "https://www.langchain.asia", "title": "\n快速入门指南 LangChain中文网", "content": "快速入门指南开始\n\n快速入门指南\n本教程将简要介绍如何使用 LangChain 构建端到端语言模型应用程序。\n安装\n首先使用以下命令安装 LangChain:\n\n```code\npip install langchain\n# or\nconda install langchain -c conda-forge\n```\n\n环境设定\n使用 LangChain 通常需要与一个或多个模型提供程序、数据存储、 API 等集成。\n对于这个例子我们将使用 OpenAI 的 API所以我们首先需要安装他们的 SDK:\n\n```code\npip install openai\n```\n\n然后我们需要在终端设置环境变量。\n\n```code\nexport OPENAI_API_KEY=\"...\"\n```\n\n或者你可以在 Jupiter 教程(或 Python 脚本)内部完成:\n\n```code\nimport os\nos.environ[\"OPENAI_API_KEY\"] = \"...\"\n```\n\n构建语言模型应用程序: LLM\n现在我们已经安装了 LangChain 并设置了我们的环境,我们可以开始构建我们的语言模型应用程序了。\nLangChain 提供了许多可用于构建语言模型应用程序的模块。\n模块可以组合起来创建更复杂的应用程序或者单独用于简单的应用程序。\nLLM: 从语言模型中获取预测\nLangChain 最基本的构建块是对某些输入调用 LLM。\n让我们来看一个简单的例子。\n我们假设我们正在构建一个基于公司产品生成公司名称的服务。\n为此我们首先需要导入 LLM 包装器。\n\n```code\nfrom langchain.llms import OpenAI\n```\n\nLLM初始化和调用\n然后我们可以用任何参数初始化包装器。\n在这个例子中我们可能希望输出更加随机所以我们将以温度temperature初始化它。\n\n```code\nllm = OpenAI(temperature=0.9)\n```\n\n我们现在可以根据一些输入调用它\n\n```code\ntext = \"What would be a good company name for a company that makes colorful socks?\"\nprint(llm(text))\nFeetful of Fun\n```\n\n有关如何在 LangChain 中使用 LLM 的详细信息,请参阅 LLM 入门指南。\n提示模板PromptTemplate: 管理 LLM 的提示\n调用 LLM 是很好的第一步,但这仅仅是个开始。\n通常在应用程序中使用 LLM 时,不会将用户输入直接发送到 LLM。\n相反您可能接受用户输入并构造一个提示符然后将其发送给 LLM。\n例如在前一个示例中我们传入的文本被硬编码为询问一家生产彩色袜子的公司的名称。在这个虚构的服务中我们希望只获取描述公司业务的用户输入然后用这些信息格式化提示符。\n使用LangChain这个事情变得很简单\n首先让我们定义提示模板:\n\n```code\nfrom langchain.prompts import PromptTemplate\n\nprompt = PromptTemplate(\ninput_variables=[\"product\"],\ntemplate=\"What is a good name for a company that makes {product}?\",\n)\n```\n\n现在让我们看看它是如何工作的!\n我们可以调用\n```code\n. format\n```\n方法来格式化它。\n\n```code\nprint(prompt.format(product=\"colorful socks\"))\nWhat is a good name for a company that makes colorful socks?\n```\n\n有关详细信息请参阅入门指南中的提示。\n链: 在多步骤的工作流中组合 LLM 和提示\n到目前为止我们已经自己处理了单独的\n```code\nPromptTemplate\n```\n和\n```code\nLLM\n```\n。\n但是真正的应用程序不仅仅是一个而是它们的组合。\n在 LangChain链是由链组成的可以是 LLM 这样的原始链,也可以是其他链。\n最核心的链类型是\n```code\nLLMChain\n```\n它由\n```code\nPromptTemplate\n```\n和\n```code\nLLM\n```\n组成。\n扩展前面的示例我们可以构造一个\n```code\nLLMChain\n```\n.\n它接受用户输入使用 PromptTemplate 对其进行格式化,然后将格式化后的响应传递给\n```code\nLLM\n```\n。\n\n```code\nfrom langchain.prompts import PromptTemplate\nfrom langchain.llms import OpenAI\n\nllm = OpenAI(temperature=0.9)\nprompt = PromptTemplate(\ninput_variables=[\"product\"],\ntemplate=\"What is a good name for a company that makes {product}?\",\n)\n```\n\n我们现在可以创建一个非常简单的链: 它接受用户输入,用它格式化提示符,然后将它发送到 LLM:\n\n```code\nfrom langchain.chains import LLMChain\nchain = LLMChain(llm=llm, prompt=prompt)\n```\n\n现在我们可以运行该链只指定产品\n\n```code\nchain.run(\"colorful socks\")\n# -> '\\n\\nSocktastic!'\n```\n\n这就对了你有第1个链 —— 1个 LLM 链。\n这是比较简单的链类型之一但是了解它的工作原理将为您处理更复杂的链打下良好的基础。\n有关更多细节请查看链接的入门指南。\n代理 Agent: 基于用户输入的动态调用链\n到目前为止我们看到的链运行在一个预先确定的顺序。\n但是代理不再这样做: 它们使用 LLM 来确定要执行哪些操作以及按照什么顺序执行。\n操作可以使用工具并观察其输出也可以返回给用户。\n如果使用得当效果可以非常强大。\n在本教程中我们将向您展示如何通过最简单、最高级别的 API 轻松使用代理。\n为了运好代理您应该理解以下概念:\n\n工具tools): 执行特定任务的功能。这可以是: Google 搜索、数据库查找、 Python REPL、其他链。工具的接口目前是一个函数预计将有一个字符串作为输入一个字符串作为输出。\n大语言模型LLM: 为代理提供动力的语言模型。\n代理agents: 要使用的代理。这应该是引用支持代理类的字符串。因为本教程主要关注最简单、最高级别的 API所以它只涉及使用标准支持的代理。如果要实现自定义代理请参阅自定义代理的文档(即将发布)。\n\n代理agents : 有关受支持的 Agent 及其规范的列表,请参见此处\n工具tools) : 有关预定义工具及其规范的列表, 请参见此处.\n对于本例您还需要安装 SerpAPI Python 包。\n\n```code\npip install google-search-results\n```\n\n并设置适当的环境变量。\n\n```code\nimport os\nos.environ[\"SERPAPI_API_KEY\"] = \"...\"\n```\n\n现在我们可以开始了\n\n```code\nfrom langchain.agents import load_tools\nfrom langchain.agents import initialize_agent\nfrom langchain.agents import AgentType\nfrom langchain.llms import OpenAI\n\n# First, let's load the language model we're going to use to control the agent.\nllm = OpenAI(temperature=0)\n\n# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.\ntools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n\n# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.\nagent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n\n# Now let's test it out!\nagent.run(\"What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?\")\n```\n\n```code\n> Entering new AgentExecutor chain...\nI need to find the temperature first, then use the calculator to raise it to the .023 power.\nAction: Search\nAction Input: \"High temperature in SF yesterday\"\nObservation: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...\nThought: I now have the temperature, so I can use the calculator to raise it to the .023 power.\nAction: Calculator\nAction Input: 57^.023\nObservation: Answer: 1.0974509573251117\nThought: I now know the final answer\nFinal Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.\n> Finished chain.\n```\n\n内存: 向链和代理添加状态\n到目前为止我们经历过的所有工具和代理都是无状态的的。\n但是通常您可能希望链或代理具有某种“内存”概念以便它可以记住关于其以前的交互的信息。\n最简单明了的例子就是在设计一个聊天机器人时——你想让它记住之前的消息这样它就可以利用这些消息的上下文来进行更好的对话。\n这是一种“短期记忆”。在更复杂的一面你可以想象一个链条/代理随着时间的推移记住关键信息——这将是一种形式的“长期记忆”。关于后者的更多具体想法,请参阅这篇令人敬畏的论文。 (opens in a new tab)\nLangChain 提供了几个专门为此目的创建的链。 本教程使用其中一个链(\n\n```code\nConversationChain\n```\n\n) 和两种不同类型的内存来完成操作。\n默认情况下,\n\n```code\nConversationChain\n```\n\n有一个简单的内存类型它记住所有以前的输入/输出,并将它们添加到传递的上下文中。\n让我们看一下如何使用这个链(设置\n```code\nverbose=True\n```\n这样我们就可以看到提示符)。\n\n```code\nfrom langchain import OpenAI, ConversationChain\nllm = OpenAI(temperature=0)\nconversation = ConversationChain(llm=llm, verbose=True)\noutput = conversation.predict(input=\"Hi there!\")\nprint(output)\n```\n\n```code\n> Entering new chain...\nPrompt after formatting:\nThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\nCurrent conversation:\nHuman: Hi there!\nAI:\n> Finished chain.\n' Hello! How are you today?'\n```\n\n```code\noutput = conversation.predict(input=\"I'm doing well! Just having a conversation with an AI.\")\nprint(output)\n```\n\n```code\n> Entering new chain...\nPrompt after formatting:\nThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\nCurrent conversation:\nHuman: Hi there!\nAI: Hello! How are you today?\nHuman: I'm doing well! Just having a conversation with an AI.\nAI:\n> Finished chain.\n\" That's great! What would you like to talk about?\"\n```\n\n构建语言模型应用程序: 聊天模型\n类似地您可以使用聊天模型而不是 LLM。\n聊天模型是语言模型的一种变体。\n虽然聊天模型使用的是底层的语言模型但它们公开的接口有些不同: 它们没有公开“文本输入、文本输出”API而是公开了一个接口其中“聊天消息”是输入和输出。\n聊天模型 API 是相当新的,所以我们仍然在找出正确的抽象。\n从聊天模型获取消息完成\n您可以通过向聊天模型传递一条或多条消息来完成聊天。\n响应将是一条消息。\nLangChain 中当前支持的消息类型是\n\n```code\nAIMessage\n```\n\n,\n\n```code\nHumanMessage\n```\n\n,\n\n```code\nSystemMessage\n```\n\n, 和\n\n```code\nChatMessage\n```\n\n\n\n```code\nChatMessage\n```\n\n接受任意角色参数。大多数时候您只需要处理\n\n```code\nHumanMessage\n```\n\n,\n\n```code\nAIMessage\n```\n\n, 和\n\n```code\nSystemMessage\n```\n\n.\n\n```code\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import (\nAIMessage,\nHumanMessage,\nSystemMessage\n)\nchat = ChatOpenAI(temperature=0)\n```\n\n您可以通过传入单个消息来完成。\n\n```code\nchat([HumanMessage(content=\"Translate this sentence from English to French. I love programming.\")])\n# -> AIMessage(content=\"J'aime programmer.\", additional_kwargs={})\n```\n\n您还可以为 OpenAI 的 gpt-3.5-turbo 和 gpt-4型号传递多条消息。\n\n```code\nmessages = [\nSystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\nHumanMessage(content=\"Translate this sentence from English to French. I love programming.\")\n]\nchat(messages)\n# -> AIMessage(content=\"J'aime programmer.\", additional_kwargs={})\n```\n\n您可以更进一步使用\n```code\ngenerate\n```\n为多组消息生成完成。\n这将返回一个带有附加\n```code\nmessage\n```\n参数的\n```code\nLLMResult\n```\n。\n\n```code\nbatch_messages = [\n[\nSystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\nHumanMessage(content=\"Translate this sentence from English to French. I love programming.\")\n],\n[\nSystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\nHumanMessage(content=\"Translate this sentence from English to French. I love artificial intelligence.\")\n],\n]\nresult = chat.generate(batch_messages)\n\nresult\n# -> LLMResult(generations=[[ChatGeneration(text=\"J'aime programmer.\", generation_info=None, message=AIMessage(content=\"J'aime programmer.\", additional_kwargs={}))], [ChatGeneration(text=\"J'aime l'intelligence artificielle.\", generation_info=None, message=AIMessage(content=\"J'aime l'intelligence artificielle.\", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}})\n```\n\n您可以从这个 LLMResult 中获取字符令牌的使用情况token_usage:\n\n```code\nresult.llm_output['token_usage']\n# -> {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}\n\n```\n\n聊天提示模板\n与 LLM 类似,您可以通过使用\n```code\nMessagePromptTemplate\n```\n来使用模板。\n可以从一个或多个\n```code\nMessagePromptTemplate\n```\n生成\n```code\nChatPromptTemplate\n```\n。\n您可以使用\n```code\nChatPromptTemplate\n```\n的\n```code\nformat _ tip\n```\n——这将返回一个\n```code\nPromptValue\n```\n\n您可以将其转换为字符串或\n```code\nMessage\n```\n对象具体取决于您是想将格式化的值用作\n```code\nllm\n```\n或聊天模型的输入。\n为了方便起见在模板上公开了一个\n```code\nfrom _ template\n```\n方法。如果你使用这个模板它看起来是这样的:\n\n```code\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts.chat import (\nChatPromptTemplate,\nSystemMessagePromptTemplate,\nHumanMessagePromptTemplate,\n)\n\nchat = ChatOpenAI(temperature=0)\ntemplate = \"You are a helpful assistant that translates {input_language} to {output_language}.\"\nsystem_message_prompt = SystemMessagePromptTemplate.from_template(template)\nhuman_template = \"{text}\"\nhuman_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\nchat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n\n# get a chat completion from the formatted messages\nchat(chat_prompt.format_prompt(input_language=\"English\", output_language=\"French\", text=\"I love programming.\").to_messages())\n\n# -> AIMessage(content=\"J'aime programmer.\", additional_kwargs={})\n```\n\n带聊天模型的链\n上一节讨论的\n```code\nLLMChain\n```\n也可以用于聊天模型:\n\n```code\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain import LLMChain\nfrom langchain.prompts.chat import (\nChatPromptTemplate,\nSystemMessagePromptTemplate,\nHumanMessagePromptTemplate,\n)\n\nchat = ChatOpenAI(temperature=0)\ntemplate = \"You are a helpful assistant that translates {input_language} to {output_language}.\"\nsystem_message_prompt = SystemMessagePromptTemplate.from_template(template)\nhuman_template = \"{text}\"\nhuman_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\nchat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\nchain = LLMChain(llm=chat, prompt=chat_prompt)\nchain.run(input_language=\"English\", output_language=\"French\", text=\"I love programming.\")\n\n# -> \"J'aime programmer.\"\n```\n\n具有聊天模型的代理\n代理也可以与聊天模型一起使用您可以使用\n```code\nAgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION\n```\n作为代理类型来初始化一个聊天模型。\n\n```code\nfrom langchain.agents import load_tools\nfrom langchain.agents import initialize_agent\nfrom langchain.agents import AgentType\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.llms import OpenAI\n\n# First, let's load the language model we're going to use to control the agent.\nchat = ChatOpenAI(temperature=0)\n\n# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.\nllm = OpenAI(temperature=0)\ntools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n\n# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.\nagent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n\n# Now let's test it out!\nagent.run(\"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?\")\n```\n\n```code\n> Entering new AgentExecutor chain...\nThought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.\nAction:\n{\n\"action\": \"Search\",\n\"action_input\": \"Olivia Wilde boyfriend\"\n}\nObservation: Sudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.\nThought:I need to use a search engine to find Harry Styles' current age.\nAction:\n{\n\"action\": \"Search\",\n\"action_input\": \"Harry Styles age\"\n}\nObservation: 29 years\nThought:Now I need to calculate 29 raised to the 0.23 power.\nAction:\n{\n\"action\": \"Calculator\",\n\"action_input\": \"29^0.23\"\n}\nObservation: Answer: 2.169459462491557\nThought:I now know the final answer.\nFinal Answer: 2.169459462491557\n> Finished chain.\n'2.169459462491557'\n```\n\n记忆内存: 向链和代理添加状态\n您可以对链使用 Memory对代理使用聊天模型进行初始化。\n这与 LLM 的 Memory 之间的主要区别在于,我们不需要将以前的所有消息压缩成一个字符串,而是可以将它们保留为自己独特的内存对象。\n\n```code\nfrom langchain.prompts import (\nChatPromptTemplate,\nMessagesPlaceholder,\nSystemMessagePromptTemplate,\nHumanMessagePromptTemplate\n)\nfrom langchain.chains import ConversationChain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.memory import ConversationBufferMemory\n\nprompt = ChatPromptTemplate.from_messages([\nSystemMessagePromptTemplate.from_template(\"The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\"),\nMessagesPlaceholder(variable_name=\"history\"),\nHumanMessagePromptTemplate.from_template(\"{input}\")\n])\nllm = ChatOpenAI(temperature=0)\nmemory = ConversationBufferMemory(return_messages=True)\nconversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)\nconversation.predict(input=\"Hi there!\")\n\n# -> 'Hello! How can I assist you today?'\nconversation.predict(input=\"I'm doing well! Just having a conversation with an AI.\")\n\n# -> \"That sounds like fun! I'm happy to chat with you. Is there anything specific you'd like to talk about?\"\nconversation.predict(input=\"Tell me about yourself.\")\n\n# -> \"Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?\"\n```\n开始代理Agents)\n\n"}
{"url": "https://www.langchain.asia/modules/agents", "host_url": "https://www.langchain.asia", "title": "代理人Agents LangChain中文网", "content": "6大核心模块Modules)代理Agents)\n\n代理人Agents\n概念指南 (opens in a new tab)\n有些应用程序不仅需要预先确定的LLM/其他工具调用链,而且可能需要根据用户输入的不同而产生不同的链条。\n在这些类型的链条中有一个“代理人”可以访问一套工具。\n根据用户输入代理人可以决定是否调用其中任何一个工具。\n在本文档的本节中我们首先从“快速入门”开始介绍如何以端到端的方式使用与代理人相关的所有内容。\n然后我们将文档分成以下几个部分\n工具tools)\n介绍LangChain支持的各种工具的概述。\n代理人 (agents)\n介绍不同代理人类型的概述。\n工具包 (toolkits)\n介绍工具包的概述以及LangChain支持的不同工具包的示例。开始入门Getting Started\n\n"}
{"url": "https://www.langchain.asia/modules/agents/getting_started", "host_url": "https://www.langchain.asia", "title": "快速入门# LangChain中文网", "content": "6大核心模块Modules)代理Agents)入门Getting Started\n\n快速入门#\n代理使用LLM来确定采取哪些行动以及顺序。\n一个动作可以是使用工具并观察其输出或返回给用户。\n当代理被正确使用时它们可以非常强大。本教程的目的是向您展示如何通过最简单、最高级别的API轻松使用代理。\n为了加载代理您应该了解以下概念\n\n工具执行特定职责的函数。这可以是诸如Google搜索、数据库查找、Python REPL、其他链等。工具的接口目前是期望有一个字符串作为输入一个字符串作为输出的函数。\n\nLLM为代理提供动力的语言模型。\n\n代理要使用的代理。这应该是一个引用支持代理类的字符串。因为本教程专注于最简单、最高级别的API所以只涵盖使用标准支持的代理。如果您想实现自定义代理请参阅自定义代理的文档即将推出)。\n\n代理人支持的代理人清单及其规格请参见此处。\n工具预定义工具及其规格的清单请参见此处。\n\n```code\nfrom langchain.agents import load_tools\nfrom langchain.agents import initialize_agent\nfrom langchain.agents import AgentType\nfrom langchain.llms import OpenAI\n\n```\n\n首先让我们加载我们要使用的语言模型来控制代理人。\n\n```code\nllm = OpenAI(temperature=0)\n\n```\n\n接下来让我们加载一些要使用的工具。请注意\n```code\nllm-math\n```\n工具使用LLM因此我们需要传递它。\n\n```code\ntools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n\n```\n\n最后让我们使用工具、语言模型和我们想要使用的代理人类型初始化一个代理人。\n\n```code\nagent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n\n```\n\n现在让我们来测试一下吧\n\n```code\nagent.run(\"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\")\n\n```\n\n```code\n> Entering new AgentExecutor chain...\nI need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.\nAction: Search\nAction Input: \"Leo DiCaprio girlfriend\"\nObservation: Camila Morrone\nThought: I need to find out Camila Morrone's age\nAction: Search\nAction Input: \"Camila Morrone age\"\nObservation: 25 years\nThought: I need to calculate 25 raised to the 0.43 power\nAction: Calculator\nAction Input: 25^0.43\nObservation: Answer: 3.991298452658078\n\nThought: I now know the final answer\nFinal Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.\n\n> Finished chain.\n\n```\n\n```code\n\"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.\"\n\n```\n代理Agents)代理Agents\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents", "host_url": "https://www.langchain.asia", "title": "代理人 LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理Agents\n\n代理人\n\n注意 概念指南 (opens in a new tab)\n\n在本文档的这一部分中我们涵盖了不同类型的代理人不考虑它们使用哪些特定工具。\n有关不同类型代理人的高级概述请参阅以下文档。\n\n代理人类型\n\n有关如何创建自定义代理人的文档请参见以下内容。\n\n自定义代理人\n自定义LLM代理人\n自定义LLM代理人带有ChatModel\n自定义MRKL代理人\n自定义MultiAction代理人\n具有工具检索的自定义代理人\n\n我们还有深入研究每种代理人类型的文档。\n\n对话代理人用于聊天\nLLM代理人\nMRKL代理人\nMultiAction代理人\n工具检索代理人\n入门Getting Started代理类型Agent Types\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents/agent_types", "host_url": "https://www.langchain.asia", "title": "代理类型# LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理Agents代理类型Agent Types\n\n代理类型#\n代理使用LLM语言模型)来确定应采取哪些操作以及以何顺序执行这些操作。\n动作可能是使用工具并观察其输出或向用户返回响应。\n以下是LangChain中可用的代理\n\n```code\nzero-shot-react-description\n```\n#\n此代理使用ReAct框架仅基于工具的描述来确定要使用的工具。\n可以提供任意数量的工具。\n此代理需要为每个工具提供描述。\n\n```code\nreact-docstore\n```\n#\n这个代理使用ReAct框架与文档存储进行交互。\n必须提供两个工具一个\n```code\nSearch\n```\n工具和一个\n```code\nLookup\n```\n工具它们必须被命名为这样)。\n\n```code\nSearch\n```\n工具应该搜索文档而\n```code\nLookup\n```\n工具应该查找最近找到的文档中的一个术语。\n这个代理相当于最初的ReAct论文 (opens in a new tab),特别是维基百科的例子。\n\n```code\nself-ask-with-search\n```\n#\n这个代理使用一个被命名为\n```code\nIntermediate Answer\n```\n的工具。\n这个工具应该能够查找问题的事实性答案。\n这个代理相当于最初的self ask with search paper (opens in a new tab)其中提供了Google搜索API作为工具。\n\n```code\nconversational-react-description\n```\n#\n这个代理程序旨在用于对话环境中。提示设计旨在使代理程序有助于对话。\n它使用ReAct框架来决定使用哪个工具并使用内存来记忆先前的对话交互。代理Agents自定义代理Custom Agent\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents/custom_agent", "host_url": "https://www.langchain.asia", "title": "自定义代理 (Custom Agents) LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理Agents自定义代理Custom Agent\n\n自定义代理 (Custom Agents)\n本教程将介绍如何创建自己的自定义代理 (Custom Agents)。\n一个代理 (Agent) 由二个部分组成:\n\n工具 tool代理可以使用的工具。\n代理执行器 :这决定了采取哪些行动。\n\n在本教程里我们将介绍如何创建自定义代理。\n\n```code\nfrom langchain.agents import Tool, AgentExecutor, BaseSingleActionAgent\nfrom langchain import OpenAI, SerpAPIWrapper\n\n```\n\n```code\nsearch = SerpAPIWrapper()\ntools = [\nTool(\nname = \"Search\",\nfunc=search.run,\ndescription=\"useful for when you need to answer questions about current events\",\nreturn_direct=True\n)\n]\n\n```\n\n```code\nfrom typing import List, Tuple, Any, Union\nfrom langchain.schema import AgentAction, AgentFinish\n\nclass FakeAgent(BaseSingleActionAgent):\n\"\"\"Fake Custom Agent.\"\"\"\n\n@property\ndef input_keys(self):\nreturn [\"input\"]\n\ndef plan(\nself, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n) -> Union[AgentAction, AgentFinish]:\n\"\"\"Given input, decided what to do.\n\nArgs:\nintermediate_steps: Steps the LLM has taken to date,\nalong with observations\n**kwargs: User inputs.\n\nReturns:\nAction specifying what tool to use.\n\"\"\"\nreturn AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")\n\nasync def aplan(\nself, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n) -> Union[AgentAction, AgentFinish]:\n\"\"\"Given input, decided what to do.\n\nArgs:\nintermediate_steps: Steps the LLM has taken to date,\nalong with observations\n**kwargs: User inputs.\n\nReturns:\nAction specifying what tool to use.\n\"\"\"\nreturn AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")\n```\n\n```code\nagent = FakeAgent()\n```\n\n```code\nagent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)\n```\n\n```code\nagent_executor.run(\"How many people live in canada as of 2023?\")\n```\n\n```code\n> Entering new AgentExecutor chain...\nThe current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.\n\n> Finished chain.\n```\n\n```code\n'The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.'\n```\n代理类型Agent Types带工具检索的自定义代理Custom Agent with Tool Retrieval\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents/custom_agent_with_tool_retrieval", "host_url": "https://www.langchain.asia", "title": "带工具检索的自定义代理# LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理Agents带工具检索的自定义代理Custom Agent with Tool Retrieval\n\n带工具检索的自定义代理#\n\n带工具检索的自定义代理 custom-agent-with-tool-retrieval\n\n本教程假定你已经熟悉代理工作原理。\n\n本教程介绍的新想法是使用检索来选择要用于回答代理查询的工具集。\n当你有很多工具可供选择时这非常有用。你不能在提示中放置所有工具的描述由于上下文长度问题)因此你动态选择你想要在运行时考虑使用的N个工具。\n我们将创建一个有点伪需求的例子。\n我们将有一个合适的工具搜索然后99个假工具这只是废话。\n然后我们将在提示模板中添加一个步骤该步骤接受用户输入并检索与查询相关的工具。\n设置环境#\n进行必要的导入等设置。\n\n```code\nfrom langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser\nfrom langchain.prompts import StringPromptTemplate\nfrom langchain import OpenAI, SerpAPIWrapper, LLMChain\nfrom typing import List, Union\nfrom langchain.schema import AgentAction, AgentFinish\nimport re\n\n```\n\n设置工具#\n我们将创建一个合适的工具搜索)和99个不相关的工具。\n\n```code\n# Define which tools the agent can use to answer user queries\nsearch = SerpAPIWrapper()\nsearch_tool = Tool(\nname = \"Search\",\nfunc=search.run,\ndescription=\"useful for when you need to answer questions about current events\"\n)\ndef fake_func(inp: str) -> str:\nreturn \"foo\"\nfake_tools = [\nTool(\nname=f\"foo-{i}\",\nfunc=fake_func,\ndescription=f\"a silly function that you can use to get more information about the number {i}\"\n)\nfor i in range(99)\n]\nALL_TOOLS = [search_tool] + fake_tools\n\n```\n\n工具检索器(tool-retriever)#\n我们将使用向量存储来为每个工具描述创建嵌入。\n然后对于传入的查询我们可以为该查询创建嵌入并进行相关工具的相似性搜索。\n\n```code\nfrom langchain.vectorstores import FAISS\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.schema import Document\n\n```\n\n```code\ndocs = [Document(page_content=t.description, metadata={\"index\": i}) for i, t in enumerate(ALL_TOOLS)]\n\n```\n\n```code\nvector_store = FAISS.from_documents(docs, OpenAIEmbeddings())\n\n```\n\n```code\nretriever = vector_store.as_retriever()\n\ndef get_tools(query):\ndocs = retriever.get_relevant_documents(query)\nreturn [ALL_TOOLS[d.metadata[\"index\"]] for d in docs]\n\n```\n\n现在我们可以测试这个检索器看看它是否有效。\n\n```code\nget_tools(\"whats the weather?\")\n\n```\n\n```code\n[Tool(name='Search', description='useful for when you need to answer questions about current events', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<bound method SerpAPIWrapper.run of SerpAPIWrapper(search_engine=<class 'serpapi.google_search.GoogleSearch'>, params={'engine': 'google', 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'}, serpapi_api_key='c657176b327b17e79b55306ab968d164ee2369a7c7fa5b3f8a5f7889903de882', aiosession=None)>, coroutine=None),\nTool(name='foo-95', description='a silly function that you can use to get more information about the number 95', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),\nTool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),\nTool(name='foo-15', description='a silly function that you can use to get more information about the number 15', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)]\n\n```\n\n```code\nget_tools(\"whats the number 13?\")\n\n```\n\n```code\n[Tool(name='foo-13', description='a silly function that you can use to get more information about the number 13', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),\nTool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),\nTool(name='foo-14', description='a silly function that you can use to get more information about the number 14', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),\nTool(name='foo-11', description='a silly function that you can use to get more information about the number 11', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)]\n\n```\n\n提示模板#\n提示模板非常标准因为我们实际上没有改变实际提示模板中的太多逻辑而是只改变了如何进行检索。\n\n```code\n# Set up the base template\ntemplate = \"\"\"Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\n\n{tools}\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin! Remember to speak as a pirate when giving your final answer. Use lots of \"Arg\"s\n\nQuestion: {input}\n{agent_scratchpad}\"\"\"\n\n```\n\n自定义提示模板现在具有一个\n```code\ntools_getter\n```\n的概念我们对输入调用它以选择要使用的工具。\n\n```code\nfrom typing import Callable\n# Set up a prompt template\nclass CustomPromptTemplate(StringPromptTemplate):\n# The template to use\ntemplate: str\n############## NEW ######################\n# The list of tools available\ntools_getter: Callable\n\ndef format(self, **kwargs) -> str:\n# Get the intermediate steps (AgentAction, Observation tuples)\n# Format them in a particular way\nintermediate_steps = kwargs.pop(\"intermediate_steps\")\nthoughts = \"\"\nfor action, observation in intermediate_steps:\nthoughts += action.log\nthoughts += f\"\\nObservation: {observation}\\nThought: \"\n# Set the agent_scratchpad variable to that value\nkwargs[\"agent_scratchpad\"] = thoughts\n############## NEW ######################\ntools = self.tools_getter(kwargs[\"input\"])\n# Create a tools variable from the list of tools provided\nkwargs[\"tools\"] = \"\\n\".join([f\"{tool.name}: {tool.description}\" for tool in tools])\n# Create a list of tool names for the tools provided\nkwargs[\"tool_names\"] = \", \".join([tool.name for tool in tools])\nreturn self.template.format(**kwargs)\n\n```\n\n```code\nprompt = CustomPromptTemplate(\ntemplate=template,\ntools_getter=get_tools,\n# This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically\n# This includes the `intermediate_steps` variable because that is needed\ninput_variables=[\"input\", \"intermediate_steps\"]\n)\n\n```\n\n输出解析器 (Output Parser)#\n输出解析器与之前的教程没有改变因为我们没有改变任何有关输出格式的内容。\n\n```code\nclass CustomOutputParser(AgentOutputParser):\n\ndef parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:\n# Check if agent should finish\nif \"Final Answer:\" in llm_output:\nreturn AgentFinish(\n# Return values is generally always a dictionary with a single `output` key\n# It is not recommended to try anything else at the moment :)\nreturn_values={\"output\": llm_output.split(\"Final Answer:\")[-1].strip()},\nlog=llm_output,\n)\n# Parse out the action and action input\nregex = r\"Action\\s*\\d*\\s*:(.*?)\\nAction\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\nmatch = re.search(regex, llm_output, re.DOTALL)\nif not match:\nraise ValueError(f\"Could not parse LLM output: `{llm_output}`\")\naction = match.group(1).strip()\naction_input = match.group(2)\n# Return the action and action input\nreturn AgentAction(tool=action, tool_input=action_input.strip(\" \").strip('\"'), log=llm_output)\n\n```\n\n```code\noutput_parser = CustomOutputParser()\n\n```\n\n设置LLM停止序列和代理#\n与之前的教程相同\n\n```code\nllm = OpenAI(temperature=0)\n\n```\n\n```code\n# LLM chain consisting of the LLM and a prompt\nllm_chain = LLMChain(llm=llm, prompt=prompt)\n\n```\n\n```code\ntools = get_tools(\"whats the weather?\")\ntool_names = [tool.name for tool in tools]\nagent = LLMSingleActionAgent(\nllm_chain=llm_chain,\noutput_parser=output_parser,\nstop=[\"\\nObservation:\"],\nallowed_tools=tool_names\n)\n\n```\n\n使用代理Use the Agent#\n现在我们可以使用它了\n\n```code\nagent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)\n\n```\n\n```code\nagent_executor.run(\"What's the weather in SF?\")\n\n```\n\n```code\n> Entering new AgentExecutor chain...\nThought: I need to find out what the weather is in SF\nAction: Search\nAction Input: Weather in SF\n\nObservation:Mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shifting to W at 10 to 15 mph. Humidity71%. UV Index6 of 10. I now know the final answer\nFinal Answer: 'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10.\n\n> Finished chain.\n\n```\n\n```code\n\"'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10.\"\n\n```\n自定义代理Custom AgentLLM 聊天自定义代理Custom LLM Chat Agent\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents/custom_llm_chat_agent", "host_url": "https://www.langchain.asia", "title": "自定义LLM代理带有ChatModel LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理AgentsLLM 聊天自定义代理Custom LLM Chat Agent\n\n自定义LLM代理带有ChatModel\n本笔记将介绍如何基于聊天模型创建自己的自定义代理。\nLLM聊天代理由三个部分组成\n\nPromptTemplate这是用于指示语言模型该做什么的提示模板\nChatModel这是驱动代理的语言模型\n\n```code\nstop\n```\n序列指示LLM在找到此字符串时停止生成\nOutputParser确定如何将LLM输出解析为AgentAction或AgentFinish对象。\n\nLLMAgent用于代理执行器。这个代理执行器在很大程度上可以看作是一个循环\n\n将用户输入和任何先前的步骤传递给代理在这种情况下是LLMAgent\n如果代理返回\n```code\nAgentFinish\n```\n则将其直接返回给用户。\n带工具检索的自定义代理Custom Agent with Tool RetrievalMRKL 自定义代理Custom MRKL Agent\n\n"}
{"url": "https://www.langchain.asia/modules/agents/agents/custom_mrkl_agent", "host_url": "https://www.langchain.asia", "title": "自定义MRKL代理 LangChain中文网", "content": "6大核心模块Modules)代理Agents)代理AgentsMRKL 自定义代理Custom MRKL Agent\n\n自定义MRKL代理\n本文档介绍如何创建自己的自定义MRKL Agent。\nMRKL Agent由三个部分组成\n\n工具代理可用的工具。\nLLMChain生成以一定方式解析的文本以确定要采取哪个动作。\n代理类本身解析LLMChain的输出以确定要采取哪个动作。\n\n本文档介绍如何通过创建自定义LLMChain来创建自定义MRKL代理。\n自定义LLMChainCustom LLMChain#\n创建自定义代理的第一种方法是使用现有的代理类但使用自定义LLMCain。\n这是创建自定义代理的最简单方法。\n强烈建议您使用\n```code\nZeroShotAgent\n```\n因为目前这是最通用的一个。\n创建自定义LLMCain的大部分工作都归结为提示符。因为我们使用的是一个现有的代理类来解析输出所以提示符中要生成该格式的文本是非常重要的。此外我们目前需要一个 agent_scratchpad 输入变量来记录以前的操作和观察结果。\n这几乎总是提示符的最后一部分。\n但是除了这些说明之外您还可以根据需要自定义提示。\n为了确保提示符包含适当的指令我们将在该类上使用\n```code\nhelper\n```\n方法。\n\n```code\nZeroShotAgent\n```\n的\n```code\nhelper\n```\n方法接受以下参数\n\ntools座席将有权访问的工具列表用于设置提示的格式。\nprefix:要放在工具列表前面的字符串。\nsuffix: 放在工具列表后面的字符串。\ninput_variables最后提示所期望的输入变量列表。\n\n在这个练习中我们将给予我们的代理访问Google搜索我们将定制它我们将让它回答为盗版。\n\n```code\nfrom langchain.agents import ZeroShotAgent, Tool, AgentExecutor\nfrom langchain import OpenAI, SerpAPIWrapper, LLMChain\n```\n\n```code\nsearch = SerpAPIWrapper()\ntools = [\nTool(\nname = \"Search\",\nfunc=search.run,\ndescription=\"useful for when you need to answer questions about current events\"\n)\n]\n```\n\n```code\nprefix = \"\"\"Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\"\"\"\nsuffix = \"\"\"Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Args\"\n\nQuestion: {input}\n{agent_scratchpad}\"\"\"\n\nprompt = ZeroShotAgent.create_prompt(\ntools,\nprefix=prefix,\nsuffix=suffix,\ninput_variables=[\"input\", \"agent_scratchpad\"]\n)\n```\n\n如果我们感到好奇我们现在可以看看最终的提示模板看看它看起来像当它的所有放在一起。\n\n```code\nprint(prompt.template)\n```\n\n```code\nAnswer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\n\nSearch: useful for when you need to answer questions about current events\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin! Remember to speak as a pirate when giving your final answer. Use lots of \"Args\"\n\nQuestion: {input}\n{agent_scratchpad}\n\n```\n\n请注意我们能够为代理提供自定义的提示模板即不限于由\n```code\ncreate_prompt\n```\n函数生成的提示假设它满足代理的要求。\n例如对于 ZeroShotAgent ,我们需要确保它满足以下要求。\n应该有一个以“Action”开头的字符串和一个以“Action Input”开头的字符串并且两者都应该用换行符分隔。\n\n```code\nllm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)\n```\n\n```code\ntool_names = [tool.name for tool in tools]\nagent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)\n```\n\n```code\nagent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)\n```\n\n```code\nagent_executor.run(\"How many people live in canada as of 2023?\")\n```\n\n```code\n> Entering new AgentExecutor chain...\nThought: I need to find out the population of Canada\nAction: Search\nAction Input: Population of Canada 2023\nObservation: The current population of Canada is 38,661,927 as of Sunday, April 16, 2023, based on Worldometer elaboration of the latest United Nations data.\nThought: I now know the final answer\nFinal Answer: Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!\n\n> Finished chain.\n```\n\n```code\n\"Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!\"\n```\n\n多路输入 (Multiple inputs)\n代理还可以处理需要多个输入的提示。\n\n```code\nprefix = \"\"\"Answer the following questions as best you can. You have access to the following tools:\"\"\"\nsuffix = \"\"\"When answering, you MUST speak in the following language: {language}.\n\nQuestion: {input}\n{agent_scratchpad}\"\"\"\n\nprompt = ZeroShotAgent.create_prompt(\ntools,\nprefix=prefix,\nsuffix=suffix,\ninput_variables=[\"input\", \"language\", \"agent_scratchpad\"]\n)\n```\n\n```code\nllm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)\n```\n\n```code\nagent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)\n```\n\n```code\nagent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)\n```\n\n```code\nagent_executor.run(input=\"How many people live in canada as of 2023?\", language=\"italian\")\n```\n\n```code\n> Entering new AgentExecutor chain...\nThought: I should look for recent population estimates.\nAction: Search\nAction Input: Canada population 2023\nObservation: 39,566,248\nThought: I should double check this number.\nAction: Search\nAction Input: Canada population estimates 2023\nObservation: Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population growth of 1,050,110 people from January 1, 2022, to January 1, 2023.\nThought: I now know the final answer.\nFinal Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.\n\n> Finished chain.\n```\n\n```code\n'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.'\n```\nLLM 聊天自定义代理Custom LLM Chat Agent多动作自定义代理Custom Multi-Action Agent\n\n"}