Skip to content

Commit 5dae600

Browse files
committed
chore: format
1 parent f1be85d commit 5dae600

81 files changed

Lines changed: 247 additions & 140 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

backend/open_webui/constants.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,7 @@ def __str__(self) -> str:
9292
INVALID_PASSWORD = lambda err='': err if err else 'The password does not meet the required validation criteria.'
9393

9494
AUTOMATION_LIMIT_EXCEEDED = lambda size='': f'Automation limit reached ({size})'
95-
AUTOMATION_TOO_FREQUENT = (
96-
lambda interval='': f'Schedule too frequent. Minimum interval is {interval} seconds.'
97-
)
95+
AUTOMATION_TOO_FREQUENT = lambda interval='': f'Schedule too frequent. Minimum interval is {interval} seconds.'
9896
AUTOMATION_INVALID_RRULE = lambda err='': f'Invalid RRULE: {err}'
9997
AUTOMATION_NO_FUTURE_RUNS = 'RRULE has no future occurrences'
10098

backend/open_webui/main.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1707,7 +1707,9 @@ async def chat_completion(
17071707
},
17081708
'messages': [
17091709
{'role': 'user', 'content': user_message.get('content', '')},
1710-
] if user_message_id else [],
1710+
]
1711+
if user_message_id
1712+
else [],
17111713
'tags': [],
17121714
'timestamp': int(time.time() * 1000),
17131715
},
@@ -1734,9 +1736,7 @@ async def chat_completion(
17341736
pass
17351737
else:
17361738
# Existing chat — verify ownership
1737-
if (
1738-
not await Chats.is_chat_owner(chat_id, user.id) and user.role != 'admin'
1739-
):
1739+
if not await Chats.is_chat_owner(chat_id, user.id) and user.role != 'admin':
17401740
raise HTTPException(
17411741
status_code=status.HTTP_404_NOT_FOUND,
17421742
detail=ERROR_MESSAGES.DEFAULT(),
@@ -1787,16 +1787,16 @@ async def chat_completion(
17871787

17881788
# Link user message → all assistant messages (childrenIds)
17891789
if user_message_id and all_assistant_ids:
1790-
existing_user_message = await Chats.get_message_by_id_and_message_id(
1791-
chat_id, user_message_id
1792-
)
1790+
existing_user_message = await Chats.get_message_by_id_and_message_id(chat_id, user_message_id)
17931791
if existing_user_message:
17941792
child_ids = existing_user_message.get('childrenIds', [])
17951793
for assistant_id in all_assistant_ids:
17961794
if assistant_id not in child_ids:
17971795
child_ids.append(assistant_id)
17981796
await Chats.upsert_message_to_chat_by_id_and_message_id(
1799-
chat_id, user_message_id, {'childrenIds': child_ids},
1797+
chat_id,
1798+
user_message_id,
1799+
{'childrenIds': child_ids},
18001800
)
18011801

18021802
# Save each assistant placeholder
@@ -1956,11 +1956,19 @@ async def _cleanup_mcp():
19561956
task_id, _ = await create_task(
19571957
request.app.state.redis,
19581958
process_chat(
1959-
request, model_form_data, user, per_model_metadata, resolved_model,
1960-
tasks if idx == 0 else {
1961-
k: v for k, v in (tasks or {}).items()
1959+
request,
1960+
model_form_data,
1961+
user,
1962+
per_model_metadata,
1963+
resolved_model,
1964+
tasks
1965+
if idx == 0
1966+
else {
1967+
k: v
1968+
for k, v in (tasks or {}).items()
19621969
if k not in (TASKS.TITLE_GENERATION, TASKS.TAGS_GENERATION)
1963-
} or None,
1970+
}
1971+
or None,
19641972
),
19651973
id=chat_id,
19661974
)

backend/open_webui/retrieval/utils.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -506,9 +506,7 @@ async def _fetch_collection(name: str):
506506
log.exception(f'Failed to fetch collection {name}: {e}')
507507
return name, None
508508

509-
collection_results = dict(
510-
await asyncio.gather(*(_fetch_collection(name) for name in collection_names))
511-
)
509+
collection_results = dict(await asyncio.gather(*(_fetch_collection(name) for name in collection_names)))
512510

513511
log.info(f'Starting hybrid search for {len(queries)} queries in {len(collection_names)} collections...')
514512

@@ -1153,9 +1151,7 @@ async def get_sources_from_items(
11531151
if full_context:
11541152
# Sync helper makes blocking VECTOR_DB_CLIENT calls;
11551153
# offload so the async caller's event loop stays free.
1156-
query_result = await asyncio.to_thread(
1157-
get_all_items_from_collections, collection_names
1158-
)
1154+
query_result = await asyncio.to_thread(get_all_items_from_collections, collection_names)
11591155
else:
11601156
query_result = await query_collection(
11611157
request,

backend/open_webui/retrieval/vector/async_client.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -101,19 +101,15 @@ async def search(
101101
filter: Optional[Dict] = None,
102102
limit: int = 10,
103103
) -> Optional[SearchResult]:
104-
return await asyncio.to_thread(
105-
self._sync.search, collection_name, vectors, filter, limit
106-
)
104+
return await asyncio.to_thread(self._sync.search, collection_name, vectors, filter, limit)
107105

108106
async def query(
109107
self,
110108
collection_name: str,
111109
filter: Dict,
112110
limit: Optional[int] = None,
113111
) -> Optional[GetResult]:
114-
return await asyncio.to_thread(
115-
self._sync.query, collection_name, filter, limit
116-
)
112+
return await asyncio.to_thread(self._sync.query, collection_name, filter, limit)
117113

118114
async def get(self, collection_name: str) -> Optional[GetResult]:
119115
return await asyncio.to_thread(self._sync.get, collection_name)
@@ -124,9 +120,7 @@ async def delete(
124120
ids: Optional[List[str]] = None,
125121
filter: Optional[Dict] = None,
126122
) -> None:
127-
return await asyncio.to_thread(
128-
self._sync.delete, collection_name, ids, filter
129-
)
123+
return await asyncio.to_thread(self._sync.delete, collection_name, ids, filter)
130124

131125
async def reset(self) -> None:
132126
return await asyncio.to_thread(self._sync.reset)

backend/open_webui/retrieval/vector/utils.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,3 @@ def process_metadata(
2727
else:
2828
result[key] = sanitize_text_for_db(value)
2929
return result
30-

backend/open_webui/routers/images.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,6 @@ async def image_generations(
543543

544544
model = get_image_model(request)
545545

546-
547546
try:
548547
if request.app.state.config.IMAGE_GENERATION_ENGINE == 'openai':
549548
headers = {
@@ -856,7 +855,6 @@ def get_image_file_item(base64_string, param_name='image'):
856855
),
857856
)
858857

859-
860858
try:
861859
if request.app.state.config.IMAGE_EDIT_ENGINE == 'openai':
862860
headers = {

backend/open_webui/routers/retrieval.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2532,9 +2532,7 @@ async def delete_entries_from_collection(
25322532
if hash is None:
25332533
raise HTTPException(
25342534
status_code=status.HTTP_400_BAD_REQUEST,
2535-
detail=ERROR_MESSAGES.DEFAULT(
2536-
'File has no hash; cannot delete vector entries by hash.'
2537-
),
2535+
detail=ERROR_MESSAGES.DEFAULT('File has no hash; cannot delete vector entries by hash.'),
25382536
)
25392537

25402538
# Pre-existing bug: this used `metadata=` which is not a

backend/open_webui/utils/anthropic.py

Lines changed: 15 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,7 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
205205
elif content_type == 'image':
206206
source = content_block.get('source', {})
207207
if source.get('type') == 'base64':
208-
media_type = source.get(
209-
'media_type', 'image/png'
210-
)
208+
media_type = source.get('media_type', 'image/png')
211209
data = source.get('data', '')
212210
converted_parts.append(
213211
{
@@ -229,68 +227,36 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
229227
elif content_type == 'document':
230228
# Documents have no direct OpenAI equivalent;
231229
# convert to a text representation.
232-
document_source = content_block.get(
233-
'source', {}
234-
)
235-
document_title = content_block.get(
236-
'title', 'Document'
237-
)
238-
document_context = content_block.get(
239-
'context', ''
240-
)
241-
document_text = (
242-
f'[Document: {document_title}]'
243-
)
230+
document_source = content_block.get('source', {})
231+
document_title = content_block.get('title', 'Document')
232+
document_context = content_block.get('context', '')
233+
document_text = f'[Document: {document_title}]'
244234
if document_context:
245235
document_text += f'\n{document_context}'
246-
if (
247-
document_source.get('type') == 'text'
248-
and document_source.get('data')
249-
):
250-
document_text += (
251-
f'\n{document_source["data"]}'
252-
)
253-
converted_parts.append(
254-
{'type': 'text', 'text': document_text}
255-
)
236+
if document_source.get('type') == 'text' and document_source.get('data'):
237+
document_text += f'\n{document_source["data"]}'
238+
converted_parts.append({'type': 'text', 'text': document_text})
256239
elif content_type == 'search_result':
257240
# Convert search results to a text
258241
# representation with source attribution.
259242
search_title = content_block.get('title', '')
260243
search_url = content_block.get('source', '')
261-
search_content_blocks = content_block.get(
262-
'content', []
263-
)
244+
search_content_blocks = content_block.get('content', [])
264245
search_texts = []
265246
for search_block in search_content_blocks:
266-
if (
267-
isinstance(search_block, dict)
268-
and search_block.get('type') == 'text'
269-
):
270-
search_texts.append(
271-
search_block.get('text', '')
272-
)
247+
if isinstance(search_block, dict) and search_block.get('type') == 'text':
248+
search_texts.append(search_block.get('text', ''))
273249
search_body = '\n'.join(search_texts)
274-
search_text = (
275-
f'[Search Result: {search_title}]'
276-
)
250+
search_text = f'[Search Result: {search_title}]'
277251
if search_url:
278252
search_text += f'\nSource: {search_url}'
279253
if search_body:
280254
search_text += f'\n{search_body}'
281-
converted_parts.append(
282-
{'type': 'text', 'text': search_text}
283-
)
255+
converted_parts.append({'type': 'text', 'text': search_text})
284256

285257
# Flatten to string when only text parts are present
286-
if all(
287-
part.get('type') == 'text'
288-
for part in converted_parts
289-
):
290-
tool_content = '\n'.join(
291-
part.get('text', '')
292-
for part in converted_parts
293-
)
258+
if all(part.get('type') == 'text' for part in converted_parts):
259+
tool_content = '\n'.join(part.get('text', '') for part in converted_parts)
294260
elif converted_parts:
295261
tool_content = converted_parts
296262
else:

backend/open_webui/utils/asgi_middleware.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
105105
try:
106106
ScopedSession.commit()
107107
except Exception:
108-
log.exception(
109-
'CommitSessionMiddleware: post-request commit failed; '
110-
'response was already sent to client'
111-
)
108+
log.exception('CommitSessionMiddleware: post-request commit failed; response was already sent to client')
112109
try:
113110
ScopedSession.rollback()
114111
except Exception:
@@ -190,9 +187,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
190187
if query_params.get('transport', [''])[0] == 'websocket':
191188
headers = _scope_headers(scope)
192189
upgrade = headers.get('upgrade', '').lower()
193-
connection_tokens = [
194-
token.strip() for token in headers.get('connection', '').lower().split(',')
195-
]
190+
connection_tokens = [token.strip() for token in headers.get('connection', '').lower().split(',')]
196191
if upgrade != 'websocket' or 'upgrade' not in connection_tokens:
197192
response = JSONResponse(
198193
status_code=400,

backend/open_webui/utils/middleware.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3101,8 +3101,8 @@ async def outlet_filter_handler(ctx):
31013101
'content': m.get('content', ''),
31023102
'info': m.get('info'),
31033103
'timestamp': m.get('timestamp'),
3104-
**(({'usage': m['usage']} if m.get('usage') else {})),
3105-
**(({'sources': m['sources']} if m.get('sources') else {})),
3104+
**({'usage': m['usage']} if m.get('usage') else {}),
3105+
**({'sources': m['sources']} if m.get('sources') else {}),
31063106
}
31073107
for m in message_list
31083108
],
@@ -3157,10 +3157,12 @@ async def outlet_filter_handler(ctx):
31573157
)
31583158

31593159
if event_emitter:
3160-
await event_emitter({
3161-
'type': 'chat:outlet',
3162-
'data': {'messages': outlet_result['messages']},
3163-
})
3160+
await event_emitter(
3161+
{
3162+
'type': 'chat:outlet',
3163+
'data': {'messages': outlet_result['messages']},
3164+
}
3165+
)
31643166
except Exception as e:
31653167
log.debug(f'Error running outlet filters: {e}')
31663168

0 commit comments

Comments
 (0)