Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm_chat): search the web through a configured search provider

Elian Doran26d8f5995453
diff --git a/apps/client/src/services/llm_providers.spec.ts b/apps/client/src/services/llm_providers.spec.ts
index 61b3c673f3..46babd29cc 100644
--- a/apps/client/src/services/llm_providers.spec.ts
+++ b/apps/client/src/services/llm_providers.spec.ts
@@ -5,7 +5,7 @@ const mocks = vi.hoisted(() => ({ stored: [] as unknown[] }));
vi.mock("./options.js", () => ({ default: { getJson: () => mocks.stored } }));
-import { readSelectedModels, readsAttachmentKind, unreadableAttachments } from "./llm_providers.js";
+import { readSelectedModels, readsAttachmentKind, resolveWebSearch, unreadableAttachments } from "./llm_providers.js";
const textOnly: LlmModelInfo = { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro", attachmentKinds: [] };
const imagesOnly: LlmModelInfo = { id: "codex", name: "Codex", attachmentKinds: [ "image" ] };
@@ -49,3 +49,30 @@ describe("readSelectedModels", () => {
expect(readSelectedModels().hasProvider).toBe(false);
});
});
+
+describe("resolveWebSearch", () => {
+ const TAVILY = { id: "s1", name: "Tavily", provider: "tavily" };
+ const resolve = (modelProvider: string | undefined, overrides: Partial<Parameters<typeof resolveWebSearch>[0]> = {}) =>
+ resolveWebSearch({ modelProvider, enableWebSearch: true, enableNoteTools: false, searchProviderId: "", searchProviders: [ TAVILY ], ...overrides });
+
+ it("uses the model's built-in search by default, where the model has one", () => {
+ expect(resolve("anthropic")).toEqual({ choice: "builtin", enableWebSearch: true, webSearchProviderId: undefined });
+ expect(resolve("deepseek")).toMatchObject({ choice: "builtin", enableWebSearch: false, builtInUnavailableKey: "llm_chat.web_search_builtin_unsupported" });
+ // Gemini can't combine its own search with note tools.
+ expect(resolve("google", { enableNoteTools: true })).toMatchObject({ enableWebSearch: false, builtInUnavailableKey: "llm_chat.web_search_unavailable_gemini" });
+ });
+
+ it("searches through the chosen search provider, falling back to built-in once it is gone", () => {
+ expect(resolve("deepseek", { searchProviderId: "s1" })).toEqual({ choice: "s1", enableWebSearch: true, webSearchProviderId: "s1", builtInUnavailableKey: "llm_chat.web_search_builtin_unsupported" });
+ expect(resolve("google", { searchProviderId: "s1", enableNoteTools: true })).toMatchObject({ enableWebSearch: true, webSearchProviderId: "s1" });
+ expect(resolve("anthropic", { searchProviderId: "deleted" })).toMatchObject({ choice: "builtin", enableWebSearch: true, webSearchProviderId: undefined });
+ });
+
+ it("sends no search provider to a model that runs its own agent loop, nor anything when disabled", () => {
+ expect(resolve("claude-agent", { searchProviderId: "s1" })).toMatchObject({
+ choice: "s1", enableWebSearch: false, webSearchProviderId: undefined, searchProviderUnavailableKey: "llm_chat.web_search_provider_unsupported"
+ });
+ expect(resolve("claude-agent")).toMatchObject({ choice: "builtin", enableWebSearch: true });
+ expect(resolve("anthropic", { enableWebSearch: false, searchProviderId: "s1" })).toMatchObject({ choice: "disabled", enableWebSearch: false, webSearchProviderId: undefined });
+ });
+});
diff --git a/apps/client/src/services/llm_providers.ts b/apps/client/src/services/llm_providers.ts
index 01857c247e..e595e43ef4 100644
--- a/apps/client/src/services/llm_providers.ts
+++ b/apps/client/src/services/llm_providers.ts
@@ -50,6 +50,73 @@ export function readSelectedModels(): { models: ModelOption[]; groups: ModelProv
return { models, groups, hasProvider: configs.length > 0 };
}
+/** A configured search provider, as the chat's Tools menu lists it. */
+export interface SearchProviderOption {
+ id: string;
+ name: string;
+ provider: string;
+}
+
+/** The search providers configured in the `llmProviders` option, in config order. */
+export function readSearchProviders(): SearchProviderOption[] {
+ return ((options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [])
+ .filter(config => isProviderOfKind(config, "search"))
+ .map(({ id, name, provider }) => ({ id, name, provider }));
+}
+
+/** Provider types whose models search the web themselves when `enableWebSearch` is set. */
+const BUILT_IN_WEB_SEARCH = new Set([ "anthropic", "openai", "google", "claude-agent", "antigravity-agent", "codex-agent" ]);
+
+/** Provider types that run their own agent loop, which takes no tool from Trilium's chat. */
+const OWN_AGENT_LOOP = new Set([ "claude-agent", "copilot-agent", "antigravity-agent", "codex-agent" ]);
+
+/** The web search of a chat turn, as the Tools menu shows it and as the turn is sent. */
+export interface WebSearchState {
+ /** The marked choice: `"disabled"`, `"builtin"`, or the config id of a search provider. */
+ choice: string;
+ /** The i18n key saying why the model's built-in search can't be used, if it can't. */
+ builtInUnavailableKey?: string;
+ /** The i18n key saying why a search provider can't be used with this model, if it can't. */
+ searchProviderUnavailableKey?: string;
+ /** Whether the turn searches the web. False when the marked choice can't be used. */
+ enableWebSearch: boolean;
+ /** The search provider the turn searches through, in place of the built-in search. */
+ webSearchProviderId?: string;
+}
+
+/**
+ * Resolve the chat's web search for a model of `modelProvider`. `searchProviderId` is the
+ * `llmWebSearchProvider` option; one that names no configured search provider means built-in.
+ */
+export function resolveWebSearch({ modelProvider, enableWebSearch, enableNoteTools, searchProviderId, searchProviders }: {
+ modelProvider: string | undefined;
+ enableWebSearch: boolean;
+ enableNoteTools: boolean;
+ searchProviderId: string;
+ searchProviders: SearchProviderOption[];
+}): WebSearchState {
+ let builtInUnavailableKey: string | undefined;
+ if (modelProvider && !BUILT_IN_WEB_SEARCH.has(modelProvider)) {
+ builtInUnavailableKey = "llm_chat.web_search_builtin_unsupported";
+ } else if (modelProvider === "google" && enableNoteTools) {
+ builtInUnavailableKey = "llm_chat.web_search_unavailable_gemini";
+ }
+ const searchProviderUnavailableKey = modelProvider && OWN_AGENT_LOOP.has(modelProvider)
+ ? "llm_chat.web_search_provider_unsupported"
+ : undefined;
+
+ const isSearchProvider = searchProviders.some(p => p.id === searchProviderId);
+ const choice = !enableWebSearch ? "disabled" : isSearchProvider ? searchProviderId : "builtin";
+ const usable = choice === "builtin" ? !builtInUnavailableKey : choice !== "disabled" && !searchProviderUnavailableKey;
+ return {
+ choice,
+ builtInUnavailableKey,
+ searchProviderUnavailableKey,
+ enableWebSearch: usable,
+ webSearchProviderId: usable && isSearchProvider ? searchProviderId : undefined
+ };
+}
+
/**
* Resolve the active model from the available list. Several providers can expose
* the same model ID (e.g. an Anthropic API key and a Claude subscription, or two
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 66cd7ea102..823c1309ec 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2612,7 +2612,7 @@
"empty_state": "Start a conversation by typing a message below.",
"searching_web": "Searching the web...",
"web_search": "Web search",
- "web_search_unavailable_gemini": "Not available on Gemini models while note access is on — Google's API does not allow combining both. Disable note access or switch to a different provider to use web search.",
+ "web_search_unavailable_gemini": "Gemini can't combine its built-in search with note access. Turn off note access, or choose a search provider instead.",
"note_tools": "Note access",
"sources": "Sources",
"sources_summary": "{{count}} sources from {{sites}} sites",
@@ -2723,7 +2723,11 @@
"remove_unreadable_attachments": "Remove the attachments {{- model}} can't read",
"tools": "Tools",
"note_tools_description": "Search, read and edit your notes",
- "web_search_description": "Search the internet for current information"
+ "web_search_disabled": "Disabled",
+ "web_search_builtin": "Use the model's built-in search",
+ "manage_search_providers": "Manage search providers…",
+ "web_search_builtin_unsupported": "This model has no built-in web search. Choose a search provider instead.",
+ "web_search_provider_unsupported": "This model's provider searches the web with its own tools."
},
"sidebar_chat": {
"title": "AI Chat",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index c9bcd58bfb..a6c491795d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -3,7 +3,7 @@ import "./ChatInputBar.css";
import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionHostedFeed } from "@triliumnext/ckeditor5";
import type { DISPLAYABLE_LOCALE_IDS, LlmReasoningEffort } from "@triliumnext/commons";
import { Fragment } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
import link from "../../../services/link.js";
@@ -27,7 +27,7 @@ import ChatToolsDropdown from "./ChatToolsDropdown.js";
import ReasoningEffortDropdown from "./ReasoningEffortDropdown.js";
import { SafeImage } from "./retry_image.js";
import { getAttachmentLightbox, getUnreadableReasons, useChatAttachments } from "./useChatAttachments.js";
-import { type ModelOption, resolveSelectedModel, unreadableAttachments } from "../../../services/llm_providers.js";
+import { type ModelOption, readSearchProviders, resolveSelectedModel, resolveWebSearch, unreadableAttachments } from "../../../services/llm_providers.js";
import { type AttachmentBlock, type UseLlmChatReturn } from "./useLlmChat.js";
const READ_ONLY_LOCK = "llm-chat-streaming";
@@ -91,6 +91,10 @@ export default function ChatInputBar({
const editorApiRef = useRef<CKEditorApi | undefined>(undefined);
const editorInstanceRef = useRef<CKTextEditor | undefined>(undefined);
const [ uiLanguage ] = useTriliumOption("locale");
+ const [ llmProviders ] = useTriliumOption("llmProviders");
+ const [ webSearchProviderId, setWebSearchProviderId ] = useTriliumOption("llmWebSearchProvider");
+ // Read through `options`; `llmProviders` is the dependency so the list follows the settings.
+ const searchProviders = useMemo(readSearchProviders, [ llmProviders ]);
// CKEditor is the heaviest module the client has, and importing it statically here put it
// on the startup critical path: the right panel mounts SidebarChat, which pulls this bar,
// which pulled the editor — and its math plugin, and mathlive — before the app finished
@@ -163,8 +167,12 @@ export default function ChatInputBar({
}
}, [chat.isStreaming]);
- const handleWebSearchToggle = (newValue: boolean) => {
- chat.setEnableWebSearch(newValue);
+ /** Turns web search off for this chat, or on with the chosen source, which every chat shares. */
+ const handleWebSearchChoose = (choice: string) => {
+ chat.setEnableWebSearch(choice !== "disabled");
+ if (choice !== "disabled") {
+ void setWebSearchProviderId(choice === "builtin" ? "" : choice);
+ }
onWebSearchChange?.();
};
@@ -229,11 +237,14 @@ export default function ChatInputBar({
const currentModel = resolveSelectedModel(chat.availableModels, chat.selectedModel, chat.selectedProvider, chat.selectedProviderId);
const isSelectedModel = (m: ModelOption) => m === currentModel;
const unreadableReasons = getUnreadableReasons(currentModel, chat.pendingAttachments);
- // Gemini 2.x cannot combine googleSearch with function tools in a single
- // request. When note tools are enabled on a Gemini model we silently drop
- // web search server-side; reflect that here by disabling the toggle so the
- // user understands the trade-off instead of seeing it mysteriously ignored.
- const webSearchUnavailable = currentModel?.provider === "google" && chat.enableNoteTools;
+ // Resolved as `useLlmChat` resolves it for sending, so the menu marks what the turn will use.
+ const webSearch = resolveWebSearch({
+ modelProvider: currentModel?.provider,
+ enableWebSearch: chat.enableWebSearch,
+ enableNoteTools: chat.enableNoteTools,
+ searchProviderId: webSearchProviderId,
+ searchProviders
+ });
// Null until the window is close enough to matter, and null (rather than a guess) when
// the model advertises no window at all. See chat_context_usage.
const contextUsage = computeContextUsage({
@@ -466,10 +477,10 @@ export default function ChatInputBar({
<div className="llm-chat-capabilities">
<ChatToolsDropdown
enableNoteTools={chat.enableNoteTools}
- enableWebSearch={chat.enableWebSearch}
onNoteToolsChange={handleNoteToolsToggle}
- onWebSearchChange={handleWebSearchToggle}
- webSearchUnavailableReason={webSearchUnavailable ? t("llm_chat.web_search_unavailable_gemini") : undefined}
+ webSearch={webSearch}
+ searchProviders={searchProviders}
+ onWebSearchChoose={handleWebSearchChoose}
disabled={chat.isStreaming}
/>
{!currentModel?.reasoningEfforts?.length && (
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.css
index 12df72dba4..efb94b4722 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.css
@@ -11,4 +11,11 @@
max-width: 18rem;
white-space: normal;
}
+
+ .llm-chat-tools-provider-icon {
+ --masked-icon-size: 1em;
+
+ margin-inline-end: 0.4em;
+ opacity: 0.8;
+ }
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx
index 600a6db120..63e091b195 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx
@@ -2,7 +2,10 @@ import { type ComponentChildren, render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ triggerCommand: vi.fn() }));
+
vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key }));
+vi.mock("../../../components/app_context.js", () => ({ default: { triggerCommand: mocks.triggerCommand } }));
// Renders the toggle's face, class and tooltip, and the menu, without the popup machinery.
vi.mock("../../react/Dropdown.js", () => ({
@@ -16,6 +19,7 @@ vi.mock("../../react/Dropdown.js", () => ({
)
}));
+import type { WebSearchState } from "../../../services/llm_providers.js";
import ChatToolsDropdown from "./ChatToolsDropdown.js";
let host: HTMLElement | undefined;
@@ -26,23 +30,34 @@ afterEach(() => {
host.remove();
host = undefined;
}
+ vi.clearAllMocks();
});
-function renderMenu(props: Partial<Parameters<typeof ChatToolsDropdown>[0]> = {}) {
+const TAVILY = { id: "s1", name: "Tavily", provider: "tavily" };
+
+function renderMenu({ enableNoteTools = false, webSearch = { choice: "disabled", enableWebSearch: false } }: {
+ enableNoteTools?: boolean;
+ webSearch?: WebSearchState;
+} = {}) {
const onNoteToolsChange = vi.fn();
- const onWebSearchChange = vi.fn();
+ const onWebSearchChoose = vi.fn();
host = document.body.appendChild(document.createElement("div"));
const target = host;
act(() => render(
<ChatToolsDropdown
- enableNoteTools={false}
- enableWebSearch={false}
+ enableNoteTools={enableNoteTools}
onNoteToolsChange={onNoteToolsChange}
- onWebSearchChange={onWebSearchChange}
- {...props}
+ webSearch={webSearch}
+ searchProviders={[ TAVILY ]}
+ onWebSearchChoose={onWebSearchChoose}
/>, target));
const rows = [ ...target.querySelectorAll<HTMLElement>(".menu .dropdown-item") ];
+ const row = (text: string) => {
+ const found = rows.find((candidate) => candidate.textContent?.includes(text));
+ expect(found).toBeDefined();
+ return found;
+ };
const toggle = target.querySelector<HTMLButtonElement>(".dropdown-stub > button");
return {
toggle,
@@ -51,51 +66,59 @@ function renderMenu(props: Partial<Parameters<typeof ChatToolsDropdown>[0]> = {}
expect(icon).not.toBeNull();
return icon?.classList.contains("llm-chat-tools-on");
},
- noteRow: rows.find((row) => row.textContent?.includes("llm_chat.note_tools")),
- webRow: rows.find((row) => row.textContent?.includes("llm_chat.web_search")),
+ row,
+ /** The web search choices, by their text, that the menu marks as chosen. */
+ marked: () => rows.filter((candidate) => candidate.getAttribute("aria-checked") === "true" || candidate.querySelector(".bx-check"))
+ .map((candidate) => candidate.textContent),
onNoteToolsChange,
- onWebSearchChange
+ onWebSearchChoose
};
}
const isOn = (row: HTMLElement | undefined) => row?.querySelector<HTMLInputElement>("input[type='checkbox']")?.checked;
describe("ChatToolsDropdown", () => {
- it("shows a switch per tool group, and marks the toggle while any is on", () => {
+ it("marks the toggle while note access or a usable web search is on", () => {
const off = renderMenu();
expect(off.toggle?.title).toBe("llm_chat.tools");
// The compact combo box of the model picker, which draws the dropdown caret.
expect(off.toggle?.classList.contains("llm-chat-model-select")).toBe(true);
expect(off.isToggleOn()).toBe(false);
- expect(isOn(off.noteRow)).toBe(false);
- expect(isOn(off.webRow)).toBe(false);
+ expect(isOn(off.row("llm_chat.note_tools"))).toBe(false);
- const on = renderMenu({ enableWebSearch: true });
- expect(on.isToggleOn()).toBe(true);
- expect(isOn(on.noteRow)).toBe(false);
- expect(isOn(on.webRow)).toBe(true);
+ expect(renderMenu({ enableNoteTools: true }).isToggleOn()).toBe(true);
+ expect(renderMenu({ webSearch: { choice: "s1", enableWebSearch: true, webSearchProviderId: "s1" } }).isToggleOn()).toBe(true);
+ // Chosen, but the model can't use it.
+ expect(renderMenu({ webSearch: { choice: "builtin", enableWebSearch: false, builtInUnavailableKey: "no_builtin" } }).isToggleOn()).toBe(false);
});
- it("flips the group whose row is pressed", async () => {
- const { noteRow, webRow, onNoteToolsChange, onWebSearchChange } = renderMenu({ enableNoteTools: true });
- expect(noteRow).toBeDefined();
- expect(webRow).toBeDefined();
+ it("marks the chosen web search source, and reports a pressed one or the note access switch", async () => {
+ const menu = renderMenu({ enableNoteTools: true, webSearch: { choice: "s1", enableWebSearch: true, webSearchProviderId: "s1" } });
+ expect(menu.marked()).toEqual([ "Tavily" ]);
+
+ await act(async () => menu.row("llm_chat.web_search_builtin")?.click());
+ expect(menu.onWebSearchChoose).toHaveBeenLastCalledWith("builtin");
+ await act(async () => menu.row("llm_chat.web_search_disabled")?.click());
+ expect(menu.onWebSearchChoose).toHaveBeenLastCalledWith("disabled");
+ await act(async () => menu.row("llm_chat.note_tools")?.click());
+ expect(menu.onNoteToolsChange).toHaveBeenCalledExactlyOnceWith(false);
- await act(async () => noteRow?.click());
- expect(onNoteToolsChange).toHaveBeenCalledExactlyOnceWith(false);
- await act(async () => webRow?.click());
- expect(onWebSearchChange).toHaveBeenCalledExactlyOnceWith(true);
+ await act(async () => menu.row("llm_chat.manage_search_providers")?.click());
+ expect(mocks.triggerCommand).toHaveBeenCalledExactlyOnceWith("showOptions", { section: "_optionsLlm" });
});
- it("shows web search off and disabled, with the reason, when the model cannot combine it", async () => {
- const { isToggleOn, webRow, onWebSearchChange } = renderMenu({ enableWebSearch: true, webSearchUnavailableReason: "Not on Gemini" });
+ it("keeps a choice the model can't use listed, disabled, with the reason under it", async () => {
+ const menu = renderMenu({ webSearch: {
+ choice: "builtin", enableWebSearch: false,
+ builtInUnavailableKey: "no_builtin", searchProviderUnavailableKey: "own_tools"
+ } });
- expect(isToggleOn()).toBe(false);
- expect(isOn(webRow)).toBe(false);
- expect(webRow?.classList.contains("disabled")).toBe(true);
- expect(webRow?.querySelector(".description")?.textContent).toBe("Not on Gemini");
+ const builtIn = menu.row("llm_chat.web_search_builtin");
+ expect(builtIn?.classList.contains("disabled")).toBe(true);
+ expect(builtIn?.querySelector(".description")?.textContent).toBe("no_builtin");
+ expect(menu.row("Tavily")?.querySelector(".description")?.textContent).toBe("own_tools");
- await act(async () => webRow?.click());
- expect(onWebSearchChange).not.toHaveBeenCalled();
+ await act(async () => menu.row("Tavily")?.click());
+ expect(menu.onWebSearchChoose).not.toHaveBeenCalled();
});
});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx
index 019550ea6d..51a2b65be4 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx
@@ -1,28 +1,33 @@
import "./ChatToolsDropdown.css";
import clsx from "clsx";
+import type { ComponentChildren } from "preact";
+import appContext from "../../../components/app_context.js";
import { t } from "../../../services/i18n.js";
+import type { SearchProviderOption, WebSearchState } from "../../../services/llm_providers.js";
import Dropdown from "../../react/Dropdown.js";
-import { FormListToggleableItem } from "../../react/FormList.js";
+import { FormDropdownDivider, FormListHeader, FormListItem, FormListToggleableItem } from "../../react/FormList.js";
import Icon from "../../react/Icon.js";
+import MaskedIcon from "../../react/MaskedIcon.js";
+import { SEARCH_PROVIDER_ICON } from "../options/llm/provider_icons.js";
/**
- * The Tools menu of the chat input bar: one switch per group of tools the model can reach this
- * turn. Each row stops its click, so the menu stays open while several are flipped. Its toggle
+ * The Tools menu of the chat input bar: what the model can reach this turn, one section per group
+ * of tools. Its rows leave the menu open, so several can be changed in one visit. Its toggle
* shares the compact combo box styling of the model picker beside it.
*/
-export default function ChatToolsDropdown({ enableNoteTools, enableWebSearch, onNoteToolsChange, onWebSearchChange, webSearchUnavailableReason, disabled }: {
+export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange, webSearch, searchProviders, onWebSearchChoose, disabled }: {
enableNoteTools: boolean;
- enableWebSearch: boolean;
onNoteToolsChange: (newValue: boolean) => void;
- onWebSearchChange: (newValue: boolean) => void;
- /** Why web search can't be used with the current model and settings, if it can't. */
- webSearchUnavailableReason?: string;
+ webSearch: WebSearchState;
+ searchProviders: SearchProviderOption[];
+ /** Called with `"disabled"`, `"builtin"` or the config id of a search provider. */
+ onWebSearchChoose: (choice: string) => void;
disabled?: boolean;
}) {
- const webSearchActive = enableWebSearch && !webSearchUnavailableReason;
- const anyActive = enableNoteTools || webSearchActive;
+ const anyActive = enableNoteTools || webSearch.enableWebSearch;
+ const searchProviderUnavailable = webSearch.searchProviderUnavailableKey && t(webSearch.searchProviderUnavailableKey);
return (
<Dropdown
@@ -41,14 +46,63 @@ export default function ChatToolsDropdown({ enableNoteTools, enableWebSearch, on
currentValue={enableNoteTools}
onChange={onNoteToolsChange}
/>
- <FormListToggleableItem
- icon="bx bx-globe"
- title={t("llm_chat.web_search")}
- description={webSearchUnavailableReason ?? t("llm_chat.web_search_description")}
- currentValue={webSearchActive}
- onChange={onWebSearchChange}
- disabled={!!webSearchUnavailableReason}
- />
+
+ <FormDropdownDivider />
+ <FormListHeader text={t("llm_chat.web_search")} />
+ <WebSearchChoice choice="disabled" webSearch={webSearch} onChoose={onWebSearchChoose}>
+ {t("llm_chat.web_search_disabled")}
+ </WebSearchChoice>
+ <WebSearchChoice
+ choice="builtin"
+ webSearch={webSearch}
+ onChoose={onWebSearchChoose}
+ unavailableReason={webSearch.builtInUnavailableKey && t(webSearch.builtInUnavailableKey)}
+ >
+ {t("llm_chat.web_search_builtin")}
+ </WebSearchChoice>
+ {searchProviders.map(provider => (
+ <WebSearchChoice
+ key={provider.id}
+ choice={provider.id}
+ webSearch={webSearch}
+ onChoose={onWebSearchChoose}
+ unavailableReason={searchProviderUnavailable}
+ >
+ <MaskedIcon url={SEARCH_PROVIDER_ICON} className="llm-chat-tools-provider-icon" />
+ {provider.name}
+ </WebSearchChoice>
+ ))}
+ <FormListItem
+ icon="bx bx-cog"
+ onClick={() => appContext.triggerCommand("showOptions", { section: "_optionsLlm" })}
+ >
+ {t("llm_chat.manage_search_providers")}
+ </FormListItem>
</Dropdown>
);
}
+
+/**
+ * One choice of the web search section. A choice the current model can't use stays listed,
+ * disabled, with the reason under it; the marked one is shown as such either way.
+ */
+function WebSearchChoice({ choice, webSearch, onChoose, unavailableReason, children }: {
+ choice: string;
+ webSearch: WebSearchState;
+ onChoose: (choice: string) => void;
+ unavailableReason?: string;
+ children: ComponentChildren;
+}) {
+ return (
+ <FormListItem
+ checkable
+ checked={webSearch.choice === choice}
+ disabled={!!unavailableReason}
+ description={unavailableReason}
+ closeOnSelect={false}
+ onClick={() => onChoose(choice)}
+ >
+ {children}
+ </FormListItem>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
index 69923ba83d..a538278798 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
@@ -10,8 +10,10 @@ vi.mock("../../../services/llm_chat.js", () => ({
// The chat picker now reads the user's selected models straight from the
// `llmProviders` option (no server fetch), so stub that service.
const optionsGetJsonMock = vi.hoisted(() => vi.fn());
+/** The `llmWebSearchProvider` option. */
+const webSearchProvider = vi.hoisted(() => ({ id: "" }));
vi.mock("../../../services/options.js", () => ({
- default: { getJson: optionsGetJsonMock }
+ default: { getJson: optionsGetJsonMock, get: () => webSearchProvider.id }
}));
// useTriliumEvent subscribes to the app-wide event bus; stub it so the hook
@@ -86,6 +88,7 @@ describe("useLlmChat", () => {
});
afterEach(() => {
+ webSearchProvider.id = "";
if (host) {
render(null, host);
host.remove();
@@ -162,6 +165,29 @@ describe("useLlmChat", () => {
expect(options.providerId).toBe("ca_1");
});
+ it("sends the chosen search provider, unless the model runs its own agent loop", async () => {
+ optionsGetJsonMock.mockReturnValue([ ...PROVIDERS, { id: "s1", name: "Tavily", provider: "tavily", kind: "search" } ]);
+ webSearchProvider.id = "s1";
+ await mountChat();
+ const send = async () => {
+ await act(async () => {
+ api().setInput("hello");
+ });
+ await act(async () => {
+ await api().handleSubmit(new Event("submit"));
+ });
+ return streamChatCompletionMock.mock.calls.at(-1)?.[1];
+ };
+
+ // The default model is Claude Code, which searches with its own tools.
+ expect(await send()).toMatchObject({ enableWebSearch: false, webSearchProviderId: undefined });
+
+ await act(async () => {
+ api().setSelectedModel("llama3.2", "ollama", "ol_1");
+ });
+ expect(await send()).toMatchObject({ enableWebSearch: true, webSearchProviderId: "s1" });
+ });
+
it("holds back a message whose attachments the model cannot read, until the model changes", async () => {
optionsGetJsonMock.mockReturnValue([
{ id: "ds_1", name: "DeepSeek", provider: "deepseek", selectedModels: [
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index 0ed94b5f6a..b356359ca9 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -3,7 +3,8 @@ import { RefObject } from "preact";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { streamChatCompletion } from "../../../services/llm_chat.js";
-import { type ModelOption, type ModelProviderGroup, readSelectedModels, resolveSelectedModel, unreadableAttachments } from "../../../services/llm_providers.js";
+import { type ModelOption, type ModelProviderGroup, readSearchProviders, readSelectedModels, resolveSelectedModel, resolveWebSearch, unreadableAttachments } from "../../../services/llm_providers.js";
+import optionService from "../../../services/options.js";
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
import { estimateTokens, quantizeDraftTokens } from "./chat_context_usage.js";
@@ -603,13 +604,21 @@ export function useLlmChat(
const matchedModel = availableModels.find(m =>
m.id === selectedModel && (!selectedProvider || m.provider === selectedProvider));
const selectedModelProvider = selectedProvider ?? matchedModel?.provider;
+ const webSearch = resolveWebSearch({
+ modelProvider: selectedModelProvider,
+ enableWebSearch,
+ enableNoteTools,
+ searchProviderId: optionService.get("llmWebSearchProvider") ?? "",
+ searchProviders: readSearchProviders()
+ });
const streamOptions: Parameters<typeof streamChatCompletion>[1] = {
model: selectedModel || undefined,
provider: selectedModelProvider,
// The config id pins the exact provider instance when several of the
// same type are configured (e.g. OpenAI + self-hosted Ollama).
providerId: selectedProviderId ?? matchedModel?.providerId,
- enableWebSearch,
+ enableWebSearch: webSearch.enableWebSearch,
+ webSearchProviderId: webSearch.webSearchProviderId,
enableNoteTools,
contextNoteId,
chatNoteId: chatNoteIdRef.current
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
index 9cff809212..76cd0b23b3 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
@@ -112,15 +112,25 @@
<h3>Web search</h3>
<p>The AI can optionally search the web to find more information about a
specific topic.&nbsp;</p>
-<p>This feature is on by default. To turn it off, press the <span class="tn-icon bx bx-shield-quarter"></span> <em>Tools</em> button
- next to the model selector at the bottom of the chat and switch off <em>Web search</em>.</p>
-<aside
-class="admonition note">
- <p>Currently only the search native to the LLM provider is used. External
- search providers (Brave Search, Tavily, Exa and SearXNG) can already be
- added in the <em>Search Providers</em> section of the AI settings, but the
- chat does not use them yet.</p>
-</aside>
+<p>Where the search comes from is chosen under <em>Web search</em> in the <span
+ class="tn-icon bx bx-shield-quarter"></span> <em>Tools</em> menu next to
+ the model selector at the bottom of the chat:</p>
+<ul>
+ <li><em>Disabled</em> turns web search off for this chat.</li>
+ <li><em>Use the model's built-in search</em>, the default, lets the model
+ search with its provider's own search. Anthropic, OpenAI and Google Gemini
+ models have one, as do Claude Code, Google Antigravity and OpenAI Codex.
+ DeepSeek, Ollama, LM Studio and custom endpoints don't, so this choice
+ is disabled for their models.</li>
+ <li>A search provider (Brave Search, Tavily, Exa or SearXNG) searches through
+ that service instead, whichever model is answering. Search providers are
+ added in the <em>Search Providers</em> section of the AI settings, which <em>Manage search providers…</em> at
+ the end of the menu opens.</li>
+</ul>
+<p>Whether web search is on is kept per chat; the search source is shared
+ by all chats. A choice the current model can't use stays in the menu, disabled,
+ with the reason under it. Claude Code, GitHub Copilot, Google Antigravity
+ and OpenAI Codex run their own tools, so they can't use a search provider.</p>
<h3>Thinking</h3>
<p>Some models reason before they answer. While the model is thinking, its
reasoning is shown in full under a spinner; once it is done, it folds into
@@ -240,9 +250,9 @@ class="admonition note">
an attribute because there is no attribute history).</p>
</aside>
<aside class="admonition note">
- <p>Gemini has a special case in which <em>Note access</em> and <em>Web search</em> can't
- be both enabled at the same time. While note access is on, the <em>Web search</em> switch
- in the <em>Tools</em> menu is disabled and says why.</p>
+ <p>Gemini can't use its built-in search while note access is on. While it
+ is, the built-in search choice in the <em>Tools</em> menu is disabled and
+ says why; a search provider works with note access on.</p>
</aside>
<h3>Attachments</h3>
<p>Since Trilium v0.140.0,&nbsp;<a class="reference-link" href="#root/_help_0vhv7lsOLy82">Attachments</a>&nbsp;allow
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
index b8dbedb8d2..7c66b01c0b 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
@@ -75,7 +75,9 @@
PDFs and text files are sent to the provider, and an <code>@</code> mention
makes that note fetchable.</li>
<li><strong>Your search query</strong>, when web search is enabled, the model's
- search terms reach the provider's own search infrastructure.</li>
+ search terms reach the provider's own search infrastructure, or the search
+ provider chosen in the <em>Tools</em> menu (Brave Search, Tavily, Exa or
+ your SearXNG instance).</li>
</ul>
<h2>The in-editor AI assistant</h2>
<p>A run of the&nbsp;<a class="reference-link" href="#root/_help_VRoP0g1uHHc2">In-editor AI assistant</a>&nbsp;sends
diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.md
index ed6a6674d2..a3912b7231 100644
--- a/docs/User Guide/User Guide/AI.md
+++ b/docs/User Guide/User Guide/AI.md
@@ -85,10 +85,13 @@ Pricing information is displayed for known models. The pricing information (pric
The AI can optionally search the web to find more information about a specific topic. 
-This feature is on by default. To turn it off, press the <span class="tn-icon bx bx-shield-quarter"></span> _Tools_ button next to the model selector at the bottom of the chat and switch off _Web search_.
+Where the search comes from is chosen under _Web search_ in the <span class="tn-icon bx bx-shield-quarter"></span> _Tools_ menu next to the model selector at the bottom of the chat:
-> [!NOTE]
-> Currently only the search native to the LLM provider is used. External search providers (Brave Search, Tavily, Exa and SearXNG) can already be added in the _Search Providers_ section of the AI settings, but the chat does not use them yet.
+* _Disabled_ turns web search off for this chat.
+* _Use the model's built-in search_, the default, lets the model search with its provider's own search. Anthropic, OpenAI and Google Gemini models have one, as do Claude Code, Google Antigravity and OpenAI Codex. DeepSeek, Ollama, LM Studio and custom endpoints don't, so this choice is disabled for their models.
+* A search provider (Brave Search, Tavily, Exa or SearXNG) searches through that service instead, whichever model is answering. Search providers are added in the _Search Providers_ section of the AI settings, which _Manage search providers…_ at the end of the menu opens.
+
+Whether web search is on is kept per chat; the search source is shared by all chats. A choice the current model can't use stays in the menu, disabled, with the reason under it. Claude Code, GitHub Copilot, Google Antigravity and OpenAI Codex run their own tools, so they can't use a search provider.
### Thinking
@@ -142,7 +145,7 @@ When the reply stops moving for a couple of seconds while the AI is still at wor
> Currently there is **no permission management** implemented for note tools, meaning that the LLM could potentially remove existing notes or clutter the tree with notes. Generally most actions are easily reversible (deleting the notes, restoring deleted notes, reverting modifications to a note), but there are some that are harder to revert (e.g. setting an attribute because there is no attribute history).
> [!NOTE]
-> Gemini has a special case in which _Note access_ and _Web search_ can't be both enabled at the same time. While note access is on, the _Web search_ switch in the _Tools_ menu is disabled and says why.
+> Gemini can't use its built-in search while note access is on. While it is, the built-in search choice in the _Tools_ menu is disabled and says why; a search provider works with note access on.
### Attachments
diff --git a/docs/User Guide/User Guide/AI/Privacy.md b/docs/User Guide/User Guide/AI/Privacy.md
index f88249982e..e24565792b 100644
--- a/docs/User Guide/User Guide/AI/Privacy.md
+++ b/docs/User Guide/User Guide/AI/Privacy.md
@@ -30,7 +30,7 @@ This is the reason the provider list is grouped this way, and why Trilium pre-se
* Tools let the model search your tree and read notes, attributes and attachments beyond the current one.
* It decides what to fetch; there is no per-note permission system, so the reachable scope is your whole tree.
* **Attachments and mentions**, when you add them: images, PDFs and text files are sent to the provider, and an `@` mention makes that note fetchable.
-* **Your search query**, when web search is enabled, the model's search terms reach the provider's own search infrastructure.
+* **Your search query**, when web search is enabled, the model's search terms reach the provider's own search infrastructure, or the search provider chosen in the _Tools_ menu (Brave Search, Tavily, Exa or your SearXNG instance).
## The in-editor AI assistant
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index 5ee5f6d9e6..1971036762 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -97,6 +97,11 @@ export interface LlmChatConfig {
systemPrompt?: string;
/** Enable web search tool */
enableWebSearch?: boolean;
+ /**
+ * The config id of the search provider that answers {@link enableWebSearch}, in place of the
+ * model's built-in search. Absent, or naming no configured search provider, means built-in.
+ */
+ webSearchProviderId?: string;
/** Enable note tools (search and read notes) */
enableNoteTools?: boolean;
/** Enable extended thinking for deeper reasoning */
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index d1c10d1f11..244134ed4b 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -321,6 +321,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
aiEnabled: boolean;
/** JSON array of configured LLM providers with their API keys */
llmProviders: string;
+ /** Config id of the search provider the chat's web search uses; empty for the model's built-in search. */
+ llmWebSearchProvider: string;
/** The model the text editor's AI assistant runs on, as JSON `{ providerId, provider, model }`; empty to follow the first configured provider's default. */
aiAssistantModel: string;
/** Whether the MCP (Model Context Protocol) server endpoint is enabled. */
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 778310120f..603ab5b5ff 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -157,6 +157,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
// LLM options
"aiEnabled",
"llmProviders",
+ "llmWebSearchProvider",
"aiAssistantModel",
"mcpEnabled",
// OCR options
diff --git a/packages/trilium-core/src/services/llm/chat.spec.ts b/packages/trilium-core/src/services/llm/chat.spec.ts
index 5c9cf77dfd..9876ecb852 100644
--- a/packages/trilium-core/src/services/llm/chat.spec.ts
+++ b/packages/trilium-core/src/services/llm/chat.spec.ts
@@ -11,13 +11,19 @@ const state = vi.hoisted(() => ({
chunkSignal: undefined as AbortSignal | undefined,
/** Records how runChat resolved the provider. */
providerIdRequested: undefined as string | undefined,
- providerTypeRequested: undefined as string | undefined
+ providerTypeRequested: undefined as string | undefined,
+ /** The config the provider's `chat()` was handed. */
+ chatConfig: undefined as unknown
}));
vi.mock("./index.js", () => {
const makeProvider = () => ({
name: "fake",
- chat: () => { if (state.chatThrows !== undefined) throw state.chatThrows; return {}; },
+ chat: (_messages: unknown, config: unknown) => {
+ state.chatConfig = config;
+ if (state.chatThrows !== undefined) throw state.chatThrows;
+ return {};
+ },
chatChunks: state.chunkNative
? async function* (_messages: unknown, _config: unknown, signal?: AbortSignal) {
state.chunkSignal = signal;
@@ -30,6 +36,7 @@ vi.mock("./index.js", () => {
return {
hasConfiguredProviders: () => state.configured,
getSelectedModel: () => undefined,
+ getSearchProviderSetup: (id: string | undefined) => (id === "s1" ? { id: "s1", provider: "tavily", apiKey: "tk" } : undefined),
getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
};
@@ -65,6 +72,16 @@ async function collect(messages: LlmMessage[], config: object = {}, signal?: Abo
const HELLO: LlmMessage[] = [{ role: "user", content: "hi" }];
describe("runChat", () => {
+ it("routes web search through the stored search provider the request names, and only that", async () => {
+ const smuggled = { provider: "brave", apiKey: "stolen", baseURL: "http://169.254.169.254" };
+
+ await collect(HELLO, { enableWebSearch: true, webSearchProviderId: "s1", webSearch: smuggled });
+ expect((state.chatConfig as { webSearch?: unknown }).webSearch).toEqual({ id: "s1", provider: "tavily", apiKey: "tk" });
+
+ await collect(HELLO, { enableWebSearch: true, webSearchProviderId: "deleted", webSearch: smuggled });
+ expect((state.chatConfig as { webSearch?: unknown }).webSearch).toBeUndefined();
+ });
+
afterEach(() => {
Object.assign(state, {
configured: true,
@@ -74,7 +91,8 @@ describe("runChat", () => {
chunkNative: false,
chunkSignal: undefined,
providerIdRequested: undefined,
- providerTypeRequested: undefined
+ providerTypeRequested: undefined,
+ chatConfig: undefined
});
generateChatTitle.mockClear();
errorMock.mockClear();
diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.ts
index 499e127bc7..764d46dcc9 100644
--- a/packages/trilium-core/src/services/llm/chat.ts
+++ b/packages/trilium-core/src/services/llm/chat.ts
@@ -12,7 +12,7 @@ import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
import { getLog } from "../log.js";
import { safeExtractMessageAndStackFromError } from "../utils/index.js";
import { generateChatTitle } from "./chat_title.js";
-import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, type LlmProviderConfig } from "./index.js";
+import { getProvider, getProviderByType, getSearchProviderSetup, getSelectedModel, hasConfiguredProviders, type LlmProviderConfig } from "./index.js";
import { formatStreamError, streamToChunks } from "./stream.js";
import { resolveToolRegistries } from "./tools/index.js";
@@ -29,9 +29,11 @@ import { resolveToolRegistries } from "./tools/index.js";
*/
export async function* runChat(
messages: LlmMessage[],
- config: LlmProviderConfig = {},
+ requestConfig: LlmProviderConfig = {},
abortSignal?: AbortSignal
): AsyncGenerator<LlmStreamChunk> {
+ // `webSearch` comes from the stored provider config only, never from the request.
+ const config: LlmProviderConfig = { ...requestConfig, webSearch: getSearchProviderSetup(requestConfig.webSearchProviderId) };
try {
if (!hasConfiguredProviders()) {
yield { type: "error", error: "No LLM providers configured. Please add a provider in Options → AI / LLM." };
diff --git a/packages/trilium-core/src/services/llm/index.spec.ts b/packages/trilium-core/src/services/llm/index.spec.ts
index de9b295f8e..2615e7b35e 100644
--- a/packages/trilium-core/src/services/llm/index.spec.ts
+++ b/packages/trilium-core/src/services/llm/index.spec.ts
@@ -49,6 +49,7 @@ import {
clearProviderCache,
getProvider,
getProviderByType,
+ getSearchProviderSetup,
getSelectedModel,
hasConfiguredProviders,
HOST_PROVIDED_TYPES,
@@ -201,6 +202,17 @@ describe("llm/index provider registry", () => {
expect(hasConfiguredProviders()).toBe(true);
});
+ it("finds a search provider by config id, never a chat provider", () => {
+ const search = { id: "s1", name: "Tavily", provider: "tavily", kind: "search", apiKey: "k" };
+ setProviders([ ...TWO, search ]);
+ expect(getSearchProviderSetup("s1")).toEqual(search);
+ expect(getSearchProviderSetup("a1")).toBeUndefined();
+ expect(getSearchProviderSetup(undefined)).toBeUndefined();
+
+ getOptionOrNullMock.mockReturnValue("{not json");
+ expect(getSearchProviderSetup("s1")).toBeUndefined();
+ });
+
it("leaves search providers out of the chat providers", async () => {
const search = { id: "s1", name: "Brave Search", provider: "brave", kind: "search", apiKey: "k" };
setProviders([ search ]);
diff --git a/packages/trilium-core/src/services/llm/index.ts b/packages/trilium-core/src/services/llm/index.ts
index 4dde717079..9df3d0bd7c 100644
--- a/packages/trilium-core/src/services/llm/index.ts
+++ b/packages/trilium-core/src/services/llm/index.ts
@@ -95,6 +95,23 @@ let cachedProviders: Record<string, LlmProvider> = {};
*/
let cachedProvidersSource: string | null = null;
+/**
+ * The configured search provider with the config id `searchProviderId`, or undefined when there is
+ * none, so web search falls back to the model's built-in search.
+ */
+export function getSearchProviderSetup(searchProviderId: string | undefined): LlmProviderSetup | undefined {
+ if (!searchProviderId) {
+ return undefined;
+ }
+ try {
+ const configs = JSON.parse(optionService.getOptionOrNull("llmProviders") ?? "[]") as LlmProviderSetup[];
+ return configs.find(c => c.id === searchProviderId && isProviderOfKind(c, "search"));
+ } catch (e) {
+ getLog().error(`Failed to parse llmProviders option: ${e}`);
+ return undefined;
+ }
+}
+
/**
* Get the configured chat providers from the options. Search providers share the option and are
* left out, so none of them is ever picked to answer a chat.
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.ts
index 91dbcc6309..52edad6059 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts
@@ -13,6 +13,7 @@ import { buildNoteHint } from "../note_hint.js";
import { buildSystemPrompt as composeSystemPrompt } from "../system_prompt.js";
import { allToolRegistries } from "../tools/index.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
+import { createWebSearchTool } from "../web_search.js";
import MODEL_PRICES_JSON from "./model_prices.json" with { type: "json" };
const DEFAULT_MAX_TOKENS = 8096;
@@ -406,7 +407,11 @@ export abstract class BaseProvider implements LlmProvider {
const tools: ToolSet = {};
if (config.enableWebSearch) {
- this.addWebSearchTool(tools);
+ if (config.webSearch) {
+ tools.web_search = createWebSearchTool(config.webSearch);
+ } else {
+ this.addWebSearchTool(tools);
+ }
}
if (config.enableNoteTools) {
diff --git a/packages/trilium-core/src/services/llm/providers/google.spec.ts b/packages/trilium-core/src/services/llm/providers/google.spec.ts
index a2d4e4bb8f..240d875f32 100644
--- a/packages/trilium-core/src/services/llm/providers/google.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.spec.ts
@@ -162,6 +162,22 @@ describe("GoogleProvider tool handling", () => {
expect(opts.system).toContain("web search is unavailable in this turn");
});
+ it("keeps note tools beside a configured search provider, which has no conflict to drop", () => {
+ const provider = new GoogleProvider("test-key");
+ provider.chat([{ role: "user", content: "hi" }], {
+ enableWebSearch: true,
+ enableNoteTools: true,
+ webSearch: { provider: "tavily", apiKey: "tk" }
+ });
+
+ expect(googleSearchMock).not.toHaveBeenCalled();
+ const opts = streamTextMock.mock.calls[0][0] as any;
+ expect(opts.tools.google_search).toBeUndefined();
+ expect(opts.tools.web_search).toBeDefined();
+ expect(opts.tools.search_notes).toBeDefined();
+ expect(opts.system).not.toContain("web search is unavailable in this turn");
+ });
+
it("forwards thinkingBudget override under extended thinking with tools enabled", () => {
const provider = new GoogleProvider("test-key");
provider.chat([{ role: "user", content: "hi" }], {
diff --git a/packages/trilium-core/src/services/llm/providers/google.ts b/packages/trilium-core/src/services/llm/providers/google.ts
index fc61c5de1c..535be91d52 100644
--- a/packages/trilium-core/src/services/llm/providers/google.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.ts
@@ -18,7 +18,7 @@ const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
* is Trilium's higher-value capability and is what the user explicitly toggled.
*/
function geminiHasToolConflict(config: LlmProviderConfig): boolean {
- return !!(config.enableWebSearch && config.enableNoteTools);
+ return !!(config.enableWebSearch && config.enableNoteTools && !config.webSearch);
}
export class GoogleProvider extends BaseProvider {
diff --git a/packages/trilium-core/src/services/llm/system_prompt.spec.ts b/packages/trilium-core/src/services/llm/system_prompt.spec.ts
index 4a0d871e4c..db3772a344 100644
--- a/packages/trilium-core/src/services/llm/system_prompt.spec.ts
+++ b/packages/trilium-core/src/services/llm/system_prompt.spec.ts
@@ -44,11 +44,11 @@ describe("buildSystemPrompt", () => {
expect(prompt).toContain("do not have access to web search");
});
- it("points the user at the switch in the Tools menu that turns a missing capability on", () => {
+ it("points the user at the place in the Tools menu that turns a missing capability on", () => {
const prompt = buildSystemPrompt([], {}) ?? "";
// The menu's own icon, as ChatToolsDropdown draws it, for the model to show the user.
const menu = `<span class="tn-icon bx bx-shield-quarter"></span> "Tools" menu`;
- expect(prompt).toContain(`turn it on with the "Web search" switch in the ${menu}`);
+ expect(prompt).toContain(`turn it on by choosing a search source under "Web search" in the ${menu}`);
expect(prompt).toContain(`turn it on with the "Note access" switch in the ${menu}`);
expect(prompt).not.toContain("model name dropdown");
});
diff --git a/packages/trilium-core/src/services/llm/system_prompt.ts b/packages/trilium-core/src/services/llm/system_prompt.ts
index 9c8a208008..cd8f7642ed 100644
--- a/packages/trilium-core/src/services/llm/system_prompt.ts
+++ b/packages/trilium-core/src/services/llm/system_prompt.ts
@@ -72,7 +72,7 @@ export function buildSystemPrompt(messages: LlmMessage[], config: LlmProviderCon
// Web search hint
if (!config.enableWebSearch) {
parts.push(
- `You do not have access to web search. If the user asks for current/real-time information, news, or anything that requires searching the web, inform them that "Web search" is disabled and they can turn it on with ${WEB_SEARCH_TOGGLE}.`
+ `You do not have access to web search. If the user asks for current/real-time information, news, or anything that requires searching the web, inform them that "Web search" is disabled and they can turn it on by ${WEB_SEARCH_TOGGLE}.`
);
}
@@ -139,12 +139,9 @@ function buildTaskListHint(): string {
}
/**
- * Where the user turns a capability on: a switch in the Tools menu beside the model selector in
+ * Where the user turns a capability on: the Tools menu beside the model selector in
* `ChatInputBar`. The icon class must match the toggle button of `ChatToolsDropdown`.
*/
-const NOTE_ACCESS_TOGGLE = describeToggle("Note access");
-const WEB_SEARCH_TOGGLE = describeToggle("Web search");
-
-function describeToggle(label: string): string {
- return `the "${label}" switch in the <span class="tn-icon bx bx-shield-quarter"></span> "Tools" menu next to the model selector, below the message box (include the icon exactly as written, so the user sees the same icon)`;
-}
+const TOOLS_MENU = `the <span class="tn-icon bx bx-shield-quarter"></span> "Tools" menu next to the model selector, below the message box (include the icon exactly as written, so the user sees the same icon)`;
+const NOTE_ACCESS_TOGGLE = `the "Note access" switch in ${TOOLS_MENU}`;
+const WEB_SEARCH_TOGGLE = `choosing a search source under "Web search" in ${TOOLS_MENU}`;
diff --git a/packages/trilium-core/src/services/llm/types.ts b/packages/trilium-core/src/services/llm/types.ts
index eacdce520c..10ec9c596b 100644
--- a/packages/trilium-core/src/services/llm/types.ts
+++ b/packages/trilium-core/src/services/llm/types.ts
@@ -7,12 +7,19 @@
import type { LlmAttachmentKind, LlmChatConfig, LlmMessage, LlmReasoningEffort, LlmStreamChunk } from "@triliumnext/commons";
import type { streamText } from "ai";
+import type { WebSearchSetup } from "./web_search.js";
+
/**
* Extended provider config with server-specific options.
*/
export interface LlmProviderConfig extends LlmChatConfig {
maxTokens?: number;
temperature?: number;
+ /**
+ * The search provider named by {@link LlmChatConfig.webSearchProviderId}, resolved by
+ * `runChat()`. When set, web search goes through it instead of the model's built-in search.
+ */
+ webSearch?: WebSearchSetup;
}
/**
diff --git a/packages/trilium-core/src/services/llm/web_search.spec.ts b/packages/trilium-core/src/services/llm/web_search.spec.ts
new file mode 100644
index 0000000000..775f0becff
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/web_search.spec.ts
@@ -0,0 +1,92 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const fetchMock = vi.hoisted(() => vi.fn());
+vi.mock("./providers/fetch.js", () => ({ llmFetch: fetchMock }));
+
+import { createWebSearchTool, searchWeb } from "./web_search.js";
+
+function respond(body: unknown, status = 200) {
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status }));
+}
+
+/** The URL and init of the one request the search made. */
+function request() {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [ url, init ] = fetchMock.mock.calls[0] as [ string, RequestInit ];
+ return { url, init, headers: init.headers as Record<string, string>, body: init.body ? JSON.parse(init.body as string) : undefined };
+}
+
+const PAGE = { title: "Trilium", url: "https://triliumnotes.org" };
+
+afterEach(() => {
+ fetchMock.mockReset();
+});
+
+describe("searchWeb", () => {
+ it("queries Brave with its subscription token and reads its descriptions", async () => {
+ respond({ web: { results: [ { ...PAGE, description: "Notes" } ] } });
+ const sources = await searchWeb({ provider: "brave", apiKey: "bk" }, "trilium notes");
+
+ const { url, headers } = request();
+ expect(url).toBe("https://api.search.brave.com/res/v1/web/search?q=trilium+notes&count=8");
+ expect(headers["X-Subscription-Token"]).toBe("bk");
+ expect(sources).toEqual([ { ...PAGE, snippet: "Notes" } ]);
+ });
+
+ it("posts to Tavily and Exa with their keys, honoring a base URL override", async () => {
+ respond({ results: [ { ...PAGE, content: "From Tavily" } ] });
+ expect(await searchWeb({ provider: "tavily", apiKey: "tk", baseURL: "https://proxy.example" }, "q"))
+ .toEqual([ { ...PAGE, snippet: "From Tavily" } ]);
+ const tavily = request();
+ expect(tavily.url).toBe("https://proxy.example/search");
+ expect(tavily.init.method).toBe("POST");
+ expect(tavily.headers.Authorization).toBe("Bearer tk");
+ expect(tavily.body).toEqual({ query: "q", max_results: 8 });
+
+ fetchMock.mockReset();
+ respond({ results: [ { ...PAGE, text: "From Exa" } ] });
+ expect(await searchWeb({ provider: "exa", apiKey: "ek" }, "q")).toEqual([ { ...PAGE, snippet: "From Exa" } ]);
+ const exa = request();
+ expect(exa.url).toBe("https://api.exa.ai/search");
+ expect(exa.headers["x-api-key"]).toBe("ek");
+ expect(exa.body).toMatchObject({ query: "q", numResults: 8 });
+ });
+
+ it("asks SearXNG for JSON, sends a key only when there is one, and keeps web URLs only", async () => {
+ respond({ results: [ { ...PAGE, content: "Hit" }, { title: "Local", url: "file:///etc/passwd" }, { url: "https://untitled.example" } ] });
+ const sources = await searchWeb({ provider: "searxng", apiKey: "", baseURL: "http://localhost:8888/" }, "q");
+
+ const { url, headers } = request();
+ expect(url).toBe("http://localhost:8888/search?q=q&format=json");
+ expect(headers).not.toHaveProperty("Authorization");
+ expect(sources).toEqual([
+ { ...PAGE, snippet: "Hit" },
+ { title: "https://untitled.example", url: "https://untitled.example", snippet: "" }
+ ]);
+
+ await expect(searchWeb({ provider: "searxng", apiKey: "" }, "q")).rejects.toThrow("has no address");
+ });
+
+ it("names a refused key, any other HTTP failure, and an unknown provider type", async () => {
+ respond({}, 401);
+ await expect(searchWeb({ provider: "brave", apiKey: "bad" }, "q")).rejects.toThrow("check its API key");
+ respond({}, 500);
+ await expect(searchWeb({ provider: "brave", apiKey: "bk" }, "q")).rejects.toThrow("HTTP 500");
+ await expect(searchWeb({ provider: "bing", apiKey: "" }, "q")).rejects.toThrow("Unknown search provider type: bing");
+ });
+});
+
+describe("createWebSearchTool", () => {
+ const run = (tool: ReturnType<typeof createWebSearchTool>, query: string) =>
+ tool.execute?.({ query }, { toolCallId: "1", messages: [], context: {} });
+
+ it("returns the query and its sources, or the failure for the model to report", async () => {
+ const tool = createWebSearchTool({ provider: "tavily", apiKey: "tk" });
+
+ respond({ results: [ { ...PAGE, content: "Hit" } ] });
+ expect(await run(tool, "trilium")).toEqual({ query: "trilium", sources: [ { ...PAGE, snippet: "Hit" } ] });
+
+ respond({}, 403);
+ expect(await run(tool, "trilium")).toEqual({ error: expect.stringContaining("HTTP 403") });
+ });
+});
diff --git a/packages/trilium-core/src/services/llm/web_search.ts b/packages/trilium-core/src/services/llm/web_search.ts
new file mode 100644
index 0000000000..a0804b252a
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/web_search.ts
@@ -0,0 +1,120 @@
+/**
+ * Web search through a search provider the user configured (`kind: "search"` in the
+ * `llmProviders` option), offered to the model as a `web_search` tool in place of the model's
+ * built-in search.
+ */
+
+import { tool } from "ai";
+import { z } from "zod";
+
+import { llmFetch } from "./providers/fetch.js";
+
+/** A configured search provider, as stored in the `llmProviders` option. */
+export interface WebSearchSetup {
+ provider: string;
+ apiKey: string;
+ baseURL?: string;
+}
+
+export interface WebSearchSource {
+ title: string;
+ url: string;
+ snippet: string;
+}
+
+const MAX_RESULTS = 8;
+const SEARCH_TIMEOUT_MS = 30_000;
+
+/**
+ * The `web_search` tool for `setup`. Its result has the `sources` the chat lists under the tool's
+ * line, and a failure is returned as `{ error }` so the model can tell the user about it.
+ */
+export function createWebSearchTool(setup: WebSearchSetup) {
+ return tool({
+ description: "Search the web for current information. Returns the title, URL and an excerpt of each matching page.",
+ inputSchema: z.object({
+ query: z.string().describe("The search query")
+ }),
+ execute: async ({ query }) => {
+ try {
+ return { query, sources: await searchWeb(setup, query) };
+ } catch (e) {
+ return { error: e instanceof Error ? e.message : String(e) };
+ }
+ }
+ });
+}
+
+/**
+ * Run `query` against the search provider in `setup`.
+ *
+ * A switch over literal cases, as `createProviderInstance()` is, because the provider type is
+ * user-controlled.
+ */
+export async function searchWeb(setup: WebSearchSetup, query: string): Promise<WebSearchSource[]> {
+ switch (setup.provider) {
+ case "brave": {
+ const base = setup.baseURL ?? "https://api.search.brave.com/res/v1";
+ const params = new URLSearchParams({ q: query, count: String(MAX_RESULTS) });
+ const payload = await requestJson(`${base}/web/search?${params}`, {
+ headers: { "Accept": "application/json", "X-Subscription-Token": setup.apiKey }
+ }) as { web?: { results?: unknown[] } };
+ return toSources(payload.web?.results, "description");
+ }
+ case "tavily": {
+ const payload = await requestJson(`${setup.baseURL ?? "https://api.tavily.com"}/search`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${setup.apiKey}` },
+ body: JSON.stringify({ query, max_results: MAX_RESULTS })
+ }) as { results?: unknown[] };
+ return toSources(payload.results, "content");
+ }
+ case "exa": {
+ const payload = await requestJson(`${setup.baseURL ?? "https://api.exa.ai"}/search`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "x-api-key": setup.apiKey },
+ body: JSON.stringify({ query, numResults: MAX_RESULTS, contents: { text: { maxCharacters: 1000 } } })
+ }) as { results?: unknown[] };
+ return toSources(payload.results, "text");
+ }
+ case "searxng": {
+ if (!setup.baseURL) {
+ throw new Error("The SearXNG search provider has no address.");
+ }
+ const params = new URLSearchParams({ q: query, format: "json" });
+ const payload = await requestJson(`${setup.baseURL.replace(/\/+$/, "")}/search?${params}`, {
+ headers: { "Accept": "application/json", ...(setup.apiKey && { "Authorization": `Bearer ${setup.apiKey}` }) }
+ }) as { results?: unknown[] };
+ return toSources(payload.results, "content").slice(0, MAX_RESULTS);
+ }
+ default:
+ throw new Error(`Unknown search provider type: ${setup.provider}`);
+ }
+}
+
+async function requestJson(url: string, init: RequestInit): Promise<unknown> {
+ const response = await llmFetch(url, { ...init, signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS) });
+ if (!response.ok) {
+ if (response.status === 401 || response.status === 403) {
+ throw new Error(`The search provider refused the request (HTTP ${response.status}); check its API key in the AI settings.`);
+ }
+ throw new Error(`The search provider answered HTTP ${response.status}.`);
+ }
+ return await response.json();
+}
+
+/** The results that carry a web URL, with the excerpt read from `snippetField`. */
+function toSources(results: unknown[] | undefined, snippetField: string): WebSearchSource[] {
+ const sources: WebSearchSource[] = [];
+ for (const result of results ?? []) {
+ const { title, url, [snippetField]: snippet } = (result ?? {}) as Record<string, unknown>;
+ if (typeof url === "string" && /^https?:\/\//i.test(url)) {
+ sources.push({
+ title: typeof title === "string" ? title : url,
+ url,
+ snippet: typeof snippet === "string" ? snippet : ""
+ });
+ }
+ }
+ return sources;
+}
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index fc5584ac92..2ff6a0b561 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -365,6 +365,7 @@ const defaultOptions: DefaultOption[] = [
// Was previously the "llm" experimental feature; inherit the value from there for existing users.
{ name: "aiEnabled", value: (optionsMap) => optionsMap.experimentalFeatures?.includes('"llm"') ? "true" : "false", isSynced: true },
{ name: "llmProviders", value: "[]", isSynced: true },
+ { name: "llmWebSearchProvider", value: "", isSynced: true },
{ name: "aiAssistantModel", value: "", isSynced: true },
{ name: "mcpEnabled", value: "false", isSynced: false },