使用 Amazon Bedrock 生成图片
Amazon Bedrock 是一款全托管服务,提供来自 AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI 和 Amazon 等领先 AI 公司的高性能基础模型(FM)选择。每个模型都可以通过一个通用 API 访问,这个 API 提供了一整套功能,帮助你在考虑安全、隐私和负责任 AI 的前提下构建生成式 AI 应用。
本指南将通过一个示例,向你展示如何在 Supabase Edge Functions 中使用 Amazon Bedrock JavaScript SDK,通过 Amazon Titan Image Generator G1 模型生成图片。
🌐 This guide will walk you through an example using the Amazon Bedrock JavaScript SDK in Supabase Edge Functions to generate images using the Amazon Titan Image Generator G1 model.
设置 #
🌐 Setup
- 在你的 AWS 控制台中,进入 Amazon Bedrock,然后在“请求模型访问”下,选择 Amazon Titan 图片生成器 G1 模型。
- 在你的 Supabase 项目中,在
supabase目录下创建一个.env文件,内容如下:
1AWS_DEFAULT_REGION="<your_region>"2AWS_ACCESS_KEY_ID="<replace_your_own_credentials>"3AWS_SECRET_ACCESS_KEY="<replace_your_own_credentials>"4AWS_SESSION_TOKEN="<replace_your_own_credentials>"56# Mocked config files7AWS_SHARED_CREDENTIALS_FILE="./aws/credentials"8AWS_CONFIG_FILE="./aws/config"配置存储 #
🌐 Configure Storage
代码 #
🌐 Code
在你的项目中创建一个新函数:
🌐 Create a new function in your project:
1supabase functions new amazon-bedrock然后把代码加到 index.ts 文件里:
🌐 And add the code to the index.ts file:
1// We need to mock the file system for the AWS SDK to work.2import { prepareVirtualFile } from 'https://deno.land/x/mock_file@v1.1.2/mod.ts'3import { BedrockRuntimeClient, InvokeModelCommand } from 'npm:@aws-sdk/client-bedrock-runtime@^3'4import { withSupabase } from 'npm:@supabase/server@^1'5import { decode } from 'npm:base64-arraybuffer@^1'67console.log('Hello from Amazon Bedrock!')89// Called with a publishable key on the `apikey` header. Deploy with `verify_jwt = false`.10export default {11 fetch: withSupabase({ auth: 'publishable' }, async (req, ctx) => {12 prepareVirtualFile('./aws/config')13 prepareVirtualFile('./aws/credentials')1415 const client = new BedrockRuntimeClient({16 region: Deno.env.get('AWS_DEFAULT_REGION') ?? 'us-west-2',17 credentials: {18 accessKeyId: Deno.env.get('AWS_ACCESS_KEY_ID') ?? '',19 secretAccessKey: Deno.env.get('AWS_SECRET_ACCESS_KEY') ?? '',20 sessionToken: Deno.env.get('AWS_SESSION_TOKEN') ?? '',21 },22 })2324 const { prompt, seed } = await req.json()25 console.log(prompt)26 const input = {27 contentType: 'application/json',28 accept: '*/*',29 modelId: 'amazon.titan-image-generator-v1',30 body: JSON.stringify({31 taskType: 'TEXT_IMAGE',32 textToImageParams: { text: prompt },33 imageGenerationConfig: {34 numberOfImages: 1,35 quality: 'standard',36 cfgScale: 8.0,37 height: 512,38 width: 512,39 seed: seed ?? 0,40 },41 }),42 }4344 const command = new InvokeModelCommand(input)45 const response = await client.send(command)46 console.log(response)4748 if (response.$metadata.httpStatusCode === 200) {49 const { body, $metadata } = response5051 const textDecoder = new TextDecoder('utf-8')52 const jsonString = textDecoder.decode(body.buffer)53 const parsedData = JSON.parse(jsonString)54 console.log(parsedData)55 const image = parsedData.images[0]5657 const { data: upload, error: uploadError } = await ctx.supabase.storage58 .from('images')59 .upload(`${$metadata.requestId ?? ''}.png`, decode(image), {60 contentType: 'image/png',61 cacheControl: '3600',62 upsert: false,63 })64 if (!upload) {65 return Response.json({ error: uploadError?.message ?? 'Upload failed' }, { status: 500 })66 }67 const { data } = ctx.supabase.storage.from('images').getPublicUrl(upload.path!)68 return Response.json(data)69 }7071 return Response.json(response)72 }),73}在本地运行这个函数 #
🌐 Run the function locally
- 运行
supabase start(见:https://supabase.com/docs/reference/cli/supabase-start) - 从环境开始:
supabase functions serve --no-verify-jwt --env-file supabase/.env - 发送一个 HTTP 请求:
1curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/amazon-bedrock' \2 --header 'apikey: <SUPABASE_PUBLISHABLE_KEY>' \3 --header 'Content-Type: application/json' \4 --data '{"prompt":"A beautiful picture of a bird"}'- 返回你的存储桶。你可能需要点击刷新按钮才能看到上传的图片。
部署到你托管的项目 #
🌐 Deploy to your hosted project
1supabase link2supabase functions deploy amazon-bedrock --no-verify-jwt3supabase secrets set --env-file supabase/.env你现在已经部署了一个无服务器函数,它使用 AI 来生成并上传图片到你的 Supabase 存储桶。
🌐 You've now deployed a serverless function that uses AI to generate and upload images to your Supabase storage bucket.