Generate Images with Amazon Bedrock
Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) from leading AI companies like AI21 Labs, Anthropic, Cohere, Meta, Mistral AI, Stability AI, and Amazon. Each model is accessible through a common API which implements a broad set of features to help build generative AI applications with security, privacy, and responsible AI in mind.
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#
- In your AWS console, navigate to Amazon Bedrock and under "Request model access", select the Amazon Titan Image Generator G1 model.
- In your Supabase project, create a
.envfile in thesupabasedirectory with the following contents:
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#
- [locally] Run
supabase start - Open Studio URL: locally | hosted
- Navigate to Storage
- Click "New bucket"
- Create a new public bucket called "images"
Code#
Create a new function in your project:
1supabase functions new amazon-bedrockAnd 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'4import { withSupabase } from 'npm:@supabase/server@^1'5import { decode } from 'npm:base64-arraybuffer'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(uploadError)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#
- Run
supabase start(see: https://supabase.com/docs/reference/cli/supabase-start) - Start with env:
supabase functions serve --no-verify-jwt --env-file supabase/.env - Make an HTTP request:
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"}'- Navigate back to your storage bucket. You might have to hit the refresh button to see the uploaded image.
Deploy to your hosted project#
1supabase link2supabase functions deploy amazon-bedrock --no-verify-jwt3supabase secrets set --env-file supabase/.envYou've now deployed a serverless function that uses AI to generate and upload images to your Supabase storage bucket.