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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 49x 49x 49x 49x 49x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 49x 35x 35x 35x 35x 49x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 6x 6x 7x 7x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 3x 7x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 7x 7x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x | import { providerConfigs } from '@api/ai-providers';
import { GatewayError } from '@api/errors/gateway';
import { HttpError } from '@api/errors/http';
import { RouterError } from '@api/errors/router';
import { responseHandler } from '@api/handlers/response-handler';
import { retryRequest } from '@api/handlers/retry-handler';
import { ConditionalRouter } from '@api/services/conditional-router';
import transformToProviderRequest from '@api/services/transform-to-provider-request';
import type { AppContext } from '@api/types/hono';
import { HttpMethod } from '@api/types/http';
import { getCachedResponse } from '@api/utils/cache';
import { inputHookHandler, outputHookHandler } from '@api/utils/hooks';
import {
validateAndTransformParameter,
validateParameter,
} from '@api/utils/model-validator';
import { constructRequest } from '@api/utils/super-agents/requests';
import {
type CommonRequestOptions,
type CreateResponseOptions,
createResponse,
} from '@api/utils/super-agents/responses';
import type { InternalProviderAPIConfig } from '@shared/types/ai-providers/config';
import { ModelParameter } from '@shared/types/ai-providers/model-capabilities';
import { FunctionName } from '@shared/types/api/request';
import type {
SuperAgentsRequestBody,
SuperAgentsRequestData,
} from '@shared/types/api/request/body';
import type {
SuperAgentsConfig,
SuperAgentsTarget,
} from '@shared/types/api/request/headers';
import { HeaderKey, StrategyModes } from '@shared/types/api/request/headers';
import type { ChatCompletionRequestBody } from '@shared/types/api/routes/chat-completions-api';
import type { ResponsesRequestBody } from '@shared/types/api/routes/responses-api';
import { ChatCompletionMessageRole } from '@shared/types/api/routes/shared/messages';
import { AIProvider, ContentTypeName } from '@shared/types/constants';
import { CacheStatus } from '@shared/types/middleware/cache';
import { HookType } from '@shared/types/middleware/hooks';
import { cloneDeep } from 'lodash';
function getProxyPath(
requestURL: string,
proxyProvider: AIProvider,
proxyEndpointPath: string,
baseURL: string,
saTarget: SuperAgentsTarget,
): string {
const reqURL = new URL(requestURL);
let reqPath = reqURL.pathname;
const reqQuery = reqURL.search;
reqPath = reqPath.replace(proxyEndpointPath, '');
// NOTE: temporary support for the deprecated way of making azure requests
// where the endpoint was sent in request path of the incoming gateway url
if (proxyProvider === AIProvider.AZURE_OPENAI) {
// Extract what looks like a URL from the path and validate the hostname
// The path format is typically: //hostname.openai.azure.com/rest/of/path
const azureUrlMatch = reqPath.match(
/^\/\/([\w-]+\.openai\.azure\.com)(\/.*)?$/,
);
if (azureUrlMatch) {
const hostname = azureUrlMatch[1];
const path = azureUrlMatch[2] || '';
return `https://${hostname}${path}${reqQuery}`;
}
}
const providerConfig = providerConfigs[proxyProvider];
if (providerConfig?.api?.getProxyEndpoint) {
return `${baseURL}${providerConfig.api.getProxyEndpoint({ reqPath, reqQuery, saTarget: saTarget })}`;
}
let proxyPath = `${baseURL}${reqPath}${reqQuery}`;
// Fix specific for Anthropic SDK calls. Is this needed? - Yes
if (proxyProvider === AIProvider.ANTHROPIC) {
proxyPath = proxyPath.replace('/v1/v1/', '/v1/');
}
return proxyPath;
}
function getHyperParamDefaults(
functionName: FunctionName,
saTarget: SuperAgentsTarget,
) {
// Apply configuration params as defaults (before override params)
const configDefaults: Record<string, unknown> = {
model: saTarget.configuration.model,
};
const provider = saTarget.configuration.ai_provider;
const modelId = saTarget.configuration.model;
// Helper function to validate, transform, and add parameter
const addParameter = (
parameter: ModelParameter,
value: unknown,
paramKey?: string,
) => {
if (value === null) return;
// Only transform numeric parameters (temperature, top_p, etc.)
const isNumericParameter = typeof value === 'number';
const validation = isNumericParameter
? validateAndTransformParameter(
provider,
modelId,
parameter,
value,
functionName,
true, // shouldTransform = true
)
: validateParameter(provider, modelId, parameter, functionName);
if (validation.isSupported && validation.parameterName) {
const key = paramKey || validation.parameterName;
// Use transformed value if available, otherwise use original
const finalValue = validation.transformedValue ?? value;
configDefaults[key] = finalValue;
}
};
// Validate and add each parameter
addParameter(
ModelParameter.TEMPERATURE,
saTarget.configuration.temperature,
'temperature',
);
addParameter(
ModelParameter.MAX_TOKENS,
saTarget.configuration.max_tokens,
'max_tokens',
);
addParameter(ModelParameter.TOP_P, saTarget.configuration.top_p, 'top_p');
addParameter(
ModelParameter.FREQUENCY_PENALTY,
saTarget.configuration.frequency_penalty,
'frequency_penalty',
);
addParameter(
ModelParameter.PRESENCE_PENALTY,
saTarget.configuration.presence_penalty,
'presence_penalty',
);
addParameter(ModelParameter.STOP, saTarget.configuration.stop, 'stop');
addParameter(ModelParameter.SEED, saTarget.configuration.seed, 'seed');
// Handle reasoning_effort (different structure for different function names)
if (saTarget.configuration.reasoning_effort !== null) {
const validation = validateParameter(
provider,
modelId,
ModelParameter.REASONING_EFFORT,
functionName,
);
if (validation.isSupported) {
switch (functionName) {
case FunctionName.STREAM_CHAT_COMPLETE:
case FunctionName.CHAT_COMPLETE:
configDefaults.reasoning_effort =
saTarget.configuration.reasoning_effort;
break;
case FunctionName.CREATE_MODEL_RESPONSE:
configDefaults.reasoning = {
effort: saTarget.configuration.reasoning_effort,
};
break;
default:
throw new Error(`Unsupported function name: ${functionName}`);
}
if (validation.warning) {
console.warn(
`[${provider}/${modelId}][${functionName}] reasoning_effort: ${validation.warning}`,
);
}
} else if (validation.reason) {
console.warn(
`[${provider}/${modelId}][${functionName}] ✗ Skipped reasoning_effort (value: ${JSON.stringify(saTarget.configuration.reasoning_effort)}): ${validation.reason}`,
);
}
}
return configDefaults;
}
/**
* Makes a POST request to a provider and returns the response.
* The POST request is constructed using the provider, apiKey, and requestBody parameters.
* The fn parameter is the type of request being made (e.g., "complete", "chatComplete").
*/
export async function tryPost(
c: AppContext,
saConfig: SuperAgentsConfig,
saTarget: SuperAgentsTarget,
saRequestData: SuperAgentsRequestData,
currentIndex: number,
): Promise<Response> {
try {
const hyperParamDefaults = getHyperParamDefaults(
saRequestData.functionName,
saTarget,
);
const overrideParams = saConfig?.override_params || {};
// Merge: base request body -> config defaults -> override params
const overriddenSuperAgentsRequestBody: SuperAgentsRequestBody = {
...(saRequestData.requestBody as Record<string, unknown>),
...hyperParamDefaults,
...overrideParams,
} as SuperAgentsRequestBody;
// Anthropic has no `response_format`, so the gateway emulates it with the
// `__json_output` tool (see ai-providers/anthropic/chat-complete.ts). Every
// other provider has to put the JSON in the message itself, and telling one
// to call a tool it was never given is how answers end up narrated or
// wrapped in a ```json fence.
const jsonOutputInstruction =
saTarget.configuration.ai_provider === AIProvider.ANTHROPIC
? 'Use the __json_output tool to provide your response.'
: 'Respond with the JSON object alone: no markdown code fences, no commentary, no other text.';
// Helper to generate JSON schema instructions for response_format
const getJsonSchemaInstructions = (
responseFormat: ChatCompletionRequestBody['response_format'],
): string => {
if (!responseFormat) return '';
if (responseFormat.type === 'json_schema') {
const schema =
responseFormat.json_schema?.schema ?? responseFormat.json_schema;
if (schema && typeof schema === 'object') {
return `\n\nIMPORTANT: You must output your response as a JSON object that strictly conforms to the following schema:\n\n${JSON.stringify(schema, null, 2)}\n\nEnsure every required field is present with the correct type and format. ${jsonOutputInstruction}`;
}
} else if (responseFormat.type === 'json_object') {
return `\n\nIMPORTANT: You must output your response as a valid JSON object. ${jsonOutputInstruction}`;
}
return '';
};
if (
saTarget.configuration.system_prompt &&
(saRequestData.functionName === FunctionName.CREATE_MODEL_RESPONSE ||
saRequestData.functionName === FunctionName.CHAT_COMPLETE ||
saRequestData.functionName === FunctionName.STREAM_CHAT_COMPLETE)
) {
// Handle system prompt with template variables
let systemPrompt = saTarget.configuration.system_prompt;
// Augment system prompt with JSON schema instructions if response_format is present
const responseFormat = (
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).response_format;
const jsonSchemaInstructions = getJsonSchemaInstructions(responseFormat);
// For strict JSON schema, prepend the instructions to ensure they override learned behavior
if (responseFormat?.type === 'json_schema' && jsonSchemaInstructions) {
systemPrompt = `${jsonSchemaInstructions}\n\n${systemPrompt}`;
} else {
systemPrompt += jsonSchemaInstructions;
}
// Add system prompt if not overridden by the user
switch (saRequestData.functionName) {
case FunctionName.CHAT_COMPLETE:
case FunctionName.STREAM_CHAT_COMPLETE: {
const messages = (
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).messages;
// Find existing system message or add new one at the beginning
const systemMessageIndex = messages.findIndex(
(msg) => msg.role === ChatCompletionMessageRole.SYSTEM,
);
const systemMessage = {
role: ChatCompletionMessageRole.SYSTEM,
content: systemPrompt,
};
if (systemMessageIndex >= 0) {
// Replace existing system message
messages[systemMessageIndex] = systemMessage;
} else {
// Add system message at the beginning
messages.unshift(systemMessage);
}
(
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).messages = messages;
break;
}
case FunctionName.CREATE_MODEL_RESPONSE: {
const inputPreview = (
overriddenSuperAgentsRequestBody as ResponsesRequestBody
).input;
let input: Record<string, unknown>[] = [];
// If inputPreview is not an array, convert it to an array so that we can add the system prompt
if (!Array.isArray(inputPreview)) {
input = [
{
role: ChatCompletionMessageRole.USER,
content: inputPreview,
},
];
} else {
input = inputPreview;
}
// Find existing system message or add new one at the beginning
const systemMessageIndex = input.findIndex(
(msg) => msg.role === ChatCompletionMessageRole.SYSTEM,
);
const systemMessage = {
role: ChatCompletionMessageRole.SYSTEM,
content: systemPrompt,
};
if (systemMessageIndex >= 0) {
// Replace existing system message
input[systemMessageIndex] = systemMessage;
} else {
// Add system message at the beginning
input.unshift(systemMessage);
}
(overriddenSuperAgentsRequestBody as Record<string, unknown>).input =
input;
}
}
} else if (
!saTarget.configuration.system_prompt &&
(saRequestData.functionName === FunctionName.CHAT_COMPLETE ||
saRequestData.functionName === FunctionName.STREAM_CHAT_COMPLETE)
) {
// If there's no system prompt from the optimization arm,
// we still need to augment any existing system message in the user's request
// with JSON schema instructions if response_format is present
const responseFormat = (
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).response_format;
const jsonInstructions = getJsonSchemaInstructions(responseFormat);
if (jsonInstructions) {
const messages = (
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).messages;
// Find existing system message
const systemMessageIndex = messages.findIndex(
(msg) => msg.role === ChatCompletionMessageRole.SYSTEM,
);
if (systemMessageIndex >= 0) {
// Augment existing system message
const existingContent = messages[systemMessageIndex].content || '';
messages[systemMessageIndex].content =
existingContent + jsonInstructions;
} else {
// Create new system message with just the JSON instructions
messages.unshift({
role: ChatCompletionMessageRole.SYSTEM,
content: jsonInstructions.trim(),
});
}
(
overriddenSuperAgentsRequestBody as ChatCompletionRequestBody
).messages = messages;
}
}
let isStreamingMode = false;
if ('stream' in overriddenSuperAgentsRequestBody) {
isStreamingMode = overriddenSuperAgentsRequestBody.stream
? (overriddenSuperAgentsRequestBody.stream as boolean)
: false;
}
const overriddenSuperAgentsRequestData = cloneDeep(saRequestData);
overriddenSuperAgentsRequestData.requestBody =
overriddenSuperAgentsRequestBody;
let strictOpenAiCompliance = true;
if (saConfig.strict_open_ai_compliance === false) {
strictOpenAiCompliance = false;
}
// Mapping providers to corresponding URLs
const internalProviderConfig =
providerConfigs[saTarget.configuration.ai_provider];
if (!internalProviderConfig) {
throw new Error(
`Provider config not found for provider: ${saTarget.configuration.ai_provider}`,
);
}
const apiConfig: InternalProviderAPIConfig = internalProviderConfig.api;
const customHost = saTarget.custom_host || '';
const baseUrl =
customHost ||
(await apiConfig.getBaseURL({
c,
saTarget,
saRequestData: overriddenSuperAgentsRequestData,
}));
const endpoint = apiConfig.getEndpoint({
c,
saTarget,
saRequestData: overriddenSuperAgentsRequestData,
});
const url =
overriddenSuperAgentsRequestData.functionName === FunctionName.PROXY
? getProxyPath(
overriddenSuperAgentsRequestData.url,
saTarget.configuration.ai_provider,
overriddenSuperAgentsRequestData.url.indexOf('/v1/proxy') > -1
? '/v1/proxy'
: '/v1',
baseUrl,
saTarget,
)
: `${baseUrl}${endpoint}`;
let fetchConfig: RequestInit = {};
const outputSyncHooks = saConfig.hooks?.filter(
(hook) => hook.type === HookType.OUTPUT_HOOK && hook.await === true,
);
c.set('sa_request_data', overriddenSuperAgentsRequestData);
const commonRequestOptions: CommonRequestOptions = {
saRequestData: overriddenSuperAgentsRequestData,
aiProviderRequestURL: url,
isStreamingMode,
provider: saTarget.configuration.ai_provider,
strictOpenAiCompliance,
areSyncHooksAvailable: outputSyncHooks?.length > 0,
currentIndex,
fetchOptions: fetchConfig,
cacheSettings: saTarget.cache,
};
const {
errorResponse: inputHooksErrorResponse,
transformedSuperAgentsBody,
} = await inputHookHandler(c, overriddenSuperAgentsRequestData);
if (inputHooksErrorResponse) {
const createResponseOptions: CreateResponseOptions = {
response: inputHooksErrorResponse,
responseTransformerFunctionName: undefined,
cacheStatus: CacheStatus.MISS,
retryCount: undefined,
aiProviderRequestBody: {},
...commonRequestOptions,
};
return createResponse(c, createResponseOptions);
}
if (transformedSuperAgentsBody) {
overriddenSuperAgentsRequestData.requestBody = transformedSuperAgentsBody;
}
let aiProviderRequestBody:
| Record<string, unknown>
| ReadableStream
| ArrayBuffer
| FormData = overriddenSuperAgentsRequestBody as
| Record<string, unknown>
| ReadableStream
| ArrayBuffer
| FormData;
// Attach the body of the request
if (
!internalProviderConfig?.requestHandlers?.[
overriddenSuperAgentsRequestData.functionName
]
) {
aiProviderRequestBody =
overriddenSuperAgentsRequestData.method === HttpMethod.POST
? transformToProviderRequest(
saTarget.configuration.ai_provider,
saTarget,
overriddenSuperAgentsRequestData,
)
: overriddenSuperAgentsRequestBody;
}
const apiConfigHeaders = await apiConfig.headers({
c,
saTarget,
saRequestData: overriddenSuperAgentsRequestData,
});
// Construct the base object for the POST request
fetchConfig = constructRequest(
overriddenSuperAgentsRequestData,
apiConfigHeaders as Record<string, string>,
{},
{},
);
let apiConfigContentTypeHeader = apiConfigHeaders[HeaderKey.CONTENT_TYPE] as
| string
| undefined;
if (!apiConfigContentTypeHeader) {
apiConfigContentTypeHeader =
overriddenSuperAgentsRequestData.requestHeaders[
HeaderKey.CONTENT_TYPE
]?.split(';')[0];
if (!apiConfigContentTypeHeader) {
console.warn(
'No Content-Type header found in request. Using application/json as default.',
);
apiConfigContentTypeHeader = 'application/json';
}
}
const requestContentType =
overriddenSuperAgentsRequestData.requestHeaders[
HeaderKey.CONTENT_TYPE
]?.split(';')[0];
if (
apiConfigContentTypeHeader === ContentTypeName.MULTIPART_FORM_DATA ||
(overriddenSuperAgentsRequestData.functionName === 'proxy' &&
requestContentType === ContentTypeName.MULTIPART_FORM_DATA)
) {
fetchConfig.body = aiProviderRequestBody as FormData;
} else if (aiProviderRequestBody instanceof ReadableStream) {
fetchConfig.body = aiProviderRequestBody;
} else if (
overriddenSuperAgentsRequestData.functionName === 'proxy' &&
requestContentType?.startsWith(ContentTypeName.GENERIC_AUDIO_PATTERN)
) {
fetchConfig.body = aiProviderRequestBody as ArrayBuffer;
} else if (requestContentType) {
fetchConfig.body = JSON.stringify(aiProviderRequestBody);
}
if (['GET', 'DELETE'].includes(overriddenSuperAgentsRequestData.method)) {
delete fetchConfig.body;
}
// Return cached response if it exists
const cachedResponse = await getCachedResponse(
c,
commonRequestOptions,
aiProviderRequestBody,
);
if (cachedResponse) {
return cachedResponse;
}
// Request handler (Including retries, recursion and hooks)
const handlerResult = await recursiveOutputHookHandler(
c,
commonRequestOptions,
url,
fetchConfig,
saTarget,
isStreamingMode,
overriddenSuperAgentsRequestData,
0,
strictOpenAiCompliance,
);
const createResponseOptions: CreateResponseOptions = {
response: handlerResult.mappedResponse,
responseTransformerFunctionName: undefined,
cacheStatus: CacheStatus.MISS,
retryCount: undefined,
aiProviderRequestBody,
responseAlreadyHandled: true, // Stream already processed by responseHandler
...commonRequestOptions,
};
return createResponse(c, createResponseOptions);
} catch (error) {
if (error instanceof HttpError) {
return new Response(error.response.body, {
status: error.response.status,
statusText: error.response.statusText,
});
}
return new Response(
JSON.stringify({
error: `${error}`,
}),
{
status: 500,
headers: {
'Content-Type': 'application/json',
},
},
);
}
}
export async function tryTarget(
c: AppContext,
saConfig: SuperAgentsConfig,
saTarget: SuperAgentsTarget,
saRequestData: SuperAgentsRequestData,
): Promise<Response> {
return await tryPost(c, saConfig, saTarget, saRequestData, 0);
}
export async function tryTargets(
c: AppContext,
saConfig: SuperAgentsConfig,
saRequestData: SuperAgentsRequestData,
): Promise<Response> {
const strategyMode = saConfig.strategy.mode;
let response: Response | undefined;
switch (strategyMode) {
case StrategyModes.FALLBACK:
for (const target of saConfig.targets) {
response = await tryTarget(c, saConfig, target, saRequestData);
if (
response?.ok &&
!saConfig.strategy.on_status_codes?.includes(response?.status)
) {
break;
}
}
break;
case StrategyModes.LOADBALANCE: {
saConfig.targets.forEach((t: SuperAgentsTarget) => {
if (t.weight === undefined) {
t.weight = 1;
}
});
const totalWeight = saConfig.targets.reduce(
(sum: number, saTarget: SuperAgentsTarget) => sum + saTarget.weight!,
0,
);
let randomWeight = Math.random() * totalWeight;
for (const saTarget of saConfig.targets) {
if (randomWeight < saTarget.weight) {
response = await tryTarget(c, saConfig, saTarget, saRequestData);
break;
}
randomWeight -= saTarget.weight;
}
break;
}
case StrategyModes.CONDITIONAL: {
const metadata = saConfig.metadata;
const params =
saRequestData.requestBody instanceof FormData ||
saRequestData.requestBody instanceof ReadableStream ||
saRequestData.requestBody instanceof ArrayBuffer
? {} // Send empty object if not JSON
: saRequestData.requestBody;
let conditionalRouter: ConditionalRouter;
let finalTarget: SuperAgentsTarget;
try {
conditionalRouter = new ConditionalRouter(saConfig, {
metadata,
params,
});
finalTarget = conditionalRouter.resolveTarget();
} catch (e: unknown) {
if (e instanceof Error) {
throw new RouterError(e.message);
}
throw new RouterError('Unknown error');
}
response = await tryTarget(c, saConfig, finalTarget, saRequestData);
break;
}
case StrategyModes.SINGLE:
response = await tryTarget(
c,
saConfig,
saConfig.targets[0],
saRequestData,
);
break;
default:
try {
response = await tryPost(
c,
saConfig,
saConfig.targets[0],
saRequestData,
0,
);
} catch (e) {
// tryPost always returns a Response.
// TypeError will check for all unhandled exceptions.
// GatewayError will check for all handled exceptions which cannot allow the request to proceed.
if (e instanceof TypeError || e instanceof GatewayError) {
const errorMessage =
e instanceof GatewayError ? e.message : 'Something went wrong';
response = new Response(
JSON.stringify({
status: 'failure',
message: errorMessage,
}),
{
status: 500,
headers: {
'content-type': 'application/json',
// Add this header so that the fallback loop can be interrupted if its an exception.
'sa-gateway-exception': 'true',
},
},
);
} else {
if (e instanceof HttpError) {
response = new Response(e.response.body, {
status: e.response.status,
statusText: e.response.statusText,
});
}
}
}
break;
}
if (!response) {
throw new GatewayError('No response from target');
}
return response;
}
export async function recursiveOutputHookHandler(
c: AppContext,
commonRequestOptions: CommonRequestOptions,
aiProviderRequestURL: string,
options: RequestInit,
saTarget: SuperAgentsTarget,
isStreamingMode: boolean,
saRequestData: SuperAgentsRequestData,
retryAttemptsMade: number,
strictOpenAiCompliance: boolean,
): Promise<{
mappedResponse: Response;
retryCount: number;
createdAt: Date;
originalResponseJson?: Record<string, unknown> | null;
}> {
let response: Response,
retryCount: number | undefined,
createdAt: Date,
retrySkipped: boolean;
const requestTimeout = saTarget.request_timeout || null;
const { retry } = saTarget;
const providerConfig = providerConfigs[saTarget.configuration.ai_provider];
if (!providerConfig) {
throw new Error(`Provider ${saTarget.configuration.ai_provider} not found`);
}
const requestHandlers = providerConfig.requestHandlers;
let requestHandler: (() => Promise<Response>) | undefined;
const fn = saRequestData.functionName;
if (requestHandlers?.[fn]) {
const requestHandlerFunction = requestHandlers[fn];
requestHandler = async (): Promise<Response> =>
requestHandlerFunction({
c,
saTarget,
saRequestData,
});
}
({
response,
attempt: retryCount,
createdAt,
skip: retrySkipped,
} = await retryRequest(
aiProviderRequestURL,
options,
retry?.attempts || 0,
retry?.on_status_codes || [],
requestTimeout || null,
requestHandler,
retry?.use_retry_after_header || false,
));
// Create callbacks for streaming responses
const onFirstChunk = isStreamingMode
? () => {
c.set('first_token_time', Date.now());
}
: undefined;
// Create a promise that resolves when the stream ends
let streamEndResolver: ((accumulatedChunks: string) => void) | undefined;
if (isStreamingMode) {
const streamEndPromise = new Promise<void>((resolve) => {
streamEndResolver = (accumulatedChunks: string) => {
c.set('stream_end_time', Date.now());
c.set('accumulated_stream_chunks', accumulatedChunks);
resolve();
};
});
c.set('stream_end_promise', streamEndPromise);
}
const {
response: mappedResponse,
saResponseBody,
originalResponseJson,
} = await responseHandler(
response,
isStreamingMode,
saTarget.configuration.ai_provider,
saRequestData.functionName,
aiProviderRequestURL,
CacheStatus.MISS,
saRequestData,
strictOpenAiCompliance,
commonRequestOptions.areSyncHooksAvailable,
onFirstChunk,
streamEndResolver,
);
if (!mappedResponse.ok) {
const errorBody = await mappedResponse.text();
throw new HttpError(errorBody, {
status: mappedResponse.status,
statusText: mappedResponse.statusText,
body: errorBody,
});
}
if (!saResponseBody && !isStreamingMode) {
throw new GatewayError('No response body from target');
}
// For streaming responses, skip output hooks and return the streaming response directly
if (isStreamingMode) {
return {
mappedResponse,
retryCount: retryCount || 0,
createdAt,
originalResponseJson,
};
}
const outputHookResponse = await outputHookHandler(
c,
saRequestData,
mappedResponse,
saResponseBody!, // Non-null assertion: we've already checked and returned early for streaming
retryAttemptsMade,
);
const remainingRetryCount =
(retry?.attempts || 0) - (retryCount || 0) - retryAttemptsMade;
const isRetriableStatusCode = retry?.on_status_codes?.includes(
outputHookResponse.status,
);
if (remainingRetryCount > 0 && !retrySkipped && isRetriableStatusCode) {
return recursiveOutputHookHandler(
c,
commonRequestOptions,
aiProviderRequestURL,
options,
saTarget,
isStreamingMode,
saRequestData,
(retryCount || 0) + 1 + retryAttemptsMade,
strictOpenAiCompliance,
);
}
let lastAttempt = (retryCount || 0) + retryAttemptsMade;
if (
(lastAttempt === (retry?.attempts || 0) && isRetriableStatusCode) ||
retrySkipped
) {
lastAttempt = -1; // All retry attempts exhausted without success.
}
return {
mappedResponse: outputHookResponse,
retryCount: lastAttempt,
createdAt,
originalResponseJson,
};
}
|