Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

fix(linux): with OpenRouter's default model, notes no longer fail when the host it picks refuses JSON mode

wquguru4483f0e1745d
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index bba1bb8..ba72b72 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -423,12 +423,20 @@ class LingClient:
self.seconds = time.monotonic() - started
r.pass_up_to("text", self.seconds)
if c.provider.id == "custom":
+ ask = "Reply with the JSON object {\"ok\": true}."
try:
- self.chat("Reply with the JSON object {\"ok\": true}.", "Reply.", SPEAK, json=True, max_tokens=20, timeout=30.0)
+ self.chat(ask, "Reply.", SPEAK, json=True, max_tokens=20, timeout=30.0, json_fallback=False)
except LingError as e:
if e.kind != LingError.HTTP:
raise
- r.fail("text", aicheck.NO_JSON, e.status)
+ # JSON mode refused (some hosts of a model do): meetings then ask without it, so
+ # what counts is whether the model still answers with a JSON object.
+ try:
+ said = self.chat(ask, "Reply.", SPEAK, max_tokens=20, timeout=30.0)
+ except LingError:
+ said = None
+ if not answers_json(said):
+ r.fail("text", aicheck.NO_JSON, e.status)
except LingError as e:
self._failed(r, aicheck.classify(e, "text"), "text")
except Exception: # noqa: BLE001
@@ -606,13 +614,15 @@ class LingClient:
def chat(self, content: str, instruction: str, priority: int, json: bool = False, max_tokens: int = 1024,
timeout: float = 30.0, model: str | None = None, audio: bytes | None = None, patient: bool = False,
- reply: list | None = None) -> str:
+ reply: list | None = None, json_fallback: bool = True) -> str:
"""One chat completion. `content` goes in the system message, `instruction` is the fixed user
message, `audio` (a WAV) goes before it for the hear model. Notes and heard audio retry 429s
with backoff (retry_waits); the rest fail fast so the caller can fall back. `patient` (the
final notes) keeps retrying for about a minute. A 429 holds every request start for a while
(_rate_limited), and a retry keeps its place in the queue, so lines stay in order. Audio goes
- to the hear model's address (`hear_url`). `reply`, when given, gets the whole JSON reply."""
+ to the hear model's address (`hear_url`). `reply`, when given, gets the whole JSON reply. A JSON
+ request refused with 400 is asked again without JSON mode unless `json_fallback` is off (the
+ check asks again itself)."""
k = self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
@@ -639,7 +649,16 @@ class LingClient:
ticket = self._acquire(priority, c.provider.spacing, ticket, fail_if_paused=not waits)
started = time.monotonic()
try:
- root = self._post_chat(base, body, k, timeout)
+ try:
+ root = self._post_chat(base, body, k, timeout)
+ except LingError as e:
+ if not (json_fallback and e.kind == LingError.HTTP and e.status == 400 and "response_format" in body):
+ raise
+ # Some hosts of a model refuse JSON mode (on OpenRouter, Novita for Ling 3.1 Flash)
+ # while the model answers JSON anyway: the prompt asks for it, the parsers find it.
+ Log.d("ling: %s JSON mode refused (400), asking again without it" % name)
+ del body["response_format"]
+ root = self._post_chat(base, body, k, timeout)
choices = arr(root.get("choices"))
choice = obj(choices[0]) if choices else None
text = string((obj(choice.get("message")) or {}).get("content")) if choice else None
@@ -840,6 +859,14 @@ class LingClient:
MAX_PAUSE = 30.0
+def answers_json(text: str | None) -> bool:
+ """A chat reply's text holds a JSON object (a fence or a sentence around it is fine)."""
+ if not text:
+ return False
+ a, z = text.find("{"), text.rfind("}")
+ return 0 <= a < z and jsonfmt.parse_object(text[a:z + 1]) is not None
+
+
def retry_waits(priority: int, audio: bool = False, patient: bool = False) -> list:
"""Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes retry a few times; the
rest fail fast so the caller can fall back, except heard audio. A meeting's: there a lost reply
diff --git a/linux/cicada/core/speakers.py b/linux/cicada/core/speakers.py
index 93f087c..26d65f9 100644
--- a/linux/cicada/core/speakers.py
+++ b/linux/cicada/core/speakers.py
@@ -346,8 +346,10 @@ def read(reply: str, s):
"""(found: voice → VoiceGuess, refuted: voice → name). A name given on a line the voice neither said
nor spoke next to is refuted; a name Ling gives two voices goes to the one with more lines."""
from .models import VoiceGuess
+ # Without JSON mode (a host that refuses it) the object may come in a fence or a sentence.
+ a, z = reply.find("{"), reply.rfind("}")
try:
- obj = json.loads(reply)
+ obj = json.loads(reply[a:z + 1]) if 0 <= a < z else None
except ValueError:
return {}, {}
lst = obj.get("speakers") if isinstance(obj, dict) else None
diff --git a/linux/tests/test_core.py b/linux/tests/test_core.py
index e48dbfd..d896e03 100644
--- a/linux/tests/test_core.py
+++ b/linux/tests/test_core.py
@@ -1377,6 +1377,9 @@ class Speakers(Base):
self.assertTrue(found[1].evidence.startswith("00:40 “Thanks"))
self.assertEqual({0: "Christina"}, refuted)
self.assertEqual(({}, {}), speakers.read("not json", s))
+ # Without JSON mode (a host that refuses it) the reply may come fenced.
+ fenced, _ = speakers.read('```json\n{"speakers": [{"speaker": 2, "name": "George", "evidence": "L11"}]}\n```', s)
+ self.assertEqual("George", fenced[1].name)
self.assertIn("说话人1", speakers.content(s))
def test_notes_prompt_names_the_voices(self):
diff --git a/linux/tests/test_custom.py b/linux/tests/test_custom.py
index 17b8d20..bf14e95 100644
--- a/linux/tests/test_custom.py
+++ b/linux/tests/test_custom.py
@@ -164,6 +164,18 @@ class TemplateKwargs(Base):
ling.chat("x", "Translate.", TRANSLATE)
self.assertIn("chat_template_kwargs", fake.sent[-1][1]) # nothing remembered
+ def test_a_refusal_for_something_else_keeps_thinking_off(self):
+ # No JSON mode on this server (OpenRouter's Novita for Ling 3.1 Flash): 400 with or without
+ # the kwargs. Asked again without JSON mode.
+ fake = Fake(lambda u, b: Response(400, "{}") if "response_format" in b else answer("好"))
+ ling, _ = self.client(fake, "custom", key=None, **custom())
+ self.assertEqual("好", ling.chat("x", "Notes.", TRANSLATE, json=True))
+ last = jsonfmt.parse_object(fake.sent[-1][1])
+ self.assertNotIn("response_format", last)
+ self.assertIn("chat_template_kwargs", last)
+ ling.chat("y", "Translate.", TRANSLATE)
+ self.assertIn("chat_template_kwargs", fake.sent[-1][1])
+
def test_other_errors_are_not_retried(self):
fake = Fake(lambda u, b: Response(500, "{}"))
ling, _ = self.client(fake, "custom", key=None, **custom())
@@ -199,6 +211,30 @@ class Check(Base):
self.assertTrue(r.slow)
self.assertIn("思考", r.slow_line())
+ def test_a_model_that_answers_json_without_json_mode_passes(self):
+ def respond(url, body):
+ if url.endswith("/models"):
+ return Response(404, "")
+ if "response_format" in body:
+ return Response(400, "{}")
+ return answer('```json\n{"ok": true}\n```' if "JSON object" in body else "周五发布。")
+ ling, _ = self.client(Fake(respond), "custom", key=None, **custom())
+ ling.check()
+ self.assertIsNone(ling.check_result.failure)
+ # One that can't answer JSON at all still fails.
+ fake = Fake(lambda u, b: Response(404, "") if u.endswith("/models") else Response(400, "{}") if "response_format" in b else answer())
+ ling, _ = self.client(fake, "custom", key=None, **custom())
+ ling.check()
+ self.assertEqual(("text", aicheck.NO_JSON, 400), ling.check_result.failure)
+
+ def test_a_json_object_in_plain_text_counts_as_json(self):
+ from cicada.core.ling import answers_json
+ self.assertTrue(answers_json('{"ok": true}'))
+ self.assertTrue(answers_json('```json\n{"ok": true}\n```'))
+ self.assertFalse(answers_json("ok"))
+ self.assertFalse(answers_json("} {"))
+ self.assertFalse(answers_json(None))
+
def test_bad_address_words_the_local_network(self):
ling, _ = self.client(Fake(lambda u, b: answer()), "custom", key="sk-x", aiCustomBase="http://gpu.example.com/v1")
ling.check()