LangGraph 에이전트 사용

시작하기 전에

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

에이전트 인스턴스 가져오기

LanggraphAgent를 쿼리하려면 먼저 새 인스턴스를 만들거나 기존 인스턴스를 가져와야 합니다.

특정 리소스 ID에 해당하는 LanggraphAgent를 가져오려면 다음 안내를 따르세요.

Python용 Vertex AI SDK

다음 코드를 실행합니다.

import vertexai

client = vertexai.Client(  # For service interactions via client.agent_engines
    project="PROJECT_ID",
    location="LOCATION",
)

agent = client.agent_engines.get(name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

print(agent)

각 항목의 의미는 다음과 같습니다.

Python 요청 라이브러리

다음 코드를 실행합니다.

from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests

def get_identity_token():
    credentials, _ = google_auth.default()
    auth_request = google_requests.Request()
    credentials.refresh(auth_request)
    return credentials.token

response = requests.get(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
    headers={
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {get_identity_token()}",
    },
)

REST API

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID

Python용 Vertex AI SDK를 사용하는 경우 agent 객체는 다음을 포함하는 AgentEngine 클래스에 해당합니다.

  • 배포된 에이전트에 관한 정보가 포함된 agent.api_resource agent.operation_schemas()를 호출하여 에이전트가 지원하는 작업 목록을 반환할 수도 있습니다. 자세한 내용은 지원되는 작업을 참고하세요.
  • 동기 서비스 상호작용을 허용하는 agent.api_client
  • 비동기 서비스 상호작용을 허용하는 agent.async_api_client

이 섹션의 나머지 부분에서는 agent라는 이름의 AgentEngine 인스턴스가 있다고 가정합니다.

지원되는 작업

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= 인수를 사용하여 중단점을 설정할 수 있습니다.

from langchain.load import load as langchain_load

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 내에서 스레드 또는 체크포인트를 지정해야 합니다.

from langchain.load import load as langchain_load

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을 지정합니다.

from langchain.load import load as langchain_load

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로 에이전트를 쿼리하여 업데이트된 상태의 체크포인트로부터 재개할 수 있습니다.

from langchain.load import load as langchain_load

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.

다음 단계