diff --git a/src/message-converter.mjs b/src/message-converter.mjs index 446883a..eecb532 100644 --- a/src/message-converter.mjs +++ b/src/message-converter.mjs @@ -21,6 +21,62 @@ const PRIVATE_IP_PATTERNS = [ /^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) { if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; diff --git a/src/message-converter.test.mjs b/src/message-converter.test.mjs index 4b36e2f..cb36b72 100644 --- a/src/message-converter.test.mjs +++ b/src/message-converter.test.mjs @@ -5,6 +5,10 @@ import { hasImageParts, parseImageUrl, openAiMessagesToAcpBlocks, + normalizeToolChoice, + toolDirectiveBlock, + toolNudgeBlock, + noToolsDirectiveBlock, MAX_IMAGES_PER_REQUEST, } from "./message-converter.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", () => { const modelOption = { id: "model", diff --git a/src/server.mjs b/src/server.mjs index 62a1819..39445db 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -28,6 +28,10 @@ import { messageContentToText, hasImageParts, openAiMessagesToAcpBlocks, + normalizeToolChoice, + toolDirectiveBlock, + toolNudgeBlock, + noToolsDirectiveBlock, } from "./message-converter.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 model = normalizeModel(body.model); + const toolChoice = normalizeToolChoice(body.tool_choice); const toolsCount = Array.isArray(body.tools) ? body.tools.length : 0; const imageCount = hasImageParts(body.messages) ? body.messages.reduce((n, m) => { if (!Array.isArray(m.content)) return n; @@ -236,12 +241,27 @@ async function handleChatCompletions(req, res) { 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) { - 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) { res.setHeader("Content-Type", "application/json"); res.end( @@ -272,10 +292,36 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) { let isFirst = true; 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 = { onAssistantDelta: (delta) => { if (res.writableEnded || finished) return; + if (enforceToolChoice) { + textBuffer += delta; + return; + } const chunk = textChunk({ id: requestId, model: session.detectedModel || "auto", @@ -287,6 +333,8 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) { }, onToolCall: (call) => { if (res.writableEnded || finished) return; + sawToolCall = true; + flushText(); const chunk = toolCallChunk({ id: requestId, model: session.detectedModel || "auto", @@ -298,8 +346,25 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks }) { }, onFinish: async (reason, _usage) => { 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; if (!res.writableEnded) { + if (reason !== "error" || !enforceToolChoice) flushText(); const chunk = finishChunk({ id: requestId, model: session.detectedModel || "auto",