mirror of
https://github.com/open-webui/computer.git
synced 2026-12-02 01:42:55 -05:00
refac
This commit is contained in:
1 parent
09793beeed
commit
28812039fc
5 files changed
+300
-18
No files matched your search
@@ -170,6 +170,7 @@ export interface ModelConfigEntry {
|
||||
request_params?: Record<string, unknown>;
|
||||
system_prompt?: string;
|
||||
compact_token_threshold?: number;
|
||||
builtin_tools?: Record<string, boolean> | null;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
import Icon from '../Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
type ParamRow = { key: string; value: string };
|
||||
type BuiltinToolsConfig = Record<string, boolean>;
|
||||
type ModelEntry = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -25,6 +27,7 @@
|
||||
rows: ParamRow[];
|
||||
systemPrompt: string;
|
||||
compactTokenThreshold: number | null;
|
||||
builtinTools: BuiltinToolsConfig;
|
||||
dirty: boolean;
|
||||
};
|
||||
|
||||
@@ -37,6 +40,7 @@
|
||||
let globalRows = $state<ParamRow[]>([]);
|
||||
let globalSystemPrompt = $state('');
|
||||
let globalCompactTokenThreshold = $state<number | null>(null);
|
||||
let globalBuiltinTools = $state<BuiltinToolsConfig>({});
|
||||
let globalDirty = $state(false);
|
||||
let globalExpanded = $state(false);
|
||||
let showVariables = $state(false);
|
||||
@@ -66,6 +70,40 @@
|
||||
{ name: 'MODEL', desc: 'Model ID being used' }
|
||||
];
|
||||
|
||||
const BUILTIN_TOOL_GROUPS = [
|
||||
{ id: 'files', label: 'models.builtinTools.files', desc: 'models.builtinTools.filesDesc' },
|
||||
{
|
||||
id: 'terminal',
|
||||
label: 'models.builtinTools.terminal',
|
||||
desc: 'models.builtinTools.terminalDesc'
|
||||
},
|
||||
{ id: 'web', label: 'models.builtinTools.web', desc: 'models.builtinTools.webDesc' },
|
||||
{
|
||||
id: 'browser',
|
||||
label: 'models.builtinTools.browser',
|
||||
desc: 'models.builtinTools.browserDesc'
|
||||
},
|
||||
{ id: 'memory', label: 'models.builtinTools.memory', desc: 'models.builtinTools.memoryDesc' },
|
||||
{ id: 'chats', label: 'models.builtinTools.chats', desc: 'models.builtinTools.chatsDesc' },
|
||||
{ id: 'skills', label: 'models.builtinTools.skills', desc: 'models.builtinTools.skillsDesc' },
|
||||
{
|
||||
id: 'automations',
|
||||
label: 'models.builtinTools.automations',
|
||||
desc: 'models.builtinTools.automationsDesc'
|
||||
},
|
||||
{ id: 'images', label: 'models.builtinTools.images', desc: 'models.builtinTools.imagesDesc' },
|
||||
{
|
||||
id: 'subagents',
|
||||
label: 'models.builtinTools.subagents',
|
||||
desc: 'models.builtinTools.subagentsDesc'
|
||||
},
|
||||
{
|
||||
id: 'notifications',
|
||||
label: 'models.builtinTools.notifications',
|
||||
desc: 'models.builtinTools.notificationsDesc'
|
||||
}
|
||||
];
|
||||
|
||||
const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer, a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress.
|
||||
|
||||
{{CPTR_CONTEXT}}
|
||||
@@ -95,6 +133,60 @@ Files:
|
||||
return Number.isFinite(threshold) && threshold > 0 ? Math.floor(threshold) : null;
|
||||
}
|
||||
|
||||
function parseBuiltinTools(config: ModelConfigEntry | undefined): BuiltinToolsConfig {
|
||||
const value = config?.params?.builtin_tools;
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).filter(([, enabled]) => typeof enabled === 'boolean')
|
||||
);
|
||||
}
|
||||
|
||||
function builtinEnabled(
|
||||
tools: BuiltinToolsConfig,
|
||||
group: string,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): boolean {
|
||||
if (tools[group] !== undefined) return tools[group] !== false;
|
||||
if (inherited?.[group] !== undefined) return inherited[group] !== false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function setBuiltinEnabled(
|
||||
tools: BuiltinToolsConfig,
|
||||
group: string,
|
||||
enabled: boolean,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): BuiltinToolsConfig {
|
||||
const next = { ...tools };
|
||||
const inheritedEnabled = inherited?.[group] !== undefined ? inherited[group] !== false : true;
|
||||
if (enabled === inheritedEnabled) {
|
||||
delete next[group];
|
||||
} else {
|
||||
next[group] = enabled;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function serializeBuiltinTools(
|
||||
tools: BuiltinToolsConfig,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): BuiltinToolsConfig | null {
|
||||
const result: BuiltinToolsConfig = {};
|
||||
for (const group of BUILTIN_TOOL_GROUPS) {
|
||||
if (tools[group.id] === undefined) continue;
|
||||
const inheritedEnabled =
|
||||
inherited?.[group.id] !== undefined ? inherited[group.id] !== false : true;
|
||||
if (tools[group.id] !== inheritedEnabled) {
|
||||
result[group.id] = tools[group.id];
|
||||
}
|
||||
}
|
||||
return Object.keys(result).length ? result : null;
|
||||
}
|
||||
|
||||
function configuredRowCount(rows: ParamRow[]): number {
|
||||
return rows.filter((row) => row.key.trim()).length;
|
||||
}
|
||||
|
||||
function rowsToRequestParams(rows: ParamRow[]): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const { key, value } of rows) {
|
||||
@@ -119,8 +211,12 @@ Files:
|
||||
globalRows = parseRows(config['*']);
|
||||
globalSystemPrompt = config['*']?.params?.system_prompt || '';
|
||||
globalCompactTokenThreshold = parseCompactTokenThreshold(config['*']);
|
||||
globalBuiltinTools = parseBuiltinTools(config['*']);
|
||||
globalExpanded =
|
||||
globalRows.length > 0 || !!globalSystemPrompt || globalCompactTokenThreshold !== null;
|
||||
globalRows.length > 0 ||
|
||||
!!globalSystemPrompt ||
|
||||
globalCompactTokenThreshold !== null ||
|
||||
Object.keys(globalBuiltinTools).length > 0;
|
||||
}
|
||||
|
||||
models = data.models.map((m) => {
|
||||
@@ -136,6 +232,7 @@ Files:
|
||||
rows: parseRows(mc),
|
||||
systemPrompt: (mc?.params as any)?.system_prompt || '',
|
||||
compactTokenThreshold: parseCompactTokenThreshold(mc),
|
||||
builtinTools: parseBuiltinTools(mc),
|
||||
dirty: false
|
||||
};
|
||||
});
|
||||
@@ -204,13 +301,17 @@ Files:
|
||||
function buildParams(
|
||||
rows: ParamRow[],
|
||||
systemPrompt: string,
|
||||
compactThreshold: number | null
|
||||
compactThreshold: number | null,
|
||||
builtinTools: BuiltinToolsConfig,
|
||||
inheritedBuiltinTools: BuiltinToolsConfig | null = null
|
||||
): Record<string, unknown> {
|
||||
const params: Record<string, unknown> = {};
|
||||
const rp = rowsToRequestParams(rows);
|
||||
const bt = serializeBuiltinTools(builtinTools, inheritedBuiltinTools);
|
||||
if (Object.keys(rp).length) params.request_params = rp;
|
||||
if (systemPrompt.trim()) params.system_prompt = systemPrompt.trim();
|
||||
if (compactThreshold && compactThreshold > 0) params.compact_token_threshold = compactThreshold;
|
||||
if (bt) params.builtin_tools = bt;
|
||||
return params;
|
||||
}
|
||||
|
||||
@@ -221,7 +322,12 @@ Files:
|
||||
if (globalDirty) {
|
||||
promises.push(
|
||||
updateModelConfig('*', {
|
||||
params: buildParams(globalRows, globalSystemPrompt, globalCompactTokenThreshold)
|
||||
params: buildParams(
|
||||
globalRows,
|
||||
globalSystemPrompt,
|
||||
globalCompactTokenThreshold,
|
||||
globalBuiltinTools
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -229,7 +335,13 @@ Files:
|
||||
if (model.dirty) {
|
||||
promises.push(
|
||||
updateModelConfig(model.id, {
|
||||
params: buildParams(model.rows, model.systemPrompt, model.compactTokenThreshold)
|
||||
params: buildParams(
|
||||
model.rows,
|
||||
model.systemPrompt,
|
||||
model.compactTokenThreshold,
|
||||
model.builtinTools,
|
||||
globalBuiltinTools
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -380,6 +492,47 @@ Files:
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet builtinToolsField(
|
||||
tools: BuiltinToolsConfig,
|
||||
inherited: BuiltinToolsConfig | null,
|
||||
onChange: (tools: BuiltinToolsConfig) => void,
|
||||
resetLabel: string
|
||||
)}
|
||||
<div class="mb-2">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-[0.625rem] text-gray-400 dark:text-gray-600 uppercase tracking-wide"
|
||||
>{$t('models.builtinTools')}</span
|
||||
>
|
||||
{#if Object.keys(tools).length > 0}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
|
||||
onclick={() => onChange({})}
|
||||
>
|
||||
{resetLabel}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3 gap-y-1">
|
||||
{#each BUILTIN_TOOL_GROUPS as group}
|
||||
<div class="flex items-center justify-between gap-2 min-h-7">
|
||||
<div class="min-w-0">
|
||||
<div class="text-[0.75rem] text-gray-600 dark:text-gray-400 truncate">
|
||||
{$t(group.label)}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate">
|
||||
{$t(group.desc)}
|
||||
</div>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={builtinEnabled(tools, group.id, inherited)}
|
||||
onchange={(enabled) => onChange(setBuiltinEnabled(tools, group.id, enabled, inherited))}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
@@ -448,11 +601,11 @@ Files:
|
||||
<span class="flex-1 text-[0.8125rem] text-gray-500 dark:text-gray-400"
|
||||
>{$t('models.defaults')}</span
|
||||
>
|
||||
{#if globalRows.filter((r) => r.key.trim()).length > 0 || globalSystemPrompt.trim()}
|
||||
{#if configuredRowCount(globalRows) > 0 || globalSystemPrompt.trim()}
|
||||
<span class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{#if globalSystemPrompt.trim()}prompt{/if}
|
||||
{#if globalRows.filter((r) => r.key.trim()).length > 0}
|
||||
{globalRows.filter((r) => r.key.trim()).length} params
|
||||
{#if configuredRowCount(globalRows) > 0}
|
||||
{configuredRowCount(globalRows)} params
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
@@ -480,6 +633,15 @@ Files:
|
||||
},
|
||||
DEFAULT_PROMPT_PLACEHOLDER
|
||||
)}
|
||||
{@render builtinToolsField(
|
||||
globalBuiltinTools,
|
||||
null,
|
||||
(tools) => {
|
||||
globalBuiltinTools = tools;
|
||||
globalDirty = true;
|
||||
},
|
||||
$t('models.resetToDefault')
|
||||
)}
|
||||
{@render paramRows(
|
||||
globalRows,
|
||||
() => (globalDirty = true),
|
||||
@@ -546,6 +708,16 @@ Files:
|
||||
},
|
||||
$t('models.systemPromptInherited')
|
||||
)}
|
||||
{@render builtinToolsField(
|
||||
model.builtinTools,
|
||||
globalBuiltinTools,
|
||||
(tools) => {
|
||||
model.builtinTools = tools;
|
||||
model.dirty = true;
|
||||
models = [...models];
|
||||
},
|
||||
$t('models.resetToDefault')
|
||||
)}
|
||||
{@render paramRows(
|
||||
model.rows,
|
||||
() => (model.dirty = true),
|
||||
|
||||
@@ -908,6 +908,29 @@
|
||||
"connections.chatCompletions": "Chat Completions",
|
||||
"connections.responses": "Responses",
|
||||
"admin.agentsNoProfiles": "No agent profiles",
|
||||
"models.builtinTools": "Builtin Tools",
|
||||
"models.builtinTools.files": "Files",
|
||||
"models.builtinTools.filesDesc": "Read, search, create, and edit workspace files",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Run commands and manage command sessions",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Search the web and read URLs",
|
||||
"models.builtinTools.browser": "Browser",
|
||||
"models.builtinTools.browserDesc": "Navigate, inspect, click, type, screenshot, and evaluate pages",
|
||||
"models.builtinTools.memory": "Memory",
|
||||
"models.builtinTools.memoryDesc": "Save durable user and workspace memories",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"models.builtinTools.chatsDesc": "Search previous chats",
|
||||
"models.builtinTools.skills": "Skills",
|
||||
"models.builtinTools.skillsDesc": "View and manage Computer skills",
|
||||
"models.builtinTools.automations": "Automations",
|
||||
"models.builtinTools.automationsDesc": "List and manage scheduled automations",
|
||||
"models.builtinTools.images": "Images",
|
||||
"models.builtinTools.imagesDesc": "Generate or edit images",
|
||||
"models.builtinTools.subagents": "Subagents",
|
||||
"models.builtinTools.subagentsDesc": "Delegate work to sub-agents",
|
||||
"models.builtinTools.notifications": "Notifications",
|
||||
"models.builtinTools.notificationsDesc": "Send user notifications",
|
||||
"models.requestParams": "Request params",
|
||||
"models.paramKey": "key",
|
||||
"models.paramValue": "value",
|
||||
|
||||
+39
-10
@@ -52,6 +52,27 @@ PLAN_MODE_PROMPT = (
|
||||
|
||||
SKILLS_CREATE_RE = re.compile(r"^/skills:create(?:\s+(.*))?$", re.IGNORECASE | re.DOTALL)
|
||||
|
||||
|
||||
def resolve_builtin_tools_config(
|
||||
chat_models_config: dict | None, *model_ids: str | None
|
||||
) -> dict | None:
|
||||
"""Merge global/model builtin tool group config. Missing/null means default."""
|
||||
if not isinstance(chat_models_config, dict):
|
||||
return None
|
||||
merged: dict = {}
|
||||
found = False
|
||||
for model_id in ("*", *[m for m in model_ids if m]):
|
||||
model_config = chat_models_config.get(model_id)
|
||||
if not isinstance(model_config, dict):
|
||||
continue
|
||||
params = model_config.get("params", {})
|
||||
value = params.get("builtin_tools") if isinstance(params, dict) else None
|
||||
if isinstance(value, dict):
|
||||
merged.update(value)
|
||||
found = True
|
||||
return merged if found else None
|
||||
|
||||
|
||||
COMPUTER_SKILL_AUTHORING_STANDARDS = """\
|
||||
Follow the Computer skill-authoring standards:
|
||||
|
||||
@@ -1631,6 +1652,11 @@ async def run_chat_task(
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
configured_model = (msg.model if msg else None) or model
|
||||
try:
|
||||
chat_models_config = await Config.get("chat.models") or {}
|
||||
except Exception:
|
||||
chat_models_config = {}
|
||||
builtin_tools = resolve_builtin_tools_config(chat_models_config, model, configured_model)
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
_apply_skills_create_prompt(messages)
|
||||
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
|
||||
@@ -1646,7 +1672,7 @@ async def run_chat_task(
|
||||
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
|
||||
if regeneration_prompt:
|
||||
messages.append({"role": "user", "content": regeneration_prompt})
|
||||
tools = await get_tool_list()
|
||||
tools = await get_tool_list(builtin_tools=builtin_tools)
|
||||
|
||||
# Remove view_skill tool if no skills are available
|
||||
skills = discover_skills(workspace)
|
||||
@@ -1715,15 +1741,17 @@ async def run_chat_task(
|
||||
global_rp = {}
|
||||
model_rp = {}
|
||||
compact_token_threshold = None
|
||||
try:
|
||||
chat_models_config = await Config.get("chat.models") or {}
|
||||
global_rp = chat_models_config.get("*", {}).get("params", {}).get("request_params", {})
|
||||
model_rp = chat_models_config.get(model, {}).get("params", {}).get("request_params", {})
|
||||
compact_token_threshold = resolve_compact_token_threshold(
|
||||
configured_model, chat_models_config=chat_models_config
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
global_params = chat_models_config.get("*", {}).get("params", {})
|
||||
if not isinstance(global_params, dict):
|
||||
global_params = {}
|
||||
model_params = chat_models_config.get(model, {}).get("params", {})
|
||||
if not isinstance(model_params, dict):
|
||||
model_params = {}
|
||||
global_rp = global_params.get("request_params") or {}
|
||||
model_rp = model_params.get("request_params") or {}
|
||||
compact_token_threshold = resolve_compact_token_threshold(
|
||||
configured_model, chat_models_config=chat_models_config
|
||||
)
|
||||
compact_token_threshold = compact_token_threshold or resolve_compact_token_threshold()
|
||||
request_params = {**global_rp, **model_rp, **chat_request_params} or None
|
||||
|
||||
@@ -1941,6 +1969,7 @@ async def run_chat_task(
|
||||
"chat_id": chat_id,
|
||||
"message_id": message_id,
|
||||
"connection": connection,
|
||||
"builtin_tools": builtin_tools,
|
||||
}
|
||||
|
||||
# Check if any call needs approval
|
||||
|
||||
+58
-1
@@ -2330,6 +2330,57 @@ SUBAGENT_TOOLS: dict[str, dict] = {
|
||||
# Combined lookup for execution and approval (always available regardless of config)
|
||||
ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS, **SUBAGENT_TOOLS}
|
||||
|
||||
BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"files": (
|
||||
"read_file",
|
||||
"list_directory",
|
||||
"search_files",
|
||||
"create_file",
|
||||
"display_file",
|
||||
"edit_file",
|
||||
"multi_edit_file",
|
||||
"write_file",
|
||||
),
|
||||
"terminal": ("run_command", "send_input", "check_task", "kill_task"),
|
||||
"web": ("web_search", "read_url"),
|
||||
"browser": (
|
||||
"browser_navigate",
|
||||
"browser_snapshot",
|
||||
"browser_click",
|
||||
"browser_type",
|
||||
"browser_screenshot",
|
||||
"browser_evaluate",
|
||||
),
|
||||
"memory": ("update_memory",),
|
||||
"chats": ("search_chats",),
|
||||
"skills": ("view_skill", "manage_skill"),
|
||||
"automations": (
|
||||
"list_automations",
|
||||
"create_automation",
|
||||
"update_automation",
|
||||
"toggle_automation",
|
||||
"delete_automation",
|
||||
),
|
||||
"images": ("image_generate",),
|
||||
"subagents": ("delegate_task",),
|
||||
"notifications": ("notify",),
|
||||
}
|
||||
|
||||
|
||||
def disabled_builtin_tool_names(builtin_tools: dict | None) -> set[str]:
|
||||
"""Return builtin tool names disabled by group config."""
|
||||
if not isinstance(builtin_tools, dict):
|
||||
return set()
|
||||
disabled: set[str] = set()
|
||||
for group, enabled in builtin_tools.items():
|
||||
if enabled is False:
|
||||
disabled.update(BUILTIN_TOOL_GROUPS.get(group, ()))
|
||||
return disabled
|
||||
|
||||
|
||||
def is_builtin_tool_enabled(name: str, builtin_tools: dict | None) -> bool:
|
||||
return name not in disabled_builtin_tool_names(builtin_tools)
|
||||
|
||||
|
||||
# ── External tool servers ───────────────────────────────────
|
||||
|
||||
@@ -2633,7 +2684,7 @@ def _without_background_param(schema: dict) -> dict:
|
||||
return schema
|
||||
|
||||
|
||||
async def get_tool_list() -> list[dict]:
|
||||
async def get_tool_list(builtin_tools: dict | None = None) -> list[dict]:
|
||||
"""Return tool schemas for the LLM.
|
||||
|
||||
Automatically includes browser tools when browser.enabled is true,
|
||||
@@ -2668,6 +2719,10 @@ async def get_tool_list() -> list[dict]:
|
||||
tools.pop("image_generate", None)
|
||||
pass
|
||||
|
||||
disabled_tools = disabled_builtin_tool_names(builtin_tools)
|
||||
if disabled_tools:
|
||||
tools = {name: tool for name, tool in tools.items() if name not in disabled_tools}
|
||||
|
||||
schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]
|
||||
if not background_subagents_enabled:
|
||||
schemas = [_without_background_param(s) for s in schemas]
|
||||
@@ -2687,6 +2742,8 @@ async def execute_tool(name: str, args: dict, __context__: dict) -> str:
|
||||
"""Execute a tool by name, injecting execution context."""
|
||||
info = ALL_TOOLS.get(name)
|
||||
if info:
|
||||
if not is_builtin_tool_enabled(name, __context__.get("builtin_tools")):
|
||||
return f"Error: tool disabled: {name}"
|
||||
fn = info["fn"]
|
||||
try:
|
||||
sig = inspect.signature(fn)
|
||||
|
||||
Reference in new issue
Block a user