langchain agent

这篇具有很好参考价值的文章主要介绍了langchain agent。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

 zero-shot-react-description

代码

from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from langchain.tools import BaseTool
import os
os.environ['OPENAI_API_KEY']="sk-xxx"

# 搜索工具
class SearchTool(BaseTool):
    name = "Search"
    description = "如果我想知道天气,'鸡你太美'这两个问题时,请使用它"
    return_direct = True  # 直接返回结果

    def _run(self, query: str) -> str:
        print("\nSearchTool query: " + query)
        return "这个是一个通用的返回"

    async def _arun(self, query: str) -> str:
        raise NotImplementedError("暂时不支持异步")


# 计算工具
class CalculatorTool(BaseTool):
    name = "Calculator"
    description = "如果是关于数学计算的问题,请使用它"

    def _run(self, query: str) -> str:
        print("\nCalculatorTool query: " + query)
        return "100"

    async def _arun(self, query: str) -> str:
        raise NotImplementedError("暂时不支持异步")


llm = OpenAI(temperature=0.5)
tools = [SearchTool(), CalculatorTool()]
agent = initialize_agent(
    tools, llm, agent="zero-shot-react-description", verbose=True)

print("问题:")
print("答案:" + agent.run("查询这周天气"))
print("问题:")
print("答案:" + agent.run("告诉我'鸡你太美'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我'hello world'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我10的3次方是多少?"))

 以上代码构造如下prompt

Answer the following questions as best you can. You have access to the following tools:

Search: 如果我想知道天气,'鸡你太美'这两个问题时,请使用它
Calculator: 如果是关于数学计算的问题,请使用它

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search, Calculator]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: 查询这周天气
Thought:

prompt模板:

PREFIX = """Answer the following questions as best you can. You have access to the following tools:"""
FORMAT_INSTRUCTIONS = """Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
SUFFIX = """Begin!

Question: {input}
Thought:{agent_scratchpad}"""

示例二

代码

import os
os.environ['SERPAPI_API_KEY']="xxx"

from langchain.agents import Tool
from langchain.agents import AgentType
from langchain.memory import ConversationBufferMemory
from langchain import OpenAI
from langchain.utilities import SerpAPIWrapper
from langchain.agents import initialize_agent
import os
os.environ['OPENAI_API_KEY']="sk-xxx"
search = SerpAPIWrapper()
tools = [
    Tool(
        name = "Current Search",
        func=search.run,
        description="useful for when you need to answer questions about current events or the current state of the world"
    ),
]

memory = ConversationBufferMemory(memory_key="chat_history")

llm=OpenAI(temperature=0)
agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)
agent_chain.run(input="hi, i am bob")
agent_chain.run(input="what's my name?")
agent_chain.run("what are some good dinners to make this week, if i like thai food?")
agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?")
agent_chain.run(input="whats the current temperature in pomfret?")

以上代码使用如下的prompt

Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.

TOOLS:
------

Assistant has access to the following tools:

> Current Search: useful for when you need to answer questions about current events or the current state of the world

To use a tool, please use the following format:

```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [Current Search]
Action Input: the input to the action
Observation: the result of the action
```

When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:

```
Thought: Do I need to use a tool? No
AI: [your response here]
```

Begin!

Previous conversation history:
Human: hi, i am bob
AI: Hi Bob, nice to meet you! How can I help you today?
Human: what's my name?
AI: Your name is Bob!

New input: what are some good dinners to make this week, if i like thai food?

prompt 模板:

# flake8: noqa
PREFIX = """Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.

TOOLS:
------

Assistant has access to the following tools:"""
FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:

```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```

When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:

```
Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
```"""

SUFFIX = """Begin!

Previous conversation history:
{chat_history}

New input: {input}
{agent_scratchpad}"""

llm_math_chain

每一步action,可以是另外一个chain,

代码示例:

# Import things that are needed generically
import os
os.environ['SERPAPI_API_KEY']="111xxxx"
os.environ['OPENAI_API_KEY']="sk-xxxxxx"
from langchain import LLMMathChain, SerpAPIWrapper
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, tool
from pydantic import BaseModel, Field
llm = ChatOpenAI(temperature=0)


# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)

from typing import Optional, Type

from langchain.callbacks.manager import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)


