Utilizzare un agente LangGraph

Oltre alle istruzioni generali per l'utilizzo di un agente, in questa pagina sono descritte le funzionalità specifiche di LanggraphAgent.

Prima di iniziare

Questo tutorial presuppone che tu abbia letto e seguito le istruzioni riportate in:

Operazioni supportate

Per LanggraphAgent sono supportate le seguenti operazioni:

  • query: per ricevere una risposta a una query in modo sincrono.
  • stream_query: per la visualizzazione progressiva di una risposta a una query.
  • get_state: per ottenere un checkpoint specifico.
  • get_state_history: per elencare i checkpoint di un thread.
  • update_state: per creare branche corrispondenti a diversi scenari.

Riprodurre in streaming una risposta a una query

LangGraph supporta più modalità di streaming. I principali sono:

  • values: questa modalità trasmette in streaming lo stato completo del grafo dopo la chiamata di ogni nodo.
  • updates: questa modalità trasmette in streaming gli aggiornamenti dello stato del grafo dopo l'esecuzione di ogni nodo.

Per trasmettere in streaming values (corrispondente allo stato completo del grafico):

for state_values in agent.stream_query(
    input=inputs,
    stream_mode="values",
    config={"configurable": {"thread_id": "streaming-thread-values"}},
):
    print(state_values)

Per trasmettere nuovamente updates (corrispondente agli aggiornamenti dello stato del grafico):

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

In LangGraph, un aspetto comune dell'intervento umano è aggiungere breakpoint per interrompere la sequenza di azioni dell'agente e consentire a un essere umano di riprendere il flusso in un secondo momento.

Rivedi

Puoi impostare i punti di interruzione utilizzando gli argomenti interrupt_before= o interrupt_after= quando chiami .query o .stream_query:

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

L'output sarà simile al seguente:

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

Approvazione

Per approvare la chiamata allo strumento generata e riprendere con il resto dell'esecuzione, devi passare None all'input e specificare il thread o il checkpoint all'interno del 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()

L'output sarà simile al seguente:

================================= Tool Message =================================
Name: get_exchange_rate

{"amount": 1.0, "base": "USD", "date": "2024-11-14", "rates": {"SEK": 11.0159}}

Cronologia

Per elencare tutti i checkpoint di un determinato thread, utilizza il metodo .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")

La risposta sarà simile alla seguente sequenza di output:

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?

Recuperare la configurazione di un passaggio

Per ottenere un checkpoint precedente, specifica checkpoint_id (e checkpoint_ns). Innanzitutto, torna al passaggio 1, quando è stata generata la chiamata allo strumento:

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)

L'output sarà simile al seguente:

{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
  'checkpoint_ns': '',
  'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}

Viaggio nel tempo

Per ottenere un checkpoint, puoi utilizzare il metodo .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()

Per impostazione predefinita, viene recuperato il checkpoint più recente (in base al timestamp). L'output sarà simile al seguente:

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.

Ottenere il checkpoint di una configurazione

Per una determinata configurazione (ad es. snapshot_config dalla configurazione di un passaggio), puoi ottenere il checkpoint corrispondente:

state = agent.get_state(config=snapshot_config)
print(f'step {state["metadata"]["step"]}: {state["config"]}')
state["values"]["messages"][-1].pretty_print()

L'output sarà simile al seguente:

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

Ripeti

Per riprodurre da un determinato stato, passa la configurazione dello stato (ad es. state["config"]) all'agente. La configurazione dello stato è un dizionario simile al seguente:

{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
  'checkpoint_ns': '',
  'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}

Per riprodurre da state["config"] (dove è stata generata una chiamata allo strumento), specifica None nell'input:

for state_values in agent.stream_query(
    input=None, # resume
    stream_mode="values",
    config=state["config"],
):
    langchain_load(state_values["messages"][-1]).pretty_print()

Il risultato sarà simile alla seguente sequenza di output:

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

Ramo

Puoi eseguire il branching dai checkpoint precedenti per provare scenari alternativi utilizzando il metodo .update_state:

branch_config = agent.update_state(
    config=state["config"],
    values={"messages": [last_message]}, # the update we want to make
)

print(branch_config)

L'output sarà simile al seguente:

{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
  'checkpoint_ns': '',
  'checkpoint_id': '1efa2e96-0560-62ce-8002-d1bb48a337bc'}}

Possiamo eseguire una query sull'agente con branch_config per riprendere dal checkpoint con lo stato aggiornato:

for state_values in agent.stream_query(
    input=None, # resume
    stream_mode="values",
    config=branch_config,
):
    langchain_load(state_values["messages"][-1]).pretty_print()

Il risultato sarà simile alla seguente sequenza di output:

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

Passaggi successivi