Skip to content

Studio: Expose openai and anthropic compatible external API end points - #4956

Merged
rolandtannous merged 21 commits into
mainfrom
studio/api-keys
Apr 13, 2026
Merged

rolandtannous merged 21 commits into
mainfrom
studio/api-keys

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Adds sk-unsloth- prefixed API keys so external clients (curl, Python openai SDK, Open WebUI, SillyTavern) can authenticate without the browser login flow
  • Keys are SHA-256 hashed in SQLite, shown once at creation, and support optional expiry + revocation
  • Every existing endpoint (chat completions with tool calling, training, export, data recipes, model management) works with API keys -- zero route handler changes needed

How it works

The auth layer (_get_current_subject) checks whether the Bearer token starts with sk-unsloth-. If so it validates against the api_keys table instead of decoding a JWT. Since all JWTs start with eyJ (base64 header), the prefix check is unambiguous.

Backend changes

File Change
studio/backend/auth/storage.py api_keys table + create_api_key, list_api_keys, revoke_api_key, validate_api_key
studio/backend/auth/authentication.py API key branch before JWT path in _get_current_subject
studio/backend/models/auth.py CreateApiKeyRequest, ApiKeyResponse, CreateApiKeyResponse, ApiKeyListResponse
studio/backend/routes/auth.py POST/GET/DELETE /api/auth/api-keys

Frontend changes

File Change
studio/frontend/src/features/auth/api-keys-page.tsx New page: create form, one-time key reveal dialog, keys table with revoke, usage examples
studio/frontend/src/app/routes/api-keys.tsx Route at /api-keys with requireAuth guard
studio/frontend/src/app/router.tsx Register route
studio/frontend/src/components/navbar.tsx "API Keys" link in desktop + mobile nav
studio/frontend/src/features/auth/index.ts Export

Usage

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

