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

wqugurub756cd8e9d44
diff --git a/site/changelog.json b/site/changelog.json
index 8050c68..5fb9aff 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -108,7 +108,10 @@
{
"kind": "fixed",
"platforms": [
- "mac"
+ "mac",
+ "windows",
+ "android",
+ "linux"
],
"title": "用 OpenRouter 的默认模型时,纪要不再因为服务商不支持 JSON 格式而写不出来,设置里也不再说这个模型不能用。",
"text": "OpenRouter 有时把 Ling 3.1 Flash 交给不支持 JSON 格式的服务商;现在被拒时会换个问法再问一次。"
diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.cs
index f118872..5d1e2e3 100644
--- a/windows/src/Cicada.Core/Ling.cs
+++ b/windows/src/Cicada.Core/Ling.cs
@@ -301,8 +301,16 @@ public sealed class LingClient
r.Pass(AICheck.StepId.Text, Since(t));
if (c.Provider.Id == "custom")
{
- try { await Chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 30); }
- catch (LingException e) when (e.Failure == LingException.Kind.Http) { r.Fail(AICheck.StepId.Text, AICheck.Reason.NoJSON, e.Status); }
+ const string ask = "Reply with the JSON object {\"ok\": true}.";
+ try { await Chat(ask, "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 30, jsonFallback: false); }
+ catch (LingException e) when (e.Failure == LingException.Kind.Http)
+ {
+ // 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.
+ string? said = null;
+ try { said = await Chat(ask, "Reply.", Priority.Speak, maxTokens: 20, timeout: 30); } catch (LingException) { }
+ if (!AnswersJSON(said)) r.Fail(AICheck.StepId.Text, AICheck.Reason.NoJSON, e.Status);
+ }
}
}
catch (LingException e) { Failed(e, AICheck.StepId.Text); }
@@ -471,9 +479,11 @@ public sealed class LingClient
/// 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's own
/// one for it). `reply` sees the whole reply before its text is read (the check's thinking test).
+ /// A JSON request refused with 400 is asked again without JSON mode unless `jsonFallback` is
+ /// off (the check asks again itself).
public async Task<string> Chat(string content, string instruction, Priority priority, bool json = false,
int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, bool patient = false,
- CancellationToken cancel = default, Action<JsonNode>? reply = null)
+ CancellationToken cancel = default, Action<JsonNode>? reply = null, bool jsonFallback = true)
{
var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);
if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);
@@ -492,7 +502,6 @@ public sealed class LingClient
};
c.Shape(body, maxTokens, templateKwargs: !noTemplateKwargs.ContainsKey(b));
if (json) body["response_format"] = new JsonObject { ["type"] = "json_object" };
- var payload = body.ToJsonString();
var url = new Uri(new Uri(b), "chat/completions");
var waits = RetryWaits(priority, audio is not null, patient);
@@ -507,16 +516,14 @@ public sealed class LingClient
try
{
JsonNode root;
- try { root = await Post(url, payload, k, timeout, cancel); }
- // A strict gateway answers 400 or 422 to a field it doesn't know: asked again
- // without it, and not sent it again until settings change.
- catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 422 && body.ContainsKey("chat_template_kwargs"))
+ try { root = await PostChat(url, body, b, k, timeout, cancel); }
+ catch (LingException e) when (jsonFallback && e.Failure == LingException.Kind.Http && e.Status == 400 && body.ContainsKey("response_format"))
{
- Log.Debug($"ai custom: chat_template_kwargs refused (HTTP {e.Status}), sent without it from now on");
- noTemplateKwargs[b] = true;
- body.Remove("chat_template_kwargs");
- payload = body.ToJsonString();
- root = await Post(url, payload, k, timeout, cancel);
+ // 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.Debug($"ling: {priority} JSON mode refused (400), asking again without it");
+ body.Remove("response_format");
+ root = await PostChat(url, body, b, k, timeout, cancel);
}
reply?.Invoke(root);
var choice = root["choices"]?[0];
@@ -724,6 +731,35 @@ public sealed class LingClient
return [];
}
+ /// A chat completion. A strict gateway answers 400 or 422 to a field it doesn't know: asked
+ /// again without `chat_template_kwargs`, and not sent it again (to `b`) until settings change,
+ /// but only when that request goes through (Ling.swift › postChat): a 400 for something else
+ /// (no JSON mode) must not turn thinking back on for every translation.
+ async Task<JsonNode> PostChat(Uri url, JsonObject body, string b, string k, double timeout, CancellationToken cancel)
+ {
+ try { return await Post(url, body.ToJsonString(), k, timeout, cancel); }
+ catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 422 && body.ContainsKey("chat_template_kwargs"))
+ {
+ var plain = (JsonObject)body.DeepClone();
+ plain.Remove("chat_template_kwargs");
+ JsonNode root;
+ try { root = await Post(url, plain.ToJsonString(), k, timeout, cancel); }
+ catch (LingException) { throw e; }
+ Log.Debug($"ai custom: chat_template_kwargs refused (HTTP {e.Status}), sent without it from now on");
+ noTemplateKwargs[b] = true;
+ return root;
+ }
+ }
+
+ /// A chat reply's text holds a JSON object (a fence or a sentence around it is fine).
+ public static bool AnswersJSON(string? text)
+ {
+ if (text is null) return false;
+ int a = text.IndexOf('{'), z = text.LastIndexOf('}');
+ if (a < 0 || z <= a) return false;
+ try { return JsonNode.Parse(text[a..(z + 1)]) is JsonObject; } catch (JsonException) { return false; }
+ }
+
async Task<JsonNode> Post(Uri url, string payload, string k, double timeout, CancellationToken cancel)
{
using var req = new HttpRequestMessage(HttpMethod.Post, url)
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index d46b79f..c6a3b99 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -1921,6 +1921,59 @@ static class Tests
finally { LingClient.Spacing = old; }
}
+ public static async Task ARefusalForSomethingElseKeepsThinkingOff()
+ {
+ var old = LingClient.Spacing; LingClient.Spacing = 0;
+ try
+ {
+ // 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.
+ var fake = new Service((url, body) => body.Contains("response_format") ? Status(400) : Reply("好"));
+ var (ling, _) = Using(fake, "custom", key: null, new AppSettings { AiCustomBase = "http://192.168.1.20:8000/v1", AiModels = { ["custom"] = "m" } });
+ Equal("好", await ling.Chat("x", "Notes.", Priority.Translate, json: true), "answered without JSON mode");
+ var last = fake.Sent[^1].body;
+ Check(!last.Contains("response_format") && last.Contains("chat_template_kwargs"), "thinking stays off");
+ await ling.Chat("y", "Translate.", Priority.Translate);
+ Check(fake.Sent[^1].body.Contains("chat_template_kwargs"), "and is not dropped for later requests");
+ }
+ finally { LingClient.Spacing = old; }
+ }
+
+ public static async Task ACheckPassesAModelThatAnswersJSONWithoutJSONMode()
+ {
+ var old = LingClient.Spacing; LingClient.Spacing = 0;
+ try
+ {
+ var s = new AppSettings { AiCustomBase = "http://192.168.1.20:8000/v1", AiModels = { ["custom"] = "m" }, AiHearModels = { ["custom"] = "m" } };
+ var fake = new Service((url, body) => url.EndsWith("/models") ? Status(404) : body.Contains("response_format") ? Status(400)
+ : body.Contains("JSON object") ? Reply("```json\n{\"ok\": true}\n```") : Reply("周五发布。"));
+ var (ling, _) = Using(fake, "custom", key: null, s);
+ await ling.Check();
+ Check(ling.Health[AICheck.StepId.Text].Kind == AICheck.Kind.Ok && ling.Health.Failure?.Why != AICheck.Reason.NoJSON, ling.Health.Summary);
+ // One that can't answer JSON at all still fails.
+ var plain = new Service((url, body) => url.EndsWith("/models") ? Status(404) : body.Contains("response_format") ? Status(400) : Reply("ok"));
+ var (other, _) = Using(plain, "custom", key: null, s);
+ await other.Check();
+ Equal(AICheck.Reason.NoJSON, other.Health.Failure?.Why, "no JSON either way");
+ Equal(400, other.Health.Failure?.Code, "the refusal's code");
+ }
+ finally { LingClient.Spacing = old; }
+ }
+
+ public static void AJSONObjectInPlainTextCountsAsJSON()
+ {
+ Check(LingClient.AnswersJSON("{\"ok\": true}"), "bare");
+ Check(LingClient.AnswersJSON("```json\n{\"ok\": true}\n```"), "fenced");
+ Check(LingClient.AnswersJSON("Sure: {\"ok\": true}."), "in a sentence");
+ Check(!LingClient.AnswersJSON("ok") && !LingClient.AnswersJSON("[1]") && !LingClient.AnswersJSON("} {") && !LingClient.AnswersJSON(null), "none");
+ }
+
+ public static void NotesTakeJSONOutOfAFence()
+ {
+ var n = NotesEngine.Parse("```json\n{\"summary\": \"周五发布\", \"topics\": []}\n```", [0.0], 0);
+ Check(n is not null, "fenced notes parse");
+ }
+
// 语音和文字只发给你的服务 (issue #15; the Mac's GoogleOffTests): Google is never asked.
public static void CustomOnlyActsWithTheCustomServiceAlone()