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

5.4 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import {
  CohereChatRequest,
  CohereChatResponse,
  CohereErrorResponse,
  CohereModelsResponse,
} from '../common/types';
import { cohereAuth } from '../auth';

const COHERE_CHAT_URL = 'https://api.cohere.com/v2/chat';
const COHERE_MODELS_URL = 'https://api.cohere.com/v1/models';
const MAX_RETRIES = 3;
const INITIAL_BACKOFF_MS = 1000;

async function generateWithRetry(
  apiKey: string,
  request: CohereChatRequest,
): Promise<CohereChatResponse> {
  let lastError: Error | undefined;

  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
    try {
      const response = await httpClient.sendRequest<CohereChatResponse>({
        method: HttpMethod.POST,
        url: COHERE_CHAT_URL,
        headers: {
          Authorization: `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
        },
        body: request,
      });

      return response.body;
    } catch (error: unknown) {
      lastError = error instanceof Error ? error : new Error(String(error));

      const errorAny = error as { response?: { status: number; body: unknown } };
      const statusCode = errorAny.response?.status;
      const isRetryable =
        statusCode === 429 ||
        (statusCode !== undefined && statusCode >= 500);

      if (!isRetryable || attempt === MAX_RETRIES - 1) {
        if (errorAny.response?.body) {
          const errorBody = errorAny.response.body as CohereErrorResponse;
          throw new Error(
            `Cohere API error (${statusCode}): ${errorBody.message ?? lastError.message}`,
          );
        }
        throw lastError;
      }

      const backoffMs = INITIAL_BACKOFF_MS * Math.pow(2, attempt);
      await new Promise((resolve) => setTimeout(resolve, backoffMs));
    }
  }

  throw lastError ?? new Error('Generate text failed after retries');
}

export const generateText = createAction({
  audience: 'both',
  auth: cohereAuth,
  name: 'generate_text',
  classification: 'READ',
  displayName: 'Generate Text',
  description: 'Generate a text response using Cohere AI Chat API',
  aiMetadata: { description: 'Runs a single-turn completion against Cohere\'s v2 Chat API - one user prompt in, one generated message out - with optional model, temperature, and max-token controls. This is the only purpose-built action in the Cohere piece and covers only chat-style generation, not multi-turn conversation history, embeddings, rerank, or classify; use the piece\'s Custom API Call action to reach those Cohere endpoints. Requires a prompt and a chat-capable model name. Not idempotent: each call bills a fresh generation and the wording varies unless temperature is set to 0.', idempotent: false },
  props: {
    prompt: Property.LongText({
      displayName: 'Prompt',
      description: 'The user message to send to the model',
      required: true,
    }),
    model: Property.Dropdown({
      displayName: 'Model',
      description: 'The Cohere model to use for generation',
      required: true,
      defaultValue: 'command-a-03-2025',
      auth: cohereAuth,
      refreshers: [],
      options: async ({ auth }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Enter your API key first',
            options: [],
          };
        }

        try {
          const response = await httpClient.sendRequest<CohereModelsResponse>({
            method: HttpMethod.GET,
            url: COHERE_MODELS_URL,
            headers: {
              Authorization: `Bearer ${auth.secret_text}`,
            },
            queryParams: {
              page_size: '1000',
              endpoint: 'chat',
            },
          });

          const options = response.body.models.map((model) => ({
            label: model.name,
            value: model.name,
          }));

          return { disabled: false, options };
        } catch {
          return {
            disabled: true,
            options: [],
            placeholder:
              "Couldn't load models, check your API key or try again.",
          };
        }
      },
    }),
    temperature: Property.Number({
      displayName: 'Temperature',
      description:
        'Controls randomness (0.0 = deterministic, 1.0 = maximum randomness). Default: 0.3',
      required: false,
      defaultValue: 0.3,
    }),
    maxTokens: Property.Number({
      displayName: 'Max Tokens',
      description:
        'Maximum number of tokens to generate. Leave empty for model default.',
      required: false,
    }),
  },

  async run(context) {
    const { prompt, model, temperature, maxTokens } = context.propsValue;
    const apiKey = context.auth.secret_text;

    const request: CohereChatRequest = {
      model,
      messages: [{ role: 'user', content: prompt }],
      stream: false,
    };

    if (temperature !== undefined && temperature !== null) {
      request.temperature = temperature;
    }

    if (maxTokens !== undefined && maxTokens !== null) {
      request.max_tokens = maxTokens;
    }

    const response = await generateWithRetry(apiKey, request);

    const generatedText =
      response.message?.content?.[0]?.text ?? '';

    return {
      text: generatedText,
      model,
      finishReason: response.finish_reason,
      usage: {
        inputTokens: response.usage?.billed_units?.input_tokens ?? 0,
        outputTokens: response.usage?.billed_units?.output_tokens ?? 0,
      },
    };
  },
});