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

FeiMinds 2024-09-15 15:01:23 阅读 51

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

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的逻辑得到最终结果。

具体代码如下:

<code>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",code>

history_messages_key="chat_history",code>

)

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='美国现任总统是谁?'),code>

AIMessage(content='美国现任总统是乔·拜登(Joe Biden)。他于2021年1月20日就任美国第46任总统。')],code>

'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,如下图:

在这里插入图片描述

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

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

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

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

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

Self-ask with search

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

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

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

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

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



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。