【可能是全网最丝滑的LangChain教程】十九、LangChain进阶之Agents

news2024/9/17 7:45:29

幸福,不是长生不老,不是大鱼大肉,不是权倾朝野。幸福是每一个微小的生活愿望达成。当你想吃的时候有得吃,想被爱的时候有人来爱你。

01 Agent介绍

在LangChain中,Agent 是一个核心概念,它代表了一种能够利用语言模型(LLM)和其他工具来执行复杂任务的系统。Agent的设计目的是为了处理那些简单的语言模型可能无法直接解决的问题,尤其是当这些任务涉及到多个步骤或者需要外部数据源的情况。

  • Agent 在LangChain中扮演着一个协调者和决策者的角色,它能够根据给定的任务和目标,决定使用哪些工具以及如何组合这些工具来达到目的。

  • Agent会根据输入的指令和上下文信息,调用不同的工具(如搜索引擎、数据库查询、API调用等)来获取所需的信息,并将这些信息整合起来形成最终的响应。

Agent(代理)的核心思想是使用语言模型来选择要执行的一系列操作。

在Chain(链)中,一系列操作被硬编码在代码中。在Agent(代理)中,语言模型用作推理引擎,以确定要执行哪些操作以及按什么顺序执行。

Agent的工作流程

  • 输入理解:Agent首先解析用户输入,理解其意图和需求。
  • 计划制定:基于对输入的理解,Agent会制定一个执行计划,决定使用哪些工具和执行的顺序。
  • 工具调用:Agent按照计划调用相应的工具,执行必要的操作。
  • 结果整合:收集所有工具返回的结果,进行整合和解析,形成最终的输出。
  • 反馈循环:如果任务没有完成或者需要进一步的信息,Agent可以迭代上述过程直到满足条件为止。

Agent的组成部分

  • Tools:Agent可以访问的工具集,每个工具通常执行一个特定的功能。
  • Executor:执行Agent计划的逻辑。
  • Prompt Templates:指导Agent如何理解和处理输入的模板,可以定制化以适应不同任务。

创建Agent的步骤

  • 定义工具:选择或创建适合任务的工具。
  • 初始化执行器:设置执行器,这通常涉及选择一个语言模型。
  • 设置提示词:编写或选择适当的prompt模板,帮助Agent理解任务。
  • 配置Agent:将工具、执行器和提示词组合成一个Agent实例。

02 基本使用

我们这里就简单点,问下“美国现任总统是谁?”。

  • 首先,确定我们要使用的tool。这里我们使用Wikipedia,这也是LangChain内置的一个tool,用起来比较方便~
  • 其次,我们要定义好我们的提示词。一般情况下有两种方式:一种是我们自己定义提示词,告诉模型我们有哪些tool,每个tool的具体使用场景,以及你模型要做些什么(说句心里话,稍微有点复杂);另一种方式是使用langchainhub内置的一些提示词(说句实在话,好用)。
  • 然后我们创建代理Agent。这里一般情况下我们都会使用内置的创建方法,当然,你说你想自己自定义创建Agent行不行?行是肯定行的,但是不建议且没必要!说真的,我都不知道你想骚点啥~
  • 最后,我们需要创建AgentExecutor来执行整个agent的逻辑得到最终结果。

具体代码如下:

from langchain_community.agent_toolkits.load_tools import load_tools
from langchain.agents import create_react_agent, AgentExecutor
from langchain import hub