# With tools
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-..." \
  -H "Content-Type: application/json" \
  -d '{
    "messages":[{"role":"user","content":"Search for Python 3.13 features"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["web_search", "python"],
    "session_id": "my-session"
  }'

# OpenAI Python SDK
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8888/v1", api_key="sk-unsloth-...")

Test plan

  • Backend unit tests: create, validate, list, revoke, expired key rejection, bogus key rejection (8/8 pass)
  • tsc --noEmit passes
  • vite build passes
  • End-to-end: create key via JWT, use key on /v1/models (200), use key on /v1/chat/completions (authenticated), verify last_used_at updates, revoke key, verify revoked key returns 401, verify invalid key returns 401

External users want to hit the Studio API (chat completions with tool
calling, training, export, etc.) without going through the browser
login flow. This adds sk-unsloth- prefixed API keys that work as a
drop-in replacement for JWTs in the Authorization: Bearer header.

Backend:
- New api_keys table in SQLite (storage.py)
- create/list/revoke/validate functions with SHA-256 hashed storage
- API key detection in _get_current_subject before the JWT path
- POST/GET/DELETE /api/auth/api-keys endpoints on the auth router

Frontend:
- /api-keys page with create form, one-time key reveal, keys table
- API Keys link in desktop and mobile navbar
- Route registered with requireAuth guard

Zero changes to any existing route handler -- every endpoint that uses
Depends(get_current_subject) automatically works with API keys.

@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: ae4ff49924

ℹ️ 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 +166 to +169
if payload.expires_in_days is not None:
expires_at = (
datetime.now(timezone.utc) + timedelta(days = payload.expires_in_days)
).isoformat()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate API key expiry days before building timedelta

POST /api-keys accepts any integer for expires_in_days, but the handler passes it directly into timedelta(days=...). Large magnitudes (e.g. 1000000000) raise OverflowError, which currently bubbles up as a 500 instead of a client error; negative values also produce keys that are already expired. Adding bounds validation on CreateApiKeyRequest (for example ge=1 and an upper limit) would prevent accidental invalid keys and unhandled server errors.

Useful? React with 👍 / 👎.

The examples on /api-keys were hardcoded to localhost:8888 which is
wrong for remote users. Use window.location.origin so the examples
show the correct URL regardless of where the user is connecting from.

@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 implements an API key management system, including backend storage, authentication logic, and a frontend management interface. A performance improvement was suggested for the validate_api_key function to use a cooldown when updating the last_used_at timestamp, which prevents excessive database churn on high-frequency requests.

I am having trouble creating individual review comments. Click here to see my feedback.

studio/backend/auth/storage.py (450-478)

high

The current implementation performs a synchronous UPDATE and COMMIT on every single authenticated request. For high-frequency endpoints like streaming chat completions, this creates significant database churn and latency. I suggest adding a cooldown (e.g., 60 seconds) for the last_used_at update to improve performance. Other refactoring concerns regarding user existence and password policy consistency should be addressed in separate efforts to keep the pull request scope minimal.

def validate_api_key(raw_key: str) -> Optional[str]:
    """Validate *raw_key* and return the owning username, or ``None``.

    Updates ``last_used_at`` on success with a cooldown to reduce DB churn.
    """
    key_hash = _hash_token(raw_key)
    conn = get_connection()
    try:
        cur = conn.execute(
            """
            SELECT id, username, is_active, expires_at, last_used_at
            FROM api_keys
            WHERE key_hash = ?
            """,
            (key_hash,),
        )
        row = cur.fetchone()
        if row is None or not row["is_active"]:
            return None

        now = datetime.now(timezone.utc)
        if row["expires_at"] is not None:
            expires = datetime.fromisoformat(row["expires_at"])
            if now > expires:
                return None

        # Update last_used_at with a 1-minute cooldown to reduce write churn
        last_used_str = row["last_used_at"]
        should_update = not last_used_str
        if last_used_str:
            try:
                last_used = datetime.fromisoformat(last_used_str)
                if (now - last_used).total_seconds() >= 60:
                    should_update = True
            except (ValueError, TypeError):
                should_update = True

        if should_update:
            conn.execute(
                "UPDATE api_keys SET last_used_at = ? WHERE id = ?",
                (now.isoformat(), row["id"]),
            )
            conn.commit()

        return row["username"]
    finally:
        conn.close()
References
  1. When fixing a specific issue, such as a performance bottleneck, keep the pull request's scope minimal. Avoid refactoring pre-existing, related issues in the same change; address them in a separate effort.

@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: 7838e8ad39

ℹ️ 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".

@router.post("/api-keys", response_model = CreateApiKeyResponse)
async def create_api_key(
payload: CreateApiKeyRequest,
current_subject: str = Depends(get_current_subject),

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 Disallow API keys from creating additional API keys

get_current_subject now accepts sk-unsloth- credentials, and these management endpoints depend on it, so a compromised API key can call /api/auth/api-keys to mint replacement keys before the original is revoked. In that scenario, revoking the leaked key no longer removes attacker access because the attacker-created key remains active; API key lifecycle operations should require a JWT/session-only auth path (or otherwise block API-key auth on key management routes).

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Test Results

Backend unit tests (8/8 pass)

[PASS] Created key: sk-unsloth-0230282a...
[PASS] Validated key successfully
[PASS] Listed 1 key(s)
[PASS] Revoked key
[PASS] Validation correctly fails after revoke
[PASS] Bogus key correctly rejected
[PASS] Key with future expiry validates
[PASS] Expired key correctly rejected

End-to-end: API key lifecycle via curl

=== 1. Create API Key ===
POST /api/auth/api-keys (JWT-authed)
{
    "key": "sk-unsloth-717d9e77e8f07db37bf5e9f49d3e841d",
    "api_key": {
        "id": 4,
        "name": "Test key",
        "key_prefix": "717d9e77",
        "created_at": "2026-04-10T13:31:42.941290+00:00",
        "last_used_at": null,
        "expires_at": "2026-05-10T13:31:42.941219+00:00",
        "is_active": true
    }
}

=== 2. List API Keys ===
GET /api/auth/api-keys (JWT-authed)
-> 1 key returned, no key_hash exposed

=== 3. Use API Key on /v1/models ===
GET /v1/models -H "Authorization: Bearer sk-unsloth-..."
-> HTTP 200, returned loaded model list

=== 4. Use API Key on /v1/chat/completions ===
POST /v1/chat/completions -H "Authorization: Bearer sk-unsloth-..."
-> HTTP 200 (authenticated -- returned "no model loaded" since none was loaded at the time)

=== 5. Verify last_used_at updated ===
Key 'Test key': last_used_at = 2026-04-10T13:31:56.066409+00:00

=== 6. Invalid key rejected ===
Bearer sk-unsloth-0000000000000000000000000000000000 -> HTTP 401

=== 7. Revoke key ===
DELETE /api/auth/api-keys/4 -> {"detail": "API key revoked"}

=== 8. Revoked key rejected ===
Bearer sk-unsloth-717d9e77... -> HTTP 401

End-to-end: Public IP access (AWS 3.128.175.236:8888)

Model loaded: unsloth/Qwen3-1.7B-GGUF (UD-Q4_K_XL)

1. /v1/models via public IP

{
    "object": "list",
    "data": [{"id": "unsloth/Qwen3-1.7B-GGUF", "object": "model", "owned_by": "local"}]
}

2. Streaming chat via public IP

curl http://3.128.175.236:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-..." \
  -d '{"messages":[{"role":"user","content":"Say hello in 10 words"}],"stream":true}'

-> SSE chunks streamed successfully

3. Tool calling (Python) via public IP

curl http://3.128.175.236:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-..." \
  -d '{"messages":[{"role":"user","content":"What is 2+2? Use Python to verify."}],
       "stream":true, "enable_tools":true, "enabled_tools":["python"],
       "session_id":"public-ip-test"}'

-> tool_start: python, code: "print(2 + 2)"
-> tool_end: result: "4\n"
-> Model response incorporated the tool result

End-to-end: All 4 Studio default suggestions via OpenAI Python SDK

Script uses openai.OpenAI(base_url=..., api_key="sk-unsloth-...") with enable_tools=True and enabled_tools=["web_search", "python", "terminal"].

Suggestion Tools expected Result Response length
"How do you fine-tune an audio model with Unsloth?" web_search PASS 1658 chars
"Create a live weather dashboard in HTML using no API key" web_search + python PASS 1249 chars
"Solve the integral of x*sin(x), and verify it" python PASS 2047 chars
"Draw an SVG of a cute sloth & show the code" python PASS 6222 chars
Full OpenAI SDK test script
"""
End-to-end test: hit all 4 Studio default suggestions via the OpenAI SDK
using an API key, with tools enabled (web_search, python, terminal).
"""

import os
import sys

BASE_URL = os.environ.get("STUDIO_URL", "http://localhost:8888") + "/v1"
API_KEY  = os.environ.get("STUDIO_API_KEY", "")

if not API_KEY:
    print("Set STUDIO_API_KEY env var first, e.g.:")
    print("  export STUDIO_API_KEY=sk-unsloth-...")
    sys.exit(1)

from openai import OpenAI

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)

