Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions ui/apps/chat/src/lib/constants/agentic.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,20 @@ export const LEGACY_AGENTIC_REGEX = {
REASONING_EXTRACT: /<<<reasoning_content_start>>>([\s\S]*?)<<<reasoning_content_end>>>/,
REASONING_OPEN: /<<<reasoning_content_start>>>[\s\S]*$/
} as const;

/** The tool that loads tools on demand. */
export const TOOL_SEARCH_NAME = 'tool_search';
/** A search for tools by exact name: `select:a,b`. */
export const TOOL_SEARCH_SELECT_PREFIX = 'select:';
export const TOOL_SEARCH_DEFAULT_LIMIT = 5;

export const TOOL_LOADING = {
/** Automatic mode loads on demand once definitions pass this share of the context. */
AUTO_SHARE: 0.1,
/** Rough characters per token, to size tool definitions without a tokenizer. */
CHARS_PER_TOKEN: 4,
/** Context assumed when the server does not report its size. */
DEFAULT_CONTEXT_TOKENS: 8192,
/** The share of the context the list of tools to load may take. */
LIST_SHARE: 0.05
} as const;
1 change: 1 addition & 0 deletions ui/apps/chat/src/lib/constants/settings-keys.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export const SETTINGS_KEYS = {
TITLE_GENERATION_USE_LLM: 'titleGenerationUseLLM',
TOOL_CALL_SHOWN_ARG: 'toolCallShownArg',
TOOL_CALL_SHOWN_ARG_OVERRIDES: 'toolCallShownArgOverrides',
TOOL_LOADING: 'toolLoading',
TOP_K: 'top_k',
TOP_P: 'top_p',
TYP_P: 'typ_p',
Expand Down
22 changes: 21 additions & 1 deletion ui/apps/chat/src/lib/constants/settings.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,26 @@ import Database from '@lucide/svelte/icons/database';
import Eye from '@lucide/svelte/icons/eye';
import FilePen from '@lucide/svelte/icons/file-pen';
import Funnel from '@lucide/svelte/icons/funnel';
import Layers from '@lucide/svelte/icons/layers';
import ListRestart from '@lucide/svelte/icons/list-restart';
import ListTree from '@lucide/svelte/icons/list-tree';
import Mic from '@lucide/svelte/icons/mic';
import Monitor from '@lucide/svelte/icons/monitor';
import Moon from '@lucide/svelte/icons/moon';
import PencilRuler from '@lucide/svelte/icons/pencil-ruler';
import Puzzle from '@lucide/svelte/icons/puzzle';
import Search from '@lucide/svelte/icons/search';
import ShieldQuestion from '@lucide/svelte/icons/shield-question-mark';
import SlidersVertical from '@lucide/svelte/icons/sliders-vertical';
import Sun from '@lucide/svelte/icons/sun';
import TextCursorInput from '@lucide/svelte/icons/text-cursor-input';
import Zap from '@lucide/svelte/icons/zap';
import { PermissionMode, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import {
PermissionMode,
SyncableParameterType,
ToolLoadingMode,
VoiceInputMode
} from '#lib/enums/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import type {
Expand Down Expand Up @@ -559,6 +567,18 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
],
type: SettingsFieldType.SELECT
},
{
defaultValue: ToolLoadingMode.AUTO,
help: 'How MCP and custom tools reach the model. On demand sends a short list of them and a search tool; the model loads the ones it needs, and they stay loaded for the conversation. Automatic does that once the tools would take more than a tenth of the context. Built-in and llama-server tools are always sent in full.',
key: SETTINGS_KEYS.TOOL_LOADING,
label: 'Tool loading',
options: [
{ icon: ListTree, label: 'Automatic', value: ToolLoadingMode.AUTO },
{ icon: Search, label: 'On demand', value: ToolLoadingMode.ON_DEMAND },
{ icon: Layers, label: 'All up front', value: ToolLoadingMode.UP_FRONT }
],
type: SettingsFieldType.SELECT
},
{
defaultValue: DEFAULT_MCP_CONFIG.requestTimeoutSeconds,
extension: 'mcp',
Expand Down
1 change: 1 addition & 0 deletions ui/apps/chat/src/lib/enums/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export {
SearchChatsOrder,
ServerToolType,
ToolSource,
ToolLoadingMode,
ToolPermissionDecision,
ToolResponseField
} from './tools.enums';
Expand Down
10 changes: 10 additions & 0 deletions ui/apps/chat/src/lib/enums/tools.enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ export enum ToolPermissionDecision {
SESSION = 'session'
}

/** How tool definitions reach the model. */
export enum ToolLoadingMode {
/** On demand once the definitions take a large share of the context. */
AUTO = 'auto',
/** MCP and custom tools as a list to load from, always. */
ON_DEMAND = 'on_demand',
/** Every enabled tool in every request. */
UP_FRONT = 'up_front'
}

export enum ToolResponseField {
ERROR = 'error',
PLAIN_TEXT = 'plain_text_response'
Expand Down
104 changes: 90 additions & 14 deletions ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ import {
DEFAULT_AGENTIC_CONFIG,
NEWLINE,
SETTINGS_KEYS,
TOOL_DENIED_RESULT
TOOL_DENIED_RESULT,
TOOL_LOADING,
TOOL_SEARCH_NAME
} from '#lib/constants/index.ts';
import {
AUDIO_MIME_TO_EXTENSION,
Expand All @@ -41,6 +43,7 @@ import {
BuiltInTool,
PermissionEffect,
PermissionMode,
ToolLoadingMode,
ToolPermissionDecision,
ToolSource
} from '#lib/enums/index.ts';
Expand Down Expand Up @@ -99,6 +102,7 @@ import {
isAbortError,
throwIfAborted
} from '#lib/utils/index.ts';
import { createToolCatalog, definitionsSize, type ToolCatalog } from '#lib/utils/tool-catalog.ts';
import { SvelteMap } from 'svelte/reactivity';

function createDefaultSession(): AgenticSession {
Expand Down Expand Up @@ -171,6 +175,8 @@ function withTotalTime<T extends ChatMessageTimings | undefined>(timings: T, sta
class AgenticStore {
// permission, continue and steering gates the loop waits on between turns
private gates = new AgenticGates();
/** Tools loaded on demand per conversation: they stay loaded, so the tool list only grows */
private loadedTools = new Map<string, Set<string>>();
private sessions = new SvelteMap<string, AgenticSession>();

get isAnyRunning(): boolean {
Expand Down Expand Up @@ -442,6 +448,10 @@ class AgenticStore {
signal?: AbortSignal
): Promise<Authorization> {
const toolName = toolCall.function.name;

// loading a tool is not using it: the loaded tool asks when it is called
if (toolName === TOOL_SEARCH_NAME) return { type: 'allow' };

const toolKey = toolsStore.getPermissionKey(toolName) ?? toolName;
const isServerTool = toolsStore.getToolSource(toolName) === ToolSource.SERVER;
const args = this.parseToolArguments(toolCall.function.arguments);
Expand Down Expand Up @@ -679,22 +689,36 @@ class AgenticStore {
execute: (toolCall, context) =>
this.executeTool({ callbacks, context, conversationId, effectiveModel, toolCall })
}));
const catalog = this.toolCatalog(conversationId, harnessTools, effectiveModel);
// result messages of streaming tools, created while the tool runs, by tool call id
const streamedResults = new SvelteMap<string, { content: string; messageId: string }>();
const events = harness.run(toAgenticMessages(messages) as Message[], harnessTools, signal, {
authorize: (toolCall, runSignal) => this.authorizeTool(conversationId, toolCall, runSignal),
interrupted: () => this.gates.hasPendingSteeringMessage(conversationId),
maxTurns: agenticConfig.maxTurns,
onTurnLimit: async () => {
// Turn limit reached - ask user whether to continue
const shouldContinue = await this.gates.requestContinue(conversationId, signal);

// Yield to allow Svelte to flush the UI update
await new Promise((r) => setTimeout(r, 0));

return shouldContinue;
const events = harness.run(
toAgenticMessages(messages) as Message[],
catalog ? catalog.initialTools() : harnessTools,
signal,
{
authorize: (toolCall, runSignal) => this.authorizeTool(conversationId, toolCall, runSignal),
interrupted: () => this.gates.hasPendingSteeringMessage(conversationId),
maxTurns: agenticConfig.maxTurns,
onTurnLimit: async () => {
// Turn limit reached - ask user whether to continue
const shouldContinue = await this.gates.requestContinue(conversationId, signal);

// Yield to allow Svelte to flush the UI update
await new Promise((r) => setTimeout(r, 0));

return shouldContinue;
},
prepareTurn: catalog
? async ({ tools: sent }) => {
const loaded = catalog.takeNewlyLoaded();

return loaded.length > 0 ? { tools: [...sent, ...loaded] } : undefined;
}
: undefined,
resolveTool: catalog ? (name) => catalog.resolve(name) : undefined
}
});
);

let totalToolCallCount = 0;
let lastStreamingToolCallName = '';
Expand Down Expand Up @@ -1046,6 +1070,52 @@ class AgenticStore {
* makes a provider start over; a caller without a policy falls back to
* the global defaults.
*/
/**
* The catalog that loads MCP and custom tools on demand, or nothing when
* every tool goes up front: by the setting, or in automatic mode while
* the definitions take a small share of the context.
*/
private toolCatalog(conversationId: string, tools: Tool[], model: string): ToolCatalog | null {
const mode = toolLoadingMode(settingsStore.config[SETTINGS_KEYS.TOOL_LOADING]);

if (mode === ToolLoadingMode.UP_FRONT) return null;

const isDeferred = (tool: Tool) => {
const source = toolsStore.getToolSource(tool.definition.function.name);

return source === ToolSource.MCP || source === ToolSource.CUSTOM;
};
const deferred = tools.filter(isDeferred);

if (deferred.length === 0) return null;

const contextTokens =
modelsStore.props.getModelContextSize(model) ?? TOOL_LOADING.DEFAULT_CONTEXT_TOKENS;
const definitionTokens = definitionsSize(tools) / TOOL_LOADING.CHARS_PER_TOKEN;

if (
mode === ToolLoadingMode.AUTO &&
definitionTokens < contextTokens * TOOL_LOADING.AUTO_SHARE
) {
return null;
}

let loaded = this.loadedTools.get(conversationId);

if (!loaded) {
loaded = new Set();
this.loadedTools.set(conversationId, loaded);
}

return createToolCatalog({
core: tools.filter((tool) => !isDeferred(tool)),
deferred,
groupOf: (tool) => toolsStore.getToolServerLabel(tool.definition.function.name) || 'Other',
listBudgetChars: contextTokens * TOOL_LOADING.LIST_SHARE * TOOL_LOADING.CHARS_PER_TOKEN,
loaded
});
}

private async toolsFor(toolPolicy?: AgenticToolPolicy): Promise<OpenAIToolDefinition[]> {
if (
!toolsStore.hasServerTools &&
Expand Down Expand Up @@ -1090,3 +1160,9 @@ function permissionMode(value: unknown): PermissionMode {
? (value as PermissionMode)
: PermissionMode.ASK;
}

function toolLoadingMode(value: unknown): ToolLoadingMode {
return Object.values(ToolLoadingMode).includes(value as ToolLoadingMode)
? (value as ToolLoadingMode)
: ToolLoadingMode.AUTO;
}
Loading
Loading