שימוש בסוכן LangGraph

לפני שמתחילים

במדריך הזה אנחנו יוצאים מנקודת הנחה שקראתם את ההוראות במאמרים הבאים ופעלתם לפיהן:

אחזור מופע של סוכן

כדי לשלוח שאילתה ל-LanggraphAgent, צריך קודם ליצור מכונה חדשה או לקבל מכונה קיימת.

כדי לקבל את LanggraphAgent שמתאים למזהה משאב ספציפי:

Agent Platform 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()}",
    },
)

‫API בארכיטקטורת REST

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

כשמשתמשים ב-Agent Platform SDK, האובייקט agent תואם למחלקה AgentEngine שכוללת את המאפיינים הבאים:

  • agent.api_resource עם מידע על הסוכן שנפרס. אפשר גם לקרוא לפונקציה agent.operation_schemas() כדי להחזיר את רשימת הפעולות שהסוכן תומך בהן. פרטים נוספים זמינים במאמר בנושא פעולות נתמכות.
  • agent.api_client שמאפשרת אינטראקציות סינכרוניות עם שירותים
  • agent.async_api_client שמאפשרת אינטראקציות אסינכרוניות בין שירותים

בהמשך הקטע הזה נניח שיש לכם מכונת AgentEngine שנקראת agent.

פעולות נתמכות

הפעולות הבאות נתמכות ב-LanggraphAgent:

  • query: כדי לקבל תשובה לשאילתה באופן סינכרוני.
  • stream_query: להצגת תשובה לשאילתה באופן שוטף.
  • get_state: כדי לקבל נקודת ביקורת ספציפית.
  • get_state_history: כדי להציג את נקודות הבדיקה של שרשור.
  • update_state: ליצירת ענפים שתואמים לתרחישים שונים.

הזרמת תשובה לשאילתה

כדי להזרים תשובה, משתמשים בשיטה LanggraphAgent.stream_query.

‫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)

האדם שבתהליך

ב-LangGraph, היבט נפוץ של human-in-the-loop הוא הוספת נקודות עצירה כדי להפריע לרצף הפעולות של הסוכן, ולאפשר לאדם להמשיך את התהליך בשלב מאוחר יותר.

בדיקה

אפשר להגדיר נקודות עצירה באמצעות הארגומנטים interrupt_before= או interrupt_after= כשקוראים לפונקציה .query או .stream_query:

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

היסטוריה

כדי להציג רשימה של כל נקודות הבדיקה של שרשור נתון, משתמשים בשיטה LanggraphAgent.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'}}

מסע בזמן

כדי לקבל נקודת ביקורת, משתמשים בשיטה LanggraphAgent.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.

הסתעפות

אפשר ליצור הסתעפות מנקודות ציון קודמות כדי לנסות תרחישים חלופיים באמצעות ה-method‏ LanggraphAgent.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.

המאמרים הבאים