Sebelum memulai
Tutorial ini mengasumsikan bahwa Anda telah membaca dan mengikuti petunjuk di:
- Membuat agen LangGraph: untuk membuat
agentsebagai instanceLanggraphAgent. - Autentikasi pengguna untuk mengautentikasi sebagai pengguna untuk mengkueri agen.
- Mengimpor dan menginisialisasi SDK untuk menginisialisasi klien guna mendapatkan instance yang di-deploy (jika diperlukan).
Mendapatkan instance agen
Untuk mengkueri LanggraphAgent, Anda harus terlebih dahulu
membuat instance baru atau
mendapatkan instance yang ada.
Untuk mendapatkan LanggraphAgent yang sesuai dengan ID resource tertentu:
SDK Platform Agen
Jalankan kode berikut:
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)
di mana
PROJECT_IDadalah Google Cloud ID project tempat Anda membuat dan men-deploy agen, danLOCATIONadalah salah satu region yang didukung.RESOURCE_IDadalah ID agen yang di-deploy sebagaireasoningEngineresource.
Library permintaan Python
Jalankan kode berikut:
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_IDSaat menggunakan SDK Platform Agen, objek agent sesuai dengan class
AgentEngine yang berisi hal berikut:
agent.api_resourcedengan informasi tentang agen yang di-deploy. Anda juga dapat memanggilagent.operation_schemas()untuk menampilkan daftar operasi yang didukung agen. Lihat Operasi yang didukung untuk mengetahui detailnya.agent.api_clientyang memungkinkan interaksi layanan sinkronagent.async_api_clientyang memungkinkan interaksi layanan asinkron
Bagian selanjutnya mengasumsikan bahwa Anda memiliki instance AgentEngine, yang diberi nama agent.
Operasi yang didukung
Operasi berikut didukung untuk LanggraphAgent:
query: untuk mendapatkan respons terhadap kueri secara sinkron.stream_query: untuk menstreaming respons terhadap kueri.get_state: untuk mendapatkan checkpoint tertentu.get_state_history: untuk mencantumkan checkpoint thread.update_state: untuk membuat cabang yang sesuai dengan skenario yang berbeda.
Menstreaming respons terhadap kueri
Untuk menstreaming respons, gunakan metode LanggraphAgent.stream_query.
LangGraph mendukung beberapa mode streaming. Mode utamanya adalah:
values: Mode ini menstreaming status lengkap grafik setelah setiap node dipanggil.updates: Mode ini menstreaming update ke status grafik setelah setiap node dipanggil.
Untuk menstreaming 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 menstreaming kembali updates (sesuai dengan update ke 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 interaksi manusia adalah menambahkan breakpoint untuk mengganggu urutan tindakan oleh agen, dan meminta manusia melanjutkan alur pada waktu berikutnya.
Ulasan
Anda dapat menetapkan breakpoint menggunakan interrupt_before= atau interrupt_after=
argumen saat memanggil .query atau .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()
Outputnya akan terlihat mirip dengan 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 eksekusi lainnya, Anda meneruskan None ke input, dan menentukan thread atau checkpoint di dalam 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()
Outputnya akan terlihat mirip dengan berikut:
================================= Tool Message =================================
Name: get_exchange_rate
{"amount": 1.0, "base": "USD", "date": "2024-11-14", "rates": {"SEK": 11.0159}}
Histori
Untuk mencantumkan semua checkpoint thread tertentu, gunakan metode 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")
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 checkpoint sebelumnya, tentukan checkpoint_id (dan checkpoint_ns). Pertama, mundur 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 mirip dengan berikut:
{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
'checkpoint_ns': '',
'checkpoint_id': '1efa2e95-cc7f-6d68-8001-1f6b5e57c456'}}
Perjalanan waktu
Untuk mendapatkan checkpoint, gunakan metode 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()
Secara default, checkpoint terbaru (berdasarkan stempel waktu) akan didapatkan. Outputnya akan terlihat mirip dengan 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 checkpoint 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 mirip dengan 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 agen. 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 di input:
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()
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.
Percabangan
Anda dapat membuat cabang dari checkpoint sebelumnya untuk mencoba skenario alternatif menggunakan metode
LanggraphAgent.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 mirip dengan berikut:
{'configurable': {'thread_id': 'human-in-the-loop-deepdive',
'checkpoint_ns': '',
'checkpoint_id': '1efa2e96-0560-62ce-8002-d1bb48a337bc'}}
Kita dapat mengkueri agen dengan branch_config untuk melanjutkan dari checkpoint dengan status yang diperbarui:
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()
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.