chore: format

This commit is contained in:
Timothy Jaeryang Baek
2026-07-20 22:11:42 -04:00
parent 4a42543fc3
commit 49e57f4e7e
16 changed files with 44 additions and 60 deletions
+4 -6
View File
@@ -1402,9 +1402,9 @@ async def chat_completion(
'content_preview': user_message.get('content', '')[:300],
},
)
if not getattr(request.state, 'internal', False) and not (
user_message.get('meta') or {}
).get('internal'):
if not getattr(request.state, 'internal', False) and not (user_message.get('meta') or {}).get(
'internal'
):
try:
from open_webui.utils.timers import cancel_timers_for_chat
@@ -1815,9 +1815,7 @@ async def generate_messages(
},
)
elif isinstance(response, dict):
return convert_openai_to_anthropic_response(
response, model=requested_model, input_tokens=input_tokens
)
return convert_openai_to_anthropic_response(response, model=requested_model, input_tokens=input_tokens)
else:
# Passthrough for error responses (JSONResponse, PlainTextResponse, etc.)
return response
+8 -4
View File
@@ -1593,12 +1593,14 @@ class ChatTable:
# Check if there are any tags to filter
if 'none' in tag_ids:
stmt = stmt.filter(text("""
stmt = stmt.filter(
text("""
NOT EXISTS (
SELECT 1
FROM json_each(Chat.meta, '$.tags') AS tag
)
"""))
""")
)
elif tag_ids:
stmt = stmt.filter(
and_(
@@ -1641,12 +1643,14 @@ class ChatTable:
).params(title_key=f'%{search_text}%', content_key=search_text.lower())
if 'none' in tag_ids:
stmt = stmt.filter(text("""
stmt = stmt.filter(
text("""
NOT EXISTS (
SELECT 1
FROM json_array_elements_text(Chat.meta->'tags') AS tag
)
"""))
""")
)
elif tag_ids:
stmt = stmt.filter(
and_(
+1 -3
View File
@@ -1340,9 +1340,7 @@ async def get_sources_from_items(
folder = await Folders.get_folder_by_id(folder_id)
if folder and (user.role == 'admin' or await has_folder_access(user.id, folder, 'read', db=None)):
files = (folder.data or {}).get('files', [])
folder_items.update(
(entry.get('type'), entry.get('id')) for entry in files if isinstance(entry, dict)
)
folder_items.update((entry.get('type'), entry.get('id')) for entry in files if isinstance(entry, dict))
items.extend(files)
for item in items:
@@ -156,9 +156,7 @@ class MilvusClient(VectorDBBase):
except MilvusException as e:
# The index only accelerates resource_id filters; never fail
# collection creation over it.
log.warning(
f'Could not create {RESOURCE_ID_FIELD} index on {mt_collection_name}: {e}'
)
log.warning(f'Could not create {RESOURCE_ID_FIELD} index on {mt_collection_name}: {e}')
log.info(f'Created shared collection: {mt_collection_name}')
return collection
+1 -3
View File
@@ -203,9 +203,7 @@ async def process_uploaded_file(
else:
# Keep the generic file status stream open until the
# KB-specific vector write and durable link both finish.
await Files.update_file_data_by_id(
file_item.id, {'status': 'processing'}, db=db_session
)
await Files.update_file_data_by_id(file_item.id, {'status': 'processing'}, db=db_session)
await process_file(
request,
ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id),
+1 -3
View File
@@ -582,9 +582,7 @@ async def update_note_by_id(
event_data = note.model_dump()
if form_data.data is not None:
event_data['data'] = {
key: note.data.get(key)
for key in form_data.data.keys()
if note.data is not None and key in note.data
key: note.data.get(key) for key in form_data.data.keys() if note.data is not None and key in note.data
}
await sio.emit(
@@ -254,8 +254,7 @@ async def filter_allowed_access_grants(
access_grants = strip_user_access_grants(access_grants)
if any(
(grant.get('principal_type') if isinstance(grant, dict) else getattr(grant, 'principal_type', None))
== 'group'
(grant.get('principal_type') if isinstance(grant, dict) else getattr(grant, 'principal_type', None)) == 'group'
for grant in access_grants
) and not await has_permission(
user_id,
+2 -6
View File
@@ -467,9 +467,7 @@ def convert_openai_to_anthropic_response(
}
async def openai_stream_to_anthropic_stream(
openai_stream_generator, model: str = '', input_tokens: int = 0
):
async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str = '', input_tokens: int = 0):
"""
Convert an OpenAI SSE streaming response to Anthropic Messages SSE format.
@@ -560,9 +558,7 @@ async def openai_stream_to_anthropic_stream(
# Update usage if present
if data.get('usage'):
input_tokens = data['usage'].get(
'input_tokens', data['usage'].get('prompt_tokens', input_tokens)
)
input_tokens = data['usage'].get('input_tokens', data['usage'].get('prompt_tokens', input_tokens))
output_tokens = data['usage'].get(
'output_tokens', data['usage'].get('completion_tokens', output_tokens)
)
@@ -240,9 +240,7 @@ async def get_chat_context_usage(chat: Any, model_id: str | None = None) -> dict
usage = messages[idx].get('usage') or (messages[idx].get('info') or {}).get('usage')
input_tokens = (usage or {}).get('input_tokens') or (usage or {}).get('prompt_tokens')
if isinstance(usage, dict) and input_tokens:
tokens = int(input_tokens or 0) + int(
usage.get('output_tokens') or usage.get('completion_tokens') or 0
)
tokens = int(input_tokens or 0) + int(usage.get('output_tokens') or usage.get('completion_tokens') or 0)
tokens += _estimate_messages_tokens(messages[idx + 1 :])
return _build_context_usage(tokens, threshold)
+4 -9
View File
@@ -110,10 +110,7 @@ async def process_pending_internal_messages(
and meta.get('type') == 'subagent'
and meta.get('status') in (None, 'pending')
)
or (
meta.get('internal') is True
and meta.get('type') == 'timer'
)
or (meta.get('internal') is True and meta.get('type') == 'timer')
)
]
if not pending:
@@ -137,11 +134,9 @@ async def process_pending_internal_messages(
if message.get('parentId') == parent_id
and (message.get('model') or model_id) == model_id
and (
(
meta.get('internal') is True
and meta.get('type') == 'subagent'
and meta.get('status') in (None, 'pending')
)
meta.get('internal') is True
and meta.get('type') == 'subagent'
and meta.get('status') in (None, 'pending')
)
]
combined_content = '\n\n'.join(message.get('content', '') for message in batch if message.get('content'))
+5 -11
View File
@@ -25,8 +25,8 @@ from open_webui.utils.misc import get_message_list
log = logging.getLogger(__name__)
_RELATIVE_TIME = re.compile(r"^(?:\+|in\s+)?(\d+)\s*(s|sec(?:onds?)?|m|min(?:utes?)?|h|hours?|d|days?)$")
_RFC3339_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
_RELATIVE_TIME = re.compile(r'^(?:\+|in\s+)?(\d+)\s*(s|sec(?:onds?)?|m|min(?:utes?)?|h|hours?|d|days?)$')
_RFC3339_TIME = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$')
_TIME_UNITS_NS = {
's': 1_000_000_000,
'm': 60 * 1_000_000_000,
@@ -49,15 +49,13 @@ def parse_timer_at(value: str) -> int:
if not _RFC3339_TIME.fullmatch(raw):
raise ValueError(
'at must be a relative time such as 10s or in 10 seconds, '
'or an RFC 3339 timestamp with a timezone.'
'at must be a relative time such as 10s or in 10 seconds, or an RFC 3339 timestamp with a timezone.'
)
try:
parsed = datetime.fromisoformat(raw.replace('Z', '+00:00'))
except ValueError as exc:
raise ValueError(
'at must be a relative time such as 10s or in 10 seconds, '
'or an RFC 3339 timestamp with a timezone.'
'at must be a relative time such as 10s or in 10 seconds, or an RFC 3339 timestamp with a timezone.'
) from exc
if parsed.tzinfo is None or parsed.utcoffset() is None:
raise ValueError('absolute at values must include an explicit timezone.')
@@ -182,11 +180,7 @@ async def claim_due_timers(now_ns: int, limit: int = 10) -> list[tuple[str, str]
stmt = stmt.with_for_update(skip_locked=True)
result = await db.execute(stmt)
rows = [
row
for row in result.scalars().all()
if int((row.meta or {}).get('timer_at') or 0) <= now_ns
]
rows = [row for row in result.scalars().all() if int((row.meta or {}).get('timer_at') or 0) <= now_ns]
rows.sort(key=lambda row: int((row.meta or {}).get('timer_at') or 0))
rows = rows[:limit]
+3 -1
View File
@@ -401,7 +401,9 @@ export const getOrchestratorLifecycle = async (
});
if (!res.ok) {
const body = await res.json();
throw Object.assign(new Error(body.detail || 'Failed to read lifecycle'), { status: res.status });
throw Object.assign(new Error(body.detail || 'Failed to read lifecycle'), {
status: res.status
});
}
return res.json();
};
@@ -83,7 +83,7 @@
{/if}
<div
class=" mt-2 mb-4 text-3xl text-gray-800 dark:text-gray-100 text-left flex items-center gap-4 "
class=" mt-2 mb-4 text-3xl text-gray-800 dark:text-gray-100 text-left flex items-center gap-4"
>
<div>
<div class=" capitalize line-clamp-1" in:fade={{ duration: 200 }}>
@@ -132,7 +132,7 @@
</div>
</div>
<div class=" w-full " in:fade={{ duration: 200, delay: 300 }}>
<div class=" w-full" in:fade={{ duration: 200, delay: 300 }}>
<Suggestions
className="grid grid-cols-2"
suggestionPrompts={atSelectedModel?.info?.meta?.suggestion_prompts ??
+3 -1
View File
@@ -477,7 +477,9 @@
$: contextPercent = contextHasThreshold
? Math.max(0, Math.round(statusContextUsage?.percent ?? 0))
: null;
$: contextTokens = formatTokenCount(statusContextUsage?.estimated_tokens || statusContextUsage?.tokens || 0);
$: contextTokens = formatTokenCount(
statusContextUsage?.estimated_tokens || statusContextUsage?.tokens || 0
);
$: contextValue = statusContextUsage
? contextHasThreshold
? `${contextPercent}% ${contextTokens}/${formatTokenCount(statusContextUsage.threshold)}`
+6 -2
View File
@@ -154,8 +154,12 @@
}
const availableHeight = Math.max(0, openAbove ? spaceAbove : spaceBelow);
const constrainedHeight = contentHeight ? Math.min(contentHeight, availableHeight) : contentHeight;
const preferredTop = openAbove ? rect.top - constrainedHeight - sideOffset : rect.bottom + sideOffset;
const constrainedHeight = contentHeight
? Math.min(contentHeight, availableHeight)
: contentHeight;
const preferredTop = openAbove
? rect.top - constrainedHeight - sideOffset
: rect.bottom + sideOffset;
const contentWidth = contentEl.offsetWidth || 0;
const preferredLeft = align === 'end' && contentWidth ? rect.right - contentWidth : rect.left;
const maxLeft = contentWidth ? viewportRight - contentWidth - pad : preferredLeft;
+1 -1
View File
@@ -236,7 +236,7 @@
{#if loaded}
<div
class="fixed bg-transparent min-h-screen w-full flex justify-center z-50 text-black dark:text-white"
class="fixed bg-transparent min-h-screen w-full flex justify-center z-50 text-black dark:text-white"
id="auth-container"
>
<div class="w-full px-10 min-h-screen flex flex-col text-center">