All files / src/providers/deepseek Streaming.ts

89.74% Statements 70/78
81.25% Branches 52/64
100% Functions 3/3
95.71% Lines 67/70

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                22x 22x       11x                     11x   11x   11x             11x 11x 11x   11x   11x         11x 11x 11x   11x                             10x 1x 1x     9x         9x 1x     8x 8x 8x   8x 18x 18x   18x 18x   18x 18x   18x 164x     164x       164x   164x 164x 7x     7x 1x               1x     7x     157x 157x     157x 1x     155x 164x 164x   164x 148x               155x 3x 3x   3x 1x                 2x 2x 2x     2x 2x             2x               4x 1x   3x     11x 4x          
import { ChatRequest, ChatChunk } from "../Provider.js";
import { APIError } from "../../errors/index.js";
import { logger } from "../../utils/logger.js";
import { mapSystemMessages } from "../utils.js";
import { fetchWithTimeout } from "../../utils/fetch.js";
 
export class DeepSeekStreaming {
  constructor(
    private readonly baseUrl: string,
    private readonly apiKey: string
  ) {}
 
  async *execute(request: ChatRequest, controller?: AbortController): AsyncGenerator<ChatChunk> {
    const abortController = controller || new AbortController();
    const {
      model,
      messages,
      tools,
      max_tokens,
      response_format,
      thinking: _thinking,
      headers: _headers,
      requestTimeout,
      ...rest
    } = request;
 
    const mappedMessages = mapSystemMessages(messages, false);
 
    const body: Record<string, unknown> = {
      model,
      messages: mappedMessages,
      stream: true,
      ...rest
    };
 
    if (max_tokens) body.max_tokens = max_tokens;
    Iif (tools && tools.length > 0) body.tools = tools;
    Iif (response_format) body.response_format = response_format;
 
    let done = false;
    // Track tool calls being built across chunks
    const toolCallsMap = new Map<
      number,
      { id: string; type: string; function: { name: string; arguments: string } }
    >();
 
    try {
      const url = `${this.baseUrl}/chat/completions`;
      logger.logRequest("DeepSeek", "POST", url, body);
 
      const response = await fetchWithTimeout(
        url,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${this.apiKey}`,
            "Content-Type": "application/json",
            ...request.headers
          },
          body: JSON.stringify(body),
          signal: abortController.signal
        },
        requestTimeout
      );
 
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`DeepSeek API error: ${response.status} - ${errorText}`);
      }
 
      logger.debug("DeepSeek streaming started", {
        status: response.status,
        statusText: response.statusText
      });
 
      if (!response.body) {
        throw new Error("No response body for streaming");
      }
 
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";
 
      while (true) {
        const { value, done: readerDone } = await reader.read();
        Iif (readerDone) break;
 
        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
 
        const lines = buffer.split("\n\n");
        buffer = lines.pop() || "";
 
        for (const line of lines) {
          let trimmed = line.trim();
 
          // Handle carriage returns
          Iif (trimmed.endsWith("\r")) {
            trimmed = trimmed.substring(0, trimmed.length - 1);
          }
 
          Iif (!trimmed.startsWith("data: ")) continue;
 
          const data = trimmed.replace("data: ", "").trim();
          if (data === "[DONE]") {
            done = true;
 
            // Yield final tool calls if any were accumulated
            if (toolCallsMap.size > 0) {
              const toolCalls = Array.from(toolCallsMap.values()).map((tc) => ({
                id: tc.id,
                type: "function" as const,
                function: {
                  name: tc.function.name,
                  arguments: tc.function.arguments
                }
              }));
              yield { content: "", tool_calls: toolCalls, done: true };
            }
 
            return;
          }
 
          try {
            const json = JSON.parse(data);
 
            // Check for errors in the data
            if (json.error) {
              throw new APIError("DeepSeek", response.status, json.error.message || "Stream error");
            }
 
            const delta = json.choices?.[0]?.delta;
            const deltaContent = delta?.content;
            const deltaReasoning = delta?.reasoning_content;
 
            if (deltaContent || deltaReasoning) {
              yield {
                content: deltaContent || "",
                reasoning: deltaReasoning || "",
                thinking: deltaReasoning ? { text: deltaReasoning } : undefined
              };
            }
 
            // Handle tool calls delta
            if (delta?.tool_calls) {
              for (const toolCallDelta of delta.tool_calls) {
                const index = toolCallDelta.index;
 
                if (!toolCallsMap.has(index)) {
                  toolCallsMap.set(index, {
                    id: toolCallDelta.id || "",
                    type: "function",
                    function: {
                      name: toolCallDelta.function?.name || "",
                      arguments: toolCallDelta.function?.arguments || ""
                    }
                  });
                } else {
                  const existing = toolCallsMap.get(index)!;
                  Iif (toolCallDelta.id) existing.id = toolCallDelta.id;
                  Iif (toolCallDelta.function?.name) {
                    existing.function.name += toolCallDelta.function.name;
                  }
                  Eif (toolCallDelta.function?.arguments) {
                    existing.function.arguments += toolCallDelta.function.arguments;
                  }
                }
              }
            }
          } catch (e) {
            // Re-throw APIError
            if (e instanceof APIError) throw e;
            // Ignore other parse errors
          }
        }
      }
      done = true;
    } catch (e) {
      // Graceful exit on abort
      if (e instanceof Error && e.name === "AbortError") {
        return;
      }
      throw e;
    } finally {
      // Cleanup: abort if user breaks early
      if (!done) {
        abortController.abort();
      }
    }
  }
}