AI agent开发——使用react框架

来自《动手做AI agent》,我的代码如下:

import os
os.environ['OpenAI_API_KEY'] = 'xxx填写你的'
os.environ['SERPAPI_API_KEY'] = 'xxx填写你的'

from dotenv import load_dotenv
load_dotenv()  

# 导入LangChain Hub
from langchain import hub
# 从hub中获取React的Prompt
prompt = hub.pull("hwchase17/react")
print(prompt)

# 导入ChatOpenAI
from langchain_community.llms import OpenAI
# 选择要使用的LLM
llm = OpenAI()

# 导入SerpAPIWrapper即工具包
from langchain_community.utilities import SerpAPIWrapper
from langchain.agents.tools import Tool
# 实例化SerpAPIWrapper
search = SerpAPIWrapper()
# 准备工具列表
tools = [
    Tool(
        name="Search",
        func=search.run,
        description="当大模型没有相关知识时,用于搜索知识"
    ),
]

# 导入create_react_agent功能
from langchain.agents import create_react_agent
# 构建ReAct代理
agent = create_react_agent(llm, tools, prompt)

# 导入AgentExecutor
from langchain.agents import AgentExecutor
# 创建代理执行器并传入代理和工具
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 调用代理执行器,传入输入数据
print("第一次运行的结果:")
agent_executor.invoke({"input": "当前Agent最新研究进展是什么?"})
print("第二次运行的结果:")
agent_executor.invoke({"input": "当前Agent最新研究进展是什么?"})

  

效果:

input_variables=['agent_scratchpad', 'input', 'tool_names', 'tools'] metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'react', 'lc_hub_commit_hash': 'd15fe3c426f1c4b3f37c9198853e4a86e20c425ca7f4752ec0c9b0e97ca7ea4d'} template='Answer the following questions as best you can. You have access to the following tools:\n\n{tools}\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 [{tool_names}]\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: {input}\nThought:{agent_scratchpad}'

翻译下:

模板='尽力回答以下问题。您可以使用以下工具:\n\n{tools}\n\n请使用以下格式:

问题:您必须回答的输入问题

思考:您应该始终考虑该怎么做

操作:要采取的操作,应该是[{tool_names}]之一

操作输入:操作的输入

观察:操作的结果

...(这个思考/操作/操作输入/观察可以重复N次)

思考:我现在知道最终答案

最终答案:原始输入问题的最终答案

开始!

问题:{input}

思考:{agent_scratchpad}'

 

第一次运行的结果:


> Entering new AgentExecutor chain...
 Agent是一个广泛的概念,我需要更多的信息来回答这个问题。
