All files / api/src/ai-providers/bedrock utils.ts

0% Statements 0/333
100% Branches 1/1
100% Functions 1/1
0% Lines 0/333

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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import type {
  BedrockChatCompletionsParams,
  BedrockConverseAI21ChatCompletionsParams,
  BedrockConverseAnthropicChatCompletionsParams,
  BedrockConverseCohereChatCompletionsParams,
  BedrockFinetuneRecord,
} from '@api/ai-providers/bedrock/types';
import { Sha256 } from '@aws-crypto/sha256-js';
import type { SuperAgentsTarget } from '@shared/types/api/request/headers';
 
import type { CreateFineTuningJobRequestBody } from '@shared/types/api/routes/fine-tuning-api/request';
import { SignatureV4 } from '@smithy/signature-v4';
 
import { GatewayError } from '../../errors/gateway';
 
export const azureTransformFinetuneBody = (
  body: CreateFineTuningJobRequestBody,
): CreateFineTuningJobRequestBody => {
  const _body = { ...body } as CreateFineTuningJobRequestBody;
 
  // if (_body.method && !_body.hyperparameters) {
  //   const hyperparameters =
  //     _body.method[_body.method.type]?.hyperparameters ?? {};
  //   _body.hyperparameters = {
  //     ...hyperparameters,
  //   } as unknown as typeof _body.hyperparameters;
 
  //   delete _body.method;
  // }  // TODO: fix this
 
  return {
    ..._body,
  };
};
 
export const generateAWSHeaders = async (
  body: Record<string, unknown> | string | undefined,
  headers: Record<string, string>,
  url: string,
  method: string,
  awsService: string,
  awsRegion: string,
  awsAccessKeyID: string,
  awsSecretAccessKey: string,
  awsSessionToken: string | undefined,
): Promise<Record<string, string>> => {
  const signer = new SignatureV4({
    service: awsService,
    region: awsRegion || 'us-east-1',
    credentials: {
      accessKeyId: awsAccessKeyID,
      secretAccessKey: awsSecretAccessKey,
      ...(awsSessionToken && { sessionToken: awsSessionToken }),
    },
    sha256: Sha256,
  });
 
  const urlObj = new URL(url);
  const hostname = urlObj.hostname;
  headers.host = hostname;
  let requestBody: string | Uint8Array | Buffer | null | undefined;
  if (!body) {
    requestBody = null;
  } else if (
    body instanceof Uint8Array ||
    body instanceof Buffer ||
    typeof body === 'string'
  ) {
    requestBody = body;
  } else if (body && typeof body === 'object' && method !== 'GET') {
    requestBody = JSON.stringify(body);
  }
  const queryParams = Object.fromEntries(urlObj.searchParams.entries());
  let protocol = 'https';
  if (urlObj.protocol) {
    protocol = urlObj.protocol.replace(':', '');
  }
  const request = {
    method: method,
    path: urlObj.pathname,
    protocol: protocol,
    query: queryParams,
    hostname: urlObj.hostname,
    headers: headers,
    ...(requestBody && { body: requestBody }),
  };
 
  const signed = await signer.sign(request);
  return signed.headers;
};
 
export const transformInferenceConfig = (
  params: BedrockChatCompletionsParams,
): Record<string, unknown> => {
  const inferenceConfig: Record<string, unknown> = {};
  if (params.max_tokens || params.max_completion_tokens) {
    inferenceConfig.maxTokens =
      params.max_tokens || params.max_completion_tokens;
  }
  if (params.stop) {
    inferenceConfig.stopSequences = params.stop;
  }
  if (params.temperature) {
    inferenceConfig.temperature = params.temperature;
  }
  if (params.top_p) {
    inferenceConfig.topP = params.top_p;
  }
  return inferenceConfig;
};
 
export const transformAdditionalModelRequestFields = (
  params: BedrockChatCompletionsParams,
): Record<string, unknown> => {
  const additionalModelRequestFields: Record<string, unknown> =
    params.additionalModelRequestFields ||
    params.additional_model_request_fields ||
    {};
  // if (params.top_k) {
  //   additionalModelRequestFields.top_k = params.top_k;
  // } // TODO: fix this
  if (params.response_format) {
    additionalModelRequestFields.response_format = params.response_format;
  }
  return additionalModelRequestFields;
};
 
