> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 將 Mastra 部署至 Amazon Bedrock AgentCore 使用 [AgentCore CLI](https://github.com/aws/agentcore-cli),將你的 Mastra 應用程式部署至 [Amazon Bedrock AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/)。CLI 會建立自備程式碼(BYO)TypeScript 項目的基本結構、使用 AWS CodeBuild 建置容器,並佈建 Runtime。部署時無需本機 Docker 背景程序。 本指南依照[官方 AgentCore TypeScript 逐步指南](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-cli-typescript.html),並作出調整,以便從調用處理程式呼叫 Mastra Agent。 > **資訊:** 如要以 Lambda 部署完整的 Mastra 伺服器,請參閱 [AWS Lambda 指南](https://mastra.zisheng.pro/zh-HK/guides/deployment/aws-lambda)。如要使用長時間運行的虛擬機器,請參閱 [Amazon EC2 指南](https://mastra.zisheng.pro/zh-HK/guides/deployment/amazon-ec2)。 ## 開始之前 你需要: - 一個具有 Amazon Bedrock AgentCore、AWS CodeBuild、Amazon ECR 和 AWS IAM 權限的 [AWS 帳戶](https://aws.amazon.com/) - 已安裝並完成驗證的 [AWS CLI](https://aws.amazon.com/cli/)(`aws configure` 或 `aws sso login`) - 已安裝 Node.js `v22.13.0` 或以上版本 - 用於透過 `agentcore dev` 進行本機測試的 [Docker](https://www.docker.com/)、[Podman](https://podman.io/) 或 [Finch](https://runfinch.com/)(`agentcore deploy` 並不需要) Amazon Bedrock AgentCore Runtime 只在[部分 AWS 區域](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/agentcore-regions.html)提供。請使用 AgentCore 可用,而且已啟用你計劃呼叫的基礎模型之區域。 ## 建立新的 AgentCore 項目 運行以下命令以建立新的 AgentCore 項目: **npm**: ```bash npx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **Yarn**: ```bash yarn dlx @aws/agentcore create --name MastraOnAgentCore --no-agent ``` **Bun**: ```bash bun x @aws/agentcore create --name MastraOnAgentCore --no-agent ``` 前往新建立的 `MastraOnAgentCore` 目錄: ```bash cd MastraOnAgentCore ``` 初始化將在 `app/MastraAgent` 內建立的 BYO TypeScript Agent: **npm**: ```bash npx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **Yarn**: ```bash yarn dlx @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` **Bun**: ```bash bun x @aws/agentcore add agent --name MastraAgent --type byo --build Container --language TypeScript --framework Strands --model-provider Bedrock --code-location app/MastraAgent ``` CLI 會修改 `agentcore/agentcore.json` 檔案,並建立空白的 `app/MastraAgent` 目錄。 ## 設定 Agent 項目 前往 `app/MastraAgent` 目錄,並初始化新的 Node.js 項目: ```bash cd app/MastraAgent npm init --init-type=module -y ``` 安裝所需的依賴套件。`bedrock-agentcore` 套件提供實作 [AgentCore Runtime 服務合約](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-service-contract.html)的 `BedrockAgentCoreApp` HTTP 伺服器。`@ai-sdk/amazon-bedrock` 和 `@aws-sdk/credential-providers` 套件讓 Mastra Agent 可透過 AgentCore Runtime 執行角色呼叫 Bedrock: **npm**: ```bash npm install bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **pnpm**: ```bash pnpm add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **Yarn**: ```bash yarn add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` **Bun**: ```bash bun add bedrock-agentcore @opentelemetry/auto-instrumentations-node @ai-sdk/amazon-bedrock @aws-sdk/credential-providers --legacy-peer-deps ``` 另請安裝 TypeScript 及相關開發依賴套件: **npm**: ```bash npm install --save-dev typescript @types/node tsx ``` **pnpm**: ```bash pnpm add --save-dev typescript @types/node tsx ``` **Yarn**: ```bash yarn add --dev typescript @types/node tsx ``` **Bun**: ```bash bun add --dev typescript @types/node tsx ``` 運行 [`mastra init`](https://mastra.zisheng.pro/zh-HK/reference/cli/mastra) 以設定新的 Mastra 項目。系統會在下一步覆寫你在提示中選擇的 Provider,因此選擇任何值都可以: **npm**: ```bash npx mastra@latest init ``` **pnpm**: ```bash pnpm dlx mastra@latest init ``` **Yarn**: ```bash yarn dlx mastra@latest init ``` **Bun**: ```bash bun x mastra@latest init ``` 取代產生的 `src/mastra/agents/weather-agent.ts`,使其使用 Amazon Bedrock。由於下一步會移除儲存層,因此亦會移除原有的 `memory: new Memory()`: ```ts import { Agent } from '@mastra/core/agent' import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock' import { fromNodeProviderChain } from '@aws-sdk/credential-providers' import { weatherTool } from '../tools/weather-tool.js' const bedrock = createAmazonBedrock({ credentialProvider: fromNodeProviderChain(), }) export const weatherAgent = new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: 'You are a helpful weather assistant. Use the weatherTool to fetch current weather data.', model: bedrock('us.anthropic.claude-sonnet-4-6'), tools: { weatherTool }, }) ``` > **備註:** `fromNodeProviderChain()` 讓 Agent 透過標準 SDK 解析鏈(環境變數、共享設定檔、SSO,以及容器或 EC2 角色)取得 AWS 憑證,而非只從環境變數取得。 取代產生的 `src/mastra/index.ts`,以移除預設的檔案式儲存和可觀測性設定。AgentCore Runtime 容器會以非 root 使用者身分運行,而應用程式目錄為唯讀,因此預設的 `LibSQLStore` 無法開啟 `./mastra.db`,導致 Runtime 啟動失敗: ```ts import { Mastra } from '@mastra/core/mastra' import { PinoLogger } from '@mastra/loggers' import { weatherWorkflow } from './workflows/weather-workflow.js' import { weatherAgent } from './agents/weather-agent.js' export const mastra = new Mastra({ workflows: { weatherWorkflow }, agents: { weatherAgent }, logger: new PinoLogger({ name: 'Mastra', level: 'info', }), }) ``` 建立包含以下內容的 `tsconfig.json` 檔案: ```json { "compilerOptions": { "outDir": "./dist", "rootDir": ".", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "declaration": true, "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "forceConsistentCasingInFileNames": true }, "include": ["*.ts", "src/**/*"], "exclude": ["node_modules", "dist"] } ``` > **備註:** 加入 `tsconfig.json` 檔案後,編輯器會在產生的 `src/mastra` 項目中顯示錯誤。這是預期情況,因為設定現時要求 import 包含副檔名。你可以加入 `.js` 來修正,例如: > > ```ts > // Before > import { weatherWorkflow } from './workflows/weather-workflow' > // After > import { weatherWorkflow } from './workflows/weather-workflow.js' > ``` 更新 `package.json`,以設定進入點和建置腳本。使用 `npm pkg set` 可保留 `mastra init` 加入的依賴套件: ```bash npm pkg set main=dist/agent.js scripts.build=tsc scripts.start="node dist/agent.js" scripts.dev="npx tsx --watch agent.ts" ``` ## 初始化 Agent 建立 `agent.ts` 檔案。每次收到 `POST /invocations` 請求時,都會呼叫此處理程式。在處理程式中解析 Mastra Agent 並呼叫它: ```ts import { BedrockAgentCoreApp } from 'bedrock-agentcore/runtime' import { mastra } from './src/mastra/index.js' const app = new BedrockAgentCoreApp({ invocationHandler: { process: async (payload, context) => { const { prompt } = payload as { prompt: string } const agent = mastra.getAgentById('weather-agent') const response = await agent.generate(prompt, { runId: context.sessionId, }) return response.text }, }, }) app.run() ``` 運行 `npm run build`,確認項目能成功編譯。 ## 建立 Dockerfile 在 `app/MastraAgent` 目錄中建立 `Dockerfile`。容器式部署使用多階段 Docker 建置:建置階段將 TypeScript 編譯為 JavaScript,而生產階段只運行編譯後的輸出。映像檔會以非 root 使用者身分運行以提高安全性,並開放連接埠 8080(HTTP)、連接埠 8000(MCP)和連接埠 9000(A2A)。OpenTelemetry 檢測功能會在啟動時自動載入。 ```dockerfile FROM node:22-slim AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:22-slim WORKDIR /app ENV AWS_REGION=us-east-1 COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package*.json ./ RUN useradd -m bedrock_agentcore USER bedrock_agentcore EXPOSE 8080 8000 9000 CMD ["node", "--require", "@opentelemetry/auto-instrumentations-node/register", "dist/agent.js"] ``` > **備註:** 選擇與 Bedrock 模型 ID 前綴(`us.`、`jp.`、`eu.` 或 `global.`)相配的 `AWS_REGION`。 另請建立 `.dockerignore` 檔案,從 Docker 建置內容中排除不必要的檔案: ```bash node_modules dist .git *.log ``` ## 測試你的 Agent 返回項目根目錄: ```bash cd ../.. ``` 在本機測試你的 Agent: **npm**: ```bash npx @aws/agentcore dev --runtime MastraAgent ``` **pnpm**: ```bash pnpm dlx @aws/agentcore dev --runtime MastraAgent ``` **Yarn**: ```bash yarn dlx @aws/agentcore dev --runtime MastraAgent ``` **Bun**: ```bash bun x @aws/agentcore dev --runtime MastraAgent ``` 在另一個終端機中傳送測試請求: **npm**: ```bash npx @aws/agentcore dev "What is the weather in Tokyo?" ``` **pnpm**: ```bash pnpm dlx @aws/agentcore dev "What is the weather in Tokyo?" ``` **Yarn**: ```bash yarn dlx @aws/agentcore dev "What is the weather in Tokyo?" ``` **Bun**: ```bash bun x @aws/agentcore dev "What is the weather in Tokyo?" ``` ## 部署你的 Agent 在 `agentcore/aws-targets.json` 中設定 AWS 帳戶和區域: ```json [ { "name": "default", "account": "123456789012", "region": "us-east-1" } ] ``` 部署至 AgentCore Runtime。CLI 會使用 AWS CodeBuild 建置映像檔、將其推送至 Amazon ECR,並建立 Runtime 和一個 `DEFAULT` 端點: **npm**: ```bash npx @aws/agentcore deploy ``` **pnpm**: ```bash pnpm dlx @aws/agentcore deploy ``` **Yarn**: ```bash yarn dlx @aws/agentcore deploy ``` **Bun**: ```bash bun x @aws/agentcore deploy ``` > **備註:** 部署前,請在 `agentcore/agentcore.json` 內 Agent 的 `environmentVariables` 欄位中設定 Provider API 金鑰和其他秘密資料。 ## 驗證部署 運行 `agentcore status`,查看 Runtime ARN、端點和最近的調用。然後從 CLI 呼叫已部署的 Agent: ```bash npx @aws/agentcore invoke "What is the weather in Tokyo?" ``` 如要在 token 產生時串流傳送,請使用 `--stream`: ```bash npx @aws/agentcore invoke --stream "Plan a 3-day trip to Tokyo" ``` ## 相關資源 - [Amazon Bedrock AgentCore 文件](https://docs.aws.amazon.com/bedrock-agentcore/) - [GitHub 上的 AgentCore CLI](https://github.com/aws/agentcore-cli)