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

feat(image-router): add AI actions and output schemas (#16293)

Kishan Parmara9b86f6ed9e5
diff --git a/packages/pieces/community/image-router/package.json b/packages/pieces/community/image-router/package.json
index f59bbd54ba0..9beff656bd7 100644
--- a/packages/pieces/community/image-router/package.json
+++ b/packages/pieces/community/image-router/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-image-router",
- "version": "0.1.8",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
diff --git a/packages/pieces/community/image-router/src/index.ts b/packages/pieces/community/image-router/src/index.ts
index 751faea9fec..92e57ac089d 100644
--- a/packages/pieces/community/image-router/src/index.ts
+++ b/packages/pieces/community/image-router/src/index.ts
@@ -1,20 +1,31 @@
-import { createPiece } from "@activepieces/pieces-framework";
-import { imageRouterAuth } from "./lib/common/auth";
-import { PieceCategory } from '@activepieces/pieces-framework';
-import { createImage } from "./lib/actions/create-image";
-import { imageToImage } from "./lib/actions/image-to-image";
+import { createCustomApiCallAction } from "@activepieces/pieces-common";
+import { createPiece, PieceCategory } from "@activepieces/pieces-framework";
+
+import { imageRouterAiActions } from "./lib/actions/ai";
+import { createImageAction } from "./lib/actions/create-image";
+import { imageToImageAction } from "./lib/actions/image-to-image";
+import { imageRouterAuth } from "./lib/auth";
+import { imageRouterClient } from "./lib/common/client";
export const imageRouter = createPiece({
displayName: "ImageRouter",
auth: imageRouterAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE],
description: "Generate images with any model available on ImageRouter.",
logoUrl: "https://cdn.activepieces.com/pieces/image-router.png",
authors: ["onyedikachi-david"],
actions: [
- createImage,
- imageToImage,
+ createImageAction,
+ imageToImageAction,
+ ...imageRouterAiActions,
+ createCustomApiCallAction({
+ auth: imageRouterAuth,
+ baseUrl: () => imageRouterClient.baseUrl(),
+ authMapping: async (auth) => ({
+ Authorization: `Bearer ${auth.secret_text}`,
+ }),
+ }),
],
triggers: [],
});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/create-chat-completion.ts b/packages/pieces/community/image-router/src/lib/actions/ai/create-chat-completion.ts
new file mode 100644
index 00000000000..bc4fbf034f0
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/create-chat-completion.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterAiProps } from '../../common/ai-props';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterChatCompletionOutputSchema } from '../../output-schemas';
+
+export const createChatCompletionAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_create_chat_completion',
+ displayName: 'Create Chat Completion',
+ description: 'Sends a conversation to a text model and returns its reply.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Sends an OpenAI-format list of chat messages to the chosen ImageRouter text model and returns the completion: choices (reply text in choices[0].message.content, finish reason, tool calls), token usage and the credits charged. Pick a model whose output_modalities include text from List Models; text models are paid, so check Get Credits first. Use Create Response for the Responses format with a single input. Not idempotent: each call runs and bills a new completion.',
+ idempotent: false,
+ },
+ props: {
+ model: imageRouterAiProps.model({
+ required: true,
+ description:
+ 'Text model id, e.g. "openai/gpt-4o-mini". Use List Models with output modality "text" to find ids.',
+ }),
+ messages: Property.Json({
+ displayName: 'Messages',
+ description:
+ 'The conversation as a JSON array of {"role", "content"} objects, e.g. [{"role":"system","content":"Be brief."},{"role":"user","content":"Hi"}]. Roles: system, developer, user, assistant, tool.',
+ required: true,
+ }),
+ temperature: Property.Number({
+ displayName: 'Temperature',
+ description: 'Sampling temperature from 0 to 2. Leave empty for the model default.',
+ required: false,
+ }),
+ maxTokens: Property.Number({
+ displayName: 'Max Tokens',
+ description: 'Maximum tokens in the reply. Leave empty for the model default.',
+ required: false,
+ }),
+ additionalParameters: Property.Json({
+ displayName: 'Additional Parameters',
+ description:
+ 'Optional JSON object of other OpenAI chat parameters passed to the model as-is, e.g. {"top_p":0.9,"response_format":{"type":"json_object"}}. Model, messages, temperature and max tokens above take precedence.',
+ required: false,
+ }),
+ },
+ outputSchema: imageRouterChatCompletionOutputSchema,
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.createChatCompletion({
+ auth,
+ body: {
+ ...propsValue.additionalParameters,
+ model: propsValue.model,
+ messages: propsValue.messages,
+ temperature: propsValue.temperature,
+ max_tokens: propsValue.maxTokens,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/create-response.ts b/packages/pieces/community/image-router/src/lib/actions/ai/create-response.ts
new file mode 100644
index 00000000000..171d8392ac2
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/create-response.ts
@@ -0,0 +1,77 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterAiProps } from '../../common/ai-props';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterResponseOutputSchema } from '../../output-schemas';
+
+export const createResponseAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_create_response',
+ displayName: 'Create Response',
+ description: 'Gets a reply from a text model in the OpenAI Responses format.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Sends a plain-text input, or a JSON array of OpenAI Responses input items (for images or multi-turn input), to the chosen ImageRouter text model and returns the response: output items (the reply text is in output[].content[].text), status, token usage and the credits charged. Pass exactly one of input or inputItems. Text models are paid; check Get Credits first. Use Create Chat Completion for a classic messages list. Not idempotent: each call runs and bills a new response.',
+ idempotent: false,
+ },
+ props: {
+ model: imageRouterAiProps.model({
+ required: true,
+ description:
+ 'Text model id, e.g. "openai/gpt-4o-mini". Use List Models with output modality "text" to find ids.',
+ }),
+ input: Property.LongText({
+ displayName: 'Input',
+ description: 'The prompt as plain text. Use this or Input Items, not both.',
+ required: false,
+ }),
+ inputItems: Property.Json({
+ displayName: 'Input Items',
+ description:
+ 'The input as a JSON array of OpenAI Responses input items, e.g. [{"role":"user","content":[{"type":"input_text","text":"Describe this"},{"type":"input_image","image_url":"https://..."}]}]. Use this or Input, not both.',
+ required: false,
+ }),
+ instructions: Property.LongText({
+ displayName: 'Instructions',
+ description: 'Optional system-level instructions for the model.',
+ required: false,
+ }),
+ maxOutputTokens: Property.Number({
+ displayName: 'Max Output Tokens',
+ description: 'Maximum tokens in the reply. Leave empty for the model default.',
+ required: false,
+ }),
+ temperature: Property.Number({
+ displayName: 'Temperature',
+ description: 'Sampling temperature from 0 to 2. Leave empty for the model default.',
+ required: false,
+ }),
+ additionalParameters: Property.Json({
+ displayName: 'Additional Parameters',
+ description:
+ 'Optional JSON object of other OpenAI Responses parameters passed as-is, e.g. {"top_p":0.9}. The fields above take precedence.',
+ required: false,
+ }),
+ },
+ outputSchema: imageRouterResponseOutputSchema,
+ async run({ auth, propsValue }) {
+ const { input, inputItems } = propsValue;
+ if ((input === undefined) === (inputItems === undefined)) {
+ throw new Error('Pass exactly one of input or inputItems.');
+ }
+ return await imageRouterApi.createResponse({
+ auth,
+ body: {
+ ...propsValue.additionalParameters,
+ model: propsValue.model,
+ input: input ?? inputItems,
+ instructions: propsValue.instructions,
+ max_output_tokens: propsValue.maxOutputTokens,
+ temperature: propsValue.temperature,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/edit-image.ts b/packages/pieces/community/image-router/src/lib/actions/ai/edit-image.ts
new file mode 100644
index 00000000000..60bf517ed23
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/edit-image.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterAiProps } from '../../common/ai-props';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterImageOutputSchema } from '../../output-schemas';
+
+export const editImageAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_edit_image',
+ outputSchema: imageRouterImageOutputSchema,
+ displayName: 'Edit Image',
+ description: 'Transforms or inpaints existing images and returns the new image URLs.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Sends 1 to 16 source images (http(s) URLs or data URIs) with an optional prompt and optional masks to an ImageRouter editing model, and returns hosted URLs of the new images plus the credits charged. Use for image-to-image work (style transfer, inpainting, combining images); use Generate Image when there is no source image. The model must accept image input (input_modalities include image in List Models); masks only work with models listing mask. Not idempotent: each call runs and bills a new generation.',
+ idempotent: false,
+ },
+ props: {
+ model: imageRouterAiProps.model({ required: true }),
+ images: Property.Array({
+ displayName: 'Images',
+ description:
+ 'Source images, 1 to 16, each an http(s) URL or a data URI such as "data:image/png;base64,...".',
+ required: true,
+ }),
+ prompt: Property.LongText({
+ displayName: 'Prompt',
+ description: 'How to change the images. Most models need one; a few (e.g. upscalers) do not.',
+ required: false,
+ }),
+ masks: Property.Array({
+ displayName: 'Masks',
+ description:
+ 'Optional mask images (URL or data URI) marking the area to edit, for models that support masks.',
+ required: false,
+ }),
+ quality: imageRouterAiProps.quality({ required: false }),
+ size: imageRouterAiProps.size({ required: false }),
+ outputFormat: imageRouterAiProps.outputFormat({ required: false }),
+ },
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.createImage({ auth, ...propsValue });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/generate-image.ts b/packages/pieces/community/image-router/src/lib/actions/ai/generate-image.ts
new file mode 100644
index 00000000000..60cfc58894d
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/generate-image.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterAiProps } from '../../common/ai-props';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterImageOutputSchema } from '../../output-schemas';
+
+export const generateImageAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_generate_image',
+ outputSchema: imageRouterImageOutputSchema,
+ displayName: 'Generate Image',
+ description: 'Generates images from a text prompt and returns their URLs.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Generates new images from a text prompt with the chosen ImageRouter model and returns hosted image URLs (kept 30 days), plus the credits charged. Use Edit Image instead when you have source images to transform. Pick a model whose output_modalities include image from List Models; free models such as "test/test" cost nothing. Not idempotent: each call runs and bills a new generation.',
+ idempotent: false,
+ },
+ props: {
+ model: imageRouterAiProps.model({ required: true }),
+ prompt: Property.LongText({
+ displayName: 'Prompt',
+ description: 'What the image should show.',
+ required: true,
+ }),
+ quality: imageRouterAiProps.quality({ required: false }),
+ size: imageRouterAiProps.size({ required: false }),
+ outputFormat: imageRouterAiProps.outputFormat({ required: false }),
+ },
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.createImage({ auth, ...propsValue });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/generate-video.ts b/packages/pieces/community/image-router/src/lib/actions/ai/generate-video.ts
new file mode 100644
index 00000000000..d7a0ebd7f94
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/generate-video.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterAiProps } from '../../common/ai-props';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterGenerateVideoOutputSchema } from '../../output-schemas';
+
+export const generateVideoAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_generate_video',
+ outputSchema: imageRouterGenerateVideoOutputSchema,
+ displayName: 'Generate Video',
+ description: 'Generates a video from a prompt and an optional start image, and returns its URL.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Generates a video with the chosen ImageRouter video model from a text prompt and/or one start image (http(s) URL or data URI), waits for it to finish, and returns the hosted video URL (kept 30 days) plus the credits charged. Pick a model whose output_modalities include video from List Models and check its allowed sizes and seconds with Get Model; "ir/test-video" is free. Not idempotent: each call runs and bills a new generation.',
+ idempotent: false,
+ },
+ props: {
+ model: imageRouterAiProps.model({
+ required: true,
+ description:
+ 'Video model id, e.g. "ir/test-video". Use List Models with output modality "video" to find ids.',
+ }),
+ prompt: Property.LongText({
+ displayName: 'Prompt',
+ description: 'What the video should show. Most models need one.',
+ required: false,
+ }),
+ image: Property.ShortText({
+ displayName: 'Start Image',
+ description: 'Optional start image for image-to-video models: an http(s) URL or a data URI.',
+ required: false,
+ }),
+ size: imageRouterAiProps.size({
+ required: false,
+ description:
+ '"auto" or WIDTHxHEIGHT such as "1280x720". Allowed sizes per model are in Get Model (sizes). Defaults to auto.',
+ }),
+ seconds: Property.Number({
+ displayName: 'Duration (seconds)',
+ description:
+ 'Video length in seconds; allowed values per model are in Get Model (seconds). Defaults to the model default.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.createVideo({ auth, ...propsValue });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/get-credits.ts b/packages/pieces/community/image-router/src/lib/actions/ai/get-credits.ts
new file mode 100644
index 00000000000..0c3445fe715
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/get-credits.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterGetCreditsOutputSchema } from '../../output-schemas';
+
+export const getCreditsAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_get_credits',
+ outputSchema: imageRouterGetCreditsOutputSchema,
+ displayName: 'Get Credits',
+ description: 'Gets the account credit balance and usage.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Gets the ImageRouter account balance in USD: remaining credits, total usage and total deposits, and optionally a per-API-key breakdown (usage, request count, spend limit and current-period spend). Use it before paid generations to check there are enough credits. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ includeKeyUsage: Property.Checkbox({
+ displayName: 'Include Usage per API Key',
+ description: 'Also return usage for each API key on the account. Defaults to off.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.getCredits({ auth, byApiKey: propsValue.includeKeyUsage === true });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/get-model.ts b/packages/pieces/community/image-router/src/lib/actions/ai/get-model.ts
new file mode 100644
index 00000000000..3533ada039a
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/get-model.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterGetModelOutputSchema } from '../../output-schemas';
+
+export const getModelAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_get_model',
+ outputSchema: imageRouterGetModelOutputSchema,
+ displayName: 'Get Model',
+ description: 'Gets one ImageRouter model with its parameters and pricing.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Gets one ImageRouter model by exact id (e.g. "openai/gpt-image-2"): its input and output modalities, supported parameters (quality, size, seconds, mask, or OpenAI text parameters), allowed sizes and durations, context length for text models, and pricing. Use it before a generation to choose valid size, quality or seconds values. Ids come from List Models. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ modelId: Property.ShortText({
+ displayName: 'Model ID',
+ description: 'Exact model id, e.g. "openai/gpt-image-2", from List Models.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return await imageRouterApi.getModel({ auth, modelId: propsValue.modelId });
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/index.ts b/packages/pieces/community/image-router/src/lib/actions/ai/index.ts
new file mode 100644
index 00000000000..524689853e2
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/index.ts
@@ -0,0 +1,19 @@
+import { createChatCompletionAction } from './create-chat-completion';
+import { createResponseAction } from './create-response';
+import { editImageAction } from './edit-image';
+import { generateImageAction } from './generate-image';
+import { generateVideoAction } from './generate-video';
+import { getCreditsAction } from './get-credits';
+import { getModelAction } from './get-model';
+import { listModelsAction } from './list-models';
+
+export const imageRouterAiActions = [
+ generateImageAction,
+ editImageAction,
+ generateVideoAction,
+ createChatCompletionAction,
+ createResponseAction,
+ listModelsAction,
+ getModelAction,
+ getCreditsAction,
+];
diff --git a/packages/pieces/community/image-router/src/lib/actions/ai/list-models.ts b/packages/pieces/community/image-router/src/lib/actions/ai/list-models.ts
new file mode 100644
index 00000000000..ba89632cc3b
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/actions/ai/list-models.ts
@@ -0,0 +1,92 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { imageRouterAuth } from '../../auth';
+import { imageRouterApi } from '../../common/api';
+import { imageRouterListModelsOutputSchema } from '../../output-schemas';
+
+const OUTPUT_MODALITIES = ['image', 'video', 'text'];
+const INPUT_MODALITIES = ['image', 'mask', 'text', 'audio', 'video'];
+const SORTS = ['name', 'provider', 'price', 'date'];
+const DEFAULT_LIMIT = 50;
+const MAX_LIMIT = 500;
+
+export const listModelsAction = createAction({
+ auth: imageRouterAuth,
+ name: 'image_router_list_models',
+ outputSchema: imageRouterListModelsOutputSchema,
+ displayName: 'List Models',
+ description: 'Lists ImageRouter models with their modalities, parameters and pricing.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists ImageRouter models, filtered by output modality (image, video, text), input modality (e.g. image for editing models, mask for inpainting), provider, free or paid, and name or alias, with each model id, modalities, supported parameters, allowed sizes and durations, and pricing. Use it to pick the model id for Generate Image, Edit Image, Generate Video, Create Chat Completion or Create Response. Returns at most limit models (default 50, max 500) with no paging, so narrow with filters. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ outputModality: Property.StaticDropdown({
+ displayName: 'Output Modality',
+ description: 'Only models producing this: image, video or text.',
+ required: false,
+ options: { options: OUTPUT_MODALITIES.map((value) => ({ label: value, value })) },
+ }),
+ inputModality: Property.StaticDropdown({
+ displayName: 'Input Modality',
+ description:
+ 'Only models accepting this input, e.g. image for editing or image-to-video models, mask for inpainting.',
+ required: false,
+ options: { options: INPUT_MODALITIES.map((value) => ({ label: value, value })) },
+ }),
+ provider: Property.ShortText({
+ displayName: 'Provider',
+ description: 'Provider name, partial and case-insensitive, e.g. "google" or "openai".',
+ required: false,
+ }),
+ free: Property.StaticDropdown({
+ displayName: 'Free',
+ description: 'Yes for free models only, No for paid models only. Leave empty for both.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Yes', value: 'true' },
+ { label: 'No', value: 'false' },
+ ],
+ },
+ }),
+ name: Property.ShortText({
+ displayName: 'Name',
+ description: 'Model name or alias, partial and case-insensitive, e.g. "flux".',
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort',
+ description: 'Sort by name, provider, price or date (release date).',
+ required: false,
+ options: { options: SORTS.map((value) => ({ label: value, value })) },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: `Maximum models to return, 1 to ${MAX_LIMIT}. Defaults to ${DEFAULT_LIMIT}.`,
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = propsValue.limit ?? DEFAULT_LIMIT;
+ if (limit < 1 || limit > MAX_LIMIT) {
+ throw new Error(`limit must be from 1 to ${MAX_LIMIT}.`);
+ }
+ const models = await imageRouterApi.listModels({
+ auth,
+ query: {
+ output_modalities: propsValue.outputModality,
+ input_modalities: propsValue.inputModality,
+ provider: propsValue.provider,
+ free: propsValue.free,
+ name: propsValue.name,
+ sort: propsValue.sort,
+ limit: String(limit),
+ },
+ });
+ return { models, count: models.length };
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/actions/create-image.ts b/packages/pieces/community/image-router/src/lib/actions/create-image.ts
index 8b307714054..e159718be80 100644
--- a/packages/pieces/community/image-router/src/lib/actions/create-image.ts
+++ b/packages/pieces/community/image-router/src/lib/actions/create-image.ts
@@ -1,16 +1,19 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { imageRouterAuth } from '../common/auth';
-import { imageRouterApiCall } from '../common/client';
-import { modelDropdown } from '../common/props';
import { randomBytes } from 'node:crypto';
+
+import { createAction, Property } from '@activepieces/pieces-framework';
import { kebabCase } from '@activepieces/pieces-framework';
-export const createImage = createAction({
- audience: 'both',
+import { imageRouterAuth } from '../auth';
+import { imageRouterApi } from '../common/api';
+import { imageRouterProps } from '../common/props';
+import { createImageOutputSchema } from '../output-schemas';
+
+export const createImageAction = createAction({
+ audience: 'human',
auth: imageRouterAuth,
name: 'createImage',
- classification: 'READ',
+ outputSchema: createImageOutputSchema,
+ classification: 'WRITE',
displayName: 'Create Image',
description: 'Generate an image from a text prompt using any available model',
aiMetadata: { description: 'Generates brand-new images from a text prompt alone, routing the request through ImageRouter to whichever hosted image model is named in the required Model input, then downloading each result and saving it as a flow file. Pick this when there is no source picture to work from; use Image to Image instead to edit, mask, or transform images you already have. Quality and size are advisory and are ignored by models that do not support them. Not idempotent: each call runs a fresh generation and returns different images.', idempotent: false },
@@ -20,7 +23,7 @@ export const createImage = createAction({
description: 'Text prompt describing the image you want to generate',
required: true,
}),
- model: modelDropdown,
+ model: imageRouterProps.model({ required: true }),
quality: Property.StaticDropdown({
displayName: 'Quality',
description: 'Image quality (not all models support this)',
@@ -58,34 +61,13 @@ export const createImage = createAction({
async run(context) {
const { prompt, model, quality, size, responseFormat } = context.propsValue;
- const body: any = {
+ const response = await imageRouterApi.generateImage({
+ auth: context.auth,
prompt,
model,
- };
-
- if (quality && quality !== 'auto') {
- body.quality = quality;
- }
-
- if (size && size !== 'auto') {
- body.size = size;
- }
-
- if (responseFormat && responseFormat !== 'url') {
- body.response_format = responseFormat;
- }
-
- const response = await imageRouterApiCall<{
- data?: Array<{
- url?: string;
- b64_json?: string;
- revised_prompt?: string;
- }>;
- }>({
- apiKey: context.auth.secret_text,
- method: HttpMethod.POST,
- resourceUri: '/v1/openai/images/generations',
- body,
+ quality,
+ size,
+ responseFormat,
});
const images = response.data || [];
@@ -103,12 +85,7 @@ export const createImage = createAction({
imageBuffer = Buffer.from(img.b64_json, 'base64');
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.png`;
} else if (img.url) {
- const downloadResponse = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: img.url,
- responseType: 'arraybuffer',
- });
- imageBuffer = Buffer.from(downloadResponse.body);
+ imageBuffer = await imageRouterApi.downloadFile({ url: img.url });
const urlExtension = img.url.split('.').pop()?.split('?')[0] || 'png';
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.${urlExtension}`;
} else {
diff --git a/packages/pieces/community/image-router/src/lib/actions/image-to-image.ts b/packages/pieces/community/image-router/src/lib/actions/image-to-image.ts
index f9b9e538afa..eedf057dd0f 100644
--- a/packages/pieces/community/image-router/src/lib/actions/image-to-image.ts
+++ b/packages/pieces/community/image-router/src/lib/actions/image-to-image.ts
@@ -1,25 +1,19 @@
-import { createAction, Property, ApFile } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient, AuthenticationType } from '@activepieces/pieces-common';
-import { imageRouterAuth } from '../common/auth';
-import { modelDropdown } from '../common/props';
-import { BASE_URL } from '../common/client';
-import FormData from 'form-data';
import { randomBytes } from 'node:crypto';
-import { kebabCase } from '@activepieces/pieces-framework';
-interface ImageItem {
- image: ApFile;
-}
+import { createAction, Property, ApFile } from '@activepieces/pieces-framework';
+import { kebabCase } from '@activepieces/pieces-framework';
-interface MaskItem {
- mask: ApFile;
-}
+import { imageRouterAuth } from '../auth';
+import { imageRouterApi } from '../common/api';
+import { imageRouterProps } from '../common/props';
+import { createImageOutputSchema } from '../output-schemas';
-export const imageToImage = createAction({
- audience: 'both',
+export const imageToImageAction = createAction({
+ audience: 'human',
auth: imageRouterAuth,
name: 'imageToImage',
- classification: 'READ',
+ outputSchema: createImageOutputSchema,
+ classification: 'WRITE',
displayName: 'Image to Image',
description: 'Generate or edit images using input image(s) with optional mask',
aiMetadata: { description: 'Edits or transforms one to sixteen supplied image files against a text prompt via ImageRouter\'s image-edit endpoint, either rewriting the whole picture or, when mask files are attached, confining the changes to the masked areas (some models require a mask). Choose this whenever a source image must be sent - inpainting, style transfer, background swaps, multi-image composition; use Create Image when generating from a prompt with no input image. At least one image file is required and the selected model must support editing. Not idempotent: each call renders new output images.', idempotent: false },
@@ -29,7 +23,7 @@ export const imageToImage = createAction({
description: 'Text prompt describing the image transformation',
required: true,
}),
- model: modelDropdown,
+ model: imageRouterProps.model({ required: true }),
images: Property.Array({
displayName: 'Input Images',
description: 'Input image(s) for editing (up to 16 images)',
@@ -91,8 +85,8 @@ export const imageToImage = createAction({
async run(context) {
const { prompt, model, images: inputImages, masks, quality, size, responseFormat } = context.propsValue;
- const imageItems = (inputImages as ImageItem[]) ?? [];
- const maskItems = (masks as MaskItem[]) ?? [];
+ const imageItems = inputImages ?? [];
+ const maskItems = masks ?? [];
if (!imageItems || imageItems.length === 0) {
throw new Error('At least one input image is required');
@@ -102,65 +96,21 @@ export const imageToImage = createAction({
throw new Error('Maximum 16 images allowed');
}
- const formData = new FormData();
-
- formData.append('prompt', prompt);
- formData.append('model', model);
-
- for (const imageItem of imageItems) {
- if (imageItem.image) {
- formData.append('image[]', Buffer.from(imageItem.image.data), imageItem.image.filename);
- }
- }
-
- if (maskItems && maskItems.length > 0) {
- for (const maskItem of maskItems) {
- if (maskItem.mask) {
- formData.append('mask[]', Buffer.from(maskItem.mask.data), maskItem.mask.filename);
- }
- }
- }
-
- if (quality && quality !== 'auto') {
- formData.append('quality', quality);
- }
-
- if (size && size !== 'auto') {
- formData.append('size', size);
- }
-
- if (responseFormat && responseFormat !== 'url') {
- formData.append('response_format', responseFormat);
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${BASE_URL}/v1/openai/images/edits`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: context.auth.secret_text,
- },
- headers: {
- ...formData.getHeaders(),
- },
- body: formData,
+ const responseBody = await imageRouterApi.editImage({
+ auth: context.auth,
+ prompt,
+ model,
+ images: imageItems.flatMap((item) =>
+ typeof item === 'object' && item !== null && 'image' in item && isFile(item.image) ? [item.image] : [],
+ ),
+ masks: maskItems.flatMap((item) =>
+ typeof item === 'object' && item !== null && 'mask' in item && isFile(item.mask) ? [item.mask] : [],
+ ),
+ quality,
+ size,
+ responseFormat,
});
- if (response.status >= 400) {
- const errorMessage = (response.body as any)?.error?.message ||
- (response.body as any)?.message ||
- `ImageRouter API error: ${response.status}`;
- throw new Error(errorMessage);
- }
-
- const responseBody = response.body as {
- data?: Array<{
- url?: string;
- b64_json?: string;
- revised_prompt?: string;
- }>;
- };
-
const generatedImages = responseBody.data || [];
if (generatedImages.length === 0) {
@@ -168,7 +118,7 @@ export const imageToImage = createAction({
}
const savedImages = await Promise.all(
- generatedImages.map(async (img: { url?: string; b64_json?: string; revised_prompt?: string }, index: number) => {
+ generatedImages.map(async (img, index) => {
let imageBuffer: Buffer;
let fileName: string;
@@ -176,12 +126,7 @@ export const imageToImage = createAction({
imageBuffer = Buffer.from(img.b64_json, 'base64');
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.png`;
} else if (img.url) {
- const downloadResponse = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: img.url,
- responseType: 'arraybuffer',
- });
- imageBuffer = Buffer.from(downloadResponse.body);
+ imageBuffer = await imageRouterApi.downloadFile({ url: img.url });
const urlExtension = img.url.split('.').pop()?.split('?')[0] || 'png';
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.${urlExtension}`;
} else {
@@ -211,3 +156,6 @@ export const imageToImage = createAction({
},
});
+function isFile(value: unknown): value is ApFile {
+ return typeof value === 'object' && value !== null && 'filename' in value && 'data' in value;
+}
diff --git a/packages/pieces/community/image-router/src/lib/auth.ts b/packages/pieces/community/image-router/src/lib/auth.ts
new file mode 100644
index 00000000000..4be58a50992
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/auth.ts
@@ -0,0 +1,45 @@
+import { AppConnectionType, PieceAuth } from '@activepieces/pieces-framework';
+
+import { imageRouterApi } from './common/api';
+
+export const imageRouterAuth = PieceAuth.SecretText({
+ displayName: 'API Key',
+ description:
+ 'Your ImageRouter API key. You can get your API key from the [ImageRouter API Keys page](https://imagerouter.io/api-keys).',
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await imageRouterApi.generateImage({
+ auth: { type: AppConnectionType.SECRET_TEXT, secret_text: auth },
+ prompt: 'test',
+ model: 'test/test',
+ });
+
+ return {
+ valid: true,
+ message: 'API key validated successfully. Connected to ImageRouter.',
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+
+ if (message.includes('401') || message.includes('403')) {
+ return {
+ valid: false,
+ error: 'Invalid API key. Please check your API key and try again.',
+ };
+ }
+
+ if (message.includes('429')) {
+ return {
+ valid: false,
+ error: 'Rate limit exceeded. Please wait a moment and try again.',
+ };
+ }
+
+ return {
+ valid: false,
+ error: `Authentication failed: ${message}. Please verify your API key is correct.`,
+ };
+ }
+ },
+});
diff --git a/packages/pieces/community/image-router/src/lib/common/ai-props.ts b/packages/pieces/community/image-router/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..925cdb8d832
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/common/ai-props.ts
@@ -0,0 +1,49 @@
+import { Property } from '@activepieces/pieces-framework';
+
+import type { PropParams } from './props';
+
+function model<R extends boolean>({
+ required,
+ displayName = 'Model',
+ description = 'Model id, e.g. "openai/gpt-image-2". Use List Models to find ids and what each model supports.',
+}: PropParams<R>) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function quality<R extends boolean>({
+ required,
+ displayName = 'Quality',
+ description = 'Output quality for models that support it. Defaults to auto.',
+}: PropParams<R>) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required,
+ options: {
+ options: ['auto', 'low', 'medium', 'high'].map((value) => ({ label: value, value })),
+ },
+ });
+}
+
+function size<R extends boolean>({
+ required,
+ displayName = 'Size',
+ description = '"auto" or WIDTHxHEIGHT such as "1024x1024". Allowed sizes per model are in Get Model. Defaults to auto.',
+}: PropParams<R>) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function outputFormat<R extends boolean>({
+ required,
+ displayName = 'Output Format',
+ description = 'Image file format. Defaults to webp.',
+}: PropParams<R>) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required,
+ options: { options: ['webp', 'jpeg', 'png'].map((value) => ({ label: value, value })) },
+ });
+}
+
+export const imageRouterAiProps = { model, quality, size, outputFormat };
diff --git a/packages/pieces/community/image-router/src/lib/common/api.ts b/packages/pieces/community/image-router/src/lib/common/api.ts
new file mode 100644
index 00000000000..ccef9815bb7
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/common/api.ts
@@ -0,0 +1,222 @@
+import FormData from 'form-data';
+
+import { HttpMethod } from '@activepieces/pieces-common';
+
+import { imageRouterClient } from './client';
+
+import type {
+ ImageRouterAuthValue,
+ ImageRouterEditImageOptions,
+ ImageRouterImageOptions,
+ ImageRouterImageResponse,
+ ImageRouterModels,
+} from './types';
+
+async function generateImage({
+ auth,
+ prompt,
+ model,
+ quality,
+ size,
+ responseFormat,
+}: ImageRouterImageOptions & { auth: ImageRouterAuthValue }): Promise<ImageRouterImageResponse> {
+ return await imageRouterClient.request<ImageRouterImageResponse>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/v1/openai/images/generations',
+ body: {
+ prompt,
+ model,
+ ...(quality && quality !== 'auto' ? { quality } : {}),
+ ...(size && size !== 'auto' ? { size } : {}),
+ ...(responseFormat && responseFormat !== 'url' ? { response_format: responseFormat } : {}),
+ },
+ });
+}
+
+async function editImage({
+ auth,
+ prompt,
+ model,
+ images,
+ masks,
+ quality,
+ size,
+ responseFormat,
+}: ImageRouterEditImageOptions & {
+ auth: ImageRouterAuthValue;
+}): Promise<ImageRouterImageResponse> {
+ const formData = new FormData();
+ formData.append('prompt', prompt);
+ formData.append('model', model);
+ for (const image of images) {
+ formData.append('image[]', Buffer.from(image.data), image.filename);
+ }
+ for (const mask of masks) {
+ formData.append('mask[]', Buffer.from(mask.data), mask.filename);
+ }
+ if (quality && quality !== 'auto') {
+ formData.append('quality', quality);
+ }
+ if (size && size !== 'auto') {
+ formData.append('size', size);
+ }
+ if (responseFormat && responseFormat !== 'url') {
+ formData.append('response_format', responseFormat);
+ }
+ return await imageRouterClient.upload<ImageRouterImageResponse>({
+ auth,
+ path: '/v1/openai/images/edits',
+ form: formData,
+ });
+}
+
+async function listImageModels({
+ auth,
+}: {
+ auth: ImageRouterAuthValue;
+}): Promise<ImageRouterModels> {
+ return await imageRouterClient.request<ImageRouterModels>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v1/models?type=image',
+ });
+}
+
+async function downloadFile({ url }: { url: string }): Promise<Buffer> {
+ return await imageRouterClient.download({ url });
+}
+
+async function createImage({
+ auth,
+ model,
+ prompt,
+ images,
+ masks,
+ quality,
+ size,
+ outputFormat,
+}: CreateImageParams) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/v1/openai/images/generations',
+ body: {
+ model,
+ prompt,
+ image: images,
+ mask: masks,
+ quality,
+ size,
+ output_format: outputFormat,
+ response_format: 'url',
+ },
+ });
+}
+
+async function createVideo({ auth, model, prompt, image, size, seconds }: CreateVideoParams) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/v1/openai/videos/generations',
+ body: { model, prompt, image, size, seconds, response_format: 'url' },
+ });
+}
+
+async function createChatCompletion({
+ auth,
+ body,
+}: {
+ auth: ImageRouterAuthValue;
+ body: Record<string, unknown>;
+}) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/v1/openai/chat/completions',
+ body: { ...body, stream: false },
+ });
+}
+
+async function createResponse({
+ auth,
+ body,
+}: {
+ auth: ImageRouterAuthValue;
+ body: Record<string, unknown>;
+}) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/v1/openai/responses',
+ body: { ...body, stream: false },
+ });
+}
+
+async function listModels({
+ auth,
+ query,
+}: {
+ auth: ImageRouterAuthValue;
+ query: Record<string, string | undefined>;
+}) {
+ return await imageRouterClient.request<unknown[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v3/models',
+ query: Object.fromEntries(
+ Object.entries(query).filter((entry): entry is [string, string] => entry[1] !== undefined),
+ ),
+ });
+}
+
+async function getModel({ auth, modelId }: { auth: ImageRouterAuthValue; modelId: string }) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/v3/models/${encodeURIComponent(modelId)}`,
+ });
+}
+
+async function getCredits({ auth, byApiKey }: { auth: ImageRouterAuthValue; byApiKey: boolean }) {
+ return await imageRouterClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v1/credits',
+ query: byApiKey ? { by_api_key: 'true' } : {},
+ });
+}
+
+export const imageRouterApi = {
+ generateImage,
+ editImage,
+ listImageModels,
+ downloadFile,
+ createImage,
+ createVideo,
+ createChatCompletion,
+ createResponse,
+ listModels,
+ getModel,
+ getCredits,
+};
+
+type CreateImageParams = {
+ auth: ImageRouterAuthValue;
+ model: string;
+ prompt?: string;
+ images?: unknown[];
+ masks?: unknown[];
+ quality?: string;
+ size?: string;
+ outputFormat?: string;
+};
+
+type CreateVideoParams = {
+ auth: ImageRouterAuthValue;
+ model: string;
+ prompt?: string;
+ image?: string;
+ size?: string;
+ seconds?: number;
+};
diff --git a/packages/pieces/community/image-router/src/lib/common/auth.ts b/packages/pieces/community/image-router/src/lib/common/auth.ts
deleted file mode 100644
index 8f362b7e560..00000000000
--- a/packages/pieces/community/image-router/src/lib/common/auth.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { PieceAuth } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { imageRouterApiCall } from './client';
-
-export const imageRouterAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: 'Your ImageRouter API key. You can get your API key from the [ImageRouter API Keys page](https://imagerouter.io/api-keys).',
- required: true,
- validate: async ({ auth }) => {
- try {
- await imageRouterApiCall({
- apiKey: auth as string,
- method: HttpMethod.POST,
- resourceUri: '/v1/openai/images/generations',
- body: {
- prompt: 'test',
- model: 'test/test',
- },
- });
-
- return {
- valid: true,
- message: 'API key validated successfully. Connected to ImageRouter.',
- };
- } catch (error: any) {
- if (error.message.includes('401') || error.message.includes('403')) {
- return {
- valid: false,
- error: 'Invalid API key. Please check your API key and try again.',
- };
- }
-
- if (error.message.includes('429')) {
- return {
- valid: false,
- error: 'Rate limit exceeded. Please wait a moment and try again.',
- };
- }
-
- return {
- valid: false,
- error: `Authentication failed: ${error.message}. Please verify your API key is correct.`,
- };
- }
- },
-});
-
diff --git a/packages/pieces/community/image-router/src/lib/common/client.ts b/packages/pieces/community/image-router/src/lib/common/client.ts
index 182df5871db..c9793e31c3e 100644
--- a/packages/pieces/community/image-router/src/lib/common/client.ts
+++ b/packages/pieces/community/image-router/src/lib/common/client.ts
@@ -1,40 +1,71 @@
-import { httpClient, HttpMethod, HttpMessageBody } from '@activepieces/pieces-common';
+import FormData from 'form-data';
-export const BASE_URL = 'https://api.imagerouter.io';
+import {
+ AuthenticationType,
+ httpClient,
+ HttpMethod,
+ QueryParams,
+} from '@activepieces/pieces-common';
-export type ImageRouterApiCallParams = {
- apiKey: string;
- method: HttpMethod;
- resourceUri: string;
- body?: any;
- headers?: Record<string, string>;
-};
+import type { ImageRouterAuthValue } from './types';
+
+function baseUrl(): string {
+ return BASE_URL;
+}
+
+async function request<T>({ auth, method, path, query, body }: RequestParams): Promise<T> {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${BASE_URL}${path}`,
+ headers: {
+ Authorization: `Bearer ${auth.secret_text}`,
+ 'Content-Type': 'application/json',
+ },
+ queryParams: query,
+ body,
+ });
+ return response.body;
+}
+
+async function upload<T>({ auth, path, form }: UploadParams): Promise<T> {
+ const response = await httpClient.sendRequest<T>({
+ method: HttpMethod.POST,
+ url: `${BASE_URL}${path}`,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: auth.secret_text,
+ },
+ headers: {
+ ...form.getHeaders(),
+ },
+ body: form,
+ });
+ return response.body;
+}
-export async function imageRouterApiCall<T extends HttpMessageBody>({
- apiKey,
- method,
- resourceUri,
- body,
- headers = {},
-}: ImageRouterApiCallParams): Promise<T> {
- const response = await httpClient.sendRequest<T>({
- method,
- url: `${BASE_URL}${resourceUri}`,
- headers: {
- 'Authorization': `Bearer ${apiKey}`,
- 'Content-Type': 'application/json',
- ...headers,
- },
- body,
- });
-
- if (response.status >= 400) {
- const errorMessage = (response.body as any)?.error?.message ||
- (response.body as any)?.message ||
- `ImageRouter API error: ${response.status}`;
- throw new Error(errorMessage);
- }
-
- return response.body;
+async function download({ url }: { url: string }): Promise<Buffer> {
+ const response = await httpClient.sendRequest({
+ method: HttpMethod.GET,
+ url,
+ responseType: 'arraybuffer',
+ });
+ return Buffer.from(response.body);
}
+export const imageRouterClient = { baseUrl, request, upload, download };
+
+const BASE_URL = 'https://api.imagerouter.io';
+
+type RequestParams = {
+ auth: ImageRouterAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: QueryParams;
+ body?: unknown;
+};
+
+type UploadParams = {
+ auth: ImageRouterAuthValue;
+ path: string;
+ form: FormData;
+};
diff --git a/packages/pieces/community/image-router/src/lib/common/props.ts b/packages/pieces/community/image-router/src/lib/common/props.ts
index f42ebf957f5..b1bce19d330 100644
--- a/packages/pieces/community/image-router/src/lib/common/props.ts
+++ b/packages/pieces/community/image-router/src/lib/common/props.ts
@@ -1,146 +1,109 @@
-import { Property } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { imageRouterApiCall } from './client';
-import { imageRouterAuth } from './auth';
+import { DropdownState, Property } from '@activepieces/pieces-framework';
-export const modelDropdown = Property.Dropdown({
- auth: imageRouterAuth,
- displayName: 'Model',
- description: 'Select an image generation model',
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
+import { imageRouterAuth } from '../auth';
+import { imageRouterApi } from './api';
- try {
- const response = await imageRouterApiCall<any>({
- apiKey: auth.secret_text,
- method: HttpMethod.GET,
- resourceUri: '/v1/models?type=image',
- });
+function model<R extends boolean>({
+ required,
+ displayName = 'Model',
+ description = 'Select an image generation model',
+}: PropParams<R>) {
+ return Property.Dropdown({
+ auth: imageRouterAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return disabledOptions({ placeholder: 'Please connect your account first' });
+ }
- let models: Array<{
- id: string;
- name: string;
- provider: string;
- category: string;
- isFree: boolean;
- isFast: boolean;
- isPremium: boolean;
- }> = [];
-
- if (response && typeof response === 'object') {
- const keys = Object.keys(response);
- if (keys.length > 0 && typeof response[keys[0]] === 'object') {
- models = keys.map((modelId) => {
- const modelData = response[modelId];
- const provider = modelData.providers?.[0]?.id ||
- modelData.providers?.[0]?.name ||
- '';
- const modelName = modelId.split('/').pop() || modelId;
-
- const isFree = modelId.includes(':free') ||
- modelData.providers?.some((p: any) =>
- p.pricing?.value === 0 ||
- (p.pricing?.type === 'fixed' && p.pricing?.value === 0)
- ) || false;
-
- const nameLower = modelName.toLowerCase();
- const isFast = nameLower.includes('fast') ||
- nameLower.includes('turbo') ||
- nameLower.includes('schnell') ||
- nameLower.includes('flash') ||
- nameLower.includes('lightning') ||
- nameLower.includes('mini');
-
- const isPremium = nameLower.includes('pro') ||
- nameLower.includes('ultra') ||
- nameLower.includes('max') ||
- nameLower.includes('quality');
-
- let category = '';
- if (isFree) {
- category = 'Free';
- } else if (isFast) {
- category = 'Fast';
- } else if (isPremium) {
- category = 'Premium';
- } else {
- category = 'Standard';
- }
-
- return {
- id: modelId,
- name: modelName,
- provider,
- category,
- isFree,
- isFast,
- isPremium,
- };
- });
- } else if (Array.isArray(response)) {
- models = response;
- } else if (Array.isArray(response.data)) {
- models = response.data;
- } else if (Array.isArray(response.models)) {
- models = response.models;
- } else if (Array.isArray(response.items)) {
- models = response.items;
- }
- }
-
- if (models.length === 0) {
- return {
- disabled: true,
- placeholder: 'No models found',
- options: [],
- };
- }
+ try {
+ const response = await imageRouterApi.listImageModels({ auth });
- const sortedModels = models.sort((a, b) => {
- if (a.isFree && !b.isFree) return -1;
- if (!a.isFree && b.isFree) return 1;
- if (a.isFast && !b.isFast) return -1;
- if (!a.isFast && b.isFast) return 1;
- if (a.isPremium && !b.isPremium) return -1;
- if (!a.isPremium && b.isPremium) return 1;
- return a.name.localeCompare(b.name);
- });
+ const models = Object.entries(response).map(([modelId, modelData]) => {
+ const provider = modelData.providers?.[0]?.id || modelData.providers?.[0]?.name || '';
+ const modelName = modelId.split('/').pop() || modelId;
- return {
- disabled: false,
- options: sortedModels.map((model) => {
- const modelId = model.id || '';
- const modelName = model.name || modelId.split('/').pop() || modelId;
- const provider = model.provider || '';
- const category = model.category || '';
-
- // Create label with clear category prefix using brackets
- const label = provider
- ? `[${category}] ${modelName} (${provider})`
- : `[${category}] ${modelName}`;
-
- return {
- label,
- value: modelId,
- };
- }),
- };
- } catch (error: any) {
- console.error('Error fetching models:', error);
- return {
- disabled: true,
- placeholder: `Failed to load models: ${error.message || 'Unknown error'}`,
- options: [],
- };
- }
- },
-});
+ const isFree =
+ modelId.includes(':free') ||
+ modelData.providers?.some(
+ (p) =>
+ p.pricing?.value === 0 || (p.pricing?.type === 'fixed' && p.pricing?.value === 0),
+ ) ||
+ false;
+ const nameLower = modelName.toLowerCase();
+ const isFast =
+ nameLower.includes('fast') ||
+ nameLower.includes('turbo') ||
+ nameLower.includes('schnell') ||
+ nameLower.includes('flash') ||
+ nameLower.includes('lightning') ||
+ nameLower.includes('mini');
+
+ const isPremium =
+ nameLower.includes('pro') ||
+ nameLower.includes('ultra') ||
+ nameLower.includes('max') ||
+ nameLower.includes('quality');
+
+ let category = '';
+ if (isFree) {
+ category = 'Free';
+ } else if (isFast) {
+ category = 'Fast';
+ } else if (isPremium) {
+ category = 'Premium';
+ } else {
+ category = 'Standard';
+ }
+
+ return { id: modelId, name: modelName, provider, category, isFree, isFast, isPremium };
+ });
+
+ if (models.length === 0) {
+ return disabledOptions({ placeholder: 'No models found' });
+ }
+
+ const sortedModels = models.sort((a, b) => {
+ if (a.isFree && !b.isFree) return -1;
+ if (!a.isFree && b.isFree) return 1;
+ if (a.isFast && !b.isFast) return -1;
+ if (!a.isFast && b.isFast) return 1;
+ if (a.isPremium && !b.isPremium) return -1;
+ if (!a.isPremium && b.isPremium) return 1;
+ return a.name.localeCompare(b.name);
+ });
+
+ return {
+ disabled: false,
+ options: sortedModels.map((m) => ({
+ label: m.provider
+ ? `[${m.category}] ${m.name} (${m.provider})`
+ : `[${m.category}] ${m.name}`,
+ value: m.id,
+ })),
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : '';
+ return disabledOptions({
+ placeholder: `Failed to load models: ${message || 'Unknown error'}`,
+ });
+ }
+ },
+ });
+}
+
+function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {
+ return { disabled: true, options: [], placeholder };
+}
+
+export const imageRouterProps = { model };
+
+export type PropParams<R extends boolean> = {
+ required: R;
+ displayName?: string;
+ description?: string;
+};
diff --git a/packages/pieces/community/image-router/src/lib/common/types.ts b/packages/pieces/community/image-router/src/lib/common/types.ts
new file mode 100644
index 00000000000..47f28169ea1
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/common/types.ts
@@ -0,0 +1,38 @@
+import type { ApFile, AppConnectionType } from '@activepieces/pieces-framework';
+
+export type ImageRouterAuthValue = {
+ type: AppConnectionType.SECRET_TEXT;
+ secret_text: string;
+};
+
+export type ImageRouterImageResponse = {
+ data?: Array<{
+ url?: string;
+ b64_json?: string;
+ revised_prompt?: string;
+ }>;
+};
+
+export type ImageRouterModels = Record<
+ string,
+ {
+ providers?: Array<{
+ id?: string;
+ name?: string;
+ pricing?: { type?: string; value?: number };
+ }>;
+ }
+>;
+
+export type ImageRouterImageOptions = {
+ prompt: string;
+ model: string;
+ quality?: string;
+ size?: string;
+ responseFormat?: string;
+};
+
+export type ImageRouterEditImageOptions = ImageRouterImageOptions & {
+ images: ApFile[];
+ masks: ApFile[];
+};
diff --git a/packages/pieces/community/image-router/src/lib/output-schemas.ts b/packages/pieces/community/image-router/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..c7bd17e9059
--- /dev/null
+++ b/packages/pieces/community/image-router/src/lib/output-schemas.ts
@@ -0,0 +1,230 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const generationFields: OutputSchema['fields'] = [
+ { key: 'created', label: 'Created At', format: 'datetime' },
+ { key: 'latency', label: 'Latency (ms)', format: 'number' },
+ { key: 'cost', label: 'Cost', format: 'currency', currency: 'USD' },
+];
+
+const modelFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Model ID' },
+ {
+ key: 'architecture',
+ label: 'Architecture',
+ children: [
+ { key: 'input_modalities', label: 'Input Modalities' },
+ { key: 'output_modalities', label: 'Output Modalities' },
+ ],
+ },
+ { key: 'created', label: 'Release Date (Unix seconds)', format: 'number' },
+ { key: 'supported_parameters', label: 'Supported Parameters' },
+ {
+ key: 'parameters',
+ label: 'Allowed Values',
+ children: [
+ { key: 'size', label: 'Sizes' },
+ { key: 'seconds', label: 'Durations (seconds)' },
+ ],
+ },
+ { key: 'context_length', label: 'Context Length (tokens)', format: 'number' },
+ {
+ key: 'pricing',
+ label: 'Pricing',
+ description:
+ 'Image and video models have min/average/max per generation in USD; text models have per-token prices.',
+ children: [
+ { key: 'min', label: 'Min Price per Generation', format: 'currency', currency: 'USD' },
+ {
+ key: 'average',
+ label: 'Average Price per Generation',
+ format: 'currency',
+ currency: 'USD',
+ },
+ { key: 'max', label: 'Max Price per Generation', format: 'currency', currency: 'USD' },
+ { key: 'prompt', label: 'Price per Input Token' },
+ { key: 'completion', label: 'Price per Output Token' },
+ { key: 'image', label: 'Price per Input Image' },
+ { key: 'request', label: 'Price per Request' },
+ { key: 'input_cache_read', label: 'Price per Cached Input Token' },
+ { key: 'input_cache_write', label: 'Price per Cache Write Token' },
+ { key: 'input_cache_write_1h', label: 'Price per 1h Cache Write Token' },
+ { key: 'web_search', label: 'Price per Web Search' },
+ { key: 'internal_reasoning', label: 'Price per Reasoning Token' },
+ ],
+ },
+];
+
+const usageFields: OutputSchema['fields'] = [
+ { key: 'total_tokens', label: 'Total Tokens', format: 'number' },
+ { key: 'cost', label: 'Upstream Cost', format: 'currency', currency: 'USD' },
+];
+
+export const imageRouterGetCreditsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'remaining_credits', label: 'Remaining Credits', format: 'currency', currency: 'USD' },
+ { key: 'credit_usage', label: 'Credit Usage', format: 'currency', currency: 'USD' },
+ { key: 'total_deposits', label: 'Total Deposits', format: 'currency', currency: 'USD' },
+ {
+ key: 'usage_by_api_key',
+ label: 'Usage by API Key',
+ labelKey: 'api_key_name',
+ listItems: [
+ { key: 'api_key_id', label: 'API Key ID' },
+ { key: 'api_key_name', label: 'API Key Name' },
+ { key: 'credit_usage', label: 'Credit Usage', format: 'currency', currency: 'USD' },
+ { key: 'total_requests', label: 'Total Requests', format: 'number' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'is_active', label: 'Active', format: 'boolean' },
+ { key: 'spend_limit', label: 'Spend Limit', format: 'currency', currency: 'USD' },
+ { key: 'spend_limit_period', label: 'Spend Limit Period' },
+ { key: 'period_spend', label: 'Spend This Period', format: 'currency', currency: 'USD' },
+ { key: 'period_start', label: 'Period Start', format: 'datetime' },
+ { key: 'expires_at', label: 'Expires At', format: 'datetime' },
+ ],
+ },
+ ],
+};
+
+export const imageRouterImageOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'data',
+ label: 'Images',
+ labelKey: 'url',
+ listItems: [
+ { key: 'url', label: 'Image URL', format: 'image' },
+ { key: 'revised_prompt', label: 'Revised Prompt' },
+ ],
+ },
+ ...generationFields,
+ ],
+};
+
+export const imageRouterGenerateVideoOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'data',
+ label: 'Videos',
+ labelKey: 'url',
+ listItems: [{ key: 'url', label: 'Video URL', format: 'url' }],
+ },
+ ...generationFields,
+ ],
+};
+
+export const createImageOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'images',
+ label: 'Saved Images',
+ labelKey: 'fileName',
+ listItems: [
+ { key: 'index', label: 'Index', format: 'number' },
+ { key: 'savedFile', label: 'Saved File', format: 'url' },
+ { key: 'fileName', label: 'File Name' },
+ { key: 'url', label: 'Image URL', format: 'image' },
+ { key: 'b64_json', label: 'Base64 Image' },
+ { key: 'revised_prompt', label: 'Revised Prompt' },
+ ],
+ },
+ {
+ key: 'data',
+ label: 'Raw Images',
+ listItems: [
+ { key: 'url', label: 'Image URL', format: 'image' },
+ { key: 'b64_json', label: 'Base64 Image' },
+ { key: 'revised_prompt', label: 'Revised Prompt' },
+ ],
+ },
+ ...generationFields,
+ ],
+};
+
+export const imageRouterGetModelOutputSchema: OutputSchema = {
+ fields: [...modelFields, { key: 'aliases', label: 'Aliases' }],
+};
+
+export const imageRouterListModelsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'models',
+ label: 'Models',
+ labelKey: 'id',
+ listItems: [...modelFields, { key: 'provider', label: 'Provider' }],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const imageRouterChatCompletionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Completion ID' },
+ { key: 'model', label: 'Model' },
+ { key: 'created', label: 'Created At (Unix seconds)', format: 'number' },
+ {
+ key: 'choices',
+ label: 'Choices',
+ labelKey: 'index',
+ listItems: [
+ { key: 'index', label: 'Index', format: 'number' },
+ {
+ key: 'message',
+ label: 'Message',
+ children: [
+ { key: 'role', label: 'Role' },
+ { key: 'content', label: 'Reply' },
+ { key: 'tool_calls', label: 'Tool Calls' },
+ ],
+ },
+ { key: 'finish_reason', label: 'Finish Reason' },
+ ],
+ },
+ {
+ key: 'usage',
+ label: 'Usage',
+ children: [
+ { key: 'prompt_tokens', label: 'Input Tokens', format: 'number' },
+ { key: 'completion_tokens', label: 'Output Tokens', format: 'number' },
+ ...usageFields,
+ ],
+ },
+ { key: 'cost', label: 'Credits Charged', format: 'currency', currency: 'USD' },
+ ],
+};
+
+export const imageRouterResponseOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Response ID' },
+ { key: 'model', label: 'Model' },
+ { key: 'status', label: 'Status' },
+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },
+ {
+ key: 'output',
+ label: 'Output',
+ labelKey: 'type',
+ listItems: [
+ { key: 'type', label: 'Type' },
+ { key: 'role', label: 'Role' },
+ {
+ key: 'content',
+ label: 'Content',
+ labelKey: 'type',
+ listItems: [
+ { key: 'type', label: 'Type' },
+ { key: 'text', label: 'Text' },
+ ],
+ },
+ ],
+ },
+ {
+ key: 'usage',
+ label: 'Usage',
+ children: [
+ { key: 'input_tokens', label: 'Input Tokens', format: 'number' },
+ { key: 'output_tokens', label: 'Output Tokens', format: 'number' },
+ ...usageFields,
+ ],
+ },
+ { key: 'cost', label: 'Credits Charged', format: 'currency', currency: 'USD' },
+ ],
+};