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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
import { ActivepiecesAiBilling, ActivepiecesAiConsumerSource, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { aiUtils, FlowStepMetadata } from '@activepieces/server-utils'
import { AiStepAction, ClassifyTextJobData, EngineResponseStatus, ExecuteAiJobData, ResolveAiProviderResponse, WorkerJobType } from '@activepieces/shared'
import { generateText, ModelMessage, stepCountIs } from 'ai'
import { JobContext, JobHandler, JobResult, JobResultKind } from '../../types'
import { resolveAiFiles } from './ai-files'
import { extractStructuredData } from './extract-structured-data'
import { generateImageStep } from './generate-image'
import { routeStep } from './route'
import { CandidateRun, runWithFallback } from './run-with-fallback'
export const executeAiJob: JobHandler<ExecuteAiJobData, JobResult> = {
jobType: WorkerJobType.EXECUTE_AI,
async execute(ctx: JobContext, data: ExecuteAiJobData): Promise<JobResult> {
const { data: output, error } = await tryCatch(() => callTheModel({ ctx, data }))
const stepOutput = isNil(error) ? { output } : { failure: toFailureMessage(error) }
if (isNil(data.waitpointId)) {
return { kind: JobResultKind.SYNCHRONOUS, status: EngineResponseStatus.OK, response: stepOutput }
}
const handedBack = await handBackToTheFlow({ ctx, data, waitpointId: data.waitpointId, output: stepOutput })
if (!isNil(error)) {
ctx.log.warn({ flowRun: { id: data.flowRunId }, requestId: data.requestId, error }, '[executeAiJob] Handed the failure back to the flow')
}
return { kind: JobResultKind.FIRE_AND_FORGET, status: handedBack ? EngineResponseStatus.OK : EngineResponseStatus.INTERNAL_ERROR }
},
}
async function handBackToTheFlow({ ctx, data, waitpointId, output }: {
ctx: JobContext
data: ExecuteAiJobData
waitpointId: string
output: unknown
}): Promise<boolean> {
for (let attempt = 1; attempt <= RESUME_ATTEMPTS; attempt++) {
const { error } = await tryCatch(() => ctx.apiClient.resumeAiStep({
projectId: data.projectId,
flowRunId: data.flowRunId,
waitpointId,
output,
}))
if (isNil(error)) {
return true
}
ctx.log.warn({ flowRun: { id: data.flowRunId }, requestId: data.requestId, attempt, error }, '[executeAiJob] Could not hand the answer back to the flow')
await waitBeforeRetry(attempt)
}
ctx.log.error({ flowRun: { id: data.flowRunId }, requestId: data.requestId }, '[executeAiJob] Gave up handing the answer back, so the step stays paused until its backstop fires')
return false
}
async function waitBeforeRetry(attempt: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, attempt * RETRY_DELAY_MS))
}
async function callTheModel({ ctx, data }: { ctx: JobContext, data: ExecuteAiJobData }): Promise<unknown> {
const flowStep = flowStepMetadata(data)
const billing = billingFor(data)
switch (data.action) {
case AiStepAction.EXTRACT_STRUCTURED_DATA: {
const files = await resolveAiFiles({ ctx, data })
return { answer: await withModel({ ctx, data, attempt: ({ candidate, maxRetries }) => extractStructuredData({ data, resolved: candidate, modelId: candidate.modelId, flowStep, billing, files, maxRetries }) }) }
}
case AiStepAction.GENERATE_IMAGE:
return { answer: await generateImageStep({ ctx, data, resolved: await resolveSpecificModel({ ctx, data }), flowStep, billing, inputImages: await resolveAiFiles({ ctx, data }) }) }
case AiStepAction.ROUTE:
return routeStep({ data, resolved: await resolveSpecificModel({ ctx, data }), billing })
case AiStepAction.ASK_AI:
case AiStepAction.SUMMARIZE_TEXT:
case AiStepAction.CLASSIFY_TEXT:
return withModel({ ctx, data, attempt: ({ candidate, maxRetries, onStepFinish }) => runTextStep({ data, resolved: candidate, modelId: candidate.modelId, flowStep, billing, maxRetries, onStepFinish }) })
}
}
async function withModel<T>({ ctx, data, attempt }: { ctx: JobContext, data: ExecuteAiJobData, attempt: (run: CandidateRun) => Promise<T> }): Promise<T> {
if (isNil(data.modelTierId)) {
const resolved = await resolveSpecificModel({ ctx, data })
return attempt({ candidate: { ...resolved, modelId: data.modelId, status: 'active' }, maxRetries: undefined, onStepFinish: () => undefined })
}
const { tierName, candidates } = await ctx.apiClient.resolveAiModelCandidates({
projectId: data.projectId,
platformId: data.platformId,
modelTierId: data.modelTierId,
})
return runWithFallback({
candidates,
tierName,
log: ctx.log,
attempt,
report: async ({ candidate, signal }) => {
const { error } = await tryCatch(() => ctx.apiClient.reportAiKeyOutcome({ platformId: data.platformId, providerConfigId: candidate.providerConfigId, signal }))
if (!isNil(error)) {
ctx.log.warn({ error, aiProvider: { id: candidate.providerConfigId } }, '[executeAiJob] Could not report the key outcome')
}
},
})
}
async function resolveSpecificModel({ ctx, data }: { ctx: JobContext, data: ExecuteAiJobData }): Promise<ResolveAiProviderResponse> {
return ctx.apiClient.resolveAiProvider({
projectId: data.projectId,
platformId: data.platformId,
provider: data.provider,
modelId: data.modelId,
...spreadIfDefined('providerConfigId', data.providerConfigId),
})
}
async function runTextStep({ data, resolved, modelId, flowStep, billing, maxRetries, onStepFinish }: {
data: ExecuteAiJobData
resolved: ResolveAiProviderResponse
modelId: string
flowStep: FlowStepMetadata
billing: ActivepiecesAiBilling
maxRetries: number | undefined
onStepFinish: () => void
}): Promise<unknown> {
const credentials = resolved
const { provider } = credentials
const webSearchEnabled = data.webSearch?.enabled ?? false
const webSearchOptions = data.webSearch?.options
const tools = aiUtils.buildWebSearchToolsOrThrow({ provider, model: modelId, webSearchEnabled, options: webSearchOptions })
const model = aiUtils.createModel({
credentials,
modelId,
flowStep,
billing,
providerConfigId: resolved.providerConfigId,
webSearchEnabled,
webSearchOptions,
})
const response = await generateText({
model,
messages: buildMessages(data),
tools,
onStepFinish,
...spreadIfDefined('maxRetries', maxRetries),
...spreadIfDefined('maxOutputTokens', data.maxOutputTokens),
...spreadIfDefined('temperature', data.temperature),
...spreadIfDefined('stopWhen', Object.keys(tools).length === 0 ? undefined : stepCountIs(webSearchOptions?.maxUses ?? DEFAULT_WEB_SEARCH_STEPS)),
})
return toStepOutput({ data, text: response.text ?? '', sources: response.sources })
}
function billingFor(data: ExecuteAiJobData): ActivepiecesAiBilling {
return {
source: ActivepiecesAiConsumerSource.AI_STEP_IN_FLOW,
platformId: data.platformId,
projectId: data.projectId,
flowRun: { flowId: data.flowId, flowRunId: data.flowRunId },
...spreadIfDefined('context', data.callContext),
}
}
function flowStepMetadata(data: ExecuteAiJobData): FlowStepMetadata {
return {
projectId: data.projectId,
platformId: data.platformId,
flowId: data.flowId,
runId: data.flowRunId,
}
}
function buildMessages(data: ExecuteAiJobData): ModelMessage[] {
switch (data.action) {
case AiStepAction.ASK_AI: {
const history = (data.conversation ?? []) as ModelMessage[]
return [...history, { role: 'user', content: data.prompt ?? '' }]
}
case AiStepAction.SUMMARIZE_TEXT:
return [{ role: 'user', content: `${data.prompt} Summarize the following text : ${data.text ?? ''}` }]
case AiStepAction.CLASSIFY_TEXT:
return [{ role: 'user', content: classificationPrompt(data) }]
case AiStepAction.EXTRACT_STRUCTURED_DATA:
case AiStepAction.GENERATE_IMAGE:
case AiStepAction.ROUTE:
throw new Error(`${data.action} does not build plain messages`)
}
}
function classificationPrompt(data: ClassifyTextJobData): string {
return `As a text classifier, your task is to assign one of the following categories to the provided text: ${(data.categories ?? []).join(', ')}. Please respond with only the selected category as a single word, and nothing else.
Text to classify: "${data.text ?? ''}"`
}
function toStepOutput({ data, text, sources }: { data: ExecuteAiJobData, text: string, sources: unknown }): unknown {
switch (data.action) {
case AiStepAction.ASK_AI: {
const conversation = isNil(data.conversation) ? undefined : [
...(data.conversation as ModelMessage[]),
{ role: 'user' as const, content: data.prompt ?? '' },
{ role: 'assistant' as const, content: text },
]
const answer = data.webSearch?.enabled === true && data.webSearch.options?.includeSources === true
? { text, sources }
: text
return { answer, ...spreadIfDefined('conversation', conversation) }
}
case AiStepAction.SUMMARIZE_TEXT:
return { answer: text }
case AiStepAction.CLASSIFY_TEXT: {
const label = text.trim()
if (!(data.categories ?? []).includes(label)) {
throw new Error('Unable to classify the text into the provided categories.')
}
return { answer: label }
}
case AiStepAction.EXTRACT_STRUCTURED_DATA:
case AiStepAction.GENERATE_IMAGE:
case AiStepAction.ROUTE:
throw new Error(`${data.action} returns its own output shape`)
}
}
function toFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
const DEFAULT_WEB_SEARCH_STEPS = 5
const RESUME_ATTEMPTS = 3
const RETRY_DELAY_MS = 1_000