All files / api/src/services transform-to-provider-request.ts

33.2% Statements 84/253
60% Branches 15/25
42.85% Functions 3/7
33.2% Lines 84/253

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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 3481x 1x   1x                                   8x 8x 8x 8x 8x 8x   8x 8x 6x   6x 6x 5x 4x 6x 3x 3x 3x 3x 3x 3x 3x   5x   5x 5x 5x 5x 8x     5x 5x   1x 8x 8x 8x 8x 8x 8x 8x     8x           8x 8x     8x                         8x 8x 2x 2x   8x             8x 2x 2x   8x       8x 8x   1x 6x 6x 6x 6x 6x     6x   8x 8x 8x 8x   8x   8x   8x     8x 8x 8x 8x 8x 8x                                                 8x 8x   6x 6x                   1x                                                         1x                                                                                       1x                                                             1x                                                                                                                             1x  
import { providerConfigs } from '@api/ai-providers';
import { GatewayError } from '@api/errors/gateway';
import type { AIProviderFunctionConfig } from '@shared/types/ai-providers/config';
import { FunctionName } from '@shared/types/api/request';
import type {
  SuperAgentsRequestBody,
  SuperAgentsRequestData,
} from '@shared/types/api/request/body';
import type { SuperAgentsTarget } from '@shared/types/api/request/headers';
import type {
  ChatCompletionParameterTransformFunction,
  ParameterConfig,
  ParameterValueTypes,
} from '@shared/types/api/response/body';
import type { ChatCompletionRequestBody } from '@shared/types/api/routes/chat-completions-api/request';
import type { AIProvider } from '@shared/types/constants';
 
/**
 * Helper function to set a nested property in an object.
 * Guards against prototype pollution by checking each property name inline.
 */
function setNestedProperty(
  obj: Record<string, unknown>,
  path: string,
  value: unknown,
): void {
  const parts = path.split('.');
 
  let current = obj;
  for (let i = 0; i < parts.length - 1; i++) {
    const part = parts[i];
    // Guard against prototype pollution at each step
    if (
      part === '__proto__' ||
      part === 'constructor' ||
      part === 'prototype'
    ) {
      return;
    }
    if (!Object.hasOwn(current, part)) {
      current[part] = Object.create(null);
    }
    current = current[part] as Record<string, unknown>;
  }
 
  const lastPart = parts[parts.length - 1];
  // Guard against prototype pollution for the final property
  if (
    lastPart === '__proto__' ||
    lastPart === 'constructor' ||
    lastPart === 'prototype'
  ) {
    return;
  }
  current[lastPart] = value;
}
 
const getValue = (
  configParam: string,
  saRequestBody: SuperAgentsRequestBody,
  paramConfig: ParameterConfig,
): ParameterValueTypes => {
  let value = saRequestBody[
    configParam as keyof typeof saRequestBody
  ] as ParameterValueTypes;
 
  // If a transformation is defined for this parameter, apply it
  if (paramConfig.transform) {
    value = (paramConfig.transform as ChatCompletionParameterTransformFunction)(
      saRequestBody as ChatCompletionRequestBody,
    );
  }
 
  if (
    value === 'sa-default' &&
    paramConfig &&
    paramConfig.default !== undefined
  ) {
    if (typeof paramConfig.default === 'function') {
      throw new GatewayError(
        `Default value for ${configParam} is a function, but it should be a string, number, boolean, or object`,
      );
    }
 
    // Set the transformed parameter to the default value
    value = paramConfig.default;
  }
 
  // If a minimum is defined for this parameter and the value is less than this, set the value to the minimum
  // Also, we should only do this comparison if value is of type 'number'
  if (
    typeof value === 'number' &&
    paramConfig &&
    paramConfig.min !== undefined &&
    value < paramConfig.min
  ) {
    value = paramConfig.min;
  }
 
  // If a maximum is defined for this parameter and the value is more than this, set the value to the maximum
  // Also, we should only do this comparison if value is of type 'number'
  else if (
    typeof value === 'number' &&
    paramConfig &&
    paramConfig.max !== undefined &&
    value > paramConfig.max
  ) {
    value = paramConfig.max;
  }
 
  return value;
};
 
