fix(detail-agent-pi): omit invalid 'off' reasoning_effort and auto-downgrade HTTP 400/422
This commit is contained in:
parent
35613c6dec
commit
9da00aac49
@ -71,10 +71,20 @@ const protocolBaseUrl = protocol => 'https://api.vip98k.com' +
|
||||
const authorizedCandidates = candidates => (candidates ?? []).filter(route =>
|
||||
route.protocol === 'google-generative-ai' ? googleModelPath.test(route.path?.replace(/\?alt=sse$/u,''))
|
||||
: Object.hasOwn(protocolPaths,route.protocol) && route.path === protocolPaths[route.protocol]);
|
||||
function thinkingMap(efforts, fallback) {
|
||||
if (!efforts?.length) return fallback && {...fallback,off:fallback.off ?? 'off'};
|
||||
function thinkingMap(efforts, fallback, protocol) {
|
||||
const isAnthropic = protocol === 'anthropic-messages';
|
||||
if (!efforts?.length) {
|
||||
if (!fallback) return fallback;
|
||||
const off = isAnthropic ? (fallback.off ?? 'off') : (fallback.off === 'none' ? 'none' : undefined);
|
||||
return { ...fallback, off };
|
||||
}
|
||||
const offValue = isAnthropic ? 'off' : (efforts.includes('none') ? 'none' : undefined);
|
||||
return Object.fromEntries(['off','minimal','low','medium','high','xhigh','max'].map(level=>[
|
||||
level,level==='off'||efforts.includes(level)?level:level==='minimal'&&efforts.includes('low')?'low':null,
|
||||
level,
|
||||
level === 'off' ? offValue
|
||||
: efforts.includes(level) ? level
|
||||
: level === 'minimal' && efforts.includes('low') ? 'low'
|
||||
: null,
|
||||
]));
|
||||
}
|
||||
|
||||
@ -672,6 +682,9 @@ export class DetailPiAgent {
|
||||
round = requestBroker.round(route.headers === undefined ? undefined : {invocationHeaders:route.headers});
|
||||
const key = routeKey(route);
|
||||
const dispatchModel = buildModel(routesWithoutReasoning.has(key) ? {...route,reasoning:false} : route);
|
||||
if (!options.reasoning && route.protocol !== 'anthropic-messages' && dispatchModel.thinkingLevelMap?.off !== 'none') {
|
||||
dispatchModel.thinkingLevelMap = { ...dispatchModel.thinkingLevelMap, off: null };
|
||||
}
|
||||
if (dispatchModel.api === 'anthropic-messages' && dispatchModel.compat.supportsMidConvoEffort === true) {
|
||||
dispatchModel.reasoning = true;
|
||||
}
|
||||
@ -690,7 +703,7 @@ export class DetailPiAgent {
|
||||
requestBytes = Buffer.byteLength(body);
|
||||
const payload = JSON.parse(body);
|
||||
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
|
||||
reasoningSent = route.protocol === 'openai-responses' && Object.hasOwn(payload,'reasoning');
|
||||
reasoningSent = ['reasoning', 'reasoning_effort', 'thinking'].some(key => Object.hasOwn(payload, key));
|
||||
}
|
||||
await host.store.appendEvent({type:'provider_started',id:round.id,protocol:route.protocol,...workerFields,requestBytes});
|
||||
host.productionSignal?.throwIfAborted();
|
||||
@ -699,12 +712,28 @@ export class DetailPiAgent {
|
||||
headersAt=Date.now();
|
||||
httpStatus=response.status;
|
||||
retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'));
|
||||
if (!response.ok && response.headers.get('content-type')?.includes('application/json')) {
|
||||
const {error} = await response.clone().json().catch(() => ({}));
|
||||
legacyFailure = error;
|
||||
// This exact gateway error comes from route preparation, before inference.
|
||||
reasoningRejected = reasoningSent && httpStatus === 400 && error?.code === 'invalid_request' &&
|
||||
error.message === 'The request parameter "reasoning" is not supported by the selected model.';
|
||||
if (!response.ok) {
|
||||
const rawText = await response.clone().text().catch(() => '');
|
||||
let parsed;
|
||||
if (rawText && (response.headers.get('content-type')?.includes('application/json') || rawText.trimStart().startsWith('{'))) {
|
||||
try { parsed = JSON.parse(rawText); } catch {}
|
||||
}
|
||||
const errorObj = parsed && typeof parsed.error === 'object' && parsed.error !== null ? parsed.error : undefined;
|
||||
if (errorObj) legacyFailure = errorObj;
|
||||
const errorText = [
|
||||
errorObj?.message,
|
||||
typeof parsed?.error === 'string' ? parsed.error : undefined,
|
||||
typeof parsed?.message === 'string' ? parsed.message : undefined,
|
||||
rawText,
|
||||
].find(value => typeof value === 'string' && value.length > 0) ?? '';
|
||||
// This exact gateway error comes from route preparation, before inference,
|
||||
// or from strict JSON/enum validation (e.g. HTTP 422 on reasoning_effort).
|
||||
reasoningRejected = reasoningSent && (httpStatus === 400 || httpStatus === 422) && (
|
||||
(errorObj?.code === 'invalid_request' &&
|
||||
errorObj.message === 'The request parameter "reasoning" is not supported by the selected model.') ||
|
||||
(/\b(?:reasoning_effort|reasoning|thinking)\b/i.test(errorText) &&
|
||||
/\b(?:unknown variant|not supported|unsupported|invalid)\b/i.test(errorText))
|
||||
);
|
||||
}
|
||||
return observeStreamFailure(response, identity => { legacyFailure = identity; });
|
||||
} catch (error) {
|
||||
@ -840,7 +869,7 @@ export class DetailPiAgent {
|
||||
const api = modelApi(selection.protocol);
|
||||
const known = catalogModel(runtime,selection.id,api);
|
||||
const provider = selection.provider ?? known?.provider ?? protocolProviders[selection.protocol];
|
||||
const thinkingLevelMap = thinkingMap(selection.reasoningEfforts,known?.thinkingLevelMap);
|
||||
const thinkingLevelMap = thinkingMap(selection.reasoningEfforts, known?.thinkingLevelMap, selection.protocol);
|
||||
return {
|
||||
provider, id:selection.id, name:selection.name ?? selection.id, api,
|
||||
baseUrl:protocolBaseUrl(selection.protocol),reasoning:selection.reasoning === true,
|
||||
|
||||
@ -396,6 +396,52 @@ test('a routing preflight rejection of reasoning retries only the same Responses
|
||||
request.invocationHeaders['X-Relay-Route-Option']===route.headers['X-Relay-Route-Option']));
|
||||
});
|
||||
|
||||
test('openai-chat with reasoning=true and thinking=off omits reasoning_effort instead of sending "off"',async t=>{
|
||||
const route={...chatRoute,id:'deepseek-v4.1-flash-1017',reasoning:true,reasoningEfforts:['low','high','max']};
|
||||
const x=await setup(()=>sse({content:'已关闭思考直接回复。'},'stop'),
|
||||
undefined,undefined,{model:route,candidates:[route],thinkingLevel:'off'});
|
||||
t.after(x.close);
|
||||
|
||||
assert.equal((await x.host.prompt('直接回答')).text,'已关闭思考直接回复。');
|
||||
assert.equal(x.requests.length,1);
|
||||
assert.equal(Object.hasOwn(x.requests[0],'reasoning_effort'),false);
|
||||
});
|
||||
|
||||
test('openai-responses with reasoning=true and thinking=off never sends reasoning.effort="off"',async t=>{
|
||||
const route={...responsesRoute,id:'gpt-5.4-mini',reasoning:true,reasoningEfforts:['low','high']};
|
||||
const item={type:'message',id:'msg_off',role:'assistant',status:'completed',
|
||||
content:[{type:'output_text',text:'已关闭思考。',annotations:[]}]};
|
||||
const event=(type,details)=>'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n';
|
||||
const response=event('response.output_item.added',{output_index:0,item:{...item,content:[]}})
|
||||
+event('response.output_text.delta',{output_index:0,content_index:0,delta:'已关闭思考。'})
|
||||
+event('response.output_item.done',{output_index:0,item})
|
||||
+event('response.completed',{response:{model:'gpt-5.4-mini',status:'completed',output:[item]}});
|
||||
const x=await setup(()=>response,undefined,undefined,{model:route,candidates:[route],thinkingLevel:'off'});
|
||||
t.after(x.close);
|
||||
|
||||
assert.equal((await x.host.prompt('直接回答')).text,'已关闭思考。');
|
||||
assert.equal(x.requests.length,1);
|
||||
assert.notEqual(x.requests[0].reasoning?.effort,'off');
|
||||
assert.equal(Object.hasOwn(x.requests[0],'reasoning'),false);
|
||||
});
|
||||
|
||||
test('openai-chat HTTP 422 on reasoning_effort strips reasoning and retries the same route immediately',async t=>{
|
||||
const route={...chatRoute,id:'deepseek-v4.1-flash-1017',reasoning:true,reasoningEfforts:['low','high','max']};
|
||||
const errorText="Failed to deserialize the JSON body into the target type: reasoning_effort: unknown variant 'high', expected one of 'none', 'minimal', 'low', 'medium', 'high'";
|
||||
const x=await setup((_payload,n)=>n===1
|
||||
? new Response(errorText,{status:422,headers:{'content-type':'text/plain; charset=utf-8'}})
|
||||
: sse({content:'降级重试成功。'},'stop'),
|
||||
undefined,undefined,{model:route,candidates:[route,responsesRoute],thinkingLevel:'high'});
|
||||
t.after(x.close);
|
||||
|
||||
assert.equal((await x.host.prompt('测试422降级')).text,'降级重试成功。');
|
||||
assert.equal((await x.host.prompt('下一轮')).text,'降级重试成功。');
|
||||
assert.equal(x.requests[0].reasoning_effort,'high');
|
||||
assert.equal(x.requests.length,3);
|
||||
assert.ok(x.requests.slice(1).every(request=>!Object.hasOwn(request,'reasoning_effort') && !Object.hasOwn(request,'reasoning')));
|
||||
assert.ok(x.routes.every(request=>request.path===route.path));
|
||||
});
|
||||
|
||||
test('HTTP 503 before streaming retries the selected route and keeps it for the next turn',async t=>{
|
||||
const selection={model:{id:'qa',protocol:'openai-chat'},candidates:[chatRoute,responsesRoute]};
|
||||
const x=await setup((_payload,n)=> n===1
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user