Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: /v1/responses accepts a JSON text.format together with tools (#782)

Niko1221725022a011e6
diff --git a/serve/responses.py b/serve/responses.py
index c7bc15451..2ef1dffa5 100644
--- a/serve/responses.py
+++ b/serve/responses.py
@@ -476,6 +476,7 @@ class Assembler:
self.seq = 0
self.item = None # the open output item
self.json_text = [] # structured output: the answer, held until it is checked
+ self.called = False # a tool call was made: this turn is not the final answer
reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {}
self.response = {
"id": new_id("resp"), "object": "response", "created_at": int(time.time()), "status": "in_progress",
@@ -579,6 +580,7 @@ class Assembler:
content_index=0, delta=ev.text, logprobs=[]))
elif kind == "tool_start":
out += self.close()
+ out += self._call_started()
out += self._open(self._call_item(ev))
elif kind == "tool_args":
item = self.item
@@ -592,6 +594,7 @@ class Assembler:
item = self.item
if item is None or item.get("call_id") != ev.call.id: # a call that was not announced while written
out += self.close()
+ out += self._call_started()
out += self._open(self._call_item(ev))
item = self.item
if item["type"] == "function_call":
@@ -606,6 +609,28 @@ class Assembler:
out += self.close()
return out
+ def _release(self, text: str) -> list[dict]:
+ """A held structured answer (or the words written beside a tool call) as one message item."""
+ if not text.strip():
+ return []
+ out = self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant",
+ "content": []})
+ self.item["content"][0]["text"] = text
+ out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index,
+ content_index=0, delta=text, logprobs=[]))
+ return out + self.close()
+
+ def _call_started(self) -> list[dict]:
+ """The first tool call of a JSON-format turn: this turn is not the final answer, so what the model wrote
+ before the call goes out as it is, ahead of the call, and the schema is checked on the turn that ends in
+ text (#782)."""
+ out = []
+ if self.json_mode and not self.called:
+ out = self._release("".join(self.json_text))
+ self.json_text = []
+ self.called = True
+ return out
+
def _call_item(self, ev: Event) -> dict:
namespace, name, kind = self.names.get(ev.call.name, (None, ev.call.name, "function"))
if kind == "custom":
@@ -626,13 +651,12 @@ class Assembler:
unfinished = self.item is not None and self.item["type"] in ("function_call", "custom_tool_call")
out = self.close("incomplete" if length or unfinished else "completed")
if self.json_mode:
- text = validate("".join(self.json_text), done.get("finish"))
- out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant",
- "content": []})
- self.item["content"][0]["text"] = text
- out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index,
- content_index=0, delta=text, logprobs=[]))
- out += self.close()
+ text = "".join(self.json_text)
+ self.json_text = []
+ if self.called:
+ out += self._release(text) # beside a tool call: as written (#782)
+ else:
+ out += self._release(validate(text, done.get("finish")))
n = done.get("completion_tokens", 0)
prompt = done.get("prompt_tokens", self.prompt_tokens)
self.response["usage"] = {
diff --git a/serve/server.py b/serve/server.py
index 67ee2e38d..208869102 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -4647,12 +4647,9 @@ def make_handler(svc: Service):
except ValueError as e:
raise ResponsesError(str(e), "input") from None
try:
- messages, validator = prepare_format(responses_api.text_format(req), messages)
+ messages, validator = prepare_format(responses_api.text_format(req), messages, with_tools=bool(tools))
except ValueError as e:
raise ResponsesError(str(e).replace("response_format", "text.format"), "text.format") from None
- if validator is not None and tools:
- raise ResponsesError("a JSON text.format with tools is not supported", "text.format",
- "unsupported_parameter")
noted = svc.__dict__.setdefault("hosted_tools_noted", set()) # said once per tool, not per request
if set(skipped) - noted:
print(f"[strata] /v1/responses: left out the hosted tools {', '.join(sorted(set(skipped) - noted))} "
diff --git a/serve/structured.py b/serve/structured.py
index 101c78f6d..9bed53484 100644
--- a/serve/structured.py
+++ b/serve/structured.py
@@ -80,7 +80,7 @@ def _only_objects(node, root, refs=()):
return isinstance(branches, list) and any(_only_objects(b, root, refs) for b in branches)
-def prepare_format(response_format, messages):
+def prepare_format(response_format, messages, with_tools=False):
if response_format is None:
return messages, None
if not isinstance(response_format, dict):
@@ -136,6 +136,10 @@ def prepare_format(response_format, messages):
"Use every required field, correct types, and only allowed fields. "
"Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" +
json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
+ if with_tools:
+ # /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer
+ directive += ("\nThis applies only to your final answer. To use a tool, call it as usual; the JSON object is "
+ "what you write once you are done with the tools.")
messages = [dict(message) for message in messages]
if messages and messages[0].get("role") == "system":
content = messages[0].get("content") or ""
diff --git a/serve/test_responses.py b/serve/test_responses.py
index 649027025..e2935c489 100644
--- a/serve/test_responses.py
+++ b/serve/test_responses.py
@@ -538,6 +538,59 @@ class ToolRoundTrip(Server):
["multi_agent_v1.spawn_agent", "apply_patch"])
+class JsonFormatWithTools(Server):
+ """#782: Codex's review request carries an `additional_tools` item, tools, and `text.format` json_schema together.
+ A tool call passes through; the schema is checked on the answer that ends in text."""
+ FMT = {"type": "json_schema", "name": "guardian_review", "strict": True,
+ "schema": {"type": "object", "properties": {"outcome": {"type": "string"}, "rationale": {"type": "string"}},
+ "required": ["outcome", "rationale"], "additionalProperties": False}}
+
+ def request(self, **extra):
+ user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "review this call"}]}
+ more = {"type": "additional_tools", "role": "developer", "tools": [
+ {"type": "function", "name": "later_tool", "parameters": {"type": "object"}}]}
+ return {"model": "m", "instructions": "You are a reviewer.", "input": [more, user], "tools": TOOLS,
+ "tool_choice": "auto", "parallel_tool_calls": False, "store": False,
+ "text": {"format": self.FMT}, **extra}
+
+ def script_with(self, text):
+ self.engine.scripts = [self.tok.encode(text, parse_special=True)]
+ self.engine.script = self.engine.scripts[0]
+
+ def test_a_tool_call_passes_through(self):
+ self.script_with(CALL + "<|im_end|>")
+ for stream in (False, True):
+ code, r = self.post(self.request(stream=stream))
+ self.assertEqual(code, 200, r)
+ final = r if not stream else r[-1]["response"]
+ self.assertEqual(final["status"], "completed")
+ self.assertEqual([o["type"] for o in final["output"]][-2:], ["message", "function_call"])
+ call, = [o for o in final["output"] if o["type"] == "function_call"]
+ self.assertEqual((call["type"], call["name"], json.loads(call["arguments"])),
+ ("function_call", "exec_command", {"cmd": "cat a.txt"}))
+ # the model is told the schema is for its final answer, not for a turn that calls a tool
+ self.assertIn("applies only to your final answer", self.tok.decode(self.engine.last_prompt))
+
+ def test_the_final_text_answer_is_the_schema_object(self):
+ self.script_with('</think>\n\n{"outcome": "allow", "rationale": "read only"}<|im_end|>')
+ code, r = self.post(self.request())
+ self.assertEqual(code, 200, r)
+ self.assertEqual(json.loads(r["output"][-1]["content"][0]["text"]),
+ {"outcome": "allow", "rationale": "read only"})
+ code, events = self.post(self.request(stream=True))
+ self.assertEqual(events[-1]["type"], "response.completed")
+ self.assertEqual(len([e for e in events if e["type"] == "response.output_text.delta"]), 1)
+
+ def test_a_text_answer_that_breaks_the_schema_fails_as_without_tools(self):
+ try:
+ import jsonschema # noqa: F401
+ except ImportError:
+ self.skipTest("the schema check needs jsonschema")
+ self.script_with('</think>\n\n{"outcome": 3}<|im_end|>')
+ code, r = self.post(self.request())
+ self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed"))
+
+
class ThreadTitle(Server):
def test_a_thread_title_is_answered_without_the_engine(self):
self.svc.codex_thread_titles = True # opt-in: "codex_thread_titles": true in the config