# wikipedia
tools = load_tools(['wikipedia'])
# prompt = hub.pull("hwchase17/react")
prompt = hub.pull("hwchase17/react-chat")
agent = create_react_agent(llm_model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input":"美国现任总统是谁?","chat_history":[]})

执行流程日志如下:

[chain/start] [chain:AgentExecutor] Entering Chain run with input:
{
  "input": "美国现任总统是谁?"
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad>] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad>] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad> > chain:RunnableLambda] Entering Chain run with input:
{
  "input": ""
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad> > chain:RunnableLambda] [0ms] Exiting Chain run with output:
{
  "output": ""
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad>] [1ms] Exiting Chain run with output:
{
  "agent_scratchpad": ""
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad>] [3ms] Exiting Chain run with output:
{
  "input": "美国现任总统是谁?",
  "intermediate_steps": [],
  "agent_scratchpad": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > prompt:PromptTemplate] Entering Prompt run with input:
{
  "input": "美国现任总统是谁?",
  "intermediate_steps": [],
  "agent_scratchpad": ""
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > prompt:PromptTemplate] [2ms] Exiting Prompt run with output:
[outputs]
[llm/start] [chain:AgentExecutor > chain:RunnableSequence > llm:Tongyi] Entering LLM run with input:
{
  "prompts": [
    "Answer the following questions as best you can. You have access to the following tools:\n\nwikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\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 [wikipedia]\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!\n\nQuestion: 美国现任总统是谁?\nThought:"
  ]
}
[llm/end] [chain:AgentExecutor > chain:RunnableSequence > llm:Tongyi] [1.60s] Exiting LLM run with output:
{
  "generations": [
    [
      {
        "text": "I need to find out who the current president of the United States is.\nAction: wikipedia\nAction Input: President of the United States\n",
        "generation_info": {
          "finish_reason": "stop",
          "request_id": "33fa1726-1736-98d9-8aef-fa45c1ba0007",
          "token_usage": {
            "input_tokens": 175,
            "output_tokens": 28,
            "total_tokens": 203
          }
        },
        "type": "Generation"
      }
    ]
  ],
  "llm_output": null,
  "run": null
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > parser:ReActSingleInputOutputParser] Entering Parser run with input:
{
  "input": "I need to find out who the current president of the United States is.\nAction: wikipedia\nAction Input: President of the United States\n"
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > parser:ReActSingleInputOutputParser] [0ms] Exiting Parser run with output:
[outputs]
[chain/end] [chain:AgentExecutor > chain:RunnableSequence] [1.61s] Exiting Chain run with output:
[outputs]
[tool/start] [chain:AgentExecutor > tool:wikipedia] Entering Tool run with input:
"President of the United States"
[tool/end] [chain:AgentExecutor > tool:wikipedia] [11.90s] Exiting Tool run with output:
"Page: President of the United States
Summary: The president of the United States (POTUS) is the head of state/head of government of the United States of America. The president directs the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces.
The power of the presidency has grown substantially since the first president, George Washington, took office in 1789. While presidential power has ebbed and flowed over time, the presidency has played an increasingly significant role in American political life since the beginning of the 20th century, carrying over into the 21st century with notable expansions during the presidencies of Franklin D. Roosevelt and George W. Bush. In modern times, the president is one of the world's most powerful political figures and the leader of the world's only remaining superpower. As the leader of the nation with the largest economy by nominal GDP, the president possesses significant domestic and international hard and soft power. For much of the 20th century, especially during the Cold War, the U.S. president was often called "the leader of the free world".
Article II of the Constitution establishes the executive branch of the federal government and vests executive power in the president. The power includes the execution and enforcement of federal law and the responsibility to appoint federal executive, diplomatic, regulatory, and judicial officers.  Based on constitutional provisions empowering the president to appoint and receive ambassadors and conclude treaties with foreign powers, and on subsequent laws enacted by Congress, the modern presidency has primary responsibility for conducting U.S. foreign policy. The role includes responsibility for directing the world's most expensive military, which has the second-largest nuclear arsenal.
The president also plays a leading role in federal legislation and domestic policymaking. As part of the system of separation of powers, Article I, Section 7 of the Constitution gives the president the power to sign or veto federal legislation. Since modern presidents are typically viewed as leaders of their political parties, major policymaking is significantly shaped by the outcome of presidential elections, with presidents taking an active role in promoting their policy priorities to members of Congress who are often electorally dependent on the president. In recent decades, presidents have also made increasing use of executive orders, agency regulations, and judicial appointments to shape domestic policy.
The president is elected indirectly through the Electoral College to a four-year term, along with the vice president. Under the Twenty-second Amendment, ratified in 1951, no person who has been elected to two presidential terms may be elected to a third. In addition, nine vice presidents have become president by virtue of a president's intra-term death or resignation. In all, 45 individuals have served 46 presidencies spanning 58 four-year terms. Joe Biden is the 46th and current president, having assumed office on January 20, 2021.