PROMPTS = [
    {
        "label": "Audio fine-tuning",
        "prompt": "How do you fine-tune an audio model with Unsloth?",
    },
    {
        "label": "Weather dashboard",
        "prompt": "Create a live weather dashboard in HTML using no API key. Show me the code",
    },
    {
        "label": "Integral",
        "prompt": "Solve the integral of x*sin(x), and verify it step by step",
    },
    {
        "label": "SVG sloth",
        "prompt": "Draw an SVG of a cute sloth & show the code",
    },
]


def run_prompt(label: str, prompt: str) -> None:
    print(f"\n{'='*60}")
    print(f"  {label}")
    print(f"{'='*60}")
    print(f"Prompt: {prompt}\n")

    stream = client.chat.completions.create(
        model="current",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
        extra_body={
            "enable_tools": True,
            "enabled_tools": ["web_search", "python", "terminal"],
            "auto_heal_tool_calls": True,
            "max_tool_calls_per_message": 8,
            "tool_call_timeout": 120,
            "session_id": f"e2e-test-{label.lower().replace(' ', '-')}",
        },
    )

    full_text = ""
    for chunk in stream:
        delta = chunk.choices[0].delta if chunk.choices else None
        if delta and delta.content:
            sys.stdout.write(delta.content)
            sys.stdout.flush()
            full_text += delta.content

    print(f"\n\n--- Response length: {len(full_text)} chars ---")
    return full_text


