[Feat] Add text-only OpenAI Decisions API MVP (#60465)
Signed-off-by: Francisco Javier Arceo <4163062+franciscojavierarceo@users.noreply.github.com> Co-authored-by: Codex <noreply@openai.com> Co-authored-by: Misha Goin <mgoin64@gmail.com>
This commit is contained in:
co-authored by
Codex
Misha Goin
parent
ad8d39cbab
commit
c923e7769b
@@ -344,6 +344,35 @@ class TestGeneration:
|
||||
for item_result in result.data:
|
||||
assert 0.0 <= item_result.score <= 1.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_read_returns_server_error_without_traceback(
|
||||
self, monkeypatch
|
||||
):
|
||||
mock_engine = _create_mock_engine()
|
||||
serving = _create_serving(mock_engine)
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
if False:
|
||||
yield None
|
||||
|
||||
mock_engine.generate = mock_generate
|
||||
log_exception = MagicMock()
|
||||
monkeypatch.setattr(
|
||||
"vllm.entrypoints.generate.generative_scoring.serving.logger.exception",
|
||||
log_exception,
|
||||
)
|
||||
request = GenerativeScoringRequest(
|
||||
model=MODEL_NAME,
|
||||
query=[100],
|
||||
items=[[200]],
|
||||
label_token_ids=[1234, 5678],
|
||||
)
|
||||
result = await serving.create_generative_scoring(request, None)
|
||||
|
||||
assert isinstance(result, ErrorResponse)
|
||||
assert result.error.code == 500
|
||||
log_exception.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from vllm.entrypoints.openai.decisions.adapters import (
|
||||
input_text,
|
||||
make_answer,
|
||||
make_read_question,
|
||||
)
|
||||
from vllm.entrypoints.openai.decisions.protocol import DecisionRequest
|
||||
from vllm.entrypoints.openai.decisions.question_types import (
|
||||
StructuredDecisionError,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.cpu_test, pytest.mark.skip_global_cleanup]
|
||||
|
||||
|
||||
def request(**kwargs):
|
||||
return DecisionRequest.model_validate(
|
||||
{
|
||||
"model": "test-model",
|
||||
"input": "The package is broken.",
|
||||
"questions": [{"type": "predicate", "instructions": "Is it damaged?"}],
|
||||
**kwargs,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_predicate_returns_probability_of_true_and_null_name():
|
||||
question = request().questions[0]
|
||||
read = make_read_question(0, question)
|
||||
assert [option.name for option in read.options] == ["false", "true"]
|
||||
assert make_answer(question, [0.1, 0.9], 0.5).model_dump() == {
|
||||
"type": "predicate",
|
||||
"name": None,
|
||||
"probability": 0.9,
|
||||
}
|
||||
|
||||
|
||||
def test_choice_preserves_boolean_and_string_values():
|
||||
question = request(
|
||||
questions=[
|
||||
{
|
||||
"type": "choice",
|
||||
"name": "decision",
|
||||
"instructions": "Select a value.",
|
||||
"choices": [{"value": True}, {"value": "true"}, {"value": False}],
|
||||
}
|
||||
]
|
||||
).questions[0]
|
||||
read = make_read_question(0, question)
|
||||
assert [option.name for option in read.options] == ["true", '"true"', "false"]
|
||||
answer = make_answer(question, [0.7, 0.2, 0.1], 0.5).model_dump()
|
||||
assert answer["name"] == "decision"
|
||||
assert answer["choice"] is True
|
||||
assert answer["probabilities"] == [
|
||||
{"value": True, "probability": 0.7},
|
||||
{"value": "true", "probability": 0.2},
|
||||
{"value": False, "probability": 0.1},
|
||||
]
|
||||
assert answer["confidence"] == pytest.approx(0.35)
|
||||
|
||||
|
||||
def test_score_is_weighted_average_of_zero_based_level_indices():
|
||||
question = request(
|
||||
questions=[
|
||||
{
|
||||
"type": "score",
|
||||
"instructions": "Rate severity.",
|
||||
"levels": [{"label": label} for label in ("low", "medium", "high")],
|
||||
}
|
||||
]
|
||||
).questions[0]
|
||||
answer = make_answer(question, [0.1, 0.7, 0.2], 0.8).model_dump()
|
||||
assert answer["score"] == pytest.approx(1.1)
|
||||
assert answer["probabilities"] == [
|
||||
{"value": 0, "label": "low", "probability": 0.1},
|
||||
{"value": 1, "label": "medium", "probability": 0.7},
|
||||
{"value": 2, "label": "high", "probability": 0.2},
|
||||
]
|
||||
assert answer["confidence"] == pytest.approx(0.56)
|
||||
|
||||
|
||||
def test_text_messages_preserve_evidence_order():
|
||||
parsed = request(
|
||||
input=[
|
||||
{"role": "user", "content": "first"},
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "input_text", "text": "second"},
|
||||
{"type": "input_text", "text": "third"},
|
||||
],
|
||||
},
|
||||
]
|
||||
)
|
||||
assert input_text(parsed.input) == "first\n\nsecond\nthird"
|
||||
assert input_text([]) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("evidence", ["", [], [{"role": "user", "content": []}]])
|
||||
def test_empty_input_is_valid_under_the_openai_schema(evidence):
|
||||
assert input_text(request(input=evidence).input) == ""
|
||||
|
||||
|
||||
def test_score_levels_with_the_same_label_keep_their_positions():
|
||||
question = request(
|
||||
questions=[
|
||||
{
|
||||
"type": "score",
|
||||
"instructions": "Rate severity.",
|
||||
"levels": [
|
||||
{"label": "damage", "description": "cosmetic"},
|
||||
{"label": "damage", "description": "unusable"},
|
||||
],
|
||||
}
|
||||
]
|
||||
).questions[0]
|
||||
read = make_read_question(0, question)
|
||||
assert read.labels == ("A", "B")
|
||||
answer = make_answer(question, [0.1, 0.9], 0.8).model_dump()
|
||||
assert answer["score"] == pytest.approx(0.9)
|
||||
assert [p["value"] for p in answer["probabilities"]] == [0, 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"override,match",
|
||||
[
|
||||
({"input": [{"role": "assistant", "content": "x"}]}, "user"),
|
||||
(
|
||||
{
|
||||
"input": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,AA==",
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
"text input only",
|
||||
),
|
||||
({"input": {"text": "x"}}, "Input should"),
|
||||
({"questions": []}, "at least 1"),
|
||||
(
|
||||
{"questions": [{"type": "predicate", "instructions": "x", "name": None}]},
|
||||
"name must be a string",
|
||||
),
|
||||
({"questions": [{"type": "predicate", "instructions": 1}]}, "valid string"),
|
||||
(
|
||||
{"questions": [{"type": "predicate", "instructions": "x", "criteria": {}}]},
|
||||
"Extra inputs",
|
||||
),
|
||||
({"safety_identifier": "x" * 129}, "at most 128"),
|
||||
({"stream": True}, "Extra inputs"),
|
||||
],
|
||||
)
|
||||
def test_rejects_invalid_or_unsupported_inputs(override, match):
|
||||
with pytest.raises(ValidationError, match=match):
|
||||
request(**override)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("values", [[True, True], ["a", "a"], [1, "a"], [None, "a"]])
|
||||
def test_choice_rejects_duplicates_and_non_string_non_boolean_values(values):
|
||||
with pytest.raises(ValidationError):
|
||||
request(
|
||||
questions=[
|
||||
{
|
||||
"type": "choice",
|
||||
"instructions": "x",
|
||||
"choices": [{"value": v} for v in values],
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"count,valid", [(1, False), (2, True), (255, True), (256, False)]
|
||||
)
|
||||
def test_choice_limits(count, valid):
|
||||
data = {
|
||||
"questions": [
|
||||
{
|
||||
"type": "choice",
|
||||
"instructions": "x",
|
||||
"choices": [{"value": str(i)} for i in range(count)],
|
||||
}
|
||||
]
|
||||
}
|
||||
if valid:
|
||||
assert len(request(**data).questions[0].choices) == count
|
||||
else:
|
||||
with pytest.raises(ValidationError):
|
||||
request(**data)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"count,valid", [(1, False), (2, True), (10, True), (11, False)]
|
||||
)
|
||||
def test_score_limits(count, valid):
|
||||
data = {
|
||||
"questions": [
|
||||
{
|
||||
"type": "score",
|
||||
"instructions": "x",
|
||||
"levels": [{"label": str(i)} for i in range(count)],
|
||||
}
|
||||
]
|
||||
}
|
||||
if valid:
|
||||
request(**data)
|
||||
else:
|
||||
with pytest.raises(ValidationError):
|
||||
request(**data)
|
||||
|
||||
|
||||
def test_question_limit_and_optional_safety_identifier():
|
||||
questions = [{"type": "predicate", "instructions": "x"}] * 200
|
||||
assert len(request(questions=questions, safety_identifier=None).questions) == 200
|
||||
with pytest.raises(ValidationError, match="at most 200"):
|
||||
request(questions=[*questions, questions[0]])
|
||||
|
||||
|
||||
def test_backend_rejects_more_choices_than_single_token_labels():
|
||||
question = request(
|
||||
questions=[
|
||||
{
|
||||
"type": "choice",
|
||||
"instructions": "x",
|
||||
"choices": [{"value": str(i)} for i in range(27)],
|
||||
}
|
||||
]
|
||||
).questions[0]
|
||||
with pytest.raises(StructuredDecisionError, match="at most 26 choices"):
|
||||
make_read_question(0, question)
|
||||
@@ -4,7 +4,7 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.entrypoints.generate.structured_decisions.question_types import (
|
||||
from vllm.entrypoints.openai.decisions.question_types import (
|
||||
QUESTION_TYPES,
|
||||
Option,
|
||||
Question,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
from argparse import Namespace
|
||||
from io import BytesIO
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
@@ -13,6 +17,7 @@ import torch
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
from starlette.datastructures import State
|
||||
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.engine.protocol import EngineClient
|
||||
@@ -23,16 +28,19 @@ from vllm.entrypoints.generate.structured_decisions.protocol import (
|
||||
StructuredDecisionRequest,
|
||||
StructuredDecisionResponse,
|
||||
)
|
||||
from vllm.entrypoints.generate.structured_decisions.question_types import (
|
||||
LABELS,
|
||||
StructuredDecisionError,
|
||||
build_question,
|
||||
)
|
||||
from vllm.entrypoints.generate.structured_decisions.serving import (
|
||||
ServingStructuredDecisions,
|
||||
parse_questions,
|
||||
)
|
||||
from vllm.entrypoints.generate.structured_decisions.strategies import (
|
||||
from vllm.entrypoints.openai.decisions.api_router import register_decisions_api_router
|
||||
from vllm.entrypoints.openai.decisions.question_types import (
|
||||
LABELS,
|
||||
StructuredDecisionError,
|
||||
build_question,
|
||||
)
|
||||
from vllm.entrypoints.openai.decisions.serving import OpenAIServingDecisions
|
||||
from vllm.entrypoints.openai.decisions.state import init_decisions_state
|
||||
from vllm.entrypoints.openai.decisions.strategies import (
|
||||
ClefFlashStrategy,
|
||||
DiffusionGemmaCanvasStrategy,
|
||||
JointSchemaStrategy,
|
||||
@@ -50,7 +58,8 @@ from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.exception_handling.register import (
|
||||
init_exception_handler,
|
||||
)
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.inputs import mm_input, tokens_input
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.multimodal.media import MediaConnector, MediaWithBytes
|
||||
from vllm.outputs import (
|
||||
@@ -67,6 +76,8 @@ TRACE_HEADERS = {
|
||||
"tracestate": "vendor=value",
|
||||
}
|
||||
|
||||
pytestmark = [pytest.mark.cpu_test, pytest.mark.skip_global_cleanup]
|
||||
|
||||
|
||||
def model(architecture: str, logprobs_mode: str = "raw_logprobs") -> Any:
|
||||
return SimpleNamespace(architecture=architecture, logprobs_mode=logprobs_mode)
|
||||
@@ -102,8 +113,10 @@ def test_strategy_selection():
|
||||
def test_route_is_registered_by_default():
|
||||
app = FastAPI()
|
||||
register_structured_decisions_api_router(app)
|
||||
register_decisions_api_router(app)
|
||||
paths = {getattr(route, "path", None) for route in app.routes}
|
||||
assert "/v1/systemone" in paths
|
||||
assert "/v1/decisions" in paths
|
||||
|
||||
|
||||
def test_unsupported_model_returns_501():
|
||||
@@ -125,6 +138,18 @@ def test_unsupported_model_returns_501():
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_decisions_route_returns_501_without_supported_strategy():
|
||||
app = FastAPI()
|
||||
app.state.args = SimpleNamespace(log_error_stack=False)
|
||||
app.state.openai_serving_decisions = None
|
||||
init_exception_handler(app)
|
||||
register_decisions_api_router(app)
|
||||
|
||||
with TestClient(app) as client:
|
||||
response = client.post("/v1/decisions", json=decision_body("decisions"))
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_structured_state_keeps_unicode_in_prompt():
|
||||
state = {"message": "Français 日本語"}
|
||||
assert state_text(state) == '{"message": "Français 日本語"}'
|
||||
@@ -145,6 +170,44 @@ def qwen():
|
||||
return tokenizer, prompt_ids
|
||||
|
||||
|
||||
def test_decisions_state_initializes(qwen):
|
||||
tokenizer, _ = qwen
|
||||
engine = SimpleNamespace(
|
||||
model_config=model("Qwen3ForCausalLM"), renderer=None, input_processor=None
|
||||
)
|
||||
state = State()
|
||||
state.online_renderer = SimpleNamespace(
|
||||
renderer=SimpleNamespace(get_tokenizer=lambda: tokenizer)
|
||||
)
|
||||
state.openai_serving_models = OpenAIServingModels(
|
||||
engine, [BaseModelPath(name="test-model", model_path="test-model")]
|
||||
)
|
||||
args = Namespace(chat_template_content_format="auto")
|
||||
|
||||
strategy = init_decisions_state(engine, state, args, None, None, {}, ("generate",))
|
||||
|
||||
assert isinstance(strategy, NextTokenStrategy)
|
||||
assert isinstance(state.openai_serving_decisions, OpenAIServingDecisions)
|
||||
|
||||
|
||||
def test_unsupported_decisions_state_does_not_block_startup():
|
||||
engine = SimpleNamespace(model_config=model("Qwen3ForCausalLM", "raw_logits"))
|
||||
state = State()
|
||||
|
||||
strategy = init_decisions_state(
|
||||
engine,
|
||||
state,
|
||||
Namespace(chat_template_content_format="auto"),
|
||||
None,
|
||||
None,
|
||||
{},
|
||||
("generate",),
|
||||
)
|
||||
|
||||
assert strategy is None
|
||||
assert state.openai_serving_decisions is None
|
||||
|
||||
|
||||
def test_labels_start_the_reply(qwen):
|
||||
tokenizer, prompt_ids = qwen
|
||||
tail, ids = reply_label_ids(tokenizer, prompt_ids)
|
||||
@@ -646,3 +709,165 @@ def test_liquid_caps_images_like_the_checkpoint():
|
||||
small = Image.new("RGB", (640, 480))
|
||||
assert cap_pixels(small, cap) is small
|
||||
assert NextTokenStrategy.max_image_pixels is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def decision_server(qwen):
|
||||
tokenizer, _ = qwen
|
||||
|
||||
class Engine:
|
||||
model_config = SimpleNamespace(is_encoder_decoder=False)
|
||||
renderer = input_processor = None
|
||||
errored = False
|
||||
failure = None
|
||||
|
||||
def __init__(self):
|
||||
self.admitted = []
|
||||
self.generated = []
|
||||
|
||||
def check_admission(self, count):
|
||||
self.admitted.append(count)
|
||||
|
||||
async def generate(self, prompt, params, request_id, **kwargs):
|
||||
self.generated.append(prompt)
|
||||
if self.failure == "bad_request":
|
||||
raise ValueError("Invalid generation input")
|
||||
if self.failure == "no_result":
|
||||
return
|
||||
ids = params.logprob_token_ids
|
||||
logprobs = {i: Logprob(-math.log(len(ids))) for i in ids}
|
||||
if self.failure == "missing_label":
|
||||
logprobs.pop(ids[-1])
|
||||
output = CompletionOutput(
|
||||
index=0,
|
||||
text="A",
|
||||
token_ids=[ids[0]],
|
||||
cumulative_logprob=None,
|
||||
logprobs=[logprobs],
|
||||
finish_reason="error" if self.failure == "error" else "length",
|
||||
)
|
||||
if self.failure == "no_logprobs":
|
||||
output.logprobs = None
|
||||
yield RequestOutput(
|
||||
request_id=request_id,
|
||||
prompt=None,
|
||||
prompt_token_ids=prompt["prompt_token_ids"],
|
||||
prompt_logprobs=None,
|
||||
outputs=[] if self.failure == "no_output" else [output],
|
||||
finished=True,
|
||||
)
|
||||
|
||||
class Renderer:
|
||||
renderer = SimpleNamespace(get_tokenizer=lambda: tokenizer)
|
||||
|
||||
async def preprocess_chat(self, request, messages, **kwargs):
|
||||
await asyncio.sleep(0)
|
||||
ids = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
add_generation_prompt=True,
|
||||
enable_thinking=False,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
)
|
||||
return [], [tokens_input(ids)]
|
||||
|
||||
engine, renderer = Engine(), Renderer()
|
||||
strategy = NextTokenStrategy(ReadContext(engine, renderer, None, "auto", {}))
|
||||
models = OpenAIServingModels(
|
||||
engine, [BaseModelPath(name="test-model", model_path="test-model")]
|
||||
)
|
||||
request_logger = RequestLogger(max_log_len=None)
|
||||
app = FastAPI()
|
||||
app.state.args = Namespace(log_error_stack=False)
|
||||
app.state.serving_structured_decisions = ServingStructuredDecisions(
|
||||
models, strategy, request_logger=request_logger
|
||||
)
|
||||
app.state.openai_serving_decisions = OpenAIServingDecisions(
|
||||
models, strategy, request_logger=request_logger
|
||||
)
|
||||
init_exception_handler(app)
|
||||
register_structured_decisions_api_router(app)
|
||||
register_decisions_api_router(app)
|
||||
with TestClient(app, headers={"X-Request-Id": "test-request"}) as client:
|
||||
yield SimpleNamespace(
|
||||
client=client, engine=engine, renderer=renderer, tokenizer=tokenizer
|
||||
)
|
||||
|
||||
|
||||
def decision_body(endpoint, count=1):
|
||||
questions = [
|
||||
{"type": "choice", "instructions": f"Question {i}"} for i in range(count)
|
||||
]
|
||||
if endpoint == "decisions":
|
||||
return dict(
|
||||
model="test-model",
|
||||
input="evidence",
|
||||
safety_identifier="test-user",
|
||||
questions=[
|
||||
dict(q, choices=[{"value": "yes"}, {"value": "no"}]) for q in questions
|
||||
],
|
||||
)
|
||||
return dict(
|
||||
model="test-model",
|
||||
state="evidence",
|
||||
questions={
|
||||
str(i): dict(q, criteria={"yes": None, "no": None})
|
||||
for i, q in enumerate(questions)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["decisions", "systemone"])
|
||||
@pytest.mark.parametrize("count,status", [(64, 200), (65, 400)])
|
||||
def test_model_question_limit_is_enforced_before_admission(
|
||||
decision_server, endpoint, count, status
|
||||
):
|
||||
server = decision_server
|
||||
response = server.client.post(
|
||||
f"/v1/{endpoint}", json=decision_body(endpoint, count)
|
||||
)
|
||||
assert response.status_code == status, response.text
|
||||
assert server.engine.admitted == ([count] if status == 200 else [])
|
||||
if status == 400:
|
||||
assert "at most 64" in response.json()["error"]["message"]
|
||||
assert not server.engine.generated
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["decisions", "systemone"])
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
["no_result", "no_output", "error", "no_logprobs", "missing_label", "bad_request"],
|
||||
)
|
||||
def test_generation_failures_are_server_errors(decision_server, endpoint, failure):
|
||||
server = decision_server
|
||||
server.engine.failure = failure
|
||||
response = server.client.post(f"/v1/{endpoint}", json=decision_body(endpoint))
|
||||
status = 400 if failure == "bad_request" else 500
|
||||
assert response.status_code == status, response.text
|
||||
assert response.json()["error"]["type"] == (
|
||||
"BadRequestError" if status == 400 else "InternalServerError"
|
||||
)
|
||||
assert len(server.engine.generated) == 1
|
||||
|
||||
|
||||
def test_decisions_logging_includes_receipt_and_body(
|
||||
decision_server, caplog, monkeypatch
|
||||
):
|
||||
logger_name = "vllm.entrypoints.serve.utils.request_logger"
|
||||
monkeypatch.setattr(logging.getLogger(logger_name), "propagate", True)
|
||||
with caplog.at_level(logging.DEBUG, logger=logger_name):
|
||||
response = decision_server.client.post(
|
||||
"/v1/decisions", json=decision_body("decisions")
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert "Received request decision-test-request" in caplog.text
|
||||
assert "evidence" in caplog.text
|
||||
assert '"safety_identifier":"test-user"' in caplog.text
|
||||
|
||||
|
||||
def test_prompts_retain_question_order(decision_server):
|
||||
server = decision_server
|
||||
response = server.client.post("/v1/decisions", json=decision_body("decisions", 2))
|
||||
assert response.status_code == 200, response.text
|
||||
for i, prompt in enumerate(server.engine.generated):
|
||||
assert f"Question {i}" in server.tokenizer.decode(prompt["prompt_token_ids"])
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
|
||||
MODEL_NAME = "Qwen/Qwen3-0.6B"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server():
|
||||
args = [
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"1024",
|
||||
"--enforce-eager",
|
||||
"--max-num-seqs",
|
||||
"32",
|
||||
"--enable-prefix-caching",
|
||||
]
|
||||
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
|
||||
yield remote_server
|
||||
|
||||
|
||||
def test_openai_decisions_text_questions(server):
|
||||
response = requests.post(
|
||||
server.url_for("v1/decisions"),
|
||||
json={
|
||||
"model": MODEL_NAME,
|
||||
"input": "The package arrived with a broken screen.",
|
||||
"questions": [
|
||||
{"type": "predicate", "instructions": "Is the screen broken?"},
|
||||
{
|
||||
"type": "choice",
|
||||
"name": "department",
|
||||
"instructions": "Which department should handle this?",
|
||||
"choices": [{"value": "returns"}, {"value": "billing"}],
|
||||
},
|
||||
{
|
||||
"type": "score",
|
||||
"name": "damage",
|
||||
"instructions": "Rate the damage.",
|
||||
"levels": [{"label": "undamaged"}, {"label": "broken"}],
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert set(body) == {"model", "answers", "usage"}
|
||||
predicate, choice_answer, score = body["answers"]
|
||||
assert predicate["type"] == "predicate"
|
||||
assert predicate["name"] is None
|
||||
assert 0 <= predicate["probability"] <= 1
|
||||
assert choice_answer["type"] == "choice"
|
||||
assert choice_answer["name"] == "department"
|
||||
assert [p["value"] for p in choice_answer["probabilities"]] == [
|
||||
"returns",
|
||||
"billing",
|
||||
]
|
||||
assert (
|
||||
choice_answer["choice"]
|
||||
== max(choice_answer["probabilities"], key=lambda p: p["probability"])["value"]
|
||||
)
|
||||
assert sum(
|
||||
p["probability"] for p in choice_answer["probabilities"]
|
||||
) == pytest.approx(1)
|
||||
assert score["type"] == "score"
|
||||
assert score["name"] == "damage"
|
||||
assert [p["label"] for p in score["probabilities"]] == ["undamaged", "broken"]
|
||||
assert score["score"] == pytest.approx(
|
||||
sum(p["value"] * p["probability"] for p in score["probabilities"])
|
||||
)
|
||||
usage = body["usage"]
|
||||
assert usage["output_tokens"] == 3
|
||||
assert usage["total_tokens"] == usage["input_tokens"] + usage["output_tokens"]
|
||||
|
||||
|
||||
def test_openai_decisions_rejects_images(server):
|
||||
response = requests.post(
|
||||
server.url_for("v1/decisions"),
|
||||
json={
|
||||
"model": MODEL_NAME,
|
||||
"input": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "https://example.com/image.png",
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"questions": [{"type": "predicate", "instructions": "Is this red?"}],
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "text input only" in response.json()["error"]["message"]
|
||||
@@ -235,13 +235,16 @@ def test_openapi_stateless(case: schemathesis.Case):
|
||||
}.get(key, DEFAULT_TIMEOUT_SECONDS)
|
||||
|
||||
# No need to verify SSL certificate for localhost
|
||||
systemone = case.operation.path == "/v1/systemone"
|
||||
unsupported_decisions = case.operation.path in {
|
||||
"/v1/systemone",
|
||||
"/v1/decisions",
|
||||
}
|
||||
response = case.call_and_validate(
|
||||
verify=False,
|
||||
timeout=timeout,
|
||||
headers={"Content-Type": "application/json"},
|
||||
excluded_checks=[not_a_server_error] if systemone else None,
|
||||
excluded_checks=[not_a_server_error] if unsupported_decisions else None,
|
||||
)
|
||||
if systemone:
|
||||
# SmolVLM does not support structured decisions.
|
||||
if unsupported_decisions:
|
||||
# SmolVLM does not support either decision endpoint.
|
||||
assert response.status_code < 500 or response.status_code == 501
|
||||
|
||||
Reference in New Issue
Block a user