MCPcopy
hub / github.com/msgbyte/tianji / buildOpenAIHandler

Function buildOpenAIHandler

src/server/model/aiGateway.ts:602–925  ·  view source on GitHub ↗
(
  options: OpenaiHandlerOptions
)

Source from the content-addressed store, hash-verified

600}
601
602export function buildOpenAIHandler(
603 options: OpenaiHandlerOptions
604): RequestHandler {
605 return async (req, res) => {
606 const payload = openaiRequestSchema.parse(req.body);
607 const { messages, stream } = payload;
608 const { workspaceId, gatewayId } = z
609 .object({
610 workspaceId: z.string(),
611 gatewayId: z.string(),
612 })
613 .parse(req.params);
614 const apiKey = (req.headers.authorization ?? '').replace('Bearer ', '');
615 const { gatewayInfo, modelApiKey, userId } =
616 await resolveAIGatewayModelApiKey({
617 workspaceId,
618 gatewayId,
619 requestApiKey: apiKey,
620 });
621
622 // Use custom settings from gateway if available
623 const baseUrl =
624 options.isCustomRoute && gatewayInfo?.customModelBaseUrl
625 ? gatewayInfo?.customModelBaseUrl
626 : options.baseUrl;
627 const modelName =
628 options.isCustomRoute && gatewayInfo?.customModelName
629 ? gatewayInfo?.customModelName
630 : payload.model;
631
632 const start = Date.now();
633 const modelProvider =
634 options.modelProvider ?? (options.isCustomRoute ? 'custom' : 'openai');
635
636 const logP = trackAIGatewayPendingLog(
637 req,
638 createAIGatewayPendingLog({
639 workspaceId,
640 gatewayId,
641 modelName,
642 modelProvider,
643 stream,
644 requestPayload: payload,
645 userId,
646 })
647 );
648
649 try {
650 const openai = new OpenAI({
651 apiKey: modelApiKey,
652 baseURL: baseUrl,
653 defaultHeaders: options.header?.(req),
654 });
655 const modelPriceName = options.modelPriceName
656 ? options.modelPriceName(modelName)
657 : modelName;
658
659 // Record request count with model provider label

Callers 2

aiGateway.tsFile · 0.85

Calls 15

trackAIGatewayPendingLogFunction · 0.85
getFunction · 0.85
getAIGatewayUsageFunction · 0.85
calcMessagesTokenFunction · 0.85
calcOpenAITokenFunction · 0.85
getOpenRouterCostDecimalFunction · 0.85
getLLMCostDecimalV2Function · 0.85

Tested by

no test coverage detected