Skip to content
Cloudflare Docs
非官方翻译 - 此文档为非官方中文翻译版本,仅供参考。如有疑问请以 英文官方文档 为准。

Amazon Bedrock

Amazon Bedrock 允许您使用基础模型构建和扩展生成式 AI 应用程序。

端点

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

前提条件

在向 Amazon Bedrock 发出请求时,确保您具有以下内容:

  • 您的 AI 网关账户 ID。
  • 您的 AI 网关网关名称。
  • 一个有效的 Amazon Bedrock API 令牌。
  • 您要使用的 Amazon 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/,然后在 URL 末尾添加您要运行的模型。

使用 Bedrock 时,您需要在向 AI 网关发出请求之前对 URL 进行签名。您可以尝试使用 aws4fetch SDK。

示例

在 TypeScript 中使用 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 awsClient = new AwsClient({
accessKeyId: accessKey,
secretAccessKey: secretKey,
region: region,
service: "bedrock",
});
const requestBodyString = JSON.stringify({
inputText: "What does ethereal mean?",
});
const stockUrl = new URL(
`https://bedrock-runtime.${region}.amazonaws.com/model/amazon.titan-embed-text-v1/invoke`,
);
const headers = {
"Content-Type": "application/json",
};
// 签名原始请求
const presignedRequest = await awsClient.sign(stockUrl.toString(), {
method: "POST",
headers: headers,
body: requestBodyString,
});
// 网关 URL
const gatewayUrl = new URL(
`https://gateway.ai.cloudflare.com/v1/${cfAccountId}/${gatewayName}/aws-bedrock/bedrock-runtime/${region}/model/amazon.titan-embed-text-v1/invoke`,
);
// 通过网关 URL 发出请求
const response = await fetch(gatewayUrl, {
method: "POST",
headers: presignedRequest.headers,
body: requestBodyString,
});
if (
response.ok &&
response.headers.get("content-type")?.includes("application/json")
) {
const data = await response.json();
return new Response(JSON.stringify(data));
}
return new Response("Invalid response", { status: 500 });
},
};