Skip to main content
Open In ColabOpen on GitHub

构建一个代理

仅靠语言模型本身无法采取行动——它们只会输出文本。 LangChain的一个重要用例是创建代理代理是利用大语言模型作为推理引擎,以决定采取哪些操作以及执行操作所需的输入的系统。 在执行操作后,结果可以反馈给大语言模型,以判断是否需要更多操作,或者是否可以结束。这通常通过工具调用实现。

在本教程中,我们将构建一个能够与搜索引擎交互的智能体。您将能够向该智能体提出问题,观察它调用搜索工具的过程,并与它进行对话。

端到端代理

下面的代码片段代表了一个功能完整的代理,它使用大型语言模型来决定使用哪些工具。该代理配备了一个通用的搜索工具,并具备对话记忆功能,意味着它可以作为多轮对话机器人使用。

在本指南的其余部分,我们将逐一介绍各个组件及其功能——但如果你只想快速获取一些代码并开始使用,欢迎直接使用以下内容!

# Import relevant functionality
from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent

# Create the agent
memory = MemorySaver()
model = ChatAnthropic(model_name="claude-3-sonnet-20240229")
search = TavilySearchResults(max_results=2)
tools = [search]
agent_executor = create_react_agent(model, tools, checkpointer=memory)
# Use the agent
config = {"configurable": {"thread_id": "abc123"}}
for step in agent_executor.stream(
{"messages": [HumanMessage(content="hi im bob! and i live in sf")]},
config,
stream_mode="values",
):
step["messages"][-1].pretty_print()
================================ Human Message =================================

hi im bob! and i live in sf
================================== Ai Message ==================================

Hello Bob! Since you didn't ask a specific question, I don't need to use any tools right now. I'm an AI assistant created by Anthropic to be helpful, honest, and harmless. Feel free to ask me anything and I'll do my best to provide a useful response or look up information using my capabilities.
for step in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather where I live?")]},
config,
stream_mode="values",
):
step["messages"][-1].pretty_print()
================================ Human Message =================================

whats the weather where I live?
================================== Ai Message ==================================