Page: List of presidents of the United States
Summary: The president of the United States is the head of state and head of government of the United States, indirectly elected to a four-year term via the Electoral College. The officeholder leads the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces. Since the office was established in 1789, 45 men have served in 46 presidencies. The first president, George Washington, won a unanimous vote of the Electoral College. Grover Cleveland served two non-consecutive terms and is therefore counted as the 22nd and 24th president of the United States, giving rise to the discrepancy between the number of presidencies and the number of individuals who have served as president.
The presidency of William Henry Harrison, who died 31 days after taking office in 1841, was the shortest in Ameri"
[chain/start] [chain:AgentExecutor > chain:RunnableSequence] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad>] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad>] Entering Chain run with input:
{
  "input": ""
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad> > chain:RunnableLambda] Entering Chain run with input:
{
  "input": ""
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad> > chain:RunnableLambda] [0ms] Exiting Chain run with output:
{
  "output": "I need to find out who the current president of the United States is.\nAction: wikipedia\nAction Input: President of the United States\n\nObservation: Page: President of the United States\nSummary: The president of the United States (POTUS) is the head of state/head of government of the United States of America. The president directs the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces.\nThe power of the presidency has grown substantially since the first president, George Washington, took office in 1789. While presidential power has ebbed and flowed over time, the presidency has played an increasingly significant role in American political life since the beginning of the 20th century, carrying over into the 21st century with notable expansions during the presidencies of Franklin D. Roosevelt and George W. Bush. In modern times, the president is one of the world's most powerful political figures and the leader of the world's only remaining superpower. As the leader of the nation with the largest economy by nominal GDP, the president possesses significant domestic and international hard and soft power. For much of the 20th century, especially during the Cold War, the U.S. president was often called "the leader of the free world".\nArticle II of the Constitution establishes the executive branch of the federal government and vests executive power in the president. The power includes the execution and enforcement of federal law and the responsibility to appoint federal executive, diplomatic, regulatory, and judicial officers.  Based on constitutional provisions empowering the president to appoint and receive ambassadors and conclude treaties with foreign powers, and on subsequent laws enacted by Congress, the modern presidency has primary responsibility for conducting U.S. foreign policy. The role includes responsibility for directing the world's most expensive military, which has the second-largest nuclear arsenal.\nThe president also plays a leading role in federal legislation and domestic policymaking. As part of the system of separation of powers, Article I, Section 7 of the Constitution gives the president the power to sign or veto federal legislation. Since modern presidents are typically viewed as leaders of their political parties, major policymaking is significantly shaped by the outcome of presidential elections, with presidents taking an active role in promoting their policy priorities to members of Congress who are often electorally dependent on the president. In recent decades, presidents have also made increasing use of executive orders, agency regulations, and judicial appointments to shape domestic policy.\nThe president is elected indirectly through the Electoral College to a four-year term, along with the vice president. Under the Twenty-second Amendment, ratified in 1951, no person who has been elected to two presidential terms may be elected to a third. In addition, nine vice presidents have become president by virtue of a president's intra-term death or resignation. In all, 45 individuals have served 46 presidencies spanning 58 four-year terms. Joe Biden is the 46th and current president, having assumed office on January 20, 2021.\n\nPage: List of presidents of the United States\nSummary: The president of the United States is the head of state and head of government of the United States, indirectly elected to a four-year term via the Electoral College. The officeholder leads the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces. Since the office was established in 1789, 45 men have served in 46 presidencies. The first president, George Washington, won a unanimous vote of the Electoral College. Grover Cleveland served two non-consecutive terms and is therefore counted as the 22nd and 24th president of the United States, giving rise to the discrepancy between the number of presidencies and the number of individuals who have served as president.\nThe presidency of William Henry Harrison, who died 31 days after taking office in 1841, was the shortest in Ameri\nThought: "
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad> > chain:RunnableParallel<agent_scratchpad>] [2ms] Exiting Chain run with output:
{
  "agent_scratchpad": "I need to find out who the current president of the United States is.\nAction: wikipedia\nAction Input: President of the United States\n\nObservation: Page: President of the United States\nSummary: The president of the United States (POTUS) is the head of state/head of government of the United States of America. The president directs the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces.\nThe power of the presidency has grown substantially since the first president, George Washington, took office in 1789. While presidential power has ebbed and flowed over time, the presidency has played an increasingly significant role in American political life since the beginning of the 20th century, carrying over into the 21st century with notable expansions during the presidencies of Franklin D. Roosevelt and George W. Bush. In modern times, the president is one of the world's most powerful political figures and the leader of the world's only remaining superpower. As the leader of the nation with the largest economy by nominal GDP, the president possesses significant domestic and international hard and soft power. For much of the 20th century, especially during the Cold War, the U.S. president was often called "the leader of the free world".\nArticle II of the Constitution establishes the executive branch of the federal government and vests executive power in the president. The power includes the execution and enforcement of federal law and the responsibility to appoint federal executive, diplomatic, regulatory, and judicial officers.  Based on constitutional provisions empowering the president to appoint and receive ambassadors and conclude treaties with foreign powers, and on subsequent laws enacted by Congress, the modern presidency has primary responsibility for conducting U.S. foreign policy. The role includes responsibility for directing the world's most expensive military, which has the second-largest nuclear arsenal.\nThe president also plays a leading role in federal legislation and domestic policymaking. As part of the system of separation of powers, Article I, Section 7 of the Constitution gives the president the power to sign or veto federal legislation. Since modern presidents are typically viewed as leaders of their political parties, major policymaking is significantly shaped by the outcome of presidential elections, with presidents taking an active role in promoting their policy priorities to members of Congress who are often electorally dependent on the president. In recent decades, presidents have also made increasing use of executive orders, agency regulations, and judicial appointments to shape domestic policy.\nThe president is elected indirectly through the Electoral College to a four-year term, along with the vice president. Under the Twenty-second Amendment, ratified in 1951, no person who has been elected to two presidential terms may be elected to a third. In addition, nine vice presidents have become president by virtue of a president's intra-term death or resignation. In all, 45 individuals have served 46 presidencies spanning 58 four-year terms. Joe Biden is the 46th and current president, having assumed office on January 20, 2021.\n\nPage: List of presidents of the United States\nSummary: The president of the United States is the head of state and head of government of the United States, indirectly elected to a four-year term via the Electoral College. The officeholder leads the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces. Since the office was established in 1789, 45 men have served in 46 presidencies. The first president, George Washington, won a unanimous vote of the Electoral College. Grover Cleveland served two non-consecutive terms and is therefore counted as the 22nd and 24th president of the United States, giving rise to the discrepancy between the number of presidencies and the number of individuals who have served as president.\nThe presidency of William Henry Harrison, who died 31 days after taking office in 1841, was the shortest in Ameri\nThought: "
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > chain:RunnableAssign<agent_scratchpad>] [5ms] Exiting Chain run with output:
[outputs]
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > prompt:PromptTemplate] Entering Prompt run with input:
[inputs]
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > prompt:PromptTemplate] [0ms] Exiting Prompt run with output:
[outputs]
[llm/start] [chain:AgentExecutor > chain:RunnableSequence > llm:Tongyi] Entering LLM run with input:
{
  "prompts": [
    "Answer the following questions as best you can. You have access to the following tools:\n\nwikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\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 [wikipedia]\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!\n\nQuestion: 美国现任总统是谁?\nThought:I need to find out who the current president of the United States is.\nAction: wikipedia\nAction Input: President of the United States\n\nObservation: Page: President of the United States\nSummary: The president of the United States (POTUS) is the head of state/head of government of the United States of America. The president directs the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces.\nThe power of the presidency has grown substantially since the first president, George Washington, took office in 1789. While presidential power has ebbed and flowed over time, the presidency has played an increasingly significant role in American political life since the beginning of the 20th century, carrying over into the 21st century with notable expansions during the presidencies of Franklin D. Roosevelt and George W. Bush. In modern times, the president is one of the world's most powerful political figures and the leader of the world's only remaining superpower. As the leader of the nation with the largest economy by nominal GDP, the president possesses significant domestic and international hard and soft power. For much of the 20th century, especially during the Cold War, the U.S. president was often called "the leader of the free world".\nArticle II of the Constitution establishes the executive branch of the federal government and vests executive power in the president. The power includes the execution and enforcement of federal law and the responsibility to appoint federal executive, diplomatic, regulatory, and judicial officers.  Based on constitutional provisions empowering the president to appoint and receive ambassadors and conclude treaties with foreign powers, and on subsequent laws enacted by Congress, the modern presidency has primary responsibility for conducting U.S. foreign policy. The role includes responsibility for directing the world's most expensive military, which has the second-largest nuclear arsenal.\nThe president also plays a leading role in federal legislation and domestic policymaking. As part of the system of separation of powers, Article I, Section 7 of the Constitution gives the president the power to sign or veto federal legislation. Since modern presidents are typically viewed as leaders of their political parties, major policymaking is significantly shaped by the outcome of presidential elections, with presidents taking an active role in promoting their policy priorities to members of Congress who are often electorally dependent on the president. In recent decades, presidents have also made increasing use of executive orders, agency regulations, and judicial appointments to shape domestic policy.\nThe president is elected indirectly through the Electoral College to a four-year term, along with the vice president. Under the Twenty-second Amendment, ratified in 1951, no person who has been elected to two presidential terms may be elected to a third. In addition, nine vice presidents have become president by virtue of a president's intra-term death or resignation. In all, 45 individuals have served 46 presidencies spanning 58 four-year terms. Joe Biden is the 46th and current president, having assumed office on January 20, 2021.\n\nPage: List of presidents of the United States\nSummary: The president of the United States is the head of state and head of government of the United States, indirectly elected to a four-year term via the Electoral College. The officeholder leads the executive branch of the federal government and is the commander-in-chief of the United States Armed Forces. Since the office was established in 1789, 45 men have served in 46 presidencies. The first president, George Washington, won a unanimous vote of the Electoral College. Grover Cleveland served two non-consecutive terms and is therefore counted as the 22nd and 24th president of the United States, giving rise to the discrepancy between the number of presidencies and the number of individuals who have served as president.\nThe presidency of William Henry Harrison, who died 31 days after taking office in 1841, was the shortest in Ameri\nThought:"
  ]
}
[llm/end] [chain:AgentExecutor > chain:RunnableSequence > llm:Tongyi] [3.25s] Exiting LLM run with output:
{
  "generations": [
    [
      {
        "text": "I now know the final answer\nFinal Answer: 美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就职,成为美国第46任总统。",
        "generation_info": {
          "finish_reason": "stop",
          "request_id": "5748aabc-67e8-9d4b-b639-ca9c253f21db",
          "token_usage": {
            "input_tokens": 988,
            "output_tokens": 47,
            "total_tokens": 1035
          }
        },
        "type": "Generation"
      }
    ]
  ],
  "llm_output": null,
  "run": null
}
[chain/start] [chain:AgentExecutor > chain:RunnableSequence > parser:ReActSingleInputOutputParser] Entering Parser run with input:
{
  "input": "I now know the final answer\nFinal Answer: 美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就职,成为美国第46任总统。"
}
[chain/end] [chain:AgentExecutor > chain:RunnableSequence > parser:ReActSingleInputOutputParser] [0ms] Exiting Parser run with output:
[outputs]
[chain/end] [chain:AgentExecutor > chain:RunnableSequence] [3.35s] Exiting Chain run with output:
[outputs]
[chain/end] [chain:AgentExecutor] [16.87s] Exiting Chain run with output:
{
  "output": "美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就职,成为美国第46任总统。"
}

