Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
c59eeb6
[Frontend] Structured decisions API on any generative model
mmastrac Sep 29, 2026
66197f4
[Frontend] Structured decisions: refuse any unknown question field
mmastrac Sep 29, 2026
16fc523
[Frontend] Structured decisions: Jinja decision templates and read st…
mmastrac Sep 29, 2026
374d465
[Frontend] Structured decisions: test that request templates take effect
mmastrac Sep 29, 2026
e82b4c5
[Frontend] Structured decisions: answer macro, and review cleanups
mmastrac Sep 29, 2026
8843350
[Frontend] Structured decisions: trim comments and tests
mmastrac Sep 29, 2026
96cddb0
[Frontend] Structured decisions: models name their read strategy
mmastrac Sep 29, 2026
55366e8
[Frontend] structured decisions: sweep labels per template and tokeni…
mmastrac Sep 29, 2026
142a8f0
[Frontend] structured decisions: seed request field for the label draw
mmastrac Sep 29, 2026
b3b2f20
[Frontend] structured decisions: e2e answers averaged over 16 seeds
mmastrac Sep 29, 2026
ce542c7
[Frontend] structured decisions: comment and docs pass
mmastrac Sep 29, 2026
305fc10
[Frontend] structured decisions: drop request-supplied templates
mmastrac Sep 29, 2026
69ac08b
[Frontend] structured decisions: plain prose in comments, errors and …
mmastrac Sep 29, 2026
31d6459
[Frontend] structured decisions: fix mypy errors
mmastrac Sep 29, 2026
d735dbe
[Frontend] structured decisions: each read sees only its own question
mmastrac Oct 1, 2026
53ea54e
[Frontend] structured decisions: address review (shared read, is_diff…
mmastrac Oct 1, 2026
9a87e76
Merge remote-tracking branch 'upstream/main' into structured-decisions
mmastrac Oct 2, 2026
bdd86e5
[Frontend] structured decisions: opt-in flag, Qwen allowlist, one-opt…
mmastrac Oct 2, 2026
2ea5f52
[Frontend] structured decisions: require a logprobs mode
mmastrac Oct 2, 2026
b90b35b
[Frontend] structured decisions: fixed in-order labels instead of a l…
LucasWilkinson Oct 4, 2026
450f9ea
[Frontend] structured decisions: cap choice at 26 options, labels A-Z
LucasWilkinson Oct 4, 2026
bbf4970
[Frontend] structured decisions: label token ids once, at startup
LucasWilkinson Oct 5, 2026
1281b95
[Frontend] structured decisions: fail at startup when the model canno…
mmastrac Oct 5, 2026
e48e976
Merge branch 'main' into structured-decisions
mmastrac Oct 5, 2026
448d844
Merge branch 'main' into structured-decisions
LucasWilkinson Oct 7, 2026
af0fe17
Fix duplicate chat-template kwargs in decision startup probe
franciscojavierarceo Oct 7, 2026
dccd7a4
Merge branch 'main' into structured-decisions
mmastrac Oct 7, 2026
c85f761
Merge branch 'main' into structured-decisions
mmastrac Oct 7, 2026
8fa7f04
Merge branch 'main' into structured-decisions
LucasWilkinson Oct 7, 2026
fd64fb0
Merge branch 'main' into structured-decisions
LucasWilkinson Oct 8, 2026
c9fb17a
Update vllm/entrypoints/generate/structured_decisions/strategies.py
mmastrac Oct 8, 2026
35c5683
Merge branch 'main' into structured-decisions
mmastrac Oct 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/serving/online_serving/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ For further details on speech to text, please refer to [this page](speech_to_tex
- [Generative Scoring API](generative_scoring.md) (`/generative_scoring`)
- Applicable to [CausalLM models](../../models/generative_models.md) (task `"generate"`).
- Computes next-token probabilities for specified `label_token_ids`.
- [Structured Decisions API](structured_decisions.md) (`/v1/systemone`)
- Applicable to [text generation models](../../models/generative_models.md) with a [chat template](#chat-template).
- Answers typed questions about a state with a probability for every allowed answer.

## Instrumentator APIs

Expand Down
110 changes: 110 additions & 0 deletions docs/serving/online_serving/structured_decisions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Structured Decisions

The `/v1/systemone` endpoint answers a set of typed questions about a state and
returns a probability for every allowed answer.

The endpoint is off unless the server starts with
`--enable-structured-decisions`. With the flag, startup fails for a model that
does not support structured decisions, and with `--logprobs-mode raw_logits` or
`processed_logits`, since `label_mass` needs log probabilities.

## How it works

1. Each question is one read. The user message is the state, followed by the
question and its options, labeled `A`, `B`, `C`, ... in order, and
"Answer with the letter of one option only."
2. The read is the reply's first token. Each label must be one token there,
or the request returns 400.
3. The read returns the logprobs of that question's label tokens. Softmax over
the labels gives the answer's probabilities.

Thinking is off unless `chat_template_kwargs` turns it on.

This endpoint does not serve diffusion models yet.

Every read of a request starts with the state, so with
`--enable-prefix-caching` the state is prefilled once and each further
question prefills only its own text, then reads one token.

## Question types

| type | criteria | answer |
| --- | --- | --- |
| `choice` | map of option name to a description or `null` | `choice`, `probabilities` by option name, `confidence` |

A choice has at least one option. A question id is a non-empty string.

## Example

```bash
curl -s http://localhost:8000/v1/systemone \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen3-0.6B",
"state": {"ticket": "My card was charged twice for one order."},
"questions": {
"team": {
"type": "choice",
"instructions": "Which team should handle this ticket?",
"criteria": {
"billing": "payments and refunds",
"shipping": "deliveries",
"security": "account access"
}
}
},
"chat_template_kwargs": {"enable_thinking": false}
}'
```

Response, with probabilities that depend on the model:

```json
{
"id": "decision-...",
"object": "structured_decision",
"created": 1790000000,
"model": "Qwen/Qwen3-0.6B",
"answers": {
"team": {
"type": "choice",
"choice": "billing",
"probabilities": {"billing": 0.97, "shipping": 0.01, "security": 0.02},
"confidence": 0.90
}
},
"usage": {"input_tokens": 142, "output_tokens": 1},
"diagnostics": {
"team": {"label_mass": 0.93, "argmax_is_label": true}
}
}
```

`diagnostics.label_mass` is the probability the model put on the labels across
its whole vocabulary. A low value means most of the probability went to tokens
that are not labels. `confidence` is the chosen option's probability over the
whole vocabulary: its share of the labels times `label_mass`.

## Labels

Options are labeled `A` to `Z` in the order the request lists them, so a
`choice` has at most 26 options.

## Limits

| limit | value |
| --- | --- |
| questions per request | 64 |
| options per `choice` | 26 |

## Request fields

| field | meaning |
| --- | --- |
| `state` | what the questions are about: a string, or JSON that is sent as its JSON text |
| `questions` | question id to `{type, instructions, criteria}`, asked in this order |
| `instructions` | optional context placed ahead of the questions |
| `chat_template_kwargs` | passed to the chat template, for example `{"enable_thinking": false}` |

A question with any field other than `type`, `instructions` and `criteria` is
rejected with a 400.
1 change: 1 addition & 0 deletions docs/usage/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ When `--api-key` is configured, the following endpoints require Bearer token aut
- `/v1/responses/{response_id}/cancel` - Cancel a response
- `/v1/score` - Scoring API
- `/v1/rerank` - Reranking API
- `/v1/systemone` - Structured decisions API
- `/v1/load_lora_adapter` - Load a LoRA adapter (can alter model behavior; only available when `--enable-lora` is set and `VLLM_ALLOW_RUNTIME_LORA_UPDATING=True`)
- `/v1/unload_lora_adapter` - Unload a LoRA adapter (can alter model behavior; only available when `--enable-lora` is set and `VLLM_ALLOW_RUNTIME_LORA_UPDATING=True`)
- `/inference/v1/generate` - Generate completions (available when `--enable-scale-out` is set, or with `--tokens-only`)
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any

import pytest

from vllm.entrypoints.generate.structured_decisions.question_types import (
QUESTION_TYPES,
Option,
Question,
QuestionType,
StructuredDecisionError,
build_question,
register_question_type,
)


def choice(qid="bucket", criteria=None, instructions="Which team?", max_options=128):
return build_question(
qid,
"choice",
instructions,
criteria or {"billing": "money", "outage": None, "other": None},
max_options,
)


def test_choice_labels_follow_option_order():
q = choice()
assert q.labels == ("A", "B", "C")
assert [a.name for a in q.options] == ["billing", "outage", "other"]
assert q.options[0].description == "money"
wide = choice(criteria={str(i): None for i in range(26)})
assert wide.labels[-1] == "Z"


def test_choice_prompt():
q = choice()
assert q.type.prompt(q) == (
"Question: Which team?\n"
"A: billing - money\n"
"B: outage\n"
"C: other\n"
"Answer with the letter of one option only."
)


def test_choice_answer_shape():
q = choice()
answer = q.type.answer(q, [0.2, 0.7, 0.1], 0.5)
assert answer == {
"type": "choice",
"choice": "outage",
"probabilities": {"billing": 0.2, "outage": 0.7, "other": 0.1},
"confidence": 0.35,
}


@pytest.mark.parametrize(
"qid,type_name,criteria,match",
[
("", "choice", {"x": None, "y": None}, "non-empty"),
("q", "nope", {"x": None, "y": None}, "unknown question type"),
("q", "choice", ["x", "y"], "must map option names"),
],
)
def test_build_question_rejects(qid, type_name, criteria, match):
with pytest.raises(StructuredDecisionError, match=match):
build_question(qid, type_name, "", criteria, 128)


def test_one_option_choice():
q = choice(criteria={"only": None})
assert q.labels == ("A",)
assert q.type.answer(q, [1.0], 0.4)["confidence"] == 0.4


def test_option_limit():
with pytest.raises(StructuredDecisionError, match="at most 2 options"):
choice(criteria={"x": None, "y": None, "z": None}, max_options=2)
with pytest.raises(StructuredDecisionError, match="at most 26 options"):
choice(criteria={str(i): None for i in range(27)})


def test_registered_type_plugs_in():
class BinaryQuestion(QuestionType):
name = "test_binary"

def parse_options(self, qid: str, criteria: Any) -> list[Option]:
return [Option("yes"), Option("no")]

def answer(
self, question: Question, probs: list[float], label_mass: float
) -> dict[str, Any]:
return {"type": self.name, "yes": probs[0]}

register_question_type(BinaryQuestion)
try:
q = build_question("ok", "test_binary", "Is it fine?", None, 128)
assert q.labels == ("A", "B")
assert q.type.answer(q, [0.9, 0.1], 1.0) == {"type": "test_binary", "yes": 0.9}
with pytest.raises(ValueError, match="already registered"):
register_question_type(BinaryQuestion)
finally:
del QUESTION_TYPES["test_binary"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from typing import Any

import pytest
from fastapi import FastAPI

from vllm.entrypoints.generate.structured_decisions.api_router import (
register_structured_decisions_api_router,
)
from vllm.entrypoints.generate.structured_decisions.question_types import LABELS
from vllm.entrypoints.generate.structured_decisions.strategies import (
NextTokenStrategy,
reply_label_ids,
select_read_strategy,
)


def model(architecture: str, logprobs_mode: str = "raw_logprobs") -> Any:
return SimpleNamespace(architecture=architecture, logprobs_mode=logprobs_mode)


def test_strategy_selection():
qwen = "Qwen3ForCausalLM"
assert select_read_strategy(model(qwen)) is NextTokenStrategy
assert select_read_strategy(model(qwen, "processed_logprobs")) is NextTokenStrategy
with pytest.raises(ValueError, match="does not support LlamaForCausalLM"):
select_read_strategy(model("LlamaForCausalLM"))
with pytest.raises(ValueError, match="not raw_logits"):
select_read_strategy(model(qwen, "raw_logits"))


def test_route_needs_the_flag():
for enabled in (False, True):
app = FastAPI()
app.state.args = SimpleNamespace(enable_structured_decisions=enabled)
register_structured_decisions_api_router(app)
paths = {getattr(route, "path", None) for route in app.routes}
assert ("/v1/systemone" in paths) == enabled


@pytest.fixture(scope="module")
def qwen():
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
prompt_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "state"}],
add_generation_prompt=True,
enable_thinking=False,
tokenize=True,
return_dict=False,
)
return tokenizer, prompt_ids


def test_labels_start_the_reply(qwen):
tokenizer, prompt_ids = qwen
tail, ids = reply_label_ids(tokenizer, prompt_ids)
assert tokenizer.decode(tail) == "\n\n"
assert [tokenizer.decode([i]) for i in ids] == list(LABELS)
# After a colon, Qwen writes ":A" as one token, so "A" is not one token.
with pytest.raises(ValueError, match="not one distinct token"):
reply_label_ids(tokenizer, tokenizer.encode("team:"))
Loading
Loading