mirror of
https://github.com/open-webui/open-webui.git
synced 2026-12-03 18:17:56 -05:00
refac
This commit is contained in:
1 parent
a058de949f
commit
90bdabcb35
2 files changed
+34
-16
No files matched your search
@@ -921,15 +921,18 @@ async def run_program(
|
||||
) -> str:
|
||||
"""
|
||||
Run a short Python program that calls your other tools, and return what it prints.
|
||||
Prefer this over calling tools one at a time when a task needs several tool calls, or a tool may return
|
||||
more than you need: loop over items, run independent calls together with asyncio.gather, filter and
|
||||
aggregate, then print only what you need. Tool results stay inside the program; only its printed output
|
||||
and return value come back. Call a tool directly when one call is enough.
|
||||
Call a tool with `await call_tool("tool_name", {...})`, using the exact name and arguments from your tool list.
|
||||
It returns the tool's result, decoded from JSON when possible, in the same shape as a direct call.
|
||||
The sandbox runs a subset of Python with no packages, files or network; json, re, datetime, math,
|
||||
statistics, collections, itertools and asyncio.gather are available. For data analysis with packages,
|
||||
use execute_code instead.
|
||||
Use it when the work needs many tool calls whose raw results you only need a summary of: scan, count,
|
||||
filter or rank across many items. For one or a few calls, or when you need to read the content yourself,
|
||||
call the tools directly.
|
||||
Call a tool with its exact name and arguments from your tool list, for example
|
||||
`await tools["search_chats"](query="docker")`, and run independent calls together with
|
||||
`await asyncio.gather(...)` (no keyword arguments). A result that is a JSON object or array arrives decoded;
|
||||
any other result arrives as one string.
|
||||
Do the work in the program and print only the computed answer (counts, the matching items, the top
|
||||
entries), never whole tool results: only what the program prints or returns comes back to you.
|
||||
asyncio, json, re, math, collections, itertools and datetime are already imported. No other modules,
|
||||
files or network, so all data comes through tools. At most 1000 tool calls per program.
|
||||
If a program fails, fix it and run it again. For data analysis with packages, use execute_code instead.
|
||||
|
||||
:param code: Python source. Top-level await and return are allowed.
|
||||
:return: JSON with stdout, stderr, and the program's return value
|
||||
@@ -941,13 +944,18 @@ async def run_program(
|
||||
from open_webui.utils.middleware import execute_tool_call, process_tool_result
|
||||
from open_webui.utils.tool_permissions import ToolApprovalRequired
|
||||
|
||||
callable_names = [
|
||||
name
|
||||
for name, tool in __metadata__['tools'].items()
|
||||
if name not in ('run_program', 'ask_user') and 'callable' in tool
|
||||
]
|
||||
|
||||
async def call_tool(name: str, arguments: dict | None = None):
|
||||
# OpenAI models address their tools as `functions.<name>`; tool names cannot contain dots.
|
||||
name = name.removeprefix('functions.')
|
||||
tool = __metadata__['tools'].get(name)
|
||||
if not tool:
|
||||
if name not in __metadata__['tools']:
|
||||
return f'Error: No tool named "{name}". Use the exact name from your tool list.'
|
||||
if name in ('run_program', 'ask_user') or 'callable' not in tool:
|
||||
if name not in callable_names:
|
||||
return f'Error: Tool "{name}" cannot be called from a program.'
|
||||
tool_call = {'call_id': f'call_{uuid4().hex[:24]}', 'name': name, 'arguments': JSONCodec.dumps(arguments or {})}
|
||||
try:
|
||||
@@ -957,12 +965,20 @@ async def run_program(
|
||||
except ToolApprovalRequired:
|
||||
return f'Error: {name} needs approval. Call it directly, not from a program.'
|
||||
result, _, _ = await process_tool_result(
|
||||
__request__, name, result, tool_type, __metadata__, UserModel(**__user__)
|
||||
__request__, name, result, tool_type, __metadata__, UserModel(**__user__), truncate=False
|
||||
)
|
||||
try:
|
||||
return JSONCodec.loads(result)
|
||||
decoded = JSONCodec.loads(result)
|
||||
except (JSONCodec.JSONDecodeError, TypeError):
|
||||
return result
|
||||
# Text that happens to be valid JSON, like a file holding `1`, stays text.
|
||||
return decoded if isinstance(decoded, (dict, list)) else result
|
||||
|
||||
# On its own line: a program may start with `def` or `for`, which cannot follow `;`.
|
||||
prelude = (
|
||||
'import asyncio, json, re, math, collections, itertools, datetime\n'
|
||||
f'tools = {{n: (lambda n: lambda **kw: call_tool(n, kw))(n) for n in {callable_names!r}}}\n'
|
||||
)
|
||||
|
||||
output = {'stdout': [], 'stderr': []}
|
||||
result = None
|
||||
@@ -972,7 +988,7 @@ async def run_program(
|
||||
limits={'max_feed_duration_secs': float(await Config.get('chat.programmatic_tool_calling.timeout'))}
|
||||
) as session:
|
||||
result = await session.feed_run(
|
||||
code,
|
||||
prelude + code,
|
||||
external_lookup={'call_tool': call_tool},
|
||||
print_callback=lambda stream, text: output[stream].append(text),
|
||||
)
|
||||
|
||||
@@ -962,6 +962,7 @@ async def process_tool_result(
|
||||
tool_type,
|
||||
metadata=None,
|
||||
user=None,
|
||||
truncate=True,
|
||||
):
|
||||
tool_result_embeds = []
|
||||
if isinstance(tool_result, MCPAppResult):
|
||||
@@ -1170,7 +1171,8 @@ async def process_tool_result(
|
||||
else:
|
||||
tool_result = str(tool_result)
|
||||
|
||||
max_chars = await Config.get('tools.output_max_chars')
|
||||
# truncate=False for results that stay inside a program and never reach the context.
|
||||
max_chars = await Config.get('tools.output_max_chars') if truncate else None
|
||||
if max_chars and tool_result and len(tool_result) > max_chars:
|
||||
note = f'Truncated: {len(tool_result)} characters, limit {max_chars}'
|
||||
# Machine tools read the saved file, so saving their results would only copy it again.
|
||||
|
||||
Reference in new issue
Block a user