All files / api/src/ai-providers/predibase chat-complete.ts

41.62% Statements 77/185
100% Branches 0/0
0% Functions 0/4
41.62% Lines 77/185

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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237  1x                             1x 1x   1x   1x 1x 1x 1x 1x           1x                 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x                                                                                                                                             1x 1x                                                                                                      
import type { PredibaseChatCompletionStreamChunk } from '@api/ai-providers/predibase/types';
import {
  generateErrorResponse,
  generateInvalidProviderResponseError,
  splitString,
} from '@api/utils/ai-provider';
import type {
  AIProviderFunctionConfig,
  ResponseChunkStreamTransformFunction,
  ResponseTransformFunction,
} from '@shared/types/ai-providers/config';
import type {
  ChatCompletionFinishReason,
  ChatCompletionRequestBody,
  ChatCompletionResponseBody,
} from '@shared/types/api/routes/chat-completions-api';
import { ChatCompletionMessageRole } from '@shared/types/api/routes/shared/messages';
import { AIProvider } from '@shared/types/constants';
 
const PREDIBASE = AIProvider.PREDIBASE;
 
export const predibaseChatCompleteConfig: AIProviderFunctionConfig = {
  model: {
    param: 'model',
    required: false,
    default: '',
    /*
    The Predibase model format is "<base_model>[:adapter_id]",
    where adapter_id format is "<adapter_repository_reference/version_number"
    (version_number is required).
    */
    transform: (saRequestBody: ChatCompletionRequestBody) => {
      const model = saRequestBody.model;
      return [
        {
          role: ChatCompletionMessageRole.SYSTEM,
          content: model ? splitString(model, ':').after : '',
        },
      ];
    },
  },
  messages: {
    param: 'messages',
    required: true,
    default: [],
    transform: (saRequestBody: ChatCompletionRequestBody) => {
      return (
        saRequestBody.messages?.map((message) => {
          if (message.role === ChatCompletionMessageRole.DEVELOPER)
            return { ...message, role: ChatCompletionMessageRole.SYSTEM };
          return message;
        }) || []
      );
    },
  },
  max_tokens: {
    param: 'max_tokens',
    required: false,
    default: 4096,
    min: 0,
  },
  max_completion_tokens: {
    param: 'max_tokens',
    required: false,
    default: 4096,
    min: 0,
  },
  temperature: {
    param: 'temperature',
    required: false,
    default: 0.1,
    min: 0,
    max: 1,
  },
  top_p: {
    param: 'top_p',
    required: false,
    default: 1,
    min: 0,
    max: 1,
  },
  response_format: {
    param: 'response_format',
    required: false,
  },
  stream: {
    param: 'stream',
    required: false,
    default: false,
  },
  n: {
    param: 'n',
    required: false,
    default: 1,
    max: 1,
    min: 1,
  },
  stop: {
    param: 'stop',
    required: false,
  },
  top_k: {
    param: 'top_k',
    required: false,
    default: -1,
  },
  best_of: {
    param: 'best_of',
    required: false,
  },
};
 
export const predibaseChatCompleteResponseTransform: ResponseTransformFunction =
  (aiProviderResponseBody, aiProviderResponseStatus) => {
    if ('error' in aiProviderResponseBody && aiProviderResponseStatus !== 200) {
      const error = aiProviderResponseBody.error as {
        message: string;
        type: string;
        code: string;
      };
      return generateErrorResponse(
        {
          message: error.message,
          type: error.type,
          param: undefined,
          code: error.code?.toString() || undefined,
        },
        PREDIBASE,
      );
    }
 
    if ('choices' in aiProviderResponseBody) {
      const choices = aiProviderResponseBody.choices as {
        index: number;
        message: {
          role: string;
          content: string;
        };
        logprobs: {
          token_logprobs: number[];
          top_logprobs: Record<string, number>[];
          text_offset: number[];
        };
        finish_reason: string;
      }[];
      const usage = aiProviderResponseBody.usage as {
        prompt_tokens: number;
        completion_tokens: number;
        total_tokens: number;
      };
      const responseBody: ChatCompletionResponseBody = {
        id: aiProviderResponseBody.id as string,
        object: aiProviderResponseBody.object as 'chat.completion',
        created: aiProviderResponseBody.created as number,
        model: aiProviderResponseBody.model as string,
        choices: choices.map((choice) => ({
          index: choice.index,
          message: {
            role: choice.message.role as ChatCompletionMessageRole,
            content: choice.message.content,
          },
          logprobs: {
            token_logprobs: choice.logprobs.token_logprobs,
            top_logprobs: choice.logprobs.top_logprobs,
            text_offset: choice.logprobs.text_offset,
            content: null,
          },
          finish_reason: choice.finish_reason as ChatCompletionFinishReason,
        })),
        usage: {
          prompt_tokens: usage.prompt_tokens || 0,
          completion_tokens: usage.completion_tokens || 0,
          total_tokens: usage.total_tokens || 0,
        },
      };
      return responseBody;
    }
 
    return generateInvalidProviderResponseError(
      aiProviderResponseBody,
      PREDIBASE,
    );
  };
 
export const predibaseChatCompleteStreamChunkTransform: ResponseChunkStreamTransformFunction =
  (responseChunk) => {
    let chunk = responseChunk.trim();
    chunk = chunk.replace(/^data:\s*/, '');
    chunk = chunk.trim();
    if (chunk === '[DONE]') {
      return `data: ${chunk}\n\n`;
    }
 
    const parsedChunk = JSON.parse(chunk);
 
    if (!parsedChunk || typeof parsedChunk !== 'object') {
      throw new Error('Invalid chunk format');
    }
 
    if ('error' in parsedChunk && 'error_type' in parsedChunk) {
      return `data: ${JSON.stringify({
        id: null,
        object: null,
        created: null,
        model: null,
        provider: PREDIBASE,
        choices: [
          {
            index: 0,
            delta: {
              role: parsedChunk.error_type,
              content: parsedChunk.error,
            },
            finish_reason: 'error',
          },
        ],
      })}\n\n`;
    }
 
    const typedChunk = parsedChunk as PredibaseChatCompletionStreamChunk;
    return `data: ${JSON.stringify({
      id: typedChunk.id,
      object: typedChunk.object,
      created: typedChunk.created,
      model: typedChunk.model,
      provider: PREDIBASE,
      choices: [
        {
          index: typedChunk.choices[0].index,
          delta: typedChunk.choices[0].delta,
          finish_reason: typedChunk.choices[0].finish_reason,
        },
      ],
      ...(typedChunk.usage ? { usage: typedChunk.usage } : {}),
    })}\n\n`;
  };