( options: OpenaiHandlerOptions )
| 600 | } |
| 601 | |
| 602 | export 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 |
no test coverage detected