langchain_v0.3_WebSearchAgent
这个教程关于如何使用 LangChain 的工具、模型和 Agent 来实现一个简单的智能应用。通过几个步骤来演示如何集成不同的功能,例如天气查询、与工具互动、以及如何创建和使用一个带有记忆功能的 Agent。
如何使用 LangChain 工具和 Agent 创建智能应用
这个教程关于如何使用 LangChain 的工具、模型和 Agent 来实现一个简单的智能应用。通过几个步骤来演示如何集成不同的功能,例如天气查询、与工具互动、以及如何创建和使用一个带有记忆功能的 Agent。
1. 环境设置
首先,需要加载环境变量,以便在代码中使用 API 密钥等敏感信息。dotenv 是一个流行的 Python 库,可以从 .env 文件加载环境变量。
from dotenv import load_dotenv
_ = load_dotenv()
2. 使用 Tavily 工具进行天气查询
在 LangChain 中,工具(Tool)是你可以用来与外部服务交互的组件。在本例中,我们使用 TavilySearchResults 工具来查询 San Francisco 的天气。
TAVILY_API_KEY可在 https://tavily.com/ 申请
from langchain_community.tools.tavily_search import TavilySearchResults
import os
os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
search = TavilySearchResults(max_results=2)
search_results = search.invoke("what is the weather in SF")
print(search_results)
# If we want, we can create other tools.
# Once we have all the tools we want, we can put them in a list that we will reference later.
tools = [search]
[{'url': 'https://www.weatherapi.com/', 'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.775, 'lon': -122.4183, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1730780454, 'localtime': '2024-11-04 20:20'}, 'current': {'last_updated_epoch': 1730780100, 'last_updated': '2024-11-04 20:15', 'temp_c': 14.4, 'temp_f': 57.9, 'is_day': 0, 'condition': {'text': 'Clear', 'icon': '//cdn.weatherapi.com/weather/64x64/night/113.png', 'code': 1000}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 255, 'wind_dir': 'WSW', 'pressure_mb': 1020.0, 'pressure_in': 30.12, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 70, 'cloud': 0, 'feelslike_c': 14.4, 'feelslike_f': 58.0, 'windchill_c': 14.9, 'windchill_f': 58.8, 'heatindex_c': 14.9, 'heatindex_f': 58.8, 'dewpoint_c': 10.5, 'dewpoint_f': 50.8, 'vis_km': 16.0, 'vis_miles': 9.0, 'uv': 0.0, 'gust_mph': 8.5, 'gust_kph': 13.6}}"}, {'url': 'https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA', 'content': 'Current conditions at SAN FRANCISCO DOWNTOWN (SFOC1) Lat: 37.77056°NLon: 122.42694°WElev: 150.0ft. NA. 52°F. 11°C. ... 2024-6pm PST Nov 9, 2024 . Forecast Discussion . Additional Resources. ... National Weather Service; San Francisco Bay Area, CA; 21 Grace Hopper Ave, Stop 5; Monterey, CA 93943-5505; Comments? Questions?'}]
在这段代码中,设置 TAVILY_API_KEY 环境变量,然后使用 TavilySearchResults 来执行一个查询,获取 San Francisco 的天气信息。
3. 使用 chatglm 模型与工具进行交互
接下来使用 ChatOpenAI 模块,并将其与之前定义的工具(如 TavilySearchResults)结合。首先创建模型,并调用一个简单的消息响应。
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="glm-4", temperature=0)
from langchain_core.messages import HumanMessage
response = model.invoke([HumanMessage(content="hi!")])
response.content
'Hello! How can I assist you today? If you have any questions or need information on a topic, feel free to ask.'
这是一个基本的对话,模型会回应你发送的消息。
4. 绑定工具到模型
为了让模型调用外部工具,将工具与模型绑定。这样,模型可以在需要时调用工具来获取信息。
model_with_tools = model.bind_tools(tools)
response = model_with_tools.invoke([HumanMessage(content="Hi!")])
print(f"ContentString: {response.content}")
print(f"ToolCalls: {response.tool_calls}")
ContentString: Hello! How can I assist you today?
ToolCalls: []
response = model_with_tools.invoke([HumanMessage(content="What's the weather in SF?")])
print(f"ContentString: {response.content}")
print(f"ToolCalls: {response.tool_calls}")
ContentString:
ToolCalls: [{'name': 'tavily_search_results_json', 'args': {'query': 'San Francisco weather'}, 'id': 'call_9164233601792218028', 'type': 'tool_call'}]
在这个例子中,模型回答了天气问题,同时也记录了它使用了哪个工具。
5. 使用 React Agent 创建复杂交互
接下来,使用 LangChain 的 create_react_agent 方法创建一个能够自动选择工具并回应用户的 Agent。这个 Agent 将根据用户输入来决定使用哪个工具。
from langgraph.prebuilt import create_react_agent
agent_executor = create_react_agent(model, tools)
response = agent_executor.invoke({"messages": [HumanMessage(content="hi!")]})
response["messages"]
[HumanMessage(content='hi!', additional_kwargs={}, response_metadata={}, id='36230246-8ec2-4427-8f99-ee83b8781cc7'),
AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 139, 'total_tokens': 150, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-7270ab22-2a25-47d2-9b18-52ed1859fee2-0', usage_metadata={'input_tokens': 139, 'output_tokens': 11, 'total_tokens': 150, 'input_token_details': {}, 'output_token_details': {}})]
这里的 create_react_agent 会自动根据输入消息选择最合适的工具并返回相应的结果。
6. 流式响应
对于需要多个步骤才能完成的任务,流式响应非常有用。下面的代码展示了如何使用 stream 方法来逐步获取响应。
response = agent_executor.invoke(
{"messages": [HumanMessage(content="whats the weather in sf?")]}
)
response["messages"]
[HumanMessage(content='whats the weather in sf?', additional_kwargs={}, response_metadata={}, id='538c4069-7b8c-4ccb-812f-a903a056e4bd'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_9164229925298935937', 'function': {'arguments': '{"query":"weather in San Francisco"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 144, 'total_tokens': 165, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-d8c09566-140c-4c5d-9702-a01678b2b17a-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'weather in San Francisco'}, 'id': 'call_9164229925298935937', 'type': 'tool_call'}], usage_metadata={'input_tokens': 144, 'output_tokens': 21, 'total_tokens': 165, 'input_token_details': {}, 'output_token_details': {}}),
ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.775, \'lon\': -122.4183, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1730780454, \'localtime\': \'2024-11-04 20:20\'}, \'current\': {\'last_updated_epoch\': 1730780100, \'last_updated\': \'2024-11-04 20:15\', \'temp_c\': 14.4, \'temp_f\': 57.9, \'is_day\': 0, \'condition\': {\'text\': \'Clear\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/night/113.png\', \'code\': 1000}, \'wind_mph\': 4.0, \'wind_kph\': 6.5, \'wind_degree\': 255, \'wind_dir\': \'WSW\', \'pressure_mb\': 1020.0, \'pressure_in\': 30.12, \'precip_mm\': 0.0, \'precip_in\': 0.0, \'humidity\': 70, \'cloud\': 0, \'feelslike_c\': 14.4, \'feelslike_f\': 58.0, \'windchill_c\': 14.9, \'windchill_f\': 58.8, \'heatindex_c\': 14.9, \'heatindex_f\': 58.8, \'dewpoint_c\': 10.5, \'dewpoint_f\': 50.8, \'vis_km\': 16.0, \'vis_miles\': 9.0, \'uv\': 0.0, \'gust_mph\': 8.5, \'gust_kph\': 13.6}}"}, {"url": "https://world-weather.info/forecast/usa/san_francisco/may-2024/", "content": "Detailed ⚡ San Francisco Weather Forecast for May 2024 - day/night 🌡️ temperatures, precipitations - World-Weather.info. Add the current city. Search. Weather; Archive; Widgets °F. World; United States; California; Weather in San Francisco; ... 11 +66° +55° 12 +63° +54° 13"}]', name='tavily_search_results_json', id='ac332672-cf68-4295-a2a1-841c4ea7a0ac', tool_call_id='call_9164229925298935937', artifact={'query': 'weather in San Francisco', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Weather in San Francisco', 'url': 'https://www.weatherapi.com/', 'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.775, 'lon': -122.4183, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1730780454, 'localtime': '2024-11-04 20:20'}, 'current': {'last_updated_epoch': 1730780100, 'last_updated': '2024-11-04 20:15', 'temp_c': 14.4, 'temp_f': 57.9, 'is_day': 0, 'condition': {'text': 'Clear', 'icon': '//cdn.weatherapi.com/weather/64x64/night/113.png', 'code': 1000}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 255, 'wind_dir': 'WSW', 'pressure_mb': 1020.0, 'pressure_in': 30.12, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 70, 'cloud': 0, 'feelslike_c': 14.4, 'feelslike_f': 58.0, 'windchill_c': 14.9, 'windchill_f': 58.8, 'heatindex_c': 14.9, 'heatindex_f': 58.8, 'dewpoint_c': 10.5, 'dewpoint_f': 50.8, 'vis_km': 16.0, 'vis_miles': 9.0, 'uv': 0.0, 'gust_mph': 8.5, 'gust_kph': 13.6}}", 'score': 0.9867812, 'raw_content': None}, {'title': 'Weather in San Francisco in May 2024', 'url': 'https://world-weather.info/forecast/usa/san_francisco/may-2024/', 'content': 'Detailed ⚡ San Francisco Weather Forecast for May 2024 - day/night 🌡️ temperatures, precipitations - World-Weather.info. Add the current city. Search. Weather; Archive; Widgets °F. World; United States; California; Weather in San Francisco; ... 11 +66° +55° 12 +63° +54° 13', 'score': 0.9820826, 'raw_content': None}], 'response_time': 3.23}),
AIMessage(content='The current weather in San Francisco is clear with a temperature of 14.4°C (57.9°F). It is night time and the wind is coming from the west-southwest direction at a speed of 6.5 km/h (4.0 mph). The humidity is 70% and there are no clouds. The visibility is 16.0 km (9.0 miles) and the UV index is 0.0. Please note that the information provided is based on the latest data available at the time of the search.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 113, 'prompt_tokens': 689, 'total_tokens': 802, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-279498d6-abb1-4ebc-a883-ba8ed5bd87df-0', usage_metadata={'input_tokens': 689, 'output_tokens': 113, 'total_tokens': 802, 'input_token_details': {}, 'output_token_details': {}})]
分块返回结果,并让你能实时看到每个阶段的输出。
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather in sf?")]}
):
print(chunk)
print("----")
{'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_9166058413138208762', 'function': {'arguments': '{"query":"weather in San Francisco"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 144, 'total_tokens': 165, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-d1abd384-4c57-4b9e-874f-9f732c0a022b-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'weather in San Francisco'}, 'id': 'call_9166058413138208762', 'type': 'tool_call'}], usage_metadata={'input_tokens': 144, 'output_tokens': 21, 'total_tokens': 165, 'input_token_details': {}, 'output_token_details': {}})]}}
----
{'tools': {'messages': [ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.775, \'lon\': -122.4183, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1730780454, \'localtime\': \'2024-11-04 20:20\'}, \'current\': {\'last_updated_epoch\': 1730780100, \'last_updated\': \'2024-11-04 20:15\', \'temp_c\': 14.4, \'temp_f\': 57.9, \'is_day\': 0, \'condition\': {\'text\': \'Clear\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/night/113.png\', \'code\': 1000}, \'wind_mph\': 4.0, \'wind_kph\': 6.5, \'wind_degree\': 255, \'wind_dir\': \'WSW\', \'pressure_mb\': 1020.0, \'pressure_in\': 30.12, \'precip_mm\': 0.0, \'precip_in\': 0.0, \'humidity\': 70, \'cloud\': 0, \'feelslike_c\': 14.4, \'feelslike_f\': 58.0, \'windchill_c\': 14.9, \'windchill_f\': 58.8, \'heatindex_c\': 14.9, \'heatindex_f\': 58.8, \'dewpoint_c\': 10.5, \'dewpoint_f\': 50.8, \'vis_km\': 16.0, \'vis_miles\': 9.0, \'uv\': 0.0, \'gust_mph\': 8.5, \'gust_kph\': 13.6}}"}, {"url": "https://www.timeanddate.com/weather/usa/san-francisco/ext", "content": "San Francisco Extended Forecast with high and low temperatures. °F. Last 2 weeks of weather"}]', name='tavily_search_results_json', id='62a939dd-0143-4103-ac47-86ec8604f7d3', tool_call_id='call_9166058413138208762', artifact={'query': 'weather in San Francisco', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Weather in San Francisco', 'url': 'https://www.weatherapi.com/', 'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.775, 'lon': -122.4183, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1730780454, 'localtime': '2024-11-04 20:20'}, 'current': {'last_updated_epoch': 1730780100, 'last_updated': '2024-11-04 20:15', 'temp_c': 14.4, 'temp_f': 57.9, 'is_day': 0, 'condition': {'text': 'Clear', 'icon': '//cdn.weatherapi.com/weather/64x64/night/113.png', 'code': 1000}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 255, 'wind_dir': 'WSW', 'pressure_mb': 1020.0, 'pressure_in': 30.12, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 70, 'cloud': 0, 'feelslike_c': 14.4, 'feelslike_f': 58.0, 'windchill_c': 14.9, 'windchill_f': 58.8, 'heatindex_c': 14.9, 'heatindex_f': 58.8, 'dewpoint_c': 10.5, 'dewpoint_f': 50.8, 'vis_km': 16.0, 'vis_miles': 9.0, 'uv': 0.0, 'gust_mph': 8.5, 'gust_kph': 13.6}}", 'score': 0.967115, 'raw_content': None}, {'title': 'San Francisco, California, USA 14 day weather forecast - timeanddate.com', 'url': 'https://www.timeanddate.com/weather/usa/san-francisco/ext', 'content': 'San Francisco Extended Forecast with high and low temperatures. °F. Last 2 weeks of weather', 'score': 0.94834626, 'raw_content': None}], 'response_time': 3.15})]}}
----
{'agent': {'messages': [AIMessage(content='The current weather in San Francisco is clear with a temperature of 14.4°C (57.9°F). The wind is coming from the west-southwest direction at a speed of 6.5 km/h (4.0 mph). The humidity is 70%. For more information, you can check the weatherapi website: [weatherapi.com](https://www.weatherapi.com/).', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 83, 'prompt_tokens': 627, 'total_tokens': 710, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-5463f0e8-620d-4aec-b43d-ea0d752e8858-0', usage_metadata={'input_tokens': 627, 'output_tokens': 83, 'total_tokens': 710, 'input_token_details': {}, 'output_token_details': {}})]}}
----
7. 使用记忆功能存储上下文
这个agent是无状态的。这意味着它不会记住之前的互动。为了赋予它记忆,需要传入一个检查点(checkpointer)。在传入检查点时,我们还需要在调用agent时传入一个 thread_id(这样它就知道从哪个线程/对话中恢复)。
如果希望 Agent 保持上下文记忆(比如记住用户的名字或上次的对话内容),可以使用 MemorySaver。
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
agent_executor = create_react_agent(model, tools, checkpointer=memory)
config = {"configurable": {"thread_id": "abc123"}}
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="hi im bob!")]}, config
):
print(chunk)
print("----")
{'agent': {'messages': [AIMessage(content='Hello, Bob! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 13, 'prompt_tokens': 141, 'total_tokens': 154, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-a0f219cb-d188-460d-baa2-7c47c2c47187-0', usage_metadata={'input_tokens': 141, 'output_tokens': 13, 'total_tokens': 154, 'input_token_details': {}, 'output_token_details': {}})]}}
----
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats my name?")]}, config
):
print(chunk)
print("----")
{'agent': {'messages': [AIMessage(content='Your name is Bob.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 160, 'total_tokens': 166, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-ab5438ef-1bf0-4958-85f9-344138ec341f-0', usage_metadata={'input_tokens': 160, 'output_tokens': 6, 'total_tokens': 166, 'input_token_details': {}, 'output_token_details': {}})]}}
----
这样,Agent 在与用户的互动中会记住某些信息,提供更连贯的对话体验。
如果想开始一个新的对话,所要做的就是更改使用的 thread_id。
config = {"configurable": {"thread_id": "xyz123"}}
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats my name?")]}, config
):
print(chunk)
print("----")
{'agent': {'messages': [AIMessage(content="I am an AI language model, I don't know your name. Please tell me your name, I will call you that.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 28, 'prompt_tokens': 142, 'total_tokens': 170, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'glm-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-c481475f-2ec7-45db-b4db-8da624904530-0', usage_metadata={'input_tokens': 142, 'output_tokens': 28, 'total_tokens': 170, 'input_token_details': {}, 'output_token_details': {}})]}}
----
更多推荐
所有评论(0)