{'input': '美国现任总统是谁?',
 'output': '美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就职,成为美国第46任总统。'}

通过以上简单的示例,我们就基本掌握了Agent的使用,是不是很简单~😁

但是这里有一些需要注意,这里的代理是无状态查询(没有记住以前的交互)。

Add in memoey

如前所述,此代理是无状态的。这意味着它不记得以前的交互。为了给它提供内存,我们需要传入之前的 chat_history。注意:由于我们正在使用的提示符,它需要调用 chat_history。如果我们使用不同的 prompt,我们可以更改变量名称。

from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

# 为了携带历史记录,我们需要修改使用的prompt,如下
# prompt = hub.pull("hwchase17/react-chat")

message_history = ChatMessageHistory()

agent_with_chat_history = RunnableWithMessageHistory(
    agent_executor,
    lambda session_id: message_history,
    input_messages_key="input",
    history_messages_key="chat_history",
)
agent_with_chat_history.invoke(
    {"input": "美国现任总统是谁?"},
    config={"configurable": {"session_id": "session-10086"}},
)
"""
{'input': '美国现任总统是谁?',
 'chat_history': [],
 'output': '美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就任美国第46任总统。'}
"""

下面进一步问一下“他在2022年做了哪些特别的事情?”,因为有对话记录,所以模型是知道这里的“”指的是谁。