export const transformUsingProviderConfig = (
  providerConfig: AIProviderFunctionConfig,
  saRequestBody: SuperAgentsRequestBody,
  saTarget: SuperAgentsTarget,
): Record<string, unknown> => {
  const transformedRequest: Record<string, unknown> = {};
 
  // For each parameter in the provider's configuration
  for (const configParam in providerConfig) {
    // Get the config for this parameter
    let paramConfigs = providerConfig[configParam];
    if (!Array.isArray(paramConfigs)) {
      paramConfigs = [paramConfigs];
    }
 
    for (const paramConfig of paramConfigs) {
      // If the parameter is present in the incoming request body
      if (configParam in saRequestBody) {
        // Get the value for this parameter
        const value = getValue(configParam, saRequestBody, paramConfig);
 
        // Set the transformed parameter to the validated value
        setNestedProperty(
          transformedRequest,
          paramConfig?.param as string,
          value,
        );
      }
      // If the parameter is not present in the incoming request body
      else {
        // Check if there's a transform function - if so, call it
        // This handles cases like Anthropic's __json_output tool that needs to be added
        // when response_format is present, even though tools is not required
        if (paramConfig?.transform) {
          const value = getValue(configParam, saRequestBody, paramConfig);
          // Only set if the transform returned a non-null/undefined value
          if (value !== null && value !== undefined) {
            setNestedProperty(transformedRequest, paramConfig.param, value);
          }
        }
        // Otherwise, if it's required and has a default, use the default
        else if (paramConfig?.required && paramConfig?.default !== undefined) {
          let value: unknown;
          if (typeof paramConfig.default === 'function') {
            value = paramConfig.default({ saRequestBody, saTarget });
          } else {
            value = paramConfig.default;
          }
          // Set the transformed parameter to the default value
          setNestedProperty(transformedRequest, paramConfig.param, value);
        }
      }
    }
  }
 
  return transformedRequest;
};
 
/**
 * Transforms the request body to match the structure required by the AI provider.
 * It also ensures the values for each parameter are within the minimum and maximum
 * constraints defined in the provider's configuration. If a required parameter is missing,
 * it assigns the default value from the provider's configuration.
 *
 * @throws {GatewayError} If the provider is not supported.
 */
const transformToProviderRequestJSON = (
  provider: AIProvider,
  saRequestBody: SuperAgentsRequestBody,
  fn: FunctionName,
  saTarget: SuperAgentsTarget,
): Record<string, unknown> => {
  // Get the configuration for the specified provider
  const providerConfig = providerConfigs[provider];
 
  if (!providerConfig) {
    throw new GatewayError(`${fn} is not supported by ${provider}`);
  }
 
  let functionConfig: AIProviderFunctionConfig | undefined;
  if (providerConfig.getConfig) {
    functionConfig = providerConfig.getConfig(saRequestBody)[
      fn
    ] as AIProviderFunctionConfig;
  } else {
    functionConfig = providerConfig[fn] as AIProviderFunctionConfig;
  }
 
  if (!functionConfig) {
    throw new GatewayError(`${fn} is not supported by ${provider}`);
  }
 
  return transformUsingProviderConfig(functionConfig, saRequestBody, saTarget);
};
 
