-
Notifications
You must be signed in to change notification settings - Fork 451
Expand file tree
/
Copy pathendpoints.py
More file actions
1567 lines (1389 loc) · 69.4 KB
/
Copy pathendpoints.py
File metadata and controls
1567 lines (1389 loc) · 69.4 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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""FastAPI endpoint handlers for /settings, /onboarding, /onboarding/state,
/onboarding/rollback, /settings/docling-preset, and /openrag-docs/refresh.
Lifted verbatim from the original `src/api/settings.py`. Models live in
`api.settings.models`; provider/filter helpers in `api.settings.helpers`;
Langflow-sync helpers in `api.settings.langflow_sync`. No behavior change.
"""
import asyncio
import json
from fastapi import Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from api.provider_validation import validate_provider_setup
from api.settings.helpers import (
_affected_embedding_models,
_create_openrag_docs_filter,
_embedding_conflict_response,
_first_configured_embedding_provider,
_first_configured_llm_provider,
_get_flows_service,
)
from api.settings.langflow_sync import (
_background_tasks,
_run_async_post_save_langflow_updates,
_update_langflow_docling_settings,
_update_langflow_global_variables,
_update_langflow_model_values,
_update_langflow_system_prompt,
_update_mcp_server_urls,
)
from api.settings.models import (
AgentConfig,
AnthropicProviderConfig,
DoclingPresetBody,
DoclingPresetResponse,
IngestionDefaultsConfig,
KnowledgeConfig,
OllamaProviderConfig,
OnboardingBody,
OnboardingResponse,
OnboardingStateBody,
OnboardingStateConfig,
OnboardingStateResponse,
OpenAIProviderConfig,
ProvidersConfig,
RefreshOpenRAGDocsResponse,
RollbackBody,
RollbackResponse,
SettingsResponse,
SettingsUpdateBody,
SettingsUpdateResponse,
WatsonXProviderConfig,
)
from config.settings import (
DEFAULT_DOCS_URL,
ENVIRONMENT,
INGEST_SAMPLE_DATA,
LANGFLOW_CHAT_FLOW_ID,
LANGFLOW_INGEST_FLOW_ID,
LANGFLOW_PUBLIC_URL,
LANGFLOW_URL,
LOCALHOST_URL,
OPENRAG_INGEST_VIA_CHAT,
SEGMENT_WRITE_KEY,
clients,
config_manager,
get_openrag_config,
)
from dependencies import (
get_chat_service,
get_current_user,
get_document_service,
get_flows_service,
get_knowledge_filter_service,
get_langflow_file_service,
get_models_service,
get_session_manager,
get_task_service,
require_permission,
)
from services.docling_service import DoclingConfig, get_docling_preset_configs
from session_manager import User
from utils import provider_health_cache
from utils.langflow_utils import LangflowNotReadyError, wait_for_langflow
from utils.logging_config import get_logger
from utils.telemetry import Category, MessageId, TelemetryClient
from utils.version_utils import OPENRAG_VERSION
logger = get_logger(__name__)
async def get_settings(
request: Request,
session_manager=Depends(get_session_manager),
user: User = Depends(get_current_user),
) -> SettingsResponse:
"""Get application settings"""
try:
openrag_config = get_openrag_config()
knowledge_config = openrag_config.knowledge
agent_config = openrag_config.agent
# Only expose edit URLs when a public URL is configured
langflow_edit_url = None
if LANGFLOW_PUBLIC_URL and LANGFLOW_CHAT_FLOW_ID:
langflow_edit_url = f"{LANGFLOW_PUBLIC_URL.rstrip('/')}/flow/{LANGFLOW_CHAT_FLOW_ID}"
langflow_ingest_edit_url = None
if LANGFLOW_PUBLIC_URL and LANGFLOW_INGEST_FLOW_ID:
langflow_ingest_edit_url = (
f"{LANGFLOW_PUBLIC_URL.rstrip('/')}/flow/{LANGFLOW_INGEST_FLOW_ID}"
)
ingestion_defaults_obj = None
# Fetch ingestion flow configuration to get actual component defaults
if LANGFLOW_INGEST_FLOW_ID and openrag_config.edited:
try:
response = await clients.langflow_request(
"GET", f"/api/v1/flows/{LANGFLOW_INGEST_FLOW_ID}"
)
if response.status_code == 200:
flow_data = response.json()
# Extract component defaults (ingestion-specific settings only)
# Start with configured defaults
ingestion_defaults = {
"chunkSize": knowledge_config.chunk_size,
"chunkOverlap": knowledge_config.chunk_overlap,
"separator": "\\n", # Keep hardcoded for now as it's not in config
"embeddingModel": knowledge_config.embedding_model,
}
if flow_data.get("data", {}).get("nodes"):
for node in flow_data["data"]["nodes"]:
node_template = node.get("data", {}).get("node", {}).get("template", {})
# Split Text component (SplitText-QIKhg)
if node.get("id") == "SplitText-QIKhg":
if node_template.get("chunk_size", {}).get("value"):
ingestion_defaults["chunkSize"] = node_template["chunk_size"][
"value"
]
if node_template.get("chunk_overlap", {}).get("value"):
ingestion_defaults["chunkOverlap"] = node_template[
"chunk_overlap"
]["value"]
if node_template.get("separator", {}).get("value"):
ingestion_defaults["separator"] = node_template["separator"][
"value"
]
# OpenAI Embeddings component (OpenAIEmbeddings-joRJ6)
elif node.get("id") == "OpenAIEmbeddings-joRJ6":
if node_template.get("model", {}).get("value"):
ingestion_defaults["embeddingModel"] = node_template["model"][
"value"
]
ingestion_defaults_obj = IngestionDefaultsConfig(**ingestion_defaults)
except Exception as e:
logger.warning(f"Failed to fetch ingestion flow defaults: {e}")
# Continue without ingestion defaults
return SettingsResponse(
langflow_url=LANGFLOW_URL,
flow_id=LANGFLOW_CHAT_FLOW_ID,
ingest_flow_id=LANGFLOW_INGEST_FLOW_ID,
langflow_public_url=LANGFLOW_PUBLIC_URL,
edited=openrag_config.edited,
onboarding=OnboardingStateConfig(
current_step=openrag_config.onboarding.current_step,
assistant_message=openrag_config.onboarding.assistant_message,
selected_nudge=openrag_config.onboarding.selected_nudge,
card_steps=openrag_config.onboarding.card_steps,
upload_steps=openrag_config.onboarding.upload_steps,
openrag_docs_filter_id=openrag_config.onboarding.openrag_docs_filter_id,
user_doc_filter_id=openrag_config.onboarding.user_doc_filter_id,
openrag_docs_ingested_version=openrag_config.onboarding.openrag_docs_ingested_version,
openrag_docs_remote_signature=openrag_config.onboarding.openrag_docs_remote_signature,
),
providers=ProvidersConfig(
openai=OpenAIProviderConfig(
has_api_key=bool(openrag_config.providers.openai.api_key),
configured=openrag_config.providers.openai.configured,
),
anthropic=AnthropicProviderConfig(
has_api_key=bool(openrag_config.providers.anthropic.api_key),
configured=openrag_config.providers.anthropic.configured,
),
watsonx=WatsonXProviderConfig(
has_api_key=bool(openrag_config.providers.watsonx.api_key),
endpoint=openrag_config.providers.watsonx.endpoint or None,
project_id=openrag_config.providers.watsonx.project_id or None,
configured=openrag_config.providers.watsonx.configured,
),
ollama=OllamaProviderConfig(
endpoint=openrag_config.providers.ollama.endpoint or None,
configured=openrag_config.providers.ollama.configured,
),
),
knowledge=KnowledgeConfig(
embedding_model=knowledge_config.embedding_model,
embedding_provider=knowledge_config.embedding_provider,
chunk_size=knowledge_config.chunk_size,
chunk_overlap=knowledge_config.chunk_overlap,
table_structure=knowledge_config.table_structure,
ocr=knowledge_config.ocr,
picture_descriptions=knowledge_config.picture_descriptions,
index_name=knowledge_config.index_name,
disable_ingest_with_langflow=knowledge_config.disable_ingest_with_langflow,
),
agent=AgentConfig(
llm_model=agent_config.llm_model,
llm_provider=agent_config.llm_provider,
system_prompt=agent_config.system_prompt,
),
localhost_url=LOCALHOST_URL,
langflow_edit_url=langflow_edit_url,
langflow_ingest_edit_url=langflow_ingest_edit_url,
ingestion_defaults=ingestion_defaults_obj,
ingest_via_chat=OPENRAG_INGEST_VIA_CHAT,
segment_write_key=SEGMENT_WRITE_KEY or None,
environment=ENVIRONMENT or None,
)
except Exception as e:
logger.error(f"Failed to retrieve settings: {str(e)}")
return JSONResponse({"error": f"Failed to retrieve settings: {str(e)}"}, status_code=500)
async def update_settings(
body: SettingsUpdateBody,
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("config:write")),
models_service=Depends(get_models_service),
) -> SettingsUpdateResponse:
"""Update settings in configuration"""
try:
# Get current configuration
current_config = get_openrag_config()
# Check if config is marked as edited
if not current_config.edited:
return JSONResponse(
{"error": "Configuration must be marked as edited before updates are allowed"},
status_code=403,
)
# Validate provider setup if provider-related fields are being updated
# Do this BEFORE modifying any config
provider_fields = [
"llm_provider",
"embedding_provider",
"llm_model",
"embedding_model",
"openai_api_key",
"anthropic_api_key",
"watsonx_api_key",
"watsonx_endpoint",
"watsonx_project_id",
"ollama_endpoint",
]
should_validate = any(getattr(body, field) is not None for field in provider_fields)
if should_validate:
try:
logger.info("Running provider validation before modifying config")
# Validate LLM provider if being changed
if body.llm_provider is not None or body.llm_model is not None:
llm_provider = (
body.llm_provider
if body.llm_provider is not None
else current_config.agent.llm_provider
)
llm_model = (
body.llm_model
if body.llm_model is not None
else current_config.agent.llm_model
)
# Get the provider config (with any updates from the request)
llm_provider_config = current_config.providers.get_provider_config(llm_provider)
# Apply any updates from the request
api_key = getattr(llm_provider_config, "api_key", None)
endpoint = getattr(llm_provider_config, "endpoint", None)
project_id = getattr(llm_provider_config, "project_id", None)
if (
getattr(body, f"{llm_provider}_api_key", None) is not None
and getattr(body, f"{llm_provider}_api_key", None).strip()
):
api_key = getattr(body, f"{llm_provider}_api_key", None)
if getattr(body, f"{llm_provider}_endpoint", None) is not None:
endpoint = getattr(body, f"{llm_provider}_endpoint", None)
if getattr(body, f"{llm_provider}_project_id", None) is not None:
project_id = getattr(body, f"{llm_provider}_project_id", None)
await validate_provider_setup(
provider=llm_provider,
api_key=api_key,
llm_model=llm_model,
endpoint=endpoint,
project_id=project_id,
)
logger.info(f"LLM provider validation successful for {llm_provider}")
# Validate embedding provider if being changed
if body.embedding_provider is not None or body.embedding_model is not None:
embedding_provider = (
body.embedding_provider
if body.embedding_provider is not None
else current_config.knowledge.embedding_provider
)
embedding_model = (
body.embedding_model
if body.embedding_model is not None
else current_config.knowledge.embedding_model
)
# Get the provider config (with any updates from the request)
embedding_provider_config = current_config.providers.get_provider_config(
embedding_provider
)
# Apply any updates from the request
api_key = getattr(embedding_provider_config, "api_key", None)
endpoint = getattr(embedding_provider_config, "endpoint", None)
project_id = getattr(embedding_provider_config, "project_id", None)
if (
getattr(body, f"{embedding_provider}_api_key", None) is not None
and getattr(body, f"{embedding_provider}_api_key", None).strip()
):
api_key = getattr(body, f"{embedding_provider}_api_key", None)
if getattr(body, f"{embedding_provider}_endpoint", None) is not None:
endpoint = getattr(body, f"{embedding_provider}_endpoint", None)
if getattr(body, f"{embedding_provider}_project_id", None) is not None:
project_id = getattr(body, f"{embedding_provider}_project_id", None)
await validate_provider_setup(
provider=embedding_provider,
api_key=api_key,
embedding_model=embedding_model,
endpoint=endpoint,
project_id=project_id,
)
logger.info(
f"Embedding provider validation successful for {embedding_provider}"
)
except Exception as e:
logger.error(f"Provider validation failed: {str(e)}")
return JSONResponse({"error": f"{str(e)}"}, status_code=400)
# Update configuration
# Only reached if validation passed or wasn't needed
config_updated = False
# Update agent settings
if body.llm_model is not None:
old_model = current_config.agent.llm_model
current_config.agent.llm_model = body.llm_model
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_LLM_MODEL
)
logger.info(f"LLM model changed from {old_model} to {body.llm_model}")
if body.llm_provider is not None:
old_provider = current_config.agent.llm_provider
current_config.agent.llm_provider = body.llm_provider
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_LLM_PROVIDER
)
logger.info(f"LLM provider changed from {old_provider} to {body.llm_provider}")
if body.system_prompt is not None:
current_config.agent.system_prompt = body.system_prompt
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_SYSTEM_PROMPT
)
# Also update the chat flow with the new system prompt
try:
flows_service = _get_flows_service()
await _update_langflow_system_prompt(current_config, flows_service)
except Exception as e:
logger.error(f"Failed to update chat flow system prompt: {str(e)}")
# Don't fail the entire settings update if flow update fails
# The config will still be saved
# Update knowledge settings
if body.embedding_model is not None:
old_model = current_config.knowledge.embedding_model
new_embedding_model = body.embedding_model.strip()
current_config.knowledge.embedding_model = new_embedding_model
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_EMBED_MODEL
)
logger.info(f"Embedding model changed from {old_model} to {new_embedding_model}")
if body.embedding_provider is not None:
old_provider = current_config.knowledge.embedding_provider
current_config.knowledge.embedding_provider = body.embedding_provider
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_EMBED_PROVIDER
)
logger.info(
f"Embedding provider changed from {old_provider} to {body.embedding_provider}"
)
if body.table_structure is not None:
current_config.knowledge.table_structure = body.table_structure
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_DOCLING_UPDATED
)
# Also update the flow with the new docling settings
try:
flows_service = _get_flows_service()
await _update_langflow_docling_settings(current_config, flows_service)
except Exception as e:
logger.error(f"Failed to update docling settings in flow: {str(e)}")
if body.ocr is not None:
current_config.knowledge.ocr = body.ocr
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_DOCLING_UPDATED
)
# Also update the flow with the new docling settings
try:
flows_service = _get_flows_service()
await _update_langflow_docling_settings(current_config, flows_service)
except Exception as e:
logger.error(f"Failed to update docling settings in flow: {str(e)}")
if body.picture_descriptions is not None:
current_config.knowledge.picture_descriptions = body.picture_descriptions
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_DOCLING_UPDATED
)
# Also update the flow with the new docling settings
try:
flows_service = _get_flows_service()
await _update_langflow_docling_settings(current_config, flows_service)
except Exception as e:
logger.error(f"Failed to update docling settings in flow: {str(e)}")
if body.disable_ingest_with_langflow is not None:
current_config.knowledge.disable_ingest_with_langflow = (
body.disable_ingest_with_langflow
)
config_updated = True
logger.info(
f"Disable Langflow ingestion changed to {body.disable_ingest_with_langflow}"
)
if body.chunk_size is not None:
effective_overlap = (
body.chunk_overlap
if body.chunk_overlap is not None
else current_config.knowledge.chunk_overlap
)
if effective_overlap >= body.chunk_size:
raise HTTPException(
status_code=422, detail="chunk_overlap must be less than chunk_size"
)
current_config.knowledge.chunk_size = body.chunk_size
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_CHUNK_UPDATED
)
# Also update the ingest flow with the new chunk size
try:
flows_service = _get_flows_service()
await flows_service.update_ingest_flow_chunk_size(body.chunk_size)
logger.info(f"Successfully updated ingest flow chunk size to {body.chunk_size}")
except Exception as e:
logger.error(f"Failed to update ingest flow chunk size: {str(e)}")
# Don't fail the entire settings update if flow update fails
# The config will still be saved
if body.chunk_overlap is not None:
effective_chunk_size = (
body.chunk_size
if body.chunk_size is not None
else current_config.knowledge.chunk_size
)
if body.chunk_overlap >= effective_chunk_size:
raise HTTPException(
status_code=422, detail="chunk_overlap must be less than chunk_size"
)
current_config.knowledge.chunk_overlap = body.chunk_overlap
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_CHUNK_UPDATED
)
# Also update the ingest flow with the new chunk overlap
try:
flows_service = _get_flows_service()
await flows_service.update_ingest_flow_chunk_overlap(body.chunk_overlap)
logger.info(
f"Successfully updated ingest flow chunk overlap to {body.chunk_overlap}"
)
except Exception as e:
logger.error(f"Failed to update ingest flow chunk overlap: {str(e)}")
# Don't fail the entire settings update if flow update fails
if body.index_name is not None:
old_index_name = current_config.knowledge.index_name
new_index_name = body.index_name.strip()
current_config.knowledge.index_name = new_index_name
config_updated = True
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_INDEX_NAME_UPDATED
)
logger.info(f"Index name changed from {old_index_name} to {new_index_name}")
# Also update global variable with new index name
try:
await clients._create_langflow_global_variable(
"OPENSEARCH_INDEX_NAME", new_index_name, modify=True
)
logger.info(
f"Successfully updated global variable with new index name {new_index_name}"
)
except Exception as e:
logger.error(f"Failed to update global variable with new index name: {str(e)}")
# Don't fail the entire settings update if flow update fails
# The config will still be saved
# Update provider-specific settings
provider_updated = False
if body.openai_api_key is not None and body.openai_api_key.strip():
current_config.providers.openai.api_key = body.openai_api_key.strip()
current_config.providers.openai.configured = True
config_updated = True
provider_updated = True
if body.anthropic_api_key is not None and body.anthropic_api_key.strip():
current_config.providers.anthropic.api_key = body.anthropic_api_key
current_config.providers.anthropic.configured = True
config_updated = True
provider_updated = True
if body.watsonx_api_key is not None and body.watsonx_api_key.strip():
current_config.providers.watsonx.api_key = body.watsonx_api_key
current_config.providers.watsonx.configured = True
config_updated = True
provider_updated = True
if body.watsonx_endpoint is not None:
current_config.providers.watsonx.endpoint = body.watsonx_endpoint.strip()
current_config.providers.watsonx.configured = True
config_updated = True
provider_updated = True
if body.watsonx_project_id is not None:
current_config.providers.watsonx.project_id = body.watsonx_project_id.strip()
current_config.providers.watsonx.configured = True
config_updated = True
provider_updated = True
if body.ollama_endpoint is not None:
current_config.providers.ollama.endpoint = body.ollama_endpoint.strip()
current_config.providers.ollama.configured = True
config_updated = True
provider_updated = True
if body.remove_ollama_config:
other_providers_configured = (
current_config.providers.openai.configured
or current_config.providers.anthropic.configured
or current_config.providers.watsonx.configured
)
if not other_providers_configured:
return JSONResponse(
{
"error": "Cannot remove Ollama configuration: configure another model provider first."
},
status_code=400,
)
if not body.force_remove:
affected = await _affected_embedding_models(
"ollama", session_manager, user, models_service
)
if affected:
return _embedding_conflict_response("Ollama", "ollama", affected)
current_config.providers.ollama.endpoint = ""
current_config.providers.ollama.configured = False
if current_config.agent.llm_provider == "ollama":
current_config.agent.llm_provider = _first_configured_llm_provider(
current_config, "ollama"
)
current_config.agent.llm_model = ""
if current_config.knowledge.embedding_provider == "ollama":
current_config.knowledge.embedding_provider = _first_configured_embedding_provider(
current_config, "ollama"
)
current_config.knowledge.embedding_model = ""
config_updated = True
provider_updated = True
if body.remove_openai_config:
other_providers_configured = (
current_config.providers.anthropic.configured
or current_config.providers.watsonx.configured
or current_config.providers.ollama.configured
)
if not other_providers_configured:
return JSONResponse(
{
"error": "Cannot remove OpenAI configuration: configure another model provider first."
},
status_code=400,
)
if not body.force_remove:
affected = await _affected_embedding_models(
"openai", session_manager, user, models_service
)
if affected:
return _embedding_conflict_response("OpenAI", "openai", affected)
current_config.providers.openai.api_key = ""
current_config.providers.openai.configured = False
if current_config.agent.llm_provider == "openai":
fb = _first_configured_llm_provider(current_config, "openai")
current_config.agent.llm_provider = fb
current_config.agent.llm_model = ""
if current_config.knowledge.embedding_provider == "openai":
fb = _first_configured_embedding_provider(current_config, "openai")
current_config.knowledge.embedding_provider = fb
current_config.knowledge.embedding_model = ""
config_updated = True
provider_updated = True
if body.remove_anthropic_config:
other_providers_configured = (
current_config.providers.openai.configured
or current_config.providers.watsonx.configured
or current_config.providers.ollama.configured
)
if not other_providers_configured:
return JSONResponse(
{
"error": "Cannot remove Anthropic configuration: configure another model provider first."
},
status_code=400,
)
current_config.providers.anthropic.api_key = ""
current_config.providers.anthropic.configured = False
if current_config.agent.llm_provider == "anthropic":
fb = _first_configured_llm_provider(current_config, "anthropic")
current_config.agent.llm_provider = fb
current_config.agent.llm_model = ""
# Anthropic is not a valid embedding provider; no embedding reset needed
config_updated = True
provider_updated = True
if body.remove_watsonx_config:
other_providers_configured = (
current_config.providers.openai.configured
or current_config.providers.anthropic.configured
or current_config.providers.ollama.configured
)
if not other_providers_configured:
return JSONResponse(
{
"error": "Cannot remove IBM watsonx.ai configuration: configure another model provider first."
},
status_code=400,
)
if not body.force_remove:
affected = await _affected_embedding_models(
"watsonx", session_manager, user, models_service
)
if affected:
return _embedding_conflict_response("IBM watsonx.ai", "watsonx", affected)
current_config.providers.watsonx.api_key = ""
current_config.providers.watsonx.endpoint = ""
current_config.providers.watsonx.project_id = ""
current_config.providers.watsonx.configured = False
if current_config.agent.llm_provider == "watsonx":
fb = _first_configured_llm_provider(current_config, "watsonx")
current_config.agent.llm_provider = fb
current_config.agent.llm_model = ""
if current_config.knowledge.embedding_provider == "watsonx":
fb = _first_configured_embedding_provider(current_config, "watsonx")
current_config.knowledge.embedding_provider = fb
current_config.knowledge.embedding_model = ""
config_updated = True
provider_updated = True
if provider_updated:
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_PROVIDER_CREDS
)
if not config_updated:
return JSONResponse({"error": "No valid fields provided for update"}, status_code=400)
# Save the updated configuration
if not config_manager.save_config_file(current_config):
return JSONResponse({"error": "Failed to save configuration"}, status_code=500)
provider_health_cache.invalidate()
# Refresh patched client immediately so subsequent requests pick up latest config.
await clients.refresh_patched_client()
# Run expensive Langflow sync in the background to keep settings updates responsive.
if should_validate or provider_updated:
task = asyncio.create_task(
_run_async_post_save_langflow_updates(
session_manager=session_manager,
models_service=models_service if provider_updated else None,
update_mcp_servers=(
body.embedding_provider is not None
or body.embedding_model is not None
or provider_updated
),
update_model_values=(
body.llm_provider is not None
or body.llm_model is not None
or body.embedding_provider is not None
or body.embedding_model is not None
or provider_updated
),
)
)
# Keep a strong reference until completion to avoid premature GC cancellation.
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
set_fields = [k for k, v in body.model_dump().items() if v is not None]
logger.info("Configuration updated successfully", updated_fields=set_fields)
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_UPDATED
)
return SettingsUpdateResponse(message="Configuration updated successfully")
except Exception as e:
logger.error("Failed to update settings", error=str(e))
await TelemetryClient.send_event(
Category.SETTINGS_OPERATIONS, MessageId.ORB_SETTINGS_UPDATE_FAILED
)
return JSONResponse({"error": f"Failed to update settings: {str(e)}"}, status_code=500)
async def onboarding(
body: OnboardingBody,
flows_service=Depends(get_flows_service),
session_manager=Depends(get_session_manager),
document_service=Depends(get_document_service),
models_service=Depends(get_models_service),
task_service=Depends(get_task_service),
langflow_file_service=Depends(get_langflow_file_service),
knowledge_filter_service=Depends(get_knowledge_filter_service),
user: User = Depends(require_permission("config:write")),
) -> OnboardingResponse:
"""Handle onboarding configuration setup"""
try:
await TelemetryClient.send_event(Category.ONBOARDING, MessageId.ORB_ONBOARD_START)
# Get current configuration
current_config = get_openrag_config()
# Warn if config was already edited (onboarding being re-run)
if current_config.edited:
logger.warning(
"Onboarding is being run although configuration was already edited before"
)
# Update configuration
config_updated = False
# Update agent settings (LLM)
llm_model_selected = None
llm_provider_selected = None
if body.llm_model:
llm_model_selected = body.llm_model.strip()
current_config.agent.llm_model = llm_model_selected
config_updated = True
await TelemetryClient.send_event(
Category.ONBOARDING,
MessageId.ORB_ONBOARD_LLM_MODEL,
metadata={"llm_model": llm_model_selected},
)
logger.info(f"LLM model selected during onboarding: {llm_model_selected}")
if body.llm_provider:
llm_provider_selected = body.llm_provider.strip()
current_config.agent.llm_provider = llm_provider_selected
config_updated = True
await TelemetryClient.send_event(
Category.ONBOARDING,
MessageId.ORB_ONBOARD_LLM_PROVIDER,
metadata={"llm_provider": llm_provider_selected},
)
logger.info(f"LLM provider selected during onboarding: {llm_provider_selected}")
# Update knowledge settings (embedding)
embedding_model_selected = None
embedding_provider_selected = None
if body.embedding_model:
embedding_model_selected = body.embedding_model.strip()
current_config.knowledge.embedding_model = embedding_model_selected
config_updated = True
await TelemetryClient.send_event(
Category.ONBOARDING,
MessageId.ORB_ONBOARD_EMBED_MODEL,
metadata={"embedding_model": embedding_model_selected},
)
logger.info(f"Embedding model selected during onboarding: {embedding_model_selected}")
if body.embedding_provider:
embedding_provider_selected = body.embedding_provider.strip()
current_config.knowledge.embedding_provider = embedding_provider_selected
config_updated = True
await TelemetryClient.send_event(
Category.ONBOARDING,
MessageId.ORB_ONBOARD_EMBED_PROVIDER,
metadata={"embedding_provider": embedding_provider_selected},
)
logger.info(
f"Embedding provider selected during onboarding: {embedding_provider_selected}"
)
# Update provider-specific credentials
if body.openai_api_key:
current_config.providers.openai.api_key = body.openai_api_key.strip()
current_config.providers.openai.configured = True
config_updated = True
if body.anthropic_api_key:
current_config.providers.anthropic.api_key = body.anthropic_api_key.strip()
current_config.providers.anthropic.configured = True
config_updated = True
if body.watsonx_api_key:
current_config.providers.watsonx.api_key = body.watsonx_api_key.strip()
current_config.providers.watsonx.configured = True
config_updated = True
if body.watsonx_endpoint:
current_config.providers.watsonx.endpoint = body.watsonx_endpoint.strip()
current_config.providers.watsonx.configured = True
config_updated = True
if body.watsonx_project_id:
current_config.providers.watsonx.project_id = body.watsonx_project_id.strip()
current_config.providers.watsonx.configured = True
config_updated = True
if body.ollama_endpoint:
current_config.providers.ollama.endpoint = body.ollama_endpoint.strip()
current_config.providers.ollama.configured = True
config_updated = True
# Mark providers as configured if they were chosen during onboarding
# Check LLM provider
if body.llm_provider:
llm_provider = body.llm_provider.strip().lower()
if llm_provider == "openai" and current_config.providers.openai.api_key:
current_config.providers.openai.configured = True
logger.info("Marked OpenAI as configured (chosen as LLM provider)")
elif llm_provider == "anthropic" and current_config.providers.anthropic.api_key:
current_config.providers.anthropic.configured = True
logger.info("Marked Anthropic as configured (chosen as LLM provider)")
elif (
llm_provider == "watsonx"
and current_config.providers.watsonx.api_key
and current_config.providers.watsonx.endpoint
and current_config.providers.watsonx.project_id
):
current_config.providers.watsonx.configured = True
logger.info("Marked WatsonX as configured (chosen as LLM provider)")
elif llm_provider == "ollama" and current_config.providers.ollama.endpoint:
current_config.providers.ollama.configured = True
logger.info("Marked Ollama as configured (chosen as LLM provider)")
# Check embedding provider
if body.embedding_provider:
embedding_provider = body.embedding_provider.strip().lower()
if embedding_provider == "openai" and current_config.providers.openai.api_key:
current_config.providers.openai.configured = True
logger.info("Marked OpenAI as configured (chosen as embedding provider)")
elif (
embedding_provider == "watsonx"
and current_config.providers.watsonx.api_key
and current_config.providers.watsonx.endpoint
and current_config.providers.watsonx.project_id
):
current_config.providers.watsonx.configured = True
logger.info("Marked WatsonX as configured (chosen as embedding provider)")
elif embedding_provider == "ollama" and current_config.providers.ollama.endpoint:
current_config.providers.ollama.configured = True
logger.info("Marked Ollama as configured (chosen as embedding provider)")
should_ingest_sample_data = INGEST_SAMPLE_DATA
if should_ingest_sample_data:
await TelemetryClient.send_event(Category.ONBOARDING, MessageId.ORB_ONBOARD_SAMPLE_DATA)
logger.info("Sample data ingestion enabled via environment variable")
if not config_updated:
return JSONResponse({"error": "No valid fields provided for update"}, status_code=400)
# Validate provider setup before initializing OpenSearch index
# Use full validation with completion tests (test_completion=True) to ensure provider health during onboarding
try:
# Validate LLM provider if set
if body.llm_provider or body.llm_model:
llm_provider = current_config.agent.llm_provider.lower()
llm_provider_config = current_config.get_llm_provider_config()
logger.info(
f"Validating LLM provider setup for {llm_provider} (full validation with completion test)"
)
await validate_provider_setup(
provider=llm_provider,
api_key=getattr(llm_provider_config, "api_key", None),
llm_model=current_config.agent.llm_model,
endpoint=getattr(llm_provider_config, "endpoint", None),
project_id=getattr(llm_provider_config, "project_id", None),
test_completion=True, # Full validation with completion test - ensures provider health
)
logger.info(
f"LLM provider setup validation completed successfully for {llm_provider}"
)
# Validate embedding provider if set
if body.embedding_provider or body.embedding_model:
embedding_provider = current_config.knowledge.embedding_provider.lower()
embedding_provider_config = current_config.get_embedding_provider_config()
logger.info(
f"Validating embedding provider setup for {embedding_provider} (full validation with completion test)"
)
await validate_provider_setup(
provider=embedding_provider,
api_key=getattr(embedding_provider_config, "api_key", None),
embedding_model=current_config.knowledge.embedding_model,
endpoint=getattr(embedding_provider_config, "endpoint", None),
project_id=getattr(embedding_provider_config, "project_id", None),
test_completion=True, # Full validation with completion test - ensures provider health
)
logger.info(
f"Embedding provider setup validation completed successfully for {embedding_provider}"
)
except Exception as e:
logger.error(f"Provider validation failed: {str(e)}")
return JSONResponse(
{"error": str(e)},
status_code=400,
)
# Ensure the Langflow service is ready before attempting to configure it
try:
await wait_for_langflow()
except LangflowNotReadyError as e:
message: str = "Aborted the Langflow service configuration process. The Langflow service is not ready."
logger.error(message, error=str(e))
return JSONResponse(
{"error": message},
status_code=503,
)
# Set Langflow global variables and model values based on provider configuration
try:
# Check if any provider-related fields were provided
provider_fields_provided = any(
[
body.openai_api_key,
body.anthropic_api_key,
body.watsonx_api_key,
body.watsonx_endpoint,
body.watsonx_project_id,
body.ollama_endpoint,
]
)