Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

5.9 KB
Raw Blame
/**
 * @example
 *
 * ```python
 * class ABLY:
 *     """Map of Composio's ABLY toolkit."""
 *
 *     slug: str = "ably"
 *
 *     class tools:
 *         BATCH_PRESENCE = "ABLY_BATCH_PRESENCE"
 *         BATCH_PRESENCE_HISTORY = "ABLY_BATCH_PRESENCE_HISTORY"
 *         CREATE_CHANNEL = "ABLY_CREATE_CHANNEL"
 *         DELETE_CHANNEL_SUBSCRIPTION = "ABLY_DELETE_CHANNEL_SUBSCRIPTION"
 *
 *     class triggers:
 *         NEW_GMAIL_MESSAGE = {
 *           'config': {
 *             # ...
 *           },
 *           description: "Triggers when a new message is received in Gmail.",
 *           instructions:
 *             "\n    **Instructions for Setting Up the Trigger:**\n\n    - Ensure that the Gmail API is enabled for your Google account.\n    - Provide the user ID (usually 'me' for the authenticated user).\n    - Optionally, provide label IDs to filter messages.\n    ",
 *           name: "New Gmail Message Received Trigger",
 *           payload: {
 *             # ...
 *           },
 *           slug: 'GMAIL_NEW_GMAIL_MESSAGE',
 *           type: 'poll',
 *         }
 * ```
 */

import { Match, pipe, Record } from 'effect';
import type { ToolkitName } from 'src/models/toolkits';
import type { ToolkitIndex, ToolkitIndexData } from 'src/generation/create-toolkit-index';
import type { SourceFile } from 'src/generation/types';
import type { TriggerType } from 'src/models/trigger-types';

/**
 * Converts a JavaScript value to Python dictionary/literal syntax
 */
function jsToPython(value: unknown, indent = 0): string {
  const spacePad = ' '.repeat(indent);

  if (value === null) {
    return 'None';
  }

  if (value === undefined) {
    return 'None';
  }

  if (typeof value === 'string') {
    // Escape quotes and return as Python string
    return JSON.stringify(value);
  }

  if (typeof value === 'number') {
    return value.toString();
  }

  if (typeof value === 'boolean') {
    return value ? 'True' : 'False';
  }

  if (Array.isArray(value)) {
    if (value.length === 0) {
      return '[]';
    }
    const items = value.map(item => jsToPython(item, indent + 2));
    return `[${items.join(', ')}]`;
  }

  if (typeof value === 'object' && value !== null) {
    const entries = Object.entries(value);
    if (entries.length === 0) {
      return '{}';
    }

    const formattedEntries = entries.map(([key, val]) => {
      const formattedKey = JSON.stringify(key);
      const formattedValue = jsToPython(val, indent + 2);
      return `${spacePad}  ${formattedKey}: ${formattedValue}`;
    });

    return `{\n${formattedEntries.join(',\n')}\n${spacePad}}`;
  }

  // Fallback for unknown types
  return JSON.stringify(value);
}

const PYTHON_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;

function orderPythonAssignmentEntries<T>(entries: Array<[string, T]>): Array<[string, T]> {
  const fallbackEntries: Array<[string, T]> = [];
  const identifierEntries: Array<[string, T]> = [];

  for (const entry of entries) {
    if (PYTHON_IDENTIFIER_PATTERN.test(entry[0])) {
      identifierEntries.push(entry);
    } else {
      fallbackEntries.push(entry);
    }
  }

  return [...fallbackEntries, ...identifierEntries];
}

function generatePythonAssignment(name: string, valueLiteral: string, spacing: number): string {
  const spacePad = ' '.repeat(spacing);

  if (PYTHON_IDENTIFIER_PATTERN.test(name)) {
    return `${spacePad}${name} = ${valueLiteral}`;
  }

  return `${spacePad}locals()[${jsToPython(name)}] = ${valueLiteral}`;
}

/**
 * Generates Python dictionary syntax for a trigger type object
 */
function generateTriggerTypePythonDict(triggerType: TriggerType, indent = 0): string {
  return jsToPython(triggerType, indent);
}

/**
 * Generates a list of Python source files that should be written to disk by the caller.
 */
export function generatePythonToolkitSources(banner: string) {
  return (index: ToolkitIndex): Array<SourceFile> => {
    const toolkitSources = pipe(
      index,
      Record.mapEntries(generatePythonToolkitSource(banner)),
      Record.toEntries
    );

    return toolkitSources;
  };
}

function generatePythonToolkitSource(banner: string) {
  return (toolkit: ToolkitIndexData, toolkitName: ToolkitName): SourceFile => {
    const filename = `${toolkit.slug}.py`;

    const toolsEntries = (spacing: number) => {
      if (Object.keys(toolkit.typeableTools.value).length > 0) {
        const tools = Match.value(toolkit.typeableTools).pipe(
          Match.when({ withTypes: true }, ({ value }) =>
            Record.mapEntries(value, (toolValue, toolName) => [toolName, toolValue.slug])
          ),
          Match.when({ withTypes: false }, ({ value }) =>
            Record.mapEntries(value, (toolValue, toolName) => [toolName, toolValue])
          ),
          Match.exhaustive
        );

        return orderPythonAssignmentEntries(Object.entries(tools))
          .map(([toolName, toolValue]) =>
            generatePythonAssignment(toolName, jsToPython(toolValue), spacing)
          )
          .join('\n');
      }

      return `${' '.repeat(spacing)}pass`;
    };

    const triggerTypesEntries = (spacing: number) => {
      if (Record.size(toolkit.triggerTypes) > 0) {
        return orderPythonAssignmentEntries(Object.entries(toolkit.triggerTypes))
          .map(([triggerName, triggerValue]) => {
            const pythonDict = generateTriggerTypePythonDict(triggerValue, spacing);
            return generatePythonAssignment(triggerName, pythonDict, spacing);
          })
          .join('\n');
      }

      return `${' '.repeat(spacing)}pass`;
    };

    // Build version comment if version override was used
    const versionComment = toolkit.version ? `# @toolkit-version: ${toolkit.version}\n` : '';

    const filesource = `# ${banner}.
${versionComment}
class ${toolkitName}:
    """Map of Composio's ${toolkitName} toolkit."""

    slug: str = "${toolkit.slug}"

    class tools:
${toolsEntries(8)}

    class triggers:
${triggerTypesEntries(8)}
`;

    return [filename, filesource];
  };
}