agent_with_chat_history.invoke(
    {"input": "他在2022年做了哪些特别的事情?"},
    config={"configurable": {"session_id": "session-10086"}},
)
"""
{'input': '他在2022年做了哪些特别的事情?',
 'chat_history': [HumanMessage(content='美国现任总统是谁?'),
  AIMessage(content='美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就任美国第46任总统。')],
 'output': 'In 2022, President Joe Biden continued to address several significant issues. He signed the Inflation Reduction Act into law, which included aspects of the previously proposed Build Back Better Act. This legislation aimed to reduce the federal budget deficit, lower prescription drug prices, and invest in energy security and climate change mitigation. Additionally, in 2022, Biden appointed Ketanji Brown Jackson to the Supreme Court, making her the first Black woman to serve on the court. He also managed the ongoing response to the COVID-19 pandemic and dealt with international challenges, such as the Russian invasion of Ukraine, by imposing sanctions on Russia and providing support to Ukraine.'}
"""

这里特别说明下session_id,一轮对话的内容只存储在一个key/session_id上,所以这里的session_id可以随便写,但是记住别重复。

03 Agent Types

顾名思义,代理类型。意思就是哪些模型适合哪些代理,根据模型选择使用的代理~

Tool calling agent

工具调用代理。这是一种可以让模型检测何时需要调用工具并进行相应操作的技术。

通过 API 调用,模型能够智能地选择输出包含参数的结构化对象,以便调用这些工具。这种方法比使用通用文本完成或聊天 API 更为可靠。该代理可以重复调用工具并接收结果,直到查询得到解决。

LangChain 的 ToolCall 接口支持多种提供商实现,包括 OpenAI、Anthropic、Google、FireworksAI、MistralAI 和 TogetherAI 等。

哪些模型支持tool calling agent,如下图:

在这里插入图片描述

使用方式无区别,创建方式如下:

from langchain.agents import create_tool_calling_agent

create_tool_calling_agent(llm=xxx, tools=xxx, prompt=xxx)

OpenAI tools

较新的 OpenAI 模型能够识别何时需要调用函数,并能够输出用于调用这些函数的 JSON 对象。

这些模型被训练成能够调用单个函数的 “functions” 和能够调用多个函数的 “tools”。在 OpenAI 聊天 API 中,“functions” 已被视为遗留选项,被 “tools” 所取代。

开发者在创建代理时应该使用 OpenAI Tools 代理而非 OpenAI 函数代理。通过使用 “tools”,模型能够在适当的时候请求调用多个函数,这可能会显著减少代理实现其目标所需的时间。