if __name__ == "__main__":
    print(f"Studio: {BASE_URL}")
    print(f"API Key: {API_KEY[:20]}...")

    models = client.models.list()
    model_ids = [m.id for m in models.data]
    print(f"Loaded models: {model_ids}")
    if not model_ids:
        print("No model loaded -- load one first via the Studio UI or API.")
        sys.exit(1)

    results = {}
    for p in PROMPTS:
        try:
            text = run_prompt(p["label"], p["prompt"])
            results[p["label"]] = "PASS" if len(text) > 10 else "EMPTY"
        except Exception as e:
            print(f"\n  ERROR: {e}")
            results[p["label"]] = f"FAIL: {e}"

    print(f"\n{'='*60}")
    print("  Summary")
    print(f"{'='*60}")
    for label, status in results.items():
        print(f"  {label:25s} {status}")

Usage:

export STUDIO_API_KEY=sk-unsloth-...
python test_api_key_e2e.py

# For remote access:
export STUDIO_URL=http://your-server:8888
export STUDIO_API_KEY=sk-unsloth-...
python test_api_key_e2e.py

Build checks

  • tsc --noEmit: pass
  • vite build: pass (5.28s)

danielhanchen and others added 2 commits April 10, 2026 14:18
Adds a `run` subcommand that starts Studio, loads a model, creates an
API key, and prints a ready-to-use curl command -- similar to
`ollama run` or `vllm serve`.

Usage: unsloth studio run -m unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL

@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: 924f1620a7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

import urllib.request
import urllib.error

url = f"http://127.0.0.1:{port}/api/health"

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 Use bound host instead of hardcoded loopback for startup calls

unsloth studio run always probes http://127.0.0.1 in _wait_for_server (and does the same for model loading), so --host values like a specific interface (192.168.x.x) or IPv6 (::) can fail even when the server is healthy because uvicorn only binds to the requested host. In those cases the command times out or reports model-load failures despite the backend actually running.

Useful? React with 👍 / 👎.

Comment on lines +279 to +280
studio_bin = studio_python.parent / "unsloth"
if not studio_bin.is_file():

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 Resolve Windows CLI entrypoint with executable suffix

The re-exec path checks for .../Scripts/unsloth before spawning, but Windows virtualenv console entry points are typically unsloth.exe (plus script shims), not an extensionless file. As a result, unsloth studio run from outside the studio venv exits with "missing entry point" on Windows even when the venv is correctly installed.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 10, 2026 14:27
Tests the 4 usage examples from the API Keys page:
1. curl basic (non-streaming) chat completions
2. curl streaming (SSE) chat completions
3. OpenAI Python SDK streaming completions
4. curl with tools (web_search + python)

Also tests --help output, invalid key rejection, and no-key rejection.
All 7 tests pass against Qwen3-1.7B-GGUF.

@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: c40ed3766a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

print(" PASS --help shows all flags")


def test_curl_basic(base_url: str, api_key: str):

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 Prevent pytest from collecting script-only E2E tests

This file is in the standard pytest discovery path and defines multiple test_* functions, but several of them depend on non-existent fixtures like base_url and api_key, so a normal backend test run fails at collection/execution (for example, pytest -q studio/backend/tests/test_studio_run.py::test_curl_basic errors with fixture 'base_url' not found). Because main() only runs under __main__, the intended custom harness is skipped in pytest, which makes the test suite unstable.

