All files / api/src/ai-providers/workers-ai api.ts

0% Statements 0/39
100% Branches 1/1
100% Functions 1/1
0% Lines 0/39

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                                                                                                                       
import type { InternalProviderAPIConfig } from '@shared/types/ai-providers/config';
import { FunctionName } from '@shared/types/api/request';
 
export const workersAIAPIConfig: InternalProviderAPIConfig = {
  getBaseURL: ({ saTarget }) => {
    // Workers AI requires account ID which should be part of the target configuration
    // Multiple ways to provide the account ID:
    // 1. Direct custom_host with full URL
    // 2. custom_host with just the account ID
    // 3. Future: dedicated account_id field
 
    let accountId: string | null = null;
 
    // Check if custom_host is provided
    if (saTarget.custom_host) {
      // If custom_host contains a full Cloudflare URL, extract account ID
      if (saTarget.custom_host.includes('cloudflare.com')) {
        const match = saTarget.custom_host.match(/\/accounts\/([^/]+)/);
        accountId = match ? match[1] : null;
      } else {
        // If custom_host is just the account ID
        accountId = saTarget.custom_host;
      }
    }
 
    // If no account ID found, throw a helpful error
    if (!accountId) {
      throw new Error(
        'Cloudflare Workers AI requires an account ID. Please provide it in one of these ways:\n' +
          '1. Set custom_host to your full Cloudflare API URL (e.g., "https://api.cloudflare.com/client/v4/accounts/YOUR_ACCOUNT_ID/ai/run")\n' +
          '2. Set custom_host to just your account ID (e.g., "YOUR_ACCOUNT_ID")\n' +
          '3. Add a dedicated account_id field to the configuration (future enhancement)',
      );
    }
 
    return `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run`;
  },
  headers: ({ saTarget }) => {
    return {
      Authorization: `Bearer ${saTarget.api_key}`,
      'Content-Type': 'application/json',
    };
  },
  getEndpoint: ({ saRequestData }) => {
    // Extract model from request body
    const requestBody = saRequestData.requestBody as Record<string, unknown>;
    const model = requestBody.model as string;
 
    switch (saRequestData.functionName) {
      case FunctionName.COMPLETE:
      case FunctionName.CHAT_COMPLETE:
      case FunctionName.EMBED:
      case FunctionName.GENERATE_IMAGE:
        return `/${model}`;
      default:
        return '';
    }
  },
};