Skip to content

[MCP] Handle Ollama's deviation from the OpenAI tool streaming spec #3140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions src/huggingface_hub/inference/_mcp/mcp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,16 +286,19 @@ async def process_single_turn_with_tools(
# Process tool calls
if delta.tool_calls:
for tool_call in delta.tool_calls:
# Aggregate chunks into tool calls
if tool_call.index not in final_tool_calls:
if (
tool_call.function.arguments is None or tool_call.function.arguments == "{}"
): # Corner case (depends on provider)
tool_call.function.arguments = ""
final_tool_calls[tool_call.index] = tool_call

elif tool_call.function.arguments:
final_tool_calls[tool_call.index].function.arguments += tool_call.function.arguments
idx = tool_call.index
# first chunk for this tool call
if idx not in final_tool_calls:
final_tool_calls[idx] = tool_call
if final_tool_calls[idx].function.arguments is None:
final_tool_calls[idx].function.arguments = ""
continue
# safety before concatenating text to .function.arguments
if final_tool_calls[idx].function.arguments is None:
final_tool_calls[idx].function.arguments = ""
Comment on lines +293 to +298
Copy link
Preview

Copilot AI Jun 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The check and assignment for function.arguments being None is repeated; consider refactoring this logic into a helper function to reduce duplication and improve maintainability.

Suggested change
if final_tool_calls[idx].function.arguments is None:
final_tool_calls[idx].function.arguments = ""
continue
# safety before concatenating text to .function.arguments
if final_tool_calls[idx].function.arguments is None:
final_tool_calls[idx].function.arguments = ""
self._ensure_arguments_initialized(final_tool_calls[idx].function)
continue
# safety before concatenating text to .function.arguments
self._ensure_arguments_initialized(final_tool_calls[idx].function)

Copilot uses AI. Check for mistakes.


if tool_call.function.arguments:
final_tool_calls[idx].function.arguments += tool_call.function.arguments

# Optionally exit early if no tools in first chunks
if exit_if_first_chunk_no_tool and num_of_chunks <= 2 and len(final_tool_calls) == 0:
Expand Down