Action: Search
Action Input: "Agent research progress"['This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems. It aims to identify key ...', 'Iterate between types of tasks · Try to make progress on original research problems like the ones listed above · Stay up to date on the progress ...', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems. It aims to identify key c.', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems. It aims to identify key ...', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems.', 'The Agent of Progress System is a brain function management system that is a transformational communication, advertising, marketing, and sales technology that ...', 'In the current paper, the bonding mechanisms and research progress of different types of bonding agents such as alcohol amine bonding agents, ...', 'This Special Issue comprises an in-depth exploration of recent MAS applications, including innovative approaches to learning, coordination, and cooperation ...', "Each year, to keep you updated on our research team's progress, we develop a report showcasing some of our lab's achievements.", 'The RPPR is used by recipients to submit progress reports to NIH on their grant awards. This page provides an overview of the annual RPPR, ...']信息比较多,需要筛选出和Agent相关的研究进展。
Action: Search
Action Input: "Agent research progress + related"['Abstract. This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems.', 'The Agent of Progress System Research Project recognized that all human beings have the same brain anatomy and brain physiology. This fundamental finding has ...', 'Iterate between types of tasks · Try to make progress on original research problems like the ones listed above · Stay up to date on the progress ...', "Annual RPPR – Use to describe a grant's scientific progress, identify significant changes, report on personnel, and describe plans for the ...", "Each year, to keep you updated on our research team's progress, we develop a report showcasing some of our lab's achievements.", 'Select agents are hazardous biological agents and toxins that have been identified by HHS or the U.S.. Department of Agriculture (USDA) as having the ...', 'Abstract · application being undertaken within an agent community. · proposed as a way of achieving the latter, and supporting the discovery of agent interdep ...', 'The PHS 398 Research Plan form is used only for research, multi-project, and SBIR/STTR applications. This form includes fields to upload ...', 'The committee located more than 150 projects related to source testing either under way or recently completed, with studies generally distributed as shown in ...', 'This paper mainly focused on the research on opponent modeling of agents, and introduced the opponent modeling technology in agent action ...']信息中有一些和Agent相关的研究进展,需要进一步筛选。
Action: Search
Action Input: "Agent research progress + related + autonomous"['Agent-based computing and modeling have been around for decades, but thanks to recent innovations in generative AI, researchers, ...', 'As it relates to research, first create an outline of questions to research related to the task, and then deterministically execute an agent ...', 'A new research report provides a framework for the global autonomous AI and Autonomous Agents market, projecting a significant growth ...', 'Abstract. This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems.', 'The group specialises in the development of artificial intelligence and machine learning technologies for autonomous systems control and decision making in ...', 'Finds LLMs effective in various environments for high-level planning tonresolve deadlocks. AgentQuest: A Modular Benchmark Framework to Measure Progress and ...', 'Agents and agent-based systems are becoming essential in the development ... However, further research revealed autonomous agency ... analysis agents is related to ...', "Autonomous AI agents are here and they're pretty amazing. Explore definitions, insights, and examples about the world of autonomous AI.", 'As research and development in autonomous agents accelerate, they hold promise to unlock unprecedented levels of automation and productivity ...', 'Thus, we propose a framework in which dialogue agents can evaluate the progression of a conversation toward or away from desired outcomes, and ...']信息中的关键词都有,需要进一步筛选出最新的研究进展。
Action: Search
Action Input: "Agent research progress + related + autonomous + recent"['Agent-based computing and modeling have been around for decades, but thanks to recent innovations in generative AI, researchers, ...', "Dive into autonomous agents: how they shape AI's future, boost tech, and the role of OpenAI. A must-read guide for AI buffs.", 'This white paper explores the current state and future trajectory of autonomous agent ... As research and development in autonomous agents ...', 'Self-monitoring maintains and emphasizes recent and novel events towards agent goals ... Very similar with An Autonomous Agent-definition by Franklin & Graesser ( ...', 'In the evolving landscape of AI, these autonomous agents represent a significant stride towards a future where technology seamlessly augments ...', 'AI agents are transforming work across industries through advanced language models and automation. This article explores their capabilities, ...', "The arrival of autonomous agents into the mainstream isn't far off. BCG explores why companies should be governing and monitoring autonomous ...", 'Agents are all the rage, but their planning capabilities currently outpace their ability to act reliably. How do we make them truly autonomous?', 'In the field of AI, Agents are autonomous doers/workers, capable of independently carrying out tasks that align with predefined goals and ...', 'These papers represent a snapshot of the current research landscape in AI agents, covering theoretical foundations, practical applications ...']信息中的关键词都有,而且是最新的研究进展,可以回答问题。
Final Answer: 最新研究进展是Agent-based computing and modeling have been around for decades, but thanks to recent innovations in generative AI, researchers have made significant progress in the development of artificial intelligence and machine learning technologies for autonomous systems. These technologies have the potential to greatly enhance automation and productivity in various industries.

> Finished chain.
第二次运行的结果:


> Entering new AgentExecutor chain...
 I should use the Search tool to find the latest research developments for Agents.
Action: Search
Action Input: "Agent research developments"['This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems.', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems.', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems. It aims to identify key ...', 'This paper provides an overview of research and development activities in the field of autonomous agents and multi-agent systems. It aims to identify key ...', 'As above, you have to visit the research agent. Make sure to collect any datacores BEFORE stopping research! You can restart research at the new ...', 'Select agents are hazardous biological agents and toxins that have been identified by HHS or the U.S.. Department of Agriculture (USDA) as having the ...', 'Agents of Discovery empowers educators to turn the whole world into an engaging, active, and safe learning environment. Platform Terms of ...', 'ALEXANDRIA, VA, March 30, 2022— The Big “I” is pleased to announce the promotion of Chris Boggs as the new vice president of agent development, research and ...', 'This is an emerging research area that poses new challenges for embodied AI systems and there is still significant room for improvement. A deeper understanding ...', 'Research, Development & Innovation (RDI), a division of Indirect Supply Chain, is seeking an Entry Level Procurement Agent to join our team, ...']I now know the final answer
Final Answer: Based on the search results, the latest research developments for Agents include an emphasis on autonomous and multi-agent systems, identifying key areas for improvement, and the promotion of Chris Boggs as the new vice president of agent development, research, and innovation at the Big "I". There also seems to be a growing focus on embodied AI systems and the need for continued research and development in this area.

> Finished chain.

  

再看一个例子:

import os
os.environ['OpenAI_API_KEY'] = 'sk-pxxx替换'
os.environ['SERPAPI_API_KEY'] = '9xxxxx替换'

# 导入环境变量
from dotenv import load_dotenv
load_dotenv()

# 初始化大模型
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model='gpt-3.5-turbo',
             temperature=0.5)

