Spaces:
Running
Running
Sync from felladrin/MiniSearch@ad583e0
Browse filesFiles changed (14)
- .env.example+3
- changelog.md+1
- client/components/App/App.test.tsx+1
- client/modules/config.test.ts+1
- client/modules/config.ts+2
- client/modules/pubSub.test.ts+5-2
- client/modules/settings.test.ts+1
- client/modules/textGeneration.responsePersistence.test.ts+10
- client/modules/textGeneration.ts+1-1
- client/modules/textGenerationUtilities.test.ts+36-17
- client/modules/textGenerationUtilities.ts+14-8
- client/modules/textGenerationWithInternalApi.ts+1-1
- client/modules/textGenerationWithOpenAi.ts+1-1
- docs/configuration.md+4-1
18 unmodified lines19202122232425262718 unmodified lines# The model for the internal OpenAI compatible API.INTERNAL_OPENAI_COMPATIBLE_API_MODEL=""
# The context window, in tokens, of the internal OpenAI compatible API's models. The browser sizes the search results, page excerpts, chat history and the answer's `max_tokens` from it. Leave blank for 131072 (128K).INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH=""
# The reasoning effort for the internal OpenAI compatible API, sent as `reasoning_effort` (e.g. "none", "low", "medium", "high"). Leave blank to use the API's default.INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT=""
10 unmodified lines1112131415161710 unmodified lines
## 2026-11-25
- Answers from the instance's own AI are no longer cut short. The browser sized every request to it for a 4096-token window, so with search results and page excerpts in the prompt the answer often got fewer than 2048 tokens, and the server capped it at 2048 anyway; a reasoning model could spend all of that thinking. The window now defaults to 131072 tokens (128K) and can be set with `INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH`, and the server's cap, `MODEL_DEFAULT_MAX_TOKENS`, now defaults to 8192. With the larger window, more of each page read also goes into the prompt.- Admins can now set the reasoning effort of the instance's own AI. The new `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` variable is sent as `reasoning_effort` on every request to the internal OpenAI-compatible API, for every model in the list, so a reasoning model can be told to think less (or not at all) and answer faster. Left empty, nothing is sent and the API keeps its own default.
- Follow-up questions are now shown when the main AI answer came back empty. The first follow-up question and its answer used to be hidden for good, "Copy conversation" left them out, and they could not be regenerated. A last answer that came back empty now shows "No response" with its Re-generate button, instead of showing nothing to retry from.27 unmodified lines2829303132333427 unmodified lines wllamaDefaultGpuModelId: "gemma-3-4b", internalApiEnabled: false, internalApiName: "Internal API", internalApiContextLength: 131072, defaultInferenceType: "browser", searchToken: "a".repeat(64), parentWindowOrigins: ["https://huggingface.co"],10 unmodified lines1112131415161710 unmodified lines wllamaDefaultGpuModelId: "some-gpu-model", internalApiEnabled: true, internalApiName: "Custom LLM", internalApiContextLength: 131072, defaultInferenceType: "internal", searchToken: "a".repeat(64), parentWindowOrigins: ["https://huggingface.co"],7 unmodified lines89101112131420 unmodified lines353637383940417 unmodified lines
import { DEFAULT_INFERENCE_TYPE, DEFAULT_INTERNAL_API_CONTEXT_LENGTH, DEFAULT_INTERNAL_API_NAME, DEFAULT_WLLAMA_GPU_MODEL_ID, DEFAULT_WLLAMA_MODEL_ID,20 unmodified lines wllamaDefaultGpuModelId: DEFAULT_WLLAMA_GPU_MODEL_ID, internalApiEnabled: false, internalApiName: DEFAULT_INTERNAL_API_NAME, internalApiContextLength: DEFAULT_INTERNAL_API_CONTEXT_LENGTH, defaultInferenceType: DEFAULT_INFERENCE_TYPE, searchToken: "", parentWindowOrigins: [],161 unmodified lines16216316416516516616716816917016817117217363 unmodified lines237238239240241242243161 unmodified lines getDefaultChatCompletionCreateParamsStreaming, getEffectiveContextSize, } = await import("./textGenerationUtilities"); expect(getDefaultChatCompletionCreateParamsStreaming([]).max_tokens).toBe( expect( (await getDefaultChatCompletionCreateParamsStreaming([])).max_tokens, ).toBe(defaultSettings.openAiContextLength); expect(await getEffectiveContextSize()).toBe( defaultSettings.openAiContextLength, ); expect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength); });});
63 unmodified lines wllamaDefaultGpuModelId: "gemma-3-4b", internalApiEnabled: false, internalApiName: "Internal API", internalApiContextLength: 131072, defaultInferenceType: "openai", searchToken: "a".repeat(64), parentWindowOrigins: ["https://huggingface.co"],18 unmodified lines1920212223242518 unmodified lines wllamaDefaultGpuModelId: "gemma-3-4b", internalApiEnabled: false, internalApiName: "Internal API", internalApiContextLength: 131072, defaultInferenceType: "browser", searchToken: "a".repeat(64), parentWindowOrigins: ["https://huggingface.co"],17 unmodified lines1819202122232425262728293031323317 unmodified lines
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
// The internal API sizes its budgets from /api/config; `fetch` below only// answers /inference.vi.mock("./config", async (importOriginal) => { const actual = await importOriginal<typeof import("./config")>(); return { ...actual, getConfig: vi.fn(() => Promise.resolve(actual.FALLBACK_CONFIG)), };});
vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
vi.mock("./pageContent", () => ({395 unmodified lines396397398399399400401402395 unmodified lines let response = "";
try { const contextSize = getEffectiveContextSize(); const contextSize = await getEffectiveContextSize(); // The newest message is the question being answered. It always goes out, // so the one case with no usable prompt is a question larger than the // whole window; that fails here, before anything is generated.15 unmodified lines16171819202122232425262728307 unmodified lines33633733833233934034133534234334434534634734834935035133833935235335435534235635735835934636036136236336435136536636736816 unmodified lines38538638737438838939039139239338039439539639739839938640040140240339040440540640740839440941041141241339941441541641741841940540642042142242342442541042642742841242943043143243343415 unmodified lines reasoningStartMarker?: string; reasoningEndMarker?: string; }, internalApiContextLength: 131072,}));
vi.mock("./config", () => ({ getConfig: async () => ({ internalApiContextLength: state.internalApiContextLength, }),}));
vi.mock("./pubSub", () => ({307 unmodified lines});
describe("getEffectiveContextSize", () => { it("follows the configured context on the OpenAI-compatible backend", () => { it("follows the configured context on the OpenAI-compatible backend", async () => { state.settings = { inferenceType: "openai", openAiContextLength: 32768 };
expect(getEffectiveContextSize()).toBe(32768); expect(await getEffectiveContextSize()).toBe(32768); });
it("follows the server's context length on the internal API, whatever the setting says", async () => { state.settings = { inferenceType: "internal", openAiContextLength: 4096 }; state.internalApiContextLength = 65536;
expect(await getEffectiveContextSize()).toBe(65536); });
it("stays at the default on every other backend, whatever the setting says", () => { for (const inferenceType of ["browser", "horde", "internal"]) { it("stays at the default on the in-browser and AI Horde backends, whatever the setting says", async () => { for (const inferenceType of ["browser", "horde"]) { state.settings = { inferenceType, openAiContextLength: 32768 };
expect(getEffectiveContextSize()).toBe(4096); expect(await getEffectiveContextSize()).toBe(4096); } });
it("falls back to the default when the setting cannot size a window", () => { it("falls back to the default when the setting cannot size a window", async () => { // A cleared numeric input can persist as an empty string. for (const openAiContextLength of [undefined, 0, -1, "" as never]) { state.settings = { inferenceType: "openai", openAiContextLength };
expect(getEffectiveContextSize()).toBe(4096); expect(await getEffectiveContextSize()).toBe(4096); } });});16 unmodified lines state.settings = { inferenceType: "openai", openAiContextLength: 4096 }; });
it("leaves the prompt room in the window instead of asking for all of it", () => { it("leaves the prompt room in the window instead of asking for all of it", async () => { const messages = getDefaultChatMessages(searchResultsOf(2500)); const promptTokens = countPromptTokens(messages); expect(promptTokens).toBeGreaterThan(2000);
const { max_tokens } = getDefaultChatCompletionCreateParamsStreaming(messages); await getDefaultChatCompletionCreateParamsStreaming(messages);
expect(promptTokens + max_tokens).toBeLessThanOrEqual(4096); expect(max_tokens).toBeGreaterThan(1000); });
it("still asks for a short answer when the prompt nearly fills the window", () => { it("still asks for a short answer when the prompt nearly fills the window", async () => { const messages = getDefaultChatMessages(searchResultsOf(4090));
expect( getDefaultChatCompletionCreateParamsStreaming(messages).max_tokens, (await getDefaultChatCompletionCreateParamsStreaming(messages)) .max_tokens, ).toBe(minimumOutputTokens); });
it("sizes the budget from the configured context on the OpenAI-compatible backend", () => { it("sizes the budget from the configured context on the OpenAI-compatible backend", async () => { state.settings = { inferenceType: "openai", openAiContextLength: 32768 }; const messages = getDefaultChatMessages(searchResultsOf(8000));
const { max_tokens } = getDefaultChatCompletionCreateParamsStreaming(messages); await getDefaultChatCompletionCreateParamsStreaming(messages);
expect(max_tokens).toBeGreaterThan(20000); expect(countPromptTokens(messages) + max_tokens).toBeLessThanOrEqual(32768); });
it("sizes the budget from the default context on the internal API", () => { state.settings = { inferenceType: "internal", openAiContextLength: 32768 }; it("sizes the budget from the server's context length on the internal API", async () => { state.settings = { inferenceType: "internal", openAiContextLength: 4096 }; state.internalApiContextLength = 131072; const messages = getDefaultChatMessages(searchResultsOf(1000));
const { max_tokens } = getDefaultChatCompletionCreateParamsStreaming(messages); await getDefaultChatCompletionCreateParamsStreaming(messages);
expect(max_tokens).toBeGreaterThan(100000); expect(countPromptTokens(messages) + max_tokens).toBeLessThanOrEqual(4096); expect(countPromptTokens(messages) + max_tokens).toBeLessThanOrEqual( 131072, ); });});
1234537 unmodified lines4344454546474849505152538 unmodified lines626364616265666768697071151 unmodified lines22322422522022622722822952 unmodified lines2822832842792802852862872882897 unmodified lines297298299294300301302303304299305306307308import gptTokenizer from "gpt-tokenizer";import { getConfig } from "./config";import { addLogEntry } from "./logEntries";import { allocatePageExcerpts } from "./pageExcerptAllocation";import type {37 unmodified lines * out of the prompt (page excerpts, chat history) measures against this one * number, so the parts are sized for the same window and fit together. */export function getEffectiveContextSize() {export async function getEffectiveContextSize() { const { inferenceType, openAiContextLength } = getSettings(); if (inferenceType === "internal") { return (await getConfig()).internalApiContextLength; } // `openAiContextLength` describes one backend's endpoint. Every other one // runs at `defaultContextSize` (the browser models are built with it), and // the setting outlives a switch between them, so it only counts where it8 unmodified lines return defaultContextSize;}
function getPageContentTokenBudget() { return Math.floor(getEffectiveContextSize() * pageContentTokenBudgetRatio);async function getPageContentTokenBudget() { return Math.floor( (await getEffectiveContextSize()) * pageContentTokenBudgetRatio, );}
let workerFactory = () =>151 unmodified lines const pageContents = getPageContents(); const excerpts = await allocatePageExcerptsAsync( searchResults.map(([, , url]) => pageContents[url] ?? ""), getPageContentTokenBudget(), await getPageContentTokenBudget(), );
const relevanceTags = getRelevanceTags(searchResults);52 unmodified lines * uses the same tokenizer as the other prompt budgets; the model's own may * differ a little either way. */function getMaxOutputTokens(messages: ChatMessage[]) { const contextSize = getEffectiveContextSize();async function getMaxOutputTokens(messages: ChatMessage[]) { const contextSize = await getEffectiveContextSize(); const promptTokens = messages.reduce( (total, message) => total +7 unmodified lines );}
export function getDefaultChatCompletionCreateParamsStreaming(export async function getDefaultChatCompletionCreateParamsStreaming( messages: ChatMessage[],) { return { stream: true, max_tokens: getMaxOutputTokens(messages), max_tokens: await getMaxOutputTokens(messages), temperature: 0.35, top_p: 1.0, min_p: 0.0,102 unmodified lines103104105106106107108109102 unmodified lines "Content-Type": "application/json", }, body: JSON.stringify({ ...getDefaultChatCompletionCreateParamsStreaming(messages), ...(await getDefaultChatCompletionCreateParamsStreaming(messages)), messages, }), signal,64 unmodified lines656667686869707164 unmodified lines apiKey: settings.openAiApiKey, });
const params = getDefaultChatCompletionCreateParamsStreaming(messages); const params = await getDefaultChatCompletionCreateParamsStreaming(messages);
let effectiveModel = settings.openAiApiModel; let availableModels: { id: string }[] = [];42 unmodified lines43444546464748496 unmodified lines565758596061628 unmodified lines717273747576777842 unmodified lines| `MODEL_MAX_BACKOFF_MS` | `5000` | Maximum retry backoff in milliseconds || `MODEL_REQUEST_TIMEOUT_MS` | `30000` | Model request timeout in milliseconds || `MODEL_MAX_CONCURRENT_REQUESTS` | `10` | Maximum number of simultaneous model requests || `MODEL_DEFAULT_MAX_TOKENS` | `2048` | Default maximum number of generated tokens || `MODEL_DEFAULT_MAX_TOKENS` | `8192` | Default maximum number of generated tokens || `MODEL_TEMPERATURE` | `0.7` | Model sampling temperature || `MODEL_TOP_P` | `0.9` | Model nucleus-sampling probability |
6 unmodified lines| `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` | `''` | Base URL of your API (e.g., `https://api.internal.company.com/v1`) || `INTERNAL_OPENAI_COMPATIBLE_API_KEY` | `''` | API key for authentication || `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` | `''` | Model ID, or a comma-separated list (random model if empty) || `INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH` | `131072` | Context window of the API's models, in tokens || `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` | `''` | Sent as `reasoning_effort` on every request (API default if empty) || `INTERNAL_OPENAI_COMPATIBLE_API_NAME` | `Internal API` | Display name shown in UI |
8 unmodified lines
`INTERNAL_OPENAI_COMPATIBLE_API_MODEL` takes several models, separated by commas, in order of preference (`"llama-3.1-8b,qwen-3-8b"`). When a model fails before sending the first token, the server moves to the next one, and after the last one it starts the list over once, up to 5 attempts in all. So a single model gets one retry. Left empty, each request picks a random model from the API's `/models` list, which includes every model the API serves.
`INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH` is the window the browser sizes the request from: the page excerpts get 35% of it, and the answer's `max_tokens` is what is left after the prompt. The server then caps `max_tokens` at `MODEL_DEFAULT_MAX_TOKENS` (8192), which on most OpenAI-compatible APIs also has to hold the thinking of a reasoning model. Set it lower when the models have a smaller window, or the API rejects the longer prompts. A value that is not a positive integer is logged and replaced by the default.
`INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` sets the `reasoning_effort` field of every request to the API, for every model in the list. The value is passed through as written, because providers accept different values (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`); one the API rejects fails the request, and the error shows in the server log. Left empty, the field is not sent and the API applies its own default.
### Default Behavior.env.example+3
changelog.md+1
client/components/App/App.test.tsx+1
client/modules/config.test.ts+1
client/modules/config.ts+2
client/modules/pubSub.test.ts+5-2
client/modules/settings.test.ts+1
client/modules/textGeneration.responsePersistence.test.ts+10
client/modules/textGeneration.ts+1-1
client/modules/textGenerationUtilities.test.ts+36-17
client/modules/textGenerationUtilities.ts+14-8
client/modules/textGenerationWithInternalApi.ts+1-1
client/modules/textGenerationWithOpenAi.ts+1-1
docs/configuration.md+4-1