打造不同类型的智能代理:从基础到高级应用
在当今的人工智能领域,智能代理是实现复杂任务自动化和交互性的关键。本文将深入探讨多种类型智能代理的创建和使用,包括 ReAct 代理、Self - Ask 代理、具有自主决策能力的代理以及能使用多种工具的智能代理。
1. ReAct 代理
ReAct 代理是一种强大的工具,可在 AI 应用中实现 ReAct 逻辑,使代理能够根据收集到的信息进行推理和行动。
1.1 安装和导入必要的库
from langchain import hub
from langchain.agents import AgentExecutor, create_react_agent
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import OpenAI
1.2 初始化工具
使用 Tavily Search 让代理能够在线搜索信息:
tools = [TavilySearchResults(max_results=1)]
1.3 创建代理
从 LangChain 中心获取提示,选择 OpenAI 作为语言模型,然后构建 ReAct 代理:
prompt = hub.pull("hwchase17/react")
llm = OpenAI()
agent = create_react_agent(llm, tools, prompt)
1.4 运行代理
创建执行器并运行代理,通过设置
verbose=True
查看代理的思考过程:
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "what is LangChain?"})
代理会经历一系列的思考和行动来收集关于 LangChain 的信息,最终给出答案。
1.5 使用聊天历史
若要使用聊天历史,需从 LangChain 中心获取特定的聊天提示:
prompt = hub.pull("hwchase17/react-chat")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
通过传入代表之前对话回合的字符串来使用聊天历史:
from langchain_core.messages import AIMessage, HumanMessage
agent_executor.invoke(
{
"input": "what's my name? Only use a tool if needed, otherwise respond with Final Answer",
"chat_history": "Human: Hi! My name is Rabi\nAI: Hello Rabi! Nice to meet you",
}
)
代理会根据给定的聊天历史来决定是否需要使用工具。
2. Self - Ask 代理
Self - Ask 代理具有搜索功能,可帮助找到问题的答案。
2.1 导入必要的库
from langchain import hub
from langchain.agents import AgentExecutor, create_self_ask_with_search_agent
from langchain_community.llms import Fireworks
from langchain_community.tools.tavily_search import TavilyAnswer
2.2 初始化工具
使用 Tavily Answer 为问题提供直接答案,且该代理只能使用一个名为 “Intermediate Answer” 的工具:
tools = [TavilyAnswer(max_results=1, name="Intermediate Answer")]
2.3 创建代理
从 LangChain 中心获取提示,选择 Fireworks LLM 作为语言模型,构建 Self - Ask 代理:
import os
os.environ["FIREWORKS_API_KEY"] = "your-fireworks-api-key-here"
prompt = hub.pull("hwchase17/self-ask-with-search")
llm = Fireworks(
model="accounts/fireworks/models/llama-v2-13b-chat",
max_tokens=1024,
temperature=0.7
)
agent = create_self_ask_with_search_agent(llm, tools, prompt)
2.4 运行代理
创建执行器并运行代理:
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "What is the headquarters location of the company with the largest market capitalization in the tech industry?"})
代理会先问自己一个后续问题以收集更多信息,然后使用 Tavily Answer 工具找到答案,最终给出最终答案。
3. 具有自主决策能力的代理
以 “Task Manager” 代理为例,展示代理的自主决策能力。
3.1 安装必要的库
pip install langchain==0.2.5 openai==1.35.13 google-search-results serpapi
3.2 导入所需模块
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
from langchain.utilities import GoogleSearchAPIWrapper
3.3 设置语言模型和搜索工具
llm = OpenAI(temperature=0)
search = GoogleSearchAPIWrapper()
3.4 定义代理可用的工具
tools = [
Tool(
name="Search",
func=search.run,
description="Useful for searching the internet for information."
)
]
3.5 初始化代理
agent = initialize_agent(
tools,
llm,
agent="zero-shot-react-description",
verbose=True
)
3.6 给代理提供任务
task = "I need to plan a trip to Paris. What are the top tourist attractions I should visit, and what is the best time of year to go?"
result = agent.run(task)
print(result)
代理会自主分解任务,搜索相关信息并提供全面的响应。以下是巴黎旅游的相关信息:
| 类别 | 详情 |
| ---- | ---- |
| 巴黎顶级旅游景点 | 埃菲尔铁塔、卢浮宫博物馆、巴黎圣母院大教堂、凯旋门、凡尔赛宫、蒙马特高地、塞纳河游船 |
| 最佳旅游时间 | 春季(3 - 5 月):天气温和,花朵盛开,游客较少;夏季(6 - 8 月):天气炎热,白天长,是旅游旺季;秋季(9 - 11 月):天气宜人,游客较少,秋叶美丽;冬季(12 - 2 月):天气寒冷,白天短,有节日装饰,价格较低,游客较少 |
4. 能使用多种工具的智能代理
创建一个能在线搜索信息并从预加载索引中查找特定数据的智能代理。
4.1 设置 LangSmith
设置环境变量以使用 LangSmith 进行代理的构建和调试:
export LANGCHAIN_TRACING_V2="true"
export LANGCHAIN_API_KEY="<your-api-key>"
4.2 定义工具
-
Tavily
:
- 导出 Tavily API 密钥:
export TAVILY_API_KEY="..."
- 创建 TavilySearchResults 工具实例:
from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults()
-
Retriever
:
- 使用 WebBaseLoader 加载数据:
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://docs.smith.langchain.com/overview")
docs = loader.load()
2. 使用 RecursiveCharacterTextSplitter 分割文档:
from langchain_text_splitters import RecursiveCharacterTextSplitter
documents = RecursiveCharacterTextSplitter(
chunk_size=1000, chunk_overlap=200
).split_documents(docs)
3. 使用 FAISS 和 OpenAIEmbeddings 创建向量存储:
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
vector = FAISS.from_documents(documents, OpenAIEmbeddings())
retriever = vector.as_retriever()
4. 将 Retriever 转换为工具:
from langchain.tools.retriever import create_retriever_tool
retriever_tool = create_retriever_tool(
retriever,
"langsmith_search",
"Search for information about LangSmith. For any questions about LangSmith, you must use this tool!"
)
4.3 整合工具
tools = [search, retriever_tool]
4.4 选择语言模型
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
4.5 选择提示
从 LangChain 中心获取提示:
from langchain import hub
prompt = hub.pull("hwchase17/openai-functions-agent")
4.6 初始化代理
from langchain.agents import create_tool_calling_agent
agent = create_tool_calling_agent(llm, tools, prompt)
4.7 创建代理执行器
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
4.8 测试代理
agent_executor.invoke({"input": "hi!"})
agent_executor.invoke({"input": "how can langsmith help with testing?"})
agent_executor.invoke({"input": "whats the weather in sf?"})
以下是创建能使用多种工具的智能代理的流程图:
graph TD;
A[设置 LangSmith] --> B[定义工具];
B --> B1[Tavily];
B --> B2[Retriever];
B1 --> C[整合工具];
B2 --> C;
C --> D[选择语言模型];
D --> E[选择提示];
E --> F[初始化代理];
F --> G[创建代理执行器];
G --> H[测试代理];
通过以上步骤,我们可以创建不同类型的智能代理,满足各种复杂任务的需求。无论是简单的问答还是复杂的任务规划,智能代理都能发挥重要作用。
打造不同类型的智能代理:从基础到高级应用
5. 智能代理的测试与响应分析
在创建好智能代理后,对其进行测试并分析响应结果是确保其性能和可靠性的重要环节。
5.1 简单问候测试
当我们向代理发送简单的问候 “hi!” 时,代理会迅速做出响应。以下是代码和响应示例:
agent_executor.invoke({"input": "hi!"})
响应结果:
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3mHello! How can I assist you today?[0m
[1m> Finished chain.[0m
{'input': 'hi!', 'output': 'Hello! How can I assist you today?'}
从这个响应可以看出,代理能够友好地回应问候,并询问如何提供帮助,这表明代理在处理简单输入时能够正常工作。
5.2 特定问题测试:LangSmith 测试相关
当我们询问 “how can langsmith help with testing?” 时,代理会调用相应的工具来查找答案。以下是代码和详细响应:
agent_executor.invoke({"input": "how can langsmith help with testing?"})
响应结果:
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3m
Invoking: `langsmith_search` with `{'query': 'how can LangSmith
help with testing'}`
[0m[33;1m[1;3mLangSmith is a platform for building production-
grade LLM applications that can help with testing in the
following ways:
1. **Tracing**: LangSmith provides tracing capabilities that
allow you to closely monitor and evaluate your application
during testing. You can log traces to track the behavior of
your application and identify any issues.
2. **Evaluation**: LangSmith offers evaluation capabilities
that enable you to assess the performance of your application
during testing. This helps you ensure that your application
functions as expected and meets the required standards.
3. **Production Monitoring & Automations**: LangSmith allows
you to monitor your application in production and automate
certain processes, which can be beneficial for testing
different scenarios and ensuring the stability of your
application.
4. **Prompt Hub**: LangSmith includes a Prompt Hub, a prompt
management tool that can streamline the testing process by
providing a centralized location for managing prompts and
inputs for your application.
Overall, LangSmith can assist with testing by providing tools
for monitoring, evaluating, and automating processes to ensure
the reliability and performance of your application during
testing phases.[0m
[1m> Finished chain.[0m
从这个响应可以看出,代理能够准确地调用
langsmith_search
工具,并从索引文档中检索到相关信息,详细地说明了 LangSmith 在测试方面的多种功能。
5.3 实时信息查询测试:天气查询
当我们询问 “whats the weather in sf?” 时,代理会调用 Tavily 搜索工具来获取实时天气信息。以下是代码和响应:
agent_executor.invoke({"input": "whats the weather in sf?"})
响应结果:
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3m
Invoking: `tavily_search_results_json` with `{'query': 'weather
in San Francisco'}`
[0m[36;1m[1;3m[{'url': 'https://www.weatherapi.com/',
'content': "{'location': {'name': 'San Francisco', 'region':
'California', 'country': 'United States of America', 'lat':
37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles',
'localtime_epoch': 1712847697, 'localtime': '2024-04-11
8:01'}, 'current': {'last_updated_epoch': 1712847600, 'last_
updated': '2024-04-11 08:00', 'temp_c': 11.1, 'temp_f': 52.0,
'is_day': 1, 'condition': {'text': 'Partly cloudy', 'icon':
'//cdn.weatherapi.com/weather/64x64/day/116.png', 'code':
1003}, 'wind_mph': 2.2, 'wind_kph': 3.6, 'wind_degree': 10,
'wind_dir': 'N', 'pressure_mb': 1015.0, 'pressure_in': 29.98,
'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 97, 'cloud':
25, 'feelslike_c': 11.5, 'feelslike_f': 52.6, 'vis_km': 14.0,
'vis_miles': 8.0, 'uv': 4.0, 'gust_mph': 2.8, 'gust_kph':
4.4}}"}][0m[32;1m[1;3mThe current weather in San Francisco is
partly cloudy with a temperature of 52.0°F (11.1°C). The wind
代理成功调用了
tavily_search_results_json
工具,获取到了旧金山的实时天气信息,并以清晰的方式呈现给用户。
6. 不同类型智能代理的对比与总结
| 代理类型 | 特点 | 适用场景 | 关键工具 | 语言模型 |
|---|---|---|---|---|
| ReAct 代理 | 能够根据收集到的信息进行推理和行动,支持使用聊天历史 | 一般性问答、对话场景 | Tavily Search | OpenAI |
| Self - Ask 代理 | 具有搜索能力,通过自我提问的方式找到答案 | 需要逐步推理和查找信息的问题 | Tavily Answer | Fireworks LLM |
| 具有自主决策能力的代理 | 能自主分解任务,决定使用的工具 | 复杂任务规划,如旅行规划 | Google Search API | OpenAI |
| 能使用多种工具的智能代理 | 可在线搜索信息并从预加载索引中查找数据 | 综合信息查询,如实时信息和特定领域知识查询 | Tavily、Retriever | ChatOpenAI |
7. 智能代理的未来展望
随着人工智能技术的不断发展,智能代理的功能和应用场景也将不断拓展。未来,智能代理可能会在以下几个方面取得更大的进展:
7.1 更强的学习能力
智能代理将能够更快地学习新知识,适应新的任务和环境。例如,通过强化学习和迁移学习,代理可以在不同的领域和任务中快速调整策略,提高解决问题的效率。
7.2 更复杂的任务处理
代理将能够处理更加复杂的任务,如多步骤的工艺流程管理、复杂的数据分析和决策支持。这需要代理具备更强的逻辑推理和规划能力。
7.3 更好的人机协作
智能代理将与人类进行更加紧密的协作,理解人类的意图和情感,提供更加个性化的服务。例如,在医疗领域,代理可以协助医生进行诊断和治疗方案的制定。
以下是智能代理未来发展的流程图:
graph TD;
A[当前智能代理] --> B[更强的学习能力];
A --> C[更复杂的任务处理];
A --> D[更好的人机协作];
B --> E[适应新任务和环境];
C --> F[多步骤工艺流程管理];
C --> G[复杂数据分析和决策支持];
D --> H[理解人类意图和情感];
D --> I[提供个性化服务];
通过本文的介绍,我们详细了解了不同类型智能代理的创建、使用和测试方法。无论是基础的问答代理还是具有高级自主决策能力的代理,都为我们处理各种复杂任务提供了强大的工具。随着技术的不断进步,智能代理的应用前景将更加广阔。
构建多功能智能代理全解析
超级会员免费看
168万+

被折叠的 条评论
为什么被折叠?