# 设置工具
from langchain.agents import load_tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# 设置提示模板
from langchain.prompts import PromptTemplate
template = ('''
    '尽你所能用中文回答以下问题。如果能力不够你可以使用以下工具:\n\n'
    '{tools}\n\n
    Use the following format:\n\n'
    'Question: the input question you must answer\n'
    'Thought: you should always think about what to do\n'
    'Action: the action to take, should be one of [{tool_names}]\n'
    'Action Input: the input to the action\n'
    'Observation: the result of the action\n'
    '... (this Thought/Action/Action Input/Observation can repeat N times)\n'
    'Thought: I now know the final answer\n'
    'Final Answer: the final answer to the original input question\n\n'
    'Begin!\n\n'
    'Question: {input}\n'
    'Thought:{agent_scratchpad}' 
    '''
)
prompt = PromptTemplate.from_template(template)

# 初始化Agent
from langchain.agents import create_react_agent
agent = create_react_agent(llm, tools, prompt)

# 构建AgentExecutor
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, 
                               tools=tools, 
                               handle_parsing_errors=True,
                               verbose=True)

# 执行AgentExecutor
agent_executor.invoke({"input": 
                       """目前市场上玫瑰花的一般进货价格是多少?\n
                       如果我在此基础上加价5%,应该如何定价?"""})

  

运行效果图:

python ReAct.py


> Entering new AgentExecutor chain...
我需要使用搜索引擎来查找目前市场上玫瑰花的一般进货价格,然后使用计算器来计算加价5%后的定价。

Action: Search
Action Input: "目前市场上玫瑰花的一般进货价格"['几天前叫价2元一支的红色、粉色玫瑰花,目前的零售价已渐行上涨。在一些街道的花店,同类玫瑰花的价格已卖到3元一支,更高的甚至还要4元。一经销商表示,“现在还算便宜,过 ...', '我公司每天会按照我们网站上公布的鲜花报价发货,如有我们网站上公布的价格与实际的发货价格不符,请与我们网站上的客服联系或者直接致电给我们询问. 鲜花等级说明:. A级 ...', '据中国证券报,近日,记者走访了上海的鲜花批发市场及街边花店发现,鲜花需求价量齐升。其中,以“爱”为名的玫瑰价格创新高。', '经营鲜切花店十多年的王女士称,广州本地产的一扎(20枝)的C级红玫瑰,平日的价格是20至30元,今年的普遍批发价格是120元,最贵的已叫价150元。 记者在走访过程中也发现,或因玫瑰价格较高,花卉市场内售卖玫瑰的档口并不算多,相较而言更多的店家在售卖百合等其他花卉品种。', '今年由于气温回升较快,玫瑰花已经开始采摘。平阴县玫瑰鲜花蕾 开秤价格从2.8元/斤,迅速攀升至4月27日的3.5元/斤,开秤价格平均每斤比去年同期上涨1 ...', '今年的玫瑰价格比往年几乎翻了 一番,原因是什么?不少花店老板都表示,他们的进货地是云南昆明,今年因为天气原因,昆明的玫瑰产量跟不上。“今年昆明冻了 ...', '... 花要卖980元。 玫瑰价格疯涨。上海情人节的“玫瑰仪式感”依旧丝毫未减。春寒料峭,花店、批发市场门庭若市,记者向 多家摊主老板了解到,“今年的玫瑰花 ...', "“红玫瑰一捆20支的价格一般在25-40元,像'弗洛伊德'这类特定花色的精品玫瑰普遍价格高一些,一捆约100元。”鲜花批发商陈先政介绍说。 打开网易新闻查看 ...", '扬州一束99朵玫瑰已经突破2000元 “刚刚从市场传来的信息,今天上午玫瑰C级货的地头拿价已经涨到11元一支了。”从事鲜花销售23年的高静娟看到地头收货人员发 ...', '一般来说 ,为保证情人节当天的鲜花供应,花商都会 ... 记者搜索某花卉批发电商平台发现,卡罗拉玫瑰的价格 ... 昆明斗南鲜花市场是全 国不少花店进货的渠道之一 ...']Observation results show that the general wholesale price of roses in the market varies, ranging from 3 yuan to 4 yuan per stem.

Action: Calculator
Action Input: Calculate a 5% increase on the average price of 3.5 yuan per stemAnswer: 3.6750000000000003Final Answer: If the general wholesale price of roses in the market is 3.5 yuan per stem, a 5% increase would make the price 3.68 yuan per stem.

> Finished chain.

posted @ 2024-05-21 17:41  bonelee  阅读(17)  评论(0编辑  收藏  举报