All files / frameworks cloudflare.ts

63.15% Statements 12/19
33.33% Branches 7/21
60% Functions 3/5
63.15% Lines 12/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136  1x         1x   1x                     1x   1x 1x                             1x                                             3x 3x     3x                           3x       3x                                                                                                          
// Import core dependencies
import { ComposioToolSet as BaseComposioToolSet } from "../sdk/base.toolset";
import {
  AiTextGenerationOutput,
  AiTextGenerationToolInput,
} from "@cloudflare/workers-types";
import { COMPOSIO_BASE_URL } from "../sdk/client/core/OpenAPI";
import { WorkspaceConfig } from "../env/config";
import { Workspace } from "../env";
import { ActionsListResponseDTO } from "../sdk/client";
 
// Type definitions
type Optional<T> = T | null;
type Sequence<T> = Array<T>;
 
/**
 * CloudflareToolSet provides integration with Cloudflare Workers AI
 * for executing AI tool calls and handling responses
 */
export class CloudflareToolSet extends BaseComposioToolSet {
  // Class constants
  static FRAMEWORK_NAME = "cloudflare";
  static DEFAULT_ENTITY_ID = "default";
 
  /**
   * Initialize a new CloudflareToolSet instance
   *
   * @param config Configuration options including API key, base URL, entity ID and workspace config
   */
  constructor(
    config: {
      apiKey?: Optional<string>;
      baseUrl?: Optional<string>;
      entityId?: string;
      workspaceConfig?: WorkspaceConfig;
    } = {}
  ) {
    super(
      config.apiKey || null,
      config.baseUrl || COMPOSIO_BASE_URL,
      CloudflareToolSet.FRAMEWORK_NAME,
      config.entityId || CloudflareToolSet.DEFAULT_ENTITY_ID,
      config.workspaceConfig || Workspace.Host()
    );
  }
 
  /**
   * Retrieve available tools based on provided filters
   *
   * @param filters Optional filters for actions, apps, tags and use cases
   * @returns Promise resolving to array of AI text generation tools
   */
  async getTools(filters: {
    actions?: Optional<Sequence<string>>;
    apps?: Sequence<string>;
    tags?: Optional<Array<string>>;
    useCase?: Optional<string>;
    usecaseLimit?: Optional<number>;
    filterByAvailableApps?: Optional<boolean>;
  }): Promise<Sequence<AiTextGenerationToolInput>> {
    const actions = await this.getToolsSchema(filters);
    return (
      actions.map((action) => {
        // Format the action schema for Cloudflare Workers AI
        const formattedSchema: AiTextGenerationToolInput["function"] = {
          name: action.name!,
          description: action.description!,
          parameters: action.parameters as unknown as {
            type: "object";
            properties: {
              [key: string]: {
                type: string;
                description?: string;
              };
            };
            required: string[];
          },
        };
        const tool: AiTextGenerationToolInput = {
          type: "function",
          function: formattedSchema,
        };
        return tool;
      }) || []
    );
  }
 
  /**
   * Execute a single tool call
   *
   * @param tool The tool to execute with name and arguments
   * @param entityId Optional entity ID to execute the tool for
   * @returns Promise resolving to stringified tool execution result
   */
  async executeToolCall(
    tool: {
      name: string;
      arguments: unknown;
    },
    entityId: Optional<string> = null
  ): Promise<string> {
    return JSON.stringify(
      await this.executeAction({
        action: tool.name,
        params:
          typeof tool.arguments === "string"
            ? JSON.parse(tool.arguments)
            : tool.arguments,
        entityId: entityId || this.entityId,
      })
    );
  }
 
  /**
   * Handle tool calls from AI text generation output
   *
   * @param result The AI text generation output containing tool calls
   * @param entityId Optional entity ID to execute the tools for
   * @returns Promise resolving to array of tool execution results
   */
  async handleToolCall(
    result: AiTextGenerationOutput,
    entityId: Optional<string> = null
  ): Promise<Sequence<string>> {
    const outputs = [];
    Iif ("tool_calls" in result && Array.isArray(result.tool_calls)) {
      for (const tool_call of result.tool_calls) {
        Iif (tool_call.name) {
          outputs.push(await this.executeToolCall(tool_call, entityId));
        }
      }
    }
    return outputs;
  }
}