赞
踩
幸福,不是长生不老,不是大鱼大肉,不是权倾朝野。幸福是每一个微小的生活愿望达成。当你想吃的时候有得吃,想被爱的时候有人来爱你。
在LangChain中,Agent 是一个核心概念,它代表了一种能够利用语言模型(LLM)和其他工具来执行复杂任务的系统。Agent的设计目的是为了处理那些简单的语言模型可能无法直接解决的问题,尤其是当这些任务涉及到多个步骤或者需要外部数据源的情况。
Agent 在LangChain中扮演着一个协调者和决策者的角色,它能够根据给定的任务和目标,决定使用哪些工具以及如何组合这些工具来达到目的。
Agent会根据输入的指令和上下文信息,调用不同的工具(如搜索引擎、数据库查询、API调用等)来获取所需的信息,并将这些信息整合起来形成最终的响应。
Agent(代理)的核心思想是使用语言模型来选择要执行的一系列操作。
在Chain(链)中,一系列操作被硬编码在代码中。在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的使用,是不是很简单~声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/1014493
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。