diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 735a339..399ec37 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -687,6 +687,17 @@ const textOf = (c) => (typeof c === "string" ? c : blocksOf(c).filter((b) => b.t // blocks, an assistant's tool calls as tool_calls, results as tool turns by // tool_call_id. A tool turn holds text only, so the images a tool returned // follow in a user turn — the start of the user's own when one comes next. +// +// Qoder turns the whole request away when a tool turn answers no call of the +// turn before it ("Messages with role 'tool' must be a response to a +// preceding message with 'tool_calls'"), where another API takes the same +// conversation. A client's history reaches here with such a turn because it +// dropped the id: either the call lost it, so the result names one no call +// has, or the result kept none. Both are filled in rather than dropped — a +// call without an id is given one, and the results after it take the ids it +// went out with in order, which is the pairing a dropped id means. Only a +// result with no call of its turn left to answer becomes text in the user's +// own turn, so the words the tool returned stay with the conversation. function qoderMessages(msgs) { const out = [] const names = {} @@ -695,31 +706,64 @@ function qoderMessages(msgs) { if (seen.length) out.push({ role: "user", content: seen }) seen = [] } - for (const m of msgs) { + // turn is the assistant turn being answered: the calls no result has + // answered yet, in the order they were made, and the ones a result after + // it names (kept), which a result whose id was lost must not take. + let turn = null + const asText = (txt, ims) => { + const said = txt.trim() + if (!said && !ims.length) return + if (seen.length) seen.push({ type: "text", text: "\n\n" }) + if (said) seen.push({ type: "text", text: said }) + seen.push(...ims) + } + for (const [i, m] of msgs.entries()) { if (m.role === "system" || m.role === "developer") continue + if (m.role === "user") turn = null if (m.role !== "user" && m.role !== "tool") showSeen() if (m.role === "tool") { let txt = textOf(m.content) const ims = Array.isArray(m.content) ? m.content.filter((p) => p?.type === "image_url").map(imageBlock).filter(Boolean) : [] + const named = String(m.tool_call_id ?? "").trim() + // A result naming a call of this turn answers it; one whose id the + // client lost — none, or one no call here has — answers the earliest + // call still open that no other result names, which is the order the + // calls were made in. + const at = named ? turn?.open.findIndex((id) => id === named) ?? -1 : -1 + const pick = at >= 0 ? at : turn ? turn.open.findIndex((id) => !turn.kept.has(id)) : -1 + if (pick < 0) { + asText(txt, ims) + continue + } + const answered = turn.open.splice(pick, 1)[0] if (ims.length) { - let of = "tool call " + m.tool_call_id - const name = names[m.tool_call_id] || m.name + let of = "tool call " + answered + const name = names[answered] || m.name if (name) of = `${name} (${of})` seen.push({ type: "text", text: `[From the result of ${of}:]` }, ...ims) const note = ims.length === 1 ? "[The tool returned an image; it follows in the next message.]" : `[The tool returned ${ims.length} images; they follow in the next message.]` txt = txt.trim() ? txt + "\n\n" + note : txt + note } - out.push({ role: "tool", tool_call_id: m.tool_call_id, content: txt }) + out.push({ role: "tool", tool_call_id: answered, content: txt }) continue } if (m.role === "assistant" && m.tool_calls?.length) { + // a call the client sent without an id gets one, so its result can + // answer it instead of being turned into text const calls = m.tool_calls.map((c) => { - const id = c.id || "call_" + hexID() + const id = String(c.id ?? "").trim() || "call_" + hexID() names[id] = c.function?.name const args = c.function?.arguments return { id, type: "function", function: { name: c.function?.name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) } } }) out.push({ role: "assistant", content: textOf(m.content), tool_calls: calls }) + const open = calls.map((c) => c.id) + const kept = new Set() + for (let j = i + 1; j < msgs.length && msgs[j].role === "tool"; j++) { + const id = String(msgs[j].tool_call_id ?? "").trim() + if (open.includes(id)) kept.add(id) + } + turn = { open, kept } continue } let blocks = blocksOf(m.content) @@ -727,6 +771,8 @@ function qoderMessages(msgs) { if (!blocks.length) continue if (m.role === "user" && seen.length) [blocks, seen] = [[...seen, ...blocks], []] out.push({ role: m.role, content: blocks }) + // a result after the assistant's own words answers no call before it + turn = null } showSeen() return out @@ -1928,4 +1974,4 @@ export const QoderAuthPlugin = makePlugin(SITES.qoder) export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"]) // for tests -export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, SITES, decodeBody, events } +export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, SITES, decodeBody, events } diff --git a/packages/qoder/tool-pairing.test.mjs b/packages/qoder/tool-pairing.test.mjs new file mode 100644 index 0000000..6ee331d --- /dev/null +++ b/packages/qoder/tool-pairing.test.mjs @@ -0,0 +1,142 @@ +// Qoder refuses a whole request whose tool result answers no call before it +// ("Messages with role 'tool' must be a response to a preceding message with +// 'tool_calls'"), where another API takes the same conversation. A client's +// history reaches qoderMessages with such a result when it dropped an id, so +// the pairing is filled in rather than left broken. + +import { describe, expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const { qoderMessages } = _internal + +const call = (id, name = "read_file") => ({ + role: "assistant", + content: "", + tool_calls: [{ ...(id === undefined ? {} : { id }), type: "function", function: { name, arguments: "{}" } }], +}) + +const result = (id, content = "ok") => ({ role: "tool", ...(id === undefined ? {} : { tool_call_id: id }), content }) + +// orphaned says which tool turns answer no call of the turn before them. +const orphaned = (out) => { + const open = new Set() + const bad = [] + for (const m of out) { + if (m.role === "assistant" && m.tool_calls?.length) { + open.clear() + for (const c of m.tool_calls) open.add(c.id) + continue + } + if (m.role === "tool") { + if (!open.has(m.tool_call_id)) bad.push(m.tool_call_id) + open.delete(m.tool_call_id) + continue + } + if (m.role === "user") open.clear() + } + return bad +} + +const callIds = (out) => out.filter((m) => m.tool_calls).flatMap((m) => m.tool_calls.map((c) => c.id)) +const resultIds = (out) => out.filter((m) => m.role === "tool").map((m) => m.tool_call_id) +const textOf = (out) => JSON.stringify(out.filter((m) => m.role === "user")) + +describe("a tool result whose call lost its id", () => { + test("is paired with the call, and both carry one id", () => { + const out = qoderMessages([{ role: "user", content: "read it" }, call(undefined), result("c1")]) + expect(orphaned(out)).toEqual([]) + expect(callIds(out)).toHaveLength(1) + expect(resultIds(out)).toEqual(callIds(out)) + }) + + test("answers the call when neither kept an id", () => { + const out = qoderMessages([{ role: "user", content: "read it" }, call(undefined), result(undefined, "myhost")]) + expect(orphaned(out)).toEqual([]) + expect(resultIds(out)).toEqual(callIds(out)) + // the output stays a tool turn, not words in the user's own + expect(out.filter((m) => m.role === "tool")[0].content).toBe("myhost") + }) + + test("answers a turn's calls in the order they were made", () => { + const out = qoderMessages([ + { role: "user", content: "both" }, + { role: "assistant", content: "", tool_calls: [ + { id: "a", type: "function", function: { name: "f", arguments: "{}" } }, + { id: "b", type: "function", function: { name: "g", arguments: "{}" } }, + ] }, + result(undefined, "A"), + result(undefined, "B"), + ]) + expect(orphaned(out)).toEqual([]) + expect(resultIds(out)).toEqual(["a", "b"]) + }) +}) + +test("a result naming a call of its turn still answers that call", () => { + const two = { + role: "assistant", + content: "", + tool_calls: [ + { id: "a", type: "function", function: { name: "f", arguments: "{}" } }, + { id: "b", type: "function", function: { name: "g", arguments: "{}" } }, + ], + } + const out = qoderMessages([{ role: "user", content: "hi" }, two, result("b", "B"), result("a", "A")]) + expect(orphaned(out)).toEqual([]) + // each result keeps the call it named, whatever order they come in + expect(resultIds(out)).toEqual(["b", "a"]) + expect(out.filter((m) => m.role === "tool").map((m) => m.content)).toEqual(["B", "A"]) +}) + +test("a result with no call left to answer is carried as text, not sent as a tool turn", () => { + const out = qoderMessages([{ role: "user", content: "hi" }, result("gone", "the words")]) + expect(out.filter((m) => m.role === "tool")).toHaveLength(0) + expect(textOf(out)).toContain("the words") +}) + +test("a well-formed history is unchanged", () => { + const msgs = [{ role: "user", content: "hi" }, call("c1"), result("c1", "done")] + const out = qoderMessages(msgs) + expect(callIds(out)).toEqual(["c1"]) + expect(resultIds(out)).toEqual(["c1"]) + expect(out.filter((m) => m.role === "tool")[0].content).toBe("done") +}) + +// #277's table, row 2: the call lost its id and the result names c1 +test("#277: a call missing its id still gets the result naming c1", () => { + const out = qoderMessages([{ role: "user", content: "hi" }, call(undefined), result("c1", "myhost")]) + expect(orphaned(out)).toEqual([]) + const tools = out.filter((m) => m.role === "tool") + expect(tools.map((m) => m.content)).toEqual(["myhost"]) + expect(resultIds(out)).toEqual(callIds(out)) +}) + +test("a result that lost its id doesn't take the call another result names", () => { + const two = { + role: "assistant", + content: "", + tool_calls: [ + { id: "a", type: "function", function: { name: "f", arguments: "{}" } }, + { id: "b", type: "function", function: { name: "g", arguments: "{}" } }, + ], + } + const out = qoderMessages([{ role: "user", content: "hi" }, two, result("lost", "B"), result("a", "A")]) + expect(orphaned(out)).toEqual([]) + expect(out.filter((m) => m.role === "tool").map((m) => [m.tool_call_id, m.content])).toEqual([["b", "B"], ["a", "A"]]) +}) + +test("a result after the assistant's own words is carried as text", () => { + const two = { + role: "assistant", + content: "", + tool_calls: [ + { id: "a", type: "function", function: { name: "f", arguments: "{}" } }, + { id: "b", type: "function", function: { name: "g", arguments: "{}" } }, + ], + } + const out = qoderMessages([{ role: "user", content: "hi" }, two, result("a", "A"), { role: "assistant", content: "so far" }, result("b", "late")]) + // a tool turn must follow the turn with its call, not the assistant's words + const at = out.findIndex((m) => m.role === "assistant" && !m.tool_calls) + expect(out.slice(at + 1).filter((m) => m.role === "tool")).toHaveLength(0) + expect(textOf(out)).toContain("late") +})