コンテンツにスキップ

Amazon Bedrock

Beta

Amazon Bedrock は、基盤モデルを使用して生成AIアプリケーションを構築およびスケールすることを可能にします。

エンドポイント

https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/aws-bedrock

リクエストを作成する

Amazon Bedrockにリクエストを送信する際は、現在使用しているURLの https://bedrock-runtime.us-east-1.amazonaws.com/https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/aws-bedrock/bedrock-runtime/us-east-1/ に置き換え、最後に実行したいモデルを追加します。

Bedrockを使用する場合、AI Gatewayにリクエストを送信する前にURLに署名する必要があります。 aws4fetch SDKを使用してみることができます。

例:

import { AwsClient } from "aws4fetch";
interface Env {
accessKey: string;
secretAccessKey: string;
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
// あなたの設定に置き換えてください
const cfAccountId = "{account_id}";
const gatewayName = "{gateway_id}";
const region = "us-east-1";
// シークレットとして追加されました (https://developers.cloudflare.com/workers/configuration/secrets/)
const accessKey = env.accessKey;
const secretKey = env.secretAccessKey;
const requestData = {
inputText: "etherealの意味は何ですか?",
};
const headers = {
"Content-Type": "application/json",
};
// 元のリクエストに署名する
const stockUrl = new URL(
"https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke",
);
const awsClient = new AwsClient({
accessKeyId: accessKey,
secretAccessKey: secretKey,
region: region,
service: "bedrock",
});
const presignedRequest = await awsClient.sign(stockUrl.toString(), {
method: "POST",
headers: headers,
});
// 署名されたリクエストのホストをAI Gatewayに変更する
const stockUrlSigned = new URL(presignedRequest.url);
stockUrlSigned.host = "gateway.ai.cloudflare.com";
stockUrlSigned.pathname = `/v1/${cfAccountId}/${gatewayName}/aws-bedrock/bedrock-runtime/${region}/model/amazon.titan-embed-text-v1/invoke`;
// リクエストを送信する
const response = await fetch(stockUrlSigned, {
method: "POST",
headers: presignedRequest.headers,
body: JSON.stringify(requestData),
});
if (
response.ok &&
response.headers.get("content-type")?.includes("application/json")
) {
const data = await response.json();
return new Response(JSON.stringify(response));
} else {
return new Response("無効なレスポンス", { status: 500 });
}
},
};