이 페이지에서는 에이전트 사용을 위한 일반 안내 외에도 LanggraphAgent
와 관련된 기능을 설명합니다.
시작하기 전에
이 튜토리얼에서는 사용자가 다음 안내를 읽고 따랐다고 가정합니다.
- LangGraph 에이전트 개발:
LanggraphAgent
인스턴스로agent
를 개발합니다. - 사용자 인증: 에이전트 쿼리를 위해 사용자로 인증을 수행합니다.
지원되는 작업
LanggraphAgent
에 지원되는 작업은 다음과 같습니다.
query
: 쿼리에 대한 응답을 동기적으로 가져옵니다.stream_query
: 쿼리에 대한 응답을 스트리밍합니다.get_state
: 특정 체크포인트를 가져옵니다.get_state_history
: 스레드의 체크포인트를 나열합니다.update_state
: 다양한 시나리오에 해당하는 브랜치를 만듭니다.
쿼리에 대한 응답 스트리밍
LangGraph는 여러 스트리밍 모드를 지원합니다. 주요 항목은 다음과 같습니다.
values
: 이 모드는 각 노드가 호출된 후 그래프의 전체 상태를 스트리밍합니다.updates
: 이 모드는 각 노드가 호출된 후 그래프 상태에 대한 업데이트를 스트리밍합니다.
그래프 전체 상태에 따라 values
를 스트리밍하려면:
for state_values in agent.stream_query(
input=inputs,
stream_mode="values",
config={"configurable": {"thread_id": "streaming-thread-values"}},
):
print(state_values)
그래프 상태의 업데이트에 따라 updates
를 스트리밍하려면:
for state_updates in agent.stream_query(
input=inputs,
stream_mode="updates",
config={"configurable": {"thread_id": "streaming-thread-updates"}},
):
print(state_updates)
인간 참여형(Human In The Loop)
LangGraph에서 인간 참여형(Human In The Loop)의 일반적인 특성은 에이전트의 작업 시퀀스 중단을 위해 중단점을 추가하고 인간이 이후 시점에 흐름을 재개하도록 하는 것입니다.
검토
.query
또는 .stream_query
를 호출할 때 interrupt_before=
또는 interrupt_after=
인수를 사용하여 중단점을 설정할 수 있습니다.
response = agent.query(
input=inputs,
interrupt_before=["tools"], # after generating the function call, before invoking the function
interrupt_after=["tools"], # after getting a function response, before moving on
config={"configurable": {"thread_id": "human-in-the-loop-deepdive"}},
)
langchain_load(response['messages'][-1]).pretty_print()
출력은 다음과 비슷합니다.
================================== Ai Message ==================================
Tool Calls:
get_exchange_rate (12610c50-4465-4296-b1f3-d751ec959fd5)
Call ID: 12610c50-4465-4296-b1f3-d751ec959fd5
Args:
currency_from: USD
currency_to: SEK
승인
생성된 도구 호출 호출을 승인하고 나머지 실행을 계속하려면 None
을 입력에 전달하고 config
내에서 스레드 또는 체크포인트를 지정해야 합니다.
response = agent.query(
input=None, # Continue with the function call
interrupt_before=["tools"], # after generating the function call, before invoking the function
interrupt_after=["tools"], # after getting a function response, before moving on
config={"configurable": {"thread_id": "human-in-the-loop-deepdive"}},
)
langchain_load(response['messages'][-1]).pretty_print()
출력은 다음과 비슷합니다.
================================= Tool Message =================================
Name: get_exchange_rate
{"amount": 1.0, "base": "USD", "date": "2024-11-14", "rates": {"SEK": 11.0159}}
기록
지정된 스레드의 모든 체크포인트를 나열하려면 .get_state_history
메서드를 사용합니다.
for state_snapshot in agent.get_state_history(
config={"configurable": {"thread_id": "human-in-the-loop-deepdive"}},
):
if state_snapshot["metadata"]["step"] >= 0:
print(f'step {state_snapshot["metadata"]["step"]}: {state_snapshot["config"]}')
state_snapshot["values"]["messages"][-1].pretty_print()
print("\n")
응답은 다음 출력 시퀀스와 비슷합니다.
step 3: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-ded5-67e0-8003-2d34e04507f5'}}
================================== Ai Message ==================================
The exchange rate from US dollars to Swedish krona is 1 USD to 11.0159 SEK.
step 2: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-d189-6a77-8002-5dbe79e2ce58'}}
================================= Tool Message =================================
Name: get_exchange_rate
{"amount": 1.0, "base": "USD", "date": "2024-11-14", "rates": {"SEK": 11.0159}}
step 1: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}
================================== Ai Message ==================================
Tool Calls:
get_exchange_rate (12610c50-4465-4296-b1f3-d751ec959fd5)
Call ID: 12610c50-4465-4296-b1f3-d751ec959fd5
Args:
currency_from: USD
currency_to: SEK
step 0: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-c2e4-6f3c-8000-477fd654cb53'}}
================================ Human Message =================================
What is the exchange rate from US dollars to Swedish currency?
단계의 구성 가져오기
이전 체크포인트를 가져오려면 checkpoint_id
(및 checkpoint_ns
)를 지정합니다. 먼저 도구 호출이 생성된 1단계로 돌아갑니다.
snapshot_config = {}
for state_snapshot in agent.get_state_history(
config={"configurable": {"thread_id": "human-in-the-loop-deepdive"}},
):
if state_snapshot["metadata"]["step"] == 1:
snapshot_config = state_snapshot["config"]
break
print(snapshot_config)
출력은 다음과 비슷합니다.
{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
'checkpoint_ns': '',
'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}
시간 이동
체크포인트를 가져오려면 .get_state
메서드를 사용할 수 있습니다.
# By default, it gets the latest state [unless (checkpoint_ns, checkpoint_id) is specified]
state = agent.get_state(config={"configurable": {
"thread_id": "human-in-the-loop-deepdive",
}})
print(f'step {state["metadata"]["step"]}: {state["config"]}')
state["values"]["messages"][-1].pretty_print()
기본적으로 최신 체크포인트(타임스탬프 기준)를 가져옵니다. 출력은 다음과 비슷합니다.
step 3: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-ded5-67e0-8003-2d34e04507f5'}}
================================== Ai Message ==================================
The exchange rate from US dollars to Swedish krona is 1 USD to 11.0159 SEK.
구성의 체크포인트 가져오기
특정 구성(예: 단계의 구성의 snapshot_config
)에 대해 해당 체크포인트를 가져올 수 있습니다.
state = agent.get_state(config=snapshot_config)
print(f'step {state["metadata"]["step"]}: {state["config"]}')
state["values"]["messages"][-1].pretty_print()
출력은 다음과 비슷합니다.
step 1: {'configurable': {'thread_id': 'human-in-the-loop-deepdive', 'checkpoint_ns': '', 'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}
================================== Ai Message ==================================
Tool Calls:
get_exchange_rate (12610c50-4465-4296-b1f3-d751ec959fd5)
Call ID: 12610c50-4465-4296-b1f3-d751ec959fd5
Args:
currency_from: USD
currency_to: SEK
재생
지정된 상태에서 재생하려면 상태 구성(즉, state["config"]
)을 에이전트에 전달합니다. 상태 구성은 다음과 비슷한 딕셔너리입니다.
{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
'checkpoint_ns': '',
'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}
도구 호출이 생성된 state["config"]
에서 재생하려면 입력에 None
을 지정합니다.
for state_values in agent.stream_query(
input=None, # resume
stream_mode="values",
config=state["config"],
):
langchain_load(state_values["messages"][-1]).pretty_print()
다음과 같은 출력 시퀀스와 비슷한 결과가 발생합니다.
================================== Ai Message ==================================
Tool Calls:
get_exchange_rate (12610c50-4465-4296-b1f3-d751ec959fd5)
Call ID: 12610c50-4465-4296-b1f3-d751ec959fd5
Args:
currency_from: USD
currency_to: SEK
================================= Tool Message =================================
Name: get_exchange_rate
{"amount": 1.0, "base": "USD", "date": "2024-11-14", "rates": {"SEK": 11.0159}}
================================== Ai Message ==================================
The exchange rate from US dollars to Swedish krona is 1 USD to 11.0159 SEK.
브랜칭
.update_state
메서드를 사용하여 대체 시나리오를 시도하도록 이전 체크포인트를 브랜칭할 수 있습니다.
branch_config = agent.update_state(
config=state["config"],
values={"messages": [last_message]}, # the update we want to make
)
print(branch_config)
출력은 다음과 비슷합니다.
{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
'checkpoint_ns': '',
'checkpoint_id': '1efa2e96-0560-62ce-8002-d1bb48a337bc'}}
branch_config
로 에이전트를 쿼리하여 업데이트된 상태의 체크포인트로부터 재개할 수 있습니다.
for state_values in agent.stream_query(
input=None, # resume
stream_mode="values",
config=branch_config,
):
langchain_load(state_values["messages"][-1]).pretty_print()
다음과 같은 출력 시퀀스와 비슷한 결과가 발생합니다.
================================== Ai Message ==================================
Tool Calls:
get_exchange_rate (12610c50-4465-4296-b1f3-d751ec959fd5)
Call ID: 12610c50-4465-4296-b1f3-d751ec959fd5
Args:
currency_date: 2024-09-01
currency_from: USD
currency_to: SEK
================================= Tool Message =================================
Name: get_exchange_rate
{"amount": 1.0, "base": "USD", "date": "2024-08-30", "rates": {"SEK": 10.2241}}
================================== Ai Message ==================================
The exchange rate from US dollars to Swedish krona on 2024-08-30 was 1 USD to 10.2241 SEK.