export const transformAnthropicAdditionalModelRequestFields = (
  params: BedrockConverseAnthropicChatCompletionsParams,
): Record<string, unknown> => {
  const additionalModelRequestFields: Record<string, unknown> =
    params.additionalModelRequestFields ||
    params.additional_model_request_fields ||
    {};
  // if (params.top_k) {
  //   additionalModelRequestFields.top_k = params.top_k;
  // } // TODO: fix this
  if (params.anthropic_version) {
    additionalModelRequestFields.anthropic_version = params.anthropic_version;
  }
  if (params.user) {
    additionalModelRequestFields.metadata = {
      user_id: params.user,
    };
  }
  if (params.thinking) {
    additionalModelRequestFields.thinking = params.thinking;
  }
  if (params.anthropic_beta) {
    if (typeof params.anthropic_beta === 'string') {
      additionalModelRequestFields.anthropic_beta = [params.anthropic_beta];
    } else {
      additionalModelRequestFields.anthropic_beta = params.anthropic_beta;
    }
  }
  return additionalModelRequestFields;
};
 
export const transformCohereAdditionalModelRequestFields = (
  params: BedrockConverseCohereChatCompletionsParams,
): Record<string, unknown> => {
  const additionalModelRequestFields: Record<string, unknown> =
    params.additionalModelRequestFields ||
    params.additional_model_request_fields ||
    {};
  // if (params.top_k) {
  //   additionalModelRequestFields.top_k = params.top_k;
  // } // TODO: fix this
  if (params.n) {
    additionalModelRequestFields.n = params.n;
  }
  if (params.frequency_penalty) {
    additionalModelRequestFields.frequency_penalty = params.frequency_penalty;
  }
  if (params.presence_penalty) {
    additionalModelRequestFields.presence_penalty = params.presence_penalty;
  }
  if (params.logit_bias) {
    additionalModelRequestFields.logitBias = params.logit_bias;
  }
  return additionalModelRequestFields;
};
 
export const transformAI21AdditionalModelRequestFields = (
  params: BedrockConverseAI21ChatCompletionsParams,
): Record<string, unknown> => {
  const additionalModelRequestFields: Record<string, unknown> =
    params.additionalModelRequestFields ||
    params.additional_model_request_fields ||
    {};
  // if (params.top_k) {
  //   additionalModelRequestFields.top_k = params.top_k;
  // } // TODO: fix this
  if (params.frequency_penalty) {
    additionalModelRequestFields.frequencyPenalty = {
      scale: params.frequency_penalty,
    };
  }
  if (params.presence_penalty) {
    additionalModelRequestFields.presencePenalty = {
      scale: params.presence_penalty,
    };
  }
  if (params.frequencyPenalty) {
    additionalModelRequestFields.frequencyPenalty = params.frequencyPenalty;
  }
  if (params.presencePenalty) {
    additionalModelRequestFields.presencePenalty = params.presencePenalty;
  }
  if (params.countPenalty) {
    additionalModelRequestFields.countPenalty = params.countPenalty;
  }
  return additionalModelRequestFields;
};
 
export async function getAssumedRoleCredentials(
  awsRoleArn: string,
  awsExternalId: string,
  awsRegion: string,
  creds: {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken?: string;
  },
): Promise<{
  accessKeyId: string;
  secretAccessKey: string;
  sessionToken?: string;
  expiration?: string;
} | null> {
  // const cacheKey = `${awsRoleArn}/${awsExternalId}/${awsRegion}`;
  // const getFromCacheByKey = c.get('getFromCacheByKey');
  // const putInCacheWithValue = c.get('putInCacheWithValue');
 
  // const resp = getFromCacheByKey
  //   ? await getFromCacheByKey(env(c), cacheKey)
  //   : null;
  // if (resp) {
  //   return resp;
  // } // TODO: fix this
 
  // Determine which credentials to use
  const accessKeyId: string = creds.accessKeyId;
  const secretAccessKey: string = creds.secretAccessKey;
  const sessionToken: string | undefined = creds.sessionToken;
 
  const region = awsRegion || 'us-east-1';
  const service = 'sts';
  const hostname = `sts.${region}.amazonaws.com`;
  const signer = new SignatureV4({
    service,
    region,
    credentials: {
      accessKeyId,
      secretAccessKey,
      sessionToken,
    },
    sha256: Sha256,
  });
  const date = new Date();
  const sessionName = `${date.getFullYear()}${date.getMonth()}${date.getDay()}`;
  const url = `https://${hostname}?Action=AssumeRole&Version=2011-06-15&RoleArn=${awsRoleArn}&RoleSessionName=${sessionName}${awsExternalId ? `&ExternalId=${awsExternalId}` : ''}`;
  const urlObj = new URL(url);
  const requestHeaders = { host: hostname };
  const options = {
    method: 'GET',
    path: urlObj.pathname,
    protocol: urlObj.protocol,
    hostname: urlObj.hostname,
    headers: requestHeaders,
    query: Object.fromEntries(urlObj.searchParams),
  };
  const { headers } = await signer.sign(options);
 
  let credentials: {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken?: string;
    expiration?: string;
  } | null = null;
  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: headers,
    });
 
    if (!response.ok) {
      const resp = await response.text();
      console.error({ message: resp });
      throw new Error(`HTTP error! status: ${response.status}`);
    }
 
    const xmlData = await response.text();
    credentials = parseXml(xmlData);
    // if (putInCacheWithValue) {
    //   await putInCacheWithValue(env(c), cacheKey, credentials, 300); //5 minutes
    // } // TODO: fix this
  } catch (error) {
    console.error({ message: `Error assuming role:, ${error}` });
  }
  return credentials;
}
 
