Agente Python Strands
Genera un Agente Strands in Python per costruire agenti AI con strumenti, e opzionalmente distribuiscilo su Amazon Bedrock AgentCore Runtime.
Cos’è Strands?
Sezione intitolata “Cos’è Strands?”Strands è un framework Python leggero e pronto per la produzione per costruire agenti AI. Caratteristiche principali:
- Leggero e personalizzabile: Ciclo agenti semplice che non ostacola il lavoro
- Pronto per la produzione: Osservabilità completa, tracciamento e opzioni di distribuzione scalabili
- Agnostico su modelli e provider: Supporta molti modelli diversi da vari provider
- Strumenti della community: Set potente di strumenti contribuiti dalla community
- Supporto multi-agente: Tecniche avanzate come team di agenti e agenti autonomi
- Modalità interattive flessibili: Supporto conversazionale, streaming e non-streaming
Utilizzo
Sezione intitolata “Utilizzo”Genera un Agente Strands
Sezione intitolata “Genera un Agente Strands”Puoi generare un Agente Strands in Python in due modi:
- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - py#strands-agent - Compila i parametri richiesti
- Clicca su
Generate
pnpm nx g @aws/nx-plugin:py#strands-agentyarn nx g @aws/nx-plugin:py#strands-agentnpx nx g @aws/nx-plugin:py#strands-agentbunx nx g @aws/nx-plugin:py#strands-agentPuoi anche eseguire una prova per vedere quali file verrebbero modificati
pnpm nx g @aws/nx-plugin:py#strands-agent --dry-runyarn nx g @aws/nx-plugin:py#strands-agent --dry-runnpx nx g @aws/nx-plugin:py#strands-agent --dry-runbunx nx g @aws/nx-plugin:py#strands-agent --dry-runOpzioni
Sezione intitolata “Opzioni”| Parametro | Tipo | Predefinito | Descrizione |
|---|---|---|---|
| project Obbligatorio | string | - | The project to add the Strands Agent to |
| computeType | string | BedrockAgentCoreRuntime | The type of compute to host your Strands Agent. |
| name | string | - | The name of your Strands Agent (default: agent) |
| iacProvider | string | Inherit | The preferred IaC provider. By default this is inherited from your initial selection. |
Output del Generatore
Sezione intitolata “Output del Generatore”Il generatore aggiungerà i seguenti file al tuo progetto Python esistente:
Directoryyour-project/
Directoryyour_module/
Directoryagent/ (o nome personalizzato se specificato)
- __init__.py Inizializzazione pacchetto Python
- agent.py Definizione principale dell’agente con strumenti di esempio
- main.py Punto d’ingresso per Bedrock AgentCore Runtime
- agentcore_mcp_client.py Factory client utile per invocare server MCP ospitati su Bedrock AgentCore Runtime
- Dockerfile Punto d’ingresso per ospitare il tuo agente (escluso se
computeTypeè impostato aNone)
- pyproject.toml Aggiornato con le dipendenze Strands
- project.json Aggiornato con i target di servizio dell’agente
Infrastruttura
Sezione intitolata “Infrastruttura”Poiché questo generatore fornisce infrastruttura come codice basata sul tuo iacProvider selezionato, creerà un progetto in packages/common che include i relativi costrutti CDK o moduli Terraform.
Il progetto comune di infrastruttura come codice è strutturato come segue:
Directorypackages/common/constructs
Directorysrc
Directoryapp/ Construct per l’infrastruttura specifica di un progetto/generatore
- …
Directorycore/ Construct generici riutilizzati dai construct in
app- …
- index.ts Punto di ingresso che esporta i construct da
app
- project.json Target di build e configurazione del progetto
Directorypackages/common/terraform
Directorysrc
Directoryapp/ Moduli Terraform per l’infrastruttura specifica di un progetto/generatore
- …
Directorycore/ Moduli generici riutilizzati dai moduli in
app- …
- project.json Target di build e configurazione del progetto
Per la distribuzione del tuo Strands Agent, vengono generati i seguenti file:
Directorypackages/common/constructs/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.ts Costrutto CDK per distribuire l’agente
- Dockerfile File Docker pass-through usato dal costrutto CDK
Directorypackages/common/terraform/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.tf Modulo per distribuire l’agente
Directorycore
Directoryagent-core
- runtime.tf Modulo generico per distribuire su Bedrock AgentCore Runtime
Lavorare con il tuo Strands Agent
Sezione intitolata “Lavorare con il tuo Strands Agent”Aggiungere Strumenti
Sezione intitolata “Aggiungere Strumenti”Gli strumenti sono funzioni che l’agente AI può chiamare per eseguire azioni. Il framework Strands utilizza un approccio semplice basato su decoratori per definire gli strumenti.
Puoi aggiungere nuovi strumenti nel file agent.py:
from strands import Agent, tool
@tooldef calculate_sum(numbers: list[int]) -> int: """Calcola la somma di una lista di numeri""" return sum(numbers)
@tooldef get_weather(city: str) -> str: """Ottieni informazioni meteo per una città""" # Integrazione con l'API meteo qui return f"Meteo a {city}: Soleggiato, 25°C"
# Aggiungi strumenti al tuo agenteagent = Agent( system_prompt="Sei un assistente utile con accesso a vari strumenti.", tools=[calculate_sum, get_weather],)Il framework Strands gestisce automaticamente:
- Validazione dei tipi basata sugli hint di tipo delle funzioni
- Generazione dello schema JSON per le chiamate agli strumenti
- Gestione errori e formattazione delle risposte
Utilizzare Strumenti Predefiniti
Sezione intitolata “Utilizzare Strumenti Predefiniti”Strands fornisce una collezione di strumenti predefiniti tramite il pacchetto strands-tools:
from strands_tools import current_time, http_request, file_read
agent = Agent( system_prompt="Sei un assistente utile.", tools=[current_time, http_request, file_read],)Configurazione del Modello
Sezione intitolata “Configurazione del Modello”Di default, gli agenti Strands usano Claude 4 Sonnet, ma puoi personalizzare il provider del modello. Vedi la documentazione Strands sui provider di modelli per le opzioni di configurazione:
from strands import Agentfrom strands.models import BedrockModel
# Crea un BedrockModelbedrock_model = BedrockModel( model_id="anthropic.claude-sonnet-4-20250514-v1:0", region_name="us-west-2", temperature=0.3,)
agent = Agent(model=bedrock_model)Utilizzare Server MCP
Sezione intitolata “Utilizzare Server MCP”Puoi aggiungere strumenti da server MCP al tuo agente Strands.
Per utilizzare server MCP creati con i generatori py#mcp-server o ts#mcp-server (o altri ospitati su Bedrock AgentCore Runtime), viene generata per te una factory client in agentcore_mcp_client.py.
Puoi aggiornare il tuo metodo get_agent in agent.py per creare client MCP e aggiungere strumenti. L’esempio seguente mostra come farlo con autenticazione IAM (SigV4):
import osfrom contextlib import contextmanager
import boto3from strands import Agent
from .agentcore_mcp_client import AgentCoreMCPClient
# Ottieni regione e credenzialiregion = os.environ["AWS_REGION"]boto_session = boto3.Session(region_name=region)credentials = boto_session.get_credentials()
@contextmanagerdef get_agent(session_id: str): mcp_client = AgentCoreMCPClient.with_iam_auth( agent_runtime_arn=os.environ["MCP_AGENTCORE_RUNTIME_ARN"], credentials=credentials, region=region, session_id=session_id, )
with mcp_client: mcp_tools = mcp_client.list_tools_sync()
yield Agent( system_prompt="..." tools=[*mcp_tools], )Con l’esempio di autenticazione IAM sopra, dobbiamo configurare due cose nella nostra infrastruttura. Primo, aggiungere la variabile d’ambiente che il nostro agente consuma per l’ARN del Runtime AgentCore del server MCP, e secondo, concedere i permessi al nostro agente per invocare il server MCP. Questo può essere ottenuto come segue:
import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
const agent = new MyProjectAgent(this, 'MyProjectAgent', { environmentVariables: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.agentRuntimeArn, }, });
mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime); }}# MCP Servermodule "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
# Agentmodule "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
env = { MCP_AGENTCORE_RUNTIME_ARN = module.my_project_mcp_server.agent_core_runtime_arn }
additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ] } ]}Approfondimenti
Sezione intitolata “Approfondimenti”Per una guida più dettagliata sulla scrittura di agenti Strands, consulta la documentazione Strands.
Server FastAPI
Sezione intitolata “Server FastAPI”Il generatore utilizza FastAPI per creare il server HTTP per il tuo Strands Agent. FastAPI fornisce un framework web moderno e veloce per costruire API con Python, con documentazione API automatica e validazione dei tipi.
Il server generato include:
- Configurazione dell’applicazione FastAPI con middleware CORS
- Middleware per la gestione degli errori
- Generazione dello schema OpenAPI
- Endpoint di controllo dello stato (
/ping) - Endpoint di invocazione dell’agente (
/invocations)
Personalizzare Input e Output di Invocazione con Pydantic
Sezione intitolata “Personalizzare Input e Output di Invocazione con Pydantic”L’endpoint di invocazione dell’agente utilizza modelli Pydantic per definire e validare gli schemi di richiesta e risposta. Puoi personalizzare questi modelli in main.py per adattarli ai requisiti del tuo agente.
Definire Modelli di Input
Sezione intitolata “Definire Modelli di Input”Il modello InvokeInput predefinito accetta un prompt e un ID di sessione.
from pydantic import BaseModel
class InvokeInput(BaseModel): prompt: str session_id: strPuoi estendere questo modello per includere qualsiasi campo aggiuntivo di cui il tuo agente ha bisogno.
Definire Modelli di Output
Sezione intitolata “Definire Modelli di Output”Per le risposte in streaming, l’annotazione del tipo di ritorno sul tuo endpoint corrisponde al tipo di ogni valore prodotto dalla tua funzione generatore. Di default, l’agente produce stringhe contenenti il testo di risposta dell’agente mentre viene trasmesso in streaming da Strands:
@app.post("/invocations", openapi_extra={"x-streaming": True})async def invoke(input: InvokeInput) -> str: """Entry point for agent invocation""" return StreamingResponse(handle_invoke(input), media_type="text/event-stream")Puoi definire un modello Pydantic per produrre dati strutturati invece. Per fare questo, dovrai serializzare i modelli pydantic prodotti da handle_invoke:
from pydantic import BaseModel
class StreamChunk(BaseModel): content: str timestamp: str token_count: int
def handle_invoke(...): ... yield StreamChunk(content="xx", timestamp="yy", token_count=5)
def serialize_stream(generator): async for output in generator: yield (output.model_dump_json() + "\n").encode("utf-8")
@app.post("/invocations", openapi_extra={"x-streaming": True})async def invoke(input: InvokeInput) -> StreamChunk: return StreamingResponse(serialize_stream(handle_invoke(input)), media_type="application/json")Bedrock AgentCore Python SDK
Sezione intitolata “Bedrock AgentCore Python SDK”Il generatore include una dipendenza sul Bedrock AgentCore Python SDK per le costanti PingStatus. Se desiderato, è semplice utilizzare BedrockAgentCoreApp invece di FastAPI, tuttavia nota che la type-safety viene persa.
Puoi trovare maggiori dettagli sulle capacità dell’SDK nella documentazione qui.
Eseguire il tuo Strands Agent
Sezione intitolata “Eseguire il tuo Strands Agent”Sviluppo Locale
Sezione intitolata “Sviluppo Locale”Il generatore configura un target chiamato <your-agent-name>-serve, che avvia il tuo Strands Agent localmente per sviluppo e test.
pnpm nx run your-project:agent-serveyarn nx run your-project:agent-servenpx nx run your-project:agent-servebunx nx run your-project:agent-serveQuesto comando usa uv run per eseguire il tuo Strands Agent utilizzando il Bedrock AgentCore Python SDK.
Distribuire il tuo Strands Agent su Bedrock AgentCore Runtime
Sezione intitolata “Distribuire il tuo Strands Agent su Bedrock AgentCore Runtime”Infrastructure as Code
Sezione intitolata “Infrastructure as Code”Se hai selezionato BedrockAgentCoreRuntime per computeType, viene generata l’infrastruttura CDK o Terraform rilevante che puoi utilizzare per distribuire il tuo Strands Agent su Amazon Bedrock AgentCore Runtime.
Viene generato un costrutto CDK per il tuo agent, denominato in base al name che hai scelto durante l’esecuzione del generatore, o <ProjectName>Agent per impostazione predefinita.
Puoi utilizzare questo costrutto CDK in un’applicazione CDK:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the agent to your stack const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Grant permissions to invoke the relevant models in bedrock agent.agentCoreRuntime.addToRolePolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], // You can scope the below down to the specific models you use resources: [ 'arn:aws:bedrock:*:*:foundation-model/*', 'arn:aws:bedrock:*:*:inference-profile/*', ], }), ); }}Viene generato un modulo Terraform per te, denominato in base al name che hai scelto durante l’esecuzione del generatore, o <ProjectName>-agent per impostazione predefinita.
Puoi utilizzare questo modulo terraform in un progetto Terraform:
# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
# Grant permissions to invoke the relevant models in bedrock additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] # You can scope the below down to the specific models you use Resource = [ "arn:aws:bedrock:*:*:foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ] } ]}Autenticazione
Sezione intitolata “Autenticazione”Per impostazione predefinita, il tuo Strands Agent sarà protetto utilizzando l’autenticazione IAM, semplicemente distribuiscilo senza alcun argomento:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}Puoi concedere l’accesso per invocare il tuo agent su Bedrock AgentCore Runtime utilizzando il metodo grantInvoke, ad esempio:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const lambdaFunction = new Function(this, ...);
agent.agentCoreRuntime.grantInvoke(lambdaFunction); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}Per concedere l’accesso per invocare il tuo agent, dovrai aggiungere una policy come la seguente, facendo riferimento all’output module.my_project_agent.agent_core_runtime_arn:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Autenticazione Cognito JWT
Sezione intitolata “Autenticazione Cognito JWT”Quanto segue dimostra come configurare l’autenticazione Cognito per il tuo agent.
Per configurare l’autenticazione JWT utilizzando Cognito, utilizza il metodo factory RuntimeAuthorizerConfiguration.usingCognito():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const userPool = new UserPool(this, 'UserPool'); const client = userPool.addClient('Client', { authFlows: { userPassword: true, }, });
new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingCognito( userPool, [client], ), }); }}In alternativa, per l’autenticazione JWT personalizzata con il tuo provider OIDC, utilizza RuntimeAuthorizerConfiguration.usingJWT():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingJWT( 'https://example.com/.well-known/openid-configuration', ['client1', 'client2'], // Allowed Client IDs (optional) ['audience1'], // Allowed Audiences (optional) ), }); }}Per configurare l’autenticazione JWT, puoi modificare il modulo del tuo agent per configurare la variabile authorizer_configuration come segue:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.id
# Replace with your user pool and client ids or expose as variables user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectAgent" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "HTTP" authorizer_configuration = { custom_jwt_authorizer = { discovery_url = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration" allowed_clients = local.user_pool_client_ids } } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}Target Bundle e Docker
Sezione intitolata “Target Bundle e Docker”Per costruire il tuo Strands Agent per Bedrock AgentCore Runtime, viene aggiunto un target bundle al tuo progetto, che:
- Esporta le dipendenze Python in un file
requirements.txtusandouv export - Installa le dipendenze per la piattaforma target (
aarch64-manylinux2014) usandouv pip install
Viene anche aggiunto un target docker specifico per il tuo Strands Agent, che:
- Costruisce un’immagine docker dal
Dockerfileche esegue il tuo agente, secondo il contratto runtime di AgentCore
Autenticazione
Sezione intitolata “Autenticazione”Di default, il tuo Strands Agent sarà protetto con autenticazione IAM, distribuiscilo semplicemente senza argomenti:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}Puoi concedere l’accesso per invocare il tuo agente su Bedrock AgentCore Runtime usando il metodo grantInvoke, ad esempio:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const lambdaFunction = new Function(this, ...);
agent.agentCoreRuntime.grantInvoke(lambdaFunction); }}# Agentmodule "my_project_agent" { # Percorso relativo al modulo generato nel progetto common/terraform source = "../../common/terraform/src/app/agents/my-project-agent"}Per concedere l’accesso a invocare il tuo agente, dovrai aggiungere una policy come la seguente, referenziando l’output module.my_project_agent.agent_core_runtime_arn:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Autenticazione JWT con Cognito
Sezione intitolata “Autenticazione JWT con Cognito”Quanto segue dimostra come configurare l’autenticazione Cognito per il tuo agente.
Per configurare l’autenticazione JWT usando Cognito, usa il metodo factory RuntimeAuthorizerConfiguration.usingCognito():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const userPool = new UserPool(this, 'UserPool'); const client = userPool.addClient('Client', { authFlows: { userPassword: true, }, });
new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingCognito( userPool, [client], ), }); }}In alternativa, per l’autenticazione JWT personalizzata con il tuo provider OIDC, usa RuntimeAuthorizerConfiguration.usingJWT():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingJWT( 'https://example.com/.well-known/openid-configuration', ['client1', 'client2'], // ID Client Consentiti (opzionale) ['audience1'], // Audience Consentite (opzionale) ), }); }}Per configurare l’autenticazione JWT, puoi modificare il tuo modulo agent per configurare la variabile authorizer_configuration come segue:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.id
# Sostituisci con i tuoi ID user pool e client o esponili come variabili user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectAgent" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "HTTP" authorizer_configuration = { custom_jwt_authorizer = { discovery_url = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration" allowed_clients = local.user_pool_client_ids } } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}Osservabilità
Sezione intitolata “Osservabilità”Il tuo agente è configurato automaticamente con osservabilità usando AWS Distro for Open Telemetry (ADOT), configurando auto-strumentazione nel tuo Dockerfile.
Puoi trovare le tracce nella Console AWS CloudWatch, selezionando “GenAI Observability” nel menu. Nota che per popolare le tracce dovrai abilitare Transaction Search.
Per maggiori dettagli, consulta la documentazione AgentCore sull’osservabilità.
Invocare il tuo Strands Agent
Sezione intitolata “Invocare il tuo Strands Agent”Invocare il Server Locale
Sezione intitolata “Invocare il Server Locale”Per invocare un Agente in esecuzione localmente tramite il target <your-agent-name>-serve, puoi inviare una semplice richiesta POST a /invocations sulla porta su cui il tuo agente locale è in esecuzione. Ad esempio, con curl:
curl -N -X POST http://localhost:8081/invocations \ -d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \ -H "Content-Type: application/json"Invocare l’Agente Distribuito
Sezione intitolata “Invocare l’Agente Distribuito”Per invocare il tuo Agent distribuito su Bedrock AgentCore Runtime, puoi inviare una richiesta POST all’endpoint dataplane di Bedrock AgentCore Runtime con il tuo ARN runtime codificato in URL.
Puoi ottenere l’ARN runtime dalla tua infrastruttura come segue:
import { CfnOutput } from 'aws-cdk-lib';import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent');
new CfnOutput(this, 'AgentArn', { value: agent.agentCoreRuntime.agentRuntimeArn, }); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}
output "agent_arn" { value = module.my_project_agent.agent_core_runtime_arn}L’ARN avrà il seguente formato: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.
Puoi quindi codificare in URL l’ARN sostituendo : con %3A e / con %2F.
L’URL dataplane di Bedrock AgentCore Runtime per invocare l’agent è il seguente:
https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocationsIl modo esatto per invocare questo URL dipende dal metodo di autenticazione utilizzato.
Autenticazione IAM
Sezione intitolata “Autenticazione IAM”Per l’Autenticazione IAM, la richiesta deve essere firmata usando AWS Signature Version 4 (SigV4).
acurl <region> bedrock-agentcore -N -X POST \'https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations' \-d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \-H 'Content-Type: application/json'curl abilitato per Sigv4
Puoi aggiungere il seguente script al tuo file .bashrc (ed eseguire source su di esso) oppure incollare quanto segue nello stesso terminale in cui desideri eseguire il comando.
acurl () { REGION=$1 SERVICE=$2 shift; shift; curl --aws-sigv4 "aws:amz:$REGION:$SERVICE" --user "$(aws configure get aws_access_key_id):$(aws configure get aws_secret_access_key)" -H "X-Amz-Security-Token: $(aws configure get aws_session_token)" "$@"}Per effettuare una richiesta curl autenticata con sigv4, invoca acurl come segue:
acurl <region> <service> <other-curl-arguments>Ad esempio:
API Gateway
Sezione intitolata “API Gateway”acurl ap-southeast-2 execute-api -X GET https://xxxURL funzione Lambda streaming
Sezione intitolata “URL funzione Lambda streaming”acurl ap-southeast-2 lambda -N -X POST https://xxxPuoi aggiungere la seguente funzione al tuo profilo PowerShell oppure incollare quanto segue nella stessa sessione PowerShell in cui desideri eseguire il comando.
# PowerShell profile or current sessionfunction acurl { param( [Parameter(Mandatory=$true)][string]$Region, [Parameter(Mandatory=$true)][string]$Service, [Parameter(ValueFromRemainingArguments=$true)][string[]]$CurlArgs )
$AccessKey = aws configure get aws_access_key_id $SecretKey = aws configure get aws_secret_access_key $SessionToken = aws configure get aws_session_token
& curl --aws-sigv4 "aws:amz:$Region`:$Service" --user "$AccessKey`:$SecretKey" -H "X-Amz-Security-Token: $SessionToken" @CurlArgs}Per effettuare una richiesta curl autenticata con sigv4, invoca acurl utilizzando questi esempi:
API Gateway
Sezione intitolata “API Gateway”acurl ap-southeast-2 execute-api -X GET https://xxxURL funzione Lambda streaming
Sezione intitolata “URL funzione Lambda streaming”acurl ap-southeast-2 lambda -N -X POST https://xxxAutenticazione JWT / Cognito
Sezione intitolata “Autenticazione JWT / Cognito”Per l’Autenticazione Cognito, passa il Token di Accesso Cognito nell’header Authorization:
curl -N -X POST 'https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations' \ -d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <access-token>"Puoi ottenere il token di accesso usando il comando cognito-idp admin-initiate-auth dell’AWS CLI, ad esempio:
aws cognito-idp admin-initiate-auth \ --user-pool-id <user-pool-id> \ --client-id <user-pool-client-id> \ --auth-flow ADMIN_NO_SRP_AUTH \ --auth-parameters USERNAME=<username>,PASSWORD=<password> \ --region <region> \ --query 'AuthenticationResult.AccessToken' \ --output text