Sebelum memulai
Tutorial ini mengasumsikan bahwa Anda telah membaca dan mengikuti petunjuk dalam:
- Mengembangkan agen LangGraph: untuk mengembangkan
agentsebagai instanceLanggraphAgent. - Autentikasi pengguna untuk mengautentikasi sebagai pengguna guna membuat kueri agen.
- Impor dan inisialisasi SDK untuk menginisialisasi klien guna mendapatkan instance yang di-deploy (jika diperlukan).
Mendapatkan instance agen
Untuk membuat kueri LanggraphAgent, Anda harus
membuat instance baru atau
mendapatkan instance yang ada terlebih dahulu.
Untuk mendapatkan LanggraphAgent yang sesuai dengan ID resource tertentu:
Vertex AI SDK untuk Python
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)
dengan
PROJECT_IDadalah Google Cloud project ID yang digunakan untuk mengembangkan dan men-deploy agen, danLOCATIONadalah salah satu wilayah 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 Vertex AI SDK untuk Python, 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 melakukan streaming respons terhadap 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.
Mengalirkan respons terhadap 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 human-in-the-loop adalah menambahkan titik henti sementara untuk menghentikan urutan tindakan oleh agen, dan membuat manusia melanjutkan alur pada waktu yang akan datang.
Ulasan
Anda dapat menyetel titik henti menggunakan argumen interrupt_before= atau interrupt_after=
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()
Output-nya akan terlihat mirip dengan berikut ini:
================================== 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 titik pemeriksaan 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 ini:
================================= 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 dari 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, 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 ini:
{'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, fungsi ini akan mendapatkan checkpoint terbaru (berdasarkan stempel waktu). Outputnya akan terlihat mirip dengan berikut ini:
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 mirip dengan berikut ini:
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 dalam 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()
Hal 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 titik pemeriksaan 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 mirip dengan berikut ini:
{'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 titik pemeriksaan 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()
Hal 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.