Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let a person turn an Ollama model's thinking off, or pick its level
milind-soni46ad8c4b8864
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdxindex c1b0cd60d2..296bffb049 100644--- a/apps/docs/content/docs/providers/model-providers.mdx+++ b/apps/docs/content/docs/providers/model-providers.mdx@@ -258,6 +258,9 @@ address you added before keeps its name, key and model.- A model that can't call tools still chats, but its turns run without tools.The picker marks it **No tools**. Pick a model with tool support, such as`llama3.2` or `qwen3`, for work that needs tools.+- A model that can think gets a thinking control in the picker: on or off, or+ the levels Ollama lists for it. Turning it off is usually much faster on a+ laptop.- When Ollama isn't running, can't be reached, or has no models yet, Settingssays so and how to fix it. To get a first model, run `ollama pull llama3.2`.diff --git a/server/drivers/ollama.test.ts b/server/drivers/ollama.test.tsindex d808efb23f..731c3a681b 100644--- a/server/drivers/ollama.test.ts+++ b/server/drivers/ollama.test.ts@@ -9,7 +9,7 @@ import { instanceLook } from "../provider-icon.ts";import { forgetServedModels } from "./ollama-context.ts";import {answeredAsOllama, findOllama, forgetOllamaAnswers, isOllamaServer, ollamaOrigin, ollamaTags, ollamaUnavailable,- probeOllama, showCapabilities,+ probeOllama, showCapabilities, thinkingEffort,} from "./ollama.ts";import { OpenAICompatDriver } from "./openai-compat.ts";@@ -25,13 +25,13 @@ afterEach(async () => {}});-interface FakeModel { name: string; size?: number; details?: Record<string, unknown>; capabilities?: string[] }+interface FakeModel { name: string; size?: number; details?: Record<string, unknown>; capabilities?: string[]; thinking?: unknown }/** A server speaking Ollama's own routes and its OpenAI-compatible chat, recording each chat request. */async function fakeOllama(options: { models?: FakeModel[]; version?: string | null; tags?: boolean } = {}) {// Read per request, so a test can change what the server answers.const models = options.models ?? [];- const chats: Array<{ model: string; tools?: unknown[] }> = [];+ const chats: Array<{ model: string; tools?: unknown[]; reasoning_effort?: string }> = [];const asked: string[] = [];const server = createServer(async (request, response) => {let data = "";@@ -46,13 +46,13 @@ async function fakeOllama(options: { models?: FakeModel[]; version?: string | nuif (path === "/api/version" && options.version !== null) return json({ version: options.version ?? "0.12.6" });if (path === "/api/show") {const model = models.find((entry) => entry.name === (JSON.parse(data) as { model: string }).model);- return model ? json({ capabilities: model.capabilities, model_info: { "llama.context_length": 131_072 } }) : json({ error: "not found" }, 404);+ return model ? json({ capabilities: model.capabilities, thinking: model.thinking, model_info: { "llama.context_length": 131_072 } }) : json({ error: "not found" }, 404);}if (path === "/api/ps") return json({ models: [] });if (path === "/api/create") return json({ status: "success" });if (path === "/v1/models") return json({ data: models.map((model) => ({ id: model.name })) });if (path === "/v1/chat/completions") {- chats.push(JSON.parse(data) as { model: string; tools?: unknown[] });+ chats.push(JSON.parse(data) as { model: string; tools?: unknown[]; reasoning_effort?: string });response.writeHead(200, { "content-type": "text/event-stream" });response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Hi." }, finish_reason: "stop" }] })}\n\n`);return response.end("data: [DONE]\n\n");@@ -110,6 +110,28 @@ describe("Ollama's model list", () => {expect(showCapabilities({ model_info: {} })).toEqual({});});+ it("reads a thinking model's controls, or only that it thinks from a server that doesn't list them", () => {+ expect(showCapabilities({ capabilities: ["completion", "thinking"], thinking: { values: ["low", "medium", "high"], default: "medium" } }).thinking).toEqual({ choices: ["low", "medium", "high"], described: true });+ expect(showCapabilities({ capabilities: ["completion", "thinking"], thinking: { values: [false, true], default: true } }).thinking).toEqual({ choices: ["off", "on"], described: true });+ expect(showCapabilities({ capabilities: ["completion", "thinking"] }).thinking).toEqual({ choices: ["off", "on"], described: false });+ expect(showCapabilities({ capabilities: ["completion", "thinking"], thinking: { values: [true], default: true } }).thinking).toBeUndefined();+ expect(showCapabilities({ capabilities: ["completion"], thinking: { values: [false, true] } }).thinking).toBeUndefined();+ });++ it("turns a thinking choice into what Ollama's /v1 takes", () => {+ const listed = { choices: ["off", "on"], described: true };+ const unlisted = { choices: ["off", "on"], described: false };+ const levels = { choices: ["low", "high"], described: true };+ expect(thinkingEffort(listed, "off")).toBe("none");+ expect(thinkingEffort(unlisted, "off")).toBe("none");+ expect(thinkingEffort(listed, "on")).toBe("high");+ expect(thinkingEffort(unlisted, "on")).toBeUndefined();+ expect(thinkingEffort(levels, "low")).toBe("low");+ expect(thinkingEffort(levels, "medium")).toBeUndefined();+ expect(thinkingEffort(levels, undefined)).toBeUndefined();+ expect(thinkingEffort(undefined, "low")).toBeUndefined();+ });+it("drops the /v1 the OpenAI-compatible routes sit under", () => {expect(ollamaOrigin("http://127.0.0.1:11434/v1/")).toBe("http://127.0.0.1:11434");expect(ollamaOrigin("http://gpu-box.local:11434")).toBe("http://gpu-box.local:11434");@@ -376,6 +398,27 @@ describe("the chat engine on Ollama", () => {} finally { await instance.dispose(); }});+ it("offers a thinking model's controls and sends the one picked, under the name that carries the window", async () => {+ const thinker: FakeModel = { name: "qwen3:4b", size: GB, capabilities: ["completion", "tools", "thinking"], thinking: { values: [false, true], default: true } };+ const { url, chats } = await fakeOllama({ models: [thinker, LLAMA] });+ const instance = await create({ url: `${url}/v1`, catalog: "ollama" });+ const recorder = recordEvents(instance.adapter);+ try {+ expect(instance.adapter.capabilities.modelVariants).toBe(true);+ expect(instance.models.options.map((option) => option.variants)).toEqual([[{ id: "off", label: "Off" }, { id: "on", label: "On" }], undefined]);+ for (const [model, variant] of [["qwen3:4b", "off"], ["qwen3:4b", undefined], ["qwen3:4b", "on"], ["llama3.2:latest", "off"]] as const) {+ const threadId = randomUUID();+ await instance.adapter.sendTurn({ threadId, text: "hi", model, ...(variant ? { variant } : {}) });+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);+ }+ expect(chats.map((chat) => chat.reasoning_effort)).toEqual(["none", undefined, "high", undefined]);+ expect(chats[0]!.model).toMatch(/-omb-\d+k$/);+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });+it("asks nothing of a server on this network that has a fixed model list", async () => {const { url } = await fakeOllama({ models: [LLAMA] });const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY", managedModels: ["llama3.2:latest"] }, { FIXTURE_KEY: "fixture-key" });diff --git a/server/drivers/ollama.ts b/server/drivers/ollama.tsindex ed729cedb0..a9be5a6645 100644--- a/server/drivers/ollama.ts+++ b/server/drivers/ollama.ts@@ -1,7 +1,7 @@// Ollama's own API (docs/api.md in github.com/ollama/ollama): /api/tags lists the pulled models with their size and// details, /api/version answers with a version, and /api/show names a model's capabilities ("tools", "vision") from// v0.6.4. A default install takes no key on these routes or on the OpenAI-compatible ones under /v1.-import type { LocalModel, OllamaState, OllamaStatus } from "../../shared/local-model.ts";+import type { LocalModel, LocalModelThinking as OllamaThinking, OllamaState, OllamaStatus } from "../../shared/local-model.ts";import { isContextName } from "./ollama-context.ts";export const OLLAMA_PORT = "11434";@@ -53,11 +53,29 @@ export function ollamaTags(payload: unknown): OllamaModel[] | null {return models;}+function thinkingControls(described: unknown): OllamaThinking {+ const values = described && typeof described === "object" ? (described as { values?: unknown }).values : undefined;+ const choices = Array.isArray(values)+ ? values.flatMap((value) => value === false ? ["off"] : value === true ? ["on"] : text(value) ? [text(value)!] : [])+ : [];+ return choices.length ? { choices, described: true } : { choices: ["off", "on"], described: false };+}+/** What /api/show says a model can do; empty when the server predates capabilities. */-export function showCapabilities(show: unknown): Pick<OllamaModel, "tools" | "vision"> {- const capabilities = show && typeof show === "object" ? (show as { capabilities?: unknown }).capabilities : undefined;+export function showCapabilities(show: unknown): Pick<OllamaModel, "tools" | "vision" | "thinking"> {+ const { capabilities, thinking } = (show && typeof show === "object" ? show : {}) as { capabilities?: unknown; thinking?: unknown };if (!Array.isArray(capabilities) || !capabilities.every((entry) => typeof entry === "string")) return {};- return { tools: capabilities.includes("tools"), vision: capabilities.includes("vision") };+ const controls = capabilities.includes("thinking") ? thinkingControls(thinking) : undefined;+ return { tools: capabilities.includes("tools"), vision: capabilities.includes("vision"), ...(controls && controls.choices.length > 1 ? { thinking: controls } : {}) };+}++/** The `reasoning_effort` a thinking choice sends on /v1, undefined to leave the model's default. Before /api/show+ * listed a model's controls Ollama refused a level on a model that only thinks or doesn't, so "on" stays unsent there. */+export function thinkingEffort(thinking: OllamaThinking | undefined, choice: string | undefined): string | undefined {+ if (!thinking || !choice || !thinking.choices.includes(choice)) return undefined;+ if (choice === "off") return "none";+ if (choice === "on") return thinking.described ? "high" : undefined;+ return choice;}/** False only for a model /api/show says cannot chat. */diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 03e7fd8bd8..b26493700a 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -93,7 +93,7 @@ interface RuntimeOptions<Config> {apiKey: string;apiUrl: string;models: () => ModelCatalog;- requestBody(model: string, messages: OpenAIChatMessage[], stream: boolean): Record<string, unknown>;+ requestBody(model: string, messages: OpenAIChatMessage[], stream: boolean, variant?: string): Record<string, unknown>;httpErrorLabel: string;missingKeyError: string;unavailableReason: string;@@ -116,8 +116,8 @@ interface RuntimeOptions<Config> {computerUse?: boolean;/** A text-only model keeps the computer and browser tools but never receives a screenshot or attachment. */imageInput?: (model: string) => boolean;- /** False for a model its server says cannot call tools: its turns go without them instead of being refused. */- toolUse?: (model: string) => boolean;+ /** Some models list `variants`; the picked one reaches `requestBody`. */ modelVariants?: boolean;+ /** False for a model its server says cannot call tools: its turns go without them instead of being refused. */ toolUse?: (model: string) => boolean;/** Why the server cannot answer now (not running, nothing to run), asked before the key is. */serverUnavailable?: () => Promise<Pick<ProviderSnapshot, "reason" | "ollama"> | null>;/** The name to send for a model, when its server knows it by another. */@@ -260,7 +260,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)signal?: AbortSignal,onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,tools: ChatToolDefinition[] = [],- onUsage?: TextGenerationOptions["onUsage"],+ onUsage?: TextGenerationOptions["onUsage"], variant?: string,): Promise<Completion> => {const timeoutController = new AbortController();let idleTimer: NodeJS.Timeout | null = null;@@ -283,7 +283,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const payload = JSON.stringify(route === "responses"? responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model) }): {- ...options.requestBody(served, messages, stream),+ ...options.requestBody(served, messages, stream, variant),...(route === "chat-reasoning-off" ? { reasoning_effort: "none" } : {}),...(tools.length ? { tools } : {}),});@@ -462,7 +462,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)signal?: AbortSignal,onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,tools: ChatToolDefinition[] = [],- onUsage?: TextGenerationOptions["onUsage"],+ onUsage?: TextGenerationOptions["onUsage"], variant?: string,): Promise<Completion> => {for (;;) {let replied = false;@@ -470,7 +470,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)return await completeOn(routes.routeFor(model, tools.length > 0), messages, model, stream, signal, onDelta && ((text, kind) => {replied = true;onDelta(text, kind);- }), tools, onUsage);+ }), tools, onUsage, variant);} catch (error) {if (!(error instanceof ModelRouteRefused) || replied || signal?.aborted) throw error;if (!routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));@@ -651,7 +651,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (streamKind === "assistant_text") answerStreamed = true;const shown = holdback && streamKind === "assistant_text" ? holdback.feed(text) : text;if (shown) delta(shown, streamKind);- }, tools.definitions);+ }, tools.definitions, undefined, turn.variant);// A reply cut off at the token limit may be a call cut short; running half of one is worse than saying so.const written = holdback && !completion.toolCalls.length && completion.finishReason !== "length" ? textToolCalls(completion.text, tools.definitions) : null;unreadable = written?.kind === "unreadable" && !askedAgain;@@ -949,7 +949,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)capabilities: { ...(options.computerUse ? { computerMcp: options.tools !== false,localComputerMcp: options.tools !== false,browserMcp: options.tools !== false, nativeImageInput: true, images: true } : {}),- sessionModelSwitch: "in-session", customMcp: options.tools !== false, agentsMcp: options.tools !== false, composioMcp: options.tools !== false,+ ...(options.modelVariants ? { modelVariants: true } : {}), sessionModelSwitch: "in-session", customMcp: options.tools !== false, agentsMcp: options.tools !== false, composioMcp: options.tools !== false,dataMcp: options.tools !== false,emailMcp: options.tools !== false,deviceMcp: options.tools !== false,diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex e815f2465a..e8e5168f76 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -1,10 +1,10 @@// Transcript-replay driver for OpenRouter, Groq, Together, llama.cpp, and// other endpoints that speak the OpenAI chat-completions contract.-import type { ModelCatalog, ProviderDriver } from "../contracts.ts";+import { titleCaseModelId, type ModelCatalog, type ProviderDriver } from "../contracts.ts";import { isLoopback } from "../provider-key-check.ts";import { lmStudioV1Catalog } from "./local-inject.ts";-import { isContextName, isOllama, serveWithWindow } from "./ollama-context.ts";-import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, type OllamaModel, type OllamaStatus } from "./ollama.ts";+import { isContextName, isOllama, pickedName, serveWithWindow } from "./ollama-context.ts";+import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, thinkingEffort, type OllamaModel, type OllamaStatus } from "./ollama.ts";import { createOpenAIChatRuntime } from "./openai-chat.ts";import {freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,@@ -42,6 +42,8 @@ const NO_MODELS: ModelCatalog = { default: "", options: [] };const OLLAMA_STATUS_MS = 5_000;const OLLAMA_FIRST_LIST_MS = 2_000;+const withEffort = (effort: string | undefined) => effort ? { reasoning_effort: effort } : {};+const localFacts = ({ bytes, parameters, quantization, tools, vision }: OllamaModel) => ({...(bytes ? { bytes } : {}), ...(parameters ? { parameters } : {}), ...(quantization ? { quantization } : {}),...(tools !== undefined ? { tools } : {}), ...(vision !== undefined ? { vision } : {}),@@ -230,7 +232,10 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {facts.clear();for (const model of status.models) facts.set(model.name, model);if (config.managedModels) return true;- const options: ModelCatalog["options"] = status.models.map((model) => ({ id: model.name, label: model.name, custom: true, local: localFacts(model) }));+ const options: ModelCatalog["options"] = status.models.map((model) => ({+ id: model.name, label: model.name, custom: true, local: localFacts(model),+ ...(model.thinking ? { variants: model.thinking.choices.map((id) => ({ id, label: titleCaseModelId(id, /[-_ ]+/) })) } : {}),+ }));if (config.model && !options.some((model) => model.id === config.model)) options.unshift({ id: config.model, label: config.model, custom: true });catalog = { default: config.model ?? options[0]?.id ?? "", options };return true;@@ -366,11 +371,13 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {return reason ? { reason, ollama: { state: status.state, url: status.url, ...(status.problem ? { problem: status.problem } : {}) } } : null;},} : {}),- requestBody: (model, messages, stream) => ({+ modelVariants: ollamaCandidate,+ requestBody: (model, messages, stream, variant) => ({model,messages,stream,stream_options: stream ? { include_usage: true } : undefined,+ ...withEffort(thinkingEffort(fact(pickedName(model))?.thinking, variant)),...(config.provider && isOpenRouterUrl(config.url)? { provider: { order: [config.provider], allow_fallbacks: false } }: {}),diff --git a/shared/local-model.ts b/shared/local-model.tsindex 94cae23c28..35d5d781f4 100644--- a/shared/local-model.ts+++ b/shared/local-model.ts@@ -8,8 +8,15 @@ export interface LocalModelFacts {vision?: boolean;}+/** A model's thinking controls: `described` when its server listed them, not only that the model thinks. */+export interface LocalModelThinking {+ choices: string[];+ described: boolean;+}+export interface LocalModel extends LocalModelFacts {name: string;+ thinking?: LocalModelThinking;}/** `ready`: running with models. `no-models`: running, nothing pulled. `not-running`: nothing listens there.diff --git a/src/components/model-picker-reasoning.test.ts b/src/components/model-picker-reasoning.test.tsnew file mode 100644index 0000000000..383527a4e5--- /dev/null+++ b/src/components/model-picker-reasoning.test.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";++vi.hoisted(() => {+ vi.stubGlobal("window", {});+ vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => {} });+});++const { variantLabel } = await import("./model-picker-reasoning");++afterEach(() => setLocale("en"));++describe("a thinking choice's words", () => {+ it("are the app's own on the chat engine, in the reader's language", () => {+ expect(variantLabel({ id: "on", label: "On" }, "openai-compat")).toBe("On");+ setLocale("pt-br");+ expect(variantLabel({ id: "on", label: "On" }, "openai-compat")).toBe("Ligado");+ expect(variantLabel({ id: "off", label: "Off" }, "openai-compat")).toBe("Desligado");+ expect(variantLabel({ id: "low", label: "Low" }, "openai-compat")).toBe("Baixo");+ });++ it("stay what the model calls them when it names its own, and on other engines", () => {+ setLocale("pt-br");+ expect(variantLabel({ id: "deep-dive", label: "Deep Dive" }, "openai-compat")).toBe("Deep Dive");+ expect(variantLabel({ id: "low", label: "Low" }, "copilotAgent")).toBe("Low");+ });+});diff --git a/src/components/model-picker-reasoning.ts b/src/components/model-picker-reasoning.tsindex bae30eacf7..1fbd4b5743 100644--- a/src/components/model-picker-reasoning.ts+++ b/src/components/model-picker-reasoning.ts@@ -2,9 +2,18 @@ import { useEffect, useRef, type RefObject } from "react";import type { AppState, Bot, InstanceInfo, ModelSelection } from "@/state/store";import type { ModelVariantOption } from "../../shared/runtime-events";import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";-export const variantLabel = (option: ModelVariantOption, driverKind?: string): string =>- option.id === "default" && driverKind === "opencodeGo" ? t("model.variant.openCodeDefault") : option.label;+/** The chat engine's variants are thinking levels with these ids; other engines name their own. */+const CHAT_ENGINE_VARIANTS: Readonly<Record<string, LocaleKey>> = {+ off: "model.effort.off", on: "model.variant.on", none: "model.effort.none", low: "model.effort.low",+ medium: "model.effort.medium", high: "model.effort.high", xhigh: "model.effort.xhigh", max: "model.effort.max",+};++export const variantLabel = (option: ModelVariantOption, driverKind?: string): string => {+ if (option.id === "default" && driverKind === "opencodeGo") return t("model.variant.openCodeDefault");+ return driverKind === "openai-compat" && Object.hasOwn(CHAT_ENGINE_VARIANTS, option.id) ? t(CHAT_ENGINE_VARIANTS[option.id]!) : option.label;+};/** ACP variant ids are opaque; their model/session declares the available choices. */export function variantChoices(state: Pick<AppState, "instances" | "modelVariantSessions">, selection: ModelSelection, threadId: string | undefined) {diff --git a/src/locales/en.json b/src/locales/en.jsonindex 111205c364..58f2ad2298 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3284,6 +3284,7 @@"model.variant.unavailableChoice": "Saved variant “{variant}” is unavailable. Choose an available variant.","model.variant.unverifiedChoice": "Saved variant “{variant}” has not been checked in this session.","model.variant.none": "No variant selected.",+ "model.variant.on": "On","model.variant.sessionValue": "Session: {variant}.","model.variant.clearHint": "Send no thinking selection; the agent keeps its session or configured setting","model.variant.clear": "Clear variant selection",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 42c992f7f6..83d887dc69 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3150,6 +3150,7 @@"model.variant.unavailableChoice": "A variante salva “{variant}” está indisponível. Escolha uma variante disponível.","model.variant.unverifiedChoice": "A variante salva “{variant}” ainda não foi verificada nesta sessão.","model.variant.none": "Nenhuma variante selecionada.",+ "model.variant.on": "Ligado","model.variant.sessionValue": "Sessão: {variant}.","model.variant.clearHint": "Não enviar uma variante de raciocínio; o agente mantém o ajuste da sessão ou o que já estiver configurado","model.variant.clear": "Limpar seleção de variante",