Bỏ qua để đến nội dung

TypeScript Strands Agent

Tạo một TypeScript Strands Agent để xây dựng các AI agent với công cụ, và tùy chọn triển khai nó lên Amazon Bedrock AgentCore Runtime. Generator sử dụng tRPC qua WebSocket để tận dụng hỗ trợ streaming hai chiều của AgentCore cho giao tiếp thời gian thực, type-safe.

Strands là một framework nhẹ để xây dựng các AI agent. Các tính năng chính bao gồm:

  • Nhẹ và có thể tùy chỉnh: Vòng lặp agent đơn giản không cản trở bạn
  • Sẵn sàng cho production: Khả năng quan sát đầy đủ, tracing, và các tùy chọn triển khai cho quy mô lớn
  • Không phụ thuộc vào model và provider: Hỗ trợ nhiều model khác nhau từ nhiều provider
  • Công cụ do cộng đồng đóng góp: Bộ công cụ mạnh mẽ do cộng đồng đóng góp
  • Hỗ trợ đa agent: Các kỹ thuật nâng cao như nhóm agent và agent tự động
  • Chế độ tương tác linh hoạt: Hỗ trợ hội thoại, streaming, và non-streaming

Bạn có thể tạo một TypeScript Strands Agent theo hai cách:

  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - ts#strands-agent
  5. Fill in the required parameters
    • Click Generate
    Parameter Type Default Description
    project Required 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.

    Generator sẽ thêm các file sau vào dự án TypeScript hiện có của bạn:

    • Thư mụcyour-project/
      • Thư mụcsrc/
        • Thư mụcagent/ (hoặc tên tùy chỉnh nếu được chỉ định)
          • index.ts Điểm vào cho Bedrock AgentCore Runtime
          • init.ts Khởi tạo tRPC
          • router.ts tRPC router với các agent procedure
          • agent.ts Định nghĩa agent chính với các công cụ mẫu
          • client.ts Client được cung cấp để gọi agent của bạn
          • agent-core-trpc-client.ts Client factory để kết nối với các agent trên AgentCore Runtime
          • agent-core-mcp-client.ts Client factory để kết nối với các MCP server trên AgentCore Runtime
          • Dockerfile Điểm vào để host agent của bạn (loại trừ khi computeType được đặt thành None)
      • package.json Được cập nhật với các dependency của Strands
      • project.json Được cập nhật với các target serve agent

    Vì generator này cung cấp infrastructure as code dựa trên iacProvider bạn đã chọn, nó sẽ tạo một dự án trong packages/common bao gồm các CDK constructs hoặc Terraform modules liên quan.

    Dự án infrastructure as code chung được cấu trúc như sau:

    • Thư mụcpackages/common/constructs
      • Thư mụcsrc
        • Thư mụcapp/ Constructs cho infrastructure cụ thể của một dự án/generator
        • Thư mụccore/ Constructs chung được tái sử dụng bởi các constructs trong app
        • index.ts Entry point xuất các constructs từ app
      • project.json Các build targets và cấu hình của dự án

    Để triển khai Strands Agent của bạn, các file sau được tạo ra:

    • Thư mụcpackages/common/constructs/src
      • Thư mụcapp
        • Thư mụcagents
          • Thư mục<project-name>
            • <project-name>.ts CDK construct để triển khai agent của bạn
            • Dockerfile File docker passthrough được sử dụng bởi CDK construct

    TypeScript Strands Agent sử dụng tRPC qua WebSocket, tận dụng hỗ trợ streaming hai chiều của AgentCore để cho phép giao tiếp thời gian thực, type-safe giữa client và agent của bạn.

    Vì tRPC hỗ trợ các procedure Query, Mutation và Subscription qua WebSocket, bạn có thể định nghĩa bất kỳ số lượng procedure nào. Mặc định, một subscription procedure duy nhất có tên invoke được định nghĩa cho bạn trong router.ts.

    Công cụ là các hàm mà AI agent có thể gọi để thực hiện các hành động. Bạn có thể thêm công cụ mới trong file agent.ts:

    import { Agent, tool } from '@strands-agents/sdk';
    import z from 'zod';
    const letterCounter = tool({
    name: 'letter_counter',
    description: 'Count occurrences of a specific letter in a word',
    inputSchema: z.object({
    word: z.string().describe('The input word to search in'),
    letter: z.string().length(1).describe('The specific letter to count'),
    }),
    callback: (input) => {
    const { word, letter } = input;
    const count = word.toLowerCase().split(letter.toLowerCase()).length - 1;
    return `The letter '${letter}' appears ${count} time(s) in '${word}'`;
    },
    });
    // Add tools to your agent
    export const agent = new Agent({
    systemPrompt: 'You are a helpful assistant with access to various tools.',
    tools: [letterCounter],
    });

    Framework Strands tự động xử lý:

    • Xác thực đầu vào sử dụng Zod schema
    • Tạo JSON schema cho việc gọi công cụ
    • Xử lý lỗi và định dạng response

    Mặc định, các Strands agent sử dụng Claude 4 Sonnet, nhưng bạn có thể dễ dàng chuyển đổi giữa các model provider:

    import { Agent } from '@strands-agents/sdk';
    import { BedrockModel } from '@strands-agents/sdk/models/bedrock';
    import { OpenAIModel } from '@strands-agents/sdk/models/openai';
    // Use Bedrock
    const bedrockModel = new BedrockModel({
    modelId: 'anthropic.claude-sonnet-4-20250514-v1:0',
    });
    let agent = new Agent({ model: bedrockModel });
    let response = await agent.invoke('What can you help me with?');
    // Alternatively, use OpenAI by just switching model provider
    const openaiModel = new OpenAIModel({
    apiKey: process.env.OPENAI_API_KEY,
    modelId: 'gpt-4o',
    });
    agent = new Agent({ model: openaiModel });
    response = await agent.invoke('What can you help me with?');

    Xem tài liệu Strands về các model provider để biết thêm các tùy chọn cấu hình.

    Bạn có thể thêm công cụ từ các MCP server vào Strands agent của bạn.

    Để sử dụng các MCP Server mà bạn đã tạo bằng generator py#mcp-server hoặc ts#mcp-server (hoặc các server khác được host trên Bedrock AgentCore Runtime), một client factory được tạo cho bạn trong agent-core-mcp-client.ts.

    Bạn có thể cập nhật khởi tạo agent của bạn trong agent.ts để tạo MCP client và thêm công cụ. Ví dụ sau đây cho thấy cách thực hiện điều này với xác thực IAM (SigV4):

    agent.ts
    import { Agent } from '@strands-agents/sdk';
    import { AgentCoreMcpClient } from './agent-core-mcp-client.js';
    const mcpClient = AgentCoreMcpClient.withIamAuth({
    agentRuntimeArn: process.env.MCP_AGENTCORE_RUNTIME_ARN!,
    region: process.env.AWS_REGION || 'us-west-2',
    sessionId: 'my-session-id',
    });
    export const agent = new Agent({
    systemPrompt: '...',
    tools: [mcpClient],
    });

    Với ví dụ xác thực IAM ở trên, chúng ta cần cấu hình hai thứ trong hạ tầng của mình. Thứ nhất, chúng ta cần thêm biến môi trường mà agent của chúng ta đang sử dụng cho ARN của AgentCore Runtime của MCP server, và thứ hai chúng ta cần cấp quyền cho agent của chúng ta để gọi MCP server. Điều này có thể đạt được như sau:

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

    Để có hướng dẫn chi tiết hơn về viết Strands agent, tham khảo tài liệu Strands.

    Generator cấu hình một target có tên <your-agent-name>-serve, khởi động Strands Agent của bạn locally để phát triển và kiểm thử.

    Terminal window
    pnpm nx run your-project:agent-serve

    Lệnh này sử dụng tsx --watch để tự động khởi động lại server khi các file thay đổi. Agent sẽ có sẵn tại http://localhost:8081 (hoặc cổng được gán nếu bạn có nhiều agent).

    Triển khai Strands Agent của bạn lên Bedrock AgentCore Runtime

    Phần tiêu đề “Triển khai Strands Agent của bạn lên Bedrock AgentCore Runtime”

    Nếu bạn đã chọn BedrockAgentCoreRuntime cho computeType, cơ sở hạ tầng CDK hoặc Terraform liên quan sẽ được tạo ra mà bạn có thể sử dụng để triển khai Strands Agent của mình lên Amazon Bedrock AgentCore Runtime.

    Một CDK construct được tạo ra cho agent của bạn, được đặt tên dựa trên name bạn đã chọn khi chạy trình tạo, hoặc mặc định là <ProjectName>Agent.

    Bạn có thể sử dụng CDK construct này trong một ứng dụng 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/*',
    ],
    }),
    );
    }
    }

    Theo mặc định, Strands Agent của bạn sẽ được bảo mật bằng xác thực IAM, chỉ cần triển khai nó mà không cần bất kỳ tham số nào:

    import { MyProjectAgent } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    new MyProjectAgent(this, 'MyProjectAgent');
    }
    }

    Bạn có thể cấp quyền truy cập để gọi agent của mình trên Bedrock AgentCore Runtime bằng phương thức grantInvoke, ví dụ:

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

    Dưới đây minh họa cách cấu hình xác thực Cognito cho agent của bạn.

    Để cấu hình xác thực JWT sử dụng Cognito, hãy sử dụng phương thức 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],
    ),
    });
    }
    }

    Ngoài ra, để xác thực JWT tùy chỉnh với nhà cung cấp OIDC của riêng bạn, hãy sử dụng 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)
    ),
    });
    }
    }

    Generator tự động cấu hình một target bundle sử dụng Rolldown để tạo gói triển khai:

    Terminal window
    pnpm nx run <project-name>:bundle

    Cấu hình Rolldown có thể được tìm thấy trong rolldown.config.ts, với một entry cho mỗi bundle cần tạo. Rolldown quản lý việc tạo nhiều bundle song song nếu được định nghĩa.

    Bundle target sử dụng index.ts làm entrypoint cho WebSocket server để host trên Bedrock AgentCore Runtime.

    Generator cấu hình một target <your-agent-name>-docker chạy WebSocket server đã được bundle trên cổng 8080 theo hợp đồng runtime của AgentCore.

    Một target docker cũng được tạo ra để chạy docker build cho tất cả các agent nếu bạn có nhiều agent được định nghĩa.

    Agent của bạn được tự động cấu hình với khả năng quan sát sử dụng AWS Distro for Open Telemetry (ADOT), bằng cách cấu hình auto-instrumentation trong Dockerfile của bạn.

    Bạn có thể tìm thấy các trace trong CloudWatch AWS Console, bằng cách chọn “GenAI Observability” trong menu. Lưu ý rằng để các trace được điền, bạn sẽ cần bật Transaction Search.

    Để biết thêm chi tiết, tham khảo tài liệu AgentCore về khả năng quan sát.

    Giao tiếp với agent được truyền qua tRPC qua WebSocket. Do đó, nên sử dụng client factory type-safe được tạo ra trong client.ts.

    Bạn có thể gọi một agent đang chạy locally sử dụng phương thức factory .local từ client factory.

    Bạn có thể, ví dụ, tạo một file có tên scripts/test.ts trong workspace của bạn để import client:

    scripts/test.ts
    import { AgentClient } from '../packages/<project>/src/agent/client.js';
    const client = AgentClient.local({ url: 'http://localhost:8081/ws' });
    client.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: console.log });

    Để gọi Agent của bạn đã triển khai lên Bedrock AgentCore Runtime, bạn có thể gửi một yêu cầu POST đến điểm cuối dataplane của Bedrock AgentCore Runtime với ARN runtime đã được mã hóa URL.

    Bạn có thể lấy ARN runtime từ cơ sở hạ tầng của mình như sau:

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

    ARN sẽ có định dạng như sau: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.

    Sau đó, bạn có thể mã hóa URL cho ARN bằng cách thay thế : bằng %3A/ bằng %2F.

    URL dataplane của Bedrock AgentCore Runtime để gọi agent như sau:

    https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations

    Cách chính xác để gọi URL này phụ thuộc vào phương thức xác thực được sử dụng.

    File client.ts được tạo ra bao gồm một client factory type-safe có thể được sử dụng để gọi agent đã triển khai của bạn.

    Bạn có thể gọi agent đã triển khai của bạn bằng cách truyền ARN của nó vào phương thức factory withIamAuth:

    import { AgentClient } from './agent/client.js';
    const client = AgentClient.withIamAuth({
    agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    });
    client.invoke.subscribe({ message: 'what is 1 plus 1?' }, {
    onData: (message) => console.log(message),
    onError: (error) => console.error(error),
    onComplete: () => console.log('Done'),
    });

    Sử dụng phương thức factory withJwtAuth để xác thực với JWT / Cognito access token.

    const client = AgentClient.withJwtAuth({
    agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    accessTokenProvider: async () => `<access-token>`,
    });
    client.invoke.subscribe({ message: 'what is 1 plus 1?' }, {
    onData: console.log,
    });

    accessTokenProvider phải trả về token được sử dụng để xác thực request. Bạn có thể, ví dụ, lấy token trong phương thức này để đảm bảo rằng credential mới được tái sử dụng khi tRPC khởi động lại kết nối WebSocket. Ví dụ dưới đây cho thấy việc sử dụng AWS SDK để lấy token từ Cognito:

    import { CognitoIdentityProvider } from "@aws-sdk/client-cognito-identity-provider";
    const cognito = new CognitoIdentityProvider();
    const jwtClient = AgentClient.withJwtAuth({
    agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    accessTokenProvider: async () => {
    const response = await cognito.adminInitiateAuth({
    UserPoolId: '<user-pool-id>',
    ClientId: '<user-pool-client-id>',
    AuthFlow: 'ADMIN_NO_SRP_AUTH',
    AuthParameters: {
    USERNAME: '<username>',
    PASSWORD: '<password>',
    },
    });
    return response.AuthenticationResult!.AccessToken!;
    },
    });

    WebSocket trong trình duyệt không hỗ trợ chỉ định header (ngoại trừ Sec-WebSocket-Protocol), và do đó client factory được tạo ra trong client.ts không thể được sử dụng trong trình duyệt (điều này thực sự sẽ dẫn đến lỗi biên dịch vì constructor WebSocket không chấp nhận header như nó làm trong NodeJS).

    Để gọi agent của bạn từ trình duyệt, bạn cần tạo một presigned WebSocket URL sử dụng AWS SigV4.

    Ví dụ dưới đây cho thấy luồng end-to-end của việc lấy credential, tạo presigned URL, và gọi agent:

    import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
    import { AwsClient } from 'aws4fetch';
    import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity';
    import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity';
    import type { AppRouter } from './your-agent/router';
    // Build a presigned WebSocket URL
    async function buildSignedUrl(
    agentRuntimeArn: string,
    idToken: string,
    region: string = 'us-west-2'
    ): Promise<string> {
    // Get credentials from a Cognito Identity Pool (or other source)
    const credentials = fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region }),
    identityPoolId: 'us-west-2:xxxxx',
    logins: {
    [`cognito-idp.${region}.amazonaws.com/us-west-2_xxxxx`]: idToken,
    },
    });
    const cognitoIdentity = new CognitoIdentityClient({ credentials });
    const credential = await cognitoIdentity.config.credentials();
    // Create AWS SigV4 client
    const awsClient = new AwsClient({
    ...credential,
    service: 'bedrock-agentcore',
    });
    // Build WebSocket URL from ARN
    const wsUrl = `wss://bedrock-agentcore.${region}.amazonaws.com/runtimes/${agentRuntimeArn.replace(/:/g, '%3A').replace(/\//g, '%2F')}/ws`;
    // Create presigned URL
    const signedRequest = await awsClient.sign(wsUrl, {
    method: 'GET',
    aws: { signQuery: true },
    });
    return signedRequest.url;
    }
    // Create tRPC client with presigned WebSocket URL
    const agentRuntimeArn = 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent';
    const idToken = '<your-id-token>';
    const wsClient = createWSClient({
    url: async () => buildSignedUrl(agentRuntimeArn, idToken),
    });
    const trpcClient = createTRPCClient<AppRouter>({
    links: [wsLink({ client: wsClient })],
    });
    // Invoke the agent
    trpcClient.invoke.subscribe({ message: 'what is 1 plus 1?' }, {
    onData: (message) => console.log(message),
    });