# All files / src/providers/openai Streaming.ts

73.86% Statements 65/88
64.47% Branches 49/76
66.66% Functions 2/3
77.1% Lines 64/83

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

    49x
    49x

    49x

    12x
    12x

    12x
    12x

    12x

    12x

    12x

    12x

    12x
    1x

    12x
    3x
    1x

    2x

    12x

    12x

    12x
    1x

    12x

    12x

    12x
    12x
    12x

    12x

    12x
    2x

    10x

    10x
    1x

    9x
    9x
    9x

    9x
    17x
    17x

    17x
    17x

    17x
    17x

    17x
    41x

    41x

    41x

    39x
    39x
    9x

    9x

    9x

    30x
    30x

    30x

    29x

    41x
    22x

    29x

    29x

    1x

    3x

    3x

    12x
    3x

     import { ChatRequest, ChatChunk } from "../Provider.js";
    import { Capabilities } from "./Capabilities.js";
    import { handleOpenAIError } from "./Errors.js";
    import { buildUrl } from "./utils.js";
    import { APIError } from "../../errors/index.js";
    import { logger } from "../../utils/logger.js";
    import { fetchWithTimeout } from "../../utils/fetch.js";

    import { OpenAIProvider } from "./OpenAIProvider.js";
    import { mapSystemMessages } from "../utils.js";

    export class OpenAIStreaming {
      private readonly baseUrl: string;

      constructor(
        private readonly providerOrUrl: OpenAIProvider | string,
        private readonly apiKey: string
      ) {
        this.baseUrl = typeof providerOrUrl === "string" ? providerOrUrl : providerOrUrl.apiBase();
      }

      async *execute(request: ChatRequest, controller?: AbortController): AsyncGenerator<ChatChunk> {
        const internalController = new AbortController();
        const abortController = controller || internalController;

        const signal = request.signal ? (request.signal as AbortSignal) : abortController.signal;
        const temperature = Capabilities.normalizeTemperature(request.temperature, request.model);

        const isMainOpenAI = this.baseUrl.includes("api.openai.com");
        const supportsDeveloperRole =
          isMainOpenAI &&
          (typeof this.providerOrUrl === "string"
            ? Capabilities.supportsDeveloperRole(request.model)
            : this.providerOrUrl.capabilities?.supportsDeveloperRole(request.model));

        const mappedMessages = mapSystemMessages(request.messages, !!supportsDeveloperRole);

        const body: Record<string, unknown> = {
          model: request.model,
          messages: mappedMessages,
          stream: true
        };

        if (temperature !== undefined && temperature !== null) {
          body.temperature = temperature;
        }

        if (request.max_tokens) {
          if (Capabilities.needsMaxCompletionTokens(request.model)) {
            body.max_completion_tokens = request.max_tokens;
          } else {
            body.max_tokens = request.max_tokens;
          }
        }

        Iif (request.response_format) {
          body.response_format = request.response_format;
        }

        Iif (request.tools && request.tools.length > 0) {
          body.tools = request.tools;
        }

        if (request.thinking?.effort && request.thinking.effort !== "none") {
          body.reasoning_effort = request.thinking.effort;
        }

        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 = buildUrl(this.baseUrl, "/chat/completions");
          logger.logRequest("OpenAI", "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
            },
            request.requestTimeout
          );

          if (!response.ok) {
            await handleOpenAIError(response, request.model);
          }

          logger.debug("OpenAI 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() || ""; // Keep the last incomplete part in the buffer

            for (const line of lines) {
              let trimmed = line.trim();

              // Handle carriage returns
              Iif (trimmed.endsWith("\r")) {
                trimmed = trimmed.substring(0, trimmed.length - 1);
              }

              if (!trimmed.startsWith("data: ")) continue;

              const data = trimmed.replace("data: ", "").trim();
              if (data === "[DONE]") {
                done = true;

                // Yield final tool calls if any were accumulated
                Iif (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
                Iif (json.error) {
                  throw new APIError("OpenAI", response.status, json.error.message || "Stream error");
                }

                const delta = json.choices?.[0]?.delta;

                // Handle content delta
                if (delta?.content) {
                  yield { content: delta.content };
                }

                // Handle reasoning content delta
                Iif (delta?.reasoning_content) {
                  yield { content: "", thinking: { text: delta.reasoning_content } };
                }

                // Handle tool calls delta
                Iif (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)!;
                      if (toolCallDelta.id) existing.id = toolCallDelta.id;
                      if (toolCallDelta.function?.name) {
                        existing.function.name += toolCallDelta.function.name;
                      }
                      if (toolCallDelta.function?.arguments) {
                        existing.function.arguments += toolCallDelta.function.arguments;
                      }
                    }
                  }
                }
              } catch (e) {
                // Re-throw APIError
                Iif (e instanceof APIError) throw e;
                // Ignore other parse errors
              }
            }
          }
          done = true;
        } catch (e) {
          // Graceful exit on abort
          Iif (e instanceof Error && e.name === "AbortError") {
            return;
          }
          throw e;
        } finally {
          // Cleanup: abort if user breaks early
          if (!done) {
            abortController.abort();
          }
        }
      }
    }