Agente Python Strands
Genera un Agente Strands in Python per costruire agenti AI con strumenti, e opzionalmente distribuirlo 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 di agente semplice che non ostacola il lavoro
- Pronto per la produzione: Osservabilità completa, tracciamento e opzioni di deployment per scalare
- 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à di interazione 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-agent
yarn nx g @aws/nx-plugin:py#strands-agent
npx nx g @aws/nx-plugin:py#strands-agent
bunx nx g @aws/nx-plugin:py#strands-agent
Puoi anche eseguire una prova per vedere quali file verrebbero modificati
pnpm nx g @aws/nx-plugin:py#strands-agent --dry-run
yarn nx g @aws/nx-plugin:py#strands-agent --dry-run
npx nx g @aws/nx-plugin:py#strands-agent --dry-run
bunx nx g @aws/nx-plugin:py#strands-agent --dry-run
Opzioni
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 | CDK | The preferred IaC provider |
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 richiamare server MCP ospitati su Bedrock AgentCore Runtime
- Dockerfile Punto d’ingresso per hostare il tuo agente (escluso se
computeType
è impostato suNone
)
- 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 il deployment del tuo Agente Strands, vengono generati i seguenti file:
Directorypackages/common/constructs/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.ts Costrutto CDK per deployare l’agente
- Dockerfile Dockerfile pass-through usato dal costrutto CDK
Directorycore
Directoryagent-core
- runtime.ts Costrutto CDK generico per deploy su Bedrock AgentCore Runtime
Directorypackages/common/terraform/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.tf Modulo per deployare l’agente
Directorycore
Directoryagent-core
- runtime.tf Modulo generico per deploy su Bedrock AgentCore Runtime
Lavorare con il Tuo Agente Strands
Sezione intitolata “Lavorare con il Tuo Agente Strands”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 all'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 type hint delle funzioni
- Generazione dello schema JSON per le chiamate agli strumenti
- Gestione errori e formattazione delle risposte
Utilizzare Strumenti Precostruiti
Sezione intitolata “Utilizzare Strumenti Precostruiti”Strands fornisce una collezione di strumenti precostruiti 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. Consulta 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)
Consumare Server MCP
Sezione intitolata “Consumare Server MCP”Puoi aggiungere strumenti da server MCP al tuo agente Strands.
Per consumare server MCP creati con i generatori py#mcp-server
o ts#mcp-server
(o altri hostati su Bedrock AgentCore Runtime), viene generata per te una factory client in agentcore_mcp_client.py
.
Puoi aggiornare il 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, secondo concedere al nostro agente i permessi per richiamare 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', { environment: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.arn, }, });
mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime); }}
# Server MCPmodule "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
# Agentemodule "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.
Bedrock AgentCore Python SDK
Sezione intitolata “Bedrock AgentCore Python SDK”Il generatore configura il Bedrock AgentCore Python SDK per gestire il contratto HTTP sottostante che gli agenti su AgentCore devono implementare.
Puoi trovare maggiori dettagli sulle capacità dell’SDK nella documentazione qui.
Eseguire il Tuo Agente Strands
Sezione intitolata “Eseguire il Tuo Agente Strands”Sviluppo Locale
Sezione intitolata “Sviluppo Locale”Il generatore configura un target chiamato <your-agent-name>-serve
, che avvia il tuo Agente Strands localmente per sviluppo e test.
pnpm nx run your-project:agent-serve
yarn nx run your-project:agent-serve
npx nx run your-project:agent-serve
bunx nx run your-project:agent-serve
Questo comando usa uv run
per eseguire il tuo Agente Strands utilizzando il Bedrock AgentCore Python SDK.
Deploy dell’Agente Strands su Bedrock AgentCore Runtime
Sezione intitolata “Deploy dell’Agente Strands su Bedrock AgentCore Runtime”Infrastruttura as-Code
Sezione intitolata “Infrastruttura as-Code”Se hai selezionato BedrockAgentCoreRuntime
per computeType
, viene generata l’infrastruttura CDK o Terraform rilevante che puoi usare per deployare il tuo Agente Strands su Amazon Bedrock AgentCore Runtime.
Viene generato un costrutto CDK per te, nominato in base al name
scelto durante l’esecuzione del generatore, o <ProjectName>Agent
di default.
Puoi usare questo costrutto CDK in un’applicazione CDK:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Aggiungi l'agente al tuo stack const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Concedi permessi per richiamare i modelli pertinenti in bedrock agent.agentCoreRuntime.role.addToPolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], // Puoi limitare il sotto a specifici modelli usati resources: ['arn:aws:bedrock:*::foundation-model/*'], }), ); }}
Viene generato un modulo Terraform per te, nominato in base al name
scelto durante l’esecuzione del generatore, o <ProjectName>-agent
di default.
Puoi usare questo modulo Terraform in un progetto Terraform:
# Agentemodule "my_project_agent" { # Percorso relativo al modulo generato in common/terraform source = "../../common/terraform/src/app/agents/my-project-agent"
# Concedi permessi per richiamare i modelli pertinenti in bedrock additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] Resource = [ "arn:aws:bedrock:*::foundation-model/*" ] } ]}
Target Bundle e Docker
Sezione intitolata “Target Bundle e Docker”Per buildare il tuo Agente Strands per Bedrock AgentCore Runtime, viene aggiunto un target bundle
al tuo progetto, che:
- Esporta le dipendenze Python in un file
requirements.txt
usandouv export
- Installa le dipendenze per la piattaforma target (
aarch64-manylinux2014
) usandouv pip install
Viene anche aggiunto un target docker
specifico per il tuo Agente Strands, che:
- Builda un’immagine docker dal
Dockerfile
che esegue il tuo agente, secondo il contratto runtime di AgentCore
Autenticazione
Sezione intitolata “Autenticazione”Di default, il tuo Agente Strands sarà protetto usando autenticazione IAM, semplicemente deployalo 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 richiamare il tuo agente su Bedrock AgentCore Runtime usando il metodo grantInvoke
, per 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); }}
# Agentemodule "my_project_agent" { # Percorso relativo al modulo generato in common/terraform source = "../../common/terraform/src/app/agents/my-project-agent"}
Per concedere l’accesso a richiamare l’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 Cognito JWT
Sezione intitolata “Autenticazione Cognito JWT”Quanto segue dimostra come configurare l’autenticazione Cognito per il tuo agente.
Per configurare l’autenticazione JWT, puoi passare la proprietà authorizerConfiguration
al tuo costrutto agente. Ecco un esempio che configura un user pool e client Cognito per proteggere l’agente:
import { MyProjectAgent } from ':my-scope/common-constructs';
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: { customJWTAuthorizer: { discoveryUrl: `https://cognito-idp.${Stack.of(userPool).region}.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`, allowedClients: [client.userPoolClientId], }, }, }); }}
Per configurare l’autenticazione JWT, puoi modificare il tuo modulo agente per configurare la variabile customJWTAuthorizer
come segue:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.name
# 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" customJWTAuthorizer = { discoveryUrl = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration", allowedClients = 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 devi abilitare Transaction Search.
Per maggiori dettagli, consulta la documentazione AgentCore sull’osservabilità.