[{'text': 'To get the current weather for your location in San Francisco, I can use the tavily_search_results_json tool:', 'type': 'text'}, {'id': 'toolu_01AKa2MErG1CU3zRiGsvpBud', 'input': {'query': 'san francisco weather'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01AKa2MErG1CU3zRiGsvpBud)
Call ID: toolu_01AKa2MErG1CU3zRiGsvpBud
Args:
query: san francisco weather
================================= Tool Message =================================
Name: tavily_search_results_json

[{"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': 1739994486, 'localtime': '2025-02-19 11:48'}, 'current': {'last_updated_epoch': 1739994300, 'last_updated': '2025-02-19 11:45', 'temp_c': 13.3, 'temp_f': 55.9, 'is_day': 1, 'condition': {'text': 'Light rain', 'icon': '//cdn.weatherapi.com/weather/64x64/day/296.png', 'code': 1183}, 'wind_mph': 5.8, 'wind_kph': 9.4, 'wind_degree': 195, 'wind_dir': 'SSW', 'pressure_mb': 1023.0, 'pressure_in': 30.2, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 87, 'cloud': 100, 'feelslike_c': 12.7, 'feelslike_f': 54.8, 'windchill_c': 9.1, 'windchill_f': 48.4, 'heatindex_c': 10.2, 'heatindex_f': 50.3, 'dewpoint_c': 9.8, 'dewpoint_f': 49.7, 'vis_km': 4.0, 'vis_miles': 2.0, 'uv': 1.4, 'gust_mph': 8.9, 'gust_kph': 14.4}}"}, {"url": "https://world-weather.info/forecast/usa/san_francisco/february-2025/", "content": "Weather in San Francisco in February 2025 (California) - Detailed Weather Forecast for a Month Weather World Weather in San Francisco Weather in San Francisco in February 2025 San Francisco Weather Forecast for February 2025, is based on previous years' statistical data. +59°+50° +59°+52° +59°+50° +61°+52° +59°+50° +61°+50° +61°+52° +63°+52° +61°+52° +61°+50° +61°+50° +61°+50° +59°+50° +59°+50° +61°+50° +61°+52° +59°+50° +59°+48° +57°+48° +59°+50° +59°+48° +59°+50° +57°+46° +61°+50° +61°+50° +59°+50° +59°+48° +59°+50° Extended weather forecast in San Francisco HourlyWeek10-Day14-Day30-DayYear Weather in large and nearby cities Weather in Washington, D.C.+41° Sacramento+55° Pleasanton+55° Redwood City+55° San Leandro+55° San Mateo+54° San Rafael+52° San Ramon+52° South San Francisco+54° Vallejo+50° Palo Alto+55° Pacifica+55° Berkeley+54° Castro Valley+55° Concord+52° Daly City+54° Noverd+52° Sign Hill+54° world's temperature today day day Temperature units"}]
================================== Ai Message ==================================

The search results provide the current weather conditions and forecast for San Francisco. According to the data from WeatherAPI, the current temperature in San Francisco is around 55°F (13°C) with light rain and winds around 6 mph. The extended forecast shows temperatures ranging from the upper 40s to low 60s Fahrenheit over the next few weeks.

So in summary, it's a cool, rainy day currently in San Francisco where you live, Bob. Let me know if you need any other details about the weather there!

设置

Jupyter Notebook

本指南(以及文档中的大多数其他指南)使用 Jupyter 笔记本,并假设读者也熟悉该工具。Jupyter 笔记本是学习如何使用大语言模型系统的理想交互环境,因为很多时候会出现问题(如意外输出、API 故障等),观察这些情况是更好地理解大语言模型开发的绝佳方式。

其他教程可能最方便在 Jupyter Notebook 中运行。有关安装说明,请参见 此处

安装

要安装 LangChain,请运行:

%pip install -U langchain-community langgraph langchain-anthropic tavily-python langgraph-checkpoint-sqlite

有关详细信息,请参阅我们的 安装指南

LangSmith

使用 LangChain 构建的许多应用程序都包含多个步骤,以及多次调用大型语言模型(LLM)。 随着这些应用程序变得越来越复杂,能够检查链或代理内部的具体情况变得至关重要。 实现这一点的最佳方式是使用 LangSmith

在您通过上方链接注册后,请确保设置您的环境变量以开始记录追踪信息:

export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."

或者,如果在笔记本中,你可以通过以下方式设置它们:

import getpass
import os

os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

Tavily

我们将使用 Tavily(一种搜索引擎)作为工具。 要使用它,您需要获取并设置一个API密钥:

export TAVILY_API_KEY="..."

或者,如果在笔记本中,可以使用以下方式设置:

import getpass
import os

os.environ["TAVILY_API_KEY"] = getpass.getpass()

定义工具

我们首先需要创建想要使用的工具。我们的主要工具选择将是Tavily——一种搜索引擎。LangChain中内置了工具,可轻松将Tavily搜索引擎用作工具。

from langchain_community.tools.tavily_search import TavilySearchResults

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]
API 参考:TavilySearchResults
[{'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': 1739993250, 'localtime': '2025-02-19 11:27'}, 'current': {'last_updated_epoch': 1739992500, 'last_updated': '2025-02-19 11:15', 'temp_c': 13.3, 'temp_f': 55.9, 'is_day': 1, 'condition': {'text': 'Light rain', 'icon': '//cdn.weatherapi.com/weather/64x64/day/296.png', 'code': 1183}, 'wind_mph': 5.8, 'wind_kph': 9.4, 'wind_degree': 195, 'wind_dir': 'SSW', 'pressure_mb': 1023.0, 'pressure_in': 30.2, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 87, 'cloud': 100, 'feelslike_c': 12.7, 'feelslike_f': 54.8, 'windchill_c': 9.1, 'windchill_f': 48.4, 'heatindex_c': 10.2, 'heatindex_f': 50.3, 'dewpoint_c': 9.8, 'dewpoint_f': 49.7, 'vis_km': 4.0, 'vis_miles': 2.0, 'uv': 1.4, 'gust_mph': 8.9, 'gust_kph': 14.4}}"}, {'url': 'https://weathershogun.com/weather/usa/ca/san-francisco/480/february/2025-02-19', 'content': 'San Francisco, California Weather: Wednesday, February 19, 2025. Cloudy weather, overcast skies with clouds. Day 61°. Night 43°.'}]

使用语言模型

接下来,让我们学习如何使用语言模型调用工具。LangChain 支持多种不同的语言模型,您可以随意互换使用——请在下面选择您想要使用的模型!

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-4", model_provider="openai")

您可以传入消息列表来调用语言模型。默认情况下,响应是一个 content 字符串。

from langchain_core.messages import HumanMessage

response = model.invoke([HumanMessage(content="hi!")])
response.content
API 参考:HumanMessage
'Hi there!'

现在我们可以看到启用此模型进行工具调用的效果。为了实现这一点,我们使用 .bind_tools 来让语言模型了解这些工具

model_with_tools = model.bind_tools(tools)

现在我们可以调用模型了。我们先用一条普通消息调用它,看看它的响应。我们可以查看 content 字段以及 tool_calls 字段。

response = model_with_tools.invoke([HumanMessage(content="Hi!")])

print(f"ContentString: {response.content}")
print(f"ToolCalls: {response.tool_calls}")
ContentString: Hello!
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': 'weather san francisco'}, 'id': 'toolu_01VTP7DUvSfgtYxsq9x4EwMp'}]

我们可以看到,现在没有文本内容,但有一个工具调用!它希望我们调用 Tavily Search 工具。

这还并没有调用该工具——它只是在告诉我们去调用。为了真正调用它,我们需要创建我们的代理。

创建代理

现在我们已经定义了工具和大语言模型,可以创建代理了。我们将使用 LangGraph 来构建代理。 目前,我们使用的是一个高级接口来构建代理,但 LangGraph 的优点在于,这个高级接口背后有一个低级别的、高度可控制的 API,以便在需要时修改代理逻辑。

现在,我们可以使用 LLM 和工具来初始化代理。

请注意,我们传入的是 model,而不是 model_with_tools。这是因为 create_react_agent 会在后台为我们调用 .bind_tools

from langgraph.prebuilt import create_react_agent

agent_executor = create_react_agent(model, tools)
API 参考:create_react_agent

运行代理

现在我们可以运行代理并进行一些查询了!请注意,目前这些查询都是< strong >无状态的(不会记住之前的交互)。请注意,代理将在交互结束时返回< strong >最终状态(包括所有输入,我们稍后会看到如何仅获取输出)。

首先,我们来看看它在不需要调用工具时的响应情况:

response = agent_executor.invoke({"messages": [HumanMessage(content="hi!")]})

response["messages"]
[HumanMessage(content='hi!', id='a820fcc5-9b87-457a-9af0-f21768143ee3'),
AIMessage(content='Hello!', response_metadata={'id': 'msg_01VbC493X1VEDyusgttiEr1z', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 264, 'output_tokens': 5}}, id='run-0e0ddae8-a85b-4bd6-947c-c36c857a4698-0', usage_metadata={'input_tokens': 264, 'output_tokens': 5, 'total_tokens': 269})]