const transformToProviderRequestFormData = (
  provider: AIProvider,
  saRequestBody: SuperAgentsRequestBody,
  fn: FunctionName,
  saTarget: SuperAgentsTarget,
): FormData => {
  const providerConfig = providerConfigs[provider];
 
  if (!providerConfig) {
    throw new GatewayError(`${fn} is not supported by ${provider}`);
  }
 
  let functionConfig: AIProviderFunctionConfig | undefined;
  if (providerConfig?.getConfig) {
    const overrideConfig = providerConfig.getConfig(saRequestBody);
    functionConfig = overrideConfig[fn] as AIProviderFunctionConfig;
  } else {
    functionConfig = providerConfig[fn] as AIProviderFunctionConfig;
  }
  const formData = new FormData();
  for (const configParam in functionConfig) {
    let paramConfigs = functionConfig[configParam];
    if (!Array.isArray(paramConfigs)) {
      paramConfigs = [paramConfigs];
    }
    for (const paramConfig of paramConfigs) {
      if (configParam in saRequestBody) {
        const value = getValue(configParam, saRequestBody, paramConfig);
 
        formData.append(paramConfig.param, value as unknown as string);
      } else if (paramConfig?.required && paramConfig?.default !== undefined) {
        let value: unknown;
        if (typeof paramConfig.default === 'function') {
          value = paramConfig.default({ saRequestBody, saTarget });
        } else {
          value = paramConfig.default;
        }
        formData.append(paramConfig.param, value?.toString() ?? '');
      }
    }
  }
  return formData;
};
 
const transformToProviderRequestReadableStream = (
  provider: AIProvider,
  body: ReadableStream,
  fn: FunctionName,
): ReadableStream => {
  const providerConfig = providerConfigs[provider];
 
  if (!providerConfig) {
    throw new GatewayError(`${fn} is not supported by ${provider}`);
  }
 
  let transformers: Record<string, unknown> | undefined;
  if (providerConfig.getConfig) {
    transformers = providerConfig.getConfig(undefined).requestTransforms;
  } else {
    transformers = providerConfig.requestTransforms;
  }
 
  if (!transformers) {
    throw new GatewayError(`${fn} is not supported by ${provider}`);
  }
 
  const transformer = transformers[fn] as (
    body: ReadableStream,
  ) => ReadableStream;
  return transformer(body);
};
 
/**
 * Transforms the request parameters to the format expected by the provider.
 */
export const transformToProviderRequest = (
  aiProvider: AIProvider,
  saTarget: SuperAgentsTarget,
  saRequestData: SuperAgentsRequestData,
): Record<string, unknown> | ReadableStream | FormData | ArrayBuffer => {
  // this returns a ReadableStream
  if (saRequestData.functionName === FunctionName.UPLOAD_FILE) {
    if (!(saRequestData.requestBody instanceof ReadableStream)) {
      throw new GatewayError(
        `Expected a ReadableStream for ${saRequestData.functionName} but got ${typeof saRequestData.requestBody}`,
      );
    }
 
    return transformToProviderRequestReadableStream(
      aiProvider,
      saRequestData.requestBody as ReadableStream,
      saRequestData.functionName,
    );
  }
 
  if (
    saRequestData.requestBody instanceof FormData ||
    saRequestData.requestBody instanceof ArrayBuffer
  )
    return saRequestData.requestBody;
 
  if (saRequestData.requestBody instanceof ReadableStream) {
    throw new GatewayError(
      `Unsupported request body type for ${saRequestData.functionName}: ${typeof saRequestData.requestBody}`,
    );
  }
 
  if (saRequestData.functionName === FunctionName.PROXY) {
    return saRequestData.requestBody;
  }
 
  const providerConfig = providerConfigs[aiProvider];
 
  if (!providerConfig) {
    throw new GatewayError(
      `${saRequestData.functionName} is not supported by ${aiProvider}`,
    );
  }
 
  const providerAPIConfig = providerConfig.api;
 
  if (providerAPIConfig.transformToFormData?.({ saRequestData })) {
    return transformToProviderRequestFormData(
      aiProvider,
      saRequestData.requestBody,
      saRequestData.functionName,
      saTarget,
    );
  }
 
  return transformToProviderRequestJSON(
    aiProvider,
    saRequestData.requestBody,
    saRequestData.functionName,
    saTarget,
  );
};
 
export default transformToProviderRequest;