Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

6.0 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import { InvokeModelCommand } from '@aws-sdk/client-bedrock-runtime';
import { ModelModality } from '@aws-sdk/client-bedrock';
import { awsBedrockCombinedAuth } from '../auth';
import {
  createBedrockRuntimeClient,
  getBedrockModelOptions,
  formatBedrockError,
} from '../common';

export const generateImage = createAction({
  audience: 'both',
  auth: awsBedrockCombinedAuth,
  name: 'generate_image',
  classification: 'READ',
  displayName: 'Generate Image',
  description:
    'Generate an image from a text prompt using Amazon Titan Image Generator or Stability AI models.',
  aiMetadata: { description: 'Generates one image from a text prompt using a Bedrock image model (Amazon Titan Image Generator, Nova Canvas, or Stability AI) and stores it as a file reference; supports a negative prompt, width and height, and a seed for reproducible output. Pick this to create new imagery from a description - use Generate Content from Image to interpret an existing image, and Ask Bedrock for text output. Requires an image-output model enabled in the connected AWS region, at a resolution that model supports. Not idempotent: each call invokes the model and writes a new file, though a fixed seed with the same prompt reproduces the same picture.', idempotent: false },
  props: {
    model: Property.Dropdown({
      displayName: 'Model',
      required: true,
      auth: awsBedrockCombinedAuth,
      description: 'The image generation model to use.',
      refreshers: [],
      options: async ({ auth }, { server }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your AWS account first',
            options: [],
          };
        }
        return getBedrockModelOptions(auth.props, {
          outputModality: ModelModality.IMAGE,
        }, server);
      },
    }),
    prompt: Property.LongText({
      displayName: 'Prompt',
      required: true,
      description: 'A text description of the image you want to generate.',
    }),
    negativePrompt: Property.LongText({
      displayName: 'Negative Prompt',
      required: false,
      description:
        'Describe what you do NOT want in the image. Helps refine the output.',
    }),
    width: Property.Number({
      displayName: 'Width',
      required: false,
      description: 'Image width in pixels. Must be supported by the model.',
      defaultValue: 1024,
    }),
    height: Property.Number({
      displayName: 'Height',
      required: false,
      description: 'Image height in pixels. Must be supported by the model.',
      defaultValue: 1024,
    }),
    seed: Property.Number({
      displayName: 'Seed',
      required: false,
      description:
        'A seed for reproducible results. Use the same seed and prompt to get the same image.',
    }),
  },
  async run({ auth, propsValue, files, server }) {
    const client = await createBedrockRuntimeClient({ auth: auth.props, server });
    const { model, prompt, negativePrompt, width, height, seed } = propsValue;

    const isTitan = model.startsWith('amazon.titan-image');
    const isStability = model.startsWith('stability.');
    const isNovaCanvas = model.startsWith('amazon.nova-canvas');

    let requestBody: Record<string, unknown>;

    if (isTitan) {
      requestBody = {
        taskType: 'TEXT_IMAGE',
        textToImageParams: {
          text: prompt,
          ...(negativePrompt ? { negativeText: negativePrompt } : {}),
        },
        imageGenerationConfig: {
          numberOfImages: 1,
          width: width ?? 1024,
          height: height ?? 1024,
          ...(seed != null ? { seed: seed } : {}),
        },
      };
    } else if (isNovaCanvas) {
      requestBody = {
        taskType: 'TEXT_IMAGE',
        textToImageParams: {
          text: prompt,
          ...(negativePrompt ? { negativeText: negativePrompt } : {}),
        },
        imageGenerationConfig: {
          numberOfImages: 1,
          width: width ?? 1024,
          height: height ?? 1024,
          ...(seed != null ? { seed: seed } : {}),
        },
      };
    } else if (isStability) {
      requestBody = {
        text_prompts: [
          { text: prompt, weight: 1 },
          ...(negativePrompt
            ? [{ text: negativePrompt, weight: -1 }]
            : []),
        ],
        cfg_scale: 7,
        steps: 30,
        width: width ?? 1024,
        height: height ?? 1024,
        ...(seed != null ? { seed: seed } : {}),
      };
    } else {
      requestBody = {
        text_prompts: [
          { text: prompt, weight: 1 },
          ...(negativePrompt
            ? [{ text: negativePrompt, weight: -1 }]
            : []),
        ],
        width: width ?? 1024,
        height: height ?? 1024,
        ...(seed != null ? { seed: seed } : {}),
      };
    }

    try {
      const response = await client.send(
        new InvokeModelCommand({
          modelId: model,
          body: Buffer.from(JSON.stringify(requestBody)),
          contentType: 'application/json',
          accept: 'application/json',
        })
      );

      const responseBody = JSON.parse(
        new TextDecoder().decode(response.body)
      );

      let base64Image: string | undefined;

      if (responseBody.images && responseBody.images.length > 0) {
        base64Image = responseBody.images[0];
      } else if (
        responseBody.artifacts &&
        responseBody.artifacts.length > 0
      ) {
        base64Image = responseBody.artifacts[0].base64;
      }

      if (!base64Image) {
        throw new Error(
          'No image was returned by the model. The response format may not be supported.'
        );
      }

      const imageBuffer = Buffer.from(base64Image, 'base64');

      const file = await files.write({
        fileName: 'generated-image.png',
        data: imageBuffer,
      });

      return {
        image: file,
        model: model,
      };
    } catch (error) {
      if (error instanceof Error && error.message.includes('No image')) {
        throw error;
      }
      throw new Error(formatBedrockError(error));
    }
  },
});