mirror of
https://github.com/open-webui/open-webui.git
synced 2026-12-05 08:49:12 +00:00
416 lines
16 KiB
Python
416 lines
16 KiB
Python
"""Workspace tools run in Monty instead of the server process (the tool sandbox is on with engine `monty`).
|
|
|
|
The source is read with `ast`, never run here: specs, Valves and UserValves come from the syntax tree.
|
|
Each call runs the source plus that one method call in a Monty worker, with JSON in and out.
|
|
"""
|
|
|
|
import ast
|
|
import asyncio
|
|
import inspect
|
|
import logging
|
|
import types
|
|
import uuid
|
|
from typing import Any, Literal, Optional, Union
|
|
|
|
from fastapi import HTTPException
|
|
from open_webui.env import (
|
|
AIOHTTP_CLIENT_ALLOW_REDIRECTS,
|
|
AIOHTTP_CLIENT_SESSION_SSL,
|
|
AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER,
|
|
)
|
|
from open_webui.models.config import Config
|
|
from open_webui.retrieval.web.utils import assert_identity_encoding, get_ssrf_safe_session, validate_url
|
|
from open_webui.utils.json_codec import JSONCodec
|
|
from open_webui.utils.plugin import extract_frontmatter
|
|
from pydantic import BaseModel, Field, create_model
|
|
from pydantic_monty import AsyncMonty, MontyError
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
TYPES = {
|
|
'str': str,
|
|
'int': int,
|
|
'float': float,
|
|
'bool': bool,
|
|
'bytes': bytes,
|
|
'dict': dict,
|
|
'Dict': dict,
|
|
'list': list,
|
|
'List': list,
|
|
'tuple': tuple,
|
|
'Tuple': tuple,
|
|
'set': set,
|
|
'Set': set,
|
|
'Any': Any,
|
|
'None': type(None),
|
|
}
|
|
GENERICS = {'dict', 'Dict', 'list', 'List', 'tuple', 'Tuple', 'set', 'Set'}
|
|
FACTORIES = {'list': list, 'dict': dict, 'set': set}
|
|
|
|
# Valves cannot be pydantic models in Monty (no inheritance, no nested classes), so the source gets these
|
|
# instead. They read the values the host validated.
|
|
PRELUDE = """
|
|
class _Valves:
|
|
def __init__(self, **values):
|
|
self._values = {**__valves__, **values}
|
|
for key, value in self._values.items():
|
|
setattr(self, key, value)
|
|
|
|
def model_dump(self):
|
|
return dict(self._values)
|
|
|
|
|
|
class _UserValves:
|
|
def __init__(self, **values):
|
|
self._values = {**__user_valves__, **values}
|
|
for key, value in self._values.items():
|
|
setattr(self, key, value)
|
|
|
|
def model_dump(self):
|
|
return dict(self._values)
|
|
|
|
"""
|
|
|
|
|
|
def _name(node) -> str | None:
|
|
"""`Optional` for both `Optional` and `typing.Optional`."""
|
|
if isinstance(node, ast.Attribute):
|
|
return node.attr
|
|
if isinstance(node, ast.Name):
|
|
return node.id
|
|
return None
|
|
|
|
|
|
def _annotation(node):
|
|
"""A real type for an annotation, without evaluating it. Anything unknown is Any."""
|
|
if node is None:
|
|
return inspect.Parameter.empty
|
|
if isinstance(node, ast.Constant):
|
|
if node.value is None:
|
|
return type(None)
|
|
if isinstance(node.value, str):
|
|
try:
|
|
return _annotation(ast.parse(node.value, mode='eval').body)
|
|
except SyntaxError:
|
|
return Any
|
|
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
|
|
return Union[_annotation(node.left), _annotation(node.right)]
|
|
if isinstance(node, ast.Subscript):
|
|
outer = _name(node.value)
|
|
args = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
if outer == 'Optional':
|
|
return Optional[_annotation(args[0])]
|
|
if outer == 'Union':
|
|
return Union[tuple(_annotation(arg) for arg in args)]
|
|
if outer == 'Literal':
|
|
try:
|
|
return Literal[tuple(ast.literal_eval(arg) for arg in args)]
|
|
except (ValueError, TypeError, SyntaxError):
|
|
return Any
|
|
if outer in GENERICS:
|
|
inner = [_annotation(arg) for arg in args if not isinstance(arg, ast.Constant) or arg.value is not ...]
|
|
return TYPES[outer][tuple(inner) if len(inner) > 1 else inner[0]] if inner else TYPES[outer]
|
|
return Any
|
|
return TYPES.get(_name(node), Any)
|
|
|
|
|
|
def _literal(node, where: str):
|
|
try:
|
|
return ast.literal_eval(node)
|
|
except (ValueError, TypeError, SyntaxError):
|
|
raise ValueError(f'{where} needs a literal value in the tool sandbox, not `{ast.unparse(node)}`') from None
|
|
|
|
|
|
def _is_field(node) -> bool:
|
|
return isinstance(node, ast.Call) and _name(node.func) == 'Field'
|
|
|
|
|
|
def _value(node, where: str):
|
|
"""A default: a literal, or `Field(...)` with literal arguments as a real pydantic Field."""
|
|
if not _is_field(node):
|
|
return _literal(node, where)
|
|
kwargs = {}
|
|
for keyword in node.keywords:
|
|
if keyword.arg == 'default_factory' and _name(keyword.value) in FACTORIES:
|
|
kwargs['default_factory'] = FACTORIES[_name(keyword.value)]
|
|
elif keyword.arg:
|
|
kwargs[keyword.arg] = _literal(keyword.value, where)
|
|
return Field(*(_literal(arg, where) for arg in node.args), **kwargs)
|
|
|
|
|
|
def _plain_default(node):
|
|
"""What Monty gets in place of a `Field(...)` default: the default itself."""
|
|
if not _is_field(node):
|
|
return node
|
|
keywords = {keyword.arg: keyword.value for keyword in node.keywords}
|
|
default = node.args[0] if node.args else keywords.get('default')
|
|
if default is None and 'default_factory' in keywords:
|
|
return ast.Call(func=keywords['default_factory'], args=[], keywords=[])
|
|
if default is None or (isinstance(default, ast.Constant) and default.value is ...):
|
|
return ast.Constant(None)
|
|
return default
|
|
|
|
|
|
def _model(node: ast.ClassDef) -> type[BaseModel]:
|
|
fields = {}
|
|
for statement in node.body:
|
|
if isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name):
|
|
name = statement.target.id
|
|
annotation = _annotation(statement.annotation)
|
|
default = _value(statement.value, f'{node.name}.{name}') if statement.value else ...
|
|
fields[name] = (Any if annotation is inspect.Parameter.empty else annotation, default)
|
|
return create_model(node.name, **fields)
|
|
|
|
|
|
def _signature(function: ast.AsyncFunctionDef) -> tuple[inspect.Signature, dict]:
|
|
"""The method's signature without `self`, as `inspect` would report it."""
|
|
arguments = function.args
|
|
positional = arguments.posonlyargs + arguments.args
|
|
defaults = [None] * (len(positional) - len(arguments.defaults)) + arguments.defaults
|
|
entries = [
|
|
(
|
|
argument,
|
|
inspect.Parameter.POSITIONAL_ONLY
|
|
if argument in arguments.posonlyargs
|
|
else inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
default,
|
|
)
|
|
for argument, default in list(zip(positional, defaults))[1:]
|
|
]
|
|
if arguments.vararg:
|
|
entries.append((arguments.vararg, inspect.Parameter.VAR_POSITIONAL, None))
|
|
entries += [
|
|
(argument, inspect.Parameter.KEYWORD_ONLY, default)
|
|
for argument, default in zip(arguments.kwonlyargs, arguments.kw_defaults)
|
|
]
|
|
if arguments.kwarg:
|
|
entries.append((arguments.kwarg, inspect.Parameter.VAR_KEYWORD, None))
|
|
|
|
parameters, annotations = [], {}
|
|
for argument, kind, default in entries:
|
|
annotation = _annotation(argument.annotation)
|
|
if annotation is not inspect.Parameter.empty:
|
|
annotations[argument.arg] = annotation
|
|
parameters.append(
|
|
inspect.Parameter(
|
|
argument.arg,
|
|
kind,
|
|
default=inspect.Parameter.empty
|
|
if default is None
|
|
else _value(default, f'{function.name}({argument.arg})'),
|
|
annotation=annotation,
|
|
)
|
|
)
|
|
returns = _annotation(function.returns)
|
|
if returns is not inspect.Parameter.empty:
|
|
annotations['return'] = returns
|
|
return inspect.Signature(parameters, return_annotation=returns), annotations
|
|
|
|
|
|
def _attributes(tools: ast.ClassDef) -> dict:
|
|
"""Literal `citation`, `file_handler` and whether `valves` is set, from the class body or `__init__`."""
|
|
found = {}
|
|
assignments = [statement for statement in tools.body if isinstance(statement, ast.Assign)]
|
|
init = next((s for s in tools.body if isinstance(s, ast.FunctionDef) and s.name == '__init__'), None)
|
|
if init:
|
|
assignments += [statement for statement in ast.walk(init) if isinstance(statement, ast.Assign)]
|
|
for statement in assignments:
|
|
for target in statement.targets:
|
|
name = target.id if isinstance(target, ast.Name) else None
|
|
if isinstance(target, ast.Attribute) and _name(target.value) == 'self':
|
|
name = target.attr
|
|
if name == 'valves':
|
|
found['valves'] = None
|
|
elif name in ('citation', 'file_handler'):
|
|
try:
|
|
found[name] = ast.literal_eval(statement.value)
|
|
except (ValueError, TypeError, SyntaxError):
|
|
pass
|
|
return found
|
|
|
|
|
|
def _jsonable(value):
|
|
"""Values cross into the sandbox as JSON."""
|
|
return JSONCodec.loads(
|
|
JSONCodec.dumps(value, default=lambda o: o.model_dump() if isinstance(o, BaseModel) else str(o))
|
|
)
|
|
|
|
|
|
def _host(function):
|
|
"""An event emitter or caller as a Monty host function."""
|
|
|
|
async def host(data):
|
|
return _jsonable(await function(data))
|
|
|
|
return host
|
|
|
|
|
|
def _defaults(model) -> dict:
|
|
if model is None:
|
|
return {}
|
|
return {
|
|
key: field.get_default(call_default_factory=True)
|
|
for key, field in model.model_fields.items()
|
|
if not field.is_required()
|
|
}
|
|
|
|
|
|
def _method(call, node: ast.AsyncFunctionDef):
|
|
"""A host-side method with the real signature and docstring, so specs and extra params work unchanged."""
|
|
signature, annotations = _signature(node)
|
|
|
|
async def method(**kwargs):
|
|
return await call(node.name, kwargs)
|
|
|
|
method.__name__ = method.__qualname__ = node.name
|
|
method.__doc__ = ast.get_docstring(node)
|
|
method.__signature__ = signature
|
|
method.__annotations__ = annotations
|
|
return method
|
|
|
|
|
|
async def _run(tool_id: str, code: str, inputs: dict, hosts: dict):
|
|
timeout = float(AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER) if AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER else None
|
|
|
|
def print_line(_stream, text):
|
|
# Where `print` in a tool went before: the server log.
|
|
if text.strip():
|
|
log.info(f'Tool {tool_id}: {text.rstrip()}')
|
|
|
|
try:
|
|
async with AsyncMonty() as pool:
|
|
async with pool.checkout(limits={'max_feed_duration_secs': timeout}) as session:
|
|
return await session.feed_run(
|
|
code,
|
|
inputs=inputs,
|
|
external_lookup={'http_request': http_request, **hosts},
|
|
print_callback=print_line,
|
|
)
|
|
except MontyError as e:
|
|
raise RuntimeError(str(e)) from None
|
|
|
|
|
|
async def http_request(
|
|
method: str,
|
|
url: str,
|
|
params: dict | None = None,
|
|
headers: dict | None = None,
|
|
json: Any = None,
|
|
data: Any = None,
|
|
) -> dict:
|
|
"""The sandbox's only way to the network, checked like web fetch (WEB_FETCH_FILTER_LIST, ENABLE_LOCAL_WEB_FETCH)."""
|
|
await asyncio.to_thread(validate_url, url)
|
|
try:
|
|
max_size_mb = int(await Config.get('rag.file.max_size') or 0)
|
|
except (TypeError, ValueError):
|
|
max_size_mb = 0
|
|
# Fetch through an SSRF-safe session that re-checks the connect-time IP, so a
|
|
# rebinding DNS answer that passed validate_url cannot reach an internal address.
|
|
async with get_ssrf_safe_session() as session:
|
|
async with session.request(
|
|
method,
|
|
url,
|
|
params=params,
|
|
headers={**(headers or {}), 'Accept-Encoding': 'identity'},
|
|
json=json,
|
|
data=data,
|
|
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
|
allow_redirects=AIOHTTP_CLIENT_ALLOW_REDIRECTS,
|
|
) as response:
|
|
assert_identity_encoding(response.headers.getall('Content-Encoding', ()))
|
|
body = bytearray()
|
|
async for chunk in response.content.iter_chunked(64 * 1024):
|
|
body.extend(chunk)
|
|
if max_size_mb and len(body) > max_size_mb * 1024 * 1024:
|
|
raise ValueError(f'Response is larger than {max_size_mb} MB')
|
|
text = body.decode(response.charset or 'utf-8', errors='replace')
|
|
try:
|
|
parsed = JSONCodec.loads(text)
|
|
except ValueError:
|
|
parsed = None
|
|
return {'status': response.status, 'headers': dict(response.headers), 'text': text, 'json': parsed}
|
|
|
|
|
|
async def load_sandboxed_tool(tool_id: str, content: str):
|
|
"""The same (tool, frontmatter, module) as `load_tool_module_by_id`, without running the source here."""
|
|
frontmatter = extract_frontmatter(content)
|
|
if frontmatter.get('requirements'):
|
|
raise ValueError('The tool sandbox cannot install packages; remove `requirements` from the frontmatter.')
|
|
|
|
tree = ast.parse(content)
|
|
tools = next((n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Tools'), None)
|
|
if tools is None:
|
|
raise Exception('No Tools class found in the module')
|
|
|
|
nested = {n.name: n for n in tools.body if isinstance(n, ast.ClassDef) and n.name in ('Valves', 'UserValves')}
|
|
public = [
|
|
n for n in tools.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and not n.name.startswith('_')
|
|
]
|
|
sync_names = [n.name for n in public if isinstance(n, ast.FunctionDef)]
|
|
if sync_names:
|
|
raise HTTPException(400, f'Methods must be defined with async def: {", ".join(sync_names)}')
|
|
|
|
models = {name: _model(node) for name, node in nested.items()}
|
|
Valves, UserValves = models.get('Valves'), models.get('UserValves')
|
|
tool = types.SimpleNamespace(**_attributes(tools), **models)
|
|
|
|
# The source Monty runs: no pydantic, no nested Valves classes, plain defaults.
|
|
tree.body = [
|
|
n
|
|
for n in tree.body
|
|
if not (isinstance(n, ast.ImportFrom) and (n.module or '').split('.')[0] == 'pydantic')
|
|
and not (isinstance(n, ast.Import) and all(a.name.split('.')[0] == 'pydantic' for a in n.names))
|
|
]
|
|
tools.body = [n for n in tools.body if n not in nested.values()] or [ast.Pass()]
|
|
for function in tools.body:
|
|
if isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
function.args.defaults = [_plain_default(d) for d in function.args.defaults]
|
|
function.args.kw_defaults = [d and _plain_default(d) for d in function.args.kw_defaults]
|
|
source = PRELUDE + ast.unparse(ast.fix_missing_locations(tree)) + '\n'
|
|
source += ''.join(f'Tools.{name} = _{name}\n' for name in nested)
|
|
|
|
async def call(name: str, kwargs: dict):
|
|
hosts, arguments = {}, {}
|
|
for key, value in kwargs.items():
|
|
if key in ('__event_emitter__', '__event_call__'):
|
|
if value is not None:
|
|
hosts[key] = _host(value)
|
|
elif key != '__request__' and not callable(value):
|
|
arguments[key] = value
|
|
arguments = _jsonable(arguments)
|
|
|
|
valves = getattr(tool, 'valves', None)
|
|
user_valves = (arguments.get('__user__') or {}).get('valves')
|
|
code = source + '__tool__ = Tools()\n'
|
|
if 'UserValves' in nested and isinstance(user_valves, dict):
|
|
code += '__arguments__["__user__"]["valves"] = _UserValves()\n'
|
|
code += f'return await __tool__.{name}(**__arguments__{"".join(f", {k}={k}" for k in hosts)})\n'
|
|
return await _run(
|
|
tool_id,
|
|
code,
|
|
{
|
|
'__valves__': valves.model_dump() if isinstance(valves, BaseModel) else _defaults(Valves),
|
|
'__user_valves__': user_valves if isinstance(user_valves, dict) else _defaults(UserValves),
|
|
'__arguments__': arguments,
|
|
},
|
|
hosts,
|
|
)
|
|
|
|
for node in public:
|
|
setattr(tool, node.name, _method(call, node))
|
|
|
|
# Fail the save on what Monty cannot run (imports, syntax, a failing __init__), not on the first call.
|
|
await _run(
|
|
tool_id,
|
|
source + 'Tools()\n',
|
|
{
|
|
'__valves__': _defaults(Valves),
|
|
'__user_valves__': _defaults(UserValves),
|
|
'__arguments__': {},
|
|
},
|
|
{},
|
|
)
|
|
|
|
log.info('Loaded sandboxed tool: %s', tool_id)
|
|
return tool, frontmatter, types.ModuleType(f'tool_{tool_id}_{uuid.uuid4().hex}')
|