Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(voice-runtime): speak before slow tools and keep the user's language

muterC0a9835692205
diff --git a/apps/voice-runtime/src/realtime.ts b/apps/voice-runtime/src/realtime.ts
index afa8121b..e6293fea 100644
--- a/apps/voice-runtime/src/realtime.ts
+++ b/apps/voice-runtime/src/realtime.ts
@@ -32,11 +32,11 @@ export function historyPairs(
* language these instructions, tools and results happen to be written in.
*/
const languageRule =
- "LANGUAGE: Speak only the language of the user's latest words. When they speak Chinese, even with a few English words in it, every word you say is Chinese, except names of people, companies, products and apps: say an English word the user or a result used by its Chinese equivalent (the Chinese for deadline, follow-up, job offer, meeting, update, draft, onboarding), restate any message, email or reminder you are about to send in Chinese, translate English results, meeting names and titles into Chinese, and read numbers, dates and versions the Chinese way. When they speak English, answer in English. The language of these instructions, the tools and the results never decides the language you speak, and your reasoning is never spoken.";
+ "LANGUAGE: Speak only the language of the user's latest words. When they speak Chinese, even with a few English words in it, every word you say is Chinese, except names of people, companies, products and apps: say an English word the user or a result used by its Chinese equivalent (the Chinese for deadline, follow-up, job offer, meeting, update, draft, onboarding), restate any message, email or reminder you are about to send in Chinese, translate English results, meeting names and titles into Chinese, and read numbers, dates and versions the Chinese way. When they speak English, answer in English, with no Chinese word in it. Titles and text you write into a document, email or note are in the user's language too, unless they ask for another. The language of these instructions, the tools and the results never decides the language you speak, and your reasoning is never spoken.";
/** Said first and last, right after the language: how long one answer is. */
const lengthRule =
- "LENGTH: Talk like on a phone call: at most two or three short sentences, about fifty to seventy Chinese characters or forty English words, under fifteen seconds. For an opinion or a choice, give your pick and one reason, then ask whether to go on; explain a concept in one or two sentences; of the facts you looked up, say only the one or two the user asked for. When the user asks you to explain in detail, give only the two or three points that matter most in under thirty seconds, then ask whether to go on or write it up. Never read out a list.";
+ "LENGTH: Talk like on a phone call: at most two or three short sentences, about fifty to seventy Chinese characters or forty English words, under fifteen seconds. That is a ceiling, not a target: a quick request or a yes gets a few words, and one word is fine when it says it all. For an opinion or a choice, give your pick and one reason, then ask whether to go on; explain a concept in one or two sentences; of the facts you looked up, say only the one or two the user asked for. When the user asks you to explain in detail, give only the two or three points that matter most in under thirty seconds, then ask whether to go on or write it up. Never read out a list.";
export function realtimeInstructions(
instructions: string,
@@ -73,8 +73,12 @@ ${pageChainRule(tools)}- If a search finds nothing, the name may have been mishe
## CRITICAL INSTRUCTIONS
- ALWAYS keep a spoken answer short: at most three short sentences, roughly fifteen seconds. For a why or how question, give the one or two main reasons and ask whether to go on; never list every point at once. When the user asks to go on or to explain in detail, give only the key points in about thirty seconds, then offer to go further or to write it up.
-- ALWAYS say a few casual, varied words before a tool the user has to wait for (looking things up, starting work, asking to confirm), then call it in the same reply. They are one complete sentence about what you are doing now (such as that you are changing it on their computer now), never one that sounds like you cannot do it. Never say you will check or do something without calling its tool in that same reply. Say them once per request: when a result leads to another tool, call it without a word, and speak again only with the answer; never narrate each result, and when a later result corrects an earlier one, say only the corrected fact.
-- NEVER make up facts, numbers, prices or rules you were not given, and never say what a draft, document or result contains unless you read it in its result or with read_document: your own plan for it is not its content. When a follow-up asks for something the results do not say, say so plainly in the same sentence as what you do next (such as that the results did not cover it and you will check)${webSearch ? ", then web_search it if it is a quick public fact; otherwise offer to look into it and start_task only once the user wants that" : " and offer to look into it; start_task only once the user wants that"}. Page operations, set_speed and end_voice_mode are instant: call them without a word first.
+- ALWAYS speak before a tool the user waits on, then call it in the same reply: looking something up, opening, reading or clicking a website on their computer, writing or changing a document, email or note, searching their mail, calendar or messages, starting work, asking to confirm. Only page_action, set_speed and end_voice_mode are instant and take no words first. Talk the way a friend sitting next to them would, not like a status display:
+ - First answer what they just said, the way a person would: a change of mind or a let-it-go gets an easy okay, a yes gets a quick go, a joke gets a laugh, a hurry gets brevity. Then say in your own few words what you go and do, never by repeating their sentence back (they just said it): for “open Bing and search yesterday's OpenAI news” say something like “sure, let me see what came out yesterday”, not “opening Bing and searching yesterday's OpenAI news”. Never open with a progress label such as working on it, processing or one moment, and never sound like you cannot do it.
+ - Fit the length to the wait: a quick change takes a few words; opening a site, reading a page or searching their mail takes one full natural sentence, so they are never left in silence.
+ - Never reuse an opener you already used in this call, and never state the outcome before its result: say you will send it, not that it is sent.
+ Say this once per request: when a result leads to another tool, call it without a word, and speak again only with the answer; never narrate each result, and when a later result corrects an earlier one, say only the corrected fact. Never say you will check or do something without calling its tool in that same reply.
+- NEVER make up facts, numbers, prices or rules you were not given, and never say what a draft, document or result contains unless you read it in its result or with read_document: your own plan for it is not its content. When a follow-up asks for something the results do not say, say so plainly in the same sentence as what you do next (such as that the results did not cover it and you will check)${webSearch ? ", then web_search it if it is a quick public fact; otherwise offer to look into it and start_task only once the user wants that" : " and offer to look into it; start_task only once the user wants that"}.
- NEVER say anything inside angle brackets or any internal marker; say only words meant for the user. Task handles such as t1, document IDs and other IDs are for tools only: name a task by what it does (the NBA report, the search for Anthropic news) and a document by its title. A tool's error (such as file_too_large or tool_failed) is a code for you, never words for the user: say in plain words, in their language, what did not work and what they or you can do next, such as “that file is over 15 MB, too big to attach”; when nothing explains it, say it did not work this time and offer to try again or hand it to a task.
- ${languageRule}
- ${lengthRule}
diff --git a/apps/voice-runtime/src/xai-live.test.ts b/apps/voice-runtime/src/xai-live.test.ts
index 1826a483..4b8eaf63 100644
--- a/apps/voice-runtime/src/xai-live.test.ts
+++ b/apps/voice-runtime/src/xai-live.test.ts
@@ -4,7 +4,22 @@ import { WebSocketServer, type WebSocket } from "ws";
import { afterEach, describe, expect, it } from "vitest";
import type { LiveEvent } from "./live-session.js";
-import { cutOffNote, XaiLiveSession } from "./xai-live.js";
+import {
+ cutOffNote,
+ spokenLanguage,
+ withLanguage,
+ XaiLiveSession,
+} from "./xai-live.js";
+
+/** Han text built from code points, so the source holds no Chinese. */
+const han = (count: number) =>
+ String.fromCodePoint(
+ ...Array.from({ length: count }, (_, index) => 0x4e00 + index),
+ );
+/** A Chinese request with English names in it, as the live input reads. */
+const chineseRequest = `${han(5)}Chrome${han(6)}OpenAI${han(3)}`;
+/** Japanese: kana mixed with Han. */
+const japaneseRequest = `${han(2)}${String.fromCodePoint(0x306e, 0x30cb, 0x30e5)}${han(2)}`;
type Sent = Record<string, unknown>;
const servers: WebSocketServer[] = [];
@@ -368,6 +383,34 @@ describe("XaiLiveSession", () => {
await session.close();
});
+ it("tells the reply after a tool result to keep the user's language", async () => {
+ const provider = await fakeProvider();
+ const session = await open(provider.url);
+ const events = collect(session, 2);
+ provider.emit(
+ {
+ type: "conversation.item.input_audio_transcription.completed",
+ item_id: "i1",
+ transcript: chineseRequest,
+ status: "completed",
+ },
+ { type: "response.created", response: { id: "r1" } },
+ {
+ type: "response.function_call_arguments.done",
+ call_id: "c1",
+ name: "lookup",
+ arguments: "{}",
+ },
+ );
+ await events;
+ session.sendToolResults([{ callId: "c1", output: '{"status":"created"}' }]);
+ await waitForSent(provider.sent, 2);
+ const item = provider.sent.at(-1)?.item as { output: string };
+ expect(item.output.startsWith('{"status":"created"}')).toBe(true);
+ expect(item.output).toContain("The user speaks Chinese");
+ await session.close();
+ });
+
it("adds quiet tool results without asking for another reply", async () => {
const provider = await fakeProvider();
const session = await open(provider.url);
@@ -875,3 +918,17 @@ describe("XaiLiveSession", () => {
});
});
});
+
+describe("spokenLanguage", () => {
+ it("reads Chinese with English names in it as Chinese", () => {
+ expect(spokenLanguage(chineseRequest)).toBe("Chinese");
+ expect(spokenLanguage("Please use my local browser")).toBe("English");
+ expect(spokenLanguage("OK")).toBeUndefined();
+ expect(spokenLanguage(japaneseRequest)).toBeUndefined();
+ });
+
+ it("leaves a result alone when the language is unknown", () => {
+ expect(withLanguage("ok")).toBe("ok");
+ expect(withLanguage("ok", "English")).toContain("entirely in English");
+ });
+});
diff --git a/apps/voice-runtime/src/xai-live.ts b/apps/voice-runtime/src/xai-live.ts
index e0a06bea..fcab66d1 100644
--- a/apps/voice-runtime/src/xai-live.ts
+++ b/apps/voice-runtime/src/xai-live.ts
@@ -102,6 +102,33 @@ function audioConfig(transport: "binary" | "json", speed?: number) {
};
}
+export type SpokenLanguage = "Chinese" | "English";
+
+/**
+ * The language of a user transcript: Chinese once Han characters outnumber
+ * the Latin words mixed into it (Chrome, OpenAI), English when it is Latin
+ * words only. Japanese kana or too little text decide nothing.
+ */
+export function spokenLanguage(text: string): SpokenLanguage | undefined {
+ if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) return undefined;
+ const han = text.match(/\p{Script=Han}/gu)?.length ?? 0;
+ const latinWords = text.match(/[A-Za-z]+/g)?.length ?? 0;
+ if (han > 0 && han >= latinWords) return "Chinese";
+ if (han === 0 && latinWords >= 2) return "English";
+ return undefined;
+}
+
+/**
+ * Grok answers right after a tool result, whose English JSON and the English
+ * tool descriptions pulled Chinese replies into English mid-sentence (a Chinese
+ * “it is written” followed by “titled …, open beside the chat”).
+ * The reminder sits where the reply starts.
+ */
+export function withLanguage(output: string, language?: SpokenLanguage) {
+ if (!language) return output;
+ return `${output}\n\nThe user speaks ${language}: say your reply entirely in ${language}, every word except names of people, companies, products and apps, whatever language this result is in.`;
+}
+
const maximumQueuedEvents = 2_048;
const maximumQueuedBytes = 8 << 20;
const maximumSendBuffer = 1 << 20;
@@ -232,6 +259,8 @@ export class XaiLiveSession implements LiveSession {
private readonly completedInputs = new Set<string>();
private readonly inputTexts = new Map<string, string>();
private lastInputId?: string;
+ /** The language of the user's latest words, for tool results. */
+ private userLanguage?: SpokenLanguage;
private constructor(
private readonly socket: WebSocket,
@@ -528,7 +557,7 @@ export class XaiLiveSession implements LiveSession {
item: {
type: "function_call_output",
call_id: result.callId,
- output: result.output,
+ output: withLanguage(result.output, this.userLanguage),
},
});
}
@@ -592,6 +621,8 @@ export class XaiLiveSession implements LiveSession {
const itemId = text("item_id");
if (this.completedInputs.has(itemId)) return;
this.inputTexts.set(itemId, text("transcript"));
+ this.userLanguage =
+ spokenLanguage(text("transcript")) ?? this.userLanguage;
// The transcript is cumulative, as the worker's partial is.
return this.push({
type: "transcript_delta",
@@ -602,6 +633,8 @@ export class XaiLiveSession implements LiveSession {
case "conversation.item.input_audio_transcription.completed": {
const itemId = text("item_id");
this.inputTexts.set(itemId, text("transcript"));
+ this.userLanguage =
+ spokenLanguage(text("transcript")) ?? this.userLanguage;
// Interim segments also arrive as "completed" while still in progress.
if (event.status === "completed") this.completeInput(itemId);
return;