feat(api): enforce OpenAI tool_choice contract (required/named/none)
build-and-push / build (push) Successful in 4m59s

- normalizeToolChoice maps OpenAI tool_choice values to internal shapes
- required/named: prepend a mandatory-tool directive block; buffer text
  deltas and only flush when a tool call actually arrives; on plain-text
  turn, retry in-process with a nudge block (max 2 retries) instead of
  emitting the violating text (streaming + non-streaming paths)
- none: prepend a no-tools directive
- unit tests for all new mapping/directive helpers (32 passing)

Verified live against cursor-agent ACP with model=auto: image+required
yields clean tool_calls chunks with no text pollution; follow-up turns
resolve parked MCP tool calls and retry on invalid observations.
This commit is contained in:
Ubuntu
2026-09-27 12:02:40 +00:00
parent 706733fed3
commit b467998ba4
3 changed files with 181 additions and 3 deletions
+56
View File
@@ -21,6 +21,62 @@ const PRIVATE_IP_PATTERNS = [
/^fe80:/i, /^fe80:/i,
]; ];
/**
* Normalize an OpenAI tool_choice value into an internal shape the session
* manager can enforce. Returns null for the default ("auto"/absent).
* @param {any} tc
* @returns {{kind: "none"} | {kind: "required"} | {kind: "named", name: string} | null}
*/
export function normalizeToolChoice(tc) {
if (!tc) return null;
if (tc === "auto") return null;
if (tc === "none") return { kind: "none" };
if (tc === "required") return { kind: "required" };
if (
typeof tc === "object" &&
tc.type === "function" &&
tc.function &&
typeof tc.function.name === "string" &&
tc.function.name
) {
return { kind: "named", name: tc.function.name };
}
return null;
}
/** Prepend-block instructing the model that a tool call is mandatory. */
export function toolDirectiveBlock(toolChoice) {
const target =
toolChoice.kind === "named" ? `the "${toolChoice.name}" client tool` : "one of the available client tools";
const mode = toolChoice.kind === "named" ? `"${toolChoice.name}"` : "required";
return {
type: "text",
text:
`[System]\nAPI constraint: tool_choice is set to ${mode} for this turn. ` +
`You MUST deliver your answer exclusively by calling ${target}. ` +
`A plain-text answer violates the API contract and will be rejected. ` +
`If you already know the result, put it into the tool arguments and call the tool now.`,
};
}
/** Follow-up block for enforcement retries (plain-text answer was rejected). */
export function toolNudgeBlock() {
return {
type: "text",
text:
"[User]\nThe previous answer was rejected: tool_choice requires a function call. " +
"Call the required client tool NOW with your final result. Do not reply with plain text.",
};
}
/** Prepend-block for tool_choice "none". */
export function noToolsDirectiveBlock() {
return {
type: "text",
text: '[System]\nAPI constraint: tool_choice is set to "none" for this turn. Do not call any tools; answer in plain text only.',
};
}
export function messageContentToText(content) { export function messageContentToText(content) {
if (typeof content === "string") return content; if (typeof content === "string") return content;
if (!Array.isArray(content)) return ""; if (!Array.isArray(content)) return "";
+57
View File
@@ -5,6 +5,10 @@ import {
hasImageParts, hasImageParts,
parseImageUrl, parseImageUrl,
openAiMessagesToAcpBlocks, openAiMessagesToAcpBlocks,
normalizeToolChoice,
toolDirectiveBlock,
toolNudgeBlock,
noToolsDirectiveBlock,
MAX_IMAGES_PER_REQUEST, MAX_IMAGES_PER_REQUEST,
} from "./message-converter.mjs"; } from "./message-converter.mjs";
import { pickModelValueId, resolveModelId } from "./session-manager.mjs"; import { pickModelValueId, resolveModelId } from "./session-manager.mjs";
@@ -106,6 +110,59 @@ describe("openAiMessagesToAcpBlocks", () => {
}); });
}); });
describe("normalizeToolChoice", () => {
it("returns null for absent and auto", () => {
assert.equal(normalizeToolChoice(undefined), null);
assert.equal(normalizeToolChoice(null), null);
assert.equal(normalizeToolChoice("auto"), null);
});
it("maps required", () => {
assert.deepEqual(normalizeToolChoice("required"), { kind: "required" });
});
it("maps none", () => {
assert.deepEqual(normalizeToolChoice("none"), { kind: "none" });
});
it("maps named function choice", () => {
assert.deepEqual(
normalizeToolChoice({ type: "function", function: { name: "submit_ttn_extraction" } }),
{ kind: "named", name: "submit_ttn_extraction" }
);
});
it("returns null for unrecognized shapes", () => {
assert.equal(normalizeToolChoice({ type: "function" }), null);
assert.equal(normalizeToolChoice(42), null);
});
});
describe("tool directive blocks", () => {
it("required directive mentions mandatory call", () => {
const b = toolDirectiveBlock({ kind: "required" });
assert.equal(b.type, "text");
assert.match(b.text, /tool_choice is set to required/);
assert.match(b.text, /MUST/);
});
it("named directive mentions the tool name", () => {
const b = toolDirectiveBlock({ kind: "named", name: "submit_result" });
assert.match(b.text, /"submit_result"/);
});
it("nudge block rejects plain text", () => {
const b = toolNudgeBlock();
assert.match(b.text, /tool_choice requires a function call/);
});
it("none directive forbids tools", () => {
const b = noToolsDirectiveBlock();
assert.match(b.text, /"none"/);
assert.match(b.text, /plain text only/);
});
});
describe("pickModelValueId", () => { describe("pickModelValueId", () => {
const modelOption = { const modelOption = {
id: "model", id: "model",
+68 -3
View File
@@ -28,6 +28,10 @@ import {
messageContentToText, messageContentToText,
hasImageParts, hasImageParts,
openAiMessagesToAcpBlocks, openAiMessagesToAcpBlocks,
normalizeToolChoice,
toolDirectiveBlock,
toolNudgeBlock,
noToolsDirectiveBlock,
} from "./message-converter.mjs"; } from "./message-converter.mjs";
import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs"; import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs";
@@ -167,6 +171,7 @@ async function handleChatCompletions(req, res) {
const stream = body.stream === true; const stream = body.stream === true;
const model = normalizeModel(body.model); const model = normalizeModel(body.model);
const toolChoice = normalizeToolChoice(body.tool_choice);
const toolsCount = Array.isArray(body.tools) ? body.tools.length : 0; const toolsCount = Array.isArray(body.tools) ? body.tools.length : 0;
const imageCount = hasImageParts(body.messages) ? body.messages.reduce((n, m) => { const imageCount = hasImageParts(body.messages) ? body.messages.reduce((n, m) => {
if (!Array.isArray(m.content)) return n; if (!Array.isArray(m.content)) return n;
@@ -236,12 +241,27 @@ async function handleChatCompletions(req, res) {
return; return;
} }
await streamSessionTurn({ res, session, requestId, stream, blocks }); // tool_choice enforcement: prepend directive blocks before user content.
if (toolChoice && toolChoice.kind !== "none" && (body.tools || []).length > 0) {
blocks.unshift(toolDirectiveBlock(toolChoice));
} else if (toolChoice && toolChoice.kind === "none") {
blocks.unshift(noToolsDirectiveBlock());
}
await streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice });
} }
async function streamSessionTurn({ res, session, requestId, stream, blocks }) { async function streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice = null }) {
if (!stream) { if (!stream) {
const result = await collectSessionTurn(session, blocks); let result = await collectSessionTurn(session, blocks);
// tool_choice enforcement (non-streaming): retry internally when the
// model answered in plain text despite a required/named tool choice.
if (toolChoice && toolChoice.kind !== "none" && result.finishReason !== "tool_calls" && result.text.trim()) {
for (let attempt = 0; attempt < 2; attempt++) {
result = await collectSessionTurn(session, [toolNudgeBlock()]);
if (result.finishReason === "tool_calls") break;
}
}
if (!res.headersSent) { if (!res.headersSent) {
res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Type", "application/json");
res.end( res.end(
@@ -272,10 +292,36 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
let isFirst = true; let isFirst = true;
let finished = false; let finished = false;
// tool_choice enforcement (streaming): buffer text deltas while a
// required/named choice is active; flush only when a tool call arrives or
// the turn finishes. On plain-text-only turn, retry with a nudge instead
// of emitting the violating text.
const enforceToolChoice = Boolean(toolChoice && toolChoice.kind !== "none");
let textBuffer = "";
let sawToolCall = false;
let enforcementRetries = 0;
const MAX_ENFORCEMENT_RETRIES = 2;
const flushText = () => {
if (!textBuffer) return;
const chunk = textChunk({
id: requestId,
model: session.detectedModel || "auto",
delta: textBuffer,
isFirst,
});
isFirst = false;
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
textBuffer = "";
};
const handlers = { const handlers = {
onAssistantDelta: (delta) => { onAssistantDelta: (delta) => {
if (res.writableEnded || finished) return; if (res.writableEnded || finished) return;
if (enforceToolChoice) {
textBuffer += delta;
return;
}
const chunk = textChunk({ const chunk = textChunk({
id: requestId, id: requestId,
model: session.detectedModel || "auto", model: session.detectedModel || "auto",
@@ -287,6 +333,8 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
}, },
onToolCall: (call) => { onToolCall: (call) => {
if (res.writableEnded || finished) return; if (res.writableEnded || finished) return;
sawToolCall = true;
flushText();
const chunk = toolCallChunk({ const chunk = toolCallChunk({
id: requestId, id: requestId,
model: session.detectedModel || "auto", model: session.detectedModel || "auto",
@@ -298,8 +346,25 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
}, },
onFinish: async (reason, _usage) => { onFinish: async (reason, _usage) => {
if (finished) return; if (finished) return;
// Enforcement retry: plain-text-only turn under required tool choice.
if (
enforceToolChoice &&
!sawToolCall &&
reason === "stop" &&
enforcementRetries < MAX_ENFORCEMENT_RETRIES &&
!res.writableEnded
) {
enforcementRetries += 1;
console.error(
`[chat] id=${requestId} tool_choice enforcement retry ${enforcementRetries}/${MAX_ENFORCEMENT_RETRIES}`
);
textBuffer = "";
session.runTurn([toolNudgeBlock()], handlers);
return;
}
finished = true; finished = true;
if (!res.writableEnded) { if (!res.writableEnded) {
if (reason !== "error" || !enforceToolChoice) flushText();
const chunk = finishChunk({ const chunk = finishChunk({
id: requestId, id: requestId,
model: session.detectedModel || "auto", model: session.detectedModel || "auto",