为了确切了解幕后发生的情况(并确保它没有调用工具),我们可以查看 LangSmith 跟踪

现在让我们在一个示例中尝试一下,此时应该调用该工具

response = agent_executor.invoke(
{"messages": [HumanMessage(content="whats the weather in sf?")]}
)
response["messages"]
[HumanMessage(content='whats the weather in sf?', id='1d6c96bb-4ddb-415c-a579-a07d5264de0d'),
AIMessage(content=[{'id': 'toolu_01Y5EK4bw2LqsQXeaUv8iueF', 'input': {'query': 'weather in san francisco'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}], response_metadata={'id': 'msg_0132wQUcEduJ8UKVVVqwJzM4', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 269, 'output_tokens': 61}}, id='run-26d5e5e8-d4fd-46d2-a197-87b95b10e823-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'weather in san francisco'}, 'id': 'toolu_01Y5EK4bw2LqsQXeaUv8iueF'}], usage_metadata={'input_tokens': 269, 'output_tokens': 61, 'total_tokens': 330}),
ToolMessage(content='[{"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\': 1717238703, \'localtime\': \'2024-06-01 3:45\'}, \'current\': {\'last_updated_epoch\': 1717237800, \'last_updated\': \'2024-06-01 03:30\', \'temp_c\': 12.0, \'temp_f\': 53.6, \'is_day\': 0, \'condition\': {\'text\': \'Mist\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/night/143.png\', \'code\': 1030}, \'wind_mph\': 5.6, \'wind_kph\': 9.0, \'wind_degree\': 310, \'wind_dir\': \'NW\', \'pressure_mb\': 1013.0, \'pressure_in\': 29.92, \'precip_mm\': 0.0, \'precip_in\': 0.0, \'humidity\': 88, \'cloud\': 100, \'feelslike_c\': 10.5, \'feelslike_f\': 50.8, \'windchill_c\': 9.3, \'windchill_f\': 48.7, \'heatindex_c\': 11.1, \'heatindex_f\': 51.9, \'dewpoint_c\': 8.8, \'dewpoint_f\': 47.8, \'vis_km\': 6.4, \'vis_miles\': 3.0, \'uv\': 1.0, \'gust_mph\': 12.5, \'gust_kph\': 20.1}}"}, {"url": "https://www.timeanddate.com/weather/usa/san-francisco/hourly", "content": "Sun & Moon. Weather Today Weather Hourly 14 Day Forecast Yesterday/Past Weather Climate (Averages) Currently: 59 \\u00b0F. Passing clouds. (Weather station: San Francisco International Airport, USA). See more current weather."}]', name='tavily_search_results_json', id='37aa1fd9-b232-4a02-bd22-bc5b9b44a22c', tool_call_id='toolu_01Y5EK4bw2LqsQXeaUv8iueF'),
AIMessage(content='Based on the search results, here is a summary of the current weather in San Francisco:\n\nThe weather in San Francisco is currently misty with a temperature of around 53°F (12°C). There is complete cloud cover and moderate winds from the northwest around 5-9 mph (9-14 km/h). Humidity is high at 88%. Visibility is around 3 miles (6.4 km). \n\nThe results provide an hourly forecast as well as current conditions from a couple different weather sources. Let me know if you need any additional details about the San Francisco weather!', response_metadata={'id': 'msg_01BRX9mrT19nBDdHYtR7wJ92', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 920, 'output_tokens': 132}}, id='run-d0325583-3ddc-4432-b2b2-d023eb97660f-0', usage_metadata={'input_tokens': 920, 'output_tokens': 132, 'total_tokens': 1052})]