class CustomSearchTool(BaseTool):
    name = "custom_search"
    description = "useful for when you need to answer questions about current events"

    def _run(
        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> str:
        """Use the tool."""
        return search.run(query)

    async def _arun(
        self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
    ) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("custom_search does not support async")



class CalculatorInput(BaseModel):
    question: str = Field()

class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "useful for when you need to answer questions about math"
    args_schema: Type[BaseModel] = CalculatorInput

    def _run(
        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> str:
        """Use the tool."""
        return llm_math_chain.run(query)

    async def _arun(
        self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
    ) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("Calculator does not support async")
tools = [CustomSearchTool(), CustomCalculatorTool()]
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

agent.run(
    "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)

prompt

Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question.

Question: ${Question with math problem.}
```text
${single line mathematical expression that solves the problem}
```
...numexpr.evaluate(text)...
```output
${Output of running the code}
```
Answer: ${Answer}

Begin.

Question: What is 37593 * 67?
```text
37593 * 67
```
...numexpr.evaluate("37593 * 67")...
```output
2518731
```
Answer: 2518731

Question: 37593^(1/5)
```text
37593**(1/5)
```
...numexpr.evaluate("37593**(1/5)")...
```output
8.222831614237718
```
Answer: 8.222831614237718

Question: 19 ^ 0.43

prompt模板:

 """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question.

Question: ${{Question with math problem.}}
```text
${{single line mathematical expression that solves the problem}}
```
...numexpr.evaluate(text)...
```output
${{Output of running the code}}
```
Answer: ${{Answer}}

Begin.

Question: What is 37593 * 67?
```text
37593 * 67
```
...numexpr.evaluate("37593 * 67")...
```output
2518731
```
Answer: 2518731

Question: 37593^(1/5)
```text
37593**(1/5)
```
...numexpr.evaluate("37593**(1/5)")...
```output
8.222831614237718
```
Answer: 8.222831614237718

Question: {question}
"""

STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION

核心思想:工具如果需要多种输入,也需要将参数一起构建进prompt当中

代码示例

import os
os.environ['SERPAPI_API_KEY']="23123"
os.environ['OPENAI_API_KEY']="sk-232323"
os.environ["LANGCHAIN_TRACING"] = "true"
from langchain import OpenAI
from langchain.agents import initialize_agent, AgentType

llm = OpenAI(temperature=0)
from langchain.tools import StructuredTool


def multiplier(a: float, b: float) -> float:
    """Multiply the provided floats."""
    return a * b


tool = StructuredTool.from_function(multiplier)
# Structured tools are compatible with the STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION agent type.
agent_executor = initialize_agent(
    [tool],
    llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)

agent_executor.run("What is 3 times 4")

prompt文章来源地址https://www.toymoban.com/news/detail-686246.html

System: Respond to the human as helpfully and accurately as possible. You have access to the following tools:

multiplier: multiplier(a: float, b: float) -> float - Multiply the provided floats., args: {{'a': {{'title': 'A', 'type': 'number'}}, 'b': {{'title': 'B', 'type': 'number'}}}}

Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).

Valid "action" values: "Final Answer" or multiplier

Provide only ONE action per $JSON_BLOB, as shown:

```
{
  "action": $TOOL_NAME,
  "action_input": $INPUT
}
```

Follow this format:

Question: input question to answer
Thought: consider previous and subsequent steps
Action:
```
$JSON_BLOB
```
Observation: action result
... (repeat Thought/Action/Observation N times)
Thought: I know what to respond
Action:
```
{
  "action": "Final Answer",
  "action_input": "Final response to human"
}
```

Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.
Thought:
Human: What is 3 times 4

This was your previous work (but I haven't seen any of it! I only see what you return as final answer):
Action:
```
{
  "action": "multiplier",
  "action_input": {"a": 3, "b": 4}
}
```


Observation: 12.0
Thought:

到了这里,关于langchain agent的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • LangChain Agent 执行过程解析 OpenAI

    简单来说,用户像LangChain输入的内容未知。此时可以有一套工具集合(也可以自定义工具),将这套自定义工具托管给LLM,让其自己决定使用工具中的某一个(如果存在的话) 首先,这里自定义了两个简单的工具 接下来是针对于工具的简单调用:注意,这里使用OpenAI temperature=0 需要

    2023年04月24日
    浏览(22)
  • 【Langchain Agent研究】SalesGPT项目介绍(五)

    【Langchain Agent研究】SalesGPT项目介绍(四)-CSDN博客                 上节课,我们分析了一下salesGPT项目里源代码的一些问题,重新写了一个运行方法,换了一个模型并修改了一些源代码开始把项目跑起来了,我们已经可以通过console和模型进行对话了。         我们

    2024年02月19日
    浏览(22)
  • 【Langchain Agent研究】SalesGPT项目介绍(四)

    【Langchain Agent研究】SalesGPT项目介绍(三)-CSDN博客   github地址:GitHub - jerry1900/SalesGPT: Context-aware AI Sales Agent to automate sales outreach.               上节课,我们主要介绍了SalesGPT的类属性和它最重要的类方法from_llm()。因为SalesGPT没有构造器方法,所以类方法from_llm()方法就

    2024年02月21日
    浏览(38)
  • 让AI做决策,学会langChain的Agent

    今天内容涉及如下: 1.initialize_agent,:执行gent工作,并把工具Tool传入 2.Tool:选取行为函数工具类 之前我们学习的都是把问题给AI,让AI模型给出答案,那么这种情况下应该怎么处理呢,我需要根据不同的问题选择不同的答案,比如我问AI我想选择一件衣服就去调用挑选衣服的

    2024年01月18日
    浏览(33)
  • LangChain Agents深入剖析及源码解密上(一)

    LangChain Agents深入剖析及源码解密上(一) LangChain Agents深入剖析及源码解密上 Agent工作原理详解 本节会结合AutoGPT的案例,讲解LangChain代理(Agent)为核心的内容。我们前面已经谈了代理本身的很多内容,也看了绝大部分的源代码,例如:ReAct的源代码,还有mrkl的源代码,如图

    2024年02月15日
    浏览(28)
  • LangChain Agents深入剖析及源码解密上(三)

    AutoGPT案例V1版本 AutoGPT是一个实验性的开源应用程序,展示了GPT-4语言模型的功能,AutoGPT程序由GPT-4驱动,将大语言模型的思考链接在一起,以自主实现设定的任何目标。作为GPT-4完全自主运行的首批例子之一,AutoGPT突破了人工智能的可能性。LangChain框架复现了https://github.co

    2024年02月15日
    浏览(38)
  • 【AI大模型应用开发】【LangChain系列】5. 实战LangChain的智能体Agents模块

    大家好,我是【同学小张】。持续学习,持续干货输出,关注我,跟我一起学AI大模型技能。 在我前面的MetaGPT系列文章中,已经对智能体有了一个认知,重温一下: 智能体 = LLM+观察+思考+行动+记忆 将大语言模型作为一个推理引擎。给定一个任务,智能体自动生成完成任务所

    2024年03月09日
    浏览(48)
  • 怎么和Bing一样使用ChatGPT?如何让ChapGPT与外界世界交互结合?LangChain Agent模块帮你解决问题。LangChain Agent模块的使用案例和源码详解

    ChatGPT很火,但是对于这个模型我们怎么用呢?只是和他聊聊天,回答回答问题? 如何基于这个模型进行二次开发呢?是否可以和new bing一样,可以搜索资料然后进行回复?甚至可以按照你的指令帮你操作机器人? LangChain的 Agent模块就可以帮大家做到这些,而Agent是如何使用

    2023年04月14日
    浏览(49)
  • LangChain大型语言模型(LLM)应用开发(六):Agents

    LangChain是一个基于大语言模型(如ChatGPT)用于构建端到端语言模型应用的 Python 框架。它提供了一套工具、组件和接口,可简化创建由大型语言模型 (LLM) 和聊天模型提供支持的应用程序的过程。LangChain 可以轻松管理与语言模型的交互,将多个组件链接在一起,以便在不同的

    2024年02月16日
    浏览(34)
  • LangChain-Agent自定义Tools类 ——基础篇(一)

    其他友情链接: 为 LLM 代理构建自定义工具 |松果 (pinecone.io) Create Custom Tools for Chatbots in LangChain — LangChain #8 - YouTube //油管这个小哥讲的比较好  Tools怎么使用?可以定义自己的tool么? - General - LangChain中文社区

    2024年02月11日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包