Spaces:
Running
Running
Sync from felladrin/MiniSearch@f00ca4d
Browse filesFiles changed (6)
10 unmodified lines111213141415161718192010 unmodified lines- The six search results an AI answer reads are now the six with the best relevance score, for the first question and for follow-ups. The result list still shows the search engine's first result at the top, but that result no longer takes one of the six places when its score is low.- A follow-up question with a relative date, such as "what comes out next month", now searches with the month and year written out ("December 2026"), as the first question already did, so the results match the right period.- When a search was still waiting for permission to download the in-browser model and a second one started (for example, by accepting the "Enable AI Responses?" prompt with AI responses already on), allowing the download loaded the model twice at the same time, and both answers failed with a file-lock error. Now only the newest search loads the model.- A follow-up question with a relative date ("who won it last year", "明年的呢") now keeps that date in its search query more often, so the date anchor turns it into the right year instead of the model writing a year itself ("2023" for last year). Measured with Gemma 3 4B in the browser on three such questions, three runs each: the relative date reached the anchor in 6 of 9 runs, against 3 of 9 before. When the model still writes the year itself, it can still be wrong.- A follow-up question with a relative date ("who won it last year", "明年的呢") now keeps that date in its search query more often, so the date anchor turns it into the right year instead of the model writing a year itself ("2023" for last year). Measured with Gemma 3 4B in the browser on three such questions, three runs each: the relative date reached the anchor in 6 of 9 runs, against 3 of 9 before.- The search query of a follow-up question no longer keeps the quote marks some models wrap it in (“ ”, 「 」, « »), as it already did with straight quotes.- The search query of a follow-up question in Chinese, Japanese, Korean, Thai, Greek or Hebrew now stays in that language: when the model writes it in another script, the query is translated back, and when that fails too, the typed question is searched. Measured with Gemma 3 4B in the browser, "它大概多少钱" after a question about Apple's new phone searched in Chinese, naming the phone, in 9 of 9 runs; before, the query came out in Turkish, Persian or English in most runs. A question in another script (Latin, Arabic, Cyrillic...) whose query changes script also searches for the typed question now.- A follow-up question with a relative date now searches for the date the user meant even when the model writes a year of its own: "明年的呢" after a question about Apple's new phone used to search "苹果 2025 新手机 发布时间", and now searches "苹果 新手机 发布时间 2027年". The year comes from the question as typed, and a year the user wrote is kept. Measured with Gemma 3 4B in the browser on three such questions, nine runs each: the right date reached the search in 27 of 27 runs, against 17 of 27 with the old code on the same queries.
## 2026-11-18
286 unmodified lines287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325286 unmodified lines expect(mockSearchImages).toHaveBeenCalledWith(anchoredQuery, 10); });
it("replaces the year the model wrote with the one the question means", async () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-11-19T12:00:00Z")); mockGenerateRelatedSearchQuery.mockResolvedValueOnce( "who won world series 2026", ); mockSearchText.mockResolvedValueOnce({ results: [], stale: false });
try { await runFollowUpSearch( [ { role: "user", content: "who won the world series" }, { role: "assistant", content: "The Dodgers won the 2026 World Series.", }, { role: "user", content: "who won it last year" }, ], "who won it last year", makeSettings(), [], [], ); } finally { vi.useRealTimers(); }
expect(mockSearchText).toHaveBeenCalledWith( "who won world series 2025", 10, ); });
it("refreshes text results when enabled", async () => { mockSearchText.mockResolvedValueOnce({ results: [["Title", "snippet", "https://new.com"]],11234172 unmodified lines177178179180180181182183184185186187import { normalizeRelativeDates } from "@shared/relativeDates";import { normalizeFollowUpDates } from "@shared/relativeDates";import { getCurrentSearchRunId, type ImageResults,172 unmodified lines const relatedQuery = await generateRelatedSearchQuery([...messages]); // Same anchor as the first search in `startTextSearch`: "next month" names no // year to the engine, and only this machine's clock knows which one is meant. const searchQuery = normalizeRelativeDates( const searchQuery = normalizeFollowUpDates( relatedQuery || currentInput, messages .filter(({ role }) => role === "user") .map(({ content }) => content), new Date(), { maxLength: 2000 }, ).searchQuery;65 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920065 unmodified lines ).toBe("Avengers: Doomsday release delay reasons"); });
const chineseFollowUp = [ { role: "user", content: "苹果什么时候发布新手机" }, { role: "assistant", content: "苹果通常在九月发布新款 iPhone。" }, { role: "user", content: "它大概多少钱" }, ] as const;
it("keeps a query that shares the question's script, with one model call", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce("iPhone价格大概多少钱");
expect(await generateRelatedSearchQuery([...chineseFollowUp])).toBe( "iPhone价格大概多少钱", ); expect(mockGenerateReplyToMessages).toHaveBeenCalledTimes(1); });
it("checks a Chinese question even when a brand name outweighs the Chinese", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce("iPhone Pro Max price");
await generateRelatedSearchQuery([ { role: "user", content: "那 iPhone Pro Max 呢" }, ]);
const [messages] = mockGenerateReplyToMessages.mock.calls[1]; expect(messages[0].content).toContain("into Chinese"); });
it.each([ ["what are the side effects of β-blockers", "beta blocker side effects"], ["difference between α and β error", "alpha beta error difference"], ["what are γδ T cells", "gamma delta T cells function"], ])("keeps the English query for %s", async (question, reply) => { mockGenerateReplyToMessages.mockResolvedValueOnce(reply);
expect( await generateRelatedSearchQuery([{ role: "user", content: question }]), ).toBe(reply); expect(mockGenerateReplyToMessages).toHaveBeenCalledTimes(1); });
it.each([["Xiaomi founder 雷军"], ["Tencent founder 马化腾"]])( "keeps an English query that adds a native name: %s", async (reply) => { mockGenerateReplyToMessages.mockResolvedValueOnce(reply);
expect( await generateRelatedSearchQuery([ { role: "user", content: "who founded it" }, ]), ).toBe(reply); expect(mockGenerateReplyToMessages).toHaveBeenCalledTimes(1); }, );
it("keeps a Chinese query for a question that is mostly a brand name", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce("苹果手机价格");
expect( await generateRelatedSearchQuery([{ role: "user", content: "iPhone呢" }]), ).toBe("苹果手机价格"); });
it("keeps a Japanese query that adds kanji to a question in kana", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce("東京タワー 入場料");
expect( await generateRelatedSearchQuery([ { role: "user", content: "それはいくらですか" }, ]), ).toBe("東京タワー 入場料"); expect(mockGenerateReplyToMessages).toHaveBeenCalledTimes(1); });
it.each([ ["它大概多少钱", "Chinese"], ["東京タワーの高さは", "Japanese"], ["그거 얼마예요", "Korean"], ])( "asks for a translation into the language of %s", async (question, language) => { mockGenerateReplyToMessages.mockResolvedValueOnce("iPhone fiyatı kaç TL");
await generateRelatedSearchQuery([{ role: "user", content: question }]);
const [messages] = mockGenerateReplyToMessages.mock.calls[1]; expect(messages).toHaveLength(1); expect(messages[0].content).toContain(`into ${language}`); expect(messages[0].content).toContain("iPhone fiyatı kaç TL"); }, );
it("uses a translation that ends with a line break", async () => { mockGenerateReplyToMessages .mockResolvedValueOnce("iPhone price in China") .mockResolvedValueOnce("iPhone 价格\n");
expect(await generateRelatedSearchQuery([...chineseFollowUp])).toBe( "iPhone 价格", ); });
it("translates a query that mixes in another non-Latin script", async () => { mockGenerateReplyToMessages .mockResolvedValueOnce("iPhone قیمت大概多少钱") .mockResolvedValueOnce("iPhone 价格大概多少钱");
expect(await generateRelatedSearchQuery([...chineseFollowUp])).toBe( "iPhone 价格大概多少钱", ); });
it("falls back to the typed question when the translation misses too", async () => { mockGenerateReplyToMessages .mockResolvedValueOnce("iPhone fiyatı kaç TL") .mockResolvedValueOnce("iPhone قیمت چقدر است؟");
expect(await generateRelatedSearchQuery([...chineseFollowUp])).toBe(""); });
it("falls back without a translation when the script has no single language", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce("iPhone price");
expect( await generateRelatedSearchQuery([ { role: "user", content: "сколько он стоит" }, ]), ).toBe(""); expect(mockGenerateReplyToMessages).toHaveBeenCalledTimes(1); });
it("returns nothing when the generation fails", async () => { mockGenerateReplyToMessages.mockRejectedValueOnce(new Error("offline"));
1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415519 unmodified lines17517617730313233343536371781791801811821831841 unmodified lineimport { generateReplyToMessages } from "./textGeneration";import type { ChatMessage } from "./types";
const SCRIPTS = { Latin: /\p{Script=Latin}/gu, Arabic: /\p{Script=Arabic}/gu, Bengali: /\p{Script=Bengali}/gu, Cyrillic: /\p{Script=Cyrillic}/gu, Devanagari: /\p{Script=Devanagari}/gu, Greek: /\p{Script=Greek}/gu, Hangul: /\p{Script=Hangul}/gu, Hebrew: /\p{Script=Hebrew}/gu, Thai: /\p{Script=Thai}/gu, // Japanese mixes kanji and kana, so they count as one script. CJK: /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu,};
type Script = keyof typeof SCRIPTS;
const SCRIPT_NAMES = Object.keys(SCRIPTS) as Script[];
/** * Scripts that name the question's language, so a translation can ask for it. * CJK is Chinese unless the question has kana. Arabic, Bengali, Cyrillic and * Devanagari each serve several languages, and naming the wrong one would * translate the query away from the user's language. */const LANGUAGE_BY_SCRIPT: Partial<Record<Script, string>> = { Greek: "Greek", CJK: "Chinese", Hangul: "Korean", Hebrew: "Hebrew", Thai: "Thai",};
function countLetters(text: string, script: Script): number { return text.match(SCRIPTS[script])?.length ?? 0;}
/** * A CJK character or a Hangul syllable is a word on its own. In the other * scripts it takes three letters, because English questions write Greek * letters as symbols, alone or in pairs ("α and β error", "γδ T cells"). */function countWords(text: string, script: Script): number { if (script === "CJK" || script === "Hangul") return countLetters(text, script); const word = new RegExp(`(?:${SCRIPTS[script].source}){3,}`, "gu"); return text.match(word)?.length ?? 0;}
/** * Brand names make Latin letters outnumber the Chinese ones in "iPhone呢", so * any other script with a word wins over Latin. */function questionScript(question: string): Script | undefined { let script: Script | undefined; let most = 0; for (const candidate of SCRIPT_NAMES) { const count = countWords(question, candidate); if (candidate !== "Latin" && count > most) { script = candidate; most = count; } } return script ?? (countLetters(question, "Latin") > 0 ? "Latin" : undefined);}
/** * Latin letters are allowed anywhere, because correct Chinese queries carry * brand names ("iPhone价格"). Another script the question does not use marks * a drift, even next to the right one ("iPhone قیمت大概多少钱"), from three * letters on: one or two are a short name or a symbol ("Ω"). A Latin * question has no language to translate into, so a native name next to its * Latin words is kept ("Tencent founder 马化腾"). */function isWrittenLike(query: string, question: string): boolean { const script = questionScript(question); if (!script) return true; if (countLetters(query, script) === 0) return false; if (script === "Latin") return true; return SCRIPT_NAMES.every( (other) => other === "Latin" || countLetters(question, other) > 0 || countLetters(query, other) < 3, );}
function questionLanguage(question: string): string | undefined { const script = questionScript(question); if ( script === "CJK" && /[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(question) ) return "Japanese"; return script && LANGUAGE_BY_SCRIPT[script];}
function extractQuery(reply: string): string { return ( (reply.trim().split("\n").pop()?.trim() ?? "") // Models also wrap the query in the quote marks of other languages. .replace(/^["'“”‘’「」『』«»]/, "") .replace(/["'“”‘’「」『』«»]$/, "") );}
/** An empty query makes the caller search for the question as typed. */function fallBackToQuestion(query: string): string { addLogEntry( `Follow-up search query '${query}' is not in the question's language; searching for the question instead`, ); return "";}
/** * Small models drift into another language when they write the query (Gemma * 3 4B turned "它大概多少钱" into Turkish or Persian), and asking harder in the * main prompt did not hold. A translation that names the language did, so * a query in the wrong script gets one, and the typed question is the * fallback when the language has no single name or the translation misses. */async function keepQuestionLanguage( query: string, question: string,): Promise<string> { if (query === "" || isWrittenLike(query, question)) return query;
const language = questionLanguage(question); if (!language) return fallBackToQuestion(query);
addLogEntry(`Translating follow-up search query '${query}' into ${language}`); const translation = extractQuery( await generateReplyToMessages([ { role: "user", content: `Translate this web search query into ${language}, keeping its meaning.
${query}
Respond with only the translated search query.`, }, ]), );
return isWrittenLike(translation, question) ? translation : fallBackToQuestion(translation);}
export async function generateRelatedSearchQuery( conversation: ChatMessage[],): Promise<string> {19 unmodified linesRespond with only the search query text, no quotes or additional text.`, };
const raw = await generateReplyToMessages(prompt);
let webSearchQuery = raw.split("\n").reverse()[0]?.trim() ?? "";
// Models also wrap the query in the quote marks of other languages. webSearchQuery = webSearchQuery .replace(/^["'“”‘’「」『』«»]/, "") .replace(/["'“”‘’「」『』«»]$/, ""); const webSearchQuery = await keepQuestionLanguage( extractQuery(await generateReplyToMessages(prompt)), question, );
addLogEntry(`Generated follow-up search query: '${webSearchQuery}'`);
263 unmodified lines264265266267267268269270263 unmodified linesSave to history database```
Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it with `normalizeRelativeDates`, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19.Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19. The model still drops the phrase at times, writing a year of its own ("苹果 2025 新手机 发布时间" for 明年的呢), so the anchors come from the question the user typed: `normalizeFollowUpDates` (`shared/relativeDates.ts`) removes the years the model wrote and the user did not type in any message, then appends the question's anchors. A month the model writes without a year ("November releases") stays in the query next to the anchor. A query that still comes out in another script than the question's (Turkish or Persian for a Chinese question) gets one more call that translates it, naming the language: that held where asking harder in the main prompt did not. The question's script is the non-Latin one with the most words, since brand names can outnumber the Chinese letters ("iPhone呢"). A CJK character or a Hangul syllable counts as a word, while the other scripts need three letters in a row, because English questions write Greek letters as symbols, alone or in pairs ("α and β error", "γδ T cells"). Latin counts only when nothing else is there, and then any Latin letter in the query is enough ("Tencent founder 马化腾"). A question whose script serves several languages (Arabic, Bengali, Cyrillic, Devanagari) or is Latin cannot be named safely, so its query falls back to the typed question, as does a translation that misses again. Known gaps: Latin-script drift (English to French) is not caught; a Chinese query passes for a Japanese question, since kanji and kana count as one script; a Japanese question in kanji only is translated as Chinese; and an English question that quotes a word in another script gets its query translated into that language ("who is 雷军") or searched as typed when the script has no single language ("who is Путин").
### Text Generation State Machine
changelog.md+3-1
client/modules/chatHelpers.test.ts+33
client/modules/chatHelpers.ts+5-2
client/modules/relatedSearchQuery.test.ts+129
client/modules/relatedSearchQuery.ts+152-8
docs/ai-integration.md+1-1