-
Notifications
You must be signed in to change notification settings - Fork 9.8k
Expand file tree
/
Copy pathsetup.py
More file actions
1603 lines (1386 loc) · 70.6 KB
/
Copy pathsetup.py
File metadata and controls
1603 lines (1386 loc) · 70.6 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
import asyncio
import copy
import io
import json
import re
import shutil
import zipfile
from collections import defaultdict
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import AnyStr
from uuid import UUID
import aiofiles
import anyio
import httpx
import orjson
import sqlalchemy as sa
from emoji import demojize, purely_emoji
from lfx.base.constants import (
FIELD_FORMAT_ATTRIBUTES,
NODE_FORMAT_ATTRIBUTES,
ORJSON_OPTIONS,
SKIPPED_COMPONENTS,
SKIPPED_FIELD_ATTRIBUTES,
)
from lfx.log.logger import logger
from lfx.template.field.prompt import DEFAULT_PROMPT_INTUT_TYPES
from lfx.utils.component_aliases import flatten_components_with_aliases
from lfx.utils.util import escape_json_dump
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import selectinload
from sqlmodel import col, select
from sqlmodel.ext.asyncio.session import AsyncSession
from langflow.initial_setup.constants import (
ASSISTANT_FOLDER_DESCRIPTION,
ASSISTANT_FOLDER_NAME,
STARTER_FOLDER_DESCRIPTION,
STARTER_FOLDER_NAME,
)
from langflow.services.database.models.flow.model import Flow, FlowCreate
from langflow.services.database.models.folder.constants import (
DEFAULT_FOLDER_DESCRIPTION,
DEFAULT_FOLDER_NAME,
LEGACY_FOLDER_NAMES,
)
from langflow.services.database.models.folder.model import Folder, FolderCreate, FolderRead
from langflow.services.deps import (
get_settings_service,
get_storage_service,
get_variable_service,
session_scope,
)
# In the folder ./starter_projects we have a few JSON files that represent
# starter projects. We want to load these into the database so that users
# can use them as a starting point for their own projects.
# Extension components are loaded under the runtime-only ``_lfx_ext.*``
# sys.modules namespace, so the live template's ``metadata.module`` is not an
# importable path outside a running extension loader. Persisted starter
# projects must keep the stable legacy path (``lfx.components.<provider>...``,
# importable via the bundle shims) -- it is what the migration table and the
# template tests resolve.
_RUNTIME_EXT_MODULE_PREFIX = "_lfx_ext."
def _merge_node_metadata(current_metadata, latest_metadata):
"""Return the latest metadata, preserving a stored importable ``module`` path.
When the live template carries a runtime ``_lfx_ext.*`` module (an ext
component) and the node already has a module value, keep the node's --
otherwise persisting the runtime namespace breaks every consumer that
imports the path.
"""
if not isinstance(latest_metadata, dict):
return latest_metadata
latest_module = latest_metadata.get("module")
current_module = current_metadata.get("module") if isinstance(current_metadata, dict) else None
if isinstance(latest_module, str) and latest_module.startswith(_RUNTIME_EXT_MODULE_PREFIX) and current_module:
merged = deepcopy(latest_metadata)
merged["module"] = current_module
return merged
return latest_metadata
def update_projects_components_with_latest_component_versions(project_data, all_types_dict):
all_types_dict_flat = flatten_components_with_aliases(all_types_dict)
node_changes_log = defaultdict(list)
project_data_copy = deepcopy(project_data)
for node in project_data_copy.get("nodes", []):
node_data = node.get("data").get("node")
node_type = node.get("data").get("type")
if node_type in all_types_dict_flat:
latest_node = all_types_dict_flat.get(node_type)
latest_template = latest_node.get("template")
node_data["template"]["code"] = deepcopy(latest_template["code"])
# Sync field_order so the UI renders fields in the correct order
latest_field_order = latest_node.get("field_order")
if latest_field_order is not None:
node_data["field_order"] = latest_field_order
# skip components that are having dynamic values that need to be persisted for templates
if node_type in SKIPPED_COMPONENTS:
continue
is_tool_or_agent = node_data.get("tool_mode", False) or node_data.get("key") in {
"Agent",
"LanguageModelComponent",
"TypeConverterComponent",
}
has_tool_outputs = any(output.get("types") == ["Tool"] for output in node_data.get("outputs", []))
if "outputs" in latest_node and not has_tool_outputs and not is_tool_or_agent:
# Deep copy to avoid mutating the shared latest_node template across flows
new_outputs = deepcopy(latest_node["outputs"])
# Set selected output as the previous selected output with type migration support
type_migrations = {
"Data": "JSON",
"DataFrame": "Table",
}
for output in new_outputs:
node_data_output = next(
(output_ for output_ in node_data["outputs"] if output_["name"] == output["name"]),
None,
)
if node_data_output:
old_selected = node_data_output.get("selected")
if old_selected:
# Old flows may use Data/DataFrame; map to JSON/Table for backward compatibility
migrated_selected = type_migrations.get(old_selected, old_selected)
if migrated_selected in output.get("types", []):
output["selected"] = migrated_selected
node_data["outputs"] = new_outputs
if node_data["template"]["_type"] != latest_template["_type"]:
node_data["template"]["_type"] = latest_template["_type"]
if node_type != "Prompt":
node_data["template"] = deepcopy(latest_template)
else:
for key, value in latest_template.items():
if key not in node_data["template"]:
node_changes_log[node_type].append(
{
"attr": key,
"old_value": None,
"new_value": value,
}
)
node_data["template"][key] = deepcopy(value)
elif isinstance(value, dict) and value.get("value"):
node_changes_log[node_type].append(
{
"attr": key,
"old_value": node_data["template"][key],
"new_value": value,
}
)
node_data["template"][key]["value"] = value["value"]
for key in node_data["template"]:
if key not in latest_template:
node_data["template"][key]["input_types"] = DEFAULT_PROMPT_INTUT_TYPES
node_changes_log[node_type].append(
{
"attr": "_type",
"old_value": node_data["template"]["_type"],
"new_value": latest_template["_type"],
}
)
else:
for attr in NODE_FORMAT_ATTRIBUTES:
latest_attr_value = latest_node.get(attr)
current_attr_value = node_data.get(attr)
if attr == "metadata":
latest_attr_value = _merge_node_metadata(current_attr_value, latest_attr_value)
if (
attr in latest_node
# Check if it needs to be updated
and latest_attr_value != current_attr_value
):
node_changes_log[node_type].append(
{
"attr": attr,
"old_value": current_attr_value,
"new_value": latest_attr_value,
}
)
node_data[attr] = deepcopy(latest_attr_value)
for field_name, field_dict in latest_template.items():
if field_name not in node_data["template"]:
node_data["template"][field_name] = deepcopy(field_dict)
continue
# The idea here is to update some attributes of the field
to_check_attributes = FIELD_FORMAT_ATTRIBUTES
# Skip specific field attributes that should respect the starter project template values.
# Currently we skip 'advanced' so that a field marked as advanced in the component code
# will NOT overwrite the value specified in the starter project template. This preserves
# the intended UX configuration of the starter projects.
# SKIPPED_FIELD_ATTRIBUTES = {"advanced"}
# Iterate through the attributes we want to potentially update
for attr in to_check_attributes:
# Respect the template value by not updating if the attribute is in the skipped set
if attr in SKIPPED_FIELD_ATTRIBUTES:
continue
if (
attr in field_dict
and attr in node_data["template"].get(field_name)
# Check if it needs to be updated
and field_dict[attr] != node_data["template"][field_name][attr]
):
node_changes_log[node_type].append(
{
"attr": f"{field_name}.{attr}",
"old_value": node_data["template"][field_name][attr],
"new_value": field_dict[attr],
}
)
node_data["template"][field_name][attr] = deepcopy(field_dict[attr])
# Remove fields that are not in the latest template
if node_type != "Prompt":
for field_name in list(node_data["template"].keys()):
is_tool_mode_and_field_is_tools_metadata = (
node_data.get("tool_mode", False) and field_name == "tools_metadata"
)
if field_name not in latest_template and not is_tool_mode_and_field_is_tools_metadata:
node_data["template"].pop(field_name)
log_node_changes(node_changes_log)
return project_data_copy
def scape_json_parse(json_string: str) -> dict:
if json_string is None:
return {}
if isinstance(json_string, dict):
return json_string
parsed_string = json_string.replace("œ", '"')
return json.loads(parsed_string)
def update_new_output(data):
nodes = copy.deepcopy(data["nodes"])
edges = copy.deepcopy(data["edges"])
for edge in edges:
if "sourceHandle" in edge and "targetHandle" in edge:
new_source_handle = scape_json_parse(edge["sourceHandle"])
new_target_handle = scape_json_parse(edge["targetHandle"])
id_ = new_source_handle["id"]
source_node_index = next((index for (index, d) in enumerate(nodes) if d["id"] == id_), -1)
source_node = nodes[source_node_index] if source_node_index != -1 else None
if "baseClasses" in new_source_handle:
if "output_types" not in new_source_handle:
if source_node and "node" in source_node["data"] and "output_types" in source_node["data"]["node"]:
new_source_handle["output_types"] = source_node["data"]["node"]["output_types"]
else:
new_source_handle["output_types"] = new_source_handle["baseClasses"]
del new_source_handle["baseClasses"]
if new_target_handle.get("inputTypes"):
intersection = [
type_ for type_ in new_source_handle["output_types"] if type_ in new_target_handle["inputTypes"]
]
else:
intersection = [
type_ for type_ in new_source_handle["output_types"] if type_ == new_target_handle["type"]
]
selected = intersection[0] if intersection else None
if "name" not in new_source_handle:
new_source_handle["name"] = " | ".join(new_source_handle["output_types"])
new_source_handle["output_types"] = [selected] if selected else []
if source_node and not source_node["data"]["node"].get("outputs"):
if "outputs" not in source_node["data"]["node"]:
source_node["data"]["node"]["outputs"] = []
types = source_node["data"]["node"].get(
"output_types", source_node["data"]["node"].get("base_classes", [])
)
if not any(output.get("selected") == selected for output in source_node["data"]["node"]["outputs"]):
source_node["data"]["node"]["outputs"].append(
{
"types": types,
"selected": selected,
"name": " | ".join(types),
"display_name": " | ".join(types),
}
)
deduplicated_outputs = []
if source_node is None:
source_node = {"data": {"node": {"outputs": []}}}
for output in source_node["data"]["node"]["outputs"]:
if output["name"] not in [d["name"] for d in deduplicated_outputs]:
deduplicated_outputs.append(output)
source_node["data"]["node"]["outputs"] = deduplicated_outputs
edge["sourceHandle"] = escape_json_dump(new_source_handle)
edge["data"]["sourceHandle"] = new_source_handle
edge["data"]["targetHandle"] = new_target_handle
# The above sets the edges but some of the sourceHandles do not have valid name
# which can be found in the nodes. We need to update the sourceHandle with the
# name from node['data']['node']['outputs']
for node in nodes:
if "outputs" in node["data"]["node"]:
for output in node["data"]["node"]["outputs"]:
for edge in edges:
if node["id"] != edge["source"] or output.get("method") is None:
continue
source_handle = scape_json_parse(edge["sourceHandle"])
if source_handle["output_types"] == output.get("types") and source_handle["name"] != output["name"]:
source_handle["name"] = output["name"]
if isinstance(source_handle, str):
source_handle = scape_json_parse(source_handle)
edge["sourceHandle"] = escape_json_dump(source_handle)
edge["data"]["sourceHandle"] = source_handle
data_copy = copy.deepcopy(data)
data_copy["nodes"] = nodes
data_copy["edges"] = edges
return data_copy
def update_edges_with_latest_component_versions(project_data):
"""Update edges in a project with the latest component versions.
This function processes each edge in the project data and ensures that the source and target handles
are updated to match the latest component versions. It tracks all changes made to edges in a log
for debugging purposes.
Args:
project_data (dict): The project data containing nodes and edges to be updated.
Returns:
dict: A deep copy of the project data with updated edges.
The function performs the following operations:
1. Creates a deep copy of the project data to avoid modifying the original
2. For each edge, extracts and parses the source and target handles
3. Finds the corresponding source and target nodes
4. Updates output types in the source handle based on the node's outputs
5. Updates input types in the target handle based on the node's template
6. Escapes and updates the handles in the edge data
7. Logs all changes made to the edges
"""
# Initialize a dictionary to track changes for logging
edge_changes_log = defaultdict(list)
# Create a deep copy to avoid modifying the original data
project_data_copy = deepcopy(project_data)
# Create a mapping of node types to node IDs for node reconciliation
node_type_map = {}
for node in project_data_copy.get("nodes", []):
node_type = node.get("data", {}).get("type", "")
if node_type:
if node_type not in node_type_map:
node_type_map[node_type] = []
node_type_map[node_type].append(node.get("id"))
# Process each edge in the project
for edge in project_data_copy.get("edges", []):
# Extract and parse source and target handles
source_handle = edge.get("data", {}).get("sourceHandle")
source_handle = scape_json_parse(source_handle)
target_handle = edge.get("data", {}).get("targetHandle")
target_handle = scape_json_parse(target_handle)
# Find the corresponding source and target nodes
source_node = next(
(node for node in project_data_copy.get("nodes", []) if node.get("id") == edge.get("source")),
None,
)
target_node = next(
(node for node in project_data_copy.get("nodes", []) if node.get("id") == edge.get("target")),
None,
)
# Try to reconcile missing nodes by type
if source_node is None and source_handle and "dataType" in source_handle:
node_type = source_handle.get("dataType")
if node_type_map.get(node_type):
# Use the first node of matching type as replacement
new_node_id = node_type_map[node_type][0]
logger.info(f"Reconciling missing source node: replacing {edge.get('source')} with {new_node_id}")
# Update edge source
edge["source"] = new_node_id
# Update source handle ID
source_handle["id"] = new_node_id
# Find the new source node
source_node = next(
(node for node in project_data_copy.get("nodes", []) if node.get("id") == new_node_id),
None,
)
# Update edge ID (complex as it contains encoded handles)
# This is a simplified approach - in production you'd need to parse and rebuild the ID
old_id_prefix = edge.get("id", "").split("{")[0]
if old_id_prefix:
new_id_prefix = old_id_prefix.replace(edge.get("source"), new_node_id)
edge["id"] = edge.get("id", "").replace(old_id_prefix, new_id_prefix)
if target_node is None and target_handle and "id" in target_handle:
# Extract node type from target handle ID (e.g., "AstraDBGraph-jr8pY" -> "AstraDBGraph")
id_parts = target_handle.get("id", "").split("-")
if len(id_parts) > 0:
node_type = id_parts[0]
if node_type_map.get(node_type):
# Use the first node of matching type as replacement
new_node_id = node_type_map[node_type][0]
logger.info(f"Reconciling missing target node: replacing {edge.get('target')} with {new_node_id}")
# Update edge target
edge["target"] = new_node_id
# Update target handle ID
target_handle["id"] = new_node_id
# Find the new target node
target_node = next(
(node for node in project_data_copy.get("nodes", []) if node.get("id") == new_node_id),
None,
)
# Update edge ID (simplified approach)
old_id_suffix = edge.get("id", "").split("}-")[1] if "}-" in edge.get("id", "") else ""
if old_id_suffix:
new_id_suffix = old_id_suffix.replace(edge.get("target"), new_node_id)
edge["id"] = edge.get("id", "").replace(old_id_suffix, new_id_suffix)
if source_node and target_node:
# Extract node data for easier access
source_node_data = source_node.get("data", {}).get("node", {})
target_node_data = target_node.get("data", {}).get("node", {})
# Find the output data that matches the source handle name
output_data = next(
(
output
for output in source_node_data.get("outputs", [])
if output.get("name") == source_handle.get("name")
),
None,
)
# If not found by name, try to find by display_name
if not output_data:
output_data = next(
(
output
for output in source_node_data.get("outputs", [])
if output.get("display_name") == source_handle.get("name")
),
None,
)
# Update source handle name if found by display_name
if output_data:
source_handle["name"] = output_data.get("name")
# Determine the new output types based on the output data
# Always prefer "types" over "selected" to ensure we use the current type names (JSON/Table)
# rather than potentially stale "selected" values (Data/DataFrame)
if output_data:
if len(output_data.get("types", [])) == 1:
new_output_types = output_data.get("types", [])
elif len(output_data.get("types", [])) > 1 and output_data.get("selected"):
# Only use "selected" if there are multiple types available
# and selected is present
selected = output_data.get("selected")
# Migrate old type names to new ones
type_migrations = {
"Data": "JSON",
"DataFrame": "Table",
}
migrated_selected = type_migrations.get(selected, selected)
# Verify the migrated selected is in the available types
if migrated_selected in output_data.get("types", []):
new_output_types = [migrated_selected]
else:
# Fallback to first type if selected is invalid
new_output_types = output_data.get("types", [])
else:
new_output_types = output_data.get("types", [])
else:
new_output_types = []
# Update output types if they've changed and log the change
if source_handle.get("output_types", []) != new_output_types:
edge_changes_log[source_node_data.get("display_name", "unknown")].append(
{
"attr": "output_types",
"old_value": source_handle.get("output_types", []),
"new_value": new_output_types,
}
)
source_handle["output_types"] = new_output_types
# Update input types if they've changed and log the change
field_name = target_handle.get("fieldName")
if field_name in target_node_data.get("template", {}) and target_handle.get(
"inputTypes", []
) != target_node_data.get("template", {}).get(field_name, {}).get("input_types", []):
edge_changes_log[target_node_data.get("display_name", "unknown")].append(
{
"attr": "inputTypes",
"old_value": target_handle.get("inputTypes", []),
"new_value": target_node_data.get("template", {}).get(field_name, {}).get("input_types", []),
}
)
target_handle["inputTypes"] = (
target_node_data.get("template", {}).get(field_name, {}).get("input_types", [])
)
# Escape the updated handles for JSON storage
escaped_source_handle = escape_json_dump(source_handle)
escaped_target_handle = escape_json_dump(target_handle)
# Try to parse and escape the old handles for comparison
try:
old_escape_source_handle = escape_json_dump(json.loads(edge.get("sourceHandle", "{}")))
except (json.JSONDecodeError, TypeError):
old_escape_source_handle = edge.get("sourceHandle", "")
try:
old_escape_target_handle = escape_json_dump(json.loads(edge.get("targetHandle", "{}")))
except (json.JSONDecodeError, TypeError):
old_escape_target_handle = edge.get("targetHandle", "")
# Update source handle if it's changed and log the change
if old_escape_source_handle != escaped_source_handle:
edge_changes_log[source_node_data.get("display_name", "unknown")].append(
{
"attr": "sourceHandle",
"old_value": old_escape_source_handle,
"new_value": escaped_source_handle,
}
)
edge["sourceHandle"] = escaped_source_handle
if "data" in edge:
edge["data"]["sourceHandle"] = source_handle
# Update target handle if it's changed and log the change
if old_escape_target_handle != escaped_target_handle:
edge_changes_log[target_node_data.get("display_name", "unknown")].append(
{
"attr": "targetHandle",
"old_value": old_escape_target_handle,
"new_value": escaped_target_handle,
}
)
edge["targetHandle"] = escaped_target_handle
if "data" in edge:
edge["data"]["targetHandle"] = target_handle
else:
# Log an error if source or target node is not found after reconciliation attempt
logger.error(f"Source or target node not found for edge: {edge}")
# Log all the changes that were made
log_node_changes(edge_changes_log)
return project_data_copy
def log_node_changes(node_changes_log) -> None:
# The idea here is to log the changes that were made to the nodes in debug
# Something like:
# Node: "Node Name" was updated with the following changes:
# attr_name: old_value -> new_value
# let's create one log per node
formatted_messages = []
for node_name, changes in node_changes_log.items():
message = f"\nNode: {node_name} was updated with the following changes:"
for change in changes:
message += f"\n- {change['attr']}: {change['old_value']} -> {change['new_value']}"
formatted_messages.append(message)
if formatted_messages:
logger.debug("\n".join(formatted_messages))
async def load_starter_projects(retries=3, delay=1) -> list[tuple[anyio.Path, dict]]:
starter_projects = []
folder = anyio.Path(__file__).parent / "starter_projects"
await logger.adebug("Loading starter projects")
async for file in folder.glob("*.json"):
attempt = 0
while attempt < retries:
content = await file.read_text(encoding="utf-8")
try:
project = orjson.loads(content)
starter_projects.append((file, project))
break # Break if load is successful
except orjson.JSONDecodeError as e:
attempt += 1
if attempt >= retries:
msg = f"Error loading starter project {file}: {e}"
raise ValueError(msg) from e
await asyncio.sleep(delay) # Wait before retrying
await logger.adebug(f"Loaded {len(starter_projects)} starter projects")
return starter_projects
async def copy_profile_pictures() -> None:
"""Asynchronously copies profile pictures from the source directory to the target configuration directory.
This function copies profile pictures while optimizing I/O operations by:
1. Using a set to track existing files and avoid redundant filesystem checks
2. Performing bulk copy operations concurrently using asyncio.gather
3. Offloading blocking I/O to threads
The directory structure is:
profile_pictures/
├── People/
│ └── [profile images]
└── Space/
└── [profile images]
"""
# Get config directory from settings
config_dir = get_storage_service().settings_service.settings.config_dir
if config_dir is None:
msg = "Config dir is not set in the settings"
raise ValueError(msg)
# Setup source and target paths
origin = anyio.Path(__file__).parent / "profile_pictures"
target = anyio.Path(config_dir) / "profile_pictures"
if not await origin.exists():
msg = f"The source folder '{origin}' does not exist."
raise ValueError(msg)
# Create target dir if needed
if not await target.exists():
await target.mkdir(parents=True, exist_ok=True)
try:
# Get set of existing files in target to avoid redundant checks
target_files = {str(f.relative_to(target)) async for f in target.rglob("*") if await f.is_file()}
# Define a helper coroutine to copy a single file concurrently
async def copy_file(src_file, dst_file, rel_path):
# Create parent directories if needed
await dst_file.parent.mkdir(parents=True, exist_ok=True)
# Offload blocking I/O to a thread
await asyncio.to_thread(shutil.copy2, str(src_file), str(dst_file))
await logger.adebug(f"Copied file '{rel_path}'")
tasks = []
async for src_file in origin.rglob("*"):
if not await src_file.is_file():
continue
rel_path = src_file.relative_to(origin)
if str(rel_path) not in target_files:
dst_file = target / rel_path
tasks.append(copy_file(src_file, dst_file, rel_path))
if tasks:
await asyncio.gather(*tasks)
except Exception as exc:
await logger.aexception("Error copying profile pictures")
msg = "An error occurred while copying profile pictures."
raise RuntimeError(msg) from exc
def get_project_data(project):
project_name = project.get("name")
project_description = project.get("description")
project_is_component = project.get("is_component")
project_updated_at = project.get("updated_at")
if not project_updated_at:
updated_at_datetime = datetime.now(tz=timezone.utc)
else:
updated_at_datetime = datetime.fromisoformat(project_updated_at)
project_data = project.get("data")
project_icon = project.get("icon")
project_icon = demojize(project_icon) if project_icon and purely_emoji(project_icon) else project_icon
project_icon_bg_color = project.get("icon_bg_color")
project_gradient = project.get("gradient")
project_tags = project.get("tags")
return (
project_name,
project_description,
project_is_component,
updated_at_datetime,
project_data,
project_icon,
project_icon_bg_color,
project_gradient,
project_tags,
)
async def update_project_file(project_path: anyio.Path, project: dict, updated_project_data) -> None:
"""Update starter project JSON file with new data.
This function attempts to write updated project data back to the source file.
In containerized environments with read-only filesystems (e.g., Kubernetes with
readOnlyRootFilesystem: true), the write will fail gracefully since the database
is the source of truth for project data.
Args:
project_path: Path to the project JSON file
project: Project dictionary to update
updated_project_data: New project data to write
"""
project["data"] = updated_project_data
try:
async with aiofiles.open(str(project_path), "w", encoding="utf-8") as f:
await f.write(orjson.dumps(project, option=ORJSON_OPTIONS).decode())
await logger.adebug(f"Updated starter project {project['name']} file")
except OSError as e:
# Handle read-only filesystem (common in containerized environments)
# The database update is the important part - file updates are optional
await logger.adebug(
f"Could not update starter project file {project['name']} (read-only filesystem): {e}. "
"This is expected in containerized environments with read-only root filesystem."
)
def update_existing_project(
existing_project,
project_name,
project_description,
project_is_component,
updated_at_datetime,
project_data,
project_icon,
project_icon_bg_color,
) -> None:
logger.info(f"Updating starter project {project_name}")
existing_project.data = project_data
existing_project.folder = STARTER_FOLDER_NAME
existing_project.description = project_description
existing_project.is_component = project_is_component
existing_project.updated_at = updated_at_datetime
existing_project.icon = project_icon
existing_project.icon_bg_color = project_icon_bg_color
def create_new_project(
session,
project_name,
project_description,
project_is_component,
updated_at_datetime,
project_data,
project_gradient,
project_tags,
project_icon,
project_icon_bg_color,
new_folder_id,
) -> None:
new_project = FlowCreate(
name=project_name,
description=project_description,
icon=project_icon,
icon_bg_color=project_icon_bg_color,
data=project_data,
is_component=project_is_component,
updated_at=updated_at_datetime,
folder_id=new_folder_id,
gradient=project_gradient,
tags=project_tags,
)
db_flow = Flow.model_validate(new_project.model_dump(exclude={"id"}))
session.add(db_flow)
async def get_all_flows_similar_to_project(session: AsyncSession, folder_id: UUID) -> list[Flow]:
stmt = select(Folder).options(selectinload(Folder.flows)).where(Folder.id == folder_id)
return list((await session.exec(stmt)).first().flows)
async def delete_starter_projects(session, folder_id) -> None:
flows = await get_all_flows_similar_to_project(session, folder_id)
for flow in flows:
await session.delete(flow)
async def folder_exists(session, folder_name):
stmt = select(Folder).where(Folder.name == folder_name)
folder = (await session.exec(stmt)).first()
return folder is not None
async def get_or_create_starter_folder(session):
if not await folder_exists(session, STARTER_FOLDER_NAME):
new_folder = FolderCreate(name=STARTER_FOLDER_NAME, description=STARTER_FOLDER_DESCRIPTION)
db_folder = Folder.model_validate(new_folder, from_attributes=True)
session.add(db_folder)
await session.flush()
await session.refresh(db_folder)
return db_folder
stmt = select(Folder).where(Folder.name == STARTER_FOLDER_NAME)
return (await session.exec(stmt)).first()
async def get_or_create_assistant_folder(session, user_id: UUID):
"""Create or get the Langflow Assistant folder for a specific user.
This folder contains agentic flows and cannot be deleted.
Args:
session: Database session
user_id: The ID of the user who owns the folder
Returns:
The Langflow Assistant folder
"""
stmt = select(Folder).where(Folder.user_id == user_id, Folder.name == ASSISTANT_FOLDER_NAME)
result = await session.exec(stmt)
folder = result.first()
if not folder:
new_folder = FolderCreate(name=ASSISTANT_FOLDER_NAME, description=ASSISTANT_FOLDER_DESCRIPTION)
db_folder = Folder.model_validate(new_folder, from_attributes=True)
db_folder.user_id = user_id
session.add(db_folder)
await session.commit()
await session.refresh(db_folder)
return db_folder
return folder
async def load_agentic_flows() -> list[tuple[anyio.Path, dict]]:
"""Load agentic flows from the agentic/flows directory.
Returns:
List of tuples containing (file_path, flow_data)
"""
agentic_flows: list[tuple[anyio.Path, dict]] = []
# Get the path to the agentic/flows directory
folder = anyio.Path(__file__).parent.parent / "agentic" / "flows"
if not await folder.exists():
await logger.adebug(f"Agentic flows directory does not exist: {folder}")
return agentic_flows
await logger.adebug("Loading agentic flows")
async for file in folder.glob("*.json"):
try:
async with aiofiles.open(str(file), encoding="utf-8") as f:
content = await f.read()
flow = orjson.loads(content)
agentic_flows.append((file, flow))
await logger.adebug(f"Loaded agentic flow: {file.name}")
except (OSError, orjson.JSONDecodeError) as e:
await logger.aexception(f"Error loading agentic flow {file}: {e}")
await logger.adebug(f"Loaded {len(agentic_flows)} agentic flows")
return agentic_flows
async def create_or_update_agentic_flows(session: AsyncSession, user_id: UUID) -> None:
"""Create or update agentic flows in the Langflow Assistant folder for a user.
This function is called on user login to ensure that all agentic flows
are present and up-to-date in the user's Langflow Assistant folder.
The function will:
- Extract flow_id and endpoint_name from the JSON
- Skip updates if flow already exists (only create new flows)
- Create new flows if they don't exist
Args:
session: Database session
user_id: The ID of the user
"""
from lfx.services.deps import get_settings_service
# Only configure if agentic experience is enabled
settings_service = get_settings_service()
if not settings_service.settings.agentic_experience:
await logger.adebug("Agentic experience disabled, skipping agentic flows creation")
return
try:
# Get or create the Langflow Assistant folder
assistant_folder = await get_or_create_assistant_folder(session, user_id)
# Load all agentic flows from the directory
agentic_flows = await load_agentic_flows()
if not agentic_flows:
await logger.adebug("No agentic flows found to load")
return
flows_created = 0
flows_updated = 0
for _, flow_data in agentic_flows:
# Extract flow metadata from JSON
(
flow_name,
flow_description,
flow_is_component,
updated_at_datetime,
project_data,
flow_icon,
flow_icon_bg_color,
flow_gradient,
flow_tags,
) = get_project_data(flow_data)
# Extract flow_id and endpoint_name from JSON
flow_id = flow_data.get("id")
flow_endpoint_name = flow_data.get("endpoint_name")
# Convert flow_id to UUID if it's a valid UUID string
if flow_id and isinstance(flow_id, str):
try:
flow_id = UUID(flow_id)
except ValueError:
await logger.awarning(f"Invalid UUID for flow {flow_name}: {flow_id}, will use auto-generated ID")
flow_id = None
# Try to find an existing flow by ID or endpoint_name
existing_flow = await find_existing_flow(session, flow_id, flow_endpoint_name)
if existing_flow:
# Skip update if flow already exists
await logger.adebug(f"Agentic flow already exists, skipping: {flow_name}")
flows_updated += 1
else:
try:
await logger.adebug(f"Creating agentic flow: {flow_name}")
# Create new flow with ID and endpoint_name from JSON
new_project = FlowCreate(
name=flow_name,
description=flow_description,
icon=flow_icon,
icon_bg_color=flow_icon_bg_color,
data=project_data,
is_component=flow_is_component,
updated_at=updated_at_datetime,
folder_id=assistant_folder.id,
gradient=flow_gradient,
tags=flow_tags,
endpoint_name=flow_endpoint_name, # Set endpoint_name from JSON
)
db_flow = Flow.model_validate(new_project.model_dump(exclude={"id"}))
# Set the ID from JSON if provided
if flow_id:
db_flow.id = flow_id
session.add(db_flow)
flows_created += 1
except Exception: # noqa: BLE001
await logger.aexception(f"Error while creating agentic flow {flow_name}")
if flows_created > 0 or flows_updated > 0:
await session.commit()
await logger.adebug(
f"Successfully created {flows_created} and skipped {flows_updated} existing agentic flows"
)
else:
await logger.adebug("No agentic flows to create")
except Exception: # noqa: BLE001
await logger.aexception("Error in create_or_update_agentic_flows")
def _is_valid_uuid(val):
try:
uuid_obj = UUID(val)
except ValueError:
return False
return str(uuid_obj) == val
async def load_flows_from_directory() -> None:
"""On langflow startup, this loads all flows from the directory specified in the settings.
All flows are uploaded into the default folder for the superuser.
"""
settings_service = get_settings_service()
flows_path = settings_service.settings.load_flows_path
if not flows_path:
return
async with session_scope() as session:
# Find superuser by role instead of username to avoid issues with credential reset
from langflow.services.database.models.user.model import User
stmt = select(User).where(User.is_superuser == True) # noqa: E712
result = await session.exec(stmt)