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.

11.3 KB
Raw Blame
import type Anthropic from '@anthropic-ai/sdk';
import type { Stream } from '@anthropic-ai/sdk/streaming';
import type { ChatCitationItem, ChatMessageError } from '@lobechat/types';

import type { ChatStreamCallbacks } from '../../../types';
import { AgentRuntimeErrorType } from '../../../types/error';
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 { convertAnthropicUsage } from '../../usageConverters';

export const transformAnthropicStream = (
  chunk: Anthropic.MessageStreamEvent,
  context: StreamContext,
  payload?: ChatPayloadForTransformStream,
): StreamProtocolChunk | StreamProtocolChunk[] => {
  /**
   * `convertIterableToStream` turns an SDK iterator failure (e.g. `TypeError: terminated` when
   * the upstream connection drops mid-stream) into an error chunk. Without surfacing it here the
   * chunk fell through as unknown data, the stream closed normally, and the dropped connection
   * was misreported as an empty completion instead of an interrupted, fallback-eligible one.
   */
  if (FIRST_CHUNK_ERROR_KEY in chunk) {
    const {
      [FIRST_CHUNK_ERROR_KEY]: _,
      name: _name,
      stack: _stack,
      ...body
    } = chunk as Record<string, unknown>;
    const errorData = {
      body,
      message: typeof body.message === 'string' ? body.message : JSON.stringify(body),
      type:
        typeof body.errorType === 'string'
          ? (body.errorType as typeof AgentRuntimeErrorType.ProviderBizError)
          : AgentRuntimeErrorType.ProviderBizError,
    } satisfies ChatMessageError;
    return { data: errorData, id: 'first_chunk_error', type: 'error' };
  }

  const raw = chunk as unknown as Record<string, unknown>;

  /**
   * Anthropic reports a mid-stream failure (e.g. `overloaded_error`) as an `error` event. The
   * official SDK throws on the `event: error` line, but relays often forward the payload as a plain
   * data frame, which reached the switch below as an unknown event and closed as an empty
   * completion.
   */
  if (raw.type === 'error') {
    const error = (raw.error ?? {}) as { message?: string; type?: string };
    const errorData = {
      body: raw,
      message: error.message || error.type || 'The provider reported an error mid-stream.',
      type: AgentRuntimeErrorType.ProviderBizError,
    } satisfies ChatMessageError;
    return { data: errorData, id: context.id, type: 'error' };
  }

  /**
   * A relay that answers an Anthropic request in OpenAI chat-completions format produces no event
   * this adapter understands, so the whole answer was dropped and reported as an empty completion.
   * Name the protocol mismatch instead, so the user knows to fix the provider's API format.
   */
  if (Array.isArray(raw.choices) || raw.object === 'chat.completion.chunk') {
    const errorData = {
      body: raw,
      message:
        'The provider answered an Anthropic-format request with OpenAI chat-completions chunks. Check that this provider is configured with the API format its endpoint actually serves.',
      type: AgentRuntimeErrorType.UpstreamMalformedResponse,
    } satisfies ChatMessageError;
    return { data: errorData, id: context.id, type: 'error' };
  }

  // maybe need another structure to add support for multiple choices
  switch (chunk.type) {
    case 'message_start': {
      context.id = chunk.message.id;
      context.returnedCitationArray = [];
      const usage = convertAnthropicUsage(chunk, undefined, payload);

      if (usage) {
        context.usage = usage;
      } else {
        delete context.usage;
      }

      return { data: chunk.message, id: chunk.message.id, type: 'data' };
    }
    case 'content_block_start': {
      switch (chunk.content_block.type) {
        case 'redacted_thinking': {
          return {
            data: chunk.content_block.data,
            id: context.id,
            type: 'flagged_reasoning_signature',
          };
        }

        case 'text': {
          return { data: chunk.content_block.text, id: context.id, type: 'data' };
        }

        case 'server_tool_use':
        case 'tool_use': {
          const toolChunk = chunk.content_block;

          // if toolIndex is not defined, set it to 0
          if (typeof context.toolIndex === 'undefined') {
            context.toolIndex = 0;
          }
          // if toolIndex is defined, increment it
          else {
            context.toolIndex += 1;
          }

          const toolCall: StreamToolCallChunkData = {
            function: {
              arguments: '',
              name: toolChunk.name,
            },
            id: toolChunk.id,
            index: context.toolIndex,
            type: 'function',
          };

          context.tool = { id: toolChunk.id, index: context.toolIndex, name: toolChunk.name };

          return { data: [toolCall], id: context.id, type: 'tool_calls' };
        }

        /*
        case 'web_search_tool_result': {
          const citations = chunk.content_block.content;

          return [
            {
              data: {
                citations: (citations as any[]).map(
                  (item) =>
                    ({
                      title: item.title,
                      url: item.url,
                    }) as CitationItem,
                ),
              },
              id: context.id,
              type: 'grounding',
            },
          ];
        }
        */

        case 'thinking': {
          const thinkingChunk = chunk.content_block;

          // if there is signature in the thinking block, return both thinking and signature
          if (!!thinkingChunk.signature) {
            return [
              { data: thinkingChunk.thinking, id: context.id, type: 'reasoning' },
              { data: thinkingChunk.signature, id: context.id, type: 'reasoning_signature' },
            ];
          }

          if (typeof thinkingChunk.thinking === 'string')
            return { data: thinkingChunk.thinking, id: context.id, type: 'reasoning' };

          return { data: thinkingChunk, id: context.id, type: 'data' };
        }

        default: {
          break;
        }
      }

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

    case 'content_block_delta': {
      switch (chunk.delta.type) {
        case 'text_delta': {
          return { data: chunk.delta.text, id: context.id, type: 'text' };
        }

        case 'input_json_delta': {
          const delta = chunk.delta.partial_json;

          const toolCall: StreamToolCallChunkData = {
            function: { arguments: delta },
            index: context.toolIndex || 0,
            type: 'function',
          };

          return {
            data: [toolCall],
            id: context.id,
            type: 'tool_calls',
          } as StreamProtocolToolCallChunk;
        }

        case 'signature_delta': {
          return {
            data: chunk.delta.signature,
            id: context.id,
            type: 'reasoning_signature',
          };
        }

        case 'thinking_delta': {
          return {
            data: chunk.delta.thinking,
            id: context.id,
            type: 'reasoning',
          };
        }

        case 'citations_delta': {
          const citations = (chunk as any).delta.citation;

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

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

        default: {
          break;
        }
      }
      return { data: chunk, id: context.id, type: 'data' };
    }

    case 'message_delta': {
      const aggregatedUsage = convertAnthropicUsage(chunk, context.usage, payload);

      if (aggregatedUsage) {
        context.usage = aggregatedUsage;
      }

      if (aggregatedUsage && (aggregatedUsage.totalTokens ?? 0) > 0) {
        delete context.usageMissingDiagnostics;
        return [
          { data: chunk.delta.stop_reason, id: context.id, type: 'stop' },
          { data: aggregatedUsage, id: context.id, type: 'usage' },
        ];
      }

      context.usageMissingDiagnostics = {
        apiMode: 'messages',
        finishReason: chunk.delta.stop_reason,
        hasUsageMetadata: Boolean(chunk.usage),
        model: payload?.model,
        provider: payload?.provider,
        source: 'anthropic_messages',
        terminalEventType: chunk.type,
      };

      return { data: chunk.delta.stop_reason, id: context.id, type: 'stop' };
    }

    case 'message_stop': {
      if (!context.usage && !context.usageMissingDiagnostics) {
        context.usageMissingDiagnostics = {
          apiMode: 'messages',
          hasUsageMetadata: false,
          model: payload?.model,
          provider: payload?.provider,
          source: 'anthropic_messages',
          terminalEventType: chunk.type,
        };
      }

      return [
        ...(context.returnedCitationArray?.length
          ? [
              {
                data: { citations: context.returnedCitationArray },
                id: context.id,
                type: 'grounding',
              },
            ]
          : []),
        { data: 'message_stop', id: context.id, type: 'stop' },
      ] as any;
    }

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

export interface AnthropicStreamOptions {
  callbacks?: ChatStreamCallbacks;
  enableStreaming?: boolean; // Select TPS calculation method (pass false for non-streaming)
  inputStartAt?: number;
  payload?: ChatPayloadForTransformStream;
}

export const AnthropicStream = (
  stream: Stream<Anthropic.MessageStreamEvent> | ReadableStream,
  { callbacks, inputStartAt, enableStreaming = true, payload }: AnthropicStreamOptions = {},
) => {
  const streamStack: StreamContext = { id: '', pricingOptions: payload?.pricingOptions };

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

  const transformWithPayload: typeof transformAnthropicStream = (chunk, ctx) => {
    recordProviderReportedCost(streamStack, chunk);
    return transformAnthropicStream(chunk, ctx, payload);
  };

  return readableStream
    .pipeThrough(createFirstErrorHandleTransformer(undefined, payload?.provider))
    .pipeThrough(
      createTokenSpeedCalculator(transformWithPayload, {
        enableStreaming,
        inputStartAt,
        streamStack,
      }),
    )
    .pipeThrough(
      /**
       * A Messages stream always ends with `message_delta` + `message_stop`. Some relays close the
       * connection mid-response without either; without this flag the truncated output was
       * treated as a normal completion, so half-written tool arguments got executed.
       */
      createModelEventTransformer((c) => c, streamStack, { requireTerminalEvent: true }),
    )
    .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))
    .pipeThrough(createSSEEncoder());
};