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(alai): let agents list, build, export and annotate Alai decks (#16728)

Odai Ahmad8faf51ec683f
diff --git a/bun.lock b/bun.lock
index a67cf10e2a5..55fc25e048e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -478,15 +478,17 @@
},
"packages/pieces/community/alai": {
"name": "@activepieces/piece-alai",
- "version": "0.2.0",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/algolia": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 89ee3328860..0ad8e0bb202 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Alai 0.3.0: three actions are no longer AI agent tools, and Custom API Call only calls the Alai API
+
+**Generate Presentation**, **Add Slide** and **Export Presentation** are no longer offered to AI agents as tools; flow steps that use them keep working unchanged. Agents get **Generate Presentation (Agent)**, **Add Slide (Agent)** and **Export Presentation (Agent)** instead: they take plain IDs and return a `generation_id` at once, which the agent polls with **Get Generation**. **Custom API Call** now sends the API key only to `https://slides-api.getalai.com/api` and refuses any other host or a path that escapes it.
+
+#### What you need to do
+
+If a Run Agent step or MCP server used one of the three actions as a tool, switch it to the matching (Agent) tool. Custom API Call steps that point at another host have to use the HTTP piece instead.
+
#### Tarvent 0.2.0: actions return the record itself, and Tarvent errors now fail the step
Tarvent actions used to return the raw GraphQL envelope, so later steps read values like `data.createContact.id` or `data.audiences.nodes`. From Tarvent 0.2.0 actions return the record itself (for example `id`), and searches return `items`, `hasMore` and `nextCursor`. Tarvent reports errors with HTTP 200, and earlier versions treated those as success; upgraded steps now fail with Tarvent's message, and a connection with a wrong API key or account ID no longer saves. These 11 actions are no longer offered to AI agents as tools: **Create/Update Contact**, **Find Contact**, **Add/Remove Contact Tag**, **Add/Remove Contact From Audience Group**, **Add/Remove A Contact From A Journey**, **Start/Stop Journey**, **Create An Audience Group**, **Find Audience Group**, **Generate A Custom Event**, **Send A Transactional Email** and **Send Campaign**. Agents get new **(AI)** tools that take plain IDs instead; **Send A Transactional Email (AI)** always respects suppression filters, and **Create or Update Contact (AI)** never replaces existing groups or tags. Searches now return up to 50 results per call with paging: **Find Audience**, **Find Campaign** and **Find Audience Group** used to return up to 100, and **Find Journey** returned only 1. Step settings are unchanged. Existing connections keep working: the API key is now a masked secret under the same field.
diff --git a/packages/pieces/community/alai/package.json b/packages/pieces/community/alai/package.json
index 4673b29201b..bbabf7bb8f9 100644
--- a/packages/pieces/community/alai/package.json
+++ b/packages/pieces/community/alai/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-alai",
- "version": "0.2.0",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -8,14 +8,17 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/alai/src/i18n/translation.json b/packages/pieces/community/alai/src/i18n/translation.json
index 402ca497d2b..d94deb2ea1d 100644
--- a/packages/pieces/community/alai/src/i18n/translation.json
+++ b/packages/pieces/community/alai/src/i18n/translation.json
@@ -1,38 +1,73 @@
{
+ "1": "1",
"AI-powered presentation generation API. Create, export, and manage professional presentations from text.": "AI-powered presentation generation API. Create, export, and manage professional presentations from text.",
"API Key": "API Key",
- "Paste your API key here.": "Paste your API key here.",
- "\nFollow these steps to get your Alai API Key:\n\n1. Go to [**https://getalai.com/api**](https://getalai.com/api) and sign up or log in.\n2. Navigate to the **API Keys** section.\n3. Click **Create API Key** and give it a name (e.g., \"Activepieces\").\n4. Copy the key and paste it below.\n": "\nFollow these steps to get your Alai API Key:\n\n1. Go to [**https://getalai.com/api**](https://getalai.com/api) and sign up or log in.\n2. Navigate to the **API Keys** section.\n3. Click **Create API Key** and give it a name (e.g., \"Activepieces\").\n4. Copy the key and paste it below.\n",
+ "Your Alai API key.": "Your Alai API key.",
+ "\nTo get your Alai API key:\n\n1. Sign in at [app.getalai.com](https://app.getalai.com).\n2. Open the account menu and choose **API**.\n3. Click **Add new API key**, name it (for example \"Activepieces\") and copy the key.\n4. Paste it below.\n\nAPI calls use the same AI credits as the Alai app.\n": "\nTo get your Alai API key:\n\n1. Sign in at [app.getalai.com](https://app.getalai.com).\n2. Open the account menu and choose **API**.\n3. Click **Add new API key**, name it (for example \"Activepieces\") and copy the key.\n4. Paste it below.\n\nAPI calls use the same AI credits as the Alai app.\n",
"Generate Presentation": "Generate Presentation",
+ "Generate Presentation (Agent)": "Generate Presentation (Agent)",
+ "Add Slide (Agent)": "Add Slide (Agent)",
+ "Export Presentation (Agent)": "Export Presentation (Agent)",
+ "Generate Speaker Notes (Agent)": "Generate Speaker Notes (Agent)",
"Get Generation": "Get Generation",
"Export Presentation": "Export Presentation",
"Add Slide": "Add Slide",
"Delete Presentation": "Delete Presentation",
+ "List Presentations": "List Presentations",
+ "List Themes": "List Themes",
+ "List Vibes": "List Vibes",
+ "Delete Slide": "Delete Slide",
+ "Generate Speaker Notes": "Generate Speaker Notes",
+ "Upload Images": "Upload Images",
"Custom API Call": "Custom API Call",
"Create a new AI-generated presentation from text.": "Create a new AI-generated presentation from text.",
- "Fetch the status and result of a generation job.": "Fetch the status and result of a generation job.",
- "Export a presentation in the specified formats.": "Export a presentation in the specified formats.",
- "Add a new slide to an existing presentation.": "Add a new slide to an existing presentation.",
- "Delete a presentation by its ID.": "Delete a presentation by its ID.",
- "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
+ "Start generating a new presentation from text.": "Start generating a new presentation from text.",
+ "Start generating a new slide in an existing presentation.": "Start generating a new slide in an existing presentation.",
+ "Start exporting a presentation as link, PDF and/or PowerPoint.": "Start exporting a presentation as link, PDF and/or PowerPoint.",
+ "Start generating speaker notes for a presentation.": "Start generating speaker notes for a presentation.",
+ "Get the status and result of a generation, slide, export or speaker-notes job.": "Get the status and result of a generation, slide, export or speaker-notes job.",
+ "Export a presentation as a link, PDF and/or PowerPoint file.": "Export a presentation as a link, PDF and/or PowerPoint file.",
+ "Generate a new slide and add it to an existing presentation.": "Generate a new slide and add it to an existing presentation.",
+ "Permanently delete a presentation.": "Permanently delete a presentation.",
+ "List your presentations, newest first, optionally filtered by title.": "List your presentations, newest first, optionally filtered by title.",
+ "List the themes you can use when generating a presentation.": "List the themes you can use when generating a presentation.",
+ "List the vibes (visual styles) you can use when generating a presentation.": "List the vibes (visual styles) you can use when generating a presentation.",
+ "Permanently delete one slide from a presentation.": "Permanently delete one slide from a presentation.",
+ "Generate speaker notes for the slides of a presentation.": "Generate speaker notes for the slides of a presentation.",
+ "Upload up to 10 images (PNG, JPEG, WebP, GIF, AVIF or SVG, 10 MB each) to use in a new presentation.": "Upload up to 10 images (PNG, JPEG, WebP, GIF, AVIF or SVG, 10 MB each) to use in a new presentation.",
+ "Make a request to any Alai API endpoint, e.g. /themes (Classic v1) or /modern/v1/ping. The API key is added for you.": "Make a request to any Alai API endpoint, e.g. /themes (Classic v1) or /modern/v1/ping. The API key is added for you.",
"Input Text": "Input Text",
"Additional Instructions": "Additional Instructions",
- "Export Formats": "Export Formats",
"Title": "Title",
- "Theme ID": "Theme ID",
"Slide Range": "Slide Range",
"Tone": "Tone",
"Content Mode": "Content Mode",
"Text Density": "Text Density",
+ "Theme ID": "Theme ID",
+ "Vibe ID": "Vibe ID",
+ "Language": "Language",
+ "Variants per Slide": "Variants per Slide",
+ "Image IDs": "Image IDs",
"Include AI Images": "Include AI Images",
+ "Include Web Images": "Include Web Images",
"Image Style": "Image Style",
+ "Image Style Instructions": "Image Style Instructions",
+ "Export Formats": "Export Formats",
"Wait for Completion": "Wait for Completion",
"Max Wait Time (seconds)": "Max Wait Time (seconds)",
- "Generation ID": "Generation ID",
"Presentation ID": "Presentation ID",
- "Presentation": "Presentation",
- "Slide Context": "Slide Context",
- "Slide Order": "Slide Order",
+ "Slide Content": "Slide Content",
+ "Slide Position": "Slide Position",
+ "Slide Type": "Slide Type",
+ "Include Images": "Include Images",
+ "Formats": "Formats",
+ "Slide IDs": "Slide IDs",
+ "Generation ID": "Generation ID",
+ "Variants": "Variants",
+ "Title Contains": "Title Contains",
+ "Limit": "Limit",
+ "Slide ID": "Slide ID",
+ "Images": "Images",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -42,37 +77,75 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "The text content to generate a presentation from.": "The text content to generate a presentation from.",
- "Extra instructions for how the presentation should be generated.": "Extra instructions for how the presentation should be generated.",
- "Formats to export the presentation in after generation.": "Formats to export the presentation in after generation.",
- "A title for the presentation. If not provided, one will be generated.": "A title for the presentation. If not provided, one will be generated.",
- "The ID of the presentation theme to use. If not provided, a default theme will be applied.": "The ID of the presentation theme to use. If not provided, a default theme will be applied.",
- "Target slide count: auto, 1, 2-5, 6-10, 11-15, 16-20, 21-25, 26-50.": "Target slide count: auto, 1, 2-5, 6-10, 11-15, 16-20, 21-25, 26-50.",
- "The tone of voice for the presentation content.": "The tone of voice for the presentation content.",
- "How the input text should be handled.": "How the input text should be handled.",
- "The amount of text to include per slide.": "The amount of text to include per slide.",
- "Whether to include AI-generated images in the presentation.": "Whether to include AI-generated images in the presentation.",
- "The style for AI-generated images.": "The style for AI-generated images.",
- "Wait for the presentation generation to complete before returning.": "Wait for the presentation generation to complete before returning.",
- "Maximum time to wait for completion (default 300 seconds / 5 minutes).": "Maximum time to wait for completion (default 300 seconds / 5 minutes).",
- "The ID of the generation job (from the \"Generate Presentation\" action).": "The ID of the generation job (from the \"Generate Presentation\" action).",
- "The ID of the presentation to export.": "The ID of the presentation to export.",
- "Formats to export the presentation in.": "Formats to export the presentation in.",
- "Select a presentation": "Select a presentation",
- "The content or topic for the slide to be generated.": "The content or topic for the slide to be generated.",
- "Extra instructions for how the slide should be generated.": "Extra instructions for how the slide should be generated.",
- "The position to insert the new slide (e.g., \"0\" for the first slide, \"end\" to add at the end).": "The position to insert the new slide (e.g., \"0\" for the first slide, \"end\" to add at the end).",
- "Whether to include AI-generated images in the slide.": "Whether to include AI-generated images in the slide.",
- "The ID of the presentation to delete.": "The ID of the presentation to delete.",
+ "The content to turn into slides: plain text, markdown or notes.": "The content to turn into slides: plain text, markdown or notes.",
+ "Extra guidance on style or focus for Alai.": "Extra guidance on style or focus for Alai.",
+ "Presentation title. If empty, Alai uses its default title.": "Presentation title. If empty, Alai uses its default title.",
+ "Target number of slides. \"auto\" decides from the input length.": "Target number of slides. \"auto\" decides from the input length.",
+ "Tone of voice. Sent to Alai as part of the instructions.": "Tone of voice. Sent to Alai as part of the instructions.",
+ "Keep, shorten or expand your text. Sent as part of the instructions.": "Keep, shorten or expand your text. Sent as part of the instructions.",
+ "How much text per slide. Sent as part of the instructions.": "How much text per slide. Sent as part of the instructions.",
+ "Theme ID from \"List Themes\". If empty, Alai uses its default theme.": "Theme ID from \"List Themes\". If empty, Alai uses its default theme.",
+ "Vibe ID from \"List Vibes\".": "Vibe ID from \"List Vibes\".",
+ "Output language. If empty, Alai matches the input language.": "Output language. If empty, Alai matches the input language.",
+ "Design options per slide (1-4). More use more credits.": "Design options per slide (1-4). More use more credits.",
+ "IDs from \"Upload Images\" to use in the slides.": "IDs from \"Upload Images\" to use in the slides.",
+ "Let Alai generate images for the slides.": "Let Alai generate images for the slides.",
+ "Let Alai search the web for images.": "Let Alai search the web for images.",
+ "Style of AI images. \"custom\" needs Image Style Instructions.": "Style of AI images. \"custom\" needs Image Style Instructions.",
+ "Describe the image look. Required when Image Style is \"custom\".": "Describe the image look. Required when Image Style is \"custom\".",
+ "Formats to produce when the deck is ready. Default: link.": "Formats to produce when the deck is ready. Default: link.",
+ "Wait until Alai finishes. If off, use \"Get Generation\" with the returned ID later.": "Wait until Alai finishes. If off, use \"Get Generation\" with the returned ID later.",
+ "How long to wait when waiting is on. Default 300, capped at 480.": "How long to wait when waiting is on. Default 300, capped at 480.",
+ "The content to turn into slides (plain text or markdown).": "The content to turn into slides (plain text or markdown).",
+ "Presentation title.": "Presentation title.",
+ "Extra guidance on style or focus.": "Extra guidance on style or focus.",
+ "Target slide count. \"auto\" decides from the input.": "Target slide count. \"auto\" decides from the input.",
+ "Tone of voice.": "Tone of voice.",
+ "Keep, condense or enhance the input text.": "Keep, condense or enhance the input text.",
+ "How much text per slide.": "How much text per slide.",
+ "Theme ID from List Themes.": "Theme ID from List Themes.",
+ "Vibe ID from List Vibes.": "Vibe ID from List Vibes.",
+ "Output language; empty matches the input.": "Output language; empty matches the input.",
+ "Image IDs uploaded to Alai earlier.": "Image IDs uploaded to Alai earlier.",
+ "The presentation ID, e.g. from List Presentations or the presentation_id of Get Generation.": "The presentation ID, e.g. from List Presentations or the presentation_id of Get Generation.",
+ "What the slide should contain.": "What the slide should contain.",
+ "0-based position; omit to append at the end.": "0-based position; omit to append at the end.",
+ "classic (editable text) or creative (image-led).": "classic (editable text) or creative (image-led).",
+ "false asks Alai for a slide without images.": "false asks Alai for a slide without images.",
+ "Extra guidance for this slide.": "Extra guidance for this slide.",
+ "One or more of link, pdf, ppt.": "One or more of link, pdf, ppt.",
+ "Only these slides; omit for all slides.": "Only these slides; omit for all slides.",
+ "The generation_id returned by another Alai action.": "The generation_id returned by another Alai action.",
+ "The presentation to export. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".": "The presentation to export. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".",
+ "Formats to produce.": "Formats to produce.",
+ "The presentation to add the slide to. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".": "The presentation to add the slide to. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".",
+ "Guidance on the style or focus of this slide.": "Guidance on the style or focus of this slide.",
+ "0-based position for the slide. Empty or \"end\" adds it last.": "0-based position for the slide. Empty or \"end\" adds it last.",
+ "Classic (editable text) or creative (image-led). Default: classic.": "Classic (editable text) or creative (image-led). Default: classic.",
+ "Turn off to ask Alai for a slide without images.": "Turn off to ask Alai for a slide without images.",
+ "Optional image style, e.g. realistic or cartoon.": "Optional image style, e.g. realistic or cartoon.",
+ "How many design options to generate for this slide (1-4).": "How many design options to generate for this slide (1-4).",
+ "The presentation to delete. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".": "The presentation to delete. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".",
+ "Only titles containing this text (not case-sensitive).": "Only titles containing this text (not case-sensitive).",
+ "Maximum number of presentations to return (default 100).": "Maximum number of presentations to return (default 100).",
+ "The presentation that contains the slide. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".": "The presentation that contains the slide. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".",
+ "The slide_id from \"Add Slide\" or from \"Generate Speaker Notes\".": "The slide_id from \"Add Slide\" or from \"Generate Speaker Notes\".",
+ "The presentation to write speaker notes for. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".": "The presentation to write speaker notes for. Use \"List Presentations\" or the presentation_id from \"Generate Presentation\".",
+ "Only these slides. Leave empty for all slides.": "Only these slides. Leave empty for all slides.",
+ "Up to 10 image files.": "Up to 10 image files.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
"On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
"Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
"Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
- "Link": "Link",
- "PDF": "PDF",
- "PowerPoint (PPTX)": "PowerPoint (PPTX)",
+ "auto": "auto",
+ "2-5": "2-5",
+ "6-10": "6-10",
+ "11-15": "11-15",
+ "16-20": "16-20",
+ "21-25": "21-25",
+ "26-50": "26-50",
"Default": "Default",
"Professional": "Professional",
"Casual": "Casual",
@@ -91,11 +164,75 @@
"Essential": "Essential",
"Balanced": "Balanced",
"Detailed": "Detailed",
+ "English (US)": "English (US)",
+ "English (UK)": "English (UK)",
+ "Spanish (Latin America)": "Spanish (Latin America)",
+ "Spanish (Mexico)": "Spanish (Mexico)",
+ "Spanish (Spain)": "Spanish (Spain)",
+ "French": "French",
+ "German": "German",
+ "Italian": "Italian",
+ "Portuguese (Brazil)": "Portuguese (Brazil)",
+ "Portuguese (Portugal)": "Portuguese (Portugal)",
+ "Dutch": "Dutch",
+ "Polish": "Polish",
+ "Russian": "Russian",
+ "Japanese": "Japanese",
+ "Korean": "Korean",
+ "Chinese (Simplified)": "Chinese (Simplified)",
+ "Hindi": "Hindi",
+ "Swedish": "Swedish",
+ "Norwegian": "Norwegian",
+ "Danish": "Danish",
+ "Finnish": "Finnish",
+ "Greek": "Greek",
+ "Turkish": "Turkish",
+ "Czech": "Czech",
+ "Hungarian": "Hungarian",
+ "Romanian": "Romanian",
+ "Bulgarian": "Bulgarian",
+ "Ukrainian": "Ukrainian",
+ "Vietnamese": "Vietnamese",
+ "Thai": "Thai",
+ "Indonesian": "Indonesian",
+ "Serbian": "Serbian",
+ "Croatian": "Croatian",
+ "Bosnian": "Bosnian",
+ "Slovenian": "Slovenian",
+ "Macedonian": "Macedonian",
+ "Albanian": "Albanian",
+ "Montenegrin": "Montenegrin",
+ "Lithuanian": "Lithuanian",
"Auto": "Auto",
"Realistic": "Realistic",
"Artistic": "Artistic",
"Cartoon": "Cartoon",
"3D": "3D",
+ "Link": "Link",
+ "PDF": "PDF",
+ "PowerPoint (PPTX)": "PowerPoint (PPTX)",
+ "DEFAULT": "DEFAULT",
+ "PROFESSIONAL": "PROFESSIONAL",
+ "CASUAL": "CASUAL",
+ "TECHNICAL": "TECHNICAL",
+ "EDUCATIONAL": "EDUCATIONAL",
+ "INSPIRATIONAL": "INSPIRATIONAL",
+ "NARRATIVE": "NARRATIVE",
+ "PERSUASIVE": "PERSUASIVE",
+ "AUTHORITATIVE": "AUTHORITATIVE",
+ "EMPATHETIC": "EMPATHETIC",
+ "PRESERVE": "PRESERVE",
+ "CONDENSE": "CONDENSE",
+ "ENHANCE": "ENHANCE",
+ "CUSTOM": "CUSTOM",
+ "MINIMAL": "MINIMAL",
+ "ESSENTIAL": "ESSENTIAL",
+ "BALANCED": "BALANCED",
+ "DETAILED": "DETAILED",
+ "classic": "classic",
+ "creative": "creative",
+ "Classic": "Classic",
+ "Creative": "Creative",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
diff --git a/packages/pieces/community/alai/src/index.ts b/packages/pieces/community/alai/src/index.ts
index be27be6c3c7..4e2299144dc 100644
--- a/packages/pieces/community/alai/src/index.ts
+++ b/packages/pieces/community/alai/src/index.ts
@@ -1,40 +1,42 @@
-import { createPiece } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
-import { alaiAuth } from './lib/common/auth';
-import { generatePresentation } from './lib/actions/generate-presentation';
-import { getGeneration } from './lib/actions/get-generation';
-import { exportPresentation } from './lib/actions/export-presentation';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { addSlide } from './lib/actions/add-slide';
+import { addSlideAi, exportPresentationAi, generatePresentationAi, generateSpeakerNotesAi } from './lib/actions/ai-actions';
+import { alaiCustomApiCall } from './lib/actions/custom-api-call';
import { deletePresentation } from './lib/actions/delete-presentation';
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { deleteSlide } from './lib/actions/delete-slide';
+import { exportPresentation } from './lib/actions/export-presentation';
+import { generatePresentation } from './lib/actions/generate-presentation';
+import { generateSpeakerNotes } from './lib/actions/generate-speaker-notes';
+import { getGeneration } from './lib/actions/get-generation';
+import { listPresentations, listThemes, listVibes } from './lib/actions/list-resources';
+import { uploadImages } from './lib/actions/upload-images';
+import { alaiAuth } from './lib/common/auth';
export const alai = createPiece({
displayName: 'Alai',
auth: alaiAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/alai.png',
- authors: ['getalai','sanket-a11y'],
- description:
- 'AI-powered presentation generation API. Create, export, and manage professional presentations from text.',
- categories: [
- PieceCategory.CONTENT_AND_FILES,
- PieceCategory.ARTIFICIAL_INTELLIGENCE,
- ],
+ authors: ['getalai', 'sanket-a11y', 'OdaiAhmed99'],
+ description: 'AI-powered presentation generation API. Create, export, and manage professional presentations from text.',
+ categories: [PieceCategory.CONTENT_AND_FILES, PieceCategory.ARTIFICIAL_INTELLIGENCE],
actions: [
generatePresentation,
+ generatePresentationAi,
+ addSlideAi,
+ exportPresentationAi,
+ generateSpeakerNotesAi,
getGeneration,
exportPresentation,
addSlide,
deletePresentation,
- createCustomApiCallAction({
- auth: alaiAuth,
- baseUrl: () => 'https://slides-api.getalai.com/api/v1',
- authMapping: async (auth) => {
- return {
- Authorization: `Bearer ${auth.props.apiKey}`,
- };
- },
- }),
+ listPresentations,
+ listThemes,
+ listVibes,
+ deleteSlide,
+ generateSpeakerNotes,
+ uploadImages,
+ alaiCustomApiCall,
],
triggers: [],
});
diff --git a/packages/pieces/community/alai/src/lib/actions/add-slide.ts b/packages/pieces/community/alai/src/lib/actions/add-slide.ts
index c9aa63782e0..03816933b8d 100644
--- a/packages/pieces/community/alai/src/lib/actions/add-slide.ts
+++ b/packages/pieces/community/alai/src/lib/actions/add-slide.ts
@@ -1,81 +1,125 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { alaiAuth } from '../common/auth';
-import { presentationId } from '../common/props';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { optionalInt, presentationIdProp } from './shared-props';
export const addSlide = createAction({
auth: alaiAuth,
name: 'addSlide',
classification: 'WRITE',
displayName: 'Add Slide',
- description: 'Add a new slide to an existing presentation.',
- audience: 'both',
+ description: 'Generate a new slide and add it to an existing presentation.',
+ audience: 'human',
+ outputSchema: alaiOutputSchemas.generation,
aiMetadata: {
description:
- 'Generate and insert a new AI-authored slide into an existing Alai presentation, given the presentation ID and the slide content/topic; optional slide order controls where it lands (a numeric index, or "end" to append). Use this to extend a deck after it has been generated. Not idempotent: each call appends another slide.',
+ 'Generates one new AI slide from slideContext and inserts it into an existing Alai presentation. slide_order is a 0-based position; leave it empty or "end" to append. includeAiImages=false and imageStyle are passed as instructions. Uses AI credits. By default returns at once with generation_id; set waitForCompletion to wait (max 480 s) and get the new slide_id. Not idempotent: each call adds another slide.',
idempotent: false,
},
props: {
- presentationId: presentationId,
+ presentationId: presentationIdProp('The presentation to add the slide to.'),
slide_context: Property.LongText({
- displayName: 'Slide Context',
- description: 'The content or topic for the slide to be generated.',
+ displayName: 'Slide Content',
+ description: 'What the slide should contain.',
required: true,
}),
additionalInstructions: Property.LongText({
displayName: 'Additional Instructions',
- description: 'Extra instructions for how the slide should be generated.',
+ description: 'Guidance on the style or focus of this slide.',
required: false,
}),
slide_order: Property.ShortText({
- displayName: 'Slide Order',
- description: 'The position to insert the new slide (e.g., "0" for the first slide, "end" to add at the end).',
+ displayName: 'Slide Position',
+ description: '0-based position for the slide. Empty or "end" adds it last.',
required: false,
}),
+ slideType: Property.StaticDropdown({
+ displayName: 'Slide Type',
+ description: 'Classic (editable text) or creative (image-led). Default: classic.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Classic', value: 'classic' },
+ { label: 'Creative', value: 'creative' },
+ ],
+ },
+ }),
includeAiImages: Property.Checkbox({
- displayName: 'Include AI Images',
- description: 'Whether to include AI-generated images in the slide.',
+ displayName: 'Include Images',
+ description: 'Turn off to ask Alai for a slide without images.',
required: false,
defaultValue: true,
}),
imageStyle: Property.ShortText({
displayName: 'Image Style',
- description: 'The style for AI-generated images.',
+ description: 'Optional image style, e.g. realistic or cartoon.',
+ required: false,
+ }),
+ variantsPerSlide: Property.Number({
+ displayName: 'Variants',
+ description: 'How many design options to generate for this slide (1-4).',
+ required: false,
+ }),
+ waitForCompletion: Property.Checkbox({
+ displayName: 'Wait for Completion',
+ description: 'Wait until Alai finishes. If off, use "Get Generation" with the returned ID later.',
required: false,
+ defaultValue: false,
+ }),
+ maxWaitTime: Property.Number({
+ displayName: 'Max Wait Time (seconds)',
+ description: 'How long to wait when waiting is on. Default 300, capped at 480.',
+ required: false,
+ defaultValue: 300,
}),
},
- async run(context) {
- const { presentationId, slide_context, additionalInstructions, slide_order, includeAiImages, imageStyle } =
- context.propsValue;
-
- const options: Record<string, unknown> = {};
- if (additionalInstructions) {
- options['additional_instructions'] = additionalInstructions;
- }
- if (slide_order) {
- options['slide_order'] = isNaN(Number(slide_order)) ? slide_order : Number(slide_order);
- }
- if (includeAiImages) {
- options['num_image_variants'] = imageStyle ? 2 : 1;
- } else {
- options['num_image_variants'] = 0;
- }
-
- const body: Record<string, unknown> = {
- slide_context: slide_context,
- options,
- export_formats: ['link'],
- };
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://slides-api.getalai.com/api/v1/presentations/${presentationId}/slides`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- 'Content-Type': 'application/json',
- },
+ async run({ auth, propsValue }) {
+ const { presentationId, body } = buildSlideRequest({ input: propsValue });
+ return alaiClient.startGeneration({
+ apiKey: auth.props.apiKey,
+ path: `/presentations/${presentationId}/slides`,
body,
+ waitForCompletion: propsValue.waitForCompletion,
+ maxWaitTime: propsValue.maxWaitTime,
+ requestedFormats: ['link'],
});
- return response.body;
},
});
+
+export type SlideInput = {
+ presentationId?: string;
+ slide_context?: string;
+ additionalInstructions?: string;
+ slide_order?: unknown;
+ slideType?: string;
+ includeAiImages?: boolean;
+ imageStyle?: string;
+ variantsPerSlide?: unknown;
+};
+
+export function buildSlideRequest({ input }: { input: SlideInput }): { presentationId: string; body: Record<string, unknown> } {
+ const presentationId = alaiClient.pathId({ value: input.presentationId, label: 'Presentation ID' });
+ const slideContext = (input.slide_context ?? '').trim();
+ if (slideContext.length === 0) {
+ throw new Error('Slide Content is required.');
+ }
+ const rawOrder = typeof input.slide_order === 'string' ? input.slide_order.trim() : input.slide_order;
+ const slideOrder = rawOrder === 'end' ? undefined : optionalInt({ value: rawOrder, label: 'Slide Position', min: 0 });
+ const variants = optionalInt({ value: input.variantsPerSlide, label: 'Variants', min: 1, max: 4 });
+ const slideType = input.slideType === '' ? undefined : input.slideType;
+ if (slideType !== undefined && slideType !== null && slideType !== 'classic' && slideType !== 'creative') {
+ throw new Error('Slide Type must be classic or creative.');
+ }
+ const options: Record<string, unknown> = {};
+ const hints = [
+ input.includeAiImages === false ? 'Do not use images on this slide.' : '',
+ input.includeAiImages !== false && input.imageStyle?.trim() ? `Image style: ${input.imageStyle.trim()}.` : '',
+ input.additionalInstructions?.trim() ?? '',
+ ].filter((part) => part.length > 0);
+ if (hints.length > 0) options['additional_instructions'] = hints.join(' ');
+ if (slideType) options['slide_type'] = slideType;
+ if (slideOrder !== undefined) options['slide_order'] = slideOrder;
+ if (variants !== undefined) options['total_variants_per_slide'] = variants;
+ return { presentationId, body: { slide_context: slideContext, options, export_formats: ['link'] } };
+}
diff --git a/packages/pieces/community/alai/src/lib/actions/ai-actions.ts b/packages/pieces/community/alai/src/lib/actions/ai-actions.ts
new file mode 100644
index 00000000000..b09f148327c
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/ai-actions.ts
@@ -0,0 +1,134 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { buildSlideRequest } from './add-slide';
+import { AMOUNT_MODES, buildGenerationBody, CONTENT_MODES, LANGUAGES, SLIDE_RANGES, TONES } from './generate-presentation';
+import { exportFormatOptions } from './shared-props';
+
+const enumOptions = (values: string[]) => ({ options: values.map((value) => ({ label: value, value })) });
+
+const presentationIdAi = Property.ShortText({
+ displayName: 'Presentation ID',
+ description: 'The presentation ID, e.g. from List Presentations or the presentation_id of Get Generation.',
+ required: true,
+});
+
+export const generatePresentationAi = createAction({
+ auth: alaiAuth,
+ name: 'generate_presentation_ai',
+ classification: 'WRITE',
+ displayName: 'Generate Presentation (Agent)',
+ description: 'Start generating a new presentation from text.',
+ audience: 'ai',
+ outputSchema: alaiOutputSchemas.generation,
+ aiMetadata: {
+ description:
+ 'Starts generating a new Alai presentation from inputText and creates it with a shareable link. Returns generation_id right away; call Get Generation with it about every 5 seconds until status is "completed" or "failed". The finished job has presentation_id and link_url. Uses Alai AI credits (more slides cost more); max 5 generations at once per user. themeId comes from List Themes, vibeId from List Vibes. Not idempotent: each call creates another presentation, so do not retry a call that returned a generation_id.',
+ idempotent: false,
+ },
+ props: {
+ inputText: Property.LongText({ displayName: 'Input Text', description: 'The content to turn into slides (plain text or markdown).', required: true }),
+ title: Property.ShortText({ displayName: 'Title', description: 'Presentation title.', required: false }),
+ additionalInstructions: Property.LongText({ displayName: 'Additional Instructions', description: 'Extra guidance on style or focus.', required: false }),
+ slideRange: Property.StaticDropdown({ displayName: 'Slide Range', description: 'Target slide count. "auto" decides from the input.', required: false, options: enumOptions(SLIDE_RANGES) }),
+ tone: Property.StaticDropdown({ displayName: 'Tone', description: 'Tone of voice.', required: false, options: enumOptions(TONES) }),
+ contentMode: Property.StaticDropdown({ displayName: 'Content Mode', description: 'Keep, condense or enhance the input text.', required: false, options: enumOptions(CONTENT_MODES) }),
+ amountMode: Property.StaticDropdown({ displayName: 'Text Density', description: 'How much text per slide.', required: false, options: enumOptions(AMOUNT_MODES) }),
+ themeId: Property.ShortText({ displayName: 'Theme ID', description: 'Theme ID from List Themes.', required: false }),
+ vibeId: Property.ShortText({ displayName: 'Vibe ID', description: 'Vibe ID from List Vibes.', required: false }),
+ language: Property.StaticDropdown({ displayName: 'Language', description: 'Output language; empty matches the input.', required: false, options: enumOptions(LANGUAGES) }),
+ imageIds: Property.Array({ displayName: 'Image IDs', description: 'Image IDs uploaded to Alai earlier.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const { body } = buildGenerationBody({ input: { ...propsValue, exportFormats: ['link'] } });
+ return alaiClient.startGeneration({ apiKey: auth.props.apiKey, path: '/generations', body, waitForCompletion: false, maxWaitTime: undefined, requestedFormats: ['link'] });
+ },
+});
+
+export const addSlideAi = createAction({
+ auth: alaiAuth,
+ name: 'add_slide_ai',
+ classification: 'WRITE',
+ displayName: 'Add Slide (Agent)',
+ description: 'Start generating a new slide in an existing presentation.',
+ audience: 'ai',
+ outputSchema: alaiOutputSchemas.generation,
+ aiMetadata: {
+ description:
+ 'Starts generating one AI slide from slideContext and inserts it into an existing Alai presentation. slideOrder is a 0-based position; omit it to append. Returns generation_id right away; call Get Generation with it about every 5 seconds until status is "completed" or "failed". The job\'s slide_id is the new slide (use it with Delete Slide). Uses AI credits. Not idempotent: each call adds another slide.',
+ idempotent: false,
+ },
+ props: {
+ presentationId: presentationIdAi,
+ slideContext: Property.LongText({ displayName: 'Slide Content', description: 'What the slide should contain.', required: true }),
+ slideOrder: Property.Number({ displayName: 'Slide Position', description: '0-based position; omit to append at the end.', required: false }),
+ slideType: Property.StaticDropdown({ displayName: 'Slide Type', description: 'classic (editable text) or creative (image-led).', required: false, options: enumOptions(['classic', 'creative']) }),
+ includeAiImages: Property.Checkbox({ displayName: 'Include Images', description: 'false asks Alai for a slide without images.', required: false, defaultValue: true }),
+ additionalInstructions: Property.LongText({ displayName: 'Additional Instructions', description: 'Extra guidance for this slide.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const { presentationId, body } = buildSlideRequest({
+ input: {
+ presentationId: propsValue.presentationId,
+ slide_context: propsValue.slideContext,
+ slide_order: propsValue.slideOrder,
+ slideType: propsValue.slideType,
+ includeAiImages: propsValue.includeAiImages,
+ additionalInstructions: propsValue.additionalInstructions,
+ },
+ });
+ return alaiClient.startGeneration({ apiKey: auth.props.apiKey, path: `/presentations/${presentationId}/slides`, body, waitForCompletion: false, maxWaitTime: undefined, requestedFormats: ['link'] });
+ },
+});
+
+export const exportPresentationAi = createAction({
+ auth: alaiAuth,
+ name: 'export_presentation_ai',
+ classification: 'WRITE',
+ displayName: 'Export Presentation (Agent)',
+ description: 'Start exporting a presentation as link, PDF and/or PowerPoint.',
+ audience: 'ai',
+ outputSchema: alaiOutputSchemas.generation,
+ aiMetadata: {
+ description:
+ 'Starts an export of an Alai presentation to the given formats: link, pdf, ppt. Returns generation_id right away; call Get Generation with it about every 5 seconds until status is "completed" or "failed". The finished job has link_url, pdf_url and ppt_url (signed, valid about 24 hours); a format with formats.<name>.status "failed" did not export. Not idempotent: each call starts a new export job (repeating it is harmless but wasteful).',
+ idempotent: false,
+ },
+ props: {
+ presentationId: presentationIdAi,
+ formats: Property.StaticMultiSelectDropdown({ displayName: 'Formats', description: 'One or more of link, pdf, ppt.', required: true, options: { options: exportFormatOptions } }),
+ },
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const formats = alaiClient.exportFormats(propsValue.formats);
+ if (formats.length === 0) {
+ throw new Error('Give at least one format: link, pdf or ppt.');
+ }
+ return alaiClient.startGeneration({ apiKey: auth.props.apiKey, path: `/presentations/${presentationId}/exports`, body: { formats }, waitForCompletion: false, maxWaitTime: undefined, requestedFormats: formats });
+ },
+});
+
+export const generateSpeakerNotesAi = createAction({
+ auth: alaiAuth,
+ name: 'generate_speaker_notes_ai',
+ classification: 'WRITE',
+ displayName: 'Generate Speaker Notes (Agent)',
+ description: 'Start generating speaker notes for a presentation.',
+ audience: 'ai',
+ outputSchema: alaiOutputSchemas.generation,
+ aiMetadata: {
+ description:
+ 'Starts AI speaker-notes generation for an Alai presentation, for all slides or only slideIds. Returns generation_id right away; call Get Generation with it about every 5 seconds until status is "completed" or "failed". The finished job has transcripts (slide_id, slide_order, title, content), which also give you slide IDs. Uses AI credits per slide. Not idempotent: each call uses credits again.',
+ idempotent: false,
+ },
+ props: {
+ presentationId: presentationIdAi,
+ slideIds: Property.Array({ displayName: 'Slide IDs', description: 'Only these slides; omit for all slides.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const slideIds = (propsValue.slideIds ?? []).map((id) => String(id).trim()).filter((id) => id.length > 0);
+ return alaiClient.startGeneration({ apiKey: auth.props.apiKey, path: `/presentations/${presentationId}/transcripts`, body: slideIds.length > 0 ? { slide_ids: slideIds } : {}, waitForCompletion: false, maxWaitTime: undefined, requestedFormats: [] });
+ },
+});
diff --git a/packages/pieces/community/alai/src/lib/actions/custom-api-call.ts b/packages/pieces/community/alai/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..6968a43a13f
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,171 @@
+import { createCustomApiCallAction, httpClient, HttpMethod, toFailsafeOutput } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+
+const API_ROOT = `${alaiClient.baseUrl}/api`;
+
+const base = createCustomApiCallAction({
+ auth: alaiAuth,
+ baseUrl: () => `${API_ROOT}/v1`,
+ authMapping: async (auth) => alaiClient.authHeaders(auth.props.apiKey),
+});
+
+export const alaiCustomApiCall = createAction({
+ auth: alaiAuth,
+ name: base.name,
+ displayName: base.displayName,
+ description: 'Make a request to any Alai API endpoint, e.g. /themes (Classic v1) or /modern/v1/ping. The API key is added for you.',
+ audience: 'human',
+ classification: 'WRITE',
+ outputSchema: alaiOutputSchemas.customApiCall,
+ aiMetadata: {
+ description:
+ 'Sends any request to the Alai API under https://slides-api.getalai.com/api (Classic /v1 and Modern /modern/v1) with the connection API key, for endpoints the other actions do not cover. Returns status, headers and body. Can change data or use credits depending on the endpoint.',
+ idempotent: false,
+ },
+ props: base.props,
+ propertyGroups: base.propertyGroups,
+ async run({ auth, propsValue, files }) {
+ const request = {
+ method: methodOf(propsValue.method),
+ url: urlOf(propsValue.url),
+ headers: { ...stringRecord(propsValue.headers), ...alaiClient.authHeaders(auth.props.apiKey) },
+ queryParams: stringRecord(propsValue.queryParams),
+ timeout: typeof propsValue.timeout === 'number' && propsValue.timeout > 0 ? propsValue.timeout * 1000 : 0,
+ followRedirects: false,
+ body: bodyOf({ body: propsValue.body, bodyType: propsValue.body_type }),
+ responseType: propsValue.response_is_binary ? ('arraybuffer' as const) : ('json' as const),
+ };
+ try {
+ const response = await httpClient.sendRequest(request, { dispatcher: await alaiClient.verifiedTls() });
+ const data: unknown = response.body;
+ if (propsValue.response_is_binary && (Buffer.isBuffer(data) || data instanceof ArrayBuffer)) {
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));
+ return {
+ status: response.status,
+ headers: response.headers,
+ body: await files.write({ fileName: `output.${extensionOf(response.headers?.['content-type'])}`, data: buffer }),
+ };
+ }
+ return { status: response.status, headers: response.headers, body: data };
+ } catch (error) {
+ if (propsValue.failsafe) {
+ return toFailsafeOutput({ error, requestBody: request.body });
+ }
+ throw error;
+ }
+ },
+});
+
+function methodOf(value: unknown): HttpMethod {
+ const method = Object.values(HttpMethod).find((option) => option === value);
+ if (!method) {
+ throw new Error('Method is required.');
+ }
+ return method;
+}
+
+export function urlOf(value: unknown): string {
+ const raw = typeof value === 'object' && value !== null ? Reflect.get(value, 'url') : undefined;
+ const text = typeof raw === 'string' ? raw.trim() : '';
+ if (text.length === 0) {
+ throw new Error('URL is required.');
+ }
+ if (text.split(/[/?#\\]/).some((part) => part === '..' || part === '.' || /^%2e(%2e)?$/i.test(part) || /%2f|%5c/i.test(part))) {
+ throw new Error('The URL must not contain "." or ".." segments or encoded slashes.');
+ }
+ if (text.includes('\\')) {
+ throw new Error('The URL must not contain backslashes.');
+ }
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(text) || text.startsWith('//');
+ const parsed = new URL(absolute ? text : relativeUrl(text));
+ if (parsed.origin !== alaiClient.baseUrl || parsed.username || parsed.password || !(parsed.pathname === '/api' || parsed.pathname.startsWith('/api/'))) {
+ throw new Error(`The URL must be under ${API_ROOT}, so your Alai API key is not sent anywhere else.`);
+ }
+ return parsed.toString();
+}
+
+function relativeUrl(text: string): string {
+ const path = text.replace(/^\/+/, '');
+ if (/^(v1|modern\/v1)(\/|$|\?)/.test(path)) {
+ return `${API_ROOT}/${path}`;
+ }
+ return `${API_ROOT}/v1/${path}`;
+}
+
+function extensionOf(contentType: unknown): string {
+ const raw = Array.isArray(contentType) ? contentType[0] : contentType;
+ const type = typeof raw === 'string' ? raw.split(';')[0].trim().toLowerCase() : '';
+ return CONTENT_TYPE_EXTENSIONS[type] ?? 'txt';
+}
+
+const CONTENT_TYPE_EXTENSIONS: Record<string, string> = {
+ 'application/pdf': 'pdf',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
+ 'application/vnd.ms-powerpoint': 'ppt',
+ 'application/json': 'json',
+ 'application/zip': 'zip',
+ 'application/octet-stream': 'bin',
+ 'text/plain': 'txt',
+ 'text/html': 'html',
+ 'text/csv': 'csv',
+ 'image/png': 'png',
+ 'image/jpeg': 'jpeg',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/avif': 'avif',
+ 'image/svg+xml': 'svg',
+};
+
+function stringRecord(value: unknown): Record<string, string> {
+ if (typeof value !== 'object' || value === null) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(value).flatMap(([key, entry]) =>
+ entry === undefined || entry === null || key.toLowerCase() === 'authorization' || key.toLowerCase() === 'api-key'
+ ? []
+ : [[key, typeof entry === 'string' ? entry : JSON.stringify(entry)]]
+ )
+ );
+}
+
+function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): FormData | string | Record<string, unknown> | unknown[] | undefined {
+ if (!bodyType || bodyType === 'none' || typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const data: unknown = Reflect.get(body, 'data');
+ if (bodyType === 'raw') {
+ return typeof data === 'string' ? data : undefined;
+ }
+ if (bodyType === 'json') {
+ if (Array.isArray(data)) {
+ return data;
+ }
+ return typeof data === 'object' && data !== null ? Object.fromEntries(Object.entries(data)) : undefined;
+ }
+ if (bodyType === 'form_data' && Array.isArray(data)) {
+ const form = new FormData();
+ for (const field of data) {
+ const name: unknown = Reflect.get(field, 'fieldName');
+ const textValue: unknown = Reflect.get(field, 'textFieldValue');
+ const file: unknown = Reflect.get(field, 'fileFieldValue');
+ if (typeof name !== 'string') {
+ continue;
+ }
+ if (Reflect.get(field, 'fieldType') === 'file' && typeof file === 'object' && file !== null) {
+ const fileData: unknown = Reflect.get(file, 'data');
+ const filename: unknown = Reflect.get(file, 'filename');
+ if (Buffer.isBuffer(fileData)) {
+ form.append(name, new Blob([new Uint8Array(fileData)]), typeof filename === 'string' ? filename : 'file');
+ }
+ } else if (typeof textValue === 'string') {
+ form.append(name, textValue);
+ }
+ }
+ return form;
+ }
+ return undefined;
+}
diff --git a/packages/pieces/community/alai/src/lib/actions/delete-presentation.ts b/packages/pieces/community/alai/src/lib/actions/delete-presentation.ts
index 613e9cc0590..e75e362fbc9 100644
--- a/packages/pieces/community/alai/src/lib/actions/delete-presentation.ts
+++ b/packages/pieces/community/alai/src/lib/actions/delete-presentation.ts
@@ -1,35 +1,36 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { presentationIdProp } from './shared-props';
export const deletePresentation = createAction({
auth: alaiAuth,
name: 'deletePresentation',
classification: 'DESTRUCTIVE',
displayName: 'Delete Presentation',
- description: 'Delete a presentation by its ID.',
+ description: 'Permanently delete a presentation.',
audience: 'both',
+ outputSchema: alaiOutputSchemas.deletePresentation,
aiMetadata: {
description:
- 'Permanently delete an Alai presentation by its ID. Use this to remove a deck the user no longer needs. Destructive but idempotent: once deleted, repeating the call with the same ID leaves the same end state. Requires the presentation ID.',
- idempotent: true,
+ 'Permanently deletes an Alai presentation by its ID; this cannot be undone. Fails with a not-found error if the ID does not exist or was already deleted, so a repeated call errors.',
+ idempotent: false,
},
props: {
- presentationId: Property.ShortText({
- displayName: 'Presentation ID',
- description: 'The ID of the presentation to delete.',
- required: true,
- }),
+ presentationId: presentationIdProp('The presentation to delete.'),
},
- async run(context) {
- const { presentationId } = context.propsValue;
- const response = await httpClient.sendRequest({
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const body = await alaiClient.request<{ success?: boolean; presentation_id?: string }>({
+ apiKey: auth.props.apiKey,
method: HttpMethod.DELETE,
- url: `https://slides-api.getalai.com/api/v1/presentations/${presentationId}`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- },
+ path: `/presentations/${presentationId}`,
});
- return response.body;
+ if (body?.success === false) {
+ throw new Error(`Alai did not delete presentation ${propsValue.presentationId}.`);
+ }
+ return { success: true, presentation_id: body?.presentation_id ?? propsValue.presentationId.trim() };
},
});
diff --git a/packages/pieces/community/alai/src/lib/actions/delete-slide.ts b/packages/pieces/community/alai/src/lib/actions/delete-slide.ts
new file mode 100644
index 00000000000..979454d5b79
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/delete-slide.ts
@@ -0,0 +1,42 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { presentationIdProp } from './shared-props';
+
+export const deleteSlide = createAction({
+ auth: alaiAuth,
+ name: 'deleteSlide',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Slide',
+ description: 'Permanently delete one slide from a presentation.',
+ audience: 'both',
+ outputSchema: alaiOutputSchemas.deleteSlide,
+ aiMetadata: {
+ description:
+ 'Permanently deletes one slide from an Alai presentation by presentation ID and slide ID (slide_id from Add Slide or from speaker-notes transcripts); this cannot be undone. Fails with a not-found error if the slide does not exist, so a repeated call errors.',
+ idempotent: false,
+ },
+ props: {
+ presentationId: presentationIdProp('The presentation that contains the slide.'),
+ slideId: Property.ShortText({
+ displayName: 'Slide ID',
+ description: 'The slide_id from "Add Slide" or from "Generate Speaker Notes".',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const slideId = alaiClient.pathId({ value: propsValue.slideId, label: 'Slide ID' });
+ const body = await alaiClient.request<{ success?: boolean }>({
+ apiKey: auth.props.apiKey,
+ method: HttpMethod.DELETE,
+ path: `/presentations/${presentationId}/slides/${slideId}`,
+ });
+ if (body?.success === false) {
+ throw new Error(`Alai did not delete slide ${propsValue.slideId}.`);
+ }
+ return { success: true, presentation_id: propsValue.presentationId.trim(), slide_id: propsValue.slideId.trim() };
+ },
+});
diff --git a/packages/pieces/community/alai/src/lib/actions/export-presentation.ts b/packages/pieces/community/alai/src/lib/actions/export-presentation.ts
index 7ea5c091729..842d87f8ba9 100644
--- a/packages/pieces/community/alai/src/lib/actions/export-presentation.ts
+++ b/packages/pieces/community/alai/src/lib/actions/export-presentation.ts
@@ -1,110 +1,56 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { alaiAuth } from '../common/auth';
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { exportFormatOptions, presentationIdProp } from './shared-props';
+
export const exportPresentation = createAction({
auth: alaiAuth,
name: 'exportPresentation',
classification: 'WRITE',
displayName: 'Export Presentation',
- description: 'Export a presentation in the specified formats.',
- audience: 'both',
+ description: 'Export a presentation as a link, PDF and/or PowerPoint file.',
+ audience: 'human',
+ outputSchema: alaiOutputSchemas.generation,
aiMetadata: {
description:
- 'Export an existing Alai presentation into one or more formats (link, PDF, and/or PPTX) by its presentation ID. Use this to render a deck for download or sharing. By default it returns immediately with a generation_id (poll Get Generation for status); set Wait for Completion to block until the export finishes (up to Max Wait Time). Not idempotent: each call kicks off a new export job. Requires the presentation ID and at least one export format.',
+ 'Starts an export of an existing Alai presentation to link, pdf and/or ppt by presentation ID. By default returns at once with generation_id; set waitForCompletion to wait (max 480 s) and get link_url, pdf_url and ppt_url (signed, valid about 24 h). Fails if a requested format failed. Not idempotent: each call starts a new export job.',
idempotent: false,
},
props: {
- presentationId: Property.ShortText({
- displayName: 'Presentation ID',
- description: 'The ID of the presentation to export.',
- required: true,
- }),
+ presentationId: presentationIdProp('The presentation to export.'),
exportFormats: Property.StaticMultiSelectDropdown({
displayName: 'Export Formats',
- description: 'Formats to export the presentation in.',
+ description: 'Formats to produce.',
required: true,
- options: {
- options: [
- { label: 'Link', value: 'link' },
- { label: 'PDF', value: 'pdf' },
- { label: 'PowerPoint (PPTX)', value: 'ppt' },
- ],
- },
+ options: { options: exportFormatOptions },
}),
waitForCompletion: Property.Checkbox({
displayName: 'Wait for Completion',
- description:
- 'Wait for the presentation generation to complete before returning.',
+ description: 'Wait until Alai finishes. If off, use "Get Generation" with the returned ID later.',
required: false,
defaultValue: false,
}),
maxWaitTime: Property.Number({
displayName: 'Max Wait Time (seconds)',
- description:
- 'Maximum time to wait for completion (default 300 seconds / 5 minutes).',
+ description: 'How long to wait when waiting is on. Default 300, capped at 480.',
required: false,
defaultValue: 300,
}),
},
- async run(context) {
- const { presentationId, exportFormats, waitForCompletion, maxWaitTime } =
- context.propsValue;
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://slides-api.getalai.com/api/v1/presentations/${presentationId}/exports`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- 'Content-Type': 'application/json',
- },
- body: {
- export_formats: exportFormats,
- },
- });
- const generationId = response.body?.generation_id;
-
- if (!generationId) {
- throw new Error(
- `Failed to get generation_id from response: ${JSON.stringify(
- response.body
- )}`
- );
- }
-
- if (!waitForCompletion) {
- return response.body;
- }
-
- await sleep(1000);
-
- // Poll for completion
- const maxWait = (maxWaitTime || 300) * 1000; // Convert to milliseconds
- const startTime = Date.now();
- const pollInterval = 5000; // Poll every 5 seconds
-
- while (Date.now() - startTime < maxWait) {
- const statusResponse = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://slides-api.getalai.com/api/v1/generations/${generationId}`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- },
- });
-
- const status = statusResponse.body?.status;
-
- if (status === 'completed') {
- return statusResponse.body;
- } else if (status === 'failed') {
- throw new Error(
- `Generation failed: ${statusResponse.body?.error || 'Unknown error'}`
- );
- }
-
- // Wait before polling again
- await sleep(pollInterval);
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const formats = alaiClient.exportFormats(propsValue.exportFormats);
+ if (formats.length === 0) {
+ throw new Error('Choose at least one export format.');
}
-
- throw new Error(`Generation timed out after ${maxWaitTime || 300} seconds`);
+ return alaiClient.startGeneration({
+ apiKey: auth.props.apiKey,
+ path: `/presentations/${presentationId}/exports`,
+ body: { formats },
+ waitForCompletion: propsValue.waitForCompletion,
+ maxWaitTime: propsValue.maxWaitTime,
+ requestedFormats: formats,
+ });
},
});
diff --git a/packages/pieces/community/alai/src/lib/actions/generate-presentation.ts b/packages/pieces/community/alai/src/lib/actions/generate-presentation.ts
index e6222ceb287..6bd9e94482e 100644
--- a/packages/pieces/community/alai/src/lib/actions/generate-presentation.ts
+++ b/packages/pieces/community/alai/src/lib/actions/generate-presentation.ts
@@ -1,8 +1,26 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { exportFormatOptions, optionalInt } from './shared-props';
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+export const LANGUAGES = [
+ 'English (US)', 'English (UK)', 'Spanish (Latin America)', 'Spanish (Mexico)', 'Spanish (Spain)', 'French', 'German',
+ 'Italian', 'Portuguese (Brazil)', 'Portuguese (Portugal)', 'Dutch', 'Polish', 'Russian', 'Japanese', 'Korean',
+ 'Chinese (Simplified)', 'Hindi', 'Swedish', 'Norwegian', 'Danish', 'Finnish', 'Greek', 'Turkish', 'Czech', 'Hungarian',
+ 'Romanian', 'Bulgarian', 'Ukrainian', 'Vietnamese', 'Thai', 'Indonesian', 'Serbian', 'Croatian', 'Bosnian', 'Slovenian',
+ 'Macedonian', 'Albanian', 'Montenegrin', 'Lithuanian',
+];
+export const SLIDE_RANGES = ['auto', '1', '2-5', '6-10', '11-15', '16-20', '21-25', '26-50'];
+export const TONES = ['DEFAULT', 'PROFESSIONAL', 'CASUAL', 'TECHNICAL', 'EDUCATIONAL', 'INSPIRATIONAL', 'NARRATIVE', 'PERSUASIVE', 'AUTHORITATIVE', 'EMPATHETIC'];
+export const CONTENT_MODES = ['PRESERVE', 'CONDENSE', 'ENHANCE', 'CUSTOM'];
+export const AMOUNT_MODES = ['MINIMAL', 'ESSENTIAL', 'BALANCED', 'DETAILED'];
+const CONTENT_MODE_HINTS: Record<string, string> = {
+ PRESERVE: 'Keep the input text as written.',
+ CONDENSE: 'Condense the input text.',
+ ENHANCE: 'Expand and enhance the input text.',
+};
+export const IMAGE_STYLES = ['auto', 'realistic', 'artistic', 'cartoon', 'three_d', 'custom'];
export const generatePresentation = createAction({
auth: alaiAuth,
@@ -10,242 +28,233 @@ export const generatePresentation = createAction({
classification: 'WRITE',
displayName: 'Generate Presentation',
description: 'Create a new AI-generated presentation from text.',
- audience: 'both',
+ audience: 'human',
+ outputSchema: alaiOutputSchemas.generation,
aiMetadata: {
description:
- 'Generate a brand-new presentation from input text via the Alai AI API, with optional controls for tone, slide count, text density, theme, and AI images. Use this to turn raw text into slides. By default it returns immediately with a generation_id (poll Get Generation for status); set Wait for Completion to block until the deck finishes (up to Max Wait Time). Not idempotent: each call starts a new generation.',
+ 'Starts a new Alai presentation generated from input text. Uses Alai AI credits (more slides cost more); Alai allows 5 generations at once per user. By default returns at once with generation_id and status "pending"; set waitForCompletion to wait (max 480 s) and get presentation_id and link/pdf/ppt URLs. Theme, vibe and image IDs come from List Themes, List Vibes and Upload Images. Tone, content mode and text density are added to the instructions sent to Alai. Not idempotent: each call creates another presentation.',
idempotent: false,
},
props: {
inputText: Property.LongText({
displayName: 'Input Text',
- description: 'The text content to generate a presentation from.',
+ description: 'The content to turn into slides: plain text, markdown or notes.',
required: true,
}),
additionalInstructions: Property.LongText({
displayName: 'Additional Instructions',
- description:
- 'Extra instructions for how the presentation should be generated.',
+ description: 'Extra guidance on style or focus for Alai.',
required: false,
}),
- exportFormats: Property.StaticMultiSelectDropdown({
- displayName: 'Export Formats',
- description: 'Formats to export the presentation in after generation.',
- required: false,
- options: {
- options: [
- { label: 'Link', value: 'link' },
- { label: 'PDF', value: 'pdf' },
- { label: 'PowerPoint (PPTX)', value: 'ppt' },
- ],
- },
- }),
title: Property.ShortText({
displayName: 'Title',
- description:
- 'A title for the presentation. If not provided, one will be generated.',
+ description: 'Presentation title. If empty, Alai uses its default title.',
required: false,
}),
- themeId: Property.ShortText({
- displayName: 'Theme ID',
- description:
- 'The ID of the presentation theme to use. If not provided, a default theme will be applied.',
- required: false,
- }),
- slideRange: Property.ShortText({
+ slideRange: Property.StaticDropdown({
displayName: 'Slide Range',
- description:
- 'Target slide count: auto, 1, 2-5, 6-10, 11-15, 16-20, 21-25, 26-50.',
+ description: 'Target number of slides. "auto" decides from the input length.',
required: false,
+ options: { options: SLIDE_RANGES.map((value) => ({ label: value, value })) },
}),
tone: Property.StaticDropdown({
displayName: 'Tone',
- description: 'The tone of voice for the presentation content.',
+ description: 'Tone of voice. Sent to Alai as part of the instructions.',
required: false,
- options: {
- options: [
- { label: 'Default', value: 'DEFAULT' },
- { label: 'Professional', value: 'PROFESSIONAL' },
- { label: 'Casual', value: 'CASUAL' },
- { label: 'Technical', value: 'TECHNICAL' },
- { label: 'Educational', value: 'EDUCATIONAL' },
- { label: 'Inspirational', value: 'INSPIRATIONAL' },
- { label: 'Narrative', value: 'NARRATIVE' },
- { label: 'Persuasive', value: 'PERSUASIVE' },
- { label: 'Authoritative', value: 'AUTHORITATIVE' },
- { label: 'Empathetic', value: 'EMPATHETIC' },
- ],
- },
+ options: { options: TONES.map((value) => ({ label: titleCase(value), value })) },
}),
contentMode: Property.StaticDropdown({
displayName: 'Content Mode',
- description: 'How the input text should be handled.',
+ description: 'Keep, shorten or expand your text. Sent as part of the instructions.',
required: false,
- options: {
- options: [
- { label: 'Preserve', value: 'PRESERVE' },
- { label: 'Condense', value: 'CONDENSE' },
- { label: 'Enhance', value: 'ENHANCE' },
- { label: 'Custom', value: 'CUSTOM' },
- ],
- },
+ options: { options: CONTENT_MODES.map((value) => ({ label: titleCase(value), value })) },
}),
amountMode: Property.StaticDropdown({
displayName: 'Text Density',
- description: 'The amount of text to include per slide.',
+ description: 'How much text per slide. Sent as part of the instructions.',
+ required: false,
+ options: { options: AMOUNT_MODES.map((value) => ({ label: titleCase(value), value })) },
+ }),
+ themeId: Property.ShortText({
+ displayName: 'Theme ID',
+ description: 'Theme ID from "List Themes". If empty, Alai uses its default theme.',
+ required: false,
+ }),
+ vibeId: Property.ShortText({
+ displayName: 'Vibe ID',
+ description: 'Vibe ID from "List Vibes".',
+ required: false,
+ }),
+ language: Property.StaticDropdown({
+ displayName: 'Language',
+ description: 'Output language. If empty, Alai matches the input language.',
+ required: false,
+ options: { options: LANGUAGES.map((value) => ({ label: value, value })) },
+ }),
+ variantsPerSlide: Property.Number({
+ displayName: 'Variants per Slide',
+ description: 'Design options per slide (1-4). More use more credits.',
+ required: false,
+ }),
+ imageIds: Property.Array({
+ displayName: 'Image IDs',
+ description: 'IDs from "Upload Images" to use in the slides.',
required: false,
- options: {
- options: [
- { label: 'Minimal', value: 'MINIMAL' },
- { label: 'Essential', value: 'ESSENTIAL' },
- { label: 'Balanced', value: 'BALANCED' },
- { label: 'Detailed', value: 'DETAILED' },
- ],
- },
}),
includeAiImages: Property.Checkbox({
displayName: 'Include AI Images',
- description:
- 'Whether to include AI-generated images in the presentation.',
+ description: 'Let Alai generate images for the slides.',
+ required: false,
+ defaultValue: true,
+ }),
+ includeWebImages: Property.Checkbox({
+ displayName: 'Include Web Images',
+ description: 'Let Alai search the web for images.',
required: false,
defaultValue: true,
}),
imageStyle: Property.StaticDropdown({
displayName: 'Image Style',
- description: 'The style for AI-generated images.',
+ description: 'Style of AI images. "custom" needs Image Style Instructions.',
required: false,
options: {
- options: [
- { label: 'Auto', value: 'auto' },
- { label: 'Realistic', value: 'realistic' },
- { label: 'Artistic', value: 'artistic' },
- { label: 'Cartoon', value: 'cartoon' },
- { label: '3D', value: 'three_d' },
- ],
+ options: IMAGE_STYLES.map((value) => ({ label: value === 'three_d' ? '3D' : titleCase(value.toUpperCase()), value })),
},
}),
+ imageStyleInstructions: Property.LongText({
+ displayName: 'Image Style Instructions',
+ description: 'Describe the image look. Required when Image Style is "custom".',
+ required: false,
+ }),
+ exportFormats: Property.StaticMultiSelectDropdown({
+ displayName: 'Export Formats',
+ description: 'Formats to produce when the deck is ready. Default: link.',
+ required: false,
+ options: { options: exportFormatOptions },
+ }),
waitForCompletion: Property.Checkbox({
displayName: 'Wait for Completion',
- description:
- 'Wait for the presentation generation to complete before returning.',
+ description: 'Wait until Alai finishes. If off, use "Get Generation" with the returned ID later.',
required: false,
defaultValue: false,
}),
maxWaitTime: Property.Number({
displayName: 'Max Wait Time (seconds)',
- description:
- 'Maximum time to wait for completion (default 300 seconds / 5 minutes).',
+ description: 'How long to wait when waiting is on. Default 300, capped at 480.',
required: false,
defaultValue: 300,
}),
},
- async run(context) {
- const {
- inputText,
- additionalInstructions,
- exportFormats,
- title,
- themeId,
- slideRange,
- tone,
- contentMode,
- amountMode,
- includeAiImages,
- imageStyle,
- waitForCompletion,
- maxWaitTime,
- } = context.propsValue;
-
- const body: Record<string, unknown> = {
- input_text: inputText,
- };
-
- if (additionalInstructions)
- body['additional_instructions'] = additionalInstructions;
- if (exportFormats && exportFormats.length > 0)
- body['export_formats'] = exportFormats;
- else body['export_formats'] = ['link'];
-
- const presentationOptions: Record<string, unknown> = {};
- if (title) presentationOptions['title'] = title;
- if (themeId) presentationOptions['theme_id'] = themeId;
- if (slideRange) presentationOptions['slide_range'] = slideRange;
- if (Object.keys(presentationOptions).length > 0) {
- body['presentation_options'] = presentationOptions;
- }
-
- const textOptions: Record<string, unknown> = {};
- if (tone) textOptions['tone'] = tone;
- if (contentMode) textOptions['content_mode'] = contentMode;
- if (amountMode) textOptions['amount_mode'] = amountMode;
- if (Object.keys(textOptions).length > 0) {
- body['text_options'] = textOptions;
- }
-
- const imageOptions: Record<string, unknown> = {};
- if (includeAiImages !== undefined && includeAiImages !== null) {
- imageOptions['include_ai_images'] = includeAiImages;
- }
- if (imageStyle) imageOptions['style'] = imageStyle;
- if (Object.keys(imageOptions).length > 0) {
- body['image_options'] = imageOptions;
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: 'https://slides-api.getalai.com/api/v1/generations',
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- 'Content-Type': 'application/json',
- },
+ async run({ auth, propsValue }) {
+ const { body, formats } = buildGenerationBody({ input: propsValue });
+ return alaiClient.startGeneration({
+ apiKey: auth.props.apiKey,
+ path: '/generations',
body,
+ waitForCompletion: propsValue.waitForCompletion,
+ maxWaitTime: propsValue.maxWaitTime,
+ requestedFormats: formats,
});
+ },
+});
- const generationId = response.body?.generation_id;
-
- if (!generationId) {
- throw new Error(
- `Failed to get generation_id from response: ${JSON.stringify(
- response.body
- )}`
- );
- }
-
- if (!waitForCompletion) {
- return response.body;
- }
- // Wait a bit before polling to ensure the generation is indexed in the database
- await sleep(1000);
+export type GenerationInput = {
+ inputText?: string;
+ additionalInstructions?: string;
+ title?: string;
+ slideRange?: unknown;
+ tone?: unknown;
+ contentMode?: unknown;
+ amountMode?: unknown;
+ themeId?: string;
+ vibeId?: string;
+ language?: string;
+ variantsPerSlide?: unknown;
+ imageIds?: unknown[];
+ includeAiImages?: boolean;
+ includeWebImages?: boolean;
+ imageStyle?: string;
+ imageStyleInstructions?: string;
+ exportFormats?: unknown;
+};
- // Poll for completion
- const maxWait = (maxWaitTime || 300) * 1000; // Convert to milliseconds
- const startTime = Date.now();
- const pollInterval = 5000; // Poll every 5 seconds
+export function buildGenerationBody({ input }: { input: GenerationInput }): { body: Record<string, unknown>; formats: string[] } {
+ const inputText = (input.inputText ?? '').trim();
+ if (inputText.length === 0) {
+ throw new Error('Input Text is required.');
+ }
+ const formats = alaiClient.exportFormats(input.exportFormats);
+ const style = input.imageStyle === '' ? undefined : input.imageStyle;
+ if (style !== undefined && style !== null && !IMAGE_STYLES.includes(style)) {
+ throw new Error(`Image Style must be one of ${IMAGE_STYLES.join(', ')}.`);
+ }
+ const styleInstructions = input.imageStyleInstructions?.trim();
+ if (style === 'custom' && !styleInstructions) {
+ throw new Error('Image Style Instructions are required when Image Style is "custom".');
+ }
+ const slideRange = input.slideRange === '' ? undefined : input.slideRange;
+ if (slideRange !== undefined && slideRange !== null && !SLIDE_RANGES.includes(String(slideRange))) {
+ throw new Error(`Slide Range must be one of ${SLIDE_RANGES.join(', ')}.`);
+ }
+ const language = input.language === '' ? undefined : input.language;
+ if (language !== undefined && language !== null && !LANGUAGES.includes(language)) {
+ throw new Error(`Language "${language}" is not supported by Alai.`);
+ }
+ const variants = optionalInt({ value: input.variantsPerSlide, label: 'Variants per Slide', min: 1, max: 4 });
+ const imageIds = (input.imageIds ?? []).map((id) => String(id).trim()).filter((id) => id.length > 0);
- while (Date.now() - startTime < maxWait) {
- const statusResponse = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://slides-api.getalai.com/api/v1/generations/${generationId}`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- },
- });
+ const presentationOptions: Record<string, unknown> = {};
+ if (input.title?.trim()) presentationOptions['title'] = input.title.trim();
+ if (input.themeId?.trim()) presentationOptions['theme_id'] = input.themeId.trim();
+ if (input.vibeId?.trim()) presentationOptions['vibe_id'] = input.vibeId.trim();
+ if (slideRange) presentationOptions['slide_range'] = String(slideRange);
+ if (variants !== undefined) presentationOptions['total_variants_per_slide'] = variants;
- const status = statusResponse.body?.status;
+ const imageOptions: Record<string, unknown> = {};
+ if (typeof input.includeAiImages === 'boolean') imageOptions['include_ai_images'] = input.includeAiImages;
+ if (typeof input.includeWebImages === 'boolean') imageOptions['include_web_images'] = input.includeWebImages;
+ if (style) imageOptions['style'] = style;
+ if (styleInstructions) imageOptions['style_instructions'] = styleInstructions;
- if (status === 'completed') {
- return statusResponse.body;
- } else if (status === 'failed') {
- throw new Error(
- `Generation failed: ${statusResponse.body?.error || 'Unknown error'}`
- );
- }
+ const body: Record<string, unknown> = {
+ input_text: inputText,
+ export_formats: formats.length > 0 ? formats : ['link'],
+ };
+ const instructions = buildInstructions({
+ additionalInstructions: input.additionalInstructions,
+ tone: input.tone,
+ contentMode: input.contentMode,
+ amountMode: input.amountMode,
+ });
+ if (instructions) body['additional_instructions'] = instructions;
+ if (imageIds.length > 0) body['image_ids'] = imageIds;
+ if (Object.keys(presentationOptions).length > 0) body['presentation_options'] = presentationOptions;
+ if (language) body['text_options'] = { language };
+ if (Object.keys(imageOptions).length > 0) body['image_options'] = imageOptions;
+ return { body, formats: formats.length > 0 ? formats : ['link'] };
+}
- // Wait before polling again
- await sleep(pollInterval);
- }
+function titleCase(value: string): string {
+ return value[0] + value.slice(1).toLowerCase();
+}
- throw new Error(`Generation timed out after ${maxWaitTime || 300} seconds`);
- },
-});
+function buildInstructions({
+ additionalInstructions,
+ tone,
+ contentMode,
+ amountMode,
+}: {
+ additionalInstructions: string | undefined;
+ tone: unknown;
+ contentMode: unknown;
+ amountMode: unknown;
+}): string | undefined {
+ const parts: string[] = [];
+ if (typeof tone === 'string' && TONES.includes(tone) && tone !== 'DEFAULT') parts.push(`Use a ${tone.toLowerCase()} tone.`);
+ if (typeof contentMode === 'string' && CONTENT_MODE_HINTS[contentMode]) parts.push(CONTENT_MODE_HINTS[contentMode]);
+ if (typeof amountMode === 'string' && AMOUNT_MODES.includes(amountMode)) parts.push(`Text density per slide: ${amountMode.toLowerCase()}.`);
+ const extra = additionalInstructions?.trim();
+ if (extra) parts.push(extra);
+ return parts.length > 0 ? parts.join(' ') : undefined;
+}
diff --git a/packages/pieces/community/alai/src/lib/actions/generate-speaker-notes.ts b/packages/pieces/community/alai/src/lib/actions/generate-speaker-notes.ts
new file mode 100644
index 00000000000..e21b12f84a1
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/generate-speaker-notes.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { presentationIdProp } from './shared-props';
+
+export const generateSpeakerNotes = createAction({
+ auth: alaiAuth,
+ name: 'generateSpeakerNotes',
+ classification: 'WRITE',
+ displayName: 'Generate Speaker Notes',
+ description: 'Generate speaker notes for the slides of a presentation.',
+ audience: 'human',
+ outputSchema: alaiOutputSchemas.generation,
+ aiMetadata: {
+ description:
+ 'Starts AI speaker-notes generation for an Alai presentation, for all slides or only the given slide IDs. Uses AI credits per slide. By default returns at once with generation_id; set waitForCompletion to wait (max 480 s) and get transcripts (slide_id, slide_order, title, content). Not idempotent: each call starts a new job and uses credits again.',
+ idempotent: false,
+ },
+ props: {
+ presentationId: presentationIdProp('The presentation to write speaker notes for.'),
+ slideIds: Property.Array({
+ displayName: 'Slide IDs',
+ description: 'Only these slides. Leave empty for all slides.',
+ required: false,
+ }),
+ waitForCompletion: Property.Checkbox({
+ displayName: 'Wait for Completion',
+ description: 'Wait until Alai finishes. If off, use "Get Generation" with the returned ID later.',
+ required: false,
+ defaultValue: false,
+ }),
+ maxWaitTime: Property.Number({
+ displayName: 'Max Wait Time (seconds)',
+ description: 'How long to wait when waiting is on. Default 300, capped at 480.',
+ required: false,
+ defaultValue: 300,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const presentationId = alaiClient.pathId({ value: propsValue.presentationId, label: 'Presentation ID' });
+ const slideIds = (propsValue.slideIds ?? []).map((id) => String(id).trim()).filter((id) => id.length > 0);
+ return alaiClient.startGeneration({
+ apiKey: auth.props.apiKey,
+ path: `/presentations/${presentationId}/transcripts`,
+ body: slideIds.length > 0 ? { slide_ids: slideIds } : {},
+ waitForCompletion: propsValue.waitForCompletion,
+ maxWaitTime: propsValue.maxWaitTime,
+ requestedFormats: [],
+ });
+ },
+});
diff --git a/packages/pieces/community/alai/src/lib/actions/get-generation.ts b/packages/pieces/community/alai/src/lib/actions/get-generation.ts
index 320fe5eff6c..61e172370aa 100644
--- a/packages/pieces/community/alai/src/lib/actions/get-generation.ts
+++ b/packages/pieces/community/alai/src/lib/actions/get-generation.ts
@@ -1,36 +1,29 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
export const getGeneration = createAction({
auth: alaiAuth,
name: 'getGeneration',
classification: 'READ',
displayName: 'Get Generation',
- description: 'Fetch the status and result of a generation job.',
+ description: 'Get the status and result of a generation, slide, export or speaker-notes job.',
audience: 'both',
+ outputSchema: alaiOutputSchemas.generation,
aiMetadata: {
description:
- 'Look up the current status and result of an Alai generation job by its generation_id (returned by Generate Presentation or Export Presentation). Use this to poll for completion or retrieve the finished output and export links. Read-only and idempotent. Requires a valid generation_id.',
+ 'Reads the status of an Alai job by generation_id (from Generate Presentation, Add Slide, Export Presentation or Generate Speaker Notes). Returns status (pending, in_progress, completed, failed), presentation_id, slide_id, link/pdf/ppt URLs (signed, valid about 24 h) and speaker notes when ready. Poll it about every 5 seconds until status is completed or failed. Read-only and idempotent.',
idempotent: true,
},
props: {
generationId: Property.ShortText({
displayName: 'Generation ID',
- description: 'The ID of the generation job (from the "Generate Presentation" action).',
+ description: 'The generation_id returned by another Alai action.',
required: true,
}),
},
- async run(context) {
- const { generationId } = context.propsValue;
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://slides-api.getalai.com/api/v1/generations/${generationId}`,
- headers: {
- Authorization: `Bearer ${context.auth.props.apiKey}`,
- Accept: 'application/json',
- },
- });
- return response.body;
+ async run({ auth, propsValue }) {
+ return alaiClient.getGeneration({ apiKey: auth.props.apiKey, generationId: propsValue.generationId });
},
});
diff --git a/packages/pieces/community/alai/src/lib/actions/list-resources.ts b/packages/pieces/community/alai/src/lib/actions/list-resources.ts
new file mode 100644
index 00000000000..b84188f612e
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/list-resources.ts
@@ -0,0 +1,96 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+import { optionalInt } from './shared-props';
+
+function records({ body, key }: { body: unknown; key: string }): Record<string, unknown>[] {
+ const list: unknown = typeof body === 'object' && body !== null ? Reflect.get(body, key) : undefined;
+ if (!Array.isArray(list)) {
+ throw new Error(`Alai returned an unexpected response: "${key}" is missing.`);
+ }
+ return list.filter((item): item is Record<string, unknown> => typeof item === 'object' && item !== null);
+}
+
+const text = (value: unknown): string => (typeof value === 'string' ? value : value === undefined || value === null ? '' : String(value));
+
+export const listPresentations = createAction({
+ auth: alaiAuth,
+ name: 'listPresentations',
+ classification: 'SEARCH',
+ displayName: 'List Presentations',
+ description: 'List your presentations, newest first, optionally filtered by title.',
+ audience: 'both',
+ outputSchema: alaiOutputSchemas.listPresentations,
+ aiMetadata: {
+ description:
+ 'Lists the Alai presentations of the connected user, newest first, as id and title. Optional titleContains filters case-insensitively; limit caps the result (default 100) and total/truncated say how many matched. Use it to find a presentation ID. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ titleContains: Property.ShortText({
+ displayName: 'Title Contains',
+ description: 'Only titles containing this text (not case-sensitive).',
+ required: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of presentations to return (default 100).',
+ required: false,
+ defaultValue: 100,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = optionalInt({ value: propsValue.limit, label: 'Limit', min: 1 }) ?? 100;
+ const filter = propsValue.titleContains?.trim().toLowerCase();
+ const body = await alaiClient.request<unknown>({ apiKey: auth.props.apiKey, method: HttpMethod.GET, path: '/presentations' });
+ const all = records({ body, key: 'presentations' })
+ .map((item) => ({ id: text(item['id']), title: text(item['title']) }))
+ .filter((item) => !filter || item.title.toLowerCase().includes(filter));
+ const presentations = all.slice(0, limit);
+ return { presentations, count: presentations.length, total: all.length, truncated: all.length > presentations.length };
+ },
+});
+
+export const listThemes = createAction({
+ auth: alaiAuth,
+ name: 'listThemes',
+ classification: 'SEARCH',
+ displayName: 'List Themes',
+ description: 'List the themes you can use when generating a presentation.',
+ audience: 'both',
+ outputSchema: alaiOutputSchemas.listThemes,
+ aiMetadata: {
+ description:
+ 'Lists the Alai themes available to the connected user (id and name). Pass a theme id as themeId to Generate Presentation. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ async run({ auth }) {
+ const body = await alaiClient.request<unknown>({ apiKey: auth.props.apiKey, method: HttpMethod.GET, path: '/themes' });
+ const themes = records({ body, key: 'themes' }).map((item) => ({ id: text(item['id']), name: text(item['name']) }));
+ return { themes, count: themes.length };
+ },
+});
+
+export const listVibes = createAction({
+ auth: alaiAuth,
+ name: 'listVibes',
+ classification: 'SEARCH',
+ displayName: 'List Vibes',
+ description: 'List the vibes (visual styles) you can use when generating a presentation.',
+ audience: 'both',
+ outputSchema: alaiOutputSchemas.listVibes,
+ aiMetadata: {
+ description:
+ 'Lists the Alai vibes (visual style presets) available to the connected user (id, name, source). Pass a vibe id as vibeId to Generate Presentation. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ async run({ auth }) {
+ const body = await alaiClient.request<unknown>({ apiKey: auth.props.apiKey, method: HttpMethod.GET, path: '/vibes' });
+ const vibes = records({ body, key: 'vibes' }).map((item) => ({ id: text(item['id']), name: text(item['name']), source: text(item['source']) }));
+ return { vibes, count: vibes.length };
+ },
+});
diff --git a/packages/pieces/community/alai/src/lib/actions/shared-props.ts b/packages/pieces/community/alai/src/lib/actions/shared-props.ts
new file mode 100644
index 00000000000..8bcee77bffc
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/shared-props.ts
@@ -0,0 +1,25 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const exportFormatOptions = [
+ { label: 'Link', value: 'link' },
+ { label: 'PDF', value: 'pdf' },
+ { label: 'PowerPoint (PPTX)', value: 'ppt' },
+];
+
+export const presentationIdProp = (description: string) =>
+ Property.ShortText({
+ displayName: 'Presentation ID',
+ description: `${description} Use "List Presentations" or the presentation_id from "Generate Presentation".`,
+ required: true,
+ });
+
+export function optionalInt({ value, label, min, max }: { value: unknown; label: string; min: number; max?: number }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < min || (max !== undefined && number > max)) {
+ throw new Error(`${label} must be a whole number${max !== undefined ? ` from ${min} to ${max}` : ` of at least ${min}`}.`);
+ }
+ return number;
+}
diff --git a/packages/pieces/community/alai/src/lib/actions/upload-images.ts b/packages/pieces/community/alai/src/lib/actions/upload-images.ts
new file mode 100644
index 00000000000..6a7379d6242
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/actions/upload-images.ts
@@ -0,0 +1,121 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { alaiAuth } from '../common/auth';
+import { alaiClient } from '../common/client';
+import { alaiOutputSchemas } from '../common/output-schemas';
+
+const MAX_FILES = 10;
+const MAX_BYTES = 10 * 1024 * 1024;
+const MIME_BY_EXTENSION: Record<string, string> = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ webp: 'image/webp',
+ gif: 'image/gif',
+ avif: 'image/avif',
+ svg: 'image/svg+xml',
+};
+
+type FileLike = { filename: string; data: Buffer; extension?: string };
+
+function asFile({ value, index }: { value: unknown; index: number }): FileLike {
+ if (typeof value !== 'object' || value === null) {
+ throw new Error(`Image ${index + 1} is not a file.`);
+ }
+ const data: unknown = Reflect.get(value, 'data');
+ const filename: unknown = Reflect.get(value, 'filename');
+ if (!Buffer.isBuffer(data)) {
+ throw new Error(`Image ${index + 1} is not a file.`);
+ }
+ const name = typeof filename === 'string' && filename.length > 0 ? filename : `image-${index + 1}`;
+ const extension: unknown = Reflect.get(value, 'extension');
+ return { filename: name, data, extension: typeof extension === 'string' ? extension : undefined };
+}
+
+function mimeOf(file: FileLike): string | undefined {
+ const extension = (file.extension ?? file.filename.split('.').pop() ?? '').toLowerCase().replace(/^\./, '');
+ return MIME_BY_EXTENSION[extension];
+}
+
+function imageIdsOf(body: unknown): string[] {
+ if (Array.isArray(body)) {
+ return body.flatMap((item) => (typeof item === 'string' ? [item] : imageIdsOf(item)));
+ }
+ if (typeof body !== 'object' || body === null) {
+ return [];
+ }
+ for (const key of ['image_ids', 'ids']) {
+ const value: unknown = Reflect.get(body, key);
+ if (Array.isArray(value)) {
+ return value.map(String);
+ }
+ }
+ const images: unknown = Reflect.get(body, 'images');
+ if (Array.isArray(images)) {
+ return imageIdsOf(images);
+ }
+ const id: unknown = Reflect.get(body, 'image_id') ?? Reflect.get(body, 'id');
+ return typeof id === 'string' ? [id] : [];
+}
+
+export const uploadImages = createAction({
+ auth: alaiAuth,
+ name: 'uploadImages',
+ classification: 'WRITE',
+ displayName: 'Upload Images',
+ description: 'Upload up to 10 images (PNG, JPEG, WebP, GIF, AVIF or SVG, 10 MB each) to use in a new presentation.',
+ audience: 'human',
+ outputSchema: alaiOutputSchemas.uploadImages,
+ aiMetadata: {
+ description:
+ 'Uploads 1-10 image files (png, jpeg, webp, gif, avif, svg; 10 MB each) to Alai and returns image_ids to pass to Generate Presentation. Not idempotent: each call stores new copies.',
+ idempotent: false,
+ },
+ props: {
+ images: Property.Array({
+ displayName: 'Images',
+ description: 'Up to 10 image files.',
+ required: true,
+ properties: {
+ file: Property.File({
+ displayName: 'Image',
+ required: true,
+ }),
+ },
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const entries = (propsValue.images ?? []).map((item) =>
+ typeof item === 'object' && item !== null && 'file' in item ? Reflect.get(item, 'file') : item
+ );
+ if (entries.length === 0) {
+ throw new Error('Add at least one image.');
+ }
+ if (entries.length > MAX_FILES) {
+ throw new Error(`Alai accepts at most ${MAX_FILES} images per upload; got ${entries.length}.`);
+ }
+ const form = new FormData();
+ entries.forEach((entry, index) => {
+ const file = asFile({ value: entry, index });
+ const mime = mimeOf(file);
+ if (!mime) {
+ throw new Error(`"${file.filename}" is not a supported image type (png, jpeg, webp, gif, avif, svg).`);
+ }
+ if (file.data.length > MAX_BYTES) {
+ throw new Error(`"${file.filename}" is larger than 10 MB.`);
+ }
+ form.append('files', new Blob([new Uint8Array(file.data)], { type: mime }), file.filename);
+ });
+ const body = await alaiClient.request<unknown>({
+ apiKey: auth.props.apiKey,
+ method: HttpMethod.POST,
+ path: '/upload-images',
+ body: form,
+ });
+ const imageIds = imageIdsOf(body);
+ if (imageIds.length === 0) {
+ throw new Error(`Alai did not return image IDs: ${JSON.stringify(body).slice(0, 300)}`);
+ }
+ return { image_ids: imageIds, count: imageIds.length, response: body };
+ },
+});
diff --git a/packages/pieces/community/alai/src/lib/common/auth.ts b/packages/pieces/community/alai/src/lib/common/auth.ts
index 5976dee70fa..fe25ba93069 100644
--- a/packages/pieces/community/alai/src/lib/common/auth.ts
+++ b/packages/pieces/community/alai/src/lib/common/auth.ts
@@ -1,13 +1,16 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { PieceAuth } from '@activepieces/pieces-framework';
-import { HttpError, HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { AlaiApiError, alaiClient } from './client';
const markdownDescription = `
-Follow these steps to get your Alai API Key:
+To get your Alai API key:
-1. Go to [**https://getalai.com/api**](https://getalai.com/api) and sign up or log in.
-2. Navigate to the **API Keys** section.
-3. Click **Create API Key** and give it a name (e.g., "Activepieces").
-4. Copy the key and paste it below.
+1. Sign in at [app.getalai.com](https://app.getalai.com).
+2. Open the account menu and choose **API**.
+3. Click **Add new API key**, name it (for example "Activepieces") and copy the key.
+4. Paste it below.
+
+API calls use the same AI credits as the Alai app.
`;
export const alaiAuth = PieceAuth.CustomAuth({
@@ -16,28 +19,19 @@ export const alaiAuth = PieceAuth.CustomAuth({
props: {
apiKey: PieceAuth.SecretText({
displayName: 'API Key',
- description: 'Paste your API key here.',
+ description: 'Your Alai API key.',
required: true,
}),
},
- async validate(auth) {
- const apiKey = auth.auth.apiKey;
+ async validate({ auth }) {
try {
- await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: 'https://slides-api.getalai.com/api/v1/ping',
- headers: {
- Authorization: `Bearer ${apiKey}`,
- },
- });
+ await alaiClient.request({ apiKey: auth.apiKey, method: HttpMethod.GET, path: '/ping' });
return { valid: true };
- } catch (e) {
- if (e instanceof HttpError) {
- if (e.response.status === 401) {
- return { valid: false, error: 'Invalid API Key' };
- }
+ } catch (error) {
+ if (error instanceof AlaiApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid Alai API key.' };
}
- return { valid: false, error: 'Failed to connect to Alai API' };
+ return { valid: false, error: 'Could not reach the Alai API to check the key. Try again later.' };
}
},
});
diff --git a/packages/pieces/community/alai/src/lib/common/client.ts b/packages/pieces/community/alai/src/lib/common/client.ts
new file mode 100644
index 00000000000..7e2daa6a07e
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/common/client.ts
@@ -0,0 +1,340 @@
+import { httpClient, HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+
+const BASE_URL = 'https://slides-api.getalai.com';
+const API_PREFIX = '/api/v1';
+const POLL_INTERVAL_MS = 5_000;
+const FIRST_POLL_DELAY_MS = 1_000;
+const MAX_WAIT_SECONDS = 480;
+const DEFAULT_WAIT_SECONDS = 300;
+const EARLY_NOT_FOUND_POLLS = 3;
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class AlaiApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly responseBody: unknown
+ ) {
+ super(message);
+ this.name = 'AlaiApiError';
+ }
+}
+
+const STATUS_HINTS: Record<number, string> = {
+ 400: 'Alai rejected the request (HTTP 400).',
+ 401: 'Alai rejected the API key (HTTP 401). Check the key in the connection.',
+ 402: 'Your Alai account does not have enough AI credits for this (HTTP 402). Add credits or upgrade the plan in Alai.',
+ 403: 'The Alai API key is not allowed to do this (HTTP 403).',
+ 404: 'Alai could not find that item (HTTP 404). Check the ID.',
+ 422: 'Alai could not process the input (HTTP 422).',
+ 429: 'Alai rate limit reached (HTTP 429). Alai allows 5 generations at the same time per user; try again shortly.',
+ 500: 'Alai had an internal error (HTTP 500). Try again later.',
+};
+
+function readHttpFailure(error: unknown): { status: number; body: unknown } | null {
+ if (typeof error !== 'object' || error === null) {
+ return null;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (typeof response !== 'object' || response === null) {
+ return null;
+ }
+ const status: unknown = Reflect.get(response, 'status');
+ if (typeof status !== 'number') {
+ return null;
+ }
+ return { status, body: Reflect.get(response, 'body') };
+}
+
+function vendorMessage(body: unknown): string | undefined {
+ if (typeof body === 'string') {
+ return body.length > 0 ? body.slice(0, 500) : undefined;
+ }
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const detail: unknown = Reflect.get(body, 'detail');
+ if (typeof detail === 'string') {
+ return detail;
+ }
+ if (Array.isArray(detail)) {
+ return detail
+ .map((item) => {
+ const loc: unknown = typeof item === 'object' && item !== null ? Reflect.get(item, 'loc') : undefined;
+ const msg: unknown = typeof item === 'object' && item !== null ? Reflect.get(item, 'msg') : undefined;
+ const where = Array.isArray(loc) ? loc.join('.') : '';
+ return typeof msg === 'string' ? (where ? `${where}: ${msg}` : msg) : JSON.stringify(item);
+ })
+ .join('; ');
+ }
+ const message: unknown = Reflect.get(body, 'message');
+ return typeof message === 'string' ? message : undefined;
+}
+
+function toAlaiError({ status, body }: { status: number; body: unknown }): AlaiApiError {
+ const prefix = STATUS_HINTS[status] ?? `Alai API request failed (HTTP ${status}).`;
+ const message = vendorMessage(body);
+ return new AlaiApiError(message ? `${prefix} ${message}` : prefix, status, body);
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function authHeaders(apiKey: string): Record<string, string> {
+ return { Authorization: `Bearer ${apiKey.trim()}` };
+}
+
+async function request<T>({
+ apiKey,
+ method,
+ path,
+ body,
+}: {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ body?: HttpRequest['body'];
+}): Promise<T> {
+ const headers: Record<string, string> = { ...authHeaders(apiKey), Accept: 'application/json' };
+ if (body !== undefined && !(body instanceof FormData)) {
+ headers['Content-Type'] = 'application/json';
+ }
+ try {
+ const response = await httpClient.sendRequest<T>(
+ {
+ method,
+ url: `${BASE_URL}${API_PREFIX}${path}`,
+ headers,
+ body,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ },
+ { dispatcher: await verifiedTls() }
+ );
+ if (response.status >= 300) {
+ throw new AlaiApiError(`Alai answered with an unexpected redirect (HTTP ${response.status}).`, response.status, response.body);
+ }
+ return response.body;
+ } catch (error) {
+ const failure = readHttpFailure(error);
+ if (!failure) {
+ throw error;
+ }
+ throw toAlaiError(failure);
+ }
+}
+
+function pathId({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (!/^[A-Za-z0-9_-]+$/.test(text)) {
+ throw new Error(`${label} "${text}" is not a valid Alai ID (letters, digits, "-" and "_" only).`);
+ }
+ return encodeURIComponent(text);
+}
+
+export type AlaiTranscript = {
+ slide_id: string | null;
+ slide_order: number | null;
+ title: string | null;
+ content: string | null;
+ layout: string | null;
+};
+
+export type AlaiGeneration = {
+ generation_id: string;
+ status: string;
+ completed: boolean;
+ error: string | null;
+ created_at: string | null;
+ completed_at: string | null;
+ generation_type: string | null;
+ presentation_id: string | null;
+ slide_id: string | null;
+ link_url: string | null;
+ pdf_url: string | null;
+ ppt_url: string | null;
+ formats: Record<string, { status: string | null; url: string | null; error: string | null }>;
+ transcripts: AlaiTranscript[] | null;
+};
+
+function str(value: unknown): string | null {
+ return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : null;
+}
+
+function normalizeGeneration({ raw, fallbackId }: { raw: unknown; fallbackId?: string }): AlaiGeneration {
+ const body = typeof raw === 'object' && raw !== null ? raw : {};
+ const rawFormats: unknown = Reflect.get(body, 'formats');
+ const formats: AlaiGeneration['formats'] = {};
+ if (typeof rawFormats === 'object' && rawFormats !== null) {
+ for (const [key, entry] of Object.entries(rawFormats)) {
+ const item = typeof entry === 'object' && entry !== null ? entry : {};
+ formats[key] = {
+ status: str(Reflect.get(item, 'status')),
+ url: str(Reflect.get(item, 'url')),
+ error: str(Reflect.get(item, 'error')),
+ };
+ }
+ }
+ const rawTranscripts: unknown = Reflect.get(body, 'transcripts');
+ const transcripts = Array.isArray(rawTranscripts)
+ ? rawTranscripts.map((entry) => {
+ const item = typeof entry === 'object' && entry !== null ? entry : {};
+ const order: unknown = Reflect.get(item, 'slide_order');
+ return {
+ slide_id: str(Reflect.get(item, 'slide_id')),
+ slide_order: typeof order === 'number' ? order : null,
+ title: str(Reflect.get(item, 'title')),
+ content: str(Reflect.get(item, 'content')),
+ layout: str(Reflect.get(item, 'layout')),
+ };
+ })
+ : null;
+ const status = str(Reflect.get(body, 'status')) ?? 'pending';
+ return {
+ generation_id: str(Reflect.get(body, 'generation_id')) ?? fallbackId ?? '',
+ status,
+ completed: status === 'completed',
+ error: str(Reflect.get(body, 'error')),
+ created_at: str(Reflect.get(body, 'created_at')),
+ completed_at: str(Reflect.get(body, 'completed_at')),
+ generation_type: str(Reflect.get(body, 'generation_type')),
+ presentation_id: str(Reflect.get(body, 'presentation_id')),
+ slide_id: str(Reflect.get(body, 'slide_id')),
+ link_url: formats['link']?.url ?? null,
+ pdf_url: formats['pdf']?.url ?? null,
+ ppt_url: formats['ppt']?.url ?? null,
+ formats,
+ transcripts,
+ };
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function waitSeconds(value: unknown): number {
+ if (value === undefined || value === null || value === '' || Number(value) === 0) {
+ return DEFAULT_WAIT_SECONDS;
+ }
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds) || seconds <= 0) {
+ throw new Error('Max Wait Time must be a positive number of seconds.');
+ }
+ return Math.min(seconds, MAX_WAIT_SECONDS);
+}
+
+async function getGeneration({ apiKey, generationId }: { apiKey: string; generationId: string }): Promise<AlaiGeneration> {
+ const body = await request<unknown>({
+ apiKey,
+ method: HttpMethod.GET,
+ path: `/generations/${pathId({ value: generationId, label: 'Generation ID' })}`,
+ });
+ return normalizeGeneration({ raw: body, fallbackId: generationId });
+}
+
+function assertFormatsSucceeded({ generation, requested }: { generation: AlaiGeneration; requested: string[] }): void {
+ const failed = requested.filter((format) => generation.formats[format]?.status === 'failed');
+ if (failed.length > 0) {
+ const reasons = failed.map((format) => `${format}: ${generation.formats[format]?.error ?? 'unknown error'}`).join('; ');
+ throw new Error(`Alai finished generation ${generation.generation_id} but these exports failed: ${reasons}`);
+ }
+}
+
+async function waitForGeneration({
+ apiKey,
+ generationId,
+ maxWaitTime,
+ requestedFormats,
+}: {
+ apiKey: string;
+ generationId: string;
+ maxWaitTime: unknown;
+ requestedFormats: string[];
+}): Promise<AlaiGeneration> {
+ const limitMs = waitSeconds(maxWaitTime) * 1000;
+ const started = Date.now();
+ await sleep(FIRST_POLL_DELAY_MS);
+ for (let poll = 0; ; poll++) {
+ let generation: AlaiGeneration | undefined;
+ try {
+ generation = await getGeneration({ apiKey, generationId });
+ } catch (error) {
+ if (!(error instanceof AlaiApiError && error.status === 404 && poll < EARLY_NOT_FOUND_POLLS)) {
+ throw error;
+ }
+ }
+ if (generation?.status === 'completed') {
+ assertFormatsSucceeded({ generation, requested: requestedFormats });
+ return generation;
+ }
+ if (generation?.status === 'failed') {
+ throw new Error(`Alai generation ${generationId} failed: ${generation.error ?? 'unknown error'}`);
+ }
+ if (Date.now() - started + POLL_INTERVAL_MS > limitMs) {
+ throw new Error(
+ `Alai generation ${generationId} is still running after ${Math.round((Date.now() - started) / 1000)} seconds. Use "Get Generation" with this ID to check it later.`
+ );
+ }
+ await sleep(POLL_INTERVAL_MS);
+ }
+}
+
+async function startGeneration({
+ apiKey,
+ path,
+ body,
+ waitForCompletion,
+ maxWaitTime,
+ requestedFormats,
+}: {
+ apiKey: string;
+ path: string;
+ body: Record<string, unknown>;
+ waitForCompletion: unknown;
+ maxWaitTime: unknown;
+ requestedFormats: string[];
+}): Promise<AlaiGeneration> {
+ if (waitForCompletion === true) {
+ waitSeconds(maxWaitTime);
+ }
+ const response = await request<unknown>({ apiKey, method: HttpMethod.POST, path, body });
+ const generationId = typeof response === 'object' && response !== null ? str(Reflect.get(response, 'generation_id')) : null;
+ if (!generationId) {
+ throw new Error('Alai did not return a generation_id for this request.');
+ }
+ if (waitForCompletion !== true) {
+ return normalizeGeneration({ raw: response, fallbackId: generationId });
+ }
+ return waitForGeneration({ apiKey, generationId, maxWaitTime, requestedFormats });
+}
+
+function exportFormats(value: unknown): string[] {
+ const allowed = ['link', 'pdf', 'ppt'];
+ const list = Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value];
+ const formats = [...new Set(list.map((item) => String(item).trim().toLowerCase()).filter((item) => item.length > 0))];
+ const invalid = formats.filter((item) => !allowed.includes(item));
+ if (invalid.length > 0) {
+ throw new Error(`Unknown export format(s): ${invalid.join(', ')}. Use link, pdf or ppt.`);
+ }
+ return formats;
+}
+
+export const alaiClient = {
+ baseUrl: BASE_URL,
+ apiPrefix: API_PREFIX,
+ maxWaitSeconds: MAX_WAIT_SECONDS,
+ authHeaders,
+ verifiedTls,
+ request,
+ pathId,
+ getGeneration,
+ startGeneration,
+ exportFormats,
+ toAlaiError,
+ readHttpFailure,
+};
diff --git a/packages/pieces/community/alai/src/lib/common/output-schemas.ts b/packages/pieces/community/alai/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..3f85650835c
--- /dev/null
+++ b/packages/pieces/community/alai/src/lib/common/output-schemas.ts
@@ -0,0 +1,125 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+type Field = OutputSchema['fields'][number];
+
+const formatField = ({ key, label }: { key: string; label: string }): Field => ({
+ key,
+ label,
+ children: [
+ { key: 'status', label: `${label} Status`, description: 'completed, failed or skipped.' },
+ { key: 'url', label: `${label} URL`, format: 'url', description: 'Signed URL, valid for about 24 hours.' },
+ { key: 'error', label: `${label} Error` },
+ ],
+});
+
+const generationFields: Field[] = [
+ { key: 'generation_id', label: 'Generation ID' },
+ { key: 'status', label: 'Status', description: 'pending, in_progress, completed or failed.' },
+ { key: 'completed', label: 'Completed', format: 'boolean' },
+ { key: 'error', label: 'Error' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },
+ { key: 'generation_type', label: 'Generation Type' },
+ { key: 'presentation_id', label: 'Presentation ID' },
+ { key: 'slide_id', label: 'Slide ID', description: 'Set when a slide was added.' },
+ { key: 'link_url', label: 'Presentation Link', format: 'url' },
+ { key: 'pdf_url', label: 'PDF URL', format: 'url' },
+ { key: 'ppt_url', label: 'PowerPoint URL', format: 'url' },
+ {
+ key: 'formats',
+ label: 'Formats',
+ children: [
+ formatField({ key: 'link', label: 'Link' }),
+ formatField({ key: 'pdf', label: 'PDF' }),
+ formatField({ key: 'ppt', label: 'PowerPoint' }),
+ ],
+ },
+ {
+ key: 'transcripts',
+ label: 'Speaker Notes',
+ labelKey: 'title',
+ listItems: [
+ { key: 'slide_id', label: 'Slide ID' },
+ { key: 'slide_order', label: 'Slide Order', format: 'number' },
+ { key: 'title', label: 'Slide Title' },
+ { key: 'content', label: 'Speaker Notes' },
+ { key: 'layout', label: 'Layout' },
+ ],
+ },
+];
+
+export const alaiOutputSchemas = {
+ generation: { fields: generationFields },
+ deletePresentation: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'presentation_id', label: 'Presentation ID' },
+ ],
+ },
+ deleteSlide: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'presentation_id', label: 'Presentation ID' },
+ { key: 'slide_id', label: 'Slide ID' },
+ ],
+ },
+ listPresentations: {
+ fields: [
+ {
+ key: 'presentations',
+ label: 'Presentations',
+ labelKey: 'title',
+ listItems: [
+ { key: 'id', label: 'Presentation ID' },
+ { key: 'title', label: 'Title' },
+ ],
+ },
+ { key: 'count', label: 'Returned', format: 'number' },
+ { key: 'total', label: 'Total Matching', format: 'number' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ ],
+ },
+ listThemes: {
+ fields: [
+ {
+ key: 'themes',
+ label: 'Themes',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Theme ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ listVibes: {
+ fields: [
+ {
+ key: 'vibes',
+ label: 'Vibes',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Vibe ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'source', label: 'Source' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ uploadImages: {
+ fields: [
+ { key: 'image_ids', label: 'Image IDs', description: 'Pass these to Generate Presentation.' },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'response', label: 'Raw Response' },
+ ],
+ },
+ customApiCall: {
+ fields: [
+ { key: 'status', label: 'Status Code', format: 'number' },
+ { key: 'headers', label: 'Headers', dynamicKey: true },
+ { key: 'body', label: 'Body' },
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/alai/src/lib/common/props.ts b/packages/pieces/community/alai/src/lib/common/props.ts
deleted file mode 100644
index 96d3e7ca021..00000000000
--- a/packages/pieces/community/alai/src/lib/common/props.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-import { Property } from '@activepieces/pieces-framework';
-import { alaiAuth } from './auth';
-
-export const presentationId = Property.Dropdown({
- auth: alaiAuth,
- displayName: 'Presentation',
- description: 'Select a presentation',
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) return { options: [] };
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: 'https://slides-api.getalai.com/api/v1/presentations',
- headers: {
- Authorization: `Bearer ${auth.props.apiKey}`,
- Accept: 'application/json',
- },
- });
- const presentations = response.body?.presentations || [];
- return {
- disabled: presentations.length === 0,
- options: presentations.map(
- (presentation: { presentation_id: string; title: string }) => ({
- label: presentation.title,
- value: presentation.presentation_id,
- })
- ),
- };
- },
-});
diff --git a/packages/pieces/community/alai/test/actions.test.ts b/packages/pieces/community/alai/test/actions.test.ts
new file mode 100644
index 00000000000..710502853ed
--- /dev/null
+++ b/packages/pieces/community/alai/test/actions.test.ts
@@ -0,0 +1,341 @@
+import { httpClient, HttpError } from '@activepieces/pieces-common';
+import { createMockActionContext, InputPropertyMap } from '@activepieces/pieces-framework';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { addSlide } from '../src/lib/actions/add-slide';
+import { alaiCustomApiCall, urlOf } from '../src/lib/actions/custom-api-call';
+import { deletePresentation } from '../src/lib/actions/delete-presentation';
+import { deleteSlide } from '../src/lib/actions/delete-slide';
+import { exportPresentation } from '../src/lib/actions/export-presentation';
+import { generatePresentation } from '../src/lib/actions/generate-presentation';
+import { generateSpeakerNotes } from '../src/lib/actions/generate-speaker-notes';
+import { getGeneration } from '../src/lib/actions/get-generation';
+import { listPresentations, listThemes } from '../src/lib/actions/list-resources';
+import { uploadImages } from '../src/lib/actions/upload-images';
+import { alaiAuth } from '../src/lib/common/auth';
+import { addSlideAi, exportPresentationAi, generatePresentationAi, generateSpeakerNotesAi } from '../src/lib/actions/ai-actions';
+
+const AUTH = { props: { apiKey: ' key123 ' } };
+
+function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }): Promise<unknown> {
+ const base = createMockActionContext<InputPropertyMap>({ propsValue: {} });
+ const runFn = action.run;
+ if (typeof runFn !== 'function') {
+ throw new Error('action has no run');
+ }
+ return Promise.resolve(Reflect.apply(runFn, action, [{ ...base, propsValue, auth: AUTH }]));
+}
+
+function mockResponses({ bodies = [] }: { bodies?: unknown[] } = {}) {
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ for (const body of bodies) {
+ if (body instanceof HttpError) {
+ spy.mockRejectedValueOnce(body);
+ } else {
+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body });
+ }
+ }
+ return spy;
+}
+
+const httpError = ({ status, body }: { status: number; body: unknown }) => new HttpError({}, { status, responseBody: body });
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe('generatePresentation', () => {
+ it('sends only spec fields and returns the normalized shape without waiting', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'g1' }] });
+ const out = await run({ action: generatePresentation, propsValue: {
+ inputText: ' Hello ',
+ slideRange: '2-5',
+ language: 'German',
+ themeId: 'th-1',
+ vibeId: 'v1',
+ includeAiImages: false,
+ imageIds: ['img1'],
+ exportFormats: ['pdf'],
+ } });
+ const [req, opts] = spy.mock.calls[0];
+ expect(req.url).toBe('https://slides-api.getalai.com/api/v1/generations');
+ expect(req.method).toBe('POST');
+ expect(req.headers).toMatchObject({ Authorization: 'Bearer key123' });
+ expect(req.followRedirects).toBe(false);
+ expect(opts).toHaveProperty('dispatcher');
+ expect(req.body).toEqual({
+ input_text: 'Hello',
+ export_formats: ['pdf'],
+ image_ids: ['img1'],
+ presentation_options: { theme_id: 'th-1', vibe_id: 'v1', slide_range: '2-5' },
+ text_options: { language: 'German' },
+ image_options: { include_ai_images: false },
+ });
+ expect(out).toMatchObject({ generation_id: 'g1', status: 'pending', completed: false, pdf_url: null });
+ });
+
+ it('turns legacy tone, content mode and density into instructions', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'g9' }] });
+ await run({ action: generatePresentation, propsValue: { inputText: 'x', tone: 'PERSUASIVE', contentMode: 'CONDENSE', amountMode: 'MINIMAL', additionalInstructions: 'Blue.' } });
+ expect(spy.mock.calls[0][0].body).toMatchObject({
+ additional_instructions: 'Use a persuasive tone. Condense the input text. Text density per slide: minimal. Blue.',
+ });
+ expect(spy.mock.calls[0][0].body).not.toHaveProperty('text_options');
+ });
+
+ it('requires style instructions for custom style', async () => {
+ const spy = mockResponses();
+ await expect(run({ action: generatePresentation, propsValue: { inputText: 'x', imageStyle: 'custom' } })).rejects.toThrow('Image Style Instructions');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('waits, flattens URLs and fails when a requested format failed', async () => {
+ vi.useFakeTimers();
+ mockResponses({ bodies: [
+ { generation_id: 'g2' },
+ httpError({ status: 404, body: { detail: 'not found' } }),
+ { generation_id: 'g2', status: 'completed', formats: { link: { status: 'completed', url: 'https://l' }, pdf: { status: 'failed', error: 'boom' } } }
+ ] });
+ const promise = run({ action: generatePresentation, propsValue: { inputText: 'x', exportFormats: ['link', 'pdf'], waitForCompletion: true } });
+ const assertion = expect(promise).rejects.toThrow('pdf: boom');
+ await vi.runAllTimersAsync();
+ await assertion;
+ });
+
+ it('times out within the clamp and names the generation id', async () => {
+ vi.useFakeTimers();
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { generation_id: 'g3' } });
+ spy.mockResolvedValue({ status: 200, headers: {}, body: { generation_id: 'g3', status: 'in_progress' } });
+ const promise = run({ action: generatePresentation, propsValue: { inputText: 'x', waitForCompletion: true, maxWaitTime: 99999 } });
+ const assertion = expect(promise).rejects.toThrow(/g3 is still running/);
+ await vi.runAllTimersAsync();
+ await assertion;
+ expect(spy.mock.calls.length).toBeLessThanOrEqual(2 + 480 / 5);
+ });
+
+ it('treats empty Image Style, Language and Slide Type as unset', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'g5' }, { generation_id: 'a7' }] });
+ await run({ action: generatePresentation, propsValue: { inputText: 'x', imageStyle: '', language: '' } });
+ expect(spy.mock.calls[0][0].body).not.toHaveProperty('image_options.style');
+ expect(spy.mock.calls[0][0].body).not.toHaveProperty('text_options');
+ await run({ action: addSlide, propsValue: { presentationId: 'p1', slide_context: 'S', slideType: '' } });
+ expect(spy.mock.calls[1][0].body).not.toHaveProperty('options.slide_type');
+ });
+
+ it('treats an empty Slide Range and Max Wait Time 0 as unset', async () => {
+ vi.useFakeTimers();
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { generation_id: 'g4' } });
+ spy.mockResolvedValue({ status: 200, headers: {}, body: { generation_id: 'g4', status: 'in_progress' } });
+ const promise = run({ action: generatePresentation, propsValue: { inputText: 'x', slideRange: '', waitForCompletion: true, maxWaitTime: 0 } });
+ const assertion = expect(promise).rejects.toThrow(/g4 is still running/);
+ await vi.runAllTimersAsync();
+ await assertion;
+ expect(spy.mock.calls[0][0].body).not.toHaveProperty('presentation_options.slide_range');
+ expect(spy.mock.calls.length).toBeGreaterThan(2 + 240 / 5);
+ });
+
+ it('maps 402 and 422 errors to readable messages', async () => {
+ mockResponses({ bodies: [httpError({ status: 402, body: { detail: 'Insufficient credits' } })] });
+ await expect(run({ action: generatePresentation, propsValue: { inputText: 'x' } })).rejects.toThrow(/AI credits.*Insufficient credits/);
+ mockResponses({ bodies: [httpError({ status: 422, body: { detail: [{ loc: ['body', 'input_text'], msg: 'field required' }] } })] });
+ await expect(run({ action: generatePresentation, propsValue: { inputText: 'x' } })).rejects.toThrow('body.input_text: field required');
+ });
+});
+
+describe('exportPresentation', () => {
+ it('posts formats (not export_formats)', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'e1' }] });
+ await run({ action: exportPresentation, propsValue: { presentationId: 'p1', exportFormats: ['pdf', 'ppt'] } });
+ expect(spy.mock.calls[0][0].url).toBe('https://slides-api.getalai.com/api/v1/presentations/p1/exports');
+ expect(spy.mock.calls[0][0].body).toEqual({ formats: ['pdf', 'ppt'] });
+ });
+
+ it('rejects path traversal in IDs before any request', async () => {
+ const spy = mockResponses();
+ await expect(run({ action: exportPresentation, propsValue: { presentationId: '../ping', exportFormats: ['link'] } })).rejects.toThrow('not a valid Alai ID');
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('addSlide', () => {
+ it('sends integer slide_order and spec options only', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 's1' }] });
+ await run({ action: addSlide, propsValue: { presentationId: 'p1', slide_context: 'Topic', slide_order: '2', slideType: 'creative', variantsPerSlide: 2 } });
+ expect(spy.mock.calls[0][0].body).toEqual({
+ slide_context: 'Topic',
+ options: { slide_type: 'creative', slide_order: 2, total_variants_per_slide: 2 },
+ export_formats: ['link'],
+ });
+ });
+
+ it('omits slide_order to append (empty or legacy "end"), maps image hints and rejects negatives', async () => {
+ const legacy = mockResponses({ bodies: [{ generation_id: 's3' }] });
+ await run({ action: addSlide, propsValue: { presentationId: 'p1', slide_context: 'T', slide_order: 'end', includeAiImages: false } });
+ expect(legacy.mock.calls[0][0].body).toMatchObject({ options: { additional_instructions: 'Do not use images on this slide.' } });
+ vi.restoreAllMocks();
+ const spy = mockResponses({ bodies: [{ generation_id: 's2' }] });
+ await run({ action: addSlide, propsValue: { presentationId: 'p1', slide_context: 'Topic' } });
+ expect(spy.mock.calls[0][0].body).toMatchObject({ options: {} });
+ await expect(run({ action: addSlide, propsValue: { presentationId: 'p1', slide_context: 'T', slide_order: -1 } })).rejects.toThrow('Slide Position');
+ });
+});
+
+describe('speaker notes, get, delete', () => {
+ it('posts slide_ids when given', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 't1' }] });
+ await run({ action: generateSpeakerNotes, propsValue: { presentationId: 'p1', slideIds: ['a', ' '] } });
+ expect(spy.mock.calls[0][0].url).toBe('https://slides-api.getalai.com/api/v1/presentations/p1/transcripts');
+ expect(spy.mock.calls[0][0].body).toEqual({ slide_ids: ['a'] });
+ });
+
+ it('get generation normalizes transcripts', async () => {
+ mockResponses({ bodies: [{ generation_id: 't1', status: 'completed', transcripts: [{ slide_id: 'a', slide_order: 0, title: 'T', content: 'C', layout: 'L' }] }] });
+ const out = await run({ action: getGeneration, propsValue: { generationId: 't1' } });
+ expect(out).toMatchObject({ completed: true, transcripts: [{ slide_id: 'a', slide_order: 0, title: 'T', content: 'C', layout: 'L' }] });
+ });
+
+ it('delete presentation reports 404 as a named error', async () => {
+ mockResponses({ bodies: [httpError({ status: 404, body: { detail: 'Presentation not found' } })] });
+ await expect(run({ action: deletePresentation, propsValue: { presentationId: 'p1' } })).rejects.toThrow(/could not find.*Presentation not found/);
+ });
+
+ it('delete slide hits the slide path', async () => {
+ const spy = mockResponses({ bodies: [{ success: true }] });
+ const out = await run({ action: deleteSlide, propsValue: { presentationId: 'p1', slideId: 's9' } });
+ expect(spy.mock.calls[0][0].url).toBe('https://slides-api.getalai.com/api/v1/presentations/p1/slides/s9');
+ expect(spy.mock.calls[0][0].method).toBe('DELETE');
+ expect(out).toEqual({ success: true, presentation_id: 'p1', slide_id: 's9' });
+ });
+});
+
+describe('list actions', () => {
+ it('maps id, filters and reports truncation', async () => {
+ mockResponses({ bodies: [{ presentations: [{ id: '1', title: 'Sales Q1' }, { id: '2', title: 'sales Q2' }, { id: '3', title: 'Other' }] }] });
+ const out = await run({ action: listPresentations, propsValue: { titleContains: 'SALES', limit: 1 } });
+ expect(out).toEqual({ presentations: [{ id: '1', title: 'Sales Q1' }], count: 1, total: 2, truncated: true });
+ });
+
+ it('fails on an unexpected body instead of returning empty', async () => {
+ mockResponses({ bodies: [{ nope: [] }] });
+ await expect(run({ action: listThemes, propsValue: {} })).rejects.toThrow('unexpected response');
+ });
+});
+
+describe('uploadImages', () => {
+ it('rejects unsupported types and too many files before sending', async () => {
+ const spy = mockResponses();
+ await expect(run({ action: uploadImages, propsValue: { images: [{ file: { filename: 'a.txt', extension: 'txt', data: Buffer.from('x') } }] } })).rejects.toThrow('not a supported');
+ const many = Array.from({ length: 11 }, () => ({ file: { filename: 'a.png', data: Buffer.from('x') } }));
+ await expect(run({ action: uploadImages, propsValue: { images: many } })).rejects.toThrow('at most 10');
+ await expect(run({ action: uploadImages, propsValue: { images: [{ file: { filename: 'a.png', data: Buffer.alloc(10 * 1024 * 1024 + 1) } }] } })).rejects.toThrow('10 MB');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('sends multipart files and returns ids', async () => {
+ const spy = mockResponses({ bodies: [{ image_ids: ['i1'] }] });
+ const out = await run({ action: uploadImages, propsValue: { images: [{ file: { filename: 'a.png', data: Buffer.from('x') } }] } });
+ expect(spy.mock.calls[0][0].body).toBeInstanceOf(FormData);
+ expect(spy.mock.calls[0][0].headers).not.toHaveProperty('Content-Type');
+ expect(out).toMatchObject({ image_ids: ['i1'] });
+ });
+});
+
+describe('custom api call url guard', () => {
+ it('accepts relative and same-host URLs', () => {
+ expect(urlOf({ url: '/v1/themes' })).toBe('https://slides-api.getalai.com/api/v1/themes');
+ expect(urlOf({ url: '/themes' })).toBe('https://slides-api.getalai.com/api/v1/themes');
+ expect(urlOf({ url: 'presentations?x=1' })).toBe('https://slides-api.getalai.com/api/v1/presentations?x=1');
+ expect(urlOf({ url: '/modern/v1/ping' })).toBe('https://slides-api.getalai.com/api/modern/v1/ping');
+ expect(urlOf({ url: 'https://slides-api.getalai.com/api/modern/v1/ping' })).toBe('https://slides-api.getalai.com/api/modern/v1/ping');
+ });
+
+ it.each([
+ 'https://slides-api.getalai.com.evil.io/api/v1',
+ '//evil.io/api',
+ 'https://[email protected]/api/v1',
+ '/v1/../../x',
+ '/v1/%2e%2e/x',
+ 'http://slides-api.getalai.com/api/v1',
+ 'https://slides-api.getalai.com/other',
+ ])('rejects %s', (url) => {
+ expect(() => urlOf({ url })).toThrow();
+ });
+});
+
+describe('auth validate', () => {
+ it('reports invalid credentials on 401 and 403 only', async () => {
+ const validateFn = alaiAuth.validate;
+ if (!validateFn) {
+ throw new Error('no validate');
+ }
+ const validate = (args: unknown): Promise<unknown> => Promise.resolve(Reflect.apply(validateFn, alaiAuth, [args]));
+ mockResponses({ bodies: [httpError({ status: 403, body: {} })] });
+ expect(await validate({ auth: { apiKey: 'k' } })).toEqual({ valid: false, error: 'Invalid Alai API key.' });
+ mockResponses({ bodies: [httpError({ status: 500, body: {} })] });
+ expect(await validate({ auth: { apiKey: 'k' } })).toMatchObject({ error: expect.stringMatching(/Could not reach/) });
+ const spy = mockResponses({ bodies: [{ user_id: 'u' }] });
+ expect(await validate({ auth: { apiKey: ' k ' } })).toEqual({ valid: true });
+ expect(spy.mock.calls[0][0].headers).toMatchObject({ Authorization: 'Bearer k' });
+ });
+});
+
+describe('agent tools', () => {
+ it('generate_presentation_ai sends one request, maps tone and never waits', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'a1' }] });
+ const out = await run({ action: generatePresentationAi, propsValue: { inputText: 'x', tone: 'CASUAL', slideRange: '1', themeId: 't1' } });
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy.mock.calls[0][0].body).toEqual({
+ input_text: 'x',
+ export_formats: ['link'],
+ additional_instructions: 'Use a casual tone.',
+ presentation_options: { theme_id: 't1', slide_range: '1' },
+ });
+ expect(out).toMatchObject({ generation_id: 'a1', status: 'pending' });
+ });
+
+ it('add_slide_ai sends an integer slideOrder', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'a2' }] });
+ await run({ action: addSlideAi, propsValue: { presentationId: 'p1', slideContext: 'S', slideOrder: 0, slideType: 'classic' } });
+ expect(spy.mock.calls[0][0].url).toBe('https://slides-api.getalai.com/api/v1/presentations/p1/slides');
+ expect(spy.mock.calls[0][0].body).toEqual({ slide_context: 'S', options: { slide_type: 'classic', slide_order: 0 }, export_formats: ['link'] });
+ });
+
+ it('add_slide_ai keeps images when the agent leaves Include Images out', async () => {
+ expect(addSlideAi.props.includeAiImages.defaultValue).toBe(true);
+ const spy = mockResponses({ bodies: [{ generation_id: 'a5' }, { generation_id: 'a6' }] });
+ await run({ action: addSlideAi, propsValue: { presentationId: 'p1', slideContext: 'S', includeAiImages: addSlideAi.props.includeAiImages.defaultValue } });
+ expect(JSON.stringify(spy.mock.calls[0][0].body)).not.toContain('Do not use images');
+ await run({ action: addSlideAi, propsValue: { presentationId: 'p1', slideContext: 'S', includeAiImages: false } });
+ expect(JSON.stringify(spy.mock.calls[1][0].body)).toContain('Do not use images');
+ });
+
+ it('export_presentation_ai posts formats and requires one', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'a3' }] });
+ await run({ action: exportPresentationAi, propsValue: { presentationId: 'p1', formats: ['pdf'] } });
+ expect(spy.mock.calls[0][0].body).toEqual({ formats: ['pdf'] });
+ await expect(run({ action: exportPresentationAi, propsValue: { presentationId: 'p1', formats: [] } })).rejects.toThrow('at least one format');
+ });
+
+ it('generate_speaker_notes_ai posts all slides when none given', async () => {
+ const spy = mockResponses({ bodies: [{ generation_id: 'a4' }] });
+ await run({ action: generateSpeakerNotesAi, propsValue: { presentationId: 'p1' } });
+ expect(spy.mock.calls[0][0].body).toEqual({});
+ });
+});
+
+describe('custom api call binary download', () => {
+ it('keeps the file extension from content-type', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockResolvedValueOnce({ status: 200, headers: { 'content-type': 'application/pdf; charset=binary' }, body: Buffer.from('%PDF') });
+ const base = createMockActionContext<InputPropertyMap>({ propsValue: {} });
+ const write = vi.fn(async ({ fileName }: { fileName: string }) => `file://${fileName}`);
+ const out = await Promise.resolve(
+ Reflect.apply(alaiCustomApiCall.run, alaiCustomApiCall, [
+ { ...base, files: { write }, auth: AUTH, propsValue: { method: 'GET', url: { url: '/presentations/p1/file' }, headers: {}, queryParams: {}, response_is_binary: true } },
+ ])
+ );
+ expect(write).toHaveBeenCalledWith(expect.objectContaining({ fileName: 'output.pdf' }));
+ expect(out).toMatchObject({ status: 200, body: 'file://output.pdf' });
+ });
+});
diff --git a/packages/pieces/community/alai/vitest.config.ts b/packages/pieces/community/alai/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/alai/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})