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

89.65% Statements 156/174
100% Branches 17/17
50% Functions 2/4
89.65% Lines 156/174

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        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   1x 1x 9x 9x 2x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   9x 5x 5x     5x 1x 1x 1x 1x 1x   4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 1x 1x 5x 5x 4x 4x 3x 3x 3x 3x 3x 1x 5x 5x   2x 2x 2x 2x 2x   1x 1x 6x 6x 6x 6x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 4x 4x 4x  
import type {
  DeepSeekChatCompleteResponse,
  DeepSeekStreamChunk,
} from '@api/ai-providers/deepseek/types';
import {
  generateErrorResponse,
  generateInvalidProviderResponseError,
} from '@api/utils/ai-provider';
import type {
  AIProviderFunctionConfig,
  ResponseChunkStreamTransformFunction,
  ResponseTransformFunction,
} from '@shared/types/ai-providers/config';
import type { ChatCompletionRequestBody } from '@shared/types/api/routes/chat-completions-api';
import { ChatCompletionMessageRole } from '@shared/types/api/routes/shared/messages';
import { AIProvider } from '@shared/types/constants';
 
export const deepSeekChatCompleteConfig: AIProviderFunctionConfig = {
  model: {
    param: 'model',
    required: true,
    default: 'deepseek-chat',
  },
  messages: {
    param: 'messages',
    default: '',
    transform: (saRequestBody: ChatCompletionRequestBody) => {
      if (!saRequestBody.messages) return [];
      return saRequestBody.messages?.map((message) => {
        if (message.role === ChatCompletionMessageRole.DEVELOPER)
          return { ...message, role: ChatCompletionMessageRole.SYSTEM };
        return message;
      });
    },
  },
  max_tokens: {
    param: 'max_tokens',
    default: 100,
    min: 0,
  },
  max_completion_tokens: {
    param: 'max_tokens',
    default: 100,
    min: 0,
  },
  temperature: {
    param: 'temperature',
    default: 1,
    min: 0,
    max: 2,
  },
  top_p: {
    param: 'top_p',
    default: 1,
    min: 0,
    max: 1,
  },
  stream: {
    param: 'stream',
    default: false,
  },
  frequency_penalty: {
    param: 'frequency_penalty',
    default: 0,
    min: -2,
    max: 2,
  },
  presence_penalty: {
    param: 'presence_penalty',
    default: 0,
    min: -2,
    max: 2,
  },
  stop: {
    param: 'stop',
    default: null,
  },
  logprobs: {
    param: 'logprobs',
    default: false,
  },
  top_logprobs: {
    param: 'top_logprobs',
    default: 0,
    min: 0,
    max: 20,
  },
  tools: {
    param: 'tools',
  },
  tool_choice: {
    param: 'tool_choice',
  },
  response_format: {
    param: 'response_format',
    transform: (raRequestBody: ChatCompletionRequestBody) => {
      const format = raRequestBody.response_format;
      if (!format) return undefined;
 
      // DeepSeek only supports json_object, not json_schema
      if (typeof format === 'object' && 'type' in format) {
        if (format.type === 'json_schema') {
          throw new Error(
            'DeepSeek does not support json_schema response format. Use { type: "json_object" } instead.',
          );
        }
      }
 
      return format;
    },
  },
};
 
export const deepSeekChatCompleteResponseTransform: ResponseTransformFunction =
  (aiProviderResponseBody, aiProviderResponseStatus) => {
    if (
      'message' in aiProviderResponseBody &&
      aiProviderResponseStatus !== 200
    ) {
      return generateErrorResponse(
        {
          message: aiProviderResponseBody.message as string,
          type: aiProviderResponseBody.type as string,
          param: aiProviderResponseBody.param as string | undefined,
          code: aiProviderResponseBody.code as string,
        },
        AIProvider.DEEPSEEK,
      );
    }
 
    if ('choices' in aiProviderResponseBody) {
      const response =
        aiProviderResponseBody as unknown as DeepSeekChatCompleteResponse;
 
      // Validate required fields
      if (!response.id || !Array.isArray(response.choices)) {
        return generateInvalidProviderResponseError(
          aiProviderResponseBody,
          AIProvider.DEEPSEEK,
        );
      }
 
      return {
        id: response.id,
        object: response.object,
        created: response.created,
        model: response.model,
        provider: AIProvider.DEEPSEEK,
        choices: response.choices.map((choice) => ({
          index: choice.index,
          message: {
            role: choice.message.role,
            content: choice.message.content,
            ...(choice.message.tool_calls && {
              tool_calls: choice.message.tool_calls,
            }),
          },
          finish_reason: choice.finish_reason,
        })),
        usage: response.usage
          ? {
              prompt_tokens: response.usage.prompt_tokens,
              completion_tokens: response.usage.completion_tokens,
              total_tokens: response.usage.total_tokens,
            }
          : undefined,
      };
    }
 
    return generateInvalidProviderResponseError(
      aiProviderResponseBody,
      AIProvider.DEEPSEEK,
    );
  };
 
export const deepSeekChatCompleteStreamChunkTransform: ResponseChunkStreamTransformFunction =
  (responseChunk) => {
    let chunk = String(responseChunk).trim();
    chunk = chunk.replace(/^data: /, '');
    chunk = chunk.trim();
    if (chunk === '[DONE]') {
      return `data: ${chunk}\n\n`;
    }
    const parsedChunk: DeepSeekStreamChunk = JSON.parse(chunk);
    return `data: ${JSON.stringify({
      id: parsedChunk.id,
      object: parsedChunk.object,
      created: parsedChunk.created,
      model: parsedChunk.model,
      provider: AIProvider.DEEPSEEK,
      choices: parsedChunk.choices.map((choice) => ({
        index: choice.index,
        delta: choice.delta,
        finish_reason: choice.finish_reason,
      })),
      usage: parsedChunk.usage,
    })}\n\n`;
  };