Menggunakan aplikasi LangGraph

Selain petunjuk umum untuk menggunakan aplikasi, halaman ini menjelaskan fitur yang khusus untuk LanggraphAgent.

Sebelum memulai

Tutorial ini mengasumsikan bahwa Anda telah membaca dan mengikuti petunjuk di:

Operasi yang didukung

Operasi berikut didukung untuk LanggraphAgent:

  • query: untuk mendapatkan respons kueri secara sinkron.
  • stream_query: untuk melakukan streaming respons ke kueri.
  • get_state: untuk mendapatkan titik pemeriksaan tertentu.
  • get_state_history: untuk mencantumkan titik pemeriksaan thread.
  • update_state: untuk membuat cabang yang sesuai dengan berbagai skenario.

Menstreaming respons ke kueri

LangGraph mendukung beberapa mode streaming. Yang utama adalah:

  • values: Mode ini melakukan streaming status lengkap grafik setelah setiap node dipanggil.
  • updates: Mode ini melakukan streaming pembaruan ke status grafik setelah setiap node dipanggil.

Untuk melakukan streaming kembali values (sesuai dengan status lengkap grafik):

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

Untuk melakukan streaming kembali updates (sesuai dengan pembaruan pada status grafik):

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

Memerlukan interaksi manusia

Di LangGraph, aspek umum dari human-in-the-loop adalah menambahkan titik henti sementara untuk mengganggu urutan tindakan oleh aplikasi, dan meminta manusia melanjutkan alur pada lain waktu.

Ulasan

Anda dapat menetapkan titik henti sementara menggunakan argumen interrupt_before= atau interrupt_after= saat memanggil .query atau .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()

Outputnya akan terlihat seperti berikut:

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

Persetujuan

Untuk menyetujui panggilan alat yang dihasilkan dan melanjutkan dengan eksekusi lainnya, Anda meneruskan None ke input, dan menentukan thread atau titik pemeriksaan di dalam 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()

Outputnya akan terlihat seperti berikut:

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

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

Histori

Untuk mencantumkan semua titik pemeriksaan thread tertentu, gunakan metode .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")

Responsnya akan mirip dengan urutan output berikut:

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?

Mendapatkan konfigurasi langkah

Untuk mendapatkan titik pemeriksaan sebelumnya, tentukan checkpoint_id (dan checkpoint_ns). Pertama, putar balik ke langkah 1, saat panggilan alat dibuat:

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)

Outputnya akan terlihat seperti berikut:

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

Perjalanan waktu

Untuk mendapatkan titik pemeriksaan, metode .get_state dapat digunakan:

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

Secara default, metode ini mendapatkan checkpoint terbaru (menurut stempel waktu). Outputnya akan terlihat seperti berikut:

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.

Mendapatkan checkpoint konfigurasi

Untuk konfigurasi tertentu (misalnya, snapshot_config dari konfigurasi langkah), Anda bisa mendapatkan titik pemeriksaan yang sesuai:

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

Outputnya akan terlihat seperti berikut:

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

Putar ulang

Untuk memutar ulang dari status tertentu, teruskan konfigurasi status (yaitu state["config"]) ke aplikasi. Konfigurasi status adalah dict yang terlihat seperti berikut:

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

Untuk memutar ulang dari state["config"] (tempat panggilan alat dibuat), tentukan None dalam 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()

Tindakan ini akan menghasilkan sesuatu yang mirip dengan urutan output berikut:

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

Cabang

Anda dapat membuat cabang dari checkpoint sebelumnya untuk mencoba skenario alternatif menggunakan metode .update_state:

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

print(branch_config)

Outputnya akan terlihat seperti berikut:

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

Kita dapat mengkueri aplikasi dengan branch_config untuk melanjutkan dari titik pemeriksaan dengan status yang diperbarui:

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

Tindakan ini akan menghasilkan sesuatu yang mirip dengan urutan output berikut:

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

Langkah berikutnya