Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

12.7 KB
Raw Blame
import type { ChatCitationItem, ChatMessageError } from '@lobechat/types';
import type OpenAI from 'openai';
import type { Stream } from 'openai/streaming';

import { AgentRuntimeErrorType } from '../../../types/error';
import { serializeScopedSignature } from '../../../utils/signatureScope';
import {
  createEventCallbacksTransformer,
  createModelEventTransformer,
  createSSEEncoder,
} from '../../streams/events';
import type {
  ChatPayloadForTransformStream,
  StreamContext,
  StreamProtocolChunk,
  StreamProtocolToolCallChunk,
  StreamToolCallChunkData,
} from '../../streams/protocol';
import {
  convertIterableToStream,
  createFirstErrorHandleTransformer,
  createTokenSpeedCalculator,
  FIRST_CHUNK_ERROR_KEY,
} from '../../streams/protocol';
import { recordProviderReportedCost } from '../../streams/providerReportedCost';
import { convertOpenAIResponseUsage } from '../../usageConverters';
import type { OpenAIStreamOptions } from '../openaiChatCompletions/stream';

const toResponsesError = (error: { code?: string | null; message?: string | null }) =>
  ({
    body: error,
    message: error.message || error.code || 'The provider reported an error mid-stream.',
    type: AgentRuntimeErrorType.ProviderBizError,
  }) satisfies ChatMessageError;

type ResponsesStreamContext = StreamContext & {
  responseTools?: Map<number, { id: string; index: number; name: string; namespace?: string }>;
};

