Edge Functions

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 .env file in the supabase directory with the following contents:

_10
AWS_DEFAULT_REGION="<your_region>"
_10
AWS_ACCESS_KEY_ID="<replace_your_own_credentials>"
_10
AWS_SECRET_ACCESS_KEY="<replace_your_own_credentials>"
_10
AWS_SESSION_TOKEN="<replace_your_own_credentials>"
_10
_10
# Mocked config files
_10
AWS_SHARED_CREDENTIALS_FILE="./aws/credentials"
_10
AWS_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:


_10
supabase functions new amazon-bedrock

And add the code to the index.ts file:

index.ts

_78
// We need to mock the file system for the AWS SDK to work.
_78
import { prepareVirtualFile } from 'https://deno.land/x/mock_file@v1.1.2/mod.ts'
_78
_78
import { BedrockRuntimeClient, InvokeModelCommand } from 'npm:@aws-sdk/client-bedrock-runtime'
_78
import { createClient } from 'npm:@supabase/supabase-js'
_78
import { decode } from 'npm:base64-arraybuffer'
_78
_78
console.log('Hello from Amazon Bedrock!')
_78
_78
Deno.serve(async (req) => {
_78
prepareVirtualFile('./aws/config')
_78
prepareVirtualFile('./aws/credentials')
_78
_78
const client = new BedrockRuntimeClient({
_78
region: Deno.env.get('AWS_DEFAULT_REGION') ?? 'us-west-2',
_78
credentials: {
_78
accessKeyId: Deno.env.get('AWS_ACCESS_KEY_ID') ?? '',
_78
secretAccessKey: Deno.env.get('AWS_SECRET_ACCESS_KEY') ?? '',
_78
sessionToken: Deno.env.get('AWS_SESSION_TOKEN') ?? '',
_78
},
_78
})
_78
_78
const { prompt, seed } = await req.json()
_78
console.log(prompt)
_78
const input = {
_78
contentType: 'application/json',
_78
accept: '*/*',
_78
modelId: 'amazon.titan-image-generator-v1',
_78
body: JSON.stringify({
_78
taskType: 'TEXT_IMAGE',
_78
textToImageParams: { text: prompt },
_78
imageGenerationConfig: {
_78
numberOfImages: 1,
_78
quality: 'standard',
_78
cfgScale: 8.0,
_78
height: 512,
_78
width: 512,
_78
seed: seed ?? 0,
_78
},
_78
}),
_78
}
_78
_78
const command = new InvokeModelCommand(input)
_78
const response = await client.send(command)
_78
console.log(response)
_78
_78
if (response.$metadata.httpStatusCode === 200) {
_78
const { body, $metadata } = response
_78
_78
const textDecoder = new TextDecoder('utf-8')
_78
const jsonString = textDecoder.decode(body.buffer)
_78
const parsedData = JSON.parse(jsonString)
_78
console.log(parsedData)
_78
const image = parsedData.images[0]
_78
_78
const supabaseClient = createClient(
_78
// Supabase API URL - env var exported by default.
_78
Deno.env.get('SUPABASE_URL')!,
_78
// Supabase API ANON KEY - env var exported by default.
_78
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
_78
)
_78
_78
const { data: upload, error: uploadError } = await supabaseClient.storage
_78
.from('images')
_78
.upload(`${$metadata.requestId ?? ''}.png`, decode(image), {
_78
contentType: 'image/png',
_78
cacheControl: '3600',
_78
upsert: false,
_78
})
_78
if (!upload) {
_78
return Response.json(uploadError)
_78
}
_78
const { data } = supabaseClient.storage.from('images').getPublicUrl(upload.path!)
_78
return Response.json(data)
_78
}
_78
_78
return Response.json(response)
_78
})

Run the function locally

  1. Run supabase start (see: https://supabase.com/docs/reference/cli/supabase-start)
  2. Start with env: supabase functions serve --env-file supabase/.env
  3. Make an HTTP request:

_10
curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/amazon-bedrock' \
_10
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \
_10
--header 'Content-Type: application/json' \
_10
--data '{"prompt":"A beautiful picture of a bird"}'

  1. Navigate back to your storage bucket. You might have to hit the refresh button to see the uploaded image.

Deploy to your hosted project


_10
supabase link
_10
supabase functions deploy amazon-bedrock
_10
supabase secrets set --env-file supabase/.env

That's it, you've now deployed a serverless function that uses AI to generate and upload images to your Supabase storage bucket.