LangChain 初探
LangChain 是一个可以调用搜索引擎(及其他工具)的智能体。
-
安装依赖:
pip install langgraph langchain-tavily langgraph-checkpoint-sqlite langchain-anthropic -
在
.env中设置环境变量:ANTHROPIC_API_KEY='sk-ant-api03-XXX' TAVILY_API_KEY='tvly-dev-XXX' -
构建智能体:
from langchain.chat_models import init_chat_model from langchain_tavily import TavilySearch from langgraph.checkpoint.memory import MemorySaver from langgraph.prebuilt import create_react_agent from dotenv import load_dotenv load_dotenv() # 构建智能体 memory = MemorySaver() # 记忆 model = init_chat_model("anthropic:claude-3-5-sonnet-latest") # 模型 search = TavilySearch(max_results=2) tools = [search] # 工具 agent_executor = create_react_agent(model, tools, checkpointer=memory) # 智能体构建智能体的三要素:记忆,模型,工具
-
使用智能体:
config = {"configurable": {"thread_id": "abc123"}} # 指定一个 thread 以保留记忆 input_message = { "role": "user", "content": "Hi, I'm Bob and I life in SF.", } for step in agent_executor.stream( {"messages": [input_message]}, config, stream_mode="values" ): step["messages"][-1].pretty_print()================================ Human Message ================================= Hi, I'm Bob and I life in SF. ================================== Ai Message ================================== Hello Bob! Nice to meet you. While you've shared that you live in San Francisco, you haven't asked a specific question or made a request that I can help you with. What would you like to know or discuss? I have access to search capabilities that can help find information about various topics, so please feel free to ask any question you have. -
测试智能体的记忆以及调用工具的能力:
input_message = { "role": "user", "content": "What's the weather where I live?", } for step in agent_executor.stream( {"messages": [input_message]}, config, stream_mode="values" ): step["messages"][-1].pretty_print()================================ Human Message ================================= What's the weather where I live? ================================== Ai Message ================================== [{'text': 'Let me search for current weather information in San Francisco for you.', 'type': 'text'}, {'id': 'toolu_01V2wZsDwMypWuNgp9icgczW', 'input': {'query': 'current weather San Francisco CA'}, 'name': 'tavily_search', 'type': 'tool_use'}] Tool Calls: tavily_search (toolu_01V2wZsDwMypWuNgp9icgczW) Call ID: toolu_01V2wZsDwMypWuNgp9icgczW Args: query: current weather San Francisco CA ================================= Tool Message ================================= Name: tavily_search {"query": "current weather San Francisco CA", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "Weather in San Francisco, CA", "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': 1750963955, 'localtime': '2025-06-26 11:52'}, 'current': {'last_updated_epoch': 1750963500, 'last_updated': '2025-06-26 11:45', 'temp_c': 14.4, 'temp_f': 57.9, 'is_day': 1, 'condition': {'text': 'Partly cloudy', 'icon': '//cdn.weatherapi.com/weather/64x64/day/116.png', 'code': 1003}, 'wind_mph': 5.8, 'wind_kph': 9.4, 'wind_degree': 243, 'wind_dir': 'WSW', 'pressure_mb': 1016.0, 'pressure_in': 30.0, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 81, 'cloud': 75, 'feelslike_c': 14.0, 'feelslike_f': 57.1, 'windchill_c': 11.2, 'windchill_f': 52.1, 'heatindex_c': 12.0, 'heatindex_f': 53.5, 'dewpoint_c': 10.9, 'dewpoint_f': 51.7, 'vis_km': 16.0, 'vis_miles': 9.0, 'uv': 6.9, 'gust_mph': 7.3, 'gust_kph': 11.8}}", "score": 0.9094264, "raw_content": null}, {"title": "SAN FRANCISCO DOWNTOWN (SFOC1) - National Weather Service", "url": "https://forecast.weather.gov/MapClick.php?FcstType=text&lat=37.775&lg=english&lon=-122.418", "content": "Current conditions at SAN FRANCISCO DOWNTOWN (SFOC1) Lat: 37.77056°NLon: 122.42694°WElev: 150.0ft. NA. 54°F. 12°C. ... San Francisco CA 37.77°N 122.41°W (Elev. 131 ft) Last Update: 2:15 am PDT Jun 20, 2025. Forecast Valid: 9am PDT Jun 20, 2025-6pm PDT Jun 26, 2025 . Forecast Discussion . Additional Resources. Radar & Satellite Image", "score": 0.86928266, "raw_content": null}], "response_time": 2.07} ================================== Ai Message ================================== Based on the search results, here's the current weather in San Francisco: The temperature is around 58°F (14.4°C) with partly cloudy conditions. The humidity is at 81% with light winds blowing at about 6 mph from the west-southwest direction. The "feels like" temperature is about 57°F (14°C). Visibility is good at about 9 miles. This is quite typical weather for San Francisco, with its characteristic mild temperatures and marine influence. Would you like to know any specific details about the weather or would you like a forecast for the coming days?可以看到智能体记住了我们之前提到的住址,并查询了住址的天气。

浙公网安备 33010602011771号