const transformOpenAIStream = (
  chunk:
    | OpenAI.Responses.ResponseStreamEvent
    | {
        delta: string;
        item_id: string;
        type: 'response.reasoning_text.delta';
      }
    | {
        annotation: {
          end_index: number;
          start_index: number;
          title: string;
          type: 'url_citation';
          url: string;
        };
        item_id: string;
        type: 'response.output_text.annotation.added';
      },
  streamContext: ResponsesStreamContext,
  payload?: ChatPayloadForTransformStream,
): StreamProtocolChunk | StreamProtocolChunk[] => {
  // handle the first chunk error
  if (FIRST_CHUNK_ERROR_KEY in chunk) {
    delete chunk[FIRST_CHUNK_ERROR_KEY];
    // @ts-ignore
    delete chunk['name'];
    // @ts-ignore
    delete chunk['stack'];

    const errorData = {
      body: chunk,
      message:
        'message' in chunk
          ? typeof chunk.message === 'string'
            ? chunk.message
            : JSON.stringify(chunk)
          : JSON.stringify(chunk),
      type:
        'errorType' in chunk
          ? (chunk.errorType as typeof AgentRuntimeErrorType.ProviderBizError)
          : AgentRuntimeErrorType.ProviderBizError,
    } satisfies ChatMessageError;
    return { data: errorData, id: 'first_chunk_error', type: 'error' };
  }

  try {
    switch (chunk.type) {
      case 'response.created': {
        streamContext.id = chunk.response.id;
        streamContext.returnedCitationArray = [];

        return { data: chunk.response.status, id: streamContext.id, type: 'data' };
      }

      case 'response.output_item.added': {
        switch (chunk.item.type) {
          case 'custom_tool_call':
          case 'function_call': {
            streamContext.toolIndex =
              typeof streamContext.toolIndex === 'undefined' ? 0 : streamContext.toolIndex + 1;
            streamContext.tool = {
              id: chunk.item.call_id,
              index: streamContext.toolIndex,
              name: chunk.item.name,
            };
            const namespace = chunk.item.namespace ? { namespace: chunk.item.namespace } : {};
            streamContext.responseTools ??= new Map();
            streamContext.responseTools.set(chunk.output_index, {
              ...streamContext.tool,
              ...namespace,
            });

            return {
              data: [
                {
                  function: {
                    arguments:
                      chunk.item.type === 'custom_tool_call'
                        ? chunk.item.input
                        : chunk.item.arguments,
                    name: chunk.item.name,
                  },
                  ...namespace,
                  id: chunk.item.call_id,
                  index: streamContext.toolIndex!,
                  type: chunk.item.type === 'custom_tool_call' ? 'custom' : 'function',
                } satisfies StreamToolCallChunkData,
              ],
              id: streamContext.id,
              type: 'tool_calls',
            } satisfies StreamProtocolToolCallChunk;
          }
        }

        return { data: chunk.item, id: streamContext.id, type: 'data' };
      }

      case 'response.custom_tool_call_input.delta':
      case 'response.function_call_arguments.delta': {
        const tool = streamContext.responseTools?.get(chunk.output_index) ?? streamContext.tool;
        return {
          data: [
            {
              function: { arguments: chunk.delta, name: tool?.name },
              id: tool?.id,
              index: tool?.index ?? streamContext.toolIndex!,
              type: chunk.type === 'response.custom_tool_call_input.delta' ? 'custom' : 'function',
            } satisfies StreamToolCallChunkData,
          ],
          id: streamContext.id,
          type: 'tool_calls',
        } satisfies StreamProtocolToolCallChunk;
      }
      case 'response.output_text.delta': {
        return { data: chunk.delta, id: chunk.item_id, type: 'text' };
      }

      case 'response.reasoning_summary_part.added': {
        if (!streamContext.startReasoning) {
          streamContext.startReasoning = true;
          return { data: '', id: chunk.item_id, type: 'reasoning' };
        } else {
          return { data: '\n', id: chunk.item_id, type: 'reasoning' };
        }
      }

      case 'response.reasoning_summary_text.delta':
      case 'response.reasoning_text.delta': {
        return { data: chunk.delta, id: chunk.item_id, type: 'reasoning' };
      }

      case 'response.output_text.annotation.added': {
        // OpenAI SDK v6 types the annotation payload as `unknown`; narrow to the URL-citation shape we read.
        const citations = chunk.annotation as { title?: string; url?: string };

        if (streamContext.returnedCitationArray) {
          streamContext.returnedCitationArray.push({
            title: citations.title,
            url: citations.url,
          } as ChatCitationItem);
        }

        return { data: null, id: chunk.item_id, type: 'text' };
      }

      case 'response.output_item.done': {
        if (chunk.item.type === 'reasoning') {
          const scopedEncryptedContent = chunk.item.encrypted_content
            ? serializeScopedSignature(
                chunk.item.encrypted_content,
                payload?.reasoningSignatureScope,
                'reasoning',
              )
            : undefined;
          const hasSummaryText = chunk.item.summary?.some(({ text }) => !!text);

          // Encrypted reasoning without a verifiable scope stays fail-closed (#17694):
          // never expose the raw provider payload to persistence.
          if (!scopedEncryptedContent && !hasSummaryText)
            return { data: null, id: chunk.item.id, type: 'text' };

          const chunks: StreamProtocolChunk[] = [
            {
              data: {
                ...chunk.item,
                encrypted_content: scopedEncryptedContent,
              },
              id: chunk.item.id,
              type: 'reasoning_response_item',
            },
          ];

          /**
           * Dual-emit the scope-serialized payload on the legacy string-only event so
           * already-released clients keep single-item reasoning continuation. New clients
           * prefer `responseItems` on replay, so the redundancy is harmless.
           */
          if (scopedEncryptedContent)
            chunks.push({
              data: scopedEncryptedContent,
              id: chunk.item.id,
              type: 'reasoning_signature',
            });

          return chunks;
        }

        if (streamContext.returnedCitationArray?.length) {
          return {
            data: { citations: streamContext.returnedCitationArray },
            id: chunk.item.id,
            type: 'grounding',
          };
        }

        return { data: null, id: chunk.item.id, type: 'text' };
      }

      case 'response.completed': {
        if (chunk.response.usage) {
          delete streamContext.usageMissingDiagnostics;
          return {
            data: convertOpenAIResponseUsage(chunk.response.usage, payload),
            id: chunk.response.id,
            type: 'usage',
          };
        }

        streamContext.usageMissingDiagnostics = {
          apiMode: 'responses',
          hasUsageMetadata: false,
          includeUsageRequested: payload?.includeUsageRequested,
          model: payload?.model,
          provider: payload?.provider,
          responseId: chunk.response.id,
          source: 'openai_responses',
          terminalEventType: chunk.type,
          terminalStatus: chunk.response.status,
        };

        return { data: chunk, id: streamContext.id, type: 'data' };
      }

      /**
       * Terminal failure events. Passing them through as plain `data` let the stream close
       * normally with no content, no usage and no finish reason, so a failed or rate-limited
       * response was reported as an empty completion — non-retryable, and without the
       * upstream's own explanation.
       */
      case 'response.failed': {
        const { error, usage } = chunk.response;
        const failure = toResponsesError(
          error ?? { message: 'The provider reported the response as failed.' },
        );
        const failureChunk = { data: failure, id: streamContext.id, type: 'error' } as const;
        if (!usage) return failureChunk;

        return [
          {
            data: convertOpenAIResponseUsage(usage, payload),
            id: streamContext.id,
            type: 'usage',
          },
          failureChunk,
        ];
      }

      case 'error': {
        return { data: toResponsesError(chunk), id: streamContext.id, type: 'error' };
      }

      /**
       * An incomplete response is still billed. Surface its usage and reason so a turn that hit
       * `max_output_tokens` during reasoning reads as a length stop rather than an unbilled drop.
       */
      case 'response.incomplete': {
        const { incomplete_details, usage } = chunk.response;
        const reason = incomplete_details?.reason;
        const stopChunk = {
          data: reason === 'max_output_tokens' ? 'length' : (reason ?? 'incomplete'),
          id: streamContext.id,
          type: 'stop',
        } as const;
        if (!usage) return stopChunk;

        return [
          {
            data: convertOpenAIResponseUsage(usage, payload),
            id: streamContext.id,
            type: 'usage',
          },
          stopChunk,
        ];
      }

      default: {
        return { data: chunk, id: streamContext.id, type: 'data' };
      }
    }
  } catch (e) {
    const errorName = 'StreamChunkError';
    console.error(`[${errorName}]`, e);
    console.error(`[${errorName}] raw chunk:`, chunk);

    const err = e as Error;

    const errorData = {
      body: {
        message:
          'chat response streaming chunk parse error, please contact your API Provider to fix it.',
        context: { error: { message: err.message, name: err.name }, chunk },
      },
      type: errorName,
    } as ChatMessageError;

    return { data: errorData, id: streamContext.id, type: 'error' };
  }
};