function parseXml(xml: string): {
  accessKeyId: string;
  secretAccessKey: string;
  sessionToken?: string;
  expiration?: string;
} {
  // Simple XML parser for this specific use case
  const getTagContent = (tag: string): string | null => {
    const regex = new RegExp(`<${tag}>(.*?)</${tag}>`, 's');
    const match = xml.match(regex);
    return match ? match[1] : null;
  };
 
  const credentials = getTagContent('Credentials');
  if (!credentials) {
    throw new Error('Failed to parse Credentials from XML response');
  }
 
  return {
    accessKeyId: getTagContent('AccessKeyId') || '',
    secretAccessKey: getTagContent('SecretAccessKey') || '',
    sessionToken: getTagContent('SessionToken') || undefined,
    expiration: getTagContent('Expiration') || undefined,
  };
}
 
export const bedrockFinetuneToOpenAI = (
  finetune: BedrockFinetuneRecord,
): Record<string, unknown> => {
  let status = 'running';
  switch (finetune.status) {
    case 'Completed':
      status = 'succeeded';
      break;
    case 'Failed':
      status = 'failed';
      break;
    case 'InProgress':
      status = 'running';
      break;
    case 'Stopping':
    case 'Stopped':
      status = 'cancelled';
      break;
  }
  return {
    id: encodeURIComponent(finetune.jobArn),
    job_name: finetune.jobName,
    object: 'finetune',
    status: status,
    created_at: new Date(finetune.creationTime).getTime(),
    finished_at: new Date(finetune.endTime).getTime(),
    fine_tuned_model:
      finetune.outputModelArn ||
      finetune.outputModelName ||
      finetune.customModelArn,
    suffix: finetune.customModelName,
    training_file: encodeURIComponent(
      finetune?.trainingDataConfig?.s3Uri ?? '',
    ),
    validation_file: encodeURIComponent(
      finetune?.validationDataConfig?.s3Uri ?? '',
    ),
    hyperparameters: {
      learning_rate_multiplier: Number(finetune?.hyperParameters?.learningRate),
      batch_size: Number(finetune?.hyperParameters?.batchSize),
      n_epochs: Number(finetune?.hyperParameters?.epochCount),
    },
    error: finetune?.failureMessage ?? {},
  };
};
 
export async function providerAssumedRoleCredentials(
  saTarget: SuperAgentsTarget,
): Promise<void> {
  try {
    // Assume the role in the source account
    const sourceRoleCredentials = await getAssumedRoleCredentials(
      saTarget.aws_role_arn || '', // Role ARN in the source account
      saTarget.aws_external_id || '', // External ID for source role (if needed)
      saTarget.aws_region || '',
      {
        accessKeyId: saTarget.aws_access_key_id || '',
        secretAccessKey: saTarget.aws_secret_access_key || '',
        sessionToken: saTarget.aws_session_token || '',
      },
    );
 
    if (!sourceRoleCredentials) {
      throw new Error('Server Error while assuming internal role');
    }
 
    // Assume role in destination account using temporary creds obtained in first step
    const { accessKeyId, secretAccessKey, sessionToken } =
      (await getAssumedRoleCredentials(
        saTarget.aws_role_arn || '',
        saTarget.aws_external_id || '',
        saTarget.aws_region || '',
        {
          accessKeyId: sourceRoleCredentials.accessKeyId,
          secretAccessKey: sourceRoleCredentials.secretAccessKey,
          sessionToken: sourceRoleCredentials.sessionToken,
        },
      )) || {};
    saTarget.aws_access_key_id = accessKeyId;
    saTarget.aws_secret_access_key = secretAccessKey;
    saTarget.aws_session_token = sessionToken;
  } catch (e: unknown) {
    if (e instanceof Error) {
      throw new GatewayError(e.message);
    }
    throw new GatewayError('Error while assuming bedrock role');
  }
}
 
export const populateHyperParameters = (
  saRequestBody: CreateFineTuningJobRequestBody,
): Record<string, unknown> => {
  const hyperParameters = saRequestBody.hyperparameters ?? {};
 
  // if (saRequestBody.method) {
  //   const method = saRequestBody.method.type;
  //   hyperParameters = saRequestBody.method?.[method]?.hyperparameters ?? {};
  // }  // TODO: fix this
 
  return hyperParameters;
};