我们可以查看 LangSmith trace,以确保它能有效调用搜索工具。

流式消息

我们已经看到,代理可以通过调用 .invoke 来获取最终响应。如果代理执行多个步骤,这可能需要一段时间。为了显示中间进度,我们可以实时流式返回消息。

for step in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather in sf?")]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
================================ Human Message =================================

whats the weather in sf?
================================== Ai Message ==================================

[{'text': 'Okay, let me look up the current weather for San Francisco using a search engine:', 'type': 'text'}, {'id': 'toolu_01H1brh5EZpZqtqHBxkosPtN', 'input': {'query': 'san francisco weather'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01H1brh5EZpZqtqHBxkosPtN)
Call ID: toolu_01H1brh5EZpZqtqHBxkosPtN
Args:
query: san francisco weather
================================= Tool Message =================================
Name: tavily_search_results_json

[{"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': 1739994486, 'localtime': '2025-02-19 11:48'}, 'current': {'last_updated_epoch': 1739994300, 'last_updated': '2025-02-19 11:45', 'temp_c': 13.3, 'temp_f': 55.9, 'is_day': 1, 'condition': {'text': 'Light rain', 'icon': '//cdn.weatherapi.com/weather/64x64/day/296.png', 'code': 1183}, 'wind_mph': 5.8, 'wind_kph': 9.4, 'wind_degree': 195, 'wind_dir': 'SSW', 'pressure_mb': 1023.0, 'pressure_in': 30.2, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 87, 'cloud': 100, 'feelslike_c': 12.7, 'feelslike_f': 54.8, 'windchill_c': 9.1, 'windchill_f': 48.4, 'heatindex_c': 10.2, 'heatindex_f': 50.3, 'dewpoint_c': 9.8, 'dewpoint_f': 49.7, 'vis_km': 4.0, 'vis_miles': 2.0, 'uv': 1.4, 'gust_mph': 8.9, 'gust_kph': 14.4}}"}, {"url": "https://world-weather.info/forecast/usa/san_francisco/february-2025/", "content": "Weather in San Francisco in February 2025 (California) - Detailed Weather Forecast for a Month Weather World Weather in San Francisco Weather in San Francisco in February 2025 San Francisco Weather Forecast for February 2025, is based on previous years' statistical data. +59°+50° +59°+52° +59°+50° +61°+52° +59°+50° +61°+50° +61°+52° +63°+52° +61°+52° +61°+50° +61°+50° +61°+50° +59°+50° +59°+50° +61°+50° +61°+52° +59°+50° +59°+48° +57°+48° +59°+50° +59°+48° +59°+50° +57°+46° +61°+50° +61°+50° +59°+50° +59°+48° +59°+50° Extended weather forecast in San Francisco HourlyWeek10-Day14-Day30-DayYear Weather in large and nearby cities Weather in Washington, D.C.+41° Sacramento+55° Pleasanton+55° Redwood City+55° San Leandro+55° San Mateo+54° San Rafael+52° San Ramon+52° South San Francisco+54° Vallejo+50° Palo Alto+55° Pacifica+55° Berkeley+54° Castro Valley+55° Concord+52° Daly City+54° Noverd+52° Sign Hill+54° world's temperature today day day Temperature units"}]
================================== Ai Message ==================================

The search results provide details on the current weather conditions and forecast for San Francisco. Some key details:

- It is lightly raining in San Francisco right now, with a temperature around 55°F/13°C.
- The forecast for the rest of February 2025 shows daytime highs mostly in the upper 50s to low 60s F, with night lows in the upper 40s to low 50s F.
- Typical weather includes some rain, clouds, cool temperatures and breezy conditions.

So in summary, as is common for San Francisco in late winter, it is currently cool with light rain showers, and similar mild, unsettled weather is expected over the next couple weeks. Layers and a light jacket would be advisable for being outdoors. Let me know if you need any other details!

流式传输标记

除了流式返回消息外,流式返回标记也同样有用。 我们可以通过指定 stream_mode="messages" 来实现。

::: 注意

下方我们使用 message.text(),这需要 langchain-core>=0.3.37

:::

for step, metadata in agent_executor.stream(
{"messages": [HumanMessage(content="whats the weather in sf?")]},
stream_mode="messages",
):
if metadata["langgraph_node"] == "agent" and (text := step.text()):
print(text, end="|")


Base|d on the weather| search| results, here| are the key details| about the weather in| San Francisco:|

- The current temperature| in| San Francisco is aroun|d 55|-|56|°F (13|°|C).| Light| rain is occurring with| |100|% clou|d cover. |

-| Winds| are aroun|d 5-9| mph from| the south|-southwest.|

- The| forecast| for| the rest| of February| 2025 |shows da|ytime highs mostly| in the upper| 50s to| low| 60s°|F,| with overnight lows| in| the upper| 40s to| low| 50s°|F.|

-| Overall|, typical| cool| an|d show|ery late| winter weather is| expected in San Francisco| for the remainder| of February,| with a| mix| of rain| and dry| periods|.| Temperatures will be| season|able| for| this| time of year.|

So| in summary, San| Francisco is| experiencing light| rain an|d cool| temperatures currently, but| the late| winter forecast| shows typical mil|d and show|ery conditions| pers|isting through the en|d of the| month.| Let| me know if you| need any other| details about| the weather in the| city!|

添加内存

如前所述,此代理是无状态的。这意味着它不会记住之前的交互。为了赋予它记忆功能,我们需要传入一个检查点程序。在传入检查点程序时,调用代理时还必须传入一个 thread_id(以便它知道从哪个线程/对话中恢复)。

from langgraph.checkpoint.memory import MemorySaver

memory = MemorySaver()
API 参考: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! It's nice to meet you again.", response_metadata={'id': 'msg_013C1z2ZySagEFwmU1EsysR2', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 1162, 'output_tokens': 14}}, id='run-f878acfd-d195-44e8-9166-e2796317e3f8-0', usage_metadata={'input_tokens': 1162, 'output_tokens': 14, 'total_tokens': 1176})]}}
----
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="whats my name?")]}, config
):
print(chunk)
print("----")
{'agent': {'messages': [AIMessage(content='You mentioned your name is Bob when you introduced yourself earlier. So your name is Bob.', response_metadata={'id': 'msg_01WNwnRNGwGDRw6vRdivt6i1', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 1184, 'output_tokens': 21}}, id='run-f5c0b957-8878-405a-9d4b-a7cd38efe81f-0', usage_metadata={'input_tokens': 1184, 'output_tokens': 21, 'total_tokens': 1205})]}}
----

示例 LangSmith 跟踪

如果您想开始一段新的对话,只需更改使用的 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'm afraid I don't actually know your name. As an AI assistant without personal information about you, I don't have a specific name associated with our conversation.", response_metadata={'id': 'msg_01NoaXNNYZKSoBncPcLkdcbo', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 267, 'output_tokens': 36}}, id='run-c9f7df3d-525a-4d8f-bbcf-a5b4a5d2e4b0-0', usage_metadata={'input_tokens': 267, 'output_tokens': 36, 'total_tokens': 303})]}}
----

结论

就这样!在本快速入门中,我们介绍了如何创建一个简单的智能体。 我们还演示了如何流式返回响应——不仅包括中间步骤,还包括令牌! 我们还加入了记忆功能,让你可以与它们进行对话。 智能体是一个复杂的主题,有很多内容需要学习!

有关代理的更多信息,请查看 LangGraph 文档。它拥有自己的一套概念、教程和操操作指南。