使用方式无区别,创建方式如下:

from langchain.agents import create_openai_tools_agent

create_openai_tools_agent(llm=xxx, tools=xxx, prompt=xxx)

一句话,如果你正在使用openai的模型,那你就用OpenAI tools。

OpenAI functions

OpenAI API 已经弃用 functions,推荐使用 tools,以便在某些架构中减少响应时间。

OpenAI Function APIs 的目标是提供比通用文本补全或聊天 API 更可靠的函数调用。许多开源模型也采用了相同的函数调用格式,并且对模型进行了微调以检测函数调用的时机。

尽管 functions 被弃用,但它仍然与开源模型和采用它的提供者相关,且此代理应适用于此类模型。

使用方式无区别,创建方式如下:

from langchain.agents import create_openai_functions_agent

create_openai_functions_agent(llm=xxx, tools=xxx, prompt=xxx)

因为不少开源模型都采用和openai函数调用的格式,所以这里也提一嘴,万一有的同学使用的开源模型呢~

XML Agent

首先,XML Agent 的特点是,它_特别适合与常规的大型语言模型(LLMs)一起使用_,而不是聊天模型。

并且只适用于非结构化工具,即只接受单个字符串输入的工具。

使用方式无区别,创建方式如下:

from langchain.agents import create_xml_agent

create_xml_agent(llm=xxx, tools=xxx, prompt=xxx)

这里要注意的,XML Agent并不是处理XML文件或者XML数据,仅仅是因为一些语言模型(如 Anthropic 的 Claude)特别擅长推理/编写 XML。

JSON Chat Agent

JSON 聊天代理是为了更好地支持聊天模型而设计的,它能够通过 JSON 格式化输出,提供清晰的结构化数据。

使用方式无区别,创建方式如下:

from langchain.agents import create_json_chat_agent

create_json_chat_agent(llm=xxx, tools=xxx, prompt=xxx)

同理,JSON Chat Agent并不是处理JSON文件或者JSON数据的,仅仅是因为一些语言模型特别擅长编写 JSON。

Structured chat

在LangChain中,Structured Chat 是一种特定类型的代理(Agent),它被设计用来处理复杂的任务,特别是那些需要从多个工具或数据源获取信息的任务。Structured Chat 代理能够理解结构化的输入,并且可以执行一系列子任务来完成最终目标。

这种代理特别适合于需要多步骤推理和决策的情况,例如在对话系统中,它可以根据用户的问题,通过查询数据库、调用API或其他工具来获取信息并形成回答。

使用方式无区别,创建方式如下:

from langchain.agents import create_structured_chat_agent

create_structured_chat_agent(llm=xxx, tools=xxx, prompt=xxx)

ReAct

在大语言模型(LLM)领域,ReAct 是一种创新的方法,它结合了推理(Reasoning)和行动(Action)两个方面,使模型能够在处理问题时不仅进行思考,还能执行必要的操作来收集或修改信息。这种方法最初由普林斯顿大学和谷歌的研究者提出,并在2023年的ICLR会议上发表。

ReAct 的核心思想是让模型在解决问题的过程中,能够动态地决定是否需要进一步的信息,以及如何获取这些信息。这通常通过以下步骤实现:

  1. Thought(思考):模型首先基于已有的信息对问题进行思考,形成一个初步的推理过程。
  2. Action(行动):根据思考的结果,模型决定是否需要采取行动来获取更多信息,比如查询数据库、调用API、搜索网络等。
  3. Observation(观察):如果采取了行动,模型会收到行动的结果,即新的信息或数据。
  4. Answer(回答):最后,模型将所有收集到的信息整合起来,形成最终的答案。

这个过程可以迭代进行,直到模型认为已经获得了足够的信息来回答问题为止。

在上文中,我举的美国总统例子就是用的ReAct~

Self-ask with search

在大语言模型(LLM)领域,Self-Ask with Search是一种策略,用于增强模型的决策能力和信息检索能力。这种策略允许模型在生成响应时自我提问并主动搜索相关信息,从而提高其答案的准确性和完整性。

Self-Ask with Search 的工作流程如下:

  1. 初始问题:用户向模型提出一个问题。
  2. 自我提问:模型分析问题后,可能意识到需要额外的信息才能给出准确的回答。这时,模型会自我提问,即生成一个或多个子问题,这些子问题旨在引导模型去寻找缺失的信息。
  3. 搜索:模型使用可用的搜索引擎或数据源来查找与子问题相关的信息。这可以是互联网上的公开信息,也可以是特定的数据库或文档集合。
  4. 整合信息:一旦找到相关信息,模型会将其与原始问题和现有知识结合起来,形成一个更全面的理解。
  5. 生成回答:基于整合后的信息,模型生成最终的回答,这个回答包含了从搜索中获得的新知识。

