跳到主要內容
Open In ColabOpen on GitHub

建構代理 (Agent)

語言模型本身無法執行動作 - 它們僅輸出文本。LangChain 的一個重要用例是建立代理 (agent)代理 (Agent) 是使用 LLM 作為推理引擎的系統,以決定要採取哪些動作以及執行動作所需的輸入。執行動作後,結果可以回饋到 LLM 中,以確定是否需要更多動作,或者是否可以結束。這通常透過工具呼叫 (tool-calling) 來實現。

在本教學課程中,我們將建構一個可以與搜尋引擎互動的代理 (agent)。您將能夠向此代理 (agent) 提問,觀看它呼叫搜尋工具,並與它進行對話。

端到端代理 (Agent)

下面的程式碼片段代表一個功能齊全的代理 (agent),它使用 LLM 來決定要使用哪些工具。它配備了通用搜尋工具。它具有對話記憶 - 這意味著它可以作為多輪聊天機器人使用。

在本指南的其餘部分,我們將逐步介紹各個組件以及每個部分的作用 - 但如果您只想獲取一些程式碼並開始使用,請隨時使用這個!

# 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 notebooks,並假設讀者也使用。Jupyter notebooks 是學習如何使用 LLM 系統的完美互動式環境,因為通常情況下事情可能會出錯(意外輸出、API 故障等),而觀察這些情況是更好地理解如何使用 LLM 進行建構的好方法。

這個和其他教學課程也許在 Jupyter notebook 中執行最方便。請參閱此處以獲取有關如何安裝的說明。

安裝

若要安裝 LangChain,請執行

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

如需更多詳細資訊,請參閱我們的安裝指南

LangSmith

您使用 LangChain 建構的許多應用程式將包含多個步驟,其中包含多次 LLM 呼叫。隨著這些應用程式變得越來越複雜,能夠檢查鏈或代理 (agent) 內部究竟發生了什麼變得至關重要。執行此操作的最佳方法是使用 LangSmith

在上面的連結註冊後,請務必設定您的環境變數以開始記錄追蹤

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

或者,如果在 notebook 中,您可以使用以下程式碼設定它們

import getpass
import os

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

Tavily

我們將使用 Tavily(搜尋引擎)作為工具。為了使用它,您需要取得並設定 API 金鑰

export TAVILY_API_KEY="..."

或者,如果在 notebook 中,您可以使用以下程式碼設定它

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 搜尋工具。

這尚未呼叫該工具 - 它只是告訴我們去呼叫。為了實際呼叫它,我們需要建立我們的代理 (agent)。

建立代理 (Agent)

現在我們已經定義了工具和 LLM,我們可以建立代理 (agent)。我們將使用 LangGraph 來建構代理 (agent)。目前,我們正在使用高階介面來建構代理 (agent),但 LangGraph 的優點在於,這個高階介面由低階、高度可控的 API 支援,以防您想要修改代理 (agent) 邏輯。

現在,我們可以使用 LLM 和工具初始化代理 (agent)。

請注意,我們傳入的是 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

執行代理 (Agent)

我們現在可以使用一些查詢來執行代理 (agent) 了!請注意,目前這些都是無狀態查詢(它不會記住先前的互動)。請注意,代理 (agent) 將在互動結束時返回最終狀態(包括任何輸入,我們稍後將看到如何僅取得輸出)。

首先,讓我們看看當不需要呼叫工具時,它如何回應

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 追蹤,以確保它有效地呼叫了搜尋工具。

串流 (Streaming) 訊息

我們已經看到了如何使用 .invoke 呼叫代理 (agent) 以取得最終回應。如果代理 (agent) 執行多個步驟,這可能需要一段時間。為了顯示中間進度,我們可以串流 (stream) 回傳訊息,因為它們會發生。

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!

串流 (Streaming) tokens

除了串流 (stream) 回傳訊息外,串流 (stream) 回傳 tokens 也很有用。我們可以透過指定 stream_mode="messages" 來做到這一點。

::: note

下面我們使用 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!|

新增記憶體

如前所述,此代理 (agent) 是無狀態的。這表示它不記得先前的互動。為了給它記憶體,我們需要傳入 checkpointer。當傳入 checkpointer 時,我們還必須在調用代理 (agent) 時傳入 thread_id(以便它知道要從哪個 thread/對話恢復)。

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})]}}
----

結論

總結一下!在這個快速入門中,我們介紹了如何建立一個簡單的代理 (agent)。然後,我們展示了如何串流 (stream) 回傳回應 - 不僅包含中間步驟,還包含 tokens!我們還新增了記憶體,以便您可以與它們進行對話。代理 (Agent) 是一個複雜的主題,有很多東西要學習!

有關代理 (Agent) 的更多資訊,請查看 LangGraph 文件。它有自己的一組概念、教學課程和操作指南。


此頁面是否有幫助?