2026年8月1日
MastraAWSLLM Guardrails

Notebook

MastraでAmazon Bedrock / Bedrock Guardrailsを使う方法

MastraからAmazon BedrockのモデルやBedrock Guardrailsを呼び出すための設定や実装を整理します。

MastraAmazon BedrockLLMAmazon Bedrock Guardrails
English

Guide

目次

  1. 前提
  2. Bedrock を使うためのコード
  3. curl でのテスト実行
  4. Bedrock Guardrails を追加する
  5. curl でのテスト実行
  6. ガードレールでエラー検出時に 200 以外のステータスで返したい場合
  7. まとめ

Mastra で Bedrock を使う方法がMastra 公式ドキュメントでわかりにくかったので、自分で調べたものをのせます。

前提

今回は Hono と連携して API から実行できるようにしたので、以下に従って環境を作成しています。

Mastra の Hono ガイド

Bedrock を使うためのコード

以下のようなコードを作成します。

import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { weatherTool } from '../tools/weather-tool.js';
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
 
const amazonBedrock = createAmazonBedrock({
  region: 'us-east-1',
});
 
export const bedrockTutorialAgent = new Agent({
  id: 'bedrock-tutorial-agent',
  name: 'Bedrock Tutorial Agent',
  instructions: `You are a helpful weather assistant that provides accurate weather information and can help planning activities based on the weather.
 
Your primary function is to help users get weather details for specific locations. When responding:
- Always ask for a location if none is provided
- If the location name isn't in English, please translate it
- If giving a location with multiple parts (e.g. "New York, NY"), use the most relevant part (e.g. "New York")
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
- If the user asks for activities and provides the weather forecast, suggest activities based on the weather forecast.
- If the user asks for activities, respond in the format they request.
 
Use the weatherTool to fetch current weather data.`,
  model: amazonBedrock('us.anthropic.claude-haiku-4-5-20251001-v1:0'),
  tools: { weatherTool },
  memory: new Memory(),
});

続いて Bedrock API key を AWS_BEARER_TOKEN_BEDROCK の名前で環境変数にセットします。

export AWS_BEARER_TOKEN_BEDROCK=your-api-key-here

今回は簡単に試すために Bedrock API key を使ったもので試します。
もし IAM での認証のような別の認証を使う場合は、createAmazonBedrock のパラメータを変更することで実現できます。
詳細は AI SDK -> Amazon Bedrock Provider のドキュメントを参考にしてください。

続けて Hono 側の API で今回の Agent を呼び出すように修正します。

app.post('/bedrock', async c => {
  const { message } = await c.req.json<{ message?: unknown }>()
 
  if (typeof message !== 'string' || message.trim().length === 0) {
    return c.json({ error: 'message is required' }, 400)
  }
 
  const result = await bedrockTutorialAgent.generate(message)
  return c.text(result.text)
})

curl でのテスト実行

では curl でテストします。

$ curl -X POST http://localhost:3000/bedrock -H "Content-Type: application/json" -d '{"message":"I am in Tokyo. What is the weather now?"}'
 
Here's the current weather in Tokyo:
 
**Temperature:** 27.5°C (feels like 32.8°C)
**Conditions:** Partly cloudy
**Humidity:** 78%
**Wind Speed:** 2.6 m/s
**Wind Gust:** 18 m/s
 
It's quite warm and humid in Tokyo right now with moderately strong winds. The "feels like" temperature is noticeably higher due to the humidity, so it may feel more oppressive than the actual temperature suggests. You might want to stay hydrated and consider lighter clothing!

Bedrock Guardrails を追加する

では続けて Bedrock Guardrails を適用する例を示します。

AWSTemplateFormatVersion: '2010-09-09'
Description: Bedrock Guardrail that blocks names in user input or model output.
 
Resources:
  NameBlockGuardrail:
    Type: AWS::Bedrock::Guardrail
    Properties:
      Name: "name-block-guardrail"
      Description: "Checks that text does not include a person's name."
      BlockedInputMessaging: "Your input includes a person's name."
      BlockedOutputsMessaging: "The answer includes a person's name."
      SensitiveInformationPolicyConfig:
        PiiEntitiesConfig:
          - Type: NAME
            Action: BLOCK
            InputAction: BLOCK
            OutputAction: BLOCK
            InputEnabled: true
            OutputEnabled: true
 
Outputs:
  GuardrailId:
    Description: Guardrail ID
    Value: !Ref NameBlockGuardrail

作成します。

$ aws cloudformation deploy --template-file guardrail.yaml --stack-name guardrail
$ aws cloudformation describe-stacks --stack-name guardrail --query "Stacks[0].Outputs"
[
    {
        "OutputKey": "GuardrailId",
        "OutputValue": "arn:aws:bedrock:us-east-1:123456789012:guardrail/xxxxxxxx",
        "Description": "Guardrail ID"
    }
]

作成したガードレールの情報を agent インスタンス作成箇所の defaultOptions に追加します。

@@ -25,4 +25,16 @@ Use the weatherTool to fetch current weather data.`,
   model: amazonBedrock('us.anthropic.claude-haiku-4-5-20251001-v1:0'),
   tools: { weatherTool },
   memory: new Memory(),
+  defaultOptions: {
+    providerOptions: {
+      bedrock: {
+        guardrailConfig: {
+          guardrailIdentifier: 'xxxxxxxx',
+          guardrailVersion: 'DRAFT',
+          trace: 'enabled',
+          streamProcessingMode: 'async',
+        },
+      },
+    },
+  },
 });

curl でのテスト実行

では curl でテストします。

curl -X POST http://localhost:3000/bedrock -H "Content-Type: application/json" -d '{"message":"I am Taro. What is your name?"}'
Your input includes a person's name.

名前を返さずに、Bedrock で指定したメッセージが返ってきました。

ガードレールでエラー検出時に 200 以外のステータスで返したい場合

ガードレールエラー時には result.finishReasoncontent-filter になるため、分岐時に利用することで実現可能です。

@@ -21,6 +21,13 @@ app.post('/bedrock', async c => {
   }
 
   const result = await bedrockTutorialAgent.generate(message)
+
+  const blocked = result.finishReason === 'content-filter'
+
+  if (blocked) {
+    return c.text(result.text, 400)
+  }
+
   return c.text(result.text)
 })
$ curl -s -X POST http://localhost:3000/bedrock -H "Content-Type: application/json" -d '{"message":"I am Taro. What is your name?"}' -w '\nHTTP_STATUS=%{http_code}\n'
Your input includes a person's name.
HTTP_STATUS=400

まとめ

Mastra から Amazon Bedrock を使う場合は、@ai-sdk/amazon-bedrock で Bedrock provider を作成し、Agent の model に指定することで利用できます。

また、Bedrock Guardrails のような Bedrock 固有の設定も、defaultOptions.providerOptions.bedrock に渡すことで適用できます。ガードレールでブロックされた場合も、result.textresult.finishReason を見れば、API 側で通常のレスポンスとして扱えます。

Mastra の Agent と Bedrock を組み合わせることで、アプリケーション側の実装はシンプルに保ちつつ、AWS 側のモデル管理やガードレールを利用できるため、業務アプリケーションに LLM を組み込む際に使いやすいです。