使用方式无区别,创建方式如下:

from langchain.agents import create_self_ask_with_search_agent

create_self_ask_with_search_agent(llm=xxx, tools=xxx, prompt=xxx)

这里有一个小点要注意,在使用create_self_ask_with_search_agent时,要将tool的name设置成Intermediate Answer,不然会报错!

04 总结

以上就是LangChain中Agent的完全解析,还有一些小的注意点我在这里列一下。

  • AgentExecutor参数配置
    • max_iterations:限制执行的最大步数,设置这个参数,确保不会因为意外导致死循环。
    • max_execution_time:限制执行的最大时长,有助于防止长时间运行代理程序。
    • handle_parsing_errors:处理Agent输出解析器引发的错误的方式。默认为False,即抛出错误。如果为True,错误将作为观察发送回LLM。

另外,前面我也提到了Agent也支持自定义,这块本文没有涉及,后续有需要的可以留言,我们视情况再单独开一篇文章专门讲自定义Agent。😊

如果能帮我点个免费的关注,那就是对我个人的最大的肯定。如果觉得写的还行,分享一下也是我生活的小确幸~

在这里插入图片描述

以上内容依据官方文档编写,官方地址:https://python.langchain.com/docs/modules/agents

Peace & Love~

在这里插入图片描述

  • 【LangChain进阶教程】十一、LangChain进阶之Tools
  • 【LangChain进阶教程】十、LangChain进阶之Retrievers
  • 【LangChain进阶教程】九、LangChain进阶之Vector Stores
  • 【LangChain进阶教程】八、LangChain进阶之Embedding Models

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1959220.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CTF Web信息搜集 25000字详解

目录 前言信息收集常见信息分类域名信息whois备案CDN子域名解析记录 旁站C段服务器信息端口服务器类型数据库类型waf防火墙 网站信息备份文件备份文件常见的后缀名备份文件常见的文件名gedit备份文件vim备份文件收集方法 敏感目录CMS类型&#xff08;指纹识别&#xff09;探针泄…

牛客JS题(十二)列表动态渲染

注释很详细&#xff0c;直接上代码 涉及知识点&#xff1a; 忍者码风reduce注意事项 题干&#xff1a; 我的答案 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"></head><body><ul></ul><…

决策树 和 集成学习、随机森林

决策树是非参数学习算法&#xff0c;可以解决分类问题&#xff0c;天然可以解决多分类问题&#xff08;不同于逻辑回归或者SVM&#xff0c;需要通过OVR&#xff0c;OVO的方法&#xff09;&#xff0c;也可以解决回归问题&#xff0c;甚至是多输出任务&#xff0c;并且决策树有非…

浅谈监听器之后端监听器

浅谈监听器之后端监听器 “后端监听器”&#xff08;Backend Listener&#xff09;是一种高级功能&#xff0c;用于异步地将测试结果数据发送至外部系统&#xff0c;如数据库、消息队列或时间序列数据库等&#xff0c;以便于长期存储、实时分析和可视化展示。 后端监听器的作…

python 可视化探索(二):高级图表与组合图表

总结&#xff1a;本文为和鲸python 可视化探索训练营资料整理而来&#xff0c;加入了自己的理解&#xff08;by GPT4o&#xff09; 原作者&#xff1a;作者&#xff1a;大话数据分析&#xff0c;知乎、公众号【大话数据分析】主理人&#xff0c;5年数据分析经验&#xff0c;前…

centos安装crictl

上章文章已经讲诉了如何安装centos安装containerd-CSDN博客&#xff0c;本文章讲解如何安装crictl 一、官网安装说明文档&#xff0c;官网 二、二进制安装 #!/bin/sh VERSION"v1.30.0" # check latest version in /releases page wget https://github.com/kubernet…

IDEA 本地有jar包依赖文件,但是所有引用的jar包全部爆红

前端时间 看源码&#xff0c;下载源码额按钮不见了&#xff0c;折腾了很久&#xff0c;遂打算重新安装idea&#xff0c;但是重新安装后&#xff0c;发现代码全都爆红&#xff0c;按照晚上说的删除idea 文件夹&#xff0c;idea缓存删除&#xff0c;都不好使&#xff0c;但是看到…

PMP冲刺题及知识点整理

PMP题目整理 冲刺题1错题整理冲刺题1相关重点记录&#xff1a;零散不熟悉知识点整理团队章程责任分配矩阵RAM定义是啥风险识别的工具都有啥 冲刺题2错题整理知识点整理情商风险登记在风险登记册&#xff0c;风险管理计划中没有风险团队章程项目经理来确保进行知识转移交付哪一个…

【C++】STL-红黑树封装出set和map

