Questa pagina mostra come sviluppare un agente utilizzando il modello LangGraph specifico del framework (la classe LanggraphAgent
nell'SDK Vertex AI Python).
L'agente restituisce il tasso di cambio tra due valute in una data specificata.
Procedi nel seguente modo:
- Definisci e configura un modello
- Definire e utilizzare uno strumento
- (Facoltativo) Memorizza i checkpoint
- (Facoltativo) Personalizza il modello di prompt
- (Facoltativo) Personalizza l'orchestrazione
Prima di iniziare
Assicurati che l'ambiente sia configurato seguendo i passaggi descritti in Configurare l'ambiente.
Passaggio 1: Definisci e configura un modello
Definisci la versione del modello da utilizzare.
model = "gemini-2.0-flash"
(Facoltativo) Configura le impostazioni di sicurezza del modello. Per scoprire di più sulle opzioni disponibili per le impostazioni di sicurezza in Gemini, vedi Configurare gli attributi di sicurezza. Di seguito è riportato un esempio di come puoi configurare le impostazioni della sicurezza:
from langchain_google_vertexai import HarmBlockThreshold, HarmCategory
safety_settings = {
HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
}
(Facoltativo) Specifica i parametri del modello nel seguente modo:
model_kwargs = {
# temperature (float): The sampling temperature controls the degree of
# randomness in token selection.
"temperature": 0.28,
# max_output_tokens (int): The token limit determines the maximum amount of
# text output from one prompt.
"max_output_tokens": 1000,
# top_p (float): Tokens are selected from most probable to least until
# the sum of their probabilities equals the top-p value.
"top_p": 0.95,
# top_k (int): The next token is selected from among the top-k most
# probable tokens. This is not supported by all model versions. See
# https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/image-understanding#valid_parameter_values
# for details.
"top_k": None,
# safety_settings (Dict[HarmCategory, HarmBlockThreshold]): The safety
# settings to use for generating content.
# (you must create your safety settings using the previous step first).
"safety_settings": safety_settings,
}
Crea un LanggraphAgent
utilizzando le configurazioni del modello:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model, # Required.
model_kwargs=model_kwargs, # Optional.
)
Se esegui l'operazione in un ambiente interattivo (ad es. terminale o notebook Colab), puoi eseguire una query come passaggio di test intermedio:
response = agent.query(input={"messages": [
("user", "What is the exchange rate from US dollars to SEK today?"),
]})
print(response)
La risposta è un dizionario Python simile al seguente esempio:
{
'messages': [{
'id': ['langchain', 'schema', 'messages', 'HumanMessage'],
'kwargs': {
'content': 'What is the exchange rate from US dollars to Swedish currency?',
'id': '5473dd25-d796-42ad-a690-45bc49a64bec',
'type': 'human',
},
'lc': 1,
'type': 'constructor',
}, {
'id': ['langchain', 'schema', 'messages', 'AIMessage'],
'kwargs': {
'content': """
I do not have access to real-time information, including currency exchange rates.
To get the most up-to-date exchange rate from US dollars to Swedish currency (SEK),
I recommend checking a reliable online currency converter like: ...
These websites will provide you with the current exchange rate and allow you to
convert specific amounts.""",
'id': 'run-c42f9940-8ba8-42f1-a625-3aa0780c9e87-0',
...
'usage_metadata': {
'input_tokens': 12,
'output_tokens': 145,
'total_tokens': 157,
},
},
'lc': 1,
'type': 'constructor',
}],
}
(Facoltativo) Personalizzazione avanzata
Il modello LanggraphAgent
utilizza ChatVertexAI
per impostazione predefinita, perché fornisce l'accesso a tutti i modelli di base disponibili in Google Cloud. Per utilizzare un modello non disponibile tramite ChatVertexAI
, puoi specificare l'argomento model_builder=
con una funzione Python con la seguente firma:
from typing import Optional
def model_builder(
*,
model_name: str, # Required. The name of the model
model_kwargs: Optional[dict] = None, # Optional. The model keyword arguments.
**kwargs, # Optional. The remaining keyword arguments to be ignored.
):
Per un elenco dei modelli di chat supportati in LangChain e delle relative funzionalità, consulta
Modelli di chat.
L'insieme di valori supportati per model=
e model_kwargs=
è specifico per
ogni modello di chat, quindi devi fare riferimento alla documentazione corrispondente per
i dettagli.
ChatVertexAI
Installato per impostazione predefinita.
Viene utilizzato in LanggraphAgent
quando ometti l'argomento model_builder
, ad esempio
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model, # Required.
model_kwargs=model_kwargs, # Optional.
)
ChatAnthropic
Innanzitutto, segui la documentazione per configurare un account e installare il pacchetto.
Successivamente, definisci un model_builder
che restituisca ChatAnthropic
:
def model_builder(*, model_name: str, model_kwargs = None, **kwargs):
from langchain_anthropic import ChatAnthropic
return ChatAnthropic(model_name=model_name, **model_kwargs)
Infine, utilizzalo in LanggraphAgent
con il seguente codice:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model="claude-3-opus-20240229", # Required.
model_builder=model_builder, # Required.
model_kwargs={
"api_key": "ANTHROPIC_API_KEY", # Required.
"temperature": 0.28, # Optional.
"max_tokens": 1000, # Optional.
},
)
ChatOpenAI
Puoi utilizzare ChatOpenAI
insieme all'API ChatCompletions di Gemini.
Per prima cosa, segui la documentazione per installare il pacchetto.
Successivamente, definisci un model_builder
che restituisca ChatOpenAI
:
def model_builder(
*,
model_name: str,
model_kwargs = None,
project: str, # Specified via vertexai.init
location: str, # Specified via vertexai.init
**kwargs,
):
import google.auth
from langchain_openai import ChatOpenAI
# Note: the credential lives for 1 hour by default.
# After expiration, it must be refreshed.
creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
if model_kwargs is None:
model_kwargs = {}
endpoint = f"https://{location}-aiplatform.googleapis.com"
base_url = f'{endpoint}/v1beta1/projects/{project}/locations/{location}/endpoints/openapi'
return ChatOpenAI(
model=model_name,
base_url=base_url,
api_key=creds.token,
**model_kwargs,
)
Infine, utilizzalo in LanggraphAgent
con il seguente codice:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model="google/gemini-2.0-flash", # Or "meta/llama3-405b-instruct-maas"
model_builder=model_builder, # Required.
model_kwargs={
"temperature": 0, # Optional.
"max_retries": 2, # Optional.
},
)
Passaggio 2: Definisci e utilizza uno strumento
Dopo aver definito il modello, il passaggio successivo consiste nel definire gli strumenti che il modello utilizza per il ragionamento. Uno strumento può essere uno strumento LangChain o una funzione Python. Puoi anche convertire una funzione Python definita in uno strumento LangChain.
Quando definisci la funzione, è importante includere commenti che descrivano in modo completo e chiaro i parametri della funzione, cosa fa la funzione e cosa restituisce. Queste informazioni vengono utilizzate dal modello per determinare quale funzione utilizzare. Devi anche testare la funzione localmente per verificare che funzioni.
Utilizza il seguente codice per definire una funzione che restituisce un tasso di cambio:
def get_exchange_rate(
currency_from: str = "USD",
currency_to: str = "EUR",
currency_date: str = "latest",
):
"""Retrieves the exchange rate between two currencies on a specified date.
Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
exchange rate data.
Args:
currency_from: The base currency (3-letter currency code).
Defaults to "USD" (US Dollar).
currency_to: The target currency (3-letter currency code).
Defaults to "EUR" (Euro).
currency_date: The date for which to retrieve the exchange rate.
Defaults to "latest" for the most recent exchange rate data.
Can be specified in YYYY-MM-DD format for historical rates.
Returns:
dict: A dictionary containing the exchange rate information.
Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
"rates": {"EUR": 0.95534}}
"""
import requests
response = requests.get(
f"https://api.frankfurter.app/{currency_date}",
params={"from": currency_from, "to": currency_to},
)
return response.json()
Per testare la funzione prima di utilizzarla nell'agente, esegui il comando seguente:
get_exchange_rate(currency_from="USD", currency_to="SEK")
La risposta dovrebbe essere simile alla seguente:
{'amount': 1.0, 'base': 'USD', 'date': '2024-02-22', 'rates': {'SEK': 10.3043}}
Per utilizzare lo strumento all'interno di LanggraphAgent
, aggiungilo all'elenco degli strumenti nell'argomento tools=
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model, # Required.
tools=[get_exchange_rate], # Optional.
model_kwargs=model_kwargs, # Optional.
)
Puoi testare l'agente localmente eseguendo query di test. Esegui il seguente comando per testare l'agente localmente utilizzando dollari statunitensi e corone svedesi:
response = agent.query(input={"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?"),
]})
La risposta è un dizionario simile al seguente:
{"input": "What is the exchange rate from US dollars to Swedish currency?",
"output": "For 1 US dollar you will get 10.7345 Swedish Krona."}
(Facoltativo) Più strumenti
Gli strumenti per LanggraphAgent
possono essere definiti e istanziati in altri modi.
Strumento di grounding
Per prima cosa, importa il pacchetto generate_models
e crea lo strumento
from vertexai.generative_models import grounding, Tool
grounded_search_tool = Tool.from_google_search_retrieval(
grounding.GoogleSearchRetrieval()
)
Poi, utilizza lo strumento all'interno di LanggraphAgent
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model,
tools=[grounded_search_tool],
)
response = agent.query(input={"messages": [
("user", "When is the next total solar eclipse in US?"),
]})
print(response)
La risposta è un dizionario simile al seguente:
{"input": "When is the next total solar eclipse in US?",
"output": """The next total solar eclipse in the U.S. will be on August 23, 2044.
This eclipse will be visible from three states: Montana, North Dakota, and
South Dakota. The path of totality will begin in Greenland, travel through
Canada, and end around sunset in the United States."""}
Per maggiori dettagli, visita la pagina Messa a terra.
Strumento LangChain
Innanzitutto, installa il pacchetto che definisce lo strumento.
pip install langchain-google-community
A questo punto, importa il pacchetto e crea lo strumento.
from langchain_google_community import VertexAISearchRetriever
from langchain.tools.retriever import create_retriever_tool
retriever = VertexAISearchRetriever(
project_id="PROJECT_ID",
data_store_id="DATA_STORE_ID",
location_id="DATA_STORE_LOCATION_ID",
engine_data_type=1,
max_documents=10,
)
movie_search_tool = create_retriever_tool(
retriever=retriever,
name="search_movies",
description="Searches information about movies.",
)
Infine, utilizza lo strumento all'interno di LanggraphAgent
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model,
tools=[movie_search_tool],
)
response = agent.query(input={"messages": [
("user", "List some sci-fi movies from the 1990s"),
]})
print(response)
Dovrebbe restituire una risposta come
{"input": "List some sci-fi movies from the 1990s",
"output": """Here are some sci-fi movies from the 1990s:
* The Matrix (1999): A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.
* Star Wars: Episode I - The Phantom Menace (1999): Two Jedi Knights escape a hostile blockade to find a queen and her protector, and come across a young boy [...]
* Men in Black (1997): A police officer joins a secret organization that monitors extraterrestrial interactions on Earth.
[...]
"""}
Per visualizzare l'esempio completo, visita il notebook.
Per altri esempi di strumenti disponibili in LangChain, visita la pagina Google Tools.
Vertex AI Extension
Innanzitutto, importa il pacchetto di estensioni e crea lo strumento
from typing import Optional
def generate_and_execute_code(
query: str,
files: Optional[list[str]] = None,
file_gcs_uris: Optional[list[str]] = None,
) -> str:
"""Get the results of a natural language query by generating and executing
a code snippet.
Example queries: "Find the max in [1, 2, 5]" or "Plot average sales by
year (from data.csv)". Only one of `file_gcs_uris` and `files` field
should be provided.
Args:
query:
The natural language query to generate and execute.
file_gcs_uris:
Optional. URIs of input files to use when executing the code
snippet. For example, ["gs://input-bucket/data.csv"].
files:
Optional. Input files to use when executing the generated code.
If specified, the file contents are expected be base64-encoded.
For example: [{"name": "data.csv", "contents": "aXRlbTEsaXRlbTI="}].
Returns:
The results of the query.
"""
operation_params = {"query": query}
if files:
operation_params["files"] = files
if file_gcs_uris:
operation_params["file_gcs_uris"] = file_gcs_uris
from vertexai.preview import extensions
# If you have an existing extension instance, you can get it here
# i.e. code_interpreter = extensions.Extension(resource_name).
code_interpreter = extensions.Extension.from_hub("code_interpreter")
return extensions.Extension.from_hub("code_interpreter").execute(
operation_id="generate_and_execute",
operation_params=operation_params,
)
Poi, utilizza lo strumento all'interno di LanggraphAgent
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model,
tools=[generate_and_execute_code],
)
response = agent.query(input={"messages": [("user", """
Using the data below, construct a bar chart that includes only the height values with different colors for the bars:
tree_heights_prices = {
\"Pine\": {\"height\": 100, \"price\": 100},
\"Oak\": {\"height\": 65, \"price\": 135},
\"Birch\": {\"height\": 45, \"price\": 80},
\"Redwood\": {\"height\": 200, \"price\": 200},
\"Fir\": {\"height\": 180, \"price\": 162},
}
""")]})
print(response)
Dovrebbe restituire una risposta come
{"input": """Using the data below, construct a bar chart that includes only the height values with different colors for the bars:
tree_heights_prices = {
\"Pine\": {\"height\": 100, \"price\": 100},
\"Oak\": {\"height\": 65, \"price\": 135},
\"Birch\": {\"height\": 45, \"price\": 80},
\"Redwood\": {\"height\": 200, \"price\": 200},
\"Fir\": {\"height\": 180, \"price\": 162},
}
""",
"output": """Here's the generated bar chart:
```python
import matplotlib.pyplot as plt
tree_heights_prices = {
"Pine": {"height": 100, "price": 100},
"Oak": {"height": 65, "price": 135},
"Birch": {"height": 45, "price": 80},
"Redwood": {"height": 200, "price": 200},
"Fir": {"height": 180, "price": 162},
}
heights = [tree["height"] for tree in tree_heights_prices.values()]
names = list(tree_heights_prices.keys())
plt.bar(names, heights, color=['red', 'green', 'blue', 'purple', 'orange'])
plt.xlabel('Tree Species')
plt.ylabel('Height')
plt.title('Tree Heights')
plt.show()
```
"""}
Affinché l'agente di cui è stato eseguito il deployment possa accedere all'estensione Interprete di codice, devi aggiungere il ruolo Utente Vertex AI (roles/aiplatform.user
) al account di servizio dell'agente di servizio AI Platform Reasoning Engine. Per saperne di più, consulta Gestire l'accesso.
Per maggiori dettagli, visita la pagina Vertex AI Extensions.
Puoi utilizzare tutti (o un sottoinsieme) gli strumenti che hai creato in LanggraphAgent
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model,
tools=[
get_exchange_rate, # Optional (Python function)
grounded_search_tool, # Optional (Grounding Tool)
movie_search_tool, # Optional (Langchain Tool)
generate_and_execute_code, # Optional (Vertex Extension)
],
)
response = agent.query(input={"messages": [
("user", "List some sci-fi movies from the 1990s"),
]})
print(response)
(Facoltativo) Configurazione dello strumento
Con Gemini, puoi impostare vincoli sull'utilizzo degli strumenti. Ad esempio, invece di consentire al modello di generare risposte in linguaggio naturale, puoi forzarlo a generare solo chiamate di funzione ("chiamata di funzione forzata").
from vertexai import agent_engines
from vertexai.preview.generative_models import ToolConfig
agent = agent_engines.LanggraphAgent(
model="gemini-2.0-flash",
tools=[search_arxiv, get_exchange_rate],
model_tool_kwargs={
"tool_config": { # Specify the tool configuration here.
"function_calling_config": {
"mode": ToolConfig.FunctionCallingConfig.Mode.ANY,
"allowed_function_names": ["search_arxiv", "get_exchange_rate"],
},
},
},
)
response = agent.query(input={"messages": [
("user", "Explain the Schrodinger equation in a few sentences"),
]})
print(response)
Per maggiori dettagli, visita la pagina Configurazione dello strumento.
Passaggio 3: Checkpoint del negozio
Per monitorare i messaggi di chat e aggiungerli a un database, definisci una
funzione checkpointer_builder
e passala quando crei l'agente.
Configurare un database
Innanzitutto, installa e utilizza il pacchetto pertinente per configurare un database a tua scelta (ad es. AlloyDB per PostgreSQL o Cloud SQL per PostgreSQL):
Successivamente, definisci una funzione checkpointer_builder
nel seguente modo:
Cloud SQL per PostgreSQL
checkpointer_kwargs = {
"project_id": "PROJECT_ID",
"region": "REGION",
"instance": "INSTANCE",
"database": "DATABASE",
}
def checkpointer_builder(**kwargs):
from langchain_google_cloud_sql_pg import (
PostgresEngine,
PostgresSaver,
)
engine = PostgresEngine.from_instance(**kwargs)
engine.init_checkpoint_table()
return PostgresSaver.create_sync(engine)
AlloyDB per PostgreSQL
checkpointer_kwargs = {
"project_id": "PROJECT_ID",
"region": "REGION",
"instance": "INSTANCE",
"database": "DATABASE",
"cluster": "CLUSTER",
}
def checkpointer_builder(**kwargs):
from langchain_google_alloydb_pg import (
AlloyDBEngine,
AlloyDBSaver,
)
from google.cloud.alloydb.connector import IPTypes
engine = AlloyDBEngine.from_instance(
ip_type=IPTypes.PUBLIC,
**kwargs,
)
engine.init_checkpoint_table()
return AlloyDBSaver.create_sync(engine)
Infine, crea l'agente e passalo come checkpointer_builder
:
from vertexai import agent_engines
agent = agent_engines.LanggraphAgent(
model=model,
checkpointer_kwargs=checkpointer_kwargs, # <- new
checkpointer_builder=checkpointer_builder, # <- new
)
Quando esegui una query sull'agente, assicurati di specificare un thread_id
in modo che l'agente
abbia "memoria" delle domande e delle risposte precedenti:
response = agent.query(
input={"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]},
config={"configurable": {"thread_id": "THREAD_ID"}},
)
print(response)
Puoi verificare che le query successive mantengano la memoria della sessione:
response = agent.query(
input={"messages": [("user", "How much is 100 USD?")]},
config={"configurable": {"thread_id": "THREAD_ID"}},
)
print(response)
Passaggio 4: Personalizzare il modello di prompt
I modelli di prompt aiutano a tradurre l'input utente dell'utente in istruzioni per un modello e vengono utilizzati per guidare la risposta di un modello, aiutandolo a comprendere il contesto e a generare un output pertinente e coerente basato sul linguaggio. Per maggiori dettagli, visita la pagina ChatPromptTemplates.
Il modello di prompt predefinito è organizzato in sezioni in sequenza.
Sezione | Descrizione |
---|---|
(Facoltativo) Istruzione di sistema | Istruzioni per l'agente da applicare a tutte le query. |
(Facoltativo) Cronologia chat | Messaggi corrispondenti alla cronologia chat di una sessione precedente. |
Input utente | La query dell'utente a cui l'agente deve rispondere. |
Blocco note dell'agente | Messaggi creati dall'agente (ad es. con la chiamata di funzione) mentre utilizza i suoi strumenti ed esegue il ragionamento per formulare una risposta all'utente. |
Il modello di prompt predefinito viene generato se crei l'agente senza specificare un tuo modello di prompt e avrà il seguente aspetto:
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents.format_scratchpad.tools import format_to_tool_messages
prompt_template = {
"user_input": lambda x: x["input"],
"history": lambda x: x["history"],
"agent_scratchpad": lambda x: format_to_tool_messages(x["intermediate_steps"]),
} | ChatPromptTemplate.from_messages([
("system", "{system_instruction}"),
("placeholder", "{history}"),
("user", "{user_input}"),
("placeholder", "{agent_scratchpad}"),
])
Utilizzi implicitamente il modello di prompt completo quando istanzi l'agente nel seguente esempio:
from vertexai import agent_engines
system_instruction = "I help look up the rate between currencies"
agent = agent_engines.LanggraphAgent(
model=model,
system_instruction=system_instruction,
checkpointer_kwargs=checkpointer_kwargs,
checkpointer_builder=checkpointer_builder,
tools=[get_exchange_rate],
)
Puoi sostituire il modello di prompt predefinito con il tuo modello di prompt e utilizzarlo durante la creazione dell'agente, ad esempio:
from vertexai import agent_engines
custom_prompt_template = {
"user_input": lambda x: x["input"],
"history": lambda x: x["history"],
"agent_scratchpad": lambda x: format_to_tool_messages(x["intermediate_steps"]),
} | ChatPromptTemplate.from_messages([
("placeholder", "{history}"),
("user", "{user_input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = agent_engines.LanggraphAgent(
model=model,
prompt=custom_prompt_template,
checkpointer_kwargs=checkpointer_kwargs,
checkpointer_builder=checkpointer_builder,
tools=[get_exchange_rate],
)
response = agent.query(
input={"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?"),
]}
config={"configurable": {"thread_id": "THREAD_ID"}},
)
print(response)
Passaggio 5: Personalizzare l'orchestrazione
Tutti i componenti LangChain implementano l'interfaccia Runnable,
che fornisce schemi di input e output per l'orchestrazione. La classe LanggraphAgent
richiede la creazione di un runnable per rispondere alle query. Per impostazione predefinita, LanggraphAgent
creerà un eseguibile di questo tipo utilizzando l'implementazione dell'agente React predefinita di langgraph.
Potresti voler personalizzare l'orchestrazione se intendi (i) implementare un
agente che esegue una serie deterministica di passaggi (anziché eseguire
un ragionamento aperto) o (ii) chiedere all'agente in modo simile a ReAct di
annotare ogni passaggio con i motivi per cui è stato eseguito. Per farlo, devi eseguire l'override dell'eseguibile predefinito quando crei LanggraphAgent
specificando l'argomento runnable_builder=
con una funzione Python con la seguente firma:
from typing import Optional
from langchain_core.language_models import BaseLanguageModel
def runnable_builder(
model: BaseLanguageModel,
*,
system_instruction: Optional[str] = None,
prompt: Optional["RunnableSerializable"] = None,
tools: Optional[Sequence["_ToolLike"]] = None,
checkpointer: Optional[Any] = None,
runnable_kwargs: Optional[Mapping[str, Any]] = None,
**kwargs,
):
dove
model
corrisponde al modello di chat restituito damodel_builder
(vedi Definire e configurare un modello),tools
corrisponde agli strumenti e alle configurazioni da utilizzare (vedi Definisci e utilizza uno strumento),checkpointer
corrisponde al database per l'archiviazione dei checkpoint (vedi Archiviazione dei checkpoint),system_instruction
eprompt
corrispondono alla configurazione del prompt (vedi Personalizzare il modello di prompt),runnable_kwargs
sono gli argomenti delle parole chiave che puoi utilizzare per personalizzare l'eseguibile da creare.
In questo modo, hai diverse opzioni per personalizzare la logica di orchestrazione.
ChatModel
Nel caso più semplice, per creare un agente senza orchestrazione, puoi
ignorare runnable_builder
per LanggraphAgent
per restituire direttamente model
.
from vertexai import agent_engines
from langchain_core.language_models import BaseLanguageModel
def llm_builder(model: BaseLanguageModel, **kwargs):
return model
agent = agent_engines.LanggraphAgent(
model=model,
runnable_builder=llm_builder,
)
ReAct
Per ignorare il comportamento di chiamata degli strumenti predefinito con il tuo agente ReAct basato sul tuo
prompt
(vedi Personalizzare il modello di prompt),
devi ignorare runnable_builder
per LanggraphAgent
.
from typing import Sequence
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain_core.tools import BaseTool
from langchain import hub
from vertexai import agent_engines
def react_builder(
model: BaseLanguageModel,
*,
tools: Sequence[BaseTool],
prompt: BasePromptTemplate,
agent_executor_kwargs = None,
**kwargs,
):
from langchain.agents.react.agent import create_react_agent
from langchain.agents import AgentExecutor
agent = create_react_agent(model, tools, prompt)
return AgentExecutor(agent=agent, tools=tools, **agent_executor_kwargs)
agent = agent_engines.LanggraphAgent(
model=model,
tools=[get_exchange_rate],
prompt=hub.pull("hwchase17/react"),
agent_executor_kwargs={"verbose": True}, # Optional. For illustration.
runnable_builder=react_builder,
)
Sintassi LCEL
Per costruire il seguente grafico utilizzando LangChain Expression Language (LCEL),
Input
/ \
Pros Cons
\ /
Summary
devi eseguire l'override di runnable_builder
per LanggraphAgent
:
from vertexai import agent_engines
def lcel_builder(*, model, **kwargs):
from operator import itemgetter
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
output_parser = StrOutputParser()
planner = ChatPromptTemplate.from_template(
"Generate an argument about: {input}"
) | model | output_parser | {"argument": RunnablePassthrough()}
pros = ChatPromptTemplate.from_template(
"List the positive aspects of {argument}"
) | model | output_parser
cons = ChatPromptTemplate.from_template(
"List the negative aspects of {argument}"
) | model | output_parser
final_responder = ChatPromptTemplate.from_template(
"Argument:{argument}\nPros:\n{pros}\n\nCons:\n{cons}\n"
"Generate a final response given the critique",
) | model | output_parser
return planner | {
"pros": pros,
"cons": cons,
"argument": itemgetter("argument"),
} | final_responder
agent = agent_engines.LanggraphAgent(
model=model,
runnable_builder=lcel_builder,
)
LangGraph
Per costruire il seguente grafico utilizzando LangGraph,
Input
/ \
Pros Cons
\ /
Summary
devi eseguire l'override di runnable_builder
per LanggraphAgent
:
from vertexai import agent_engines
def langgraph_builder(*, model, **kwargs):
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import END, MessageGraph
output_parser = StrOutputParser()
planner = ChatPromptTemplate.from_template(
"Generate an argument about: {input}"
) | model | output_parser
pros = ChatPromptTemplate.from_template(
"List the positive aspects of {input}"
) | model | output_parser
cons = ChatPromptTemplate.from_template(
"List the negative aspects of {input}"
) | model | output_parser
summary = ChatPromptTemplate.from_template(
"Input:{input}\nGenerate a final response given the critique",
) | model | output_parser
builder = MessageGraph()
builder.add_node("planner", planner)
builder.add_node("pros", pros)
builder.add_node("cons", cons)
builder.add_node("summary", summary)
builder.add_edge("planner", "pros")
builder.add_edge("planner", "cons")
builder.add_edge("pros", "summary")
builder.add_edge("cons", "summary")
builder.add_edge("summary", END)
builder.set_entry_point("planner")
return builder.compile()
agent = agent_engines.LanggraphAgent(
model=model,
runnable_builder=langgraph_builder,
)
# Example query
response = agent.query(input={"role": "user", "content": "scrum methodology"})
print(response)
Passaggi successivi
- Utilizza un agente LangGraph.
- Valuta un agente.
- Esegui il deployment di un agente.
- Risolvi i problemi relativi allo sviluppo di un agente.
- Richiedere assistenza.