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. Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
  2. Mở Nx Console trong VSCode
  3. Nhấp Generate (UI) trong phần "Common Nx Commands"
  4. Tìm kiếm @aws/nx-plugin - ts#strands-agent
  5. Điền các tham số bắt buộc
    • Nhấp Generate
    Tham số Kiểu Mặc định Mô tả
    project Bắt buộc string - Dự án để thêm Strands Agent vào
    computeType string BedrockAgentCoreRuntime Loại compute để lưu trữ Strands Agent của bạn.
    name string - Tên của Strands Agent của bạn (mặc định: agent)
    auth string IAM Phương thức được sử dụng để xác thực với Strands Agent của bạn. Chọn giữa IAM (mặc định) hoặc Cognito.
    iacProvider string Inherit Nhà cung cấp IaC ưa thích. Mặc định được kế thừa từ lựa chọn ban đầu của bạn.

    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
          • 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 getAgent = async (sessionId: string) => {
    return 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 bạn có thể sử dụng connection generator.

    1. Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
    2. Mở Nx Console trong VSCode
    3. Nhấp Generate (UI) trong phần "Common Nx Commands"
    4. Tìm kiếm @aws/nx-plugin - connection
    5. Điền các tham số bắt buộc
      • Nhấp Generate

      Tham khảo hướng dẫn connection generator để biết chi tiết về cách thiết lập kết nối.

      Đối với các MCP server khác, vui lòng tham khảo Tài liệu Strands.

      Để 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 agent-serve your-project

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

      Trình tạo cung cấp tùy chọn auth để cấu hình xác thực cho Strands Agent của bạn. Bạn có thể chọn giữa xác thực IAM (mặc định) hoặc Cognito khi tạo agent của mình.

      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 grantInvokeAccess, 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.grantInvokeAccess(lambdaFunction);
      }
      }

      Khi bạn chọn xác thực Cognito, trình tạo sẽ cấu hình agent để sử dụng Cognito cho xác thực.

      Construct được tạo ra chấp nhận một prop identity để cấu hình xác thực Cognito:

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

      Construct UserIdentity có thể được tạo bằng trình tạo ts#react-website#auth, hoặc bạn có thể tạo UserPoolUserPoolClient CDK của riêng mình.

      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 bundle <project-name>

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

      Để gọi Strands Agent của bạn từ một React website, bạn có thể sử dụng connection generator, generator này tự động thiết lập tRPC WebSocket client với xác thực đúng (IAM hoặc Cognito).

      1. Cài đặt Nx Console VSCode Plugin nếu bạn chưa cài đặt
      2. Mở Nx Console trong VSCode
      3. Nhấp Generate (UI) trong phần "Common Nx Commands"
      4. Tìm kiếm @aws/nx-plugin - connection
      5. Điền các tham số bắt buộc
        • Nhấp Generate

        Tham khảo hướng dẫn connection generator để biết chi tiết về cách thiết lập kết nối.