LangGraph 애플리케이션 사용

이 페이지에서는 애플리케이션 사용에 관한 일반적인 안내 외에도 LanggraphAgent에만 해당하는 기능을 설명합니다.

시작하기 전에

이 튜토리얼에서는 다음 안내를 읽고 따랐다고 가정합니다.

지원되는 작업

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에서 사람의 개입이 필요한 일반적인 측면은 중단점을 추가하여 애플리케이션의 작업 시퀀스를 중단하고 나중에 사람이 흐름을 재개하도록 하는 것입니다.

검토

.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.

다음 단계