Skip to content

Add tool-call id round-trip for OpenClaw / Hermes-style tool calling - #246

Closed
ronaldmannak wants to merge 2 commits into
ml-explore:mainfrom
ronaldmannak:toolcall-id
Closed

ronaldmannak wants to merge 2 commits into
ml-explore:mainfrom
ronaldmannak:toolcall-id

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

Multi-turn tool calling needs each tool result to reference the call it answers. This PR adds an optional id end-to-end.

Calling application supplies its own id (e.g. a UUID) and threads it through ToolCall(id:, function:) and Chat.Message.tool(_:id:).

All new fields default to nil and all new initializer parameters have nil defaults to maintain compatibility.

Example:

// 1. Model generates a turn that ends in a tool call.
//    ToolCallProcessor parses it; today id is always nil because no parser
//    extracts one from model output.
let parsed = processor.toolCalls.first!
//   ToolCall(id: nil, function: .init(name: "get_weather",
//                                     arguments: ["location": .string("Paris")]))

// 2. App synthesizes a correlation id and runs the tool.
let callId = UUID().uuidString
let result = try await runTool(parsed.function)   // e.g. "{\"tempC\":18}"

// 3. Build the next turn. The id threads from the assistant echo
//    (tool_calls[*].id) to the tool result (tool_call_id), so the model
//    can match the result to the call.
let nextTurn: [Chat.Message] = [
    .assistant("", toolCalls: [
        ToolCall(function: parsed.function, id: callId)
    ]),
    .tool(result, id: callId),
]

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@aleroot

aleroot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

I’m hesitant about this PR. The API makes id look like a generic app-supplied string, and the PR description suggests UUIDs, but tool-call IDs are not uniformly free-form across templates. For example, Mistral’s protocol requires IDs for V3+ tokenization, and some Mistral chat templates expect very specific ID shapes. So I think we should treat this as a model/template-specific transport field, not as a universally safe UUID slot.
A better approach, I think, would be to avoid putting this burden directly on the generic Chat.Message API until we have a clearer abstraction for tool-call history.

At minimum, this PR should not recommend UUIDs as the default pattern, and it should include a tokenizer-template smoke test proving that the generated tool_calls / tool_call_id history is accepted by at least one real template.

This also seems related to my open pull request #205. That PR keeps tool-call handling in the parser/processor layer, where we know the active tool-call format and can use the provided tool schemas to decide whether emitted JSON is actually a tool call.

I think that is the safer direction here too. Tool-call IDs are not purely generic metadata; they can be constrained by the model family or tokenizer chat template. So if we add ID support, I’d expect it to preserve parser-provided IDs first, validate or synthesize IDs according to the active format/template where needed, and only then expose a higher-level history API.

Right now this feels like exposing an OpenAI-shaped field in the generic chat API without enough guarantees that it is correct for the model family actually being used. @davidkoski what do you think of it?

@ronaldmannak

Copy link
Copy Markdown
Contributor Author

@aleroot Thanks for the detailed review. I think I understand the concerns as:

  1. Tool-call IDs are not universally free-form; some model/template families constrain the ID shape.
  2. Some templates include and validate tool-call IDs, while others ignore them or do not serialize them.
  3. ID generation/preservation probably belongs closer to the parser/processor or model-template layer, rather than being presented as a generic id in Chat.Message.

That makes sense. I was thinking of this mainly as the history-correlation field needed to echo an assistant tool call back with the corresponding tool result, but I agree the PR description should not recommend UUID().uuidString as a default. I can remove that guidance.

On Mistral specifically: the Tokenizer V3 docs show the assistant tool call carrying an id and the tool result echoing it as call_id. In the current mlx-swift-lm code, we do have Mistral3 / .mistral tool-call support, but the parser does not preserve IDs today. The [CALL_ID]... path is recognized only enough to strip it from the function name, and the parsed ToolCall still reaches the app with id == nil. So I agree parser-provided IDs should be preserved first.

Where I’m less sure is the final public API shape. Even if ID creation/validation is format-aware, the app still needs some structured way to send the result back with the matching call ID. That might be Chat.Message, or it might be a more explicit tool-result history type. I’m fine changing the API direction if there is a preferred abstraction.

Re #205, I also opened #214 recently, and I think these are related pieces of a broader response-parsing problem. Gemma 4 and GPT-oss are good examples of models with richer response formats that the current code does not handle well, and that seems to be outside the scope of #205. Since tool-call IDs need parser-level preservation for formats like Mistral, maybe this is a good moment to decide whether IDs should be added as part of a more complete response-parsing abstraction rather than only as fields on Chat.Message.

I know @angeloskath had, or will soon have, a call about response parsing, so it may be worth aligning this PR with that direction before locking in the public API.

@davidkoski

Copy link
Copy Markdown
Member

Where are we on this one? I don't think Angelos has anything new on the mlx-lm side (I could be wrong). I have wanted to think through how we could integrate various types of response handling but haven't had the time. If this is a missing feature it seems like it might be worth getting in even if we have a new way to implement it a few months down the road.

Thoughts?

@aleroot

aleroot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@ronaldmannak @davidkoski I am sorry but I totally forgot about this pull request and today I have opened this one: #360 . The id is indeed necessary, the id is indeed necessary, especially for multi-turn tool calling where the tool result needs to be linked back to the assistant tool call it answers.

@ronaldmannak if you want to look at my approach and adapt this PR, or if we prefer to move forward with #360, either is fine with me. The important thing is that we converge on one API shape and have the id implemented.

@ronaldmannak

Copy link
Copy Markdown
Contributor Author

Thanks for the follow-up @davidkoski and @aleroot.

I think the best way forward is to close this PR and use #360 as the foundation, since it seems to model and enforce message correctness better.

That said, I think #360 still needs one follow-up improvement: missing tool-call IDs should be normalized/generated before the calls are exposed to the caller.

Suggested behavior:

if parsedToolCall.id == nil {
    parsedToolCall.id = generateToolCallID()
}

The generated ID should then stay attached to the assistant ToolCall, and callers should use that same ID when appending the corresponding tool-result message.

It may also be worth adding tests for:

  • preserving provider/model-supplied tool-call IDs;
  • generating IDs for parsed tool calls that do not include one;
  • ensuring generated IDs are distinct for multiple tool calls in one assistant turn;
  • serializing tool-result messages with the matching tool_call_id;
  • preventing or detecting duplicate IDs in a single assistant turn;
  • preventing orphan tool-result messages that reference no prior assistant tool call.

I'm closing this PR and will copy and paste this message in #360 as well

davidtai pushed a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants