feat: add retry wave visibility controls
This commit is contained in:
+2
-1
@@ -11,7 +11,8 @@
|
||||
"request_body_limit_bytes": 1073741824,
|
||||
"request_history_limit": 200,
|
||||
"endpoints": ["/responses", "/chat/completions", "/v1/responses", "/v1/chat/completions"],
|
||||
"reasoning_equals": [516],
|
||||
"reasoning_match_mode": "formula_518n_minus_2",
|
||||
"reasoning_equals": [516, 1034, 1552],
|
||||
"retryable_status_codes": [429, 503],
|
||||
"retryable_error_messages": [
|
||||
"Selected model is at capacity. Please try a different model.",
|
||||
|
||||
+1052
-206
File diff suppressed because it is too large
Load Diff
+20
-9
@@ -9,10 +9,12 @@ import path from "node:path";
|
||||
export const DEFAULT_STATE_ROOT = path.join(os.homedir(), ".codex-retry-gateway");
|
||||
const DEFAULT_REQUEST_BODY_LIMIT_BYTES = 1024 * 1024 * 1024;
|
||||
const LEGACY_DEFAULT_REQUEST_BODY_LIMIT_BYTES = 10 * 1024 * 1024;
|
||||
export const DEFAULT_CODEX_CONFIG_PATH = path.join(os.homedir(), ".codex", "config.toml");
|
||||
export const DEFAULT_LISTEN_HOST = "127.0.0.1";
|
||||
export const DEFAULT_LISTEN_PORT = 4610;
|
||||
export const DEFAULT_HEALTH_PATH = "/__codex_retry_gateway/health";
|
||||
export const DEFAULT_CODEX_CONFIG_PATH = path.join(os.homedir(), ".codex", "config.toml");
|
||||
export const DEFAULT_LISTEN_HOST = "127.0.0.1";
|
||||
export const DEFAULT_LISTEN_PORT = 4610;
|
||||
export const DEFAULT_HEALTH_PATH = "/__codex_retry_gateway/health";
|
||||
export const DEFAULT_REASONING_MATCH_MODE = "formula_518n_minus_2";
|
||||
export const DEFAULT_REASONING_EQUALS = [516, 1034, 1552];
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return `${value}`.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
@@ -167,10 +169,10 @@ export async function setCodexProviderBaseUrl({ codexConfigPath, providerName, n
|
||||
await writeUtf8File(codexConfigPath, updatedContent);
|
||||
}
|
||||
|
||||
export function normalizeIntArray(values, fallback = [516]) {
|
||||
const source = values === undefined || values === null ? fallback : values;
|
||||
const queue = Array.isArray(source) ? source.flat(Infinity) : [source];
|
||||
const normalized = queue
|
||||
export function normalizeIntArray(values, fallback = DEFAULT_REASONING_EQUALS) {
|
||||
const source = values === undefined || values === null ? fallback : values;
|
||||
const queue = Array.isArray(source) ? source.flat(Infinity) : [source];
|
||||
const normalized = queue
|
||||
.map((value) => (typeof value === "string" ? value.split(/[\s,]+/).filter(Boolean) : [value]))
|
||||
.flat()
|
||||
.map((value) => Number.parseInt(`${value}`, 10))
|
||||
@@ -190,6 +192,14 @@ export function normalizeStringArray(values, fallback = []) {
|
||||
return normalized.length > 0 ? [...new Set(normalized)] : [...fallback];
|
||||
}
|
||||
|
||||
export function normalizeReasoningMatchMode(value) {
|
||||
const mode = `${value || DEFAULT_REASONING_MATCH_MODE}`.trim().toLowerCase();
|
||||
if (["formula_518n_minus_2", "manual"].includes(mode)) {
|
||||
return mode;
|
||||
}
|
||||
return DEFAULT_REASONING_MATCH_MODE;
|
||||
}
|
||||
|
||||
export function normalizePhraseArray(values, fallback = []) {
|
||||
const source = values === undefined || values === null ? fallback : values;
|
||||
const queue = Array.isArray(source) ? source.flat(Infinity) : [source];
|
||||
@@ -430,7 +440,8 @@ export async function installForCurrentProvider({
|
||||
: Number.parseInt(`${existingGatewayConfig.request_body_limit_bytes}`, 10)
|
||||
),
|
||||
endpoints: mergedEndpoints,
|
||||
reasoning_equals: normalizeIntArray(existingGatewayConfig?.reasoning_equals, [516]),
|
||||
reasoning_match_mode: normalizeReasoningMatchMode(existingGatewayConfig?.reasoning_match_mode),
|
||||
reasoning_equals: normalizeIntArray(existingGatewayConfig?.reasoning_equals, DEFAULT_REASONING_EQUALS),
|
||||
retryable_status_codes: normalizeIntArray(existingGatewayConfig?.retryable_status_codes, [429, 503]),
|
||||
retryable_error_messages: normalizePhraseArray(existingGatewayConfig?.retryable_error_messages, [
|
||||
"Selected model is at capacity. Please try a different model.",
|
||||
|
||||
+1
-1
@@ -221,7 +221,7 @@ function Wait-GatewayHealth {
|
||||
function Normalize-IntArray {
|
||||
param(
|
||||
$Values,
|
||||
[int[]]$Default = @(516)
|
||||
[int[]]$Default = @(516, 1034, 1552)
|
||||
)
|
||||
|
||||
if ($null -eq $Values) {
|
||||
|
||||
@@ -62,8 +62,13 @@ $gatewayConfig = [ordered]@{
|
||||
if ([int]$existingGatewayConfig.request_body_limit_bytes -eq 10485760) { 1073741824 } else { [int]$existingGatewayConfig.request_body_limit_bytes }
|
||||
} else { 1073741824 }
|
||||
endpoints = @($mergedEndpoints)
|
||||
reasoning_equals = Normalize-IntArray -Values $(if ($existingGatewayConfig) { $existingGatewayConfig.reasoning_equals } else { $null }) -Default @(516)
|
||||
non_stream_status_code = if ($existingGatewayConfig -and $null -ne $existingGatewayConfig.non_stream_status_code) { [int]$existingGatewayConfig.non_stream_status_code } else { 502 }
|
||||
reasoning_match_mode = if (
|
||||
$existingGatewayConfig -and
|
||||
$existingGatewayConfig.reasoning_match_mode -and
|
||||
@("formula_518n_minus_2", "manual") -contains ([string]$existingGatewayConfig.reasoning_match_mode)
|
||||
) { [string]$existingGatewayConfig.reasoning_match_mode } else { "formula_518n_minus_2" }
|
||||
reasoning_equals = Normalize-IntArray -Values $(if ($existingGatewayConfig) { $existingGatewayConfig.reasoning_equals } else { $null }) -Default @(516, 1034, 1552)
|
||||
non_stream_status_code = if ($existingGatewayConfig -and $null -ne $existingGatewayConfig.non_stream_status_code) { [int]$existingGatewayConfig.non_stream_status_code } else { 502 }
|
||||
stream_action = if ($existingGatewayConfig -and -not [string]::IsNullOrWhiteSpace([string]$existingGatewayConfig.stream_action)) { [string]$existingGatewayConfig.stream_action } else { "strict_502" }
|
||||
log_match = if ($existingGatewayConfig -and $null -ne $existingGatewayConfig.log_match) { [bool]$existingGatewayConfig.log_match } else { $true }
|
||||
health_path = if ($existingGatewayConfig -and -not [string]::IsNullOrWhiteSpace([string]$existingGatewayConfig.health_path)) { [string]$existingGatewayConfig.health_path } else { "/__codex_retry_gateway/health" }
|
||||
|
||||
+10
-1
@@ -11,6 +11,8 @@ import {
|
||||
DEFAULT_HEALTH_PATH,
|
||||
DEFAULT_LISTEN_HOST,
|
||||
DEFAULT_LISTEN_PORT,
|
||||
DEFAULT_REASONING_EQUALS,
|
||||
DEFAULT_REASONING_MATCH_MODE,
|
||||
DEFAULT_STATE_ROOT,
|
||||
ensureDirectory,
|
||||
getCodexProviderContext,
|
||||
@@ -18,6 +20,7 @@ import {
|
||||
getGatewayStatePaths,
|
||||
normalizeIntArray,
|
||||
normalizePhraseArray,
|
||||
normalizeReasoningMatchMode,
|
||||
normalizeStringArray,
|
||||
parseOptions,
|
||||
readJsonFile,
|
||||
@@ -183,6 +186,11 @@ function buildProfileConfig({ profileName, profileEnv, existingGatewayConfig, pr
|
||||
}
|
||||
|
||||
const profileAuthConfig = buildProfileAuthConfig(profileEnv);
|
||||
const reasoningMatchMode = normalizeReasoningMatchMode(
|
||||
profileEnv.CODEX_RETRY_GATEWAY_REASONING_MATCH_MODE ||
|
||||
existingGatewayConfig?.reasoning_match_mode ||
|
||||
DEFAULT_REASONING_MATCH_MODE,
|
||||
);
|
||||
|
||||
return {
|
||||
profile_name: profileName,
|
||||
@@ -203,9 +211,10 @@ function buildProfileConfig({ profileName, profileEnv, existingGatewayConfig, pr
|
||||
profileEnv.CODEX_RETRY_GATEWAY_ENDPOINTS || existingGatewayConfig?.endpoints,
|
||||
["/responses", "/chat/completions", "/v1/responses", "/v1/chat/completions"],
|
||||
),
|
||||
reasoning_match_mode: reasoningMatchMode,
|
||||
reasoning_equals: normalizeIntArray(
|
||||
profileEnv.CODEX_RETRY_GATEWAY_REASONING_EQUALS || existingGatewayConfig?.reasoning_equals,
|
||||
[516],
|
||||
DEFAULT_REASONING_EQUALS,
|
||||
),
|
||||
retryable_status_codes: normalizeIntArray(
|
||||
profileEnv.CODEX_RETRY_GATEWAY_RETRYABLE_STATUS_CODES || existingGatewayConfig?.retryable_status_codes,
|
||||
|
||||
+289
-39
@@ -43,13 +43,14 @@ function createJsonResponse(res, statusCode, body, extraHeaders = {}) {
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function createSseResponse(res, chunks, intervalMs = 20) {
|
||||
function createSseResponse(res, chunks, intervalMs = 20, options = {}) {
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"cache-control": "no-cache",
|
||||
connection: "keep-alive",
|
||||
"x-upstream-test": "sse",
|
||||
});
|
||||
"x-upstream-test": "sse",
|
||||
...(options.headers || {}),
|
||||
});
|
||||
|
||||
let index = 0;
|
||||
const timer = setInterval(() => {
|
||||
@@ -67,12 +68,13 @@ function createSseResponse(res, chunks, intervalMs = 20) {
|
||||
});
|
||||
}
|
||||
|
||||
function createTerminatedSseResponse(res, chunks, destroyDelayMs = 20) {
|
||||
function createTerminatedSseResponse(res, chunks, destroyDelayMs = 20, options = {}) {
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"cache-control": "no-cache",
|
||||
connection: "keep-alive",
|
||||
"x-upstream-test": "sse-terminated",
|
||||
...(options.headers || {}),
|
||||
});
|
||||
|
||||
for (const chunk of chunks) {
|
||||
@@ -120,12 +122,57 @@ function createCapacityErrorSseResponse(
|
||||
`data: ${JSON.stringify(payload)}\n\n`,
|
||||
],
|
||||
intervalMs,
|
||||
{ headers: options.headers || {} },
|
||||
);
|
||||
}
|
||||
|
||||
function reasoningRetryKeyForRequest(url, parsed) {
|
||||
return [
|
||||
url,
|
||||
parsed.stream ? "stream" : "non-stream",
|
||||
parsed.test_reasoning_retry_key || parsed.thread_id || "missing-thread",
|
||||
].join(":");
|
||||
}
|
||||
|
||||
function beginReasoningRetryTrackedRequest(statsMap, key, res) {
|
||||
const stats = statsMap.get(key) || {
|
||||
totalRequests: 0,
|
||||
activeRequests: 0,
|
||||
maxConcurrent: 0,
|
||||
cancelledRequests: 0,
|
||||
};
|
||||
stats.totalRequests += 1;
|
||||
stats.activeRequests += 1;
|
||||
stats.maxConcurrent = Math.max(stats.maxConcurrent, stats.activeRequests);
|
||||
statsMap.set(key, stats);
|
||||
|
||||
let finished = false;
|
||||
const finish = (cancelled = false) => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
stats.activeRequests = Math.max(0, stats.activeRequests - 1);
|
||||
if (cancelled) {
|
||||
stats.cancelledRequests += 1;
|
||||
}
|
||||
};
|
||||
|
||||
res.on("close", () => {
|
||||
finish(!res.writableEnded);
|
||||
});
|
||||
|
||||
return {
|
||||
stats,
|
||||
finish,
|
||||
};
|
||||
}
|
||||
|
||||
function startFakeUpstream(port) {
|
||||
const failBeforeResponseCounts = new Map();
|
||||
const capacityBeforeSuccessCounts = new Map();
|
||||
const reasoningBeforeSuccessCounts = new Map();
|
||||
const reasoningRetryStats = new Map();
|
||||
const server = http.createServer((req, res) => {
|
||||
const responsePaths = new Set(["/responses", "/v1/responses"]);
|
||||
const chatCompletionPaths = new Set(["/chat/completions", "/v1/chat/completions"]);
|
||||
@@ -148,10 +195,25 @@ function startFakeUpstream(port) {
|
||||
req.setEncoding("utf8");
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
});
|
||||
req.on("end", () => {
|
||||
const parsed = JSON.parse(body || "{}");
|
||||
const reasoning = parsed.test_reasoning_tokens ?? 128;
|
||||
let reasoning = parsed.test_reasoning_tokens ?? 128;
|
||||
let reasoningAttempt = null;
|
||||
const reasoningRetryKey = Number.isInteger(parsed.test_reasoning_before_success_times)
|
||||
? reasoningRetryKeyForRequest(req.url, parsed)
|
||||
: null;
|
||||
const reasoningRetryTracker = reasoningRetryKey
|
||||
? beginReasoningRetryTrackedRequest(reasoningRetryStats, reasoningRetryKey, res)
|
||||
: null;
|
||||
if (Number.isInteger(parsed.test_reasoning_before_success_times) && reasoningRetryKey) {
|
||||
const currentCount = (reasoningBeforeSuccessCounts.get(reasoningRetryKey) || 0) + 1;
|
||||
reasoningBeforeSuccessCounts.set(reasoningRetryKey, currentCount);
|
||||
reasoningAttempt = currentCount;
|
||||
reasoning = currentCount <= parsed.test_reasoning_before_success_times
|
||||
? 516
|
||||
: (parsed.test_reasoning_success_tokens ?? 128);
|
||||
}
|
||||
if (parsed.test_fail_before_response_once) {
|
||||
const failKey = `${req.url}:fail-before-response-once`;
|
||||
const failCount = (failBeforeResponseCounts.get(failKey) || 0) + 1;
|
||||
@@ -236,32 +298,50 @@ function startFakeUpstream(port) {
|
||||
}
|
||||
if (parsed.stream) {
|
||||
createSseResponse(res, [
|
||||
`data: ${JSON.stringify({ type: "response.output_text.delta", delta: "hello", response_id: "resp_stream", thread_id: parsed.thread_id || "thread_stream" })}\n\n`,
|
||||
`data: ${JSON.stringify({ type: "response.output_text.delta", delta: "hello", response_id: "resp_stream", thread_id: parsed.thread_id || "thread_stream", retry_attempt: reasoningAttempt })}\n\n`,
|
||||
`data: {"response":{"usage":{"output_tokens_details":{"reasoning_tokens":${reasoning}}}}}\n\n`,
|
||||
"data: [DONE]\n\n",
|
||||
], parsed.test_stream_chunk_delay_ms ?? 20);
|
||||
], parsed.test_reasoning_response_delay_ms ?? parsed.test_stream_chunk_delay_ms ?? 20, {
|
||||
headers: reasoningAttempt
|
||||
? { "x-upstream-reasoning-attempt": `${reasoningAttempt}` }
|
||||
: {},
|
||||
});
|
||||
return;
|
||||
}
|
||||
createJsonResponse(
|
||||
res,
|
||||
200,
|
||||
{
|
||||
id: "resp_test",
|
||||
thread_id: parsed.thread_id || "thread_test",
|
||||
retry_attempt: parsed.test_fail_before_response_once
|
||||
? failBeforeResponseCounts.get(`${req.url}:fail-before-response-once`) || 0
|
||||
: 0,
|
||||
usage: {
|
||||
output_tokens_details: {
|
||||
reasoning_tokens: reasoning,
|
||||
const sendJsonResponse = () => {
|
||||
if (res.writableEnded || res.destroyed) {
|
||||
reasoningRetryTracker?.finish(true);
|
||||
return;
|
||||
}
|
||||
createJsonResponse(
|
||||
res,
|
||||
200,
|
||||
{
|
||||
id: "resp_test",
|
||||
thread_id: parsed.thread_id || "thread_test",
|
||||
retry_attempt: parsed.test_fail_before_response_once
|
||||
? failBeforeResponseCounts.get(`${req.url}:fail-before-response-once`) || 0
|
||||
: reasoningAttempt || 0,
|
||||
usage: {
|
||||
output_tokens_details: {
|
||||
reasoning_tokens: reasoning,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ "x-upstream-test": `responses-${reasoning}` },
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
{
|
||||
"x-upstream-test": `responses-${reasoning}`,
|
||||
...(reasoningAttempt ? { "x-upstream-reasoning-attempt": `${reasoningAttempt}` } : {}),
|
||||
},
|
||||
);
|
||||
};
|
||||
if (parsed.test_reasoning_response_delay_ms) {
|
||||
setTimeout(sendJsonResponse, parsed.test_reasoning_response_delay_ms);
|
||||
return;
|
||||
}
|
||||
sendJsonResponse();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && chatCompletionPaths.has(req.url)) {
|
||||
let body = "";
|
||||
@@ -293,11 +373,21 @@ function startFakeUpstream(port) {
|
||||
createJsonResponse(res, 404, { error: "not found" });
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, "127.0.0.1", () => resolve(server));
|
||||
});
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
server.getReasoningRetryStat = (key) => {
|
||||
return reasoningRetryStats.get(key) || {
|
||||
totalRequests: 0,
|
||||
activeRequests: 0,
|
||||
maxConcurrent: 0,
|
||||
cancelledRequests: 0,
|
||||
};
|
||||
};
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForHealth(url, timeoutMs = 5000) {
|
||||
const startedAt = Date.now();
|
||||
@@ -386,7 +476,8 @@ async function run() {
|
||||
upstream_base_url: `http://127.0.0.1:${upstreamPort}`,
|
||||
request_body_limit_bytes: 1024 * 1024 * 1024,
|
||||
endpoints: ["/responses", "/chat/completions", "/v1/responses", "/v1/chat/completions"],
|
||||
reasoning_equals: [516],
|
||||
reasoning_match_mode: "formula_518n_minus_2",
|
||||
reasoning_equals: [516, 1034, 1552],
|
||||
retryable_status_codes: [429, 503],
|
||||
retryable_error_messages: [
|
||||
"Selected model is at capacity. Please try a different model.",
|
||||
@@ -450,9 +541,9 @@ async function run() {
|
||||
"/v1/models 未保留上游头",
|
||||
);
|
||||
|
||||
for (const responsePath of ["/responses", "/v1/responses"]) {
|
||||
const blockedResponse = await fetch(`http://127.0.0.1:${gatewayPort}${responsePath}`, {
|
||||
method: "POST",
|
||||
for (const responsePath of ["/responses", "/v1/responses"]) {
|
||||
const blockedResponse = await fetch(`http://127.0.0.1:${gatewayPort}${responsePath}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ test_reasoning_tokens: 516 }),
|
||||
});
|
||||
@@ -473,10 +564,145 @@ async function run() {
|
||||
assert(okResponse.headers.get("x-upstream-test") === "responses-128", `${responsePath} 128 未保留头`);
|
||||
assert(
|
||||
okBody?.usage?.output_tokens_details?.reasoning_tokens === 128,
|
||||
`${responsePath} 128 返回体异常`,
|
||||
);
|
||||
}
|
||||
|
||||
`${responsePath} 128 返回体异常`,
|
||||
);
|
||||
}
|
||||
|
||||
const blockedFormulaResponse = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ test_reasoning_tokens: 2070 }),
|
||||
});
|
||||
const blockedFormulaBody = await blockedFormulaResponse.json();
|
||||
assert(blockedFormulaResponse.status === 502, `/responses 2070 未按 518n-2 返回 502: ${blockedFormulaResponse.status}`);
|
||||
assert(
|
||||
blockedFormulaBody?.error?.code === "reasoning_guard_triggered",
|
||||
"/responses 2070 返回体不正确",
|
||||
);
|
||||
|
||||
const missingThreadRetryKey = reasoningRetryKeyForRequest("/responses", {
|
||||
stream: false,
|
||||
test_reasoning_retry_key: "missing-thread-fallback",
|
||||
});
|
||||
const missingThreadRetryResponse = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
test_reasoning_before_success_times: 1,
|
||||
test_reasoning_retry_key: "missing-thread-fallback",
|
||||
}),
|
||||
});
|
||||
const missingThreadRetryBody = await missingThreadRetryResponse.json();
|
||||
assert(missingThreadRetryResponse.status === 502, `无 thread_id 的 responses 请求不应自动重打: ${missingThreadRetryResponse.status}`);
|
||||
assert(
|
||||
missingThreadRetryBody?.error?.code === "reasoning_guard_triggered",
|
||||
"无 thread_id 的 responses 请求返回体异常",
|
||||
);
|
||||
const missingThreadRetryStats = upstream.getReasoningRetryStat(missingThreadRetryKey);
|
||||
assert(missingThreadRetryStats.totalRequests === 1, "无 thread_id 的 responses 请求不应启动多轮重打");
|
||||
|
||||
const retryRound2ThreadId = "thread_retry_round2";
|
||||
const retryRound2Response = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
thread_id: retryRound2ThreadId,
|
||||
test_reasoning_before_success_times: 1,
|
||||
test_reasoning_retry_key: "round2",
|
||||
}),
|
||||
});
|
||||
const retryRound2Body = await retryRound2Response.json();
|
||||
assert(retryRound2Response.status === 200, `1,1 重打未恢复: ${retryRound2Response.status}`);
|
||||
assert(retryRound2Body?.usage?.output_tokens_details?.reasoning_tokens === 128, "1,1 重打恢复后的 reasoning_tokens 异常");
|
||||
assert(retryRound2Response.headers.get("x-upstream-reasoning-attempt") === "2", "1,1 重打未命中第二次上游请求");
|
||||
const retryRound2EntryResponse = await fetch(
|
||||
`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/requests?query=${encodeURIComponent(retryRound2ThreadId)}`,
|
||||
{ headers: adminHeaders },
|
||||
);
|
||||
const retryRound2EntryPayload = await retryRound2EntryResponse.json();
|
||||
const retryRound2Entry = (retryRound2EntryPayload?.entries || []).find((entry) => entry.thread_id === retryRound2ThreadId);
|
||||
assert(retryRound2Entry?.reasoning_retry_query_count === 2, "1,1 重打未记录两次 query");
|
||||
assert(retryRound2Entry?.reasoning_retry_round_count === 2, "1,1 重打未记录两轮");
|
||||
assert(retryRound2Entry?.reasoning_retry_current_round === 2, "1,1 重打未记录当前轮次");
|
||||
assert(retryRound2Entry?.reasoning_retry_current_width === 1, "1,1 重打未记录当前轮并行数");
|
||||
assert(
|
||||
Array.isArray(retryRound2Entry?.reasoning_retry_current_firsts) &&
|
||||
retryRound2Entry.reasoning_retry_current_firsts.length === 1 &&
|
||||
Number.isInteger(retryRound2Entry.reasoning_retry_current_firsts[0]?.first_response_delay_ms) &&
|
||||
retryRound2Entry.reasoning_retry_current_firsts.every((first) => first?.outcome !== "pending"),
|
||||
"1,1 重打未记录当前轮 first 列表",
|
||||
);
|
||||
assert(retryRound2Entry?.reasoning_retry_winner_round === 2, "1,1 重打赢家轮次异常");
|
||||
assert(retryRound2Entry?.reasoning_retry_winner_slot === 1, "1,1 重打赢家槽位异常");
|
||||
assert(retryRound2Entry?.reasoning_retry_stop_reason === "success", "1,1 重打 stop reason 异常");
|
||||
|
||||
const retryWave2ThreadId = "thread_retry_wave2";
|
||||
const retryWave2Key = reasoningRetryKeyForRequest("/responses", {
|
||||
stream: false,
|
||||
thread_id: retryWave2ThreadId,
|
||||
test_reasoning_retry_key: "wave2",
|
||||
});
|
||||
const retryWave2Response = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
thread_id: retryWave2ThreadId,
|
||||
test_reasoning_before_success_times: 3,
|
||||
test_reasoning_retry_key: "wave2",
|
||||
test_reasoning_response_delay_ms: 80,
|
||||
}),
|
||||
});
|
||||
const retryWave2Body = await retryWave2Response.json();
|
||||
assert(retryWave2Response.status === 200, `1,1,2 重打未恢复: ${retryWave2Response.status}`);
|
||||
assert(retryWave2Body?.usage?.output_tokens_details?.reasoning_tokens === 128, "1,1,2 重打恢复后的 reasoning_tokens 异常");
|
||||
assert(retryWave2Response.headers.get("x-upstream-reasoning-attempt") === "4", "1,1,2 重打未命中第四次上游请求");
|
||||
const retryWave2Stats = upstream.getReasoningRetryStat(retryWave2Key);
|
||||
assert(retryWave2Stats.totalRequests === 4, "1,1,2 重打总请求数异常");
|
||||
assert(retryWave2Stats.maxConcurrent >= 2, "1,1,2 重打未出现第二轮并行");
|
||||
const retryWave2EntryResponse = await fetch(
|
||||
`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/requests?query=${encodeURIComponent(retryWave2ThreadId)}`,
|
||||
{ headers: adminHeaders },
|
||||
);
|
||||
const retryWave2EntryPayload = await retryWave2EntryResponse.json();
|
||||
const retryWave2Entry = (retryWave2EntryPayload?.entries || []).find((entry) => entry.thread_id === retryWave2ThreadId);
|
||||
assert(retryWave2Entry?.reasoning_retry_query_count === 4, "1,1,2 重打未记录四次 query");
|
||||
assert(retryWave2Entry?.reasoning_retry_round_count === 3, "1,1,2 重打未记录三轮");
|
||||
assert(retryWave2Entry?.reasoning_retry_current_round === 3, "1,1,2 重打未记录当前轮次");
|
||||
assert(retryWave2Entry?.reasoning_retry_current_width === 2, "1,1,2 重打未记录当前轮并行数");
|
||||
assert(
|
||||
Array.isArray(retryWave2Entry?.reasoning_retry_current_firsts) &&
|
||||
retryWave2Entry.reasoning_retry_current_firsts.length === 2 &&
|
||||
retryWave2Entry.reasoning_retry_current_firsts.some((first) => Number.isInteger(first?.first_response_delay_ms)) &&
|
||||
retryWave2Entry.reasoning_retry_current_firsts.every((first) => first?.outcome !== "pending"),
|
||||
"1,1,2 重打未记录当前两请求 first 列表",
|
||||
);
|
||||
assert(retryWave2Entry?.reasoning_retry_winner_round === 3, "1,1,2 重打赢家轮次异常");
|
||||
assert([1, 2].includes(retryWave2Entry?.reasoning_retry_winner_slot), "1,1,2 重打赢家槽位异常");
|
||||
assert(retryWave2Entry?.reasoning_retry_stop_reason === "success", "1,1,2 重打 stop reason 异常");
|
||||
|
||||
const streamRetryThreadId = "thread_stream_retry_v1";
|
||||
const streamRetryResponse = await readSseUntilClose(
|
||||
`http://127.0.0.1:${gatewayPort}/v1/responses`,
|
||||
{
|
||||
stream: true,
|
||||
thread_id: streamRetryThreadId,
|
||||
test_reasoning_before_success_times: 1,
|
||||
test_reasoning_retry_key: "stream-v1-round2",
|
||||
},
|
||||
);
|
||||
assert(streamRetryResponse.status === 200, `/v1/responses 流式 1,1 重打未恢复: ${streamRetryResponse.status}`);
|
||||
assert(streamRetryResponse.text.includes("hello"), "/v1/responses 流式 1,1 重打未拿到正常 SSE 内容");
|
||||
assert(streamRetryResponse.text.includes("[DONE]"), "/v1/responses 流式 1,1 重打未完整结束");
|
||||
assert(streamRetryResponse.headers.get("x-upstream-reasoning-attempt") === "2", "/v1/responses 流式 1,1 重打未命中第二次上游请求");
|
||||
const streamRetryEntryResponse = await fetch(
|
||||
`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/requests?query=${encodeURIComponent(streamRetryThreadId)}`,
|
||||
{ headers: adminHeaders },
|
||||
);
|
||||
const streamRetryEntryPayload = await streamRetryEntryResponse.json();
|
||||
const streamRetryEntry = (streamRetryEntryPayload?.entries || []).find((entry) => entry.thread_id === streamRetryThreadId);
|
||||
assert(streamRetryEntry?.reasoning_retry_query_count === 2, "/v1/responses 流式 1,1 重打未记录两次 query");
|
||||
assert(streamRetryEntry?.response_stream === true, "/v1/responses 流式 1,1 重打未保留流式标记");
|
||||
|
||||
const recoveredPayload = JSON.stringify({ test_fail_before_response_once: true });
|
||||
const recoveredResponse = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
@@ -513,6 +739,30 @@ async function run() {
|
||||
assert(threadEntry?.response_id === "resp_test", "non-stream 请求记录未保留 response_id");
|
||||
assert(threadEntry?.thread_id === "thread_nonstream", "non-stream 请求记录未保留 thread_id");
|
||||
|
||||
const effortTrackedResponse = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
test_reasoning_tokens: 128,
|
||||
reasoning: {
|
||||
effort: "xhigh",
|
||||
summary: "auto",
|
||||
},
|
||||
}),
|
||||
});
|
||||
assert(effortTrackedResponse.status === 200, `reasoning.effort 请求失败: ${effortTrackedResponse.status}`);
|
||||
await effortTrackedResponse.json();
|
||||
|
||||
const effortRequestsResponse = await fetch(
|
||||
`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/requests?query=${encodeURIComponent("xhigh")}`,
|
||||
{ headers: adminHeaders },
|
||||
);
|
||||
const effortRequestsPayload = await effortRequestsResponse.json();
|
||||
const effortEntry = (effortRequestsPayload?.entries || []).find((entry) => entry.reasoning_effort === "xhigh");
|
||||
assert(effortRequestsResponse.status === 200, `reasoning.effort 搜索失败: ${effortRequestsResponse.status}`);
|
||||
assert(effortEntry?.reasoning_effort === "xhigh", "请求记录未保留 reasoning.effort");
|
||||
assert(effortEntry?.reasoning_summary === "auto", "请求记录未保留 reasoning.summary");
|
||||
|
||||
const sameRequestPayload = JSON.stringify({ test_reasoning_tokens: 128, test_request_id_marker: "same" });
|
||||
const sameRequestFirstResponse = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
|
||||
@@ -149,6 +149,10 @@ async function run() {
|
||||
gatewayConfig.upstream_base_url === `http://127.0.0.1:${upstreamPort}`,
|
||||
"Gateway config did not preserve original upstream_base_url",
|
||||
);
|
||||
assert(
|
||||
gatewayConfig.reasoning_match_mode === "formula_518n_minus_2",
|
||||
"Gateway config did not default reasoning_match_mode to formula_518n_minus_2",
|
||||
);
|
||||
assert(Array.isArray(gatewayConfig.endpoints), "Gateway config endpoints must be an array");
|
||||
assert(
|
||||
gatewayConfig.endpoints.includes("/responses") &&
|
||||
@@ -195,6 +199,13 @@ async function run() {
|
||||
});
|
||||
assert(blocked516Response.status === 502, `Default 516 block did not trigger: ${blocked516Response.status}`);
|
||||
|
||||
const blocked2070Response = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ test_reasoning_tokens: 2070 }),
|
||||
});
|
||||
assert(blocked2070Response.status === 502, `Default 2070 formula block did not trigger: ${blocked2070Response.status}`);
|
||||
|
||||
const metricsStatusResponse = await fetch(`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/status`);
|
||||
const metricsStatusPayload = await metricsStatusResponse.json();
|
||||
assert(metricsStatusResponse.status === 200, `Status API failed after traffic: ${metricsStatusResponse.status}`);
|
||||
@@ -220,6 +231,7 @@ async function run() {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
reasoning_match_mode: "manual",
|
||||
reasoning_equals: [1024],
|
||||
retryable_status_codes: [429, 503, 529],
|
||||
retryable_error_messages: ["Selected model is at capacity. Please try a different model."],
|
||||
@@ -231,10 +243,15 @@ async function run() {
|
||||
const saveConfigPayload = await saveConfigResponse.json();
|
||||
assert(saveConfigResponse.status === 200, `Save config API failed: ${saveConfigResponse.status}`);
|
||||
assert(saveConfigPayload.config?.non_stream_status_code === 503, "Save config API did not return updated config");
|
||||
assert(saveConfigPayload.config?.reasoning_match_mode === "manual", "Save config API did not return updated reasoning_match_mode");
|
||||
|
||||
const updatedGatewayConfig = JSON.parse(
|
||||
await readFile(path.join(stateRoot, "config", "config.json"), "utf8"),
|
||||
);
|
||||
assert(
|
||||
updatedGatewayConfig.reasoning_match_mode === "manual",
|
||||
"Saved config file did not persist reasoning_match_mode",
|
||||
);
|
||||
assert(
|
||||
JSON.stringify(updatedGatewayConfig.reasoning_equals) === JSON.stringify([1024]),
|
||||
"Saved config file did not persist reasoning_equals",
|
||||
@@ -261,6 +278,13 @@ async function run() {
|
||||
});
|
||||
assert(blockedAfterSave.status === 503, `Hot reloaded config did not take effect: ${blockedAfterSave.status}`);
|
||||
|
||||
const manualModePassthrough = await fetch(`http://127.0.0.1:${gatewayPort}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ test_reasoning_tokens: 2070 }),
|
||||
});
|
||||
assert(manualModePassthrough.status === 200, `manual 模式下 2070 不应继续被拦截: ${manualModePassthrough.status}`);
|
||||
|
||||
const restoreViaUiResponse = await fetch(`http://127.0.0.1:${gatewayPort}/__codex_retry_gateway/api/restore`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
|
||||
@@ -155,6 +155,10 @@ async function run() {
|
||||
statusPayload.state?.original_base_url === upstreamBaseUrl,
|
||||
"First launch did not persist the original upstream base URL",
|
||||
);
|
||||
assert(
|
||||
statusPayload.config?.reasoning_match_mode === "formula_518n_minus_2",
|
||||
"First launch did not default reasoning_match_mode to formula_518n_minus_2",
|
||||
);
|
||||
|
||||
const firstStateRaw = await readFile(path.join(stateRoot, "state.json"), "utf8");
|
||||
const firstState = JSON.parse(firstStateRaw);
|
||||
@@ -194,6 +198,13 @@ async function run() {
|
||||
});
|
||||
assert(blockedResponse.status === 502, `Default 516 interception was not active: ${blockedResponse.status}`);
|
||||
|
||||
const blockedFormulaResponse = await fetch(`${gatewayBaseUrl}/responses`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ test_reasoning_tokens: 2070 }),
|
||||
});
|
||||
assert(blockedFormulaResponse.status === 502, `Default 2070 formula interception was not active: ${blockedFormulaResponse.status}`);
|
||||
|
||||
process.stdout.write("PASS launch-ui flow\n");
|
||||
} finally {
|
||||
try {
|
||||
|
||||
+275
-6
@@ -2,6 +2,7 @@ import { FormEvent, startTransition, useEffect, useState } from "react";
|
||||
|
||||
type PageKey = "overview" | "requests" | "profiles" | "rules" | "logs";
|
||||
type Tone = "" | "success" | "error";
|
||||
type ReasoningMatchMode = "formula_518n_minus_2" | "manual";
|
||||
|
||||
type GatewayConfig = {
|
||||
profile_name?: string;
|
||||
@@ -16,6 +17,7 @@ type GatewayConfig = {
|
||||
request_history_limit?: number;
|
||||
model_remap?: string;
|
||||
endpoints?: string[];
|
||||
reasoning_match_mode?: ReasoningMatchMode;
|
||||
reasoning_equals?: number[];
|
||||
retryable_status_codes?: number[];
|
||||
retryable_error_messages?: string[];
|
||||
@@ -90,10 +92,36 @@ type RequestEntry = {
|
||||
model?: string | null;
|
||||
requested_model?: string | null;
|
||||
forwarded_model?: string | null;
|
||||
reasoning_effort?: string | null;
|
||||
reasoning_summary?: string | null;
|
||||
response_stream?: boolean;
|
||||
stream_chunk_count?: number | null;
|
||||
usage_last_updated_at?: string | null;
|
||||
upstream_attempt_count?: number | null;
|
||||
reasoning_retry_enabled?: boolean;
|
||||
reasoning_retry_query_count?: number | null;
|
||||
reasoning_retry_round_count?: number | null;
|
||||
reasoning_retry_current_round?: number | null;
|
||||
reasoning_retry_current_width?: number | null;
|
||||
reasoning_retry_current_firsts?: Array<{
|
||||
round?: number | null;
|
||||
slot?: number | null;
|
||||
first_response_at?: string | null;
|
||||
first_response_delay_ms?: number | null;
|
||||
outcome?: string | null;
|
||||
status_code?: number | null;
|
||||
upstream_status_code?: number | null;
|
||||
reasoning_tokens?: number | null;
|
||||
matched?: boolean | null;
|
||||
}> | null;
|
||||
reasoning_retry_winner_round?: number | null;
|
||||
reasoning_retry_winner_slot?: number | null;
|
||||
reasoning_retry_stop_reason?: string | null;
|
||||
reasoning_retry_thread_mode?: string | null;
|
||||
reasoning_retry_extra_inspected_count?: number | null;
|
||||
reasoning_retry_extra_matched_count?: number | null;
|
||||
reasoning_retry_extra_usage?: Usage | null;
|
||||
reasoning_retry_extra_reasoning_counts?: Record<string, number> | null;
|
||||
matched?: boolean;
|
||||
status_code?: number | null;
|
||||
upstream_status_code?: number | null;
|
||||
@@ -130,6 +158,7 @@ type ProfileFormModel = {
|
||||
auth_json_key?: string;
|
||||
request_history_limit?: string;
|
||||
model_remap?: string;
|
||||
reasoning_match_mode?: ReasoningMatchMode;
|
||||
reasoning_equals?: string;
|
||||
retryable_status_codes?: string;
|
||||
retryable_error_messages?: string[];
|
||||
@@ -150,6 +179,7 @@ type Profile = {
|
||||
auth_source?: string;
|
||||
request_history_limit?: string;
|
||||
model_remap?: string;
|
||||
reasoning_match_mode?: ReasoningMatchMode;
|
||||
reasoning_equals?: string;
|
||||
};
|
||||
form?: ProfileFormModel;
|
||||
@@ -199,6 +229,7 @@ type ProfileFormState = {
|
||||
auth_json_key: string;
|
||||
request_history_limit: string;
|
||||
model_remap: string;
|
||||
reasoning_match_mode: ReasoningMatchMode;
|
||||
reasoning_equals: string;
|
||||
retryable_status_codes: string;
|
||||
retryable_error_messages: string;
|
||||
@@ -208,6 +239,7 @@ type ProfileFormState = {
|
||||
};
|
||||
|
||||
type RuleFormState = {
|
||||
reasoning_match_mode: ReasoningMatchMode;
|
||||
reasoning_equals: string;
|
||||
retryable_status_codes: string;
|
||||
retryable_error_messages: string;
|
||||
@@ -307,6 +339,7 @@ const defaultProfileForm: ProfileFormState = {
|
||||
auth_json_key: "OPENAI_API_KEY",
|
||||
request_history_limit: "0",
|
||||
model_remap: "",
|
||||
reasoning_match_mode: "formula_518n_minus_2",
|
||||
reasoning_equals: "516,1034,1552",
|
||||
retryable_status_codes: "429,503",
|
||||
retryable_error_messages: "Selected model is at capacity. Please try a different model.\nstream disconnected before completion: Concurrency limit exceeded for account, please retry later",
|
||||
@@ -333,6 +366,17 @@ function durationSeconds(value?: number | null) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? `${(value / 1000).toFixed(2)} s` : "-";
|
||||
}
|
||||
|
||||
function compactDurationSeconds(value?: number | null) {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
||||
return "?";
|
||||
}
|
||||
const seconds = value / 1000;
|
||||
if (seconds >= 100) {
|
||||
return `${seconds.toFixed(0)}s`;
|
||||
}
|
||||
return `${seconds.toFixed(1).replace(/\\.0$/, "")}s`;
|
||||
}
|
||||
|
||||
function secondsSince(startedAt: string | null | undefined, updatedAt: string | null | undefined) {
|
||||
if (!startedAt || !updatedAt) {
|
||||
return "-";
|
||||
@@ -392,6 +436,98 @@ function requestPrimaryId(entry: RequestEntry) {
|
||||
return entry.response_id || entry.request_id || "-";
|
||||
}
|
||||
|
||||
function hasReasoningRetryInfo(entry: RequestEntry) {
|
||||
return Boolean(
|
||||
entry.reasoning_retry_enabled ||
|
||||
entry.reasoning_retry_thread_mode ||
|
||||
entry.reasoning_retry_query_count ||
|
||||
entry.reasoning_retry_round_count ||
|
||||
entry.reasoning_retry_stop_reason,
|
||||
);
|
||||
}
|
||||
|
||||
function retryRoundWidthText(entry: RequestEntry) {
|
||||
const round = entry.reasoning_retry_current_round || entry.reasoning_retry_round_count || 0;
|
||||
const width = entry.reasoning_retry_current_width || 0;
|
||||
if (!round) {
|
||||
return "-";
|
||||
}
|
||||
return width ? `${numberFormat(round)}(${numberFormat(width)})` : numberFormat(round);
|
||||
}
|
||||
|
||||
function retryFirstLabel(first: NonNullable<RequestEntry["reasoning_retry_current_firsts"]>[number], fallbackRound?: number | null) {
|
||||
const round = first.round ?? fallbackRound ?? null;
|
||||
const slot = first.slot ?? null;
|
||||
if (typeof round === "number" && Number.isInteger(round)) {
|
||||
if (typeof slot === "number" && Number.isInteger(slot) && slot > 1) {
|
||||
return `${numberFormat(round)}-${numberFormat(slot)}`;
|
||||
}
|
||||
return numberFormat(round);
|
||||
}
|
||||
if (typeof slot === "number" && Number.isInteger(slot)) {
|
||||
return `#${numberFormat(slot)}`;
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
function retryFirstText(
|
||||
first: NonNullable<RequestEntry["reasoning_retry_current_firsts"]>[number],
|
||||
fallbackRound?: number | null,
|
||||
) {
|
||||
const delay = durationSeconds(first.first_response_delay_ms);
|
||||
const outcome = first.outcome || "pending";
|
||||
const reasoning = typeof first.reasoning_tokens === "number" ? ` r${numberFormat(first.reasoning_tokens)}` : "";
|
||||
const status = typeof first.status_code === "number" ? ` ${first.status_code}` : "";
|
||||
return `${retryFirstLabel(first, fallbackRound)} ${delay} ${outcome}${status}${reasoning}`;
|
||||
}
|
||||
|
||||
function retryFirstCompactText(
|
||||
first: NonNullable<RequestEntry["reasoning_retry_current_firsts"]>[number],
|
||||
) {
|
||||
return compactDurationSeconds(first.first_response_delay_ms);
|
||||
}
|
||||
|
||||
function formatRetryStopReason(value?: string | null) {
|
||||
const reason = `${value || ""}`.trim();
|
||||
if (!reason) {
|
||||
return "-";
|
||||
}
|
||||
const labels: Record<string, string> = {
|
||||
success: "成功",
|
||||
missing_thread_id: "缺少 thread_id",
|
||||
completed_without_retry: "未触发调度",
|
||||
reasoning_guard: "reasoning 命中",
|
||||
retryable_upstream_error: "上游可重试错误",
|
||||
fatal: "致命错误",
|
||||
exhausted_without_winner: "无赢家",
|
||||
};
|
||||
return labels[reason] || reason;
|
||||
}
|
||||
|
||||
function formatRetryThreadMode(value?: string | null) {
|
||||
const mode = `${value || ""}`.trim();
|
||||
if (!mode || mode === "disabled") {
|
||||
return "未启用";
|
||||
}
|
||||
if (mode === "thread_id") {
|
||||
return "按 thread_id";
|
||||
}
|
||||
if (mode === "missing_thread_id") {
|
||||
return "缺少 thread_id";
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
function sortedReasoningCounts(value?: Record<string, number> | null) {
|
||||
return Object.entries(value || {}).sort((left, right) => {
|
||||
const countDelta = Number(right[1] || 0) - Number(left[1] || 0);
|
||||
if (countDelta !== 0) {
|
||||
return countDelta;
|
||||
}
|
||||
return Number(left[0] || 0) - Number(right[0] || 0);
|
||||
});
|
||||
}
|
||||
|
||||
function splitList(value: string) {
|
||||
return value
|
||||
.split(/[\s,]+/)
|
||||
@@ -406,6 +542,21 @@ function splitLines(value: string) {
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function normalizeReasoningMode(value: unknown): ReasoningMatchMode {
|
||||
return value === "manual" ? "manual" : "formula_518n_minus_2";
|
||||
}
|
||||
|
||||
function formatReasoningMode(mode: ReasoningMatchMode) {
|
||||
return mode === "manual" ? "manual" : "518n-2";
|
||||
}
|
||||
|
||||
function formatReasoningRule(mode: ReasoningMatchMode, reasoningEquals?: string) {
|
||||
if (mode === "manual") {
|
||||
return reasoningEquals || "-";
|
||||
}
|
||||
return "516, 1034, 1552, ...";
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string, options?: RequestInit): Promise<T> {
|
||||
const headers = new Headers(options?.headers || {});
|
||||
const accessKey = window.localStorage.getItem(ACCESS_KEY_STORAGE_KEY)?.trim();
|
||||
@@ -435,6 +586,7 @@ function profileFormFromStatus(status: StatusPayload | null): ProfileFormState {
|
||||
auth_json_key: config.upstream_auth_json_key || defaultProfileForm.auth_json_key,
|
||||
request_history_limit: String(config.request_history_limit ?? defaultProfileForm.request_history_limit),
|
||||
model_remap: config.model_remap || "",
|
||||
reasoning_match_mode: normalizeReasoningMode(config.reasoning_match_mode),
|
||||
reasoning_equals: Array.isArray(config.reasoning_equals)
|
||||
? config.reasoning_equals.join(",")
|
||||
: defaultProfileForm.reasoning_equals,
|
||||
@@ -472,7 +624,8 @@ function profileFormFromProfile(profile: Profile): ProfileFormState {
|
||||
auth_json_key: form.auth_json_key || "OPENAI_API_KEY",
|
||||
request_history_limit: form.request_history_limit || defaultProfileForm.request_history_limit,
|
||||
model_remap: form.model_remap || "",
|
||||
reasoning_equals: form.reasoning_equals || "",
|
||||
reasoning_match_mode: normalizeReasoningMode(form.reasoning_match_mode),
|
||||
reasoning_equals: form.reasoning_equals || defaultProfileForm.reasoning_equals,
|
||||
retryable_status_codes: form.retryable_status_codes || defaultProfileForm.retryable_status_codes,
|
||||
retryable_error_messages: Array.isArray(form.retryable_error_messages)
|
||||
? form.retryable_error_messages.join("\n")
|
||||
@@ -488,6 +641,7 @@ function profileFormFromProfile(profile: Profile): ProfileFormState {
|
||||
function ruleFormFromStatus(status: StatusPayload | null): RuleFormState {
|
||||
const config = status?.config || {};
|
||||
return {
|
||||
reasoning_match_mode: normalizeReasoningMode(config.reasoning_match_mode),
|
||||
reasoning_equals: Array.isArray(config.reasoning_equals) ? config.reasoning_equals.join(", ") : "",
|
||||
retryable_status_codes: Array.isArray(config.retryable_status_codes)
|
||||
? config.retryable_status_codes.join(", ")
|
||||
@@ -724,6 +878,7 @@ export default function App() {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
reasoning_match_mode: ruleForm.reasoning_match_mode,
|
||||
reasoning_equals: splitList(ruleForm.reasoning_equals)
|
||||
.map((value) => Number.parseInt(value, 10))
|
||||
.filter((value) => Number.isInteger(value)),
|
||||
@@ -784,6 +939,7 @@ export default function App() {
|
||||
auth_json_key: profileForm.auth_json_key,
|
||||
request_history_limit: Number.parseInt(profileForm.request_history_limit, 10),
|
||||
model_remap: profileForm.model_remap,
|
||||
reasoning_match_mode: profileForm.reasoning_match_mode,
|
||||
reasoning_equals: splitList(profileForm.reasoning_equals),
|
||||
retryable_status_codes: splitList(profileForm.retryable_status_codes),
|
||||
retryable_error_messages: splitLines(profileForm.retryable_error_messages),
|
||||
@@ -1089,6 +1245,11 @@ export default function App() {
|
||||
const statusTone = entry.error ? "error" : entry.matched ? "warn" : "";
|
||||
const effectiveInput = effectiveInputTokens(usage.input_tokens, usage.cached_tokens);
|
||||
const cachedHitRatio = cachedRatio(usage.input_tokens, usage.cached_tokens);
|
||||
const showReasoningRetry = hasReasoningRetryInfo(entry);
|
||||
const retryReasoningCounts = sortedReasoningCounts(entry.reasoning_retry_extra_reasoning_counts);
|
||||
const retryCurrentFirsts = Array.isArray(entry.reasoning_retry_current_firsts)
|
||||
? entry.reasoning_retry_current_firsts
|
||||
: [];
|
||||
return (
|
||||
<article className="request-card" key={entry.seq}>
|
||||
<div className="request-head">
|
||||
@@ -1101,10 +1262,21 @@ export default function App() {
|
||||
<span className="meta-key">发</span>
|
||||
{timestamp(entry.started_at)}
|
||||
</span>
|
||||
<span className="meta-pill meta-first">
|
||||
<span className="meta-key">首</span>
|
||||
{durationSeconds(entry.first_response_delay_ms)}
|
||||
</span>
|
||||
{retryCurrentFirsts.length > 0 ? (
|
||||
<span className="meta-pill meta-first meta-first-list-pill">
|
||||
<span className="meta-key">首</span>
|
||||
{retryCurrentFirsts.map((first, index) => (
|
||||
<span className="meta-first-mini" key={`${first.round || entry.reasoning_retry_current_round || "r"}-${first.slot || index}`}>
|
||||
{retryFirstCompactText(first)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : (
|
||||
<span className="meta-pill meta-first">
|
||||
<span className="meta-key">首</span>
|
||||
{durationSeconds(entry.first_response_delay_ms)}
|
||||
</span>
|
||||
)}
|
||||
<span className="meta-pill meta-total">
|
||||
<span className="meta-key">总</span>
|
||||
{durationSeconds(entry.duration_ms)}
|
||||
@@ -1123,6 +1295,12 @@ export default function App() {
|
||||
? `${numberFormat(entry.stream_chunk_count)} chunk / ${bytesFormat(entry.response_bytes_received)} / ${secondsSince(entry.started_at, entry.last_activity_at || entry.usage_last_updated_at || entry.finished_at)}`
|
||||
: "-"}
|
||||
</span>
|
||||
{showReasoningRetry ? (
|
||||
<span className="meta-pill meta-retry">
|
||||
<span className="meta-key">重打</span>
|
||||
{`${retryRoundWidthText(entry)} / ${numberFormat(entry.reasoning_retry_query_count || 0)}q`}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="meta-pill meta-received">
|
||||
<span className="meta-key">收</span>
|
||||
{timestamp(entry.finished_at)}
|
||||
@@ -1138,6 +1316,11 @@ export default function App() {
|
||||
<div className="request-badges">
|
||||
{entry.matched ? <span className="badge warn">matched</span> : <span className="badge">pass</span>}
|
||||
{entry.error ? <span className="badge error">error</span> : null}
|
||||
{showReasoningRetry ? (
|
||||
<span className={`badge ${entry.reasoning_retry_stop_reason === "success" ? "success" : "warn"}`}>
|
||||
retry {formatRetryStopReason(entry.reasoning_retry_stop_reason)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1150,6 +1333,12 @@ export default function App() {
|
||||
? `转发为 ${entry.forwarded_model}`
|
||||
: entry.forwarded_model || "-"}
|
||||
</span>
|
||||
<span className="hint">
|
||||
{entry.reasoning_effort
|
||||
? `强度 ${entry.reasoning_effort}`
|
||||
: "强度 -"}
|
||||
{entry.reasoning_summary ? ` / summary ${entry.reasoning_summary}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="request-block">
|
||||
@@ -1182,6 +1371,54 @@ export default function App() {
|
||||
<span className="hint">{`request ${entry.request_id || "-"}`}</span>
|
||||
<span className="hint">{`thread ${entry.thread_id || "-"}`}</span>
|
||||
</div>
|
||||
|
||||
{showReasoningRetry ? (
|
||||
<div className="request-block reasoning-retry-block">
|
||||
<label>Reasoning Retry</label>
|
||||
<code>{formatRetryThreadMode(entry.reasoning_retry_thread_mode)}</code>
|
||||
<span className="hint">
|
||||
schedule 1,1,2,2,4,4... / query {numberFormat(entry.reasoning_retry_query_count || 0)}
|
||||
{" / "}
|
||||
round {retryRoundWidthText(entry)}
|
||||
</span>
|
||||
<span className="hint">
|
||||
winner {entry.reasoning_retry_winner_round && entry.reasoning_retry_winner_slot
|
||||
? `round ${entry.reasoning_retry_winner_round} slot ${entry.reasoning_retry_winner_slot}`
|
||||
: "-"}
|
||||
{" / "}
|
||||
stop {formatRetryStopReason(entry.reasoning_retry_stop_reason)}
|
||||
</span>
|
||||
<span className="hint">
|
||||
extra matched {numberFormat(entry.reasoning_retry_extra_matched_count || 0)}
|
||||
{" / "}
|
||||
inspected {numberFormat(entry.reasoning_retry_extra_inspected_count || 0)}
|
||||
{" / "}
|
||||
extra reasoning {numberFormat(entry.reasoning_retry_extra_usage?.reasoning_tokens)}
|
||||
</span>
|
||||
{retryReasoningCounts.length > 0 ? (
|
||||
<div className="retry-chip-row">
|
||||
{retryReasoningCounts.slice(0, 4).map(([reasoning, count]) => (
|
||||
<span className="chip compact-chip" key={reasoning}>
|
||||
{reasoning}: {numberFormat(count)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{retryCurrentFirsts.length > 0 ? (
|
||||
<div className="retry-first-list" aria-label="current retry wave first responses">
|
||||
{retryCurrentFirsts.map((first, index) => (
|
||||
<span
|
||||
className={`retry-first-chip ${first.first_response_delay_ms == null ? "pending" : ""}`}
|
||||
key={`${first.round || entry.reasoning_retry_current_round || "r"}-${first.slot || index}`}
|
||||
title={`first ${timestamp(first.first_response_at)} / upstream ${first.upstream_status_code ?? "-"}`}
|
||||
>
|
||||
{retryFirstText(first, entry.reasoning_retry_current_round)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
@@ -1246,7 +1483,17 @@ export default function App() {
|
||||
<MiniStat label="Auth Source" value={profile.summary?.auth_source || "-"} />
|
||||
<MiniStat label="History" value={profile.summary?.request_history_limit || "0"} />
|
||||
<MiniStat label="Model Remap" value={profile.summary?.model_remap || "-"} />
|
||||
<MiniStat label="Reasoning" value={profile.summary?.reasoning_equals || "-"} />
|
||||
<MiniStat
|
||||
label="Reasoning"
|
||||
value={formatReasoningRule(
|
||||
normalizeReasoningMode(profile.summary?.reasoning_match_mode),
|
||||
profile.summary?.reasoning_equals,
|
||||
)}
|
||||
/>
|
||||
<MiniStat
|
||||
label="Rule Mode"
|
||||
value={formatReasoningMode(normalizeReasoningMode(profile.summary?.reasoning_match_mode))}
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
))
|
||||
@@ -1323,6 +1570,17 @@ export default function App() {
|
||||
onChange={(event) => setProfileForm({ ...profileForm, request_history_limit: event.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="reasoning_match_mode" hint="`518n-2` 会命中 516、1034、1552 等;`manual` 则只按下面的列表拦截。">
|
||||
<select
|
||||
value={profileForm.reasoning_match_mode}
|
||||
onChange={(event) =>
|
||||
setProfileForm({ ...profileForm, reasoning_match_mode: normalizeReasoningMode(event.target.value) })
|
||||
}
|
||||
>
|
||||
<option value="formula_518n_minus_2">formula_518n_minus_2</option>
|
||||
<option value="manual">manual</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="reasoning_equals">
|
||||
<input value={profileForm.reasoning_equals} placeholder="516,1034,1552" onChange={(event) => setProfileForm({ ...profileForm, reasoning_equals: event.target.value })} />
|
||||
</Field>
|
||||
@@ -1396,6 +1654,17 @@ export default function App() {
|
||||
<section className="page" data-active="true">
|
||||
<Card title="当前运行规则" hint="保存后会热生效,只影响当前正在运行的 gateway config;长期 profile 默认值请去 Profiles 页保存。">
|
||||
<form onSubmit={saveRules}>
|
||||
<Field label="reasoning_match_mode" hint="`518n-2` 会命中 516、1034、1552 等;切到 `manual` 时才只按手写列表判断。">
|
||||
<select
|
||||
value={ruleForm.reasoning_match_mode}
|
||||
onChange={(event) =>
|
||||
setRuleForm({ ...ruleForm, reasoning_match_mode: normalizeReasoningMode(event.target.value) })
|
||||
}
|
||||
>
|
||||
<option value="formula_518n_minus_2">formula_518n_minus_2</option>
|
||||
<option value="manual">manual</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="reasoning_equals">
|
||||
<input value={ruleForm.reasoning_equals} placeholder="例如:516, 1034, 1552" onChange={(event) => setRuleForm({ ...ruleForm, reasoning_equals: event.target.value })} />
|
||||
</Field>
|
||||
|
||||
+69
-2
@@ -450,6 +450,11 @@ a {
|
||||
background: #fff0d9;
|
||||
}
|
||||
|
||||
.badge.success {
|
||||
color: var(--accent);
|
||||
background: #d7eee6;
|
||||
}
|
||||
|
||||
.badge.error {
|
||||
color: var(--red);
|
||||
background: #ffece7;
|
||||
@@ -622,9 +627,29 @@ a {
|
||||
background: #e5eaef;
|
||||
}
|
||||
|
||||
.meta-retry {
|
||||
color: #0f5045;
|
||||
background: #d2eee4;
|
||||
}
|
||||
|
||||
.meta-first-list-pill {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.meta-first-mini {
|
||||
border-radius: 999px;
|
||||
padding: 2px 6px;
|
||||
background: rgba(198, 84, 37, 0.09);
|
||||
color: #8d421e;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.request-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.05fr 1.35fr 1.6fr;
|
||||
grid-template-columns: minmax(150px, 1fr) minmax(220px, 1.25fr) minmax(260px, 1.5fr) minmax(180px, 1.05fr);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@@ -653,6 +678,46 @@ a {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.reasoning-retry-block {
|
||||
grid-column: span 2;
|
||||
border-color: rgba(22, 107, 92, 0.16);
|
||||
background:
|
||||
radial-gradient(circle at 0% 0%, rgba(22, 107, 92, 0.1), transparent 42%),
|
||||
rgba(255, 250, 240, 0.82);
|
||||
}
|
||||
|
||||
.retry-chip-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.retry-first-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.retry-first-chip {
|
||||
border: 1px solid rgba(22, 107, 92, 0.18);
|
||||
border-radius: 999px;
|
||||
padding: 4px 8px;
|
||||
color: #12463c;
|
||||
background: rgba(22, 107, 92, 0.1);
|
||||
font-size: 11px;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.retry-first-chip.pending {
|
||||
color: var(--muted);
|
||||
background: rgba(30, 33, 29, 0.05);
|
||||
}
|
||||
|
||||
.compact-chip {
|
||||
padding: 3px 7px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 960px;
|
||||
@@ -946,9 +1011,11 @@ form {
|
||||
}
|
||||
|
||||
.request-head,
|
||||
.request-grid {
|
||||
.request-grid,
|
||||
.reasoning-retry-block {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-column: auto;
|
||||
}
|
||||
|
||||
.info-row {
|
||||
|
||||
Reference in New Issue
Block a user