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

Function buildAIRouterRuntimeHandler

src/server/model/aiRouter.ts:1130–1302  ·  view source on GitHub ↗
(args: {
  protocol: AIRouterProtocol;
  schema: z.ZodType<Record<string, unknown>>;
  runAttempts?: AIRouterRuntimeAttemptRunner;
})

Source from the content-addressed store, hash-verified

1128}
1129
1130function buildAIRouterRuntimeHandler(args: {
1131 protocol: AIRouterProtocol;
1132 schema: z.ZodType<Record<string, unknown>>;
1133 runAttempts?: AIRouterRuntimeAttemptRunner;
1134}): RequestHandler {
1135 return async (req, res) => {
1136 const start = Date.now();
1137 const { workspaceId, routerId } = z
1138 .object({
1139 workspaceId: z.string(),
1140 routerId: z.string(),
1141 })
1142 .parse(req.params);
1143
1144 try {
1145 const requestPayload = args.schema.parse(req.body);
1146 const stream = requestPayload.stream === true;
1147 let stopKeepAlive: (() => void) | undefined;
1148
1149 if (stream) {
1150 setAIGatewayStreamHeaders(res);
1151 stopKeepAlive = startAIGatewayStreamKeepAlive(res, {
1152 writeInitial: true,
1153 });
1154 }
1155
1156 try {
1157 const runAttempts = args.runAttempts ?? runAIRouterAttempts;
1158 const outcome = await runAttempts({
1159 workspaceId,
1160 routerId,
1161 protocol: args.protocol,
1162 requestPayload,
1163 executeAttempt: ({ node, payload }) => {
1164 const gatewayHandler = buildAIRouterGatewayHandlerForNode({
1165 protocol: args.protocol,
1166 node,
1167 });
1168
1169 if (!gatewayHandler) {
1170 const modelProvider = getAIRouterNodeProvider(node);
1171
1172 return Promise.resolve({
1173 ok: false,
1174 committed: false,
1175 gatewayId: node.gatewayId,
1176 statusCode: 400,
1177 failure: {
1178 message: `AI Router provider ${modelProvider ?? 'unknown'} cannot serve protocol ${args.protocol}`,
1179 errorType: 'unknown',
1180 },
1181 });
1182 }
1183
1184 return executeBufferedAIGatewayAttempt({
1185 req,
1186 protocol: args.protocol,
1187 node,

Tested by

no test coverage detected