-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathconfig.py
More file actions
661 lines (536 loc) · 21.2 KB
/
config.py
File metadata and controls
661 lines (536 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
"""LLM configuration endpoints."""
import json
import logging
import string
from pathlib import Path
from fastapi import APIRouter, BackgroundTasks, HTTPException
from app.config import settings
from app.llm import check_llm_health, LLMConfig
from app.schemas import (
LLMConfigRequest,
LLMConfigResponse,
FeatureConfigRequest,
FeatureConfigResponse,
LanguageConfigRequest,
LanguageConfigResponse,
PromptConfigRequest,
PromptConfigResponse,
PromptOption,
PromptTemplate,
PromptTemplateCreateRequest,
PromptTemplateDeleteResponse,
PromptTemplateListResponse,
PromptTemplateResponse,
PromptTemplateUpdateRequest,
ApiKeyProviderStatus,
ApiKeyStatusResponse,
ApiKeysUpdateRequest,
ApiKeysUpdateResponse,
ResetDatabaseRequest,
)
from app.prompts import (
DEFAULT_IMPROVE_PROMPT_ID,
IMPROVE_PROMPT_OPTIONS,
IMPROVE_RESUME_PROMPTS,
)
from app.config import (
get_api_keys_from_config,
save_api_keys_to_config,
delete_api_key_from_config,
clear_all_api_keys,
)
from app.database import db
router = APIRouter(prefix="/config", tags=["Configuration"])
def _get_config_path() -> Path:
"""Get path to config storage file."""
return settings.config_path
def _load_config() -> dict:
"""Load config from file."""
path = _get_config_path()
if path.exists():
return json.loads(path.read_text())
return {}
def _save_config(config: dict) -> None:
"""Save config to file."""
path = _get_config_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(config, indent=2))
def _mask_api_key(key: str) -> str:
"""Mask API key for display."""
if not key:
return ""
if len(key) <= 8:
return "*" * len(key)
return key[:4] + "*" * (len(key) - 8) + key[-4:]
def _get_prompt_options() -> list[PromptOption]:
"""Return available prompt options for resume tailoring."""
options = [PromptOption(**option) for option in IMPROVE_PROMPT_OPTIONS]
for prompt in db.list_prompt_templates():
options.append(
PromptOption(
id=prompt["prompt_id"],
label=prompt.get("label", ""),
description=prompt.get("description", ""),
)
)
return options
def _get_builtin_prompt_templates() -> list[PromptTemplate]:
templates: list[PromptTemplate] = []
for option in IMPROVE_PROMPT_OPTIONS:
prompt_id = option["id"]
templates.append(
PromptTemplate(
id=prompt_id,
label=option["label"],
description=option["description"],
prompt=IMPROVE_RESUME_PROMPTS[prompt_id],
is_builtin=True,
created_at=None,
updated_at=None,
)
)
return templates
_ALLOWED_PROMPT_FIELDS = {
"job_description",
"job_keywords",
"original_resume",
"schema",
"output_language",
"critical_truthfulness_rules",
}
def _validate_prompt_template(prompt: str) -> None:
fields = {
field_name
for _, field_name, _, _ in string.Formatter().parse(prompt)
if field_name
}
unknown = {field for field in fields if field not in _ALLOWED_PROMPT_FIELDS}
if unknown:
raise HTTPException(
status_code=400,
detail=(
"Unsupported prompt placeholders: "
f"{sorted(unknown)}. Allowed: {sorted(_ALLOWED_PROMPT_FIELDS)}"
),
)
async def _log_llm_health_check(config: LLMConfig) -> None:
"""Run a best-effort health check and log outcome without affecting API responses."""
try:
health = await check_llm_health(config)
if not health.get("healthy", False):
logging.warning(
"LLM config saved but health check failed",
extra={"provider": config.provider, "model": config.model},
)
except Exception:
logging.exception(
"LLM config saved but health check raised exception",
extra={"provider": config.provider, "model": config.model},
)
@router.get("/llm-api-key", response_model=LLMConfigResponse)
async def get_llm_config_endpoint() -> LLMConfigResponse:
"""Get current LLM configuration (API key masked)."""
stored = _load_config()
return LLMConfigResponse(
provider=stored.get("provider", settings.llm_provider),
model=stored.get("model", settings.llm_model),
api_key=_mask_api_key(stored.get("api_key", settings.llm_api_key)),
api_base=stored.get("api_base", settings.llm_api_base),
)
@router.put("/llm-api-key", response_model=LLMConfigResponse)
async def update_llm_config(
request: LLMConfigRequest,
background_tasks: BackgroundTasks,
) -> LLMConfigResponse:
"""Update LLM configuration.
Saves the configuration and returns it (API key masked).
Note: We intentionally do NOT hard-fail the update based on a live health check.
Users may configure proxies/aggregators or temporarily unavailable endpoints and
still need to persist the configuration. Connectivity can be verified via
`/config/llm-test` and the System Status panel.
"""
stored = _load_config()
# Update only provided fields
if request.provider is not None:
stored["provider"] = request.provider
if request.model is not None:
stored["model"] = request.model
if request.api_key is not None:
stored["api_key"] = request.api_key
if request.api_base is not None:
stored["api_base"] = request.api_base
# Build normalized config for response
test_config = LLMConfig(
provider=stored.get("provider", settings.llm_provider),
model=stored.get("model", settings.llm_model),
api_key=stored.get("api_key", settings.llm_api_key),
api_base=stored.get("api_base", settings.llm_api_base),
)
# Save config regardless of health check outcome (see docstring).
_save_config(stored)
# Best-effort health check for server-side logs/diagnostics (do not block response).
background_tasks.add_task(_log_llm_health_check, test_config)
return LLMConfigResponse(
provider=test_config.provider,
model=test_config.model,
api_key=_mask_api_key(test_config.api_key),
api_base=test_config.api_base,
)
@router.post("/llm-test")
async def test_llm_connection(request: LLMConfigRequest | None = None) -> dict:
"""Test LLM connection with provided or stored configuration.
If request body is provided, tests with those values (for pre-save testing).
Otherwise, tests with the currently saved configuration.
"""
stored = _load_config()
# Build config: use request values if provided, otherwise fall back to stored/default
config = LLMConfig(
provider=(
request.provider
if request and request.provider
else stored.get("provider", settings.llm_provider)
),
model=(
request.model
if request and request.model
else stored.get("model", settings.llm_model)
),
api_key=(
request.api_key
if request and request.api_key
else stored.get("api_key", settings.llm_api_key)
),
api_base=(
request.api_base
if request and request.api_base is not None
else stored.get("api_base", settings.llm_api_base)
),
)
test_prompt = "Hi"
return await check_llm_health(config, include_details=True, test_prompt=test_prompt)
@router.get("/features", response_model=FeatureConfigResponse)
async def get_feature_config() -> FeatureConfigResponse:
"""Get current feature configuration."""
stored = _load_config()
return FeatureConfigResponse(
enable_cover_letter=stored.get("enable_cover_letter", False),
enable_outreach_message=stored.get("enable_outreach_message", False),
)
@router.put("/features", response_model=FeatureConfigResponse)
async def update_feature_config(request: FeatureConfigRequest) -> FeatureConfigResponse:
"""Update feature configuration."""
stored = _load_config()
# Update only provided fields
if request.enable_cover_letter is not None:
stored["enable_cover_letter"] = request.enable_cover_letter
if request.enable_outreach_message is not None:
stored["enable_outreach_message"] = request.enable_outreach_message
# Save config
_save_config(stored)
return FeatureConfigResponse(
enable_cover_letter=stored.get("enable_cover_letter", False),
enable_outreach_message=stored.get("enable_outreach_message", False),
)
# Supported languages for i18n
SUPPORTED_LANGUAGES = ["en", "es", "zh", "ja", "pt"]
@router.get("/language", response_model=LanguageConfigResponse)
async def get_language_config() -> LanguageConfigResponse:
"""Get current language configuration."""
stored = _load_config()
# Support legacy single 'language' field migration
legacy_language = stored.get("language", "en")
return LanguageConfigResponse(
ui_language=stored.get("ui_language", legacy_language),
content_language=stored.get("content_language", legacy_language),
supported_languages=SUPPORTED_LANGUAGES,
)
@router.put("/language", response_model=LanguageConfigResponse)
async def update_language_config(
request: LanguageConfigRequest,
) -> LanguageConfigResponse:
"""Update language configuration."""
stored = _load_config()
# Validate and update UI language
if request.ui_language is not None:
if request.ui_language not in SUPPORTED_LANGUAGES:
raise HTTPException(
status_code=400,
detail=f"Unsupported UI language: {request.ui_language}. Supported: {SUPPORTED_LANGUAGES}",
)
stored["ui_language"] = request.ui_language
# Validate and update content language
if request.content_language is not None:
if request.content_language not in SUPPORTED_LANGUAGES:
raise HTTPException(
status_code=400,
detail=f"Unsupported content language: {request.content_language}. Supported: {SUPPORTED_LANGUAGES}",
)
stored["content_language"] = request.content_language
# Save config
_save_config(stored)
# Support legacy single 'language' field migration
legacy_language = stored.get("language", "en")
return LanguageConfigResponse(
ui_language=stored.get("ui_language", legacy_language),
content_language=stored.get("content_language", legacy_language),
supported_languages=SUPPORTED_LANGUAGES,
)
@router.get("/prompts", response_model=PromptConfigResponse)
async def get_prompt_config() -> PromptConfigResponse:
"""Get current prompt configuration for resume tailoring."""
stored = _load_config()
options = _get_prompt_options()
option_ids = {option.id for option in options}
default_prompt_id = stored.get("default_prompt_id", DEFAULT_IMPROVE_PROMPT_ID)
if default_prompt_id not in option_ids:
default_prompt_id = DEFAULT_IMPROVE_PROMPT_ID
return PromptConfigResponse(
default_prompt_id=default_prompt_id,
prompt_options=options,
)
@router.put("/prompts", response_model=PromptConfigResponse)
async def update_prompt_config(
request: PromptConfigRequest,
) -> PromptConfigResponse:
"""Update prompt configuration for resume tailoring."""
stored = _load_config()
options = _get_prompt_options()
option_ids = {option.id for option in options}
if request.default_prompt_id is not None:
if request.default_prompt_id not in option_ids:
raise HTTPException(
status_code=400,
detail=(
"Unsupported prompt id: "
f"{request.default_prompt_id}. Supported: {sorted(option_ids)}"
),
)
stored["default_prompt_id"] = request.default_prompt_id
_save_config(stored)
default_prompt_id = stored.get("default_prompt_id", DEFAULT_IMPROVE_PROMPT_ID)
if default_prompt_id not in option_ids:
default_prompt_id = DEFAULT_IMPROVE_PROMPT_ID
return PromptConfigResponse(
default_prompt_id=default_prompt_id,
prompt_options=options,
)
@router.get("/prompt-templates", response_model=PromptTemplateListResponse)
async def list_prompt_templates() -> PromptTemplateListResponse:
"""List built-in and custom prompt templates."""
builtins = _get_builtin_prompt_templates()
custom = [
PromptTemplate(
id=prompt["prompt_id"],
label=prompt.get("label", ""),
description=prompt.get("description", ""),
prompt=prompt.get("prompt", ""),
is_builtin=False,
created_at=prompt.get("created_at"),
updated_at=prompt.get("updated_at"),
)
for prompt in db.list_prompt_templates()
]
return PromptTemplateListResponse(data=[*builtins, *custom])
@router.post("/prompt-templates", response_model=PromptTemplateResponse)
async def create_prompt_template(
request: PromptTemplateCreateRequest,
) -> PromptTemplateResponse:
"""Create a custom prompt template."""
label = request.label.strip()
description = request.description.strip()
prompt = request.prompt.strip()
if not label or not description or not prompt:
raise HTTPException(
status_code=400,
detail="Label, description, and prompt are required.",
)
_validate_prompt_template(prompt)
created = db.create_prompt_template(label=label, description=description, prompt=prompt)
return PromptTemplateResponse(
data=PromptTemplate(
id=created["prompt_id"],
label=created["label"],
description=created["description"],
prompt=created["prompt"],
is_builtin=False,
created_at=created.get("created_at"),
updated_at=created.get("updated_at"),
)
)
@router.put("/prompt-templates/{prompt_id}", response_model=PromptTemplateResponse)
async def update_prompt_template(
prompt_id: str,
request: PromptTemplateUpdateRequest,
) -> PromptTemplateResponse:
"""Update a custom prompt template."""
builtin_ids = {option["id"] for option in IMPROVE_PROMPT_OPTIONS}
if prompt_id in builtin_ids:
raise HTTPException(status_code=400, detail="Built-in prompts cannot be edited.")
updates: dict[str, str] = {}
if request.label is not None:
updates["label"] = request.label.strip()
if request.description is not None:
updates["description"] = request.description.strip()
if request.prompt is not None:
prompt = request.prompt.strip()
if prompt:
_validate_prompt_template(prompt)
updates["prompt"] = prompt
if not updates:
raise HTTPException(status_code=400, detail="No updates provided.")
try:
updated = db.update_prompt_template(prompt_id, updates)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return PromptTemplateResponse(
data=PromptTemplate(
id=updated["prompt_id"],
label=updated.get("label", ""),
description=updated.get("description", ""),
prompt=updated.get("prompt", ""),
is_builtin=False,
created_at=updated.get("created_at"),
updated_at=updated.get("updated_at"),
)
)
@router.delete("/prompt-templates/{prompt_id}", response_model=PromptTemplateDeleteResponse)
async def delete_prompt_template(prompt_id: str) -> PromptTemplateDeleteResponse:
"""Delete a custom prompt template."""
builtin_ids = {option["id"] for option in IMPROVE_PROMPT_OPTIONS}
if prompt_id in builtin_ids:
raise HTTPException(status_code=400, detail="Built-in prompts cannot be deleted.")
removed = db.delete_prompt_template(prompt_id)
if not removed:
raise HTTPException(status_code=404, detail="Prompt template not found.")
stored = _load_config()
if stored.get("default_prompt_id") == prompt_id:
stored["default_prompt_id"] = DEFAULT_IMPROVE_PROMPT_ID
_save_config(stored)
return PromptTemplateDeleteResponse(message="Prompt template deleted.")
# Supported API key providers
SUPPORTED_PROVIDERS = ["openai", "anthropic", "google", "openrouter", "deepseek"]
def _mask_key_short(key: str | None) -> str | None:
"""Mask API key showing only last 4 characters."""
if not key:
return None
if len(key) <= 4:
return "*" * len(key)
return "..." + key[-4:]
@router.get("/api-keys", response_model=ApiKeyStatusResponse)
async def get_api_keys_status() -> ApiKeyStatusResponse:
"""Get status of all configured API keys (masked).
Returns the configuration status for each supported provider.
API keys are masked to show only the last 4 characters.
"""
stored_keys = get_api_keys_from_config()
providers = []
for provider in SUPPORTED_PROVIDERS:
key = stored_keys.get(provider)
providers.append(
ApiKeyProviderStatus(
provider=provider,
configured=bool(key),
masked_key=_mask_key_short(key),
)
)
return ApiKeyStatusResponse(providers=providers)
@router.post("/api-keys", response_model=ApiKeysUpdateResponse)
async def update_api_keys(request: ApiKeysUpdateRequest) -> ApiKeysUpdateResponse:
"""Update API keys for one or more providers.
Only updates the providers that are explicitly set in the request.
Empty strings will clear the key for that provider.
"""
stored_keys = get_api_keys_from_config()
updated = []
# Update each provider if provided in request
if request.openai is not None:
if request.openai:
stored_keys["openai"] = request.openai
elif "openai" in stored_keys:
del stored_keys["openai"]
updated.append("openai")
if request.anthropic is not None:
if request.anthropic:
stored_keys["anthropic"] = request.anthropic
elif "anthropic" in stored_keys:
del stored_keys["anthropic"]
updated.append("anthropic")
if request.google is not None:
if request.google:
stored_keys["google"] = request.google
elif "google" in stored_keys:
del stored_keys["google"]
updated.append("google")
if request.openrouter is not None:
if request.openrouter:
stored_keys["openrouter"] = request.openrouter
elif "openrouter" in stored_keys:
del stored_keys["openrouter"]
updated.append("openrouter")
if request.deepseek is not None:
if request.deepseek:
stored_keys["deepseek"] = request.deepseek
elif "deepseek" in stored_keys:
del stored_keys["deepseek"]
updated.append("deepseek")
save_api_keys_to_config(stored_keys)
return ApiKeysUpdateResponse(
message=f"Updated {len(updated)} API key(s)",
updated_providers=updated,
)
@router.delete("/api-keys")
async def delete_all_api_keys(confirm: str | None = None) -> dict:
"""Clear all configured API keys.
This is a destructive operation. Requires confirmation token.
Args:
confirm: Must be "CLEAR_ALL_KEYS" to execute
Returns:
Success message
Note:
This is a local-only endpoint for single-user deployments.
In production/multi-user scenarios, add proper authentication.
"""
if confirm != "CLEAR_ALL_KEYS":
raise HTTPException(
status_code=400,
detail="Confirmation required. Pass confirm=CLEAR_ALL_KEYS query parameter.",
)
clear_all_api_keys()
return {"message": "All API keys have been cleared"}
@router.delete("/api-keys/{provider}")
async def delete_api_key(provider: str) -> dict:
"""Delete API key for a specific provider.
Args:
provider: The provider name (openai, anthropic, google, openrouter, deepseek)
Returns:
Success message
"""
if provider not in SUPPORTED_PROVIDERS:
raise HTTPException(
status_code=400,
detail=f"Unsupported provider: {provider}. Supported: {SUPPORTED_PROVIDERS}",
)
delete_api_key_from_config(provider)
return {"message": f"API key for {provider} has been removed"}
@router.post("/reset")
async def reset_database_endpoint(request: ResetDatabaseRequest) -> dict:
"""Reset the database and clear all data.
WARNING: This action is irreversible. It will:
1. Truncate all database tables (resumes, jobs, improvements)
2. Delete all uploaded files
Requires confirmation token for safety.
Args:
request: Request body containing confirmation token
Returns:
Success message
Note:
This is a local-only endpoint for single-user deployments.
In production/multi-user scenarios, add proper authentication.
"""
if request.confirm != "RESET_ALL_DATA":
raise HTTPException(
status_code=400,
detail="Confirmation required. Pass confirm=RESET_ALL_DATA in request body.",
)
db.reset_database()
return {"message": "Database and all data have been reset successfully"}