mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-28 16:11:43 -05:00
refac
This commit is contained in:
1 parent
a2e2680912
commit
429eeba594
5 files changed
+83
-23
No files matched your search
@@ -1115,7 +1115,12 @@ async def chat_completion(
|
||||
if isinstance(model_id, str) and model_id.startswith('agent:'):
|
||||
from open_webui.utils.agents.discovery import get_models as get_agent_models
|
||||
|
||||
candidates = await get_agent_models(request, user, form_data.get('terminal_id'), form_data.get('chat_id'))
|
||||
parts = model_id.split(':', 3)
|
||||
if len(parts) != 4:
|
||||
raise HTTPException(400, 'Invalid agent model')
|
||||
candidates = await get_agent_models(
|
||||
request, user, form_data.get('terminal_id'), form_data.get('chat_id'), provider=parts[2]
|
||||
)
|
||||
agent_model = next((item for item in candidates if item['id'] == model_id), None)
|
||||
if agent_model is None:
|
||||
raise HTTPException(400, 'Agent model is unavailable in the selected terminal')
|
||||
@@ -1645,6 +1650,8 @@ async def chat_completion(
|
||||
else await Models.get_model_by_id(form_data['model'])
|
||||
)
|
||||
controls = target.params.model_dump().get('model_controls', {}) if target else {}
|
||||
if model.get('agent'):
|
||||
controls = model.get('info', {}).get('params', {}).get('model_controls', {})
|
||||
form_data['params'] = apply_model_controls(
|
||||
copy.deepcopy(form_data.get('params') or {}),
|
||||
controls,
|
||||
|
||||
@@ -81,11 +81,22 @@ async def run(transport, output, prompt, images, options):
|
||||
thread_id = result['thread']['id']
|
||||
output.state['session_id'] = thread_id
|
||||
await output.flush(force=True)
|
||||
turn_options = {}
|
||||
chat_params = options.get('params') or {}
|
||||
chat_params = {**chat_params, **(chat_params.get('custom_params') or {})}
|
||||
for field, aliases in {
|
||||
'effort': ('reasoningEffort', 'reasoning_effort'),
|
||||
'serviceTier': ('serviceTier', 'service_tier'),
|
||||
}.items():
|
||||
value = next((chat_params.get(key) for key in aliases if chat_params.get(key)), None)
|
||||
if isinstance(value, str) and value.strip():
|
||||
turn_options[field] = value.strip()
|
||||
result = await client.request(
|
||||
'turn/start',
|
||||
{
|
||||
'threadId': thread_id,
|
||||
'input': [{'type': 'text', 'text': prompt}, *[{'type': 'image', 'url': image} for image in images]],
|
||||
**turn_options,
|
||||
},
|
||||
)
|
||||
turn_id = result['turn']['id']
|
||||
|
||||
@@ -5,14 +5,35 @@ from urllib.parse import quote, urlencode
|
||||
from open_webui.utils.terminals import get_terminal_json
|
||||
|
||||
|
||||
async def get_models(request, user, terminal_id, chat_id=None):
|
||||
def model_controls(model):
|
||||
controls = {}
|
||||
for key, label, values, value_key, label_key, default_key in (
|
||||
('reasoning_effort', 'Reasoning effort', 'supportedReasoningEfforts', 'reasoningEffort', 'reasoningEffort', 'defaultReasoningEffort'),
|
||||
('service_tier', 'Service tier', 'serviceTiers', 'id', 'name', 'defaultServiceTier'),
|
||||
):
|
||||
options = {
|
||||
option[value_key]: {
|
||||
'label': option.get(label_key) or option[value_key],
|
||||
'params': {key: option[value_key]},
|
||||
}
|
||||
for option in model.get(values, [])
|
||||
}
|
||||
if options:
|
||||
controls[key] = {'label': label, 'options': options}
|
||||
if model.get(default_key) in options:
|
||||
controls[key]['default'] = model[default_key]
|
||||
return controls
|
||||
|
||||
|
||||
async def get_models(request, user, terminal_id, chat_id=None, *, provider=None):
|
||||
if not terminal_id:
|
||||
return []
|
||||
metadata = {'terminal_id': terminal_id, 'chat_id': chat_id}
|
||||
cwd = await get_terminal_json(request, user, metadata, '/files/cwd')
|
||||
path = '/agents'
|
||||
params = {'provider': provider} if provider else {}
|
||||
if cwd and cwd.get('cwd'):
|
||||
path += '?' + urlencode({'cwd': cwd['cwd']})
|
||||
params['cwd'] = cwd['cwd']
|
||||
path = '/agents' + ('?' + urlencode(params) if params else '')
|
||||
catalog = await get_terminal_json(request, user, metadata, path)
|
||||
if not catalog or catalog.get('protocol_version') != 1:
|
||||
return []
|
||||
@@ -24,6 +45,7 @@ async def get_models(request, user, terminal_id, chat_id=None):
|
||||
'object': 'model',
|
||||
'agent': {'terminal_id': terminal_id, 'provider': agent['id'], 'model': model['id']},
|
||||
'info': {
|
||||
'params': {'model_controls': model_controls(model)},
|
||||
'meta': {
|
||||
'capabilities': {
|
||||
'vision': True,
|
||||
|
||||
@@ -23,11 +23,39 @@ class Output:
|
||||
self.usage = None
|
||||
self.emitter = None
|
||||
self.last_flush = 0
|
||||
self.last_save = 0
|
||||
self.save_task = None
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
async def flush(self, done=False, force=False):
|
||||
if not force and not done and time.monotonic() - self.last_flush < 0.1:
|
||||
async def flush(self, done=False, force=False, persist=False):
|
||||
if self.save_task and self.save_task.done():
|
||||
self.save_task.result()
|
||||
if not force and not done and time.monotonic() - self.last_flush < 0.05:
|
||||
return
|
||||
if persist or done:
|
||||
# Approval cards must exist in the DB before users can answer them.
|
||||
if self.save_task:
|
||||
await asyncio.shield(self.save_task)
|
||||
await self.save(done=done)
|
||||
if self.emitter is None:
|
||||
self.emitter = await get_event_emitter(self.metadata, update_db=False)
|
||||
await self.emitter(
|
||||
{
|
||||
'type': 'chat:completion',
|
||||
'data': {
|
||||
'content': self.content,
|
||||
'output': copy.deepcopy(self.items),
|
||||
'done': done,
|
||||
'usage': self.usage,
|
||||
},
|
||||
}
|
||||
)
|
||||
self.last_flush = time.monotonic()
|
||||
if not (persist or done) and time.monotonic() - self.last_save >= 1:
|
||||
if self.save_task is None or self.save_task.done():
|
||||
self.save_task = asyncio.create_task(self.save())
|
||||
|
||||
async def save(self, done=False):
|
||||
async with self.lock:
|
||||
async with Chats.edit_message_output(self.metadata['chat_id'], self.metadata['message_id']) as message:
|
||||
if message is None:
|
||||
@@ -51,20 +79,7 @@ class Output:
|
||||
if done:
|
||||
meta['response_ended_at'] = time.time()
|
||||
message['meta'] = meta
|
||||
if self.emitter is None:
|
||||
self.emitter = await get_event_emitter(self.metadata, update_db=False)
|
||||
await self.emitter(
|
||||
{
|
||||
'type': 'chat:completion',
|
||||
'data': {
|
||||
'content': self.content,
|
||||
'output': copy.deepcopy(self.items),
|
||||
'done': done,
|
||||
'usage': self.usage,
|
||||
},
|
||||
}
|
||||
)
|
||||
self.last_flush = time.monotonic()
|
||||
self.last_save = time.monotonic()
|
||||
|
||||
async def text(self, text, reasoning=False):
|
||||
kind = 'reasoning' if reasoning else 'message'
|
||||
@@ -122,7 +137,7 @@ class Output:
|
||||
'native': native,
|
||||
}
|
||||
self.items.append(item)
|
||||
await self.flush(force=True)
|
||||
await self.flush(force=True, persist=True)
|
||||
deadline = time.monotonic() + timeout if timeout is not None else None
|
||||
# Persisted resolutions work across workers and survive browser refreshes.
|
||||
while True:
|
||||
@@ -148,6 +163,6 @@ class Output:
|
||||
'status': 'completed',
|
||||
}
|
||||
)
|
||||
await self.flush(force=True)
|
||||
await self.flush(force=True, persist=True)
|
||||
return resolution
|
||||
await asyncio.sleep(0.5)
|
||||
@@ -106,7 +106,12 @@ async def run(request, form_data, user, metadata, model):
|
||||
await transport.start(agent['provider'], options)
|
||||
extra = {'auth_method': 'cursor_login'} if agent['provider'] == 'cursor' else {}
|
||||
await PROVIDERS[agent['provider']](
|
||||
transport, output, prompt, images, {**options, 'resume_state': previous or {}}, **extra
|
||||
transport,
|
||||
output,
|
||||
prompt,
|
||||
images,
|
||||
{**options, 'resume_state': previous or {}, 'params': form_data.get('params') or {}},
|
||||
**extra,
|
||||
)
|
||||
succeeded = True
|
||||
finally:
|
||||
|
||||
Reference in new issue
Block a user