Repository navigation
Studio: Expose openai and anthropic compatible external API end points - #4956
Conversation
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.
There was a problem hiding this comment.
💡 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".
| if payload.expires_in_days is not None: | ||
| expires_at = ( | ||
| datetime.now(timezone.utc) + timedelta(days = payload.expires_in_days) | ||
| ).isoformat() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
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
- 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.
There was a problem hiding this comment.
💡 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), |
There was a problem hiding this comment.
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 👍 / 👎.
Test ResultsBackend unit tests (8/8 pass)End-to-end: API key lifecycle via curlEnd-to-end: Public IP access (AWS
|
| 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.pyBuild checks
tsc --noEmit: passvite build: pass (5.28s)
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
There was a problem hiding this comment.
💡 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" |
There was a problem hiding this comment.
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 👍 / 👎.
| studio_bin = studio_python.parent / "unsloth" | ||
| if not studio_bin.is_file(): |
There was a problem hiding this comment.
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 👍 / 👎.
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.
There was a problem hiding this comment.
💡 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): |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 👍 / 👎.
…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
There was a problem hiding this comment.
💡 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") |
There was a problem hiding this comment.
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 👍 / 👎.
| chat_kwargs["max_tokens"] = payload.max_output_tokens | ||
|
|
||
| chat_request = ChatCompletionRequest(**chat_kwargs) | ||
| return await openai_chat_completions(chat_request, request) |
There was a problem hiding this comment.
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 👍 / 👎.
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.
There was a problem hiding this comment.
💡 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".
| "--parallel", | ||
| "1", # Single-user studio, saves VRAM | ||
| str(n_parallel), |
There was a problem hiding this comment.
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 👍 / 👎.
| choices = chunk_data.get("choices", []) | ||
| if not choices: | ||
| # Check for usage in final chunk | ||
| usage = chunk_data.get("usage") |
There was a problem hiding this comment.
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 👍 / 👎.
| body = await request.json() | ||
| target_url = f"{llama_backend.base_url}/v1/completions" | ||
| is_stream = body.get("stream", False) |
There was a problem hiding this comment.
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 👍 / 👎.
* 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>
|
Merged Anthropic messages endpoint.
more information: #4981 |
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
…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.
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.
There was a problem hiding this comment.
💡 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".
| if btype == "text": | ||
| text_parts.append(b["text"]) | ||
| elif btype == "tool_use": |
There was a problem hiding this comment.
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 👍 / 👎.
| resp = await client.send(req, stream = True) | ||
|
|
||
| async for raw_line in resp.aiter_lines(): | ||
| if await request.is_disconnected(): | ||
| cancel_event.set() |
There was a problem hiding this comment.
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 👍 / 👎.
|
Tested on Windows - all tests passed. |
|
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:
How to read this comment:
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_XLNotes:
# 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.logNotes:
# 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.logNotes:
# 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.logNotes:
Validation summary:
Interpretation for reviewers:
Logs: |
|
Tested on windows native, all tests past and manual test of endpoints work as expected. |
There was a problem hiding this comment.
💡 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".
| if text_parts: | ||
| result.append({"role": "user", "content": "\n".join(text_parts)}) | ||
| for tr in tool_results: |
There was a problem hiding this comment.
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 👍 / 👎.
| except Exception as e: | ||
| logger.error("anthropic_messages stream error: %s", e) | ||
|
|
||
| for line in emitter.finish("end_turn"): |
There was a problem hiding this comment.
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 👍 / 👎.
|
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. |
|
Hey @LeoBorcherding, GitHub's secret scanning flagged the Unsloth Studio API key in the test instructions above ( If that Studio install is still around, please delete that key under Settings > API and create a new one. |




Summary
sk-unsloth-prefixed API keys so external clients (curl, PythonopenaiSDK, Open WebUI, SillyTavern) can authenticate without the browser login flowHow it works
The auth layer (
_get_current_subject) checks whether the Bearer token starts withsk-unsloth-. If so it validates against theapi_keystable instead of decoding a JWT. Since all JWTs start witheyJ(base64 header), the prefix check is unambiguous.Backend changes
studio/backend/auth/storage.pyapi_keystable +create_api_key,list_api_keys,revoke_api_key,validate_api_keystudio/backend/auth/authentication.py_get_current_subjectstudio/backend/models/auth.pyCreateApiKeyRequest,ApiKeyResponse,CreateApiKeyResponse,ApiKeyListResponsestudio/backend/routes/auth.pyPOST/GET/DELETE /api/auth/api-keysFrontend changes
studio/frontend/src/features/auth/api-keys-page.tsxstudio/frontend/src/app/routes/api-keys.tsx/api-keyswithrequireAuthguardstudio/frontend/src/app/router.tsxstudio/frontend/src/components/navbar.tsxstudio/frontend/src/features/auth/index.tsUsage
Test plan
tsc --noEmitpassesvite buildpasses/v1/models(200), use key on/v1/chat/completions(authenticated), verifylast_used_atupdates, revoke key, verify revoked key returns 401, verify invalid key returns 401