From 0b82ab8f6c134959b309d2464f7bec1532649f93 Mon Sep 17 00:00:00 2001 From: WuJian1421 <1421172736@qq.com> Date: Tue, 20 Oct 2026 22:05:23 +0800 Subject: [PATCH] trae: a tool call history goes back as the turns Trae made, not as text (#257, WuJian1421) Trae accepts an assistant tool_calls turn and a role:"tool" result turn on llm_utils_chat, and answers such a history with native calls; the text-form bridge prompt is dropped. Assistant text folds into the calls turn after it, consecutive calls turns join one list, a nameless call is dropped with its result, and a tool result's images ride a user turn after the run of results (Doubao-Seed doesn't read an image_url in a tool turn). Refs #38. Run at the reviewed head d5d755a, merged with #260 and #273 on main 68170b3: bun test in packages/trae 173 pass 0 fail; bun scripts/check.mjs trae ok. Not tried live here (no Trae account); the live runs are the author's (CN and Global, multi-turn, parallel calls) and wangjianjq's on #251. Follow-up on main: an empty result's 4027, a request without tools, and a result answering no call. --- packages/trae/README.md | 30 ++++++-- packages/trae/images.test.mjs | 23 +++++- packages/trae/index.mjs | 126 +++++++++++++++++++++++---------- packages/trae/request.test.mjs | 91 +++++++++++++++++++++--- 4 files changed, 217 insertions(+), 53 deletions(-) diff --git a/packages/trae/README.md b/packages/trae/README.md index 95946d7..b3b13c8 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -122,11 +122,20 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: that fails (an `error` event, or Trae's stream breaking off) ends with the error and `[DONE]`, with no finish. - **Tools:** - - Trae's chat has no turn for a tool call or its result, so the tools are - named twice: - - natively in `tools`, with `parameters` as a JSON string; - - in a system prompt that asks for each call as a - `{"name", "arguments"}` block. + - The tools go natively in `tools`, with `parameters` as a JSON string. + A past call goes back as the turn Trae made it: an assistant + `tool_calls` message carrying it (each call + `{id, type: "function", function_call: {name, arguments}}`) and a + `tool` message after it answering it. Trae answers such a history with + native calls; asked for its calls in text instead — a system prompt + describing a `` block, earlier calls written out as one — + models write them as blocks, and a block the stream cuts short is an + error (plugins#38). Trae takes no two messages of one role in a row, + so an assistant turn's text is folded into the calls turn after it + and consecutive calls turns join one `tool_calls` list. + - A call with no name is dropped, and the `tool` result answering it + with it: Trae requires the name, and an empty `tool_calls` list with a + result naming no call is not a turn it takes. - GLM also writes its own template, `namek v` (a string kept as written, other types read as JSON), and sometimes a whole call into a native call's @@ -152,7 +161,9 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: requested tool but for case or punctuation (`Read`) goes on as the request's (`read`); any other goes on as written, so the agent can say the tool doesn't exist. - - Earlier calls and their results go back in as text. + - Trae requires the message answering a call to follow the call: the + results of parallel calls go out as consecutive `tool` messages, with + nothing between them, or the later ones lose their answer (11148). - Images: Trae's lists mark each model `multimodal` true or false (the Doubao-Seed models, Kimi K3 and K2.6, Qwen 3.7 Plus and MiniMax M3 take images; GLM-5 and DeepSeek V4 don't). A model marked true is listed @@ -162,6 +173,13 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: "[an image, which this model can't see]" in its place. A model whose list hasn't been read is sent its images, unless the fallback list says it takes none. + A tool result's images go in a `user` message after the whole run of + results, not in the `tool` turn: measured on the live endpoint, an + `image_url` part in a `tool` turn reaches Kimi K2.6 but not + Doubao-Seed (it answered "Blue"/"Black" to a red image), while the + user-turn placement is read by both. The results of one turn stay + consecutive — nothing may go between them (11148) — so the images + wait for the last of them. The model list is the account's own, from `/api/ide/v1/batch_get_detail_param`, every function's list in one ask, as diff --git a/packages/trae/images.test.mjs b/packages/trae/images.test.mjs index 29f69e8..c22a677 100644 --- a/packages/trae/images.test.mjs +++ b/packages/trae/images.test.mjs @@ -76,9 +76,28 @@ test("an image alone, a tool's image and two user turns in a row keep every imag { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "shot", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c1", content: [{ type: "text", text: "taken" }, { type: "image_url", image_url: { url: PNG } }] }, ] }, true) - expect(m.map((x) => x.role)).toEqual(["user", "assistant", "user"]) + // a tool result's image rides a user message after the run of results: + // a tool turn's image reaches Kimi but not Doubao, and nothing may go + // between the results of one turn (11148) + expect(m.map((x) => x.role)).toEqual(["user", "assistant", "tool", "user"]) expect(m[0].content).toEqual([{ type: "text", text: "and this" }, { type: "image_url", image_url: { url: PNG } }, { type: "image_url", image_url: { url: "https://example.invalid/b.png" } }]) - expect(m[2].content).toEqual([{ type: "text", text: "Result of shot (call c1):\ntaken" }, { type: "image_url", image_url: { url: PNG } }]) + expect(m[2].content).toEqual([{ type: "text", text: "taken" }]) + expect(m[3].content).toEqual([{ type: "image_url", image_url: { url: PNG } }]) + + // the images of parallel results come out after every result, in order + const p = _internal.traeMessages({ messages: [ + { role: "user", content: [{ type: "text", text: "two shots" }] }, + { role: "assistant", content: null, tool_calls: [ + { id: "c1", type: "function", function: { name: "shot", arguments: "{}" } }, + { id: "c2", type: "function", function: { name: "shot", arguments: "{}" } }, + ] }, + { role: "tool", tool_call_id: "c1", content: [{ type: "image_url", image_url: { url: PNG } }] }, + { role: "tool", tool_call_id: "c2", content: [{ type: "text", text: "second" }, { type: "image_url", image_url: { url: "https://example.invalid/b.png" } }] }, + ] }, true) + expect(p.map((x) => x.role)).toEqual(["user", "assistant", "tool", "tool", "user"]) + expect(p[2].content).toEqual([{ type: "text", text: "" }]) + expect(p[3].content).toEqual([{ type: "text", text: "second" }]) + expect(p[4].content).toEqual([{ type: "image_url", image_url: { url: PNG } }, { type: "image_url", image_url: { url: "https://example.invalid/b.png" } }]) }) test("a fallback model that Trae marks multimodal is sent its images before the list is read", async () => { diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index ee78185..900619c 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -914,29 +914,13 @@ const ugPage = (url) => { } } -// Trae's chat takes text only and has no turn for a tool call or its -// result. The agent's tools are named to it natively and in a system -// prompt that asks for each call as a tagged block; earlier calls and -// their results go in as text. A native call in its answer is taken too. +// A model that writes a tool call as text still writes it, mostly GLM and +// DeepSeek: the blocks are read as the calls they mean (the tools also go +// natively in the body, and a past call is a native turn, so an answer is +// usually native; the text form is read for when it is not). const OPEN = "" const CLOSE = "" -function toolPrompt(tools, choice, parallel) { - const defs = tools.map((t) => { - const f = t.function ?? t - return { name: f.name, description: f.description ?? "", parameters: f.parameters ?? {} } - }) - const lines = [ - "You can call the client's tools, listed below as JSON. They run on the user's machine, not on yours: use no built-in or server tool to reach the user's files.", - `To call a tool, write one block per call and nothing after it: ${OPEN}{"name":"tool_name","arguments":{...}}${CLOSE}. Use an exact tool name and fill arguments from its schema. Then stop and wait: the result comes back in the next message.`, - "A call is not done until its result comes back; don't say it is, and don't repeat a call whose result you have.", - ] - if (parallel === false) lines.push("Call at most one tool at a time.") - if (choice === "required") lines.push("Call a tool before answering.") - else if (choice && typeof choice === "object" && (choice.function?.name || choice.name)) lines.push(`Call the tool ${choice.function?.name || choice.name} before answering.`) - lines.push("Tools:", JSON.stringify(defs)) - return lines.join("\n") -} const partText = (content) => { if (typeof content === "string") return content @@ -970,43 +954,111 @@ const partsOf = (content, sees) => { // the model takes images: Trae's list says so of each model (multimodal), // and a model it says doesn't is sent the placeholder, not the image. function traeMessages(req, sees = false) { - const tools = Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none" ? req.tools : [] const names = new Map() const out = [] - if (tools.length) out.push({ role: "system", text: toolPrompt(tools, req.tool_choice, req.parallel_tool_calls) }) + // dropped is every call id a turn carried but Trae cannot be sent: an + // assistant turn whose calls all lost their name takes its results with it + const dropped = new Set() + // images of tool results, held until the run of results ends: Trae + // takes no message between a call's results, so they cannot go after + // each one — one user message once they are all in + const pending = [] + const flushImages = () => { + if (pending.length) out.push({ role: "user", images: pending.splice(0) }) + } for (const m of req.messages ?? []) { const role = m.role === "developer" ? "system" : m.role let { text, images } = partsOf(m.content, sees) + if (role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length) { + // a past call goes back as the turn Trae made it: an assistant + // tool_calls message, its result in the tool message after it. Trae + // answers such a history with native calls; written out as a + // block in the text it answers in blocks too, and a block + // the stream cuts short ends the turn as an error (plugins#38). + const calls = [] + for (const c of m.tool_calls) { + const name = String(c.function?.name ?? c.name ?? "").trim() + // a call Trae cannot be sent is dropped here; its result goes too + // (an empty tool_calls list and a result naming no call are not a + // turn Trae takes) + if (!name) { + if (c.id != null) dropped.add(String(c.id)) + continue + } + names.set(String(c.id ?? ""), name) + let args = c.function?.arguments ?? c.arguments ?? "{}" + if (typeof args !== "string") { + try { + args = JSON.stringify(args) + } catch { + args = "{}" + } + } + calls.push({ id: String(c.id ?? "call_" + (names.size + 1)), type: "function", function_call: { name, arguments: args } }) + } + if (calls.length) out.push({ role: "assistant", text, images, calls }) + else if (text || images.length) out.push({ role: "assistant", text, images }) + continue + } if (role === "assistant") { - const calls = (m.tool_calls ?? []).map((c) => { - names.set(c.id, c.function?.name) - let args = c.function?.arguments ?? "{}" - try { - args = JSON.parse(args) - } catch {} - return OPEN + JSON.stringify({ name: c.function?.name, arguments: args }) + CLOSE - }) - text = [text, ...calls].filter(Boolean).join("\n") - out.push({ role: "assistant", text }) + flushImages() + out.push({ role: "assistant", text, images }) } else if (role === "tool") { - out.push({ role: "user", text: `Result of ${names.get(m.tool_call_id) || m.name || "the tool"} (call ${m.tool_call_id ?? "?"}):\n${text}`, images }) + const id = String(m.tool_call_id ?? "") + if (dropped.has(id)) continue + // Trae's own result turn: the call it answers, its text as parts + // (an empty one for a result with no text). Its images wait: a + // tool turn's image_url reaches some models (Kimi) and not others + // (Doubao-Seed), so they go in a user message after the whole run + // of results, which every multimodal model reads + if (images.length) pending.push(...images) + out.push({ role: "tool", tool_call_id: id, text }) } else { + flushImages() out.push({ role: role === "system" ? "system" : "user", text, images }) } } - // Trae takes no empty message, nor two of one role in a row; a message of - // an image alone is not empty + flushImages() + // Trae takes no two messages of one role in a row, so an assistant turn is + // folded into the turn after it: text into the calls turn it introduces + // (agents send "let me read" and then the call, and parallel calls split + // over two assistant turns), calls joined into one list. A message of an + // image alone is not empty; tool results are turns of their own, each + // answering its own call. const merged = [] for (const m of out) { const images = m.images ?? [] + if (m.role === "tool") { + merged.push(m) + continue + } + if (m.role === "assistant") { + const last = merged.at(-1) + if (last && last.role === "assistant") { + // fold: text and images join, calls append to the same list + last.text = [last.text, m.text].filter(Boolean).join("\n\n") + last.images = [...(last.images ?? []), ...images] + if (m.calls) last.calls = [...(last.calls ?? []), ...m.calls] + if (!last.text && !last.images.length && !last.calls) merged.pop() + continue + } + if (!m.text && !images.length && !m.calls) continue + merged.push({ role: "assistant", text: m.text, images, ...(m.calls ? { calls: m.calls } : {}) }) + continue + } if (!m.text && !images.length) continue const last = merged.at(-1) if (last && last.role === m.role && m.role !== "system") { last.text = [last.text, m.text].filter(Boolean).join("\n\n") - last.images = [...last.images, ...images] + last.images = [...(last.images ?? []), ...images] } else merged.push({ role: m.role, text: m.text, images }) } - return merged.map((m) => ({ role: m.role, content: [...(m.text ? [{ type: "text", text: m.text }] : []), ...m.images] })) + return merged.map((m) => { + const content = [...(m.text ? [{ type: "text", text: m.text }] : []), ...(m.images ?? [])] + if (m.calls) return { role: "assistant", content: content.length ? content : null, tool_calls: m.calls } + if (m.role === "tool") return { role: "tool", tool_call_id: m.tool_call_id, content: content.length ? content : [{ type: "text", text: "" }] } // results of one turn stay consecutive: nothing may go between them (11148) + return { role: m.role, content } + }) } // nativeTools are the tools as Trae names them: parameters a JSON string diff --git a/packages/trae/request.test.mjs b/packages/trae/request.test.mjs index 4ba1214..e7b96a7 100644 --- a/packages/trae/request.test.mjs +++ b/packages/trae/request.test.mjs @@ -26,7 +26,7 @@ async function chunks(res) { const TOOLS = [{ type: "function", function: { name: "read", description: "Read a file", parameters: { type: "object", properties: { path: { type: "string" } } } } }] -test("the request is the IDE's: its headers, the device, text parts, the tools natively and in the prompt", async () => { +test("the request is the IDE's: its headers, the device, text parts, the tools natively", async () => { f = fakeTrae() f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]])) await ask({ model: "glm-5", max_tokens: 100, tools: TOOLS, messages: [{ role: "system", content: "be brief" }, { role: "user", content: [{ type: "text", text: "hi" }] }] }) @@ -43,24 +43,99 @@ test("the request is the IDE's: its headers, the device, text parts, the tools n expect(b.model).toBe("glm-5") expect(b.max_tokens).toBe(100) expect(b.stream).toBe(true) - expect(b.messages.map((m) => m.role)).toEqual(["system", "system", "user"]) - expect(b.messages[0].content[0].text).toContain("") - expect(b.messages[2].content).toEqual([{ type: "text", text: "hi" }]) + expect(b.messages.map((m) => m.role)).toEqual(["system", "user"]) + expect(b.messages[0].content[0].text).toBe("be brief") + expect(b.messages[1].content).toEqual([{ type: "text", text: "hi" }]) expect(b.tools[0].function.name).toBe("read") expect(typeof b.tools[0].function.parameters).toBe("string") }) -test("tool history goes in as text", () => { +test("tool history goes back as the turns Trae made: a call and its result", () => { const m = _internal.traeMessages({ messages: [ { role: "user", content: "read a" }, { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{\"path\":\"a\"}" } }] }, { role: "tool", tool_call_id: "c1", content: "AAA" }, + { role: "user", content: "and b" }, + ] }) + expect(m.map((x) => x.role)).toEqual(["user", "assistant", "tool", "user"]) + expect(m[1].tool_calls).toEqual([{ id: "c1", type: "function", function_call: { name: "read", arguments: "{\"path\":\"a\"}" } }]) + expect(m[1].content).toBe(null) + expect(m[2]).toEqual({ role: "tool", tool_call_id: "c1", content: [{ type: "text", text: "AAA" }] }) +}) + +test("an assistant turn folds into the calls turn after it, and parallel calls join one list", () => { + // what agents send: a "let me read" turn, then the call + const a = _internal.traeMessages({ messages: [ + { role: "user", content: "read a" }, + { role: "assistant", content: "let me read" }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{\"path\":\"a\"}" } }] }, + { role: "tool", tool_call_id: "c1", content: "AAA" }, + ] }) + expect(a.map((x) => x.role)).toEqual(["user", "assistant", "tool"]) + expect(a[1].content[0].text).toBe("let me read") + expect(a[1].tool_calls.map((c) => c.id)).toEqual(["c1"]) + + // parallel calls split over two assistant turns (magpie#1275) + const b = _internal.traeMessages({ messages: [ + { role: "user", content: "read a and b" }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{\"path\":\"a\"}" } }] }, + { role: "assistant", content: null, tool_calls: [{ id: "c2", type: "function", function: { name: "read", arguments: "{\"path\":\"b\"}" } }] }, + { role: "tool", tool_call_id: "c1", content: "AAA" }, { role: "tool", tool_call_id: "c2", content: "BBB" }, ] }) + expect(b.map((x) => x.role)).toEqual(["user", "assistant", "tool", "tool"]) + expect(b[1].tool_calls.map((c) => c.id)).toEqual(["c1", "c2"]) + expect(b[1].tool_calls[1].function_call).toEqual({ name: "read", arguments: "{\"path\":\"b\"}" }) +}) + +test("a call with no name is dropped, and the result it would answer", () => { + const a = _internal.traeMessages({ messages: [ + { role: "user", content: "do it" }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: " ", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c1", content: "RESULT" }, + { role: "user", content: "next" }, + ] }) + // no empty tool_calls list, and no result naming a call that isn't there; + // the two user turns either side of the dropped pair fold together + expect(a.map((x) => x.role)).toEqual(["user"]) + expect(a[0].content[0].text).toBe("do it\n\nnext") + expect(a.some((x) => x.role === "tool")).toBe(false) + + // a named call beside an unnamed one keeps its own + const b = _internal.traeMessages({ messages: [ + { role: "user", content: "do both" }, + { role: "assistant", content: null, tool_calls: [ + { id: "c1", type: "function", function: { name: "", arguments: "{}" } }, + { id: "c2", type: "function", function: { name: "read", arguments: "{\"path\":\"b\"}" } }, + ] }, + { role: "tool", tool_call_id: "c1", content: "DROPPED" }, + { role: "tool", tool_call_id: "c2", content: "KEPT" }, + ] }) + expect(b.map((x) => x.role)).toEqual(["user", "assistant", "tool"]) + expect(b[1].tool_calls.map((c) => c.id)).toEqual(["c2"]) + expect(b[2].tool_call_id).toBe("c2") +}) + +test("an assistant turn that loses every call keeps its text", () => { + const m = _internal.traeMessages({ messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: "thinking out loud", tool_calls: [{ id: "c1", type: "function", function: { name: "", arguments: "{}" } }] }, + { role: "user", content: "ok" }, + ] }) expect(m.map((x) => x.role)).toEqual(["user", "assistant", "user"]) - expect(m[1].content[0].text).toBe('{"name":"read","arguments":{"path":"a"}}') - expect(m[2].content[0].text).toContain("Result of read (call c1):\nAAA") - expect(m[2].content[0].text).toContain("BBB") + expect(m[1].content[0].text).toBe("thinking out loud") + expect(m[1].tool_calls).toBeUndefined() +}) + +test("a result for a call the history doesn't carry, and two in a row, keep their own turns", () => { + const m = _internal.traeMessages({ messages: [ + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c1", content: "AAA" }, + { role: "tool", tool_call_id: "c2", content: "BBB" }, + ] }) + expect(m.map((x) => x.role)).toEqual(["assistant", "tool", "tool"]) + expect(m[1].content[0].text).toBe("AAA") + expect(m[2].content[0].text).toBe("BBB") }) test("a stream: text, reasoning, a tool block split across events, a native call, usage", async () => {