Salta ai contenuti

Agente Python Strands

Genera un Agente Strands in Python per costruire agenti AI con strumenti, e opzionalmente distribuirlo su Amazon Bedrock AgentCore Runtime.

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

Puoi generare un Agente Strands in Python in due modi:

  1. Installa il Nx Console VSCode Plugin se non l'hai già fatto
  2. Apri la console Nx in VSCode
  3. Clicca su Generate (UI) nella sezione "Common Nx Commands"
  4. Cerca @aws/nx-plugin - py#strands-agent
  5. Compila i parametri richiesti
    • Clicca su Generate
    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

    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 su None)
      • pyproject.toml Aggiornato con le dipendenze Strands
      • project.json Aggiornato con i target di servizio dell’agente

    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

    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

    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
    @tool
    def calculate_sum(numbers: list[int]) -> int:
    """Calcola la somma di una lista di numeri"""
    return sum(numbers)
    @tool
    def 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'agente
    agent = 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

    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],
    )

    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 Agent
    from strands.models import BedrockModel
    # Crea un BedrockModel
    bedrock_model = BedrockModel(
    model_id="anthropic.claude-sonnet-4-20250514-v1:0",
    region_name="us-west-2",
    temperature=0.3,
    )
    agent = Agent(model=bedrock_model)

    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):

    agent.py
    import os
    from contextlib import contextmanager
    import boto3
    from strands import Agent
    from .agentcore_mcp_client import AgentCoreMCPClient
    # Ottieni regione e credenziali
    region = os.environ["AWS_REGION"]
    boto_session = boto3.Session(region_name=region)
    credentials = boto_session.get_credentials()
    @contextmanager
    def 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);
    }
    }

    Per una guida più dettagliata sulla scrittura di agenti Strands, consulta la documentazione Strands.

    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.

    Il generatore configura un target chiamato <your-agent-name>-serve, che avvia il tuo Agente Strands localmente per sviluppo e test.

    Terminal window
    pnpm 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”

    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/*'],
    }),
    );
    }
    }

    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 usando uv export
    • Installa le dipendenze per la piattaforma target (aarch64-manylinux2014) usando uv pip install

    Viene anche aggiunto un target docker specifico per il tuo Agente Strands, che:

    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);
    }
    }

    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],
    },
    },
    });
    }
    }

    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à.