LLM client: per-call extra_body hook; h3_rewrite_extra_body setting for the H3 profile rewrite

LLMClient.chat / chat_stream / _chat_blocking accept extra_body, merged into the
OpenAI-compatible payload (model / messages / stream cannot be overridden). New
setting h3_rewrite_extra_body (default {}, never sent when empty) is passed on
the minimax_h3_ref rewrite only, so e.g. {"chat_template_kwargs":
{"enable_thinking": false}} (Qwen3 on oMLX / vLLM / SGLang) turns a 158 s
thinking preview into a 27 s one without touching story/script calls.
Settings API + config file round-trip; three tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 395a4a03a68444dee8fce83f887682c17d96c6ee)
This commit is contained in:
Justo Stoll
2026-09-06 18:34:59 +02:00
parent 447a4802c9
commit 2d095b7fbb
5 changed files with 108 additions and 3 deletions
+29 -2
View File
@@ -16,6 +16,23 @@ logger = logging.getLogger("calliope.llm")
_STREAM_UNSUPPORTED_STATUS = frozenset({400, 404, 405, 501})
_PROTECTED_PAYLOAD_KEYS = frozenset({"model", "messages", "stream"})
def _merge_extra_body(payload: dict[str, Any], extra_body: dict[str, Any] | None) -> None:
"""Merge caller-supplied OpenAI-compatible request fields into a payload.
Lets one call site pass server-specific knobs (e.g. Qwen3's
``chat_template_kwargs: {"enable_thinking": false}`` on oMLX / vLLM / SGLang)
without the client knowing about them. The identity of the request —
model, messages, stream — cannot be overridden.
"""
for key, value in (extra_body or {}).items():
if key in _PROTECTED_PAYLOAD_KEYS:
continue
payload[key] = value
class LLMClient:
def __init__(
self,
@@ -57,12 +74,16 @@ class LLMClient:
messages: list[dict[str, str]],
temperature: float = 0.7,
response_format: dict[str, str] | None = None,
extra_body: dict[str, Any] | None = None,
) -> str:
try:
parts: list[str] = []
reasoning_chars = 0
async for ev in self.chat_stream(
messages, temperature=temperature, response_format=response_format
messages,
temperature=temperature,
response_format=response_format,
extra_body=extra_body,
):
if ev["type"] == "delta":
parts.append(ev["content"])
@@ -77,7 +98,9 @@ class LLMClient:
"Streaming unavailable (HTTP %s); falling back to blocking call",
exc.response.status_code,
)
return await self._chat_blocking(messages, temperature, response_format)
return await self._chat_blocking(
messages, temperature, response_format, extra_body=extra_body
)
content = "".join(parts).strip()
if not content:
# Thinking models can burn the whole completion in reasoning and
@@ -94,6 +117,7 @@ class LLMClient:
messages: list[dict[str, str]],
temperature: float = 0.7,
response_format: dict[str, str] | None = None,
extra_body: dict[str, Any] | None = None,
) -> str:
payload: dict[str, Any] = {
"model": self.model,
@@ -102,6 +126,7 @@ class LLMClient:
}
if response_format:
payload["response_format"] = response_format
_merge_extra_body(payload, extra_body)
url = f"{self.base_url}/chat/completions"
logger.info("LLM request to %s with model %s", url, self.model)
@@ -205,6 +230,7 @@ class LLMClient:
tools: list[dict[str, Any]] | None = None,
tool_choice: str | dict[str, Any] | None = None,
response_format: dict[str, str] | None = None,
extra_body: dict[str, Any] | None = None,
) -> AsyncIterator[dict[str, Any]]:
"""Streaming completion. Yields event dicts:
@@ -231,6 +257,7 @@ class LLMClient:
payload["tool_choice"] = tool_choice
if response_format:
payload["response_format"] = response_format
_merge_extra_body(payload, extra_body)
url = f"{self.base_url}/chat/completions"
logger.info("LLM stream request to %s with model %s", url, self.model)
tool_acc: dict[int, dict[str, Any]] = {}
@@ -81,7 +81,9 @@ async def _h3_rewrite(
client = LLMClient.for_role("video", timeout=timeout)
try:
return await client.chat(
build_minimax_h3_ref_messages(scene, subjects), temperature=0.4
build_minimax_h3_ref_messages(scene, subjects),
temperature=0.4,
extra_body=settings.h3_rewrite_extra_body or None,
)
except Exception as exc:
logger.warning("MiniMax H3 prompt rewrite failed (%s); using fallback template", exc)
+10
View File
@@ -125,6 +125,14 @@ class Settings(BaseSettings):
queue_max_retries: int = 2
agent_max_steps: int = 24
agent_hardening_prompt: str = DEFAULT_AGENT_HARDENING_PROMPT
# Extra OpenAI-compatible request fields merged into the MiniMax H3 prompt
# rewrite call only (the `minimax_h3_ref` profile). The rewrite is a
# formatting task: on a thinking model it can burn 10k+ reasoning tokens per
# scene, so e.g. {"chat_template_kwargs": {"enable_thinking": false}} (oMLX,
# vLLM, SGLang for Qwen3) makes previews seconds instead of minutes. Empty
# by default — never sent unless set, since strict servers reject unknown
# fields.
h3_rewrite_extra_body: dict[str, Any] = Field(default_factory=dict)
dry_run: bool = False # off by default — real ComfyUI jobs
@property
@@ -313,6 +321,7 @@ class Settings(BaseSettings):
"queue_max_retries": self.queue_max_retries,
"agent_max_steps": self.agent_max_steps,
"agent_hardening_prompt": self.agent_hardening_prompt,
"h3_rewrite_extra_body": dict(self.h3_rewrite_extra_body or {}),
"dry_run": bool(self.dry_run),
}
@@ -395,6 +404,7 @@ class Settings(BaseSettings):
"queue_max_retries": self.queue_max_retries,
"agent_max_steps": self.agent_max_steps,
"agent_hardening_prompt": self.agent_hardening_prompt,
"h3_rewrite_extra_body": dict(self.h3_rewrite_extra_body or {}),
"dry_run": bool(self.dry_run),
}
CONFIG_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
@@ -36,6 +36,7 @@ class SettingsUpdate(BaseModel):
queue_max_retries: int | None = Field(None, ge=0, le=10)
agent_max_steps: int | None = Field(None, ge=1, le=100)
agent_hardening_prompt: str | None = Field(None, max_length=20000)
h3_rewrite_extra_body: dict[str, Any] | None = None
dry_run: bool | None = None
@@ -0,0 +1,65 @@
"""The H3 rewrite's per-call request hook: `h3_rewrite_extra_body`.
The `minimax_h3_ref` profile rewrite is a formatting task; on a thinking model
it can spend 10k+ reasoning tokens per scene. The setting lets an operator
merge server-specific fields into that ONE call (e.g. Qwen3's
`chat_template_kwargs.enable_thinking=false`) without touching story/script
calls. Nothing is sent unless the setting is non-empty.
"""
from __future__ import annotations
import json
import httpx
from calliope.agent.llm import LLMClient
class _CaptureRouter:
def __init__(self) -> None:
self.requests: list[dict] = []
async def __call__(self, request: httpx.Request) -> httpx.Response:
self.requests.append(json.loads(request.content.decode()))
return httpx.Response(200, json={"choices": [{"message": {"content": "ok"}}]})
async def test_extra_body_is_merged_into_the_request(monkeypatch):
router = _CaptureRouter()
client = LLMClient()
monkeypatch.setattr(client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router)))
text = await client._chat_blocking(
[{"role": "user", "content": "hi"}],
extra_body={"chat_template_kwargs": {"enable_thinking": False}, "model": "hijack"},
)
assert text == "ok"
body = router.requests[0]
assert body["chat_template_kwargs"] == {"enable_thinking": False}
assert body["model"] != "hijack" # request identity cannot be overridden
async def test_no_extra_body_sends_nothing_extra(monkeypatch):
router = _CaptureRouter()
client = LLMClient()
monkeypatch.setattr(client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router)))
await client._chat_blocking([{"role": "user", "content": "hi"}])
assert set(router.requests[0]) == {"model", "messages", "temperature"}
def test_setting_roundtrip(client):
assert client.get("/api/settings").json()["h3_rewrite_extra_body"] == {}
r = client.post(
"/api/settings",
json={"h3_rewrite_extra_body": {"chat_template_kwargs": {"enable_thinking": False}}},
)
assert r.status_code == 200
assert client.get("/api/settings").json()["h3_rewrite_extra_body"] == {
"chat_template_kwargs": {"enable_thinking": False}
}
r = client.post("/api/settings", json={"h3_rewrite_extra_body": {}})
assert r.status_code == 200
assert client.get("/api/settings").json()["h3_rewrite_extra_body"] == {}