export const OpenAIResponsesStream = (
  stream: Stream<OpenAI.Responses.ResponseStreamEvent> | ReadableStream,
  {
    callbacks,
    bizErrorTypeTransformer,
    inputStartAt,
    enableStreaming = true,
    payload,
  }: OpenAIStreamOptions = {},
) => {
  const streamStack: StreamContext = { id: '' };

  const readableStream =
    stream instanceof ReadableStream
      ? stream
      : convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });

  // use closure to pass payload to transformOpenAIStream
  const transformWithPayload: typeof transformOpenAIStream = (chunk, streamContext) => {
    recordProviderReportedCost(streamStack, chunk);
    return transformOpenAIStream(chunk, streamContext, payload);
  };

  return (
    readableStream
      // 1. handle the first error if exist
      // provider like huggingface or minimax will return error in the stream,
      // so in the first Transformer, we need to handle the error
      .pipeThrough(createFirstErrorHandleTransformer(bizErrorTypeTransformer, payload?.provider))
      .pipeThrough(
        createTokenSpeedCalculator(transformWithPayload, {
          enableStreaming,
          inputStartAt,
          streamStack,
        }),
      )
      .pipeThrough(createModelEventTransformer((c) => c, streamStack))
      .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))
      .pipeThrough(createSSEEncoder())
  );
};