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(android): with OpenRouter's default model, notes no longer fail when the host it picks refuses JSON mode

wquguru81caf15e491d
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index 1abb5a8..4829e28 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -36,6 +36,9 @@ object ProviderTests {
"aiAThinkingModelIsSeenFromItsReply" to ::thought,
"aiASlowSentenceIsFlagged" to ::slowSentence,
"aiAServerThatRefusesTemplateKwargsIsAskedWithout" to ::kwargsRefused,
+ "aiARefusalForSomethingElseKeepsThinkingOff" to ::jsonModeRefused,
+ "aiACheckPassesAModelThatAnswersJSONWithoutJSONMode" to ::checkWithoutJSONMode,
+ "aiAJSONObjectInPlainTextCountsAsJSON" to ::answersJSON,
"aiCustomCheckTimesARealSentence" to ::customCheckTimes,
"aiTheHearModelMayHaveItsOwnAddress" to ::hearBase,
"aiAHearServerThatCantBeReachedFailsHearing" to ::hearServerDown,
@@ -188,6 +191,41 @@ object ProviderTests {
check("chat_template_kwargs" in deaf.sent[2].second, "still sent")
}
+ fun jsonModeRefused() {
+ // 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.
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"))
+ val fake = Fake({ _, b -> if ("response_format" in b) Transport.Response(400, "{}") else reply("好") })
+ val ling = client(fake, s, key = null)
+ equal("好", ling.chat("x", "Notes.", Priority.Translate, json = true), "answered without JSON mode")
+ val last = fake.sent.last().second
+ check("response_format" !in last && "chat_template_kwargs" in last, "thinking stays off")
+ ling.chat("y", "Translate.", Priority.Translate)
+ check("chat_template_kwargs" in fake.sent.last().second, "and is not dropped for later requests")
+ }
+
+ fun checkWithoutJSONMode() {
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"),
+ aiHearModels = mutableMapOf("custom" to "m"))
+ val fake = Fake({ url, b -> if (url.endsWith("models")) Transport.Response(404, "") else if ("response_format" in b) Transport.Response(400, "{}")
+ else if ("JSON object" in b) reply("```json\n{\"ok\": true}\n```") else reply("周五发布。") })
+ val ling = client(fake, s, key = null)
+ ling.check()
+ check(ling.aiCheck.failure == null, "passes: ${ling.aiCheck.summary}")
+ // One that can't answer JSON at all still fails.
+ val plain = Fake({ url, b -> if (url.endsWith("models")) Transport.Response(404, "") else if ("response_format" in b) Transport.Response(400, "{}") else reply("ok") })
+ val other = client(plain, s, key = null)
+ other.check()
+ equal(AICheck.Reason.NoJSON, other.aiCheck.failure?.reason, "no JSON either way")
+ equal(400, other.aiCheck.failure?.code, "the refusal's code")
+ }
+
+ fun answersJSON() {
+ check(LingClient.answersJSON("{\"ok\": true}"), "bare")
+ check(LingClient.answersJSON("```json\n{\"ok\": true}\n```"), "fenced")
+ check(!LingClient.answersJSON("ok") && !LingClient.answersJSON("} {") && !LingClient.answersJSON(null), "none")
+ }
+
fun customCheckTimes() {
val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"),
aiHearModels = mutableMapOf("custom" to "qwen3-omni"))
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 0ead0dd..e6a95d6 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -1147,6 +1147,8 @@ object Tests {
check(found[1]!!.evidence.startsWith("00:40 “Thanks"), "evidence is the line: ${found[1]!!.evidence}")
equal(mapOf(0 to "Christina"), refuted.toMap(), "no evidence near the voice")
equal(0, SpeakerNamer.read("not json", lines).first.size, "not JSON")
+ // Without JSON mode (a host that refuses it) the reply may come fenced.
+ equal("George", SpeakerNamer.read("```json\n{\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L11\"}]}\n```", lines).first[1]?.name, "fenced")
check(SpeakerNamer.content(lines)!!.contains("说话人1"), "Ling sees the numbers")
check(SpeakerNamer.holds(found[1]!!, 1, lines), "the guess stands while its line does")
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index 241409e..8b00264 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -167,6 +167,13 @@ class LingClient(
val DEFAULT_MODEL = Providers.LING.textModels[0].id
val AUDIO_MODEL = Providers.LING.hearModels[0].id
+ /// A chat reply's text holds a JSON object (a fence or a sentence around it is fine).
+ fun answersJSON(text: String?): Boolean {
+ if (text == null) return false
+ val a = text.indexOf('{'); val z = text.lastIndexOf('}')
+ return a in 0 until z && Json.parseObject(text.substring(a, z + 1)) != null
+ }
+
/// 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 loses the words, and Ling's 429s came in runs of up to ~10 s (two in a row lost a line
@@ -382,10 +389,15 @@ class LingClient(
}
if (c.provider.id == "openrouter") r = r.copy(balance = openRouterBalance(c, k))
if (c.provider.id == "custom") {
+ val ask = "Reply with the JSON object {\"ok\": true}."
try {
- chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 30.0)
+ chat(ask, "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 30.0, jsonFallback = false)
} catch (e: LingException) {
- if (e.kind == LingException.Kind.Http) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoJSON, e.status) else throw e
+ if (e.kind != LingException.Kind.Http) throw e
+ // 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.
+ val said = try { chat(ask, "Reply.", Priority.Speak, maxTokens = 20, timeout = 30.0) } catch (_: LingException) { null }
+ if (!answersJSON(said)) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoJSON, e.status)
}
}
if (r.failure == null) {
@@ -546,11 +558,13 @@ class LingClient(
/// `patient` (the final notes) keeps retrying for about a minute. A 429 holds every request
/// start for a while (rateLimited), and a retry keeps its place in the queue, so lines stay in order.
/// Audio goes to the hear model's address (a custom service may name its own). `reply` sees the
- /// whole reply (the check reads whether the model thought).
+ /// whole reply (the check reads whether the model thought). A JSON request refused with 400 is
+ /// asked again without JSON mode unless `jsonFallback` is off (the check asks again itself).
fun chat(
content: String, instruction: String, priority: Priority, json: Boolean = false,
maxTokens: Int = 1024, timeout: Double = 30.0, model: String? = null, audio: ByteArray? = null,
- audioType: String = "audio/wav", patient: Boolean = false, reply: ((Map<String, Any?>) -> Unit)? = null,
+ audioType: String = "audio/wav", patient: Boolean = false, jsonFallback: Boolean = true,
+ reply: ((Map<String, Any?>) -> Unit)? = null,
): String {
val k = currentKey() ?: throw LingException(LingException.Kind.NoKey)
if (keyState == KeyState.Invalid) throw LingException(LingException.Kind.InvalidKey)
@@ -574,7 +588,15 @@ class LingClient(
ticket = acquire(priority, c.provider.spacing, ticket, failIfPaused = waits.isEmpty())
val started = System.nanoTime()
try {
- val root = postChat(base + "chat/completions", body, k, timeout)
+ val root = try {
+ postChat(base + "chat/completions", body, k, timeout)
+ } catch (e: LingException) {
+ if (!jsonFallback || e.kind != LingException.Kind.Http || e.status != 400 || body.remove("response_format") == null) throw e
+ // 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: $priority JSON mode refused (400), asking again without it")
+ postChat(base + "chat/completions", body, k, timeout)
+ }
reply?.invoke(root)
val choice = root["choices"].arr().firstOrNull().obj()
val text = choice?.get("message").obj()?.get("content").str() ?: throw LingException(LingException.Kind.Parse)
@@ -699,13 +721,15 @@ class LingClient(
/// A chat completion. A custom server that refuses `chat_template_kwargs` (a strict gateway
/// answers 400 or 422 to fields it doesn't know) is asked again without it, and, when that
/// works, isn't sent it again until settings change. A second refusal was about something else
- /// (a hear model that takes no audio): the field stays. `body` loses the field either way.
- private fun postChat(url: String, body: MutableMap<String, Any?>, k: String, timeout: Double): Map<String, Any?> {
+ /// (a hear model that takes no audio, no JSON mode): the field stays, in `body` too, so a
+ /// request asked again without JSON mode still turns thinking off.
+ private fun postChat(url: String, body: Map<String, Any?>, k: String, timeout: Double): Map<String, Any?> {
try {
return post(url, Json.write(body, pretty = false), k, timeout)
} catch (e: LingException) {
- if (e.kind != LingException.Kind.Http || e.status !in listOf(400, 422) || body.remove("chat_template_kwargs") == null) throw e
- val root = post(url, Json.write(body, pretty = false), k, timeout)
+ if (e.kind != LingException.Kind.Http || e.status !in listOf(400, 422) || "chat_template_kwargs" !in body) throw e
+ val plain = LinkedHashMap(body).apply { remove("chat_template_kwargs") }
+ val root = try { post(url, Json.write(plain, pretty = false), k, timeout) } catch (_: LingException) { throw e }
if (!noTemplateKwargs) Log.d("ai custom: chat_template_kwargs refused (HTTP ${e.status}), sent without it from now on")
noTemplateKwargs = true
return root
diff --git a/android/core/src/main/kotlin/cicada/Speakers.kt b/android/core/src/main/kotlin/cicada/Speakers.kt
index a2beddb..ad71caa 100644
--- a/android/core/src/main/kotlin/cicada/Speakers.kt
+++ b/android/core/src/main/kotlin/cicada/Speakers.kt
@@ -158,7 +158,9 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
/// said nor spoke next to is refuted; a name Ling gives two voices goes to the one with more lines.
fun read(reply: String, all: List<TranscriptLine>): Pair<MutableMap<Int, VoiceGuess>, MutableMap<Int, String>> {
val found = LinkedHashMap<Int, VoiceGuess>(); val refuted = LinkedHashMap<Int, String>()
- val list = try { Json.parse(reply).obj()?.get("speakers").arr() } catch (_: Exception) { null } ?: return found to refuted
+ // Without JSON mode (a host that refuses it) the object may come in a fence or a sentence.
+ val a = reply.indexOf('{'); val z = reply.lastIndexOf('}')
+ val list = (if (a in 0 until z) Json.parseObject(reply.substring(a, z + 1)) else null)?.get("speakers").arr() ?: return found to refuted
val voiceOf = SpeakerLabels.voiceNumbers(all).entries.associate { (v, n) -> n to v }
val lines = all.takeLast(400)
fun count(v: Int) = all.count { it.voice == v }