Skip to content

Studio: add Anthropic-compatible /v1/messages endpoint - #4981

Merged
rolandtannous merged 14 commits into
studio/api-keysfrom
studio/anthropic-api
Apr 13, 2026
Merged

rolandtannous merged 14 commits into
studio/api-keysfrom
studio/anthropic-api

Conversation

@rolandtannous

@rolandtannous rolandtannous commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a /v1/messages endpoint 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.

  • Translates Anthropic ↔ internal OpenAI format and reuses the existing server-side agentic tool loop (generate_chat_completion_with_tools) — no duplicated tool execution logic
  • Supports streaming SSE (message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop) and non-streaming JSON
  • Emits a custom tool_result SSE event so clients can see server-side tool execution output (Anthropic SDKs ignore unknown event types)
  • Supports both Anthropic-native tool definitions (name, description, input_schema) and the Unsloth shorthand (enable_tools, enabled_tools, session_id) from the OpenAI endpoint
  • Strips leaked <tool_call> / <function=...> XML from content, same as the OpenAI endpoint
  • No auth or tool-execution changes — uses the existing Depends(get_current_subject) and ALL_TOOLS

How it works

Backend changes

File Change
studio/backend/models/inference.py Anthropic request/response Pydantic models (AnthropicMessagesRequest, AnthropicMessage, AnthropicTool, AnthropicContentBlock, AnthropicMessagesResponse, etc.)
studio/backend/core/inference/anthropic_compat.py New file. Pure translation functions (anthropic_messages_to_openai, anthropic_tools_to_openai) + AnthropicStreamEmitter class that converts the 5 generator event types into Anthropic SSE
studio/backend/routes/inference.py POST /messages handler with 4 helpers for streaming/non-streaming × tool/no-tool paths. Reuses generate_chat_completion_with_tools() and the existing system-prompt nudge + XML stripping logic

Request format

Accepts the Anthropic Messages API format plus Unsloth extension fields:

{
  model?: str = "default"
  max_tokens?: int
  messages: [{role: "user"|"assistant", content: str | ContentBlock[]}]
  system?: str | TextBlock[]
  tools?: [{name, description, input_schema}]        // Anthropic-native
  tool_choice?: any
  stream?: bool = false
  temperature?, top_p?, top_k?, stop_sequences?
  // Unsloth shorthand (mirrors /chat/completions)
  enable_tools?: bool
  enabled_tools?: [str]
  session_id?: str
}

Tool loop flow

  1. Translate Anthropic messages → OpenAI-format list[dict]
  2. If tools requested (either Anthropic-native or shorthand), translate + pass into generate_chat_completion_with_tools()
  3. Generator yields 5 event types (status, tool_start, tool_end, content, metadata)
  4. AnthropicStreamEmitter converts them to Anthropic SSE events:
    • content → content_block_delta (text_delta) with cumulative diff
    • tool_start → close text block + open tool_use block + input_json_delta
    • tool_end → close tool block + custom tool_result event + open new text block
    • metadata → captured for final message_delta
  5. Non-streaming path exhausts the generator and assembles an AnthropicMessagesResponse

Testing

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, assistant tool_use, user tool_result, mixed blocks)
  • TestAnthropicToolsToOpenAI — tool format translation
  • TestBuildAnthropicSSEEvent — SSE event framing
  • TestAnthropicStreamEmitter — all state transitions (content diffs, cumulative, empty, tool_start → tool_end flow, block indexing, prev_text reset, metadata capture, status ignored, finish)

Run:

cd studio/backend && python -m pytest tests/test_anthropic_messages.py -v

End-to-end tests (requires GPU + GGUF model)

studio/backend/tests/test_studio_api.py — extended with 4 new e2e tests that hit /v1/messages against a running Studio server:

  • test_anthropic_basic — non-streaming, verifies message/content/text block shape
  • test_anthropic_streaming — SSE stream, verifies message_start/message_stop events and text content
  • test_anthropic_sdk — Anthropic Python SDK (from anthropic import Anthropic)
  • test_anthropic_with_tools — streaming with Anthropic-native tools field

The file was renamed from test_studio_run.py to test_studio_api.py to 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-scoped studio_server fixture in conftest.py provides base_url / api_key to the test functions, enabling three invocation modes:

Script mode — launches its own server via unsloth studio run (backward-compatible with the pre-rename workflow):

cd studio/backend && python tests/test_studio_api.py
# or with a specific model
python tests/test_studio_api.py --model unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL

Pytest mode, external server — start a Studio server once, iterate tests against it. Fastest feedback loop, no per-run GGUF load cost:

unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL &
export UNSLOTH_E2E_BASE_URL=http://127.0.0.1:8080
export UNSLOTH_E2E_API_KEY=sk-unsloth-...   # from the server banner
cd studio/backend && pytest tests/test_studio_api.py -v
# or just the Anthropic tests
cd studio/backend && pytest tests/test_studio_api.py -k anthropic -v

Pytest mode, fixture-managed server — pytest drives _start_server / _kill_server itself. CI-friendly, single command:

cd studio/backend && pytest tests/test_studio_api.py -v \
    --unsloth-model unsloth/Qwen3-1.7B-GGUF \
    --unsloth-gguf-variant UD-Q4_K_XL

Manual curl examples

Basic chat, streaming, no tools:

curl http://localhost:8080/v1/messages \
  -H "Authorization: Bearer sk-unsloth-..." \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Hello"}], "stream":true}'

With tools (shorthand), streaming — math:

curl http://localhost:8080/v1/messages \
  -H "Authorization: Bearer sk-unsloth-..." \
  -H "Content-Type: application/json" \
  -d '{
    "messages":[{"role":"user","content":"What is 123 * 456? Use code to compute it."}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["python"],
    "session_id": "my-session"
  }'

With tools (shorthand), streaming — Fibonacci:

curl http://localhost:8080/v1/messages \
  -H "Authorization: Bearer sk-unsloth-..." \
  -H "Content-Type: application/json" \
  -d '{
    "messages":[{"role":"user","content":"Write and run a Python script that prints the first 10 Fibonacci numbers"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["python"],
    "session_id": "my-session"
  }'

Test plan

  • Offline unit tests pass
  • curl /v1/messages non-streaming returns valid Anthropic JSON
  • curl /v1/messages streaming emits correct SSE event sequence
  • enable_tools + enabled_tools shorthand works (matches OpenAI endpoint behavior)
  • Anthropic-native tools field works (auto-converted to OpenAI format)
  • session_id propagates to the sandbox (Python/terminal tools)
  • Leaked tool-call XML is stripped from content
  • Custom tool_result event is emitted on tool completion
  • Test against Anthropic Python SDK (anthropic.Anthropic(base_url=..., api_key=...))
  • Tested with Claude Code
  • Tested with opencode

Roland Tannous and others added 5 commits April 11, 2026 20:47
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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/routes/inference.py Resolved
Roland Tannous and others added 9 commits April 12, 2026 14:52
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.
Explicitly aclose aiter_lines() before the surrounding async with
blocks unwind, mirroring the prior fix in external_provider.py
(a41160d) and cc757b7's RuntimeError suppression.
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().
@rolandtannous

Copy link
Copy Markdown
Contributor Author

merging and finalizing on original branch

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +54 to +56
if btype == "text":
text_parts.append(b["text"])
elif btype == "tool_use":

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +91 to +94
if text_parts:
result.append({"role": "user", "content": "\n".join(text_parts)})
for tr in tool_results:
result.append(tr)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +2742 to +2746
async with client.stream(
"POST",
target_url,
json = body,
timeout = 600,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

1 participant