目录 1、实现红黑树的泛型 2、set和map的插入 3、set和map的迭代器 3.1 operator 3.2 operator-- 3.3 const迭代器 4、find 5、map的operator[] 6、完整代码 6.1 红黑树 6.2 set 6.3 map 1、实现红黑树的泛型 我们先引入上一节中写的红黑树 enum Colour {RED,BL…

Unity Shader 初学者指南

《Unity Shader 初学者指南》(3D Game Shaders For Beginners) 是一个面向初学者的教程项目&#xff0c;由David Lettier创建。该项目通过一系列分步指导&#xff0c;教授如何在3D游戏中实现各种着色技术&#xff0c;包括环境光遮蔽(SSAO)、景深(Depth of Field)、光照、法线贴…

产品经理-​简历内容的可准备点(24)

在互联网岗位中,产品经理是一个没有针对性的专业&#xff0c;知识结构不明确&#xff0c;那该具体准备哪些内容呢&#xff1f; 大家知道大公司实习含金量高&#xff0c;但作为纯产品“小白”&#xff0c;冷启动找实习很困难&#xff08;本科生不太好找产品实习&#xff0c;普通…

OSI七层模型详解

OSI七层模型 OSI&#xff08;Open System Interconnect&#xff09;&#xff0c;即开放式系统互连。 一般都叫OSI参考模型&#xff0c;是ISO组织在1985年研究的网络互连模型。该体系结构标准定义了网络互连的七层框架&#xff08;物理层、数据链路层、网络层、传输层、会话层、…

loguru日志模块:简化Python自动化测试的日志管理!

引言 日志是软件开发中的关键组成部分&#xff0c;为开发和测试人员提供了调试和监控应用程序的重要手段。loguru 是一个第三方的 Python 日志库&#xff0c;以其简洁的 API 和自动化的功能脱颖而出。本文将探讨为什么项目中需要日志&#xff0c;loguru 为何受到青睐&#xff…

Python | ValueError: not enough values to unpack 解析

Python | ValueError: not enough values to unpack 解析 在Python编程中&#xff0c;ValueError: not enough values to unpack是一个常见的错误&#xff0c;通常发生在尝试将一个可迭代对象解包到太多的变量中时。本文将深入探讨此错误的根源&#xff0c;提供解决思路、方法…

Vue 中使用 inMap 创建动态遮罩覆盖物

本文由ScriptEcho平台提供技术支持 项目地址&#xff1a;传送门 Vue 中使用 inMap 创建动态遮罩覆盖物 应用场景 在基于 Vue 构建的地理信息系统应用中&#xff0c;经常需要在底图上绘制动态的遮罩覆盖物&#xff0c;以突出显示特定区域或隐藏敏感信息。 基本功能 这段代…

瑞芯微平台RK3568系统开发(2)Camera 开发2

基于上文&#xff0c;继续 瑞芯微平台RK3568系统开发&#xff08;2&#xff09;Camera 开发1-CSDN博客 1、使用v4l2-ctl说明 media-ctl工具的操作是通过/dev/medio0等media设备&#xff0c;它所管理是media的拓扑结构中各个节点的format&#xff0c;大小&#xff0c;链接。 …

CTF学习笔记汇总(非常详细)零基础入门到精通,收藏这一篇就够了

CTF学习笔记汇总 Part.01 Web 01 SSRF 主要攻击方式如下&#xff1a; 01 对外网、服务器所在内网、本地进行端口扫描&#xff0c;获取一些服务的banner信息。 02 攻击运行在内网或本地的应用程序。 03 对内网Web应用进行指纹识别&#xff0c;识别企业内部的资产信息。 …

Studying-代码随想录训练营day45| 115.不同的子序列、583. 两个字符串的删除操作、72. 编辑距离、编辑距离总结篇

第45天&#xff0c;子序列part03&#xff0c;编辑距离&#x1f4aa;(ง •_•)ง&#xff0c;编程语言&#xff1a;C 目录 115.不同的子序列 583. 两个字符串的删除操作 72. 编辑距离 编辑距离总结篇 115.不同的子序列 文档讲解&#xff1a;代码随想录不同的子序列 视频讲…

高效能程序员的9个习惯

最近看了一本关于敏捷软件开发实践的指南&#xff0c;他文中主要是在帮助软件开发者和团队提升工作效率、提高产品质量&#xff0c;并建立良好的工作文化和协作模式。以下是根据目录整理出的一段总结&#xff1a; 书名&#xff1a;《敏捷之道》 本书深入探讨了敏捷开发的核心原…

从 1 到 100 万+连接数,DigitalOcean 负载均衡的架构演进

在前不久&#xff0c;DigitalOcean 全球负载均衡器&#xff08;GLB&#xff09;Beta版正式上线。该解决方案能给客户的跨区域业务带来更好的支持&#xff0c;可以增强应用程序的弹性&#xff0c;消除单点故障&#xff0c;并大幅降低终端用户的延迟。这是 DigitalOcean 负载均衡…