feat(chat_models): Enable tool calling for ChatMLX #318
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #308
This PR creates end-to-end tool-calling support for ChatMLX, allowing it to correctly use tools with compatible models running locally on Apple Silicon.
Context and History
This is a new, comprehensive approach to resolving #308 (assigned by @mdrxy). This work supersedes the previous attempt in PR #133, which was confirmed to be non-functional and is now stale with unresolved conflicts. This new implementation is fully functional, follows LangChain Core conventions, and is covered by extensive testing.
Technical Implementation
The solution is broken down into three main parts:
Prompt Formatting: The _to_chat_prompt method has been updated to accept a tools argument, which is then passed to the tokenizer's apply_chat_template. This ensures the model receives tool definitions in the correct format, enabling it to generate tool-call responses.
Response Parsing: The _to_chat_result method has been completely overhauled with a dual-strategy parsing approach:
It first checks for structured tool call data in generation_info, leveraging a model's native tool-calling capabilities when available.
If no native tool calls are found, it falls back to a ReAct-style text parser (Action: / Action Input:) to extract tool calls from the raw text, ensuring compatibility with a wide range of models.
It correctly uses langchain_core helpers to create ToolCall and InvalidToolCall objects.