Skip to content

Commit d0188f3

Browse files
committed
refac
1 parent 45f45f5 commit d0188f3

13 files changed

Lines changed: 70 additions & 56 deletions

File tree

backend/open_webui/constants.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,19 @@ def __str__(self) -> str:
9191

9292
INVALID_PASSWORD = lambda err='': err if err else 'The password does not meet the required validation criteria.'
9393

94+
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+
)
98+
AUTOMATION_INVALID_RRULE = lambda err='': f'Invalid RRULE: {err}'
99+
AUTOMATION_NO_FUTURE_RUNS = 'RRULE has no future occurrences'
100+
101+
FEATURE_DISABLED = lambda name='': f'{name} is disabled'
102+
INPUT_TOO_LONG = lambda size='': f'Input prompt exceeds maximum length of {size}'
103+
SERVER_CONNECTION_ERROR = 'Open WebUI: Server Connection Error'
104+
REQUIRED_FIELD_EMPTY = lambda name='': f'Required field {name} is empty'
105+
OAUTH_NOT_CONFIGURED = lambda name='': f"Provider '{name}' is not configured"
106+
94107

95108
class TASKS(str, Enum):
96109
def __str__(self) -> str:

backend/open_webui/routers/auths.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1131,7 +1131,7 @@ async def update_ldap_server(request: Request, form_data: LdapServerConfig, user
11311131
for key in required_fields:
11321132
value = getattr(form_data, key)
11331133
if not value:
1134-
raise HTTPException(400, detail=f'Required field {key} is empty')
1134+
raise HTTPException(400, detail=ERROR_MESSAGES.REQUIRED_FIELD_EMPTY(key))
11351135

11361136
request.app.state.config.LDAP_SERVER_LABEL = form_data.label
11371137
request.app.state.config.LDAP_SERVER_HOST = form_data.host
@@ -1260,15 +1260,15 @@ async def token_exchange(
12601260
if provider not in OAUTH_PROVIDERS:
12611261
raise HTTPException(
12621262
status_code=status.HTTP_404_NOT_FOUND,
1263-
detail=f"Provider '{provider}' is not configured",
1263+
detail=ERROR_MESSAGES.OAUTH_NOT_CONFIGURED(provider),
12641264
)
12651265
# Get the OAuth client for this provider
12661266
oauth_manager = request.app.state.oauth_manager
12671267
client = oauth_manager.get_client(provider)
12681268
if not client:
12691269
raise HTTPException(
12701270
status_code=status.HTTP_404_NOT_FOUND,
1271-
detail=f"OAuth client for '{provider}' not found",
1271+
detail=ERROR_MESSAGES.OAUTH_NOT_CONFIGURED(provider),
12721272
)
12731273

12741274
# Validate the token by calling the userinfo endpoint

backend/open_webui/routers/automations.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ async def check_automation_limits(request, user, rrule_str: str, db, is_create:
7474
if max_count > 0 and await Automations.count_by_user(user.id, db=db) >= max_count:
7575
raise HTTPException(
7676
status_code=status.HTTP_403_FORBIDDEN,
77-
detail=f'Automation limit reached ({max_count})',
77+
detail=ERROR_MESSAGES.AUTOMATION_LIMIT_EXCEEDED(max_count),
7878
)
7979

8080
# Min interval (create + update)
@@ -86,7 +86,7 @@ async def check_automation_limits(request, user, rrule_str: str, db, is_create:
8686
if interval is not None and interval < min_interval:
8787
raise HTTPException(
8888
status_code=status.HTTP_400_BAD_REQUEST,
89-
detail=f'Schedule too frequent. Minimum interval is {min_interval} seconds.',
89+
detail=ERROR_MESSAGES.AUTOMATION_TOO_FREQUENT(min_interval),
9090
)
9191

9292

backend/open_webui/routers/channels.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ async def check_channels_access(request: Request, user: Optional[UserModel] = No
140140
if not request.app.state.config.ENABLE_CHANNELS:
141141
raise HTTPException(
142142
status_code=status.HTTP_403_FORBIDDEN,
143-
detail='Channels are not enabled',
143+
detail=ERROR_MESSAGES.FEATURE_DISABLED('Channels'),
144144
)
145145

146146
if user:
@@ -1791,7 +1791,7 @@ async def post_webhook_message(
17911791
if not webhook:
17921792
raise HTTPException(
17931793
status_code=status.HTTP_401_UNAUTHORIZED,
1794-
detail='Invalid webhook URL',
1794+
detail=ERROR_MESSAGES.INVALID_URL,
17951795
)
17961796

17971797
channel = await Channels.get_channel_by_id(webhook.channel_id, db=db)
@@ -1809,7 +1809,7 @@ async def post_webhook_message(
18091809
if not message:
18101810
raise HTTPException(
18111811
status_code=status.HTTP_400_BAD_REQUEST,
1812-
detail='Failed to create message',
1812+
detail=ERROR_MESSAGES.DEFAULT('Failed to create message'),
18131813
)
18141814

18151815
# Update last_used_at

backend/open_webui/routers/functions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ async def load_function_from_url(request: Request, form_data: LoadUrlForm, user=
128128
'content': data,
129129
}
130130
except Exception as e:
131-
raise HTTPException(status_code=500, detail=f'Error importing function: {e}')
131+
raise HTTPException(status_code=500, detail=ERROR_MESSAGES.DEFAULT(e))
132132

133133

134134
############################

backend/open_webui/routers/memories.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ async def update_memory_by_id(
268268

269269
memory = await Memories.update_memory_by_id_and_user_id(memory_id, user.id, form_data.content)
270270
if memory is None:
271-
raise HTTPException(status_code=404, detail='Memory not found')
271+
raise HTTPException(status_code=404, detail=ERROR_MESSAGES.NOT_FOUND)
272272

273273
if form_data.content is not None:
274274
vector = await request.app.state.EMBEDDING_FUNCTION(memory.content, user=user)

backend/open_webui/routers/ollama.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ async def send_request(
157157
log.error(f'Failed to parse error response: {e}')
158158
raise HTTPException(
159159
status_code=r.status,
160-
detail='Open WebUI: Server Connection Error',
160+
detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR,
161161
)
162162

163163
r.raise_for_status()
@@ -184,7 +184,7 @@ async def send_request(
184184
except Exception as e:
185185
raise HTTPException(
186186
status_code=r.status if r else 500,
187-
detail=f'Ollama: {e}' if str(e) else 'Open WebUI: Server Connection Error',
187+
detail=f'Ollama: {e}' if str(e) else ERROR_MESSAGES.SERVER_CONNECTION_ERROR,
188188
)
189189
finally:
190190
if not streaming:
@@ -251,7 +251,7 @@ async def verify_connection(form_data: ConnectionVerificationForm, user=Depends(
251251
return data
252252
except aiohttp.ClientError as e:
253253
log.exception(f'Client error: {str(e)}')
254-
raise HTTPException(status_code=500, detail='Open WebUI: Server Connection Error')
254+
raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR)
255255
except Exception as e:
256256
log.exception(f'Unexpected error: {e}')
257257
error_detail = f'Unexpected error: {str(e)}'
@@ -428,7 +428,7 @@ async def get_filtered_models(models, user, db=None):
428428
@router.get('/api/tags/{url_idx}')
429429
async def get_ollama_tags(request: Request, url_idx: Optional[int] = None, user=Depends(get_verified_user)):
430430
if not request.app.state.config.ENABLE_OLLAMA_API:
431-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
431+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
432432

433433
models = []
434434

@@ -621,7 +621,7 @@ async def pull_model(
621621
user=Depends(get_admin_user),
622622
):
623623
if not request.app.state.config.ENABLE_OLLAMA_API:
624-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
624+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
625625

626626
form_data = form_data.model_dump(exclude_none=True)
627627
form_data['model'] = form_data.get('model', form_data.get('name'))
@@ -656,7 +656,7 @@ async def push_model(
656656
user=Depends(get_admin_user),
657657
):
658658
if not request.app.state.config.ENABLE_OLLAMA_API:
659-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
659+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
660660

661661
if url_idx is None:
662662
await get_all_models(request, user=user)
@@ -699,7 +699,7 @@ async def create_model(
699699
user=Depends(get_admin_user),
700700
):
701701
if not request.app.state.config.ENABLE_OLLAMA_API:
702-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
702+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
703703

704704
log.debug(f'form_data: {form_data}')
705705
url = request.app.state.config.OLLAMA_BASE_URLS[url_idx]
@@ -727,7 +727,7 @@ async def copy_model(
727727
user=Depends(get_admin_user),
728728
):
729729
if not request.app.state.config.ENABLE_OLLAMA_API:
730-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
730+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
731731

732732
if url_idx is None:
733733
await get_all_models(request, user=user)
@@ -762,7 +762,7 @@ async def delete_model(
762762
user=Depends(get_admin_user),
763763
):
764764
if not request.app.state.config.ENABLE_OLLAMA_API:
765-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
765+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
766766

767767
form_data = form_data.model_dump(exclude_none=True)
768768
form_data['model'] = form_data.get('model', form_data.get('name'))
@@ -797,7 +797,7 @@ async def delete_model(
797797
@router.post('/api/show')
798798
async def show_model_info(request: Request, form_data: ModelNameForm, user=Depends(get_verified_user)):
799799
if not request.app.state.config.ENABLE_OLLAMA_API:
800-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
800+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
801801

802802
form_data = form_data.model_dump(exclude_none=True)
803803
form_data['model'] = form_data.get('model', form_data.get('name'))
@@ -850,7 +850,7 @@ async def embed(
850850
user=Depends(get_verified_user),
851851
):
852852
if not request.app.state.config.ENABLE_OLLAMA_API:
853-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
853+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
854854

855855
log.info(f'generate_ollama_batch_embeddings {form_data}')
856856

@@ -909,7 +909,7 @@ async def embeddings(
909909
user=Depends(get_verified_user),
910910
):
911911
if not request.app.state.config.ENABLE_OLLAMA_API:
912-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
912+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
913913

914914
log.info(f'generate_ollama_embeddings {form_data}')
915915

@@ -976,7 +976,7 @@ async def generate_completion(
976976
user=Depends(get_verified_user),
977977
):
978978
if not request.app.state.config.ENABLE_OLLAMA_API:
979-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
979+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
980980

981981
# Enforce per-model access control
982982
await check_model_access(user, await Models.get_model_by_id(form_data.model), BYPASS_MODEL_ACCESS_CONTROL)
@@ -1067,7 +1067,7 @@ async def generate_chat_completion(
10671067
bypass_system_prompt: bool = False,
10681068
):
10691069
if not request.app.state.config.ENABLE_OLLAMA_API:
1070-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
1070+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
10711071

10721072
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
10731073
# Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
@@ -1313,7 +1313,7 @@ async def generate_anthropic_messages(
13131313
See https://docs.ollama.com/api/anthropic-compatibility
13141314
"""
13151315
if not request.app.state.config.ENABLE_OLLAMA_API:
1316-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
1316+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
13171317

13181318
payload = {**form_data}
13191319
model_id = payload.get('model', '')
@@ -1371,7 +1371,7 @@ async def generate_responses(
13711371
See https://ollama.com/blog/responses-api
13721372
"""
13731373
if not request.app.state.config.ENABLE_OLLAMA_API:
1374-
raise HTTPException(status_code=503, detail='Ollama API is disabled')
1374+
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
13751375

13761376
payload = form_data.model_dump()
13771377
model_id = form_data.model
@@ -1396,13 +1396,13 @@ async def generate_responses(
13961396
):
13971397
raise HTTPException(
13981398
status_code=403,
1399-
detail='Model not found',
1399+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(),
14001400
)
14011401
else:
14021402
if user.role != 'admin':
14031403
raise HTTPException(
14041404
status_code=403,
1405-
detail='Model not found',
1405+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(),
14061406
)
14071407

14081408
url, url_idx = await get_ollama_url(request, payload['model'], url_idx)

backend/open_webui/routers/openai.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,7 @@ async def verify_connection(
691691
elif is_anthropic_url(url):
692692
result = await get_anthropic_models(url, key)
693693
if result is None:
694-
raise HTTPException(status_code=500, detail='Failed to connect to Anthropic API')
694+
raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR)
695695
if 'error' in result:
696696
raise HTTPException(status_code=500, detail=result['error'])
697697
return result
@@ -718,10 +718,10 @@ async def verify_connection(
718718
except aiohttp.ClientError as e:
719719
# ClientError covers all aiohttp requests issues
720720
log.exception(f'Client error: {str(e)}')
721-
raise HTTPException(status_code=500, detail='Open WebUI: Server Connection Error')
721+
raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR)
722722
except Exception as e:
723723
log.exception(f'Unexpected error: {e}')
724-
raise HTTPException(status_code=500, detail='Open WebUI: Server Connection Error')
724+
raise HTTPException(status_code=500, detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR)
725725

726726

727727
def get_azure_allowed_params(api_version: str) -> set[str]:
@@ -1083,7 +1083,7 @@ async def generate_chat_completion(
10831083
else:
10841084
raise HTTPException(
10851085
status_code=404,
1086-
detail='Model not found',
1086+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(),
10871087
)
10881088

10891089
# Get the API config for the model
@@ -1243,7 +1243,7 @@ async def generate_chat_completion(
12431243

12441244
raise HTTPException(
12451245
status_code=r.status if r else 500,
1246-
detail='Open WebUI: Server Connection Error',
1246+
detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR,
12471247
)
12481248
finally:
12491249
if not streaming:
@@ -1321,7 +1321,7 @@ async def embeddings(request: Request, form_data: dict, user):
13211321
log.exception(e)
13221322
raise HTTPException(
13231323
status_code=r.status if r else 500,
1324-
detail='Open WebUI: Server Connection Error',
1324+
detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR,
13251325
)
13261326
finally:
13271327
if not streaming:
@@ -1445,7 +1445,7 @@ async def responses(
14451445
log.exception(e)
14461446
raise HTTPException(
14471447
status_code=r.status if r else 500,
1448-
detail='Open WebUI: Server Connection Error',
1448+
detail=ERROR_MESSAGES.SERVER_CONNECTION_ERROR,
14491449
)
14501450
finally:
14511451
if not streaming:

backend/open_webui/routers/prompts.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ async def update_prompt_by_id(
324324
if existing_prompt and existing_prompt.id != prompt.id:
325325
raise HTTPException(
326326
status_code=status.HTTP_400_BAD_REQUEST,
327-
detail=f"Command '/{form_data.command}' is already in use by another prompt",
327+
detail=ERROR_MESSAGES.COMMAND_TAKEN,
328328
)
329329

330330
form_data.access_grants = await filter_allowed_access_grants(
@@ -389,7 +389,7 @@ async def update_prompt_metadata(
389389
if existing_prompt and existing_prompt.id != prompt.id:
390390
raise HTTPException(
391391
status_code=status.HTTP_400_BAD_REQUEST,
392-
detail=f"Command '/{form_data.command}' is already in use",
392+
detail=ERROR_MESSAGES.COMMAND_TAKEN,
393393
)
394394

395395
updated_prompt = await Prompts.update_prompt_metadata(
@@ -751,7 +751,7 @@ async def get_prompt_diff(
751751
if not diff:
752752
raise HTTPException(
753753
status_code=status.HTTP_404_NOT_FOUND,
754-
detail='One or both history entries not found',
754+
detail=ERROR_MESSAGES.NOT_FOUND,
755755
)
756756

757757
return diff

0 commit comments

Comments
 (0)