diff --git a/calliope-backend/src/calliope/agent/llm.py b/calliope-backend/src/calliope/agent/llm.py index 7d06d15e..6b77af17 100644 --- a/calliope-backend/src/calliope/agent/llm.py +++ b/calliope-backend/src/calliope/agent/llm.py @@ -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]] = {} diff --git a/calliope-backend/src/calliope/agent/video_agent.py b/calliope-backend/src/calliope/agent/video_agent.py index 31946e82..1574a487 100644 --- a/calliope-backend/src/calliope/agent/video_agent.py +++ b/calliope-backend/src/calliope/agent/video_agent.py @@ -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) diff --git a/calliope-backend/src/calliope/config.py b/calliope-backend/src/calliope/config.py index da4f7b14..7a3988eb 100644 --- a/calliope-backend/src/calliope/config.py +++ b/calliope-backend/src/calliope/config.py @@ -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") diff --git a/calliope-backend/src/calliope/routers/settings.py b/calliope-backend/src/calliope/routers/settings.py index c9dc8d11..88465412 100644 --- a/calliope-backend/src/calliope/routers/settings.py +++ b/calliope-backend/src/calliope/routers/settings.py @@ -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 diff --git a/calliope-backend/tests/test_h3_rewrite_extra_body.py b/calliope-backend/tests/test_h3_rewrite_extra_body.py new file mode 100644 index 00000000..ae5a537c --- /dev/null +++ b/calliope-backend/tests/test_h3_rewrite_extra_body.py @@ -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"] == {}