(args: {
protocol: AIRouterProtocol;
responseFormat: 'openai' | 'anthropic';
})
| 878 | } |
| 879 | |
| 880 | function buildAIRouterModelsHandler(args: { |
| 881 | protocol: AIRouterProtocol; |
| 882 | responseFormat: 'openai' | 'anthropic'; |
| 883 | }): RequestHandler { |
| 884 | return async (req, res) => { |
| 885 | const { workspaceId, routerId } = z |
| 886 | .object({ |
| 887 | workspaceId: z.string(), |
| 888 | routerId: z.string(), |
| 889 | }) |
| 890 | .parse(req.params); |
| 891 | const requestApiKey = getAIRouterModelsRequestApiKey( |
| 892 | req, |
| 893 | args.responseFormat |
| 894 | ); |
| 895 | let verifyRequestApiKeyPromise: Promise<unknown> | undefined; |
| 896 | const verifyRequestApiKey = () => { |
| 897 | verifyRequestApiKeyPromise ??= verifyUserApiKey(requestApiKey); |
| 898 | |
| 899 | return verifyRequestApiKeyPromise; |
| 900 | }; |
| 901 | |
| 902 | try { |
| 903 | const result = await runAIRouterModelsDiscovery({ |
| 904 | workspaceId, |
| 905 | routerId, |
| 906 | protocol: args.protocol, |
| 907 | listModels: ({ node }) => |
| 908 | listAIRouterNodeModels({ |
| 909 | req, |
| 910 | node, |
| 911 | responseFormat: args.responseFormat, |
| 912 | requestApiKey, |
| 913 | verifyRequestApiKey, |
| 914 | }), |
| 915 | }); |
| 916 | |
| 917 | if (result.gatewayCount === 0) { |
| 918 | res.status(503).json({ |
| 919 | error: { |
| 920 | message: 'No eligible AI Router nodes are available', |
| 921 | type: 'router_unavailable', |
| 922 | }, |
| 923 | }); |
| 924 | return; |
| 925 | } |
| 926 | |
| 927 | if (result.models.length === 0 && result.failures.length > 0) { |
| 928 | res.status(502).json({ |
| 929 | error: { |
| 930 | message: 'AI Router failed to discover models from every gateway', |
| 931 | type: 'router_failed', |
| 932 | }, |
| 933 | }); |
| 934 | return; |
| 935 | } |
| 936 | |
| 937 | if (args.responseFormat === 'anthropic') { |
no test coverage detected