Repository navigation
Studio: add Anthropic-compatible /v1/messages endpoint - #4981
Conversation
Translate Anthropic Messages API format to/from internal OpenAI format and reuse the existing server-side agentic tool loop. Supports streaming SSE (message_start, content_block_delta, etc.) and non-streaming JSON. Includes offline unit tests and e2e tests in test_studio_run.py.
Support the same shorthand as /v1/chat/completions: enable_tools=true with an optional enabled_tools list uses built-in server tools without requiring full Anthropic tool definitions. session_id is passed through for sandbox isolation. max_tokens is now optional.
Apply _TOOL_XML_RE to content events in both streaming and non-streaming tool paths, matching the OpenAI endpoint behavior.
Adds a non-standard tool_result event between the tool_use block close and the next text block, so clients can see server-side tool execution results. Anthropic SDKs ignore unknown event types.
There was a problem hiding this comment.
Code Review
This pull request introduces support for the Anthropic Messages API by adding a new /messages endpoint and a translation layer to convert between Anthropic and OpenAI formats. The implementation includes Pydantic models for request/response validation, a stateful stream emitter for SSE events, and comprehensive unit and end-to-end tests. Feedback was provided regarding the non-streaming tool-calling path, specifically concerning the ordering of content blocks and the need to reset text tracking state between synthesis turns to ensure correct text extraction.
enable_tools=true runs the existing server-side agentic loop with built-in tools (web_search/python/terminal). A bare tools=[...] field now triggers a client-side pass-through: client-provided tools are forwarded to llama-server and any tool_use output is returned to the caller with stop_reason=tool_use for client execution. This fixes Claude Code (and any Anthropic SDK client) which sends tools=[...] expecting client-side execution but was previously routed through execute_tool() and failing with 'Unknown tool'. Adds AnthropicPassthroughEmitter to convert llama-server OpenAI SSE chunks into Anthropic SSE events, plus unit tests covering text blocks, tool_use blocks, mixed, stop reasons, and usage.
Plumb payload.stop_sequences to all three code paths (server-side tool loop, no-tool plain, client-side passthrough) so Anthropic SDK clients setting stop_sequences get the behavior they expect. The llama_cpp backend already accepted `stop` on both generate_chat_ completion and generate_chat_completion_with_tools; the Anthropic handler simply wasn't passing it. tool_choice remains declared on the request model for Anthropic SDK compatibility (the SDK often sets it by default) but is not yet honored. Log a structured warning on each request carrying a non- null tool_choice so the silent drop is visible to operators.
Align the Anthropic endpoint's sampling surface with /v1/chat/completions. Adds the three fields as x-unsloth extensions on AnthropicMessagesRequest and threads them through all three code paths: server-side tool loop, no-tool plain, and client-side passthrough. The passthrough builder emits "repeat_penalty" (not "repetition_penalty") because that is llama-server's field name; the backend methods already apply the same rename internally.
_anthropic_tool_non_streaming was building the response by appending all tool_use blocks first, then a single concatenated text block at the end — losing generation order and merging pre-tool and post-tool text into one block. It also never reset prev_text between synthesis turns, so the first N characters of each post-tool turn were dropped (where N = length of the prior turn's final cumulative text). Rewrite to build content_blocks incrementally in generation order, matching the streaming emitter's behavior: deltas within a turn are merged into the trailing text block, tool_use blocks interrupt the text sequence, and prev_text is reset on tool_end so turn N+1 diffs against an empty baseline. Caught by gemini-code-assist[bot] review on #4981.
Add a hybrid session-scoped studio_server fixture in conftest.py that feeds base_url / api_key into the existing e2e test functions. Three invocation modes are now supported: 1. Script mode (unchanged) — python tests/test_studio_run.py 2. Pytest + external server — point at a running instance via UNSLOTH_E2E_BASE_URL / UNSLOTH_E2E_API_KEY env vars, no per-run GGUF load cost 3. Pytest + fixture-managed server — pytest drives _start_server / _kill_server itself via --unsloth-model / --unsloth-gguf-variant, CI-friendly The existing _start_server / _kill_server helpers and main() stay untouched so the script entry point keeps working exactly as before. Test function signatures are unchanged — the (base_url, api_key) parameters now resolve via the new fixtures when running under pytest.
The file is entirely about HTTP API endpoint testing (OpenAI-compatible /v1/chat/completions, Anthropic-compatible /v1/messages, API key auth, plus a CLI --help sanity check on the command that runs the API). None of its tests cover training, export, chat-UI, or internal-Python-API concerns. The old name misleadingly suggested "tests for the unsloth studio run CLI subcommand" — the new name reflects the actual scope. Updates: - git mv the file (rename tracked, history preserved) - Rewrite opening docstring to state the API surface focus and call out what is explicitly out of scope - Update all 4 Usage-block path references to the new filename - LOG_FILE renamed to test_studio_api.log - conftest.py fixture import rewritten from test_studio_run to test_studio_api, plus 7 docstring/comment references updated No functional changes to test logic, signatures, or main().
|
merging and finalizing on original branch |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0d1835a73
ℹ️ 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".
| if btype == "text": | ||
| text_parts.append(b["text"]) | ||
| elif btype == "tool_use": |
There was a problem hiding this comment.
Handle Anthropic image blocks in message translation
This translator accepts image-capable Anthropic messages at the schema layer but only maps text, tool_use, and tool_result blocks here, so type:"image" content is silently dropped. As a result, multimodal prompts are downgraded to text-only (and image-only turns can disappear entirely), which causes incorrect model behavior for vision requests instead of a faithful /v1/messages translation.
Useful? React with 👍 / 👎.
| if text_parts: | ||
| result.append({"role": "user", "content": "\n".join(text_parts)}) | ||
| for tr in tool_results: | ||
| result.append(tr) |
There was a problem hiding this comment.
Preserve tool_result ordering before follow-up user text
For user messages that contain both tool_result and text blocks, this code always emits the user text message before emitting translated role:"tool" messages. That reverses the expected tool-call sequence (tool outputs should be in history before the follow-up user instruction), which can make the model answer without seeing tool output context or produce invalid tool-call state transitions.
Useful? React with 👍 / 👎.
| async with client.stream( | ||
| "POST", | ||
| target_url, | ||
| json = body, | ||
| timeout = 600, |
There was a problem hiding this comment.
Validate passthrough stream HTTP status before parsing
The streaming passthrough path starts consuming lines immediately and never checks resp.status_code before translating to Anthropic SSE. When llama-server returns an error body (e.g., 401/500), the parser skips it and still emits a normal message_stop, so clients observe a false-success empty stream instead of receiving the upstream failure.
Useful? React with 👍 / 👎.
Summary
Adds a
/v1/messagesendpoint that speaks the Anthropic Messages API format, so Anthropic SDK clients (and any Anthropic-compatible tool like Claude Code, etc.) can connect to Unsloth Studio alongside the existing OpenAI-compatible endpoints.generate_chat_completion_with_tools) — no duplicated tool execution logicmessage_start,content_block_start,content_block_delta,content_block_stop,message_delta,message_stop) and non-streaming JSONtool_resultSSE event so clients can see server-side tool execution output (Anthropic SDKs ignore unknown event types)name,description,input_schema) and the Unsloth shorthand (enable_tools,enabled_tools,session_id) from the OpenAI endpoint<tool_call>/<function=...>XML from content, same as the OpenAI endpointDepends(get_current_subject)andALL_TOOLSHow it works
Backend changes
studio/backend/models/inference.pyAnthropicMessagesRequest,AnthropicMessage,AnthropicTool,AnthropicContentBlock,AnthropicMessagesResponse, etc.)studio/backend/core/inference/anthropic_compat.pyanthropic_messages_to_openai,anthropic_tools_to_openai) +AnthropicStreamEmitterclass that converts the 5 generator event types into Anthropic SSEstudio/backend/routes/inference.pyPOST /messageshandler with 4 helpers for streaming/non-streaming × tool/no-tool paths. Reusesgenerate_chat_completion_with_tools()and the existing system-prompt nudge + XML stripping logicRequest format
Accepts the Anthropic Messages API format plus Unsloth extension fields:
Tool loop flow
generate_chat_completion_with_tools()status,tool_start,tool_end,content,metadata)AnthropicStreamEmitterconverts them to Anthropic SSE events:content→content_block_delta(text_delta) with cumulative difftool_start→ close text block + opentool_useblock +input_json_deltatool_end→ close tool block + customtool_resultevent + open new text blockmetadata→ captured for finalmessage_deltaAnthropicMessagesResponseTesting
Offline unit tests (no GPU / server required)
studio/backend/tests/test_anthropic_messages.py— 30+ tests covering:TestAnthropicModels— Pydantic validation (required/optional fields, extension fields, extra="allow")TestAnthropicMessagesToOpenAI— message translation (string content, block content, system as string/list, multi-turn, assistanttool_use, usertool_result, mixed blocks)TestAnthropicToolsToOpenAI— tool format translationTestBuildAnthropicSSEEvent— SSE event framingTestAnthropicStreamEmitter— all state transitions (content diffs, cumulative, empty, tool_start → tool_end flow, block indexing, prev_text reset, metadata capture, status ignored, finish)Run:
End-to-end tests (requires GPU + GGUF model)
studio/backend/tests/test_studio_api.py— extended with 4 new e2e tests that hit/v1/messagesagainst a running Studio server:test_anthropic_basic— non-streaming, verifies message/content/text block shapetest_anthropic_streaming— SSE stream, verifiesmessage_start/message_stopevents and text contenttest_anthropic_sdk— Anthropic Python SDK (from anthropic import Anthropic)test_anthropic_with_tools— streaming with Anthropic-nativetoolsfieldThe file was renamed from
test_studio_run.pytotest_studio_api.pyto reflect its actual scope (HTTP API surface testing — OpenAI-compatible and Anthropic-compatible endpoints plus API-key auth — not training, export, or chat UI). A session-scopedstudio_serverfixture inconftest.pyprovidesbase_url/api_keyto the test functions, enabling three invocation modes:Script mode — launches its own server via
unsloth studio run(backward-compatible with the pre-rename workflow):Pytest mode, external server — start a Studio server once, iterate tests against it. Fastest feedback loop, no per-run GGUF load cost:
Pytest mode, fixture-managed server — pytest drives
_start_server/_kill_serveritself. CI-friendly, single command:Manual curl examples
Basic chat, streaming, no tools:
With tools (shorthand), streaming — math:
With tools (shorthand), streaming — Fibonacci:
Test plan
curl /v1/messagesnon-streaming returns valid Anthropic JSONcurl /v1/messagesstreaming emits correct SSE event sequenceenable_tools+enabled_toolsshorthand works (matches OpenAI endpoint behavior)toolsfield works (auto-converted to OpenAI format)session_idpropagates to the sandbox (Python/terminal tools)tool_resultevent is emitted on tool completionanthropic.Anthropic(base_url=..., api_key=...))