Useful? React with 👍 / 👎.

try:
with urllib.request.urlopen(req, timeout = timeout) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as exc:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Catch non-HTTP urlopen failures in model-load helper

This handler only wraps HTTPError, but urlopen also raises URLError/timeout exceptions for connection failures; those bypass this except and bubble out of run() as uncaught tracebacks because run() only catches RuntimeError. In scenarios where /api/inference/load is temporarily unreachable, users get a crash instead of the intended clean Error: ... exit path.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 10, 2026 14:44
…rallel support

- llama_cpp.py: accept n_parallel param, pass to llama-server --parallel
- run.py: plumb llama_parallel_slots through to app.state
- inference.py: add /completions and /embeddings as transparent proxies to
  llama-server, add /responses as application-level endpoint that converts
  to ChatCompletionRequest; thread n_parallel through load_model
- studio.py: set llama_parallel_slots=4 for `unsloth studio run` path

@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: 315f3d7f81

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

async for chunk in resp.aiter_bytes():
yield chunk

return StreamingResponse(_stream(), media_type = "text/event-stream")

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 Propagate upstream status for streaming completions

When stream=true, this branch always returns a new StreamingResponse with FastAPI’s default 200 status, regardless of whether llama-server returned a 4xx/5xx error. In cases like malformed completion payloads, clients will see a successful HTTP status and may skip their normal error handling/retry paths even though the upstream request failed. Preserve the upstream status (and headers/content type) before relaying streamed bytes.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
chat_kwargs["max_tokens"] = payload.max_output_tokens

chat_request = ChatCompletionRequest(**chat_kwargs)
return await openai_chat_completions(chat_request, request)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Emit Responses API schema from /responses

This endpoint is exposed as /responses but directly returns openai_chat_completions(...), which produces chat-completions objects/stream chunks rather than the Responses API format. Clients using client.responses.create() or client.responses.stream() expect response-shaped payloads/events (for example output fields), so they will fail to parse or behave incorrectly. The handler should translate chat output into Responses API-compatible response and streaming event shapes.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 10, 2026 15:06
The existing /v1/responses shim returned Chat Completions format, which
broke OpenAI SDK clients using openai.responses.create(). This commit
replaces the endpoint with a proper implementation that:

- Returns `output` array with `output_text` content parts instead of
  `choices` with `message`
- Uses `input_tokens`/`output_tokens` instead of `prompt_tokens`/
  `completion_tokens` in usage
- Sets `object: "response"` and `id: "resp_..."`
- Emits named SSE events for streaming (response.created,
  response.output_text.delta, response.completed, etc.)
- Accepts all OpenAI Responses API fields (tools, store, metadata,
  previous_response_id) without erroring -- silently ignored
- Maps `developer` role to `system` and `input_text`/`input_image`
  content parts to the internal Chat format

Adds Pydantic schemas for request/response models and 23 unit tests
covering schema validation, input normalisation, and response format.

@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: ac8d5aee02

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines 1286 to +1287
"--parallel",
"1", # Single-user studio, saves VRAM
str(n_parallel),

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 Account for parallel slots in KV cache sizing

The loader still sizes context/GPU fit with single-slot KV estimates (_estimate_kv_cache_bytes(...)) but now launches llama-server with a variable --parallel value. With unsloth studio run setting llama_parallel_slots=4, this underestimates KV memory and can pick a context that appears to fit during planning but OOMs or crashes once llama-server allocates four parallel slots. Please fold n_parallel into the KV sizing path before choosing context/GPU placement.

Useful? React with 👍 / 👎.

Comment on lines +2098 to +2101
choices = chunk_data.get("choices", [])
if not choices:
# Check for usage in final chunk
usage = chunk_data.get("usage")

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 Propagate stream errors before emitting response.completed

In /responses streaming, chunks without choices are treated as usage-only and ignored otherwise, so inner error chunks like {"error": ...} from openai_chat_completions are dropped and the wrapper still emits response.completed. In failure scenarios (backend exception mid-stream), clients receive a successful completion event with empty/partial output instead of a failure signal, which breaks retry/error handling.

Useful? React with 👍 / 👎.

Comment on lines +1862 to +1864
body = await request.json()
target_url = f"{llama_backend.base_url}/v1/completions"
is_stream = body.get("stream", False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate completions request body before using .get

This endpoint parses raw JSON and immediately calls body.get("stream") without checking that the payload is an object. If a client sends a valid non-object JSON value (for example, a list/string), this raises AttributeError and returns a 500 instead of a client error. Adding shape validation (or a Pydantic request model) would make these bad requests return 4xx deterministically.

Useful? React with 👍 / 👎.

Roland Tannous and others added 3 commits April 10, 2026 22:14
* Add Anthropic-compatible /v1/messages endpoint with tool support

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.

* Add enable_tools, enabled_tools, session_id to /v1/messages endpoint

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.

* Strip leaked tool-call XML from Anthropic endpoint content

Apply _TOOL_XML_RE to content events in both streaming and
non-streaming tool paths, matching the OpenAI endpoint behavior.

* Emit custom tool_result SSE event in Anthropic stream

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Split /v1/messages into server-side and client-side tool paths

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix httpcore GeneratorExit in /v1/messages passthrough stream

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.

* Wire stop_sequences through /v1/messages; warn on tool_choice

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.

* Wire min_p / repetition_penalty / presence_penalty through /v1/messages

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.

* Fix block ordering and prev_text reset in non-streaming tool path

_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.

* Make test_studio_run.py e2e tests pytest-compatible

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.

* Rename test_studio_run.py -> test_studio_api.py

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().

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Comment thread studio/backend/tests/test_studio_api.py Dismissed
@rolandtannous

Copy link
Copy Markdown
Contributor

Merged Anthropic messages endpoint.
Ran 40+ tests across 3 test files.
VAlidated works in claude code
validated works in openclaw.

Screenshot 2026-04-12 at 2 58 39 PM Screenshot 2026-04-13 at 11 06 26 AM Screenshot 2026-04-13 at 11 04 23 AM Screenshot 2026-04-12 at 9 38 53 PM

more information: #4981

Roland Tannous and others added 2 commits April 13, 2026 11:18
The earlier fix in 985e92a was incomplete: it closed aiter_lines()
explicitly but still used `async with httpx.AsyncClient()` /
`async with client.stream()` inside the generator. When the generator
is orphaned (e.g. client disconnects mid-stream and Starlette drops
the StreamingResponse iterator without explicitly calling aclose()),
Python's asyncgen finalizer runs the cleanup in a DIFFERENT task than
the one that originally entered the httpx context managers. The
`async with` exits then trigger httpcore's HTTP11ConnectionByteStream
.aclose(), which enters anyio.CancelScope.__exit__ with a mismatched
task and raises RuntimeError("Attempted to exit cancel scope in a
different task"). That error escapes any user-owned try/except
because it happens during GC finalization.

Replace `async with` with manual client/response lifecycle in both
/v1/messages passthrough and /v1/completions proxy. Close the
response and client in a finally block wrapped in
`try: ... except Exception: pass`. This suppresses RuntimeError (and
other Exception subclasses) from the anyio cleanup noise while
letting GeneratorExit (a BaseException, not Exception) propagate
cleanly so the generator terminates as Python expects.

Traceback observed in user report:
  File ".../httpcore/_async/connection_pool.py", line 404, in __aiter__
      yield part
  RuntimeError: async generator ignored GeneratorExit
...
  File ".../anyio/_backends/_asyncio.py", line 455, in __exit__
      raise RuntimeError(
  RuntimeError: Attempted to exit cancel scope in a different task
Roland Tannous added 2 commits April 13, 2026 14:02
…ples

Add an explicit "OpenAI / Anthropic SDK base URL" line inside the info
box so SDK users don't accidentally copy the bare server URL (without
/v1) into their OpenAI/Anthropic SDK constructors and hit 404s.

Replace the single /v1/chat/completions curl example with three
labeled blocks: chat/completions, Anthropic /messages, and OpenAI
Responses. The Anthropic example includes max_tokens (Anthropic SDKs
require it even though Studio accepts None).

All examples derived from a computed sdk_base_url so the /v1 prefix
stays in sync if the public path ever changes.
Stores the HMAC secret in a new app_secrets singleton table. Fixes
CodeQL py/weak-sensitive-data-hashing alert on storage.py:74-76,
394-395. Refresh tokens stay on plain SHA-256 (unchanged _hash_token)
so existing user sessions survive upgrade — API keys are new on this
branch so there is no migration.
Comment thread studio/backend/auth/storage.py Fixed
Roland Tannous and others added 2 commits April 13, 2026 16:02
HMAC-SHA256 was still flagged by py/weak-sensitive-data-hashing.
Switch to hashlib.pbkdf2_hmac, which is in CodeQL's recommended
allowlist (Argon2/scrypt/bcrypt/PBKDF2). Persistent server-side
salt stays in app_secrets for defense-in-depth. 100k iterations to
match auth/hashing.py's password hasher.

@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: 035519069f

ℹ️ 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 Preserve Anthropic image blocks during translation

anthropic_messages_to_openai only handles text, tool_use, and tool_result blocks, so type: "image" content is silently dropped. For /v1/messages requests that include image blocks, the model receives text-only input (or no user message at all for image-only prompts), which breaks vision use cases and returns incorrect results. Please translate Anthropic image blocks into OpenAI-compatible image content parts instead of discarding them.

Useful? React with 👍 / 👎.

Comment on lines +2786 to +2790
resp = await client.send(req, stream = True)

async for raw_line in resp.aiter_lines():
if await request.is_disconnected():
cancel_event.set()

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 Fail passthrough streams when upstream returns HTTP errors

The streaming passthrough path never checks resp.status_code before iterating lines, so upstream 4xx/5xx responses are treated like normal streams; since non-SSE lines are skipped, the error body is ignored and the function still emits emitter.finish() completion events. In cases like invalid tool payloads, clients receive a successful-looking stream instead of an error signal, which breaks retry and failure handling.

Useful? React with 👍 / 👎.

@Etherll

Etherll commented Apr 13, 2026

Copy link
Copy Markdown
Collaborator

Tested on Windows - all tests passed.

@LeoBorcherding

LeoBorcherding commented Apr 13, 2026 •

Copy link
Copy Markdown
Collaborator

Tested on Windows PowerShell. Everything requested here is working on my side.

I tested this PR end-to-end from a clean local Windows setup to confirm the API-key flow and external API compatibility work in real usage, not just unit tests.

What I validated:

  • Local install and startup path on Windows
  • API key auth with runtime server banner key
  • OpenAI-compatible endpoint behavior
  • Anthropic-compatible endpoint behavior
  • Backend test coverage in tests/test_studio_api.py (full + Anthropic subset)

How to read this comment:

  • The code blocks below are the exact commands I ran.
  • The four log files at the bottom are the proof artifacts.
  • Anyone can reproduce this by following the blocks in order.

Command sequence I used:

# Switch to the PR branch
git checkout studio/api-keys

# Run local Windows install
./install.ps1 --local

# Start Studio in a separate terminal and keep it running
unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL

Notes:

  • I ran the server in a dedicated terminal (foreground) so I could read the startup banner.
  • The server banner provides the runtime URL/port and API key.
  • On my run, local base URL was http://127.0.0.1:8888.
# Open a second PowerShell window and go to repo root
cd D:\git_unsloth\main_group1\unsloth

# Use the runtime URL and API key from the server banner
$env:UNSLOTH_E2E_BASE_URL = "http://127.0.0.1:8888"
$env:UNSLOTH_E2E_API_KEY = "sk-unsloth-REDACTED"

# Run full API test file and save output
cd studio/backend
pytest tests/test_studio_api.py -v | Out-File output_v.log

# Run Anthropic-only subset and save output
pytest tests/test_studio_api.py -k anthropic -v 2>&1 | Tee-Object output_k.log

Notes:

  • output_v.log is the full test run.
  • output_k.log is Anthropic-only (-k anthropic).
  • Both were written under studio/backend because tests were run from that folder.
# Run chat-completions curl and save output to log
curl.exe http://localhost:8888/v1/chat/completions `
  -H "Authorization: Bearer sk-unsloth-REDACTED" `
  -H "Content-Type: application/json" `
  -d '{"messages":[{"role":"user","content":"Search for Python 3.13 features"}],"stream":true,"enable_tools":true,"enabled_tools":["web_search","python"],"session_id":"my-session"}' 2>&1 | Tee-Object chat_completions.log

Notes:

  • This verifies /v1/chat/completions with API key auth, streaming, and tools.
  • The log captures the live SSE stream output.
# Run messages curl and save output to log
curl.exe http://localhost:8888/v1/messages `
  -H "Authorization: Bearer sk-unsloth-REDACTED" `
  -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"}' 2>&1 | Tee-Object messages.log

Notes:

  • This verifies /v1/messages with API key auth, streaming, and python tool flow.
  • In my run, this log shows tool usage plus a computed numeric result.

Validation summary:

  • output_v.log: 11 passed
  • output_k.log: 4 passed, 7 deselected
  • chat_completions.log: auth + streaming + tool events worked
  • messages.log: auth + streaming + python tool use worked (returned computed result)

Interpretation for reviewers:

  • Windows local flow is working.
  • API key auth is working for both OpenAI-compatible and Anthropic-compatible endpoints.
  • Streaming responses are working.
  • Tool-calling behavior is working on both tested routes.

Logs:
output_v.log
output_k.log

chat_completions.log
messages.log

@Imagineer99

Copy link
Copy Markdown
Member

Tested on windows native, all tests past and manual test of endpoints work as expected.

@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: 69d80ca926

ℹ️ 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 +91 to +93
if text_parts:
result.append({"role": "user", "content": "\n".join(text_parts)})
for tr in tool_results:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve tool_result order when converting user content blocks

The translator batches all user text first and appends all tool_result blocks afterward, regardless of their original order in the Anthropic message. If a user message mixes tool results with follow-up text, this reordering produces an OpenAI transcript where the user turn appears before the tool output, which can break tool-call sequencing and lead to incorrect downstream reasoning. Convert user blocks in original order (splitting into multiple OpenAI messages as needed) instead of emitting text-first/tool-result-last.

Useful? React with 👍 / 👎.

Comment on lines +2549 to +2552
except Exception as e:
logger.error("anthropic_messages stream error: %s", e)

for line in emitter.finish("end_turn"):

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 Propagate Anthropic stream errors instead of completing normally

When generation raises inside _anthropic_tool_stream (and the same pattern exists in _anthropic_plain_stream), the exception is only logged and the code still emits emitter.finish("end_turn"), so clients receive a normal-looking completion after a backend failure. In cases like llama-server disconnects or tool-loop exceptions, this masks failures and prevents correct retry/error handling on Anthropic SDK clients.

Useful? React with 👍 / 👎.

@rolandtannous

Copy link
Copy Markdown
Contributor

performed E2E test:: ran training on text and vlm models, both gemma3 and gemma4 (requiriing transformers version switch), exported into gguf (confirms merging and gguf conversion works), loaded GGUF model in chat , and sent curl requests to newly exposed api endpoints. merging.

@danielhanchen

Copy link
Copy Markdown
Member Author

Hey @LeoBorcherding, GitHub's secret scanning flagged the Unsloth Studio API key in the test instructions above (sk-unsloth-...), so I replaced it with sk-unsloth-REDACTED. Nothing else in the comment changed.

If that Studio install is still around, please delete that key under Settings > API and create a new one.

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.

6 participants