unsloth/studio/backend/tests/test_gguf_completion_usage.py
oobabooga 57be5868f9
Studio: improve OpenAI- and Anthropic-compatible API spec compliance (#6010)
* Studio: fix OpenAI- and Anthropic-compatible API spec compliance

* Studio: fix API spec-compliance gaps on passthrough and streaming paths

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

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

* Studio: carry context_length_exceeded through the OpenAI passthrough error path

* Studio: count tool-schema tokens in the Anthropic server-tool stream, and small stream-handling guards

* Studio: guard message_delta usage against None and normalize developer role before proxying

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

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

* Studio: honor max_completion_tokens on the external-provider proxy path

* Studio: forward llama-server cached_tokens into OpenAI prompt_tokens_details

* Studio: sanitize messages in count_tokens to match the /v1/messages prompt

* Studio: report max_tokens for truncated tool calls and guard null usage in metadata events

* Studio: drop the request-id middleware (headers aren't declared in either spec)

* Studio: include the required request_id field in Anthropic error bodies

* Studio: honor max_completion_tokens on the audio (TTS / audio-input) paths

* Studio: add the _effective_max_tokens helper and route all max-token sites through it

* Studio: align API compatibility edge cases

* Studio: clarify multi-choice chat support

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

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

* Studio: clarify logprobs chat support

* Studio: opt the local chat UI into the streaming usage chunk so the context bar and tok/s repopulate

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

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

* Studio: forward seed to llama-server, and fix Anthropic server-tool stop_reason, tool_result id correlation, and parallel-tool execution cap

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

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

* Studio: align OpenAI chat completion spec edge cases

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

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

* Studio: align backend API compatibility tests

* Studio: honor tool caps and internal stream usage

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

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

* Studio: coerce nullable stream usage counts

* Studio: preserve system prompts with developer messages

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: wasimysaid <wasimysdev@gmail.com>
2026-06-09 17:13:25 +02:00

86 lines
2.7 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""Regression tests for GGUF non-streaming chat completion usage."""
from fastapi import FastAPI
from fastapi.testclient import TestClient
from auth.authentication import get_current_subject
import routes.inference as inference_route
class _GgufBackend:
is_loaded = True
model_identifier = "test/model.gguf"
_is_audio = False
is_vision = False
supports_tools = False
def __init__(self, usage):
self.usage = usage
def generate_chat_completion(self, **kwargs):
yield "answer"
yield {
"type": "metadata",
"usage": self.usage,
"timings": {"prompt_n": 23, "predicted_n": 1283},
}
def _request_completion(monkeypatch, usage):
monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _GgufBackend(usage))
monkeypatch.setattr(inference_route, "_effective_enable_tools", lambda payload: False)
app = FastAPI()
app.include_router(inference_route.router)
app.dependency_overrides[get_current_subject] = lambda: "test-user"
return TestClient(app).post(
"/chat/completions",
json = {
"messages": [{"role": "user", "content": "Why is the sky blue?"}],
"stream": False,
},
)
def test_non_streaming_gguf_completion_includes_generated_usage(monkeypatch):
response = _request_completion(
monkeypatch,
{"prompt_tokens": 23, "completion_tokens": 1283, "total_tokens": 1306},
)
assert response.status_code == 200
usage = response.json()["usage"]
assert usage["prompt_tokens"] == 23
assert usage["completion_tokens"] == 1283
assert usage["total_tokens"] == 1306
assert usage["prompt_tokens_details"] == {"cached_tokens": 0, "audio_tokens": 0}
assert usage["completion_tokens_details"] == {
"reasoning_tokens": 0,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0,
}
def test_non_streaming_gguf_completion_defaults_nullable_usage_to_zero(monkeypatch):
response = _request_completion(
monkeypatch,
{"prompt_tokens": None, "completion_tokens": 1283, "total_tokens": None},
)
assert response.status_code == 200
usage = response.json()["usage"]
assert usage["prompt_tokens"] == 0
assert usage["completion_tokens"] == 1283
assert usage["total_tokens"] == 1283
assert usage["prompt_tokens_details"] == {"cached_tokens": 0, "audio_tokens": 0}
assert usage["completion_tokens_details"] == {
"reasoning_tokens": 0,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0,
}