Spaces:
Paused

File size: 8,044 Bytes
35743bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { POST as postChatCompletion } from "@/app/api/v1/chat/completions/route";
import { handleValidatedEmbeddingRequestBody } from "@/app/api/v1/embeddings/route";
import { POST as postRerank } from "@/app/api/v1/rerank/route";
import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { getCustomModels } from "@/lib/localDb";
import { z } from "zod";

const testModelSchema = z.object({
  providerId: z.string().min(1),
  modelId: z.string().min(1),
});

const MODEL_TEST_TIMEOUT_MS = 20_000;
const INTERNAL_ORIGIN = "http://omniroute.internal";

function asRecord(value: unknown): Record<string, unknown> {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {};
}

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) return error.message;
  return typeof error === "string" ? error : "Unknown error";
}

function getErrorName(error: unknown): string {
  return error instanceof Error ? error.name : "";
}

function extractProviderErrorMessage(body: unknown, fallback: string) {
  const record = asRecord(body);
  const error = record.error;
  if (typeof error === "string" && error.trim()) return error;

  const errorRecord = asRecord(error);
  const message = errorRecord.message;
  return typeof message === "string" && message.trim() ? message : fallback;
}

async function runWithTimeout<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
  const controller = new AbortController();
  const timeoutPromise = new Promise<never>((_, reject) => {
    const timeoutError = new Error("Timeout (20s)");
    timeoutError.name = "AbortError";
    const timeout = setTimeout(() => {
      controller.abort();
      reject(timeoutError);
    }, MODEL_TEST_TIMEOUT_MS);
    controller.signal.addEventListener("abort", () => clearTimeout(timeout), { once: true });
  });

  try {
    return await Promise.race([operation(controller.signal), timeoutPromise]);
  } finally {
    controller.abort();
  }
}

function buildInternalChatRequest(testBody: Record<string, unknown>, signal: AbortSignal) {
  return new Request(`${INTERNAL_ORIGIN}/v1/chat/completions`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      // Reuse the existing strict-mode internal bypass for live health checks.
      "X-Internal-Test": "combo-health-check",
      "X-OmniRoute-No-Cache": "true",
      "X-Request-Id": `model-test-${randomUUID()}`,
    },
    body: JSON.stringify(testBody),
    signal,
  });
}

function buildInternalRerankRequest(testBody: Record<string, unknown>, signal: AbortSignal) {
  return new Request(`${INTERNAL_ORIGIN}/v1/rerank`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Internal-Test": "combo-health-check",
      "X-OmniRoute-No-Cache": "true",
      "X-Request-Id": `model-test-${randomUUID()}`,
    },
    body: JSON.stringify(testBody),
    signal,
  });
}

function stripFirstSegment(modelId: string): string | null {
  const slashIdx = modelId.indexOf("/");
  return slashIdx > 0 ? modelId.slice(slashIdx + 1) : null;
}

async function findCustomModelMetadata(providerId: string, modelId: string) {
  try {
    const customModels = await getCustomModels(providerId);
    if (!Array.isArray(customModels)) return null;

    const candidates = new Set([modelId]);
    const stripped = stripFirstSegment(modelId);
    if (stripped) candidates.add(stripped);
    if (modelId.startsWith(`${providerId}/`)) candidates.add(modelId.slice(providerId.length + 1));

    return (
      customModels.find(
        (model: any) => typeof model?.id === "string" && candidates.has(model.id)
      ) || null
    );
  } catch {
    return null;
  }
}

export async function POST(request: Request) {
  const authError = await requireManagementAuth(request);
  if (authError) return authError;

  let rawBody;
  try {
    rawBody = await request.json();
  } catch {
    return NextResponse.json(
      {
        error: {
          message: "Invalid request",
          details: [{ field: "body", message: "Invalid JSON body" }],
        },
      },
      { status: 400 }
    );
  }

  try {
    const validation = testModelSchema.safeParse(rawBody);
    if (!validation.success) {
      return NextResponse.json({ error: validation.error.format() }, { status: 400 });
    }
    const { providerId, modelId } = validation.data;

    // Construct target format (providerId/modelId)
    // Some models (like free alias models) might not need the prefix if it's an alias.
    // However, the wildcard router expects provider/model.
    let fullModelStr = modelId;
    if (!fullModelStr.includes("/")) {
      fullModelStr = `${providerId}/${modelId}`;
    }

    const startTime = Date.now();
    const customModel = await findCustomModelMetadata(providerId, fullModelStr);
    const supportedEndpoints = Array.isArray(customModel?.supportedEndpoints)
      ? customModel.supportedEndpoints
      : [];
    const apiFormat = typeof customModel?.apiFormat === "string" ? customModel.apiFormat : "";
    const lowerModel = fullModelStr.toLowerCase();
    const isRerank =
      apiFormat === "rerank" ||
      supportedEndpoints.includes("rerank") ||
      lowerModel.includes("rerank");
    const isEmbedding =
      !isRerank &&
      (apiFormat === "embeddings" ||
        supportedEndpoints.includes("embeddings") ||
        lowerModel.includes("embedding") ||
        lowerModel.includes("bge-") ||
        lowerModel.includes("text-embed") ||
        lowerModel.includes("jina-clip") ||
        lowerModel.includes("colbert"));

    const testBody = isRerank
      ? {
          model: fullModelStr,
          query: "What is OmniRoute?",
          documents: [
            "OmniRoute routes AI requests across configured providers.",
            "This document is unrelated to the test query.",
          ],
          top_n: 1,
          return_documents: false,
        }
      : buildComboTestRequestBody(fullModelStr, isEmbedding);

    const res = await runWithTimeout((signal) =>
      isEmbedding
        ? handleValidatedEmbeddingRequestBody(
            testBody as Record<string, unknown> & { model: string }
          )
        : isRerank
          ? postRerank(buildInternalRerankRequest(testBody, signal))
          : postChatCompletion(buildInternalChatRequest(testBody, signal))
    );

    const latencyMs = Date.now() - startTime;

    if (res.ok) {
      let responseBody = null;
      try {
        responseBody = await res.json();
      } catch {
        responseBody = null;
      }

      const responseText = extractComboTestResponseText(responseBody);
      if (isRerank) {
        return NextResponse.json({
          status: "ok",
          latencyMs,
          responseText: "[Rerank completed successfully]",
        });
      }
      if (!responseText && !isEmbedding) {
        return NextResponse.json(
          {
            status: "error",
            statusCode: res.status,
            error: "Provider returned HTTP 200 but no text content.",
            latencyMs,
          },
          { status: 400 }
        );
      }

      return NextResponse.json({ status: "ok", latencyMs, responseText });
    }

    let errorMsg = "";
    try {
      const errBody = await res.json();
      errorMsg = extractProviderErrorMessage(errBody, res.statusText);
    } catch {
      errorMsg = res.statusText;
    }

    return NextResponse.json(
      {
        status: "error",
        statusCode: res.status,
        error: errorMsg,
        latencyMs,
      },
      { status: res.status }
    );
  } catch (error: unknown) {
    return NextResponse.json(
      {
        status: "error",
        error: getErrorName(error) === "AbortError" ? "Timeout (20s)" : getErrorMessage(error),
      },
      { status: 500 }
    );
  }
}