langchain agent

文章展示了如何利用StructuredTool和OpenAI构建一个结构化的聊天系统,实现在零指令下处理问题和数学计算,通过JSON格式调用工具进行响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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

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 的概述 LangChain 是一种用于构建基于大型语言模型的应用程序的框架,而其中的核心组件之一就是 **Agent**。Agent 能够根据输入的任务动态调用不同的工具集,并通过迭代的方式完成复杂任务[^1]。 #### 什么是 LangChain AgentLangChain 中的 Agent 是指能够自主决策并执行操作的一种机制。它可以根据用户的请求自动选择合适的工具(Tools),并通过多次交互逐步解决问题。这种能力使得 Agent 成为了处理多步推理和复杂查询的理想解决方案[^3]。 --- ### LangChain Agent 的工作原理 Agent 的核心功能在于其能够解析用户输入、选择适当的工具以及生成最终响应。以下是它的主要流程: 1. 用户提供自然语言指令。 2. Agent 解析该指令并将其转化为可执行的操作序列。 3. 基于这些操作,Agent 动态调用预定义的一组工具(如搜索引擎、数据库接口或其他外部服务)。 4. 工具返回的结果被反馈到 Agent,后者会继续优化后续动作直至目标达成[^5]。 例如,在 OpenAI 提供的支持函数调用的功能中,默认提示可以通过如下方式加载: ```python from langchain.agents import load_tools, initialize_agent from langchain.llms import OpenAI llm = OpenAI(temperature=0) tools = load_tools(["serpapi", "llm-math"], llm=llm) agent_chain = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) ``` 上述代码片段展示了如何初始化一个简单的零样本反应描述型代理 (Zero-Shot React Description),此类型的代理无需任何训练即可运行[^2]。 --- ### 示例代码:创建自定义 LangChain Agent 下面是一个完整的例子,演示了如何利用 SerpAPI 和 LLM 数学计算工具来解决涉及网络搜索与算术运算的问题。 ```python import os from langchain.agents import Tool, initialize_agent, AgentType from langchain.tools import BaseTool from langchain.utilities import SerpAPIWrapper from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.llms import OpenAI class CustomSearchTool(BaseTool): name = "custom_search" description = "A tool that uses a custom search engine to find information." def _run(self, query: str) -> str: serp_api_key = os.getenv('SERP_API_KEY') search = SerpAPIWrapper(serpapi_api_key=serp_api_key) result = search.run(query) return f"Searched for {query}. Found: {result}" async def _arun(self, query: str) -> str: raise NotImplementedError() # 初始化LLM实例 llm = OpenAI(model_name="text-davinci-003") # 加载工具 search_tool = CustomSearchTool() tools = [ Tool( name=search_tool.name, func=search_tool._run, description=search_tool.description ) ] # 设置Prompt模板 prompt_template = """Use the following pieces of context to answer the question at the end. {context} Question: {question} Answer:""" prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) # 构建链式结构 chain = LLMChain(llm=llm, prompt=prompt) # 初始化Agent agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) # 测试Agent response = agent.run("What is the capital city of France and what's its population?") print(response) ``` 在这个脚本里,我们首先定义了一个名为 `CustomSearchTool` 的类继承自 `BaseTool` 接口;接着配置好所需的参数之后便可以轻松实现跨平台数据抓取等功能[^4]。 --- ### 总结 综上所述,LangChain Agents 不仅提供了强大的灵活性还简化了许多繁琐的手动编码环节,让开发者得以专注于业务逻辑本身而非底层细节。无论是初学者还是资深工程师都能从中受益匪浅。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值