All files / api/src/handlers response-handler.ts

6.25% Statements 9/144
100% Branches 0/0
0% Functions 0/1
6.25% Lines 9/144

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 1891x 1x 1x 1x 1x             1x     1x 1x 1x                                                                                                                                                                                                                                                                                                                                                        
import { providerConfigs } from '@api/ai-providers';
import { openAIModelResponseJSONToStreamGenerator } from '@api/ai-providers/open-ai-base/create-model-response';
import { openAIChatCompleteJSONToStreamResponseTransform } from '@api/ai-providers/openai/chat-complete';
import { openAICompleteJSONToStreamResponseTransform } from '@api/ai-providers/openai/complete';
import { HttpError } from '@api/errors/http';
import type {
  JSONToStreamGeneratorTransformFunction,
  ResponseChunkStreamTransformFunction,
  ResponseTransformFunction,
  ResponseTransformFunctionType,
} from '@shared/types/ai-providers/config';
import { FunctionName } from '@shared/types/api/request';
import type { SuperAgentsRequestData } from '@shared/types/api/request/body';
import type { SuperAgentsResponseBody } from '@shared/types/api/response/body';
import { type AIProvider, ContentTypeName } from '@shared/types/constants';
import { CacheStatus } from '@shared/types/middleware/cache';
import {
  handleAudioResponse,
  handleImageResponse,
  handleJSONToStreamResponse,
  handleNonStreamingMode,
  handleOctetStreamResponse,
  handleStreamingMode,
  handleTextResponse,
} from './stream-handler';
 
/**
 * Handles various types of responses based on the specified parameters
 * and returns a mapped response
 */
export async function responseHandler(
  response: Response,
  streamingMode: boolean,
  provider: AIProvider,
  responseTransformerFunctionName: FunctionName | undefined,
  aiProviderRequestURL: string,
  cacheStatus: CacheStatus,
  saRequestData: SuperAgentsRequestData,
  strictOpenAiCompliance: boolean,
  areSyncHooksAvailable: boolean,
  onFirstChunk?: () => void,
  onStreamEnd?: (accumulatedChunks: string) => void,
): Promise<{
  response: Response;
  saResponseBody: SuperAgentsResponseBody | null;
  originalResponseJson?: Record<string, unknown> | null;
}> {
  let responseTransformFunction: ResponseTransformFunctionType | undefined;
  const responseContentType = response.headers?.get('content-type');
  const isSuccessStatusCode = [200, 246].includes(response.status);
 
  const providerConfig = providerConfigs[provider];
  if (!providerConfig) {
    throw new HttpError('Provider not found', {
      status: 500,
      statusText: 'Provider not found',
      body: JSON.stringify({ error: 'Provider not found' }),
    });
  }
  let responseTransformFunctions = providerConfig?.responseTransforms;
 
  if (providerConfig?.getConfig) {
    responseTransformFunctions = providerConfig.getConfig(
      saRequestData.requestBody,
    ).responseTransforms;
  }
 
  // Checking status 200 so that errors are not considered as stream mode.
  if (responseTransformerFunctionName && streamingMode && isSuccessStatusCode) {
    // If function name already starts with 'stream_', use it directly
    // Otherwise, add 'stream_' prefix
    const streamFunctionName = responseTransformerFunctionName.startsWith(
      'stream_',
    )
      ? responseTransformerFunctionName
      : (`stream_${responseTransformerFunctionName}` as FunctionName);
 
    responseTransformFunction = responseTransformFunctions?.[
      streamFunctionName
    ] as ResponseTransformFunction | undefined;
  } else if (responseTransformerFunctionName) {
    responseTransformFunction = responseTransformFunctions?.[
      responseTransformerFunctionName
    ] as ResponseTransformFunction | undefined;
  }
 
  const isCacheHit =
    cacheStatus === CacheStatus.HIT || cacheStatus === CacheStatus.SEMANTIC_HIT;
 
  // JSON to text/event-stream conversion is only allowed for unified routes: chat completions and completions.
  // Set the transformer to OpenAI json to stream convertor function in that case.
  if (responseTransformerFunctionName && streamingMode && isCacheHit) {
    switch (responseTransformerFunctionName) {
      case FunctionName.CHAT_COMPLETE:
        responseTransformFunction =
          openAIChatCompleteJSONToStreamResponseTransform;
        break;
      case FunctionName.CREATE_MODEL_RESPONSE:
        responseTransformFunction = openAIModelResponseJSONToStreamGenerator;
        break;
      default:
        responseTransformFunction = openAICompleteJSONToStreamResponseTransform;
        break;
    }
  } else if (responseTransformerFunctionName && !streamingMode && isCacheHit) {
    responseTransformFunction = undefined;
  }
 
  if (
    streamingMode &&
    isSuccessStatusCode &&
    isCacheHit &&
    responseTransformFunction
  ) {
    const streamingResponse = await handleJSONToStreamResponse(
      response,
      provider,
      responseTransformFunction as JSONToStreamGeneratorTransformFunction,
    );
    return { response: streamingResponse, saResponseBody: null };
  }
  if (streamingMode && isSuccessStatusCode) {
    return {
      response: handleStreamingMode(
        response,
        provider,
        responseTransformFunction as ResponseChunkStreamTransformFunction,
        aiProviderRequestURL,
        saRequestData,
        strictOpenAiCompliance,
        onFirstChunk,
        onStreamEnd,
      ),
      saResponseBody: null,
    };
  }
 
  if (responseContentType?.startsWith(ContentTypeName.GENERIC_AUDIO_PATTERN)) {
    return { response: handleAudioResponse(response), saResponseBody: null };
  }
 
  if (
    responseContentType === ContentTypeName.APPLICATION_OCTET_STREAM ||
    responseContentType === ContentTypeName.BINARY_OCTET_STREAM
  ) {
    return {
      response: handleOctetStreamResponse(response),
      saResponseBody: null,
    };
  }
 
  if (responseContentType?.startsWith(ContentTypeName.GENERIC_IMAGE_PATTERN)) {
    return { response: handleImageResponse(response), saResponseBody: null };
  }
 
  if (
    responseContentType?.startsWith(ContentTypeName.PLAIN_TEXT) ||
    responseContentType?.startsWith(ContentTypeName.HTML)
  ) {
    const textResponse = await handleTextResponse(
      response,
      responseTransformFunction as ResponseTransformFunction | undefined,
      saRequestData,
    );
    return { response: textResponse, saResponseBody: null };
  }
 
  if (!responseContentType && response.status === 204) {
    return {
      response: new Response(response.body, response),
      saResponseBody: null,
    };
  }
 
  const nonStreamingResponse = await handleNonStreamingMode(
    response,
    responseTransformFunction as ResponseTransformFunction | undefined,
    strictOpenAiCompliance,
    saRequestData,
    areSyncHooksAvailable,
  );
 
  return {
    response: nonStreamingResponse.response,
    saResponseBody: nonStreamingResponse.saResponseBody,
    originalResponseJson: nonStreamingResponse.originalBodyJson,
  };
}