Repository navigation
add local tools to self-hosted providers - #8630
mahiatlinux wants to merge 21 commits into
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f20ea1118
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try: | ||
| chunk = json.loads(data_str) | ||
| except (json.JSONDecodeError, ValueError): | ||
| return [] |
There was a problem hiding this comment.
Surface malformed provider stream frames
When a self-hosted server or intermediary emits a malformed data: frame, this parser silently discards it and leaves turn.failed false. A corrupted content or error frame can therefore become a partial or empty response followed by a successful [DONE], rather than notifying the client that the upstream stream failed; mark the turn failed and emit an error (or otherwise propagate the malformed frame) instead of treating parse failure as no data.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Malformed JSON is outside the OpenAI SSE contract. Valid provider error frames are already surfaced; forwarding corrupt data would break the frontend parser rather than recover the response.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 84907a40f2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return await _select_request_tools( | ||
| payload, | ||
| tools_on = payload.enable_tools is True, |
There was a problem hiding this comment.
Normalize full access before selecting external tool schemas
When an API client uses the documented permission_mode="full" without also setting bypass_permissions=true, this call selects the ordinary sandboxed Python/terminal schemas because _select_request_tools checks only payload.bypass_permissions; the loop later normalizes full to bypass mode and executes those tools unsandboxed. Fresh evidence in the current tree is that _resolve_permission_mode still performs that later normalization while this selection receives the unnormalized payload, so the earlier full-access-schema finding remains applicable despite the claimed fix.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible at 84907a4. ChatCompletionRequest._fold_full_permission_into_bypass (studio/backend/models/inference.py:1613) is a model_validator(mode="after"), so permission_mode="full" sets bypass_permissions=True at construction, before _external_local_tools or any route guard reads it. Verified: ChatCompletionRequest(model="m", messages=[...], permission_mode="full").bypass_permissions is True, so _select_request_tools already applies apply_full_access_tool_descriptions.
| def _invoke(output_callback: Callable[[str], None], call = decision) -> str: | ||
| kwargs: dict[str, Any] = { | ||
| "cancel_event": cancel_event, | ||
| "timeout": effective_timeout, | ||
| "session_id": session_id, | ||
| "thread_id": thread_id, | ||
| "rag_scope": rag_scope, | ||
| "disable_sandbox": bypass_permissions, | ||
| } | ||
| if accepts_output_callback(execute_tool): | ||
| kwargs["output_callback"] = output_callback | ||
| return execute_tool(call.tool_name, call.arguments, **kwargs) |
There was a problem hiding this comment.
Cap repeated external knowledge-base searches
When an external model repeatedly paraphrases search_knowledge_base queries, the controller's exact-duplicate guard does not stop them and this path executes every request up to the overall 25-iteration default. Both existing local loops cap RAG searches at RAG_MAX_SEARCHES_PER_TURN (three) and return RAG_SEARCH_CAP_NUDGE afterward to prevent runaway retrieval. Apply the same cap here so enabling RAG for self-hosted providers cannot cause substantially more retrieval work and latency than the other tool runtimes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is a latency and cost guard, not a correctness defect: every search still returns real passages, and max_tool_iterations already bounds the turn. Nothing is executed wrongly, dropped or lost, so it stays out of a review pass scoped to correctness bugs.
The local tool loop over self-hosted providers diverged from the GGUF, safetensors and Codex loops in four ways: - It never called build_rag_autoinject, so attached-document RAG supplied no passages before the first provider turn even though the tool nudge tells the model that relevant passages are provided automatically. A model that answers without calling search_knowledge_base returned an ungrounded result. - With continue_final_message it appended the generated assistant turn after the resumed partial, giving two consecutive assistant messages. append_assistant_turn merges them, as the other loops do, so role alternation holds on vLLM and llama.cpp templates. - last_reprompt_text survived a real execution, so a model repeating its pre-tool intent lost the one post-tool action nudge the loop budgets separately. - _merge_usage kept only prompt/completion/total, dropping prompt_tokens_details.cached_tokens and the reasoning slice the frontend and pricing read. Details are now summed alongside the totals. chat-adapter.ts gated the local-runtime payload on Search or Code only, so a RAG-only or MCP-only turn never sent auto_heal_tool_calls and the backend defaulted it to true against the user's setting.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3093ed7de
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Four fixes across the external tool loop and the provider registry: - The loop built its controller and text-call allowlist from the raw tools list while ExternalProviderClient.stream_chat_completion sends neutralize_tool_descriptions(tools), which drops any tool whose name carries control markup. A model emitting that name from user text or prior context could execute a tool deliberately withheld from the catalog. The loop now sanitizes first, matching safetensors_agentic.py (unslothai#7066). - asyncio.to_thread cannot stop its worker, so cancelling mid-tool left next() running while the finally called tool_stream.close(), raising ValueError: generator already executing and skipping the generator cleanup. The step future is now retained, awaited through asyncio.wait so cancellation leaves it pending, and drained before the close. Same reasoning as _drain_pending_next_task in routes/inference.py. - A provider error frame returned early past both _close_provisional_cards calls, leaving a card the frontend never resolves whenever a large argument payload had already opened one. - chat-providers-dialog.tsx now filters the registry on `hidden` instead of its own qwen exclusion list, so the Qwen entry needs the flag or it appears in the Connections picker.
|
@codex review |
|
Thanks for building on the provider-level |
|
Thanks, the |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d7f7bebed5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // the pill needs the connection's local-tools opt-in, else the click explains why. | ||
| const externalLocalTools = useExternalLocalTools(); | ||
| const setLocalToolsNotice = useChatRuntimeStore( | ||
| (s) => s.setLocalToolsNoticeProvider, | ||
| ); | ||
| const localToolsOptInMissing = | ||
| externalLocalTools.supported && !externalLocalTools.enabled; |
There was a problem hiding this comment.
Apply the local-tools opt-in gate to the tools menu
When a self-hosted connection supports local tools but has not opted in, this hook makes the visible Search/Code pills clickable so they can open the new notice, but the single-chat ComposerToolsMenu still computes its disabled state only from supportsTools and does not use this notice state. Its Web search and Code rows therefore remain greyed out with no explanation or route to settings, unlike both the pills and the compare composer’s tools menu. Reuse the same supported/enabled gate and notice handler in ComposerToolsMenu.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A greyed row without an explanatory route is a UI polish gap, not a correctness defect: the gate itself is right, nothing runs that should not, and no request content changes. Out of scope for a pass limited to correctness bugs.
The tool loop created its own cancel event, so nothing registered it in _CANCEL_REGISTRY. Where a proxy swallows the browser's fetch abort (the Colab path), Stop only arrives as a POST to /inference/cancel, which found no bucket and left a python, terminal or MCP call running until its timeout. The route now owns the event, passes it in, and tracks it through _TrackedCancel under cancel_id and session_id, matching the Codex branch. providerStudioToolsEnabled required providerModelSupportsStudioTools to be exactly true, but that returns null whenever the registry capability cache is empty: before /api/providers/registry resolves, after local storage is cleared, or when the request fails. supportsProviderLocalTools already falls back to the static self-hosted set in that case, so an opted-in vLLM or Ollama connection showed Local tools as supported while chat-adapter.ts sent no tool payload at all. The gate now uses the same fallback, and a hosted provider still stays off until the registry loads.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd86444261
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
_fold_full_permission_into_bypass only folds confirm_tool_calls=true into "ask" for requests without provider routing, so a self-hosted request that sets the flag and omits permission_mode reached the loop unset and resolved to "auto". That prompts only on classifier-flagged calls, letting ordinary python, terminal and MCP calls run unapproved despite the explicit opt-in. The route now resolves the legacy pair before entering the loop. Two follow-ups to the catalog sanitization added in d7f7beb: - The client now receives the already-sanitized list as both its original and safe catalog, so it can no longer downgrade a tool_choice forcing a dropped tool. The loop reconciles the forced choice against the pre-sanitization catalog instead, keeping the request from naming a function absent from tools. - A suppressed duplicate marked its call id resolved without emitting tool_end, so _close_provisional_cards skipped an early card that no execution would ever close. The id is left unresolved for the helper to close, as the GGUF loop does.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8858a552b4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Follow-ups to the cancel wiring added in dd86444: - The loop never read the event the route now registers, so a Stop that arrived as a POST left it generating: it would finish the current provider turn and start the next. It is checked at the turn boundary, inside the provider stream, and before each pending call, ending the stream cleanly. - _drain_step_task set the event unconditionally, but a raising tool completes its future before the finally runs. The exception is converted into a model-visible error and the loop continues, so marking the whole request cancelled aborted every later tool call. It now signals only a pending worker. Three accumulator fixes: - A function name split across deltas (`web_` then `search`) was overwritten rather than appended, so the controller saw `search`, read it as disabled and forced a final answer instead of running web_search. Names accumulate the way arguments already did, matching llama_cpp.py:16971. - A structured call with no id left both the replayed assistant call and its tool message unidentified. It falls back to `call_<index>`, still replaced when a real id arrives; provisional cards stay gated on a real id, tracked per slot rather than by comparing the id text. - SSE comment keepalives were dropped, unlike the ordinary external path which forwards every non-empty upstream line, so a long prefill could idle out an nginx or tunnel connection. Comments now pass through.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c438e27a1f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| assistant_message: dict[str, Any] = { | ||
| "role": "assistant", | ||
| # markup never replays: the call is carried structurally below. | ||
| "content": strip_tool_markup( | ||
| turn.text, final = True, enabled_tool_names = enabled_tool_names |
There was a problem hiding this comment.
Preserve reasoning on tool-call follow-ups
When a reasoning-capable self-hosted model emits reasoning_content (or Ollama's normalized reasoning) before a tool call, the accumulator stores it in turn.reasoning, but this replayed assistant message copies only visible content and tool calls. The next provider request therefore loses the reasoning field that reasoning-aware chat templates consume, which can cause the post-tool turn to be rejected or templated differently; include the accumulated reasoning in the assistant tool-call message.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible as a defect. No peer loop replays reasoning: llama_cpp.py:17668 and safetensors_agentic.py build the assistant turn from content plus tool_calls only, and the Codex loop carries extra_content instead. vLLM also drops reasoning_content on incoming assistant messages (vllm-project/vllm#38488), so sending it would be inert there rather than a fix. Without a template that demonstrably consumes it, adding the field only risks changing prompts that work today.
|
Tested the local tool loop against two real self-hosted endpoints: 1. Ollama ( 2. vLLM ( |
Reverts the name accumulation from c438e27, which was wrong. llama-server re-sends the whole function name each time it grows mid-parse rather than a suffix (common/chat.cpp compute_diffs sets tool_call_delta.name = newf.name), and llama.cpp's own accumulator assigns the name while only appending arguments (tests/test-chat.cpp:1171). Appending turned a name discovered as "web" then completed as "web_search" into "webweb_search", which the controller read as a disabled tool, so the search never ran. The regression test encoded a wire shape no supported server emits and is replaced with the real one. Cancellation, following up on dd86444: - active_generations is both the model-swap guard and the thread-delete cancellation path, so dropping the external stream from it meant deleting a chat no longer stopped its running tools, and they kept writing to the deleted thread's sandbox. Entries now carry local_model, count/cancel_all/ active_thread_ids skip non-local ones, and the external stream registers with local_model=False. The /load 409 stays fixed and thread deletion works again. Three more fixes: - A turn whose only calls were no-ops appends no assistant message, so the nudge landed directly after the user turn. Nudges now merge into a trailing user turn, as does BUDGET_EXHAUSTED_NUDGE. - The replayed assistant content was stripped with the active catalog, so a spent one-shot's rehearsal form replayed as literal markup. It uses the full catalog, matching safetensors_agentic.py. - disable_parallel_tool_use drops every call after the first, but the accumulator still opened provisional cards for them: the UI streamed a second payload and then blanked it. Only the first call opens a card. chat-page.tsx gated the Search and Code pill state on the provider-side builtins, which no self-hosted type has, so an opted-in connection discarded its saved pill state on load and on every provider resync. The gate now includes local tools; defaults are unchanged, since searchOnByDefault was already false there.
|
@codex review |
A denied call runs no tool, so it never decrements remaining_iterations and never reaches the controller. An exchange where the user keeps denying could therefore issue a provider request and an approval prompt indefinitely, ignoring max_tool_calls_per_message. The loop now also counts total turns and stops at max_tool_iterations plus its reserved nudge slots, matching the bounded iteration range the GGUF and safetensors loops already use. Codex raised this after an earlier review pass had flagged the same thing and I rejected it as human-gated. That reasoning missed the point: the budget the caller sets is meant to bound the exchange, and denied turns escaped it entirely. shared-composer.tsx resolved the local-tools opt-in from the global checkpoint via useExternalLocalTools, but General Compare tracks a model per pane. Entering compare from an opted-out self-hosted connection therefore blocked Search and Code for both panes, including hosted ones that never needed the opt-in. The gate no longer applies in compare mode, where each pane's payload is already resolved per model.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
vLLM "infinite generation": not reproducible as of the latest commit Setup: vLLM serving
On the Codex review rounds: I'll take over driving them and work through the items as much time as I can give. |
|
@khalidejaz that is a thorough writeup, thanks. 94 clean runs across both configs plus the raw-SSE control is far better evidence than I could have produced without the hardware. Your commit scan matches my reading. The name-accumulation bug in c438e27 was real but it corrupted the tool name rather than the stop condition, and it was already reverted before the build you tested. The markup changes only ever affected what reached the client, never generation. So nothing in the diff between the two versions plausibly ends a runaway turn, and a transient server artifact is the explanation that fits. Worth noting your One thing to keep in mind if it ever returns: the loop still withholds content from the first tool marker to the end of the turn, so the visible symptom of any non-terminating turn is silence rather than partial text. That is deliberate, but it means "nothing rendered" will not by itself tell you where the problem is. The raw SSE remains the thing to capture. Codex came back clean on |
|
@khalidejaz Hey human here now, thank you for your help. Please keep testing and if anything comes up, please just comment it here, my automated review system will pick it up. thank you! |
|
you are very welcome! love the opportunity. been using unsloth models for months now. gotta pay some back. |
Yeah sorry I had to supersede your first contribution but I had been working on it for a while with a bit more gathered evidence. Thank you so much for the support, it means a lot. |
Appreciate that. And no worries at all. It was a good learning experience. I compared both impls and saw you were right, so I closed mine. I'll keep testing. |
The sidebar advertises Top-K for the self-hosted OpenAI-compat family (vLLM / llama.cpp / Ollama / custom) and the frontend sends it, but the OpenAI-compat request body dropped the value — only the Anthropic path forwarded it — so the control silently had no effect. Forward top_k when set and non-zero (0 = "Off" is never sent, mirroring the Anthropic path's guard). No behavior change for other providers: the field is only present in requests that already carried it.
|
pre-commit.ci retry |
|
@codex review |
|
To use Codex here, create a Codex account and connect to github. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9f488c8958
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ...(localToolRuntimeForThisTurn | ||
| ? { | ||
| ...(sandboxSessionId | ||
| ? { session_id: sandboxSessionId } | ||
| : {}), |
There was a problem hiding this comment.
Send cancel_id with external local tools
Fresh evidence after the cancel-registration fix is that this external local-tool payload still never includes cancel_id, while the Stop handler always POSTs a body containing cancel_id and /api/inference/cancel returns after looking up that key before considering session_id. In a Colab/proxy environment that swallows the fetch abort, pressing Stop therefore only stashes an unknown cancel id and never sets the route's registered event, so Python/terminal/MCP/RAG work can continue until timeout; forward cancel_id: cancelId with these local-tool requests.
Useful? React with 👍 / 👎.
| ...(localToolRuntimeForThisTurn | ||
| ? { | ||
| ...(sandboxSessionId | ||
| ? { session_id: sandboxSessionId } | ||
| : {}), |
There was a problem hiding this comment.
Request usage chunks for external local-tool streams
When this self-hosted local-tool branch runs, the backend loop does aggregate provider usage and emits it as a trailing choices: [] usage chunk, but the proxy drops that chunk unless the request has stream_options.include_usage. The local-model payload sets that flag for the context-usage bar and tok/s readout, while this external local-tool payload does not, so enabling Studio tools on vLLM/Ollama/llama.cpp/custom makes the UI lose prompt/completion totals even when the provider reported them; include stream_options: { include_usage: true } for this local-tool runtime path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e97a71.
Verified against vLLM: the loop emits prompt/completion totals and the UI now displays them.
| return ( | ||
| payload.max_tool_calls_per_message is not None and payload.max_tool_calls_per_message <= 0 | ||
| ) |
There was a problem hiding this comment.
Do not treat zero local budget as client-tool opt-out
When a self-hosted request also supplies its own tools, setting max_tool_calls_per_message=0 only disables Studio's local tool catalog; those client tools are still forwarded in the non-local branch unless tool_choice is none. This return therefore bypasses the confirm_tool_calls rejection even though Studio cannot approve provider-emitted client tool calls, so a request with confirm_tool_calls=true, tools=[...], and max_tool_calls_per_message=0 can still receive unconfirmed tool calls from vLLM/Ollama/custom. Limit the zero-budget opt-out to requests without client tools, or require tool_choice="none" for that case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Zero tool budget must not bypass the confirm gate for client tools
Fixed in 7a663c3.
The local-tools loop runs python/terminal/MCP/RAG on this machine and the backend registers its cancel event under the request's cancel_id, but the external local-tools payload never sent one. The Stop handler posts only cancel_id and /api/inference/cancel returns after that lookup, so in a Colab/proxy environment that swallows the fetch abort, Stop never reached the loop and tools kept running until timeout. Forward cancel_id on the external local-tools envelope so the backend registration and the Stop POST share the same id. The stale comment claiming external cancel ids are never registered is updated: that was true only for the plain passthrough, where nothing runs locally.
The loop aggregates provider usage and emits a trailing choices: [] usage chunk, but the proxy drops it unless the request opts in via stream_options.include_usage. The external local-tool payload never set it, so enabling Studio tools on self-hosted connections lost the prompt/completion totals the provider reported. Opt in on the local-tool runtime path so the context-usage bar and tok/s readout populate. Verified against vLLM: the loop emits the usage chunk (prompt/completion totals) and the UI now displays them.
…ient tools _local_tool_loop_opted_out treated a zero max_tool_calls_per_message as a full tool opt-out, even when the request carried its own tools. Those schemas are still forwarded by the passthrough, and Studio cannot confirm provider-emitted calls against them, so a request with confirm_tool_calls, client tools and a zero local budget could receive unconfirmed tool calls from vLLM/Ollama/custom. A zero budget now opts out only when the request has no client tools; tool_choice="none" remains an opt-out either way. Unit coverage in test_permission_mode plus a route-level test asserting the 400.
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…er (#8665) * Studio: run the local tool loop against every capable external provider Studio's tools execute on the Studio host, not on the model, but only one external provider could use them: the gate was a hardcoded provider_type == "openai_codex" in routes/inference.py and again in research_runs.py. Point Studio at your own llama.cpp, vLLM, Ollama or OpenRouter and Search, Code, MCP, Docs and Deep Research all greyed out. Generalise the capability instead of adding a second implementation: - providers.py declares studio_tools per provider type and provider_runs_local_tools() replaces the hardcoded comparison. Hidden entries now reach /registry flagged rather than filtered out, which is why the UI could never learn the self-hosted presets are capable. - The loop moves to core/inference/studio_tool_loop.py behind a Transport protocol. CodexTransport keeps the app-server call; OAICompatTransport wraps ExternalProviderClient.stream_chat_completion, the one function every provider re-yields through. - Self-hosted models often write a call as text instead of emitting structured tool_calls, so the loop feeds content through StreamToolCallHealer, the same bounded buffer the client-tool passthrough uses. Only a partial-signal window is ever withheld and an unparseable block flushes verbatim, so a turn that never terminates renders its text instead of nothing. - Deep Research accepts any capable saved connection. Research hops keep tool_choice "none" and enabled_tools [], so a prompt-injected page in the evidence set still cannot reach python. - response_format now reaches OpenAI-compatible providers at all; JSON mode was silently dropped for every one of them. Anthropic is deliberately excluded: _stream_anthropic never forwards a caller's function-tool schemas, so the loop would advertise a catalog the model never sees. It needs schema plus tool_use/tool_result translation. The local, GGUF, safetensors and MLX paths are untouched -- every hunk in routes/inference.py is inside _proxy_to_external_provider. Codex behaviour is unchanged, and the healer is only constructed when a tool catalog is actually selected. Fixes #7282. Fixes #7761. Also fixes a live bug: chat-runtime-store disarmed Deep Research for any external model id including openai_codex, which the backend and the menu both permit, so Codex users had to re-enable it after every model switch. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: carry the local loops' execution behaviour into the external one The first cut generalised the Codex loop, which never had to deal with a model that writes a call as text, repeats one, or stalls. Everything the llama.cpp and safetensors loops learned about that is now shared here, taken from the work in #8630: - ToolLoopController owns dedup, one-shot withdrawal and the force-final-answer transition, so a repeated call cannot spend the budget twice. - stream_tool_execution streams live stdout with heartbeats, so a long python or terminal call cannot idle the stream out. - The approval card is flushed on its own write before the stream blocks, so Allow and Deny paint immediately in the desktop app. - A stalled model that says what it will do gets one nudge to do it. - Usage is summed and reported once instead of a burst of partial counts. - append_assistant_turn merges a continued partial, and replayed content is stripped of markup since the call replays structurally. Fixes found by testing the above: - An intermediate turn's [DONE] was relayed, so a spec-compliant client stopped before the tool cards and the final answer. - A structured call was dropped unless finish_reason was exactly tool_calls. Ollama and several proxies close with stop, or omit it. A truncated turn (finish_reason length) still never executes. - Argument fragments without an index started a phantom call and ran the real one with empty arguments. - Two distinct calls at one index merged into unparseable JSON. - max_tool_calls_per_message capped what was advertised, not what ran: a provider that called anyway was executed. It is a safety limit, so it now gates execution, per call rather than per turn. - Provider turns are bounded, not just executions. A model asking for tools that can never run cannot trade turns forever. - Call ids are unique for the whole run, so a provider that restarts its numbering cannot put two results under one id. - An empty tool_calls list no longer counts as grammar mode working and disables healing for the rest of the turn. - A call with no id is given one instead of being silently dropped. - The provider stream is closed from this frame rather than left to the async-generator finalisation hook. - Content parts reach the replayed assistant message, not just the client. Compatibility: /api/providers/registry hides the backend-only entries again by default and takes include_hidden=true, so a browser holding a pre-capability bundle sees exactly the list it saw before instead of rendering the self-hosted presets as duplicate options. Also fixes the frontend build: thread.tsx used providerModelSupportsStudioTools without importing it. * Apply ruff formatting * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: carry structured output, budgets and Gemini signatures through the external loop Forward response_format into the native Gemini and OpenAI Responses request shapes so a deep research planning hop still gets JSON mode; Gemini takes a generationConfig responseMimeType and only on a tool-free turn, Responses takes text.format. Keep an explicit max_tool_calls_per_message of 0 meaning disabled instead of falling back to 25, refuse a non-scalar providerType with a 400 rather than a registry TypeError, recompute continue_final_message per turn so a post-tool request no longer resumes a role=tool message, replay each call's Gemini thought signature on the assistant turn, restore round_id on every tool card, and let a verified internal workflow key resolve the run's saved connection. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: stop the external loop on cancel, pair overflow calls, keep hosted images Race the provider read against the cancel flag in OAICompatTransport, so Stop and a model load close the upstream instead of waiting for the next chunk; stream_chat_completion takes no cancel_event and the cancel routes only set the flag, so nothing else could reach the socket. Replay a call that overflowed the tool budget in the assistant message that carries its result, since a role=tool message with no matching tool_call is rejected outright by a strict server. Let the unlimited sentinel keep the local loops' bound rather than a fixed 25-turn headroom that truncated a long run. Forward the provider-hosted tools the loop has no local equivalent for, so the Images toggle still works on a turn that also enables a Studio tool. * Studio: close the tool card the loop announced but then skipped The external loop relays the provider's own tool_calls delta, so the client paints a card for every call the model announces. A call the controller then declines to run (a repeat of one that already succeeded, a disabled tool, a second render_html) emitted no terminal event, so that card kept spinning for the rest of the answer and settled as a tool that ran and returned nothing. Emit a tool_end for it, the same way the budget-exhausted branch already does, and key both on the id the provider streamed: a repeated call is exactly the one the loop renames for the replayed history, so the renamed id belongs to no card. * Studio: scope the research credential path and route research off the saved provider row Authorize the saved-connection path on the Deep Research workflow key alone rather than on any internally minted key: a data-recipe job also holds one and can read provider ids, so the broader check would have let it spend an unrelated saved credential. The workflow name is set by Studio at mint time and read back from the stored key row. Validate the research connection's capability on the saved provider type and persist it, instead of comparing it to the client's UI label. A legacy custom connection still stored as backend type openai reports custom, vllm or ollama in the UI, so the equality check refused a connection the chat route drives. * Studio: fix the upgrade and integrity gaps found reviewing the external tool loop Review of the external-provider tool loop turned up several things that were either wrong before this branch or introduced by it. Each one is pinned by a test that fails without the fix. A provider endpoint could forge Studio's own tool cards. The loop writes its tool_start / tool_end frames onto the same SSE stream it relays provider chunks on, and the client tells them apart by shape, so an endpoint could paint a completed python card, sourced local, for code that never ran. base_url is user-configurable, so this needed a boundary: provider lines are stripped of Studio's control vocabulary at every relay site. The pre-change bundle asks for provider-hosted tools as enable_tools plus enabled_tools ["web_search", "code_execution"], which the widened gate captured, dropping hosted code_execution and silently swapping hosted search for local. Providers that run builtins themselves now declare hosted_tools in the registry, and a request naming only those stays on the hosted passthrough. The Code pill keeps a connection's own sandbox rather than relocating execution to this machine as a side effect of an update. A truncated turn discarded a healed tool call, and because promotion strips the markup from the relayed text, the user lost the call and the text describing it. The healer now records the promoted span so a discarded call releases what the model actually wrote. A budget-exhausted call appended a role=tool message with no matching assistant tool_calls entry, which OpenAI, DeepSeek and strict vLLM reject as invalid history, and closed a UI card that was never opened. Durable research compared the saved row's provider type against the type the client sent. Self-hosted connections are stored as openai and surfaced as llama_cpp, vllm, ollama or custom, so that check rejected exactly the connections the path exists to serve. It validates the saved row now. The saved-credential exception is scoped to the Deep Research workflow key rather than to any internally minted key, so a data-recipe subprocess key cannot spend a saved cloud credential. Pill state keyed on hosted builtins, so a self-hosted connection dropped the user's saved Search and Code preference on every reload and sent enable_tools: false while the composer left the pills clickable. The schema guard asserted an exact column set, so it failed on any unrelated column main added later. It now asserts what this change actually owns: the pre-existing columns stay readable and the capability is not persisted. * Studio: replay Responses reasoning, converge rolled-back capabilities, keep the resolved model id Three follow-ups from the same review pass. OpenAI's Responses API requires reasoning items to be passed back alongside the function call and its output; omitting them costs accuracy and the prompt-cache hit, and a reasoning item with nothing after it is rejected outright. Studio already captured those items but only the image-generation card read them, so a local tool call dropped them. They are replayed now, re-sanitized because the recorded copy carries a status the API refuses on input, buffered so a trailing reasoning item is never emitted, and carrying encrypted_content for orgs whose ids resolve to nothing. Capability sync only ever wrote rows the registry returned, so a provider that disappeared after a backend rollback kept studio_tools true in localStorage forever. Persisted capabilities are pruned to what the backend still reports. Clearing is the safe direction: an unknown capability reads as null, which every caller treats as not capable. The summed usage chunk reported the model the request asked for. OpenRouter and similar resolve a routing alias to a concrete model and name it on every chunk, which is the more specific answer, so that id wins. * Studio: accept both streamed tool-name dialects, count usage once, stop draining a cancelled tool Streamed tool-call names arrive two ways and the loop handled only one at a time. llama-server re-sends the whole name as it grows, so appending produced webweb_search; OpenAI sends fragments that continue it, so assigning produced _search. Either way the name misses the enabled-tool check and the call silently never runs. A fragment that already starts with what we have is the name resent, anything else continues it. Usage hanging off a chunk that also carries a choice was relayed intact and then counted again in the summed chunk the loop emits at the end, so a client that adds up chunks double-counted the turn. The chunk cannot be withheld wholesale without losing its content, so only the usage block is dropped. A tool that does not watch the cancel event kept being asked for heartbeats after a Stop, holding the answer open. The consumer stops requesting them and lets the existing drain join the worker under its own bounded timeout. * Studio: close the card a truncated provider turn left open A turn that streams tool_call fragments and then stops at finish_reason "length" has already put a card on the client, and the loop is right to refuse a call whose arguments are cut off mid-write. It left that card open for the rest of the response though, so it read as a tool that ran and returned nothing. Close it through the same unrun-call helper the budget and skipped paths use. Structured calls only: a call the healer recovered from text was never streamed, and the released markup span is what tells the user about that one. Also make the leaked-approval-slot assertion order independent. state .tool_approvals._pending is process global, and a sibling module that drives the route through the confirm gate leaves an entry behind, so asserting the whole registry is empty made that test pass or fail on collection order. Compare against the slots the test did not open instead. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: keep a retained hosted tool's result out of the loop's sanitizer ExternalProviderClient strips Studio's control vocabulary from every raw upstream line at the point it arrives, then synthesizes _toolEvent chunks of its own for a provider-hosted tool. The loop sanitized a second time, where a synthesized frame is no longer distinguishable from a forged one, so a hosted image or web-search result was dropped after the provider had already produced and billed it. A transport now declares whether it has already sanitized, and only one that has not is sanitized here. * Studio: offer the Code pill only where code can actually run The pill was enabled from the general Studio-tools flag, so a model on a sandbox-owning provider that cannot use that sandbox, an OpenAI o3 for instance, lit it and restored a stored preference. The placement rule deliberately runs nothing there rather than relocating the work onto the user's machine, so a Code-only send became enable_tools: false and answered without executing anything. Read the pill out of the placement rule itself, which makes it impossible for what the composer offers and what the request carries to disagree. * Studio: enforce tool_choice none, refuse a filtered turn, keep encrypted reasoning tool_choice "none" was advertised outbound but never enforced on the way back, so a provider that emitted a call anyway had it executed. Deep Research sets "none" precisely so the scraped third-party text its hops carry cannot reach python or terminal, which makes this the one place the instruction has to be a rule rather than a hint. A call arriving under "none" is now refused. A turn ending in content_filter was treated as executable. Like length, it means the model never finished saying what it wanted, so the arguments collected so far can be half written. Both are refused now. "stop" deliberately stays executable: llama.cpp and vLLM routinely end a perfectly good tool call with it, and refusing those would disable tool calling on the self-hosted servers this path is for. A pre-existing test asserted the reasoning replay sanitizer strips encrypted_content. It should not: a zero-data-retention org has store=false forced on it, so the item id resolves to nothing server side and the encrypted blob is the only thing carrying the model's reasoning state into the next request. The assertion was an exact dict match whose stated subject was the status field, so it now checks that and leaves the rest alone. * Apply the repo's kwarg-spacing formatter to the new refusal-gate tests * Studio: report a stopped tool honestly, survive nested arguments, skip Gemini image models A tool interrupted by Stop or a disconnect fell through to an empty result, which record_result then reported as a successful call with no output. The transcript claimed the tool ran and produced nothing, when it was abandoned partway and its side effects may already have happened. Cancellation now says so. Deeply nested but syntactically valid JSON in function.arguments raises RecursionError, which is not a ValueError, so it escaped the loop after the provider's tool-call delta had already been relayed and surfaced as a stream-level server error. It is treated as unparseable input like any other decoding failure. Gemini's image models drop the function catalog inside the native translator (text_tools_allowed is false for them), so the provider-wide capability flag was advertising a loop those models cannot participate in: the MCP and Docs pills lit up and the turn completed as though nothing had been selected. The gate is model-aware now and leaves them on the plain proxy. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
211da62 to
a7045a1
Compare
The squash merge of #8665 kept only two trailers, so the four PRs that work was built out of are not attributed anywhere in main's history. Recording them here. #8626 (@khalidejaz) contributed the registry capability and the hidden-entry exposure, down to the provider_runs_local_tools() name. #8630 (@mahiatlinux) contributed the loop internals: the user-turn append, the tool-stream advance and drain, usage merging, the approval flush delay, the budget-exhausted nudge and the streamed tool-name fix, plus a number of its test cases. They also built the merged branch and drove it in a browser against a control worktree, which found several real defects before release, including a truncated turn discarding a healed call together with the text describing it. #7805 (@Etherll) contributed the hosted-provider reach. #7330 (@Souravrajvi0) is the original OpenAI-compatible framing the work started from. Two things were deliberately not taken, and the difference is worth recording: the per-connection framing from #8630 and the studio_tool_execution column from #7805. #8665 shipped a static disclosure instead while widening the capability from four self-hosted types to thirteen. Co-authored-by: Malik Khalid Ejaz <[email protected]> Co-authored-by: Maheswar Kumar <[email protected]> Co-authored-by: Etherl <[email protected]> Co-authored-by: Souravrajvi0 <[email protected]>
) The squash merge of #8665 kept only two trailers, so the four PRs that work was built out of are not attributed anywhere in main's history. Recording them here. #8626 (@khalidejaz) contributed the registry capability and the hidden-entry exposure, down to the provider_runs_local_tools() name. #8630 (@mahiatlinux) contributed the loop internals: the user-turn append, the tool-stream advance and drain, usage merging, the approval flush delay, the budget-exhausted nudge and the streamed tool-name fix, plus a number of its test cases. They also built the merged branch and drove it in a browser against a control worktree, which found several real defects before release, including a truncated turn discarding a healed call together with the text describing it. #7805 (@Etherll) contributed the hosted-provider reach. #7330 (@Souravrajvi0) is the original OpenAI-compatible framing the work started from. Two things were deliberately not taken, and the difference is worth recording: the per-connection framing from #8630 and the studio_tool_execution column from #7805. #8665 shipped a static disclosure instead while widening the capability from four self-hosted types to thirteen. Co-authored-by: Malik Khalid Ejaz <[email protected]> Co-authored-by: Maheswar Kumar <[email protected]> Co-authored-by: Etherl <[email protected]> Co-authored-by: Souravrajvi0 <[email protected]>
|
superseded. #8665 |
What changed
Why this supersedes #8626
This includes the registry wildcard and shared MCP/RAG selection strengths from #8626, then covers the safety and stream behavior that implementation does not:
Fixes #7282. Supersedes #8626 and #7330.
Credit to @khalidejaz for #8626. Its provider-level
studio_toolswildcard and shared_select_request_toolspath were the right architecture for self-hosted MCP and RAG support, and those ideas are incorporated here.Verification