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'34import { BedrockRuntimeClient, InvokeModelCommand } from 'npm:@aws-sdk/client-bedrock-runtime'5import { createClient } from 'npm:@supabase/supabase-js'6import { decode } from 'npm:base64-arraybuffer'78console.log('Hello from Amazon Bedrock!')910const SUPABASE_PUBLISHABLE_KEYS = JSON.parse(Deno.env.get('SUPABASE_PUBLISHABLE_KEYS')!)1112Deno.serve(async (req) => {13 prepareVirtualFile('./aws/config')14 prepareVirtualFile('./aws/credentials')1516 const client = new BedrockRuntimeClient({17 region: Deno.env.get('AWS_DEFAULT_REGION') ?? 'us-west-2',18 credentials: {19 accessKeyId: Deno.env.get('AWS_ACCESS_KEY_ID') ?? '',20 secretAccessKey: Deno.env.get('AWS_SECRET_ACCESS_KEY') ?? '',21 sessionToken: Deno.env.get('AWS_SESSION_TOKEN') ?? '',22 },23 })2425 const { prompt, seed } = await req.json()26 console.log(prompt)27 const input = {28 contentType: 'application/json',29 accept: '*/*',30 modelId: 'amazon.titan-image-generator-v1',31 body: JSON.stringify({32 taskType: 'TEXT_IMAGE',33 textToImageParams: { text: prompt },34 imageGenerationConfig: {35 numberOfImages: 1,36 quality: 'standard',37 cfgScale: 8.0,38 height: 512,39 width: 512,40 seed: seed ?? 0,41 },42 }),43 }4445 const command = new InvokeModelCommand(input)46 const response = await client.send(command)47 console.log(response)4849 if (response.$metadata.httpStatusCode === 200) {50 const { body, $metadata } = response5152 const textDecoder = new TextDecoder('utf-8')53 const jsonString = textDecoder.decode(body.buffer)54 const parsedData = JSON.parse(jsonString)55 console.log(parsedData)56 const image = parsedData.images[0]5758 const supabaseClient = createClient(59 // Supabase API URL - env var exported by default.60 Deno.env.get('SUPABASE_URL')!,61 // Using the default Supabase API PUB KEY.62 // If you want to use a different api key, change 'default' to your preferred key name63 SUPABASE_PUBLISHABLE_KEYS['default']64 )6566 const { data: upload, error: uploadError } = await supabaseClient.storage67 .from('images')68 .upload(`${$metadata.requestId ?? ''}.png`, decode(image), {69 contentType: 'image/png',70 cacheControl: '3600',71 upsert: false,72 })73 if (!upload) {74 return Response.json(uploadError)75 }76 const { data } = supabaseClient.storage.from('images').getPublicUrl(upload.path!)77 return Response.json(data)78 }7980 return Response.json(response)81})Run the function locally#
- Run
supabase start(see: https://supabase.com/docs/reference/cli/supabase-start) - Start with env:
supabase functions serve --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-bedrock3supabase 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.