-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLangflow.json
3854 lines (3854 loc) · 216 KB
/
Langflow.json
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
{
"id": "ad67d18e-ed45-425f-8380-4b5400c22da8",
"data": {
"nodes": [
{
"id": "ChatOutput-RgIiY",
"type": "genericNode",
"position": {
"x": 2449.2506239945437,
"y": 314.28808333984153
},
"data": {
"node": {
"template": {
"_type": "Component",
"background_color": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "background_color",
"value": "",
"display_name": "Background Color",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "The background color of the icon.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"chat_icon": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "chat_icon",
"value": "",
"display_name": "Icon",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "The icon of the message.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"code": {
"type": "code",
"required": true,
"placeholder": "",
"list": false,
"show": true,
"multiline": true,
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id if hasattr(self, \"graph\") else None\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n",
"fileTypes": [],
"file_path": "",
"password": false,
"name": "code",
"advanced": true,
"dynamic": true,
"info": "",
"load_from_db": false,
"title_case": false
},
"data_template": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "data_template",
"value": "{text}",
"display_name": "Data Template",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"input_value": {
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "input_value",
"value": "",
"display_name": "Text",
"advanced": false,
"input_types": [
"Message"
],
"dynamic": false,
"info": "Message to be passed as output.",
"title_case": false,
"type": "str",
"_input_type": "MessageInput"
},
"sender": {
"tool_mode": false,
"trace_as_metadata": true,
"options": [
"Machine",
"User"
],
"combobox": false,
"required": false,
"placeholder": "",
"show": true,
"name": "sender",
"value": "Machine",
"display_name": "Sender Type",
"advanced": true,
"dynamic": false,
"info": "Type of sender.",
"title_case": false,
"type": "str",
"_input_type": "DropdownInput"
},
"sender_name": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "sender_name",
"value": "AI",
"display_name": "Sender Name",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "Name of the sender.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"session_id": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "session_id",
"value": "",
"display_name": "Session ID",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "The session ID of the chat. If empty, the current session ID parameter will be used.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"should_store_message": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "should_store_message",
"value": true,
"display_name": "Store Messages",
"advanced": true,
"dynamic": false,
"info": "Store the message in the history.",
"title_case": false,
"type": "bool",
"_input_type": "BoolInput"
},
"text_color": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "text_color",
"value": "",
"display_name": "Text Color",
"advanced": true,
"input_types": [
"Message"
],
"dynamic": false,
"info": "The text color of the name",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
}
},
"description": "Display a chat message in the Playground.",
"icon": "MessagesSquare",
"base_classes": [
"Message"
],
"display_name": "Chat Output",
"documentation": "",
"custom_fields": {},
"output_types": [],
"pinned": false,
"conditional_paths": [],
"frozen": false,
"outputs": [
{
"types": [
"Message"
],
"selected": "Message",
"name": "message",
"display_name": "Message",
"method": "message_response",
"value": "__UNDEFINED__",
"cache": true
}
],
"field_order": [
"input_value",
"should_store_message",
"sender",
"sender_name",
"session_id",
"data_template",
"background_color",
"chat_icon",
"text_color"
],
"beta": false,
"legacy": false,
"edited": false,
"metadata": {},
"tool_mode": false,
"category": "outputs",
"key": "ChatOutput",
"score": 0.003169567463043492,
"lf_version": "1.1.1"
},
"type": "ChatOutput",
"id": "ChatOutput-RgIiY"
},
"selected": false,
"width": 320,
"height": 233,
"dragging": false
},
{
"id": "OpenAIModel-DoI30",
"type": "genericNode",
"position": {
"x": 1907.4737274805425,
"y": 244.4317845498156
},
"data": {
"node": {
"template": {
"_type": "Component",
"output_parser": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "output_parser",
"value": "",
"display_name": "Output Parser",
"advanced": true,
"input_types": [
"OutputParser"
],
"dynamic": false,
"info": "The parser to use to parse the output of the model",
"title_case": false,
"type": "other",
"_input_type": "HandleInput"
},
"api_key": {
"load_from_db": true,
"required": false,
"placeholder": "",
"show": true,
"name": "api_key",
"value": "",
"display_name": "OpenAI API Key",
"advanced": false,
"input_types": [
"Message"
],
"dynamic": false,
"info": "The OpenAI API Key to use for the OpenAI model.",
"title_case": false,
"password": true,
"type": "str",
"_input_type": "SecretStrInput"
},
"code": {
"type": "code",
"required": true,
"placeholder": "",
"list": false,
"show": true,
"multiline": true,
"value": "import operator\nfrom functools import reduce\n\nfrom langchain_openai import ChatOpenAI\nfrom pydantic.v1 import SecretStr\n\nfrom langflow.base.models.model import LCModelComponent\nfrom langflow.base.models.openai_constants import OPENAI_MODEL_NAMES\nfrom langflow.field_typing import LanguageModel\nfrom langflow.field_typing.range_spec import RangeSpec\nfrom langflow.inputs import BoolInput, DictInput, DropdownInput, FloatInput, IntInput, SecretStrInput, StrInput\nfrom langflow.inputs.inputs import HandleInput\n\n\nclass OpenAIModelComponent(LCModelComponent):\n display_name = \"OpenAI\"\n description = \"Generates text using OpenAI LLMs.\"\n icon = \"OpenAI\"\n name = \"OpenAIModel\"\n\n inputs = [\n *LCModelComponent._base_inputs,\n IntInput(\n name=\"max_tokens\",\n display_name=\"Max Tokens\",\n advanced=True,\n info=\"The maximum number of tokens to generate. Set to 0 for unlimited tokens.\",\n range_spec=RangeSpec(min=0, max=128000),\n ),\n DictInput(\n name=\"model_kwargs\",\n display_name=\"Model Kwargs\",\n advanced=True,\n info=\"Additional keyword arguments to pass to the model.\",\n ),\n BoolInput(\n name=\"json_mode\",\n display_name=\"JSON Mode\",\n advanced=True,\n info=\"If True, it will output JSON regardless of passing a schema.\",\n ),\n DictInput(\n name=\"output_schema\",\n is_list=True,\n display_name=\"Schema\",\n advanced=True,\n info=\"The schema for the Output of the model. \"\n \"You must pass the word JSON in the prompt. \"\n \"If left blank, JSON mode will be disabled. [DEPRECATED]\",\n ),\n DropdownInput(\n name=\"model_name\",\n display_name=\"Model Name\",\n advanced=False,\n options=OPENAI_MODEL_NAMES,\n value=OPENAI_MODEL_NAMES[0],\n ),\n StrInput(\n name=\"openai_api_base\",\n display_name=\"OpenAI API Base\",\n advanced=True,\n info=\"The base URL of the OpenAI API. \"\n \"Defaults to https://api.openai.com/v1. \"\n \"You can change this to use other APIs like JinaChat, LocalAI and Prem.\",\n ),\n SecretStrInput(\n name=\"api_key\",\n display_name=\"OpenAI API Key\",\n info=\"The OpenAI API Key to use for the OpenAI model.\",\n advanced=False,\n value=\"OPENAI_API_KEY\",\n ),\n FloatInput(name=\"temperature\", display_name=\"Temperature\", value=0.1),\n IntInput(\n name=\"seed\",\n display_name=\"Seed\",\n info=\"The seed controls the reproducibility of the job.\",\n advanced=True,\n value=1,\n ),\n HandleInput(\n name=\"output_parser\",\n display_name=\"Output Parser\",\n info=\"The parser to use to parse the output of the model\",\n advanced=True,\n input_types=[\"OutputParser\"],\n ),\n ]\n\n def build_model(self) -> LanguageModel: # type: ignore[type-var]\n # self.output_schema is a list of dictionaries\n # let's convert it to a dictionary\n output_schema_dict: dict[str, str] = reduce(operator.ior, self.output_schema or {}, {})\n openai_api_key = self.api_key\n temperature = self.temperature\n model_name: str = self.model_name\n max_tokens = self.max_tokens\n model_kwargs = self.model_kwargs or {}\n openai_api_base = self.openai_api_base or \"https://api.openai.com/v1\"\n json_mode = bool(output_schema_dict) or self.json_mode\n seed = self.seed\n\n api_key = SecretStr(openai_api_key).get_secret_value() if openai_api_key else None\n output = ChatOpenAI(\n max_tokens=max_tokens or None,\n model_kwargs=model_kwargs,\n model=model_name,\n base_url=openai_api_base,\n api_key=api_key,\n temperature=temperature if temperature is not None else 0.1,\n seed=seed,\n )\n if json_mode:\n if output_schema_dict:\n output = output.with_structured_output(schema=output_schema_dict, method=\"json_mode\")\n else:\n output = output.bind(response_format={\"type\": \"json_object\"})\n\n return output\n\n def _get_exception_message(self, e: Exception):\n \"\"\"Get a message from an OpenAI exception.\n\n Args:\n e (Exception): The exception to get the message from.\n\n Returns:\n str: The message from the exception.\n \"\"\"\n try:\n from openai import BadRequestError\n except ImportError:\n return None\n if isinstance(e, BadRequestError):\n message = e.body.get(\"message\")\n if message:\n return message\n return None\n",
"fileTypes": [],
"file_path": "",
"password": false,
"name": "code",
"advanced": true,
"dynamic": true,
"info": "",
"load_from_db": false,
"title_case": false
},
"input_value": {
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "input_value",
"value": "",
"display_name": "Input",
"advanced": false,
"input_types": [
"Message"
],
"dynamic": false,
"info": "",
"title_case": false,
"type": "str",
"_input_type": "MessageInput"
},
"json_mode": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "json_mode",
"value": false,
"display_name": "JSON Mode",
"advanced": true,
"dynamic": false,
"info": "If True, it will output JSON regardless of passing a schema.",
"title_case": false,
"type": "bool",
"_input_type": "BoolInput"
},
"max_tokens": {
"trace_as_metadata": true,
"range_spec": {
"step_type": "float",
"min": 0,
"max": 128000,
"step": 0.1
},
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "max_tokens",
"value": "",
"display_name": "Max Tokens",
"advanced": true,
"dynamic": false,
"info": "The maximum number of tokens to generate. Set to 0 for unlimited tokens.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"model_kwargs": {
"trace_as_input": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "model_kwargs",
"value": {},
"display_name": "Model Kwargs",
"advanced": true,
"dynamic": false,
"info": "Additional keyword arguments to pass to the model.",
"title_case": false,
"type": "dict",
"_input_type": "DictInput"
},
"model_name": {
"tool_mode": false,
"trace_as_metadata": true,
"options": [
"gpt-4o-mini",
"gpt-4o",
"gpt-4-turbo",
"gpt-4-turbo-preview",
"gpt-4",
"gpt-3.5-turbo",
"gpt-3.5-turbo-0125"
],
"combobox": false,
"required": false,
"placeholder": "",
"show": true,
"name": "model_name",
"value": "gpt-4o-mini",
"display_name": "Model Name",
"advanced": false,
"dynamic": false,
"info": "",
"title_case": false,
"type": "str",
"_input_type": "DropdownInput"
},
"openai_api_base": {
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "openai_api_base",
"value": "",
"display_name": "OpenAI API Base",
"advanced": true,
"dynamic": false,
"info": "The base URL of the OpenAI API. Defaults to https://api.openai.com/v1. You can change this to use other APIs like JinaChat, LocalAI and Prem.",
"title_case": false,
"type": "str",
"_input_type": "StrInput"
},
"output_schema": {
"trace_as_input": true,
"list": true,
"required": false,
"placeholder": "",
"show": true,
"name": "output_schema",
"value": {},
"display_name": "Schema",
"advanced": true,
"dynamic": false,
"info": "The schema for the Output of the model. You must pass the word JSON in the prompt. If left blank, JSON mode will be disabled. [DEPRECATED]",
"title_case": false,
"type": "dict",
"_input_type": "DictInput"
},
"seed": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "seed",
"value": 1,
"display_name": "Seed",
"advanced": true,
"dynamic": false,
"info": "The seed controls the reproducibility of the job.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"stream": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "stream",
"value": false,
"display_name": "Stream",
"advanced": false,
"dynamic": false,
"info": "Stream the response from the model. Streaming works only in Chat.",
"title_case": false,
"type": "bool",
"_input_type": "BoolInput"
},
"system_message": {
"tool_mode": false,
"trace_as_input": true,
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "system_message",
"value": "\"You are a professional social media analyst and a helpful ai assistant. You are provided with a CSV file containing social media data. Your task is to analyze this data and provide insightful summaries, trends, and observations according to user prompt. try to keep the response concise and relevant to the user prompt”",
"display_name": "System Message",
"advanced": false,
"input_types": [
"Message"
],
"dynamic": false,
"info": "System message to pass to the model.",
"title_case": false,
"type": "str",
"_input_type": "MessageTextInput"
},
"temperature": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "temperature",
"value": 0.1,
"display_name": "Temperature",
"advanced": false,
"dynamic": false,
"info": "",
"title_case": false,
"type": "float",
"_input_type": "FloatInput"
}
},
"description": "Generates text using OpenAI LLMs.",
"icon": "OpenAI",
"base_classes": [
"LanguageModel",
"Message"
],
"display_name": "OpenAI",
"documentation": "",
"custom_fields": {},
"output_types": [],
"pinned": false,
"conditional_paths": [],
"frozen": false,
"outputs": [
{
"types": [
"Message"
],
"selected": "Message",
"name": "text_output",
"display_name": "Text",
"method": "text_response",
"value": "__UNDEFINED__",
"cache": true,
"required_inputs": []
},
{
"types": [
"LanguageModel"
],
"selected": "LanguageModel",
"name": "model_output",
"display_name": "Language Model",
"method": "build_model",
"value": "__UNDEFINED__",
"cache": true,
"required_inputs": []
}
],
"field_order": [
"input_value",
"system_message",
"stream",
"max_tokens",
"model_kwargs",
"json_mode",
"output_schema",
"model_name",
"openai_api_base",
"api_key",
"temperature",
"seed",
"output_parser"
],
"beta": false,
"legacy": false,
"edited": false,
"metadata": {},
"tool_mode": false,
"category": "models",
"key": "OpenAIModel",
"score": 2.220446049250313e-16,
"lf_version": "1.1.1"
},
"type": "OpenAIModel",
"id": "OpenAIModel-DoI30"
},
"selected": false,
"width": 320,
"height": 671,
"dragging": false
},
{
"id": "File-AV9bI",
"type": "genericNode",
"position": {
"x": 36.547773599199274,
"y": 844.7035286171263
},
"data": {
"node": {
"template": {
"_type": "Component",
"path": {
"trace_as_metadata": true,
"file_path": "ad67d18e-ed45-425f-8380-4b5400c22da8/2025-01-02_06-58-23_social_media_engagement_extended.csv",
"fileTypes": [
"txt",
"md",
"mdx",
"csv",
"json",
"yaml",
"yml",
"xml",
"html",
"htm",
"pdf",
"docx",
"py",
"sh",
"sql",
"js",
"ts",
"tsx",
"zip"
],
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "path",
"value": "",
"display_name": "Path",
"advanced": false,
"dynamic": false,
"info": "Supported file types: txt, md, mdx, csv, json, yaml, yml, xml, html, htm, pdf, docx, py, sh, sql, js, ts, tsx, zip",
"title_case": false,
"type": "file",
"_input_type": "FileInput"
},
"code": {
"type": "code",
"required": true,
"placeholder": "",
"list": false,
"show": true,
"multiline": true,
"value": "from pathlib import Path\nfrom tempfile import NamedTemporaryFile\nfrom zipfile import ZipFile, is_zipfile\n\nfrom langflow.base.data.utils import TEXT_FILE_TYPES, parallel_load_data, parse_text_file_to_data\nfrom langflow.custom import Component\nfrom langflow.io import BoolInput, FileInput, IntInput, Output\nfrom langflow.schema import Data\n\n\nclass FileComponent(Component):\n \"\"\"Handles loading of individual or zipped text files.\n\n Processes multiple valid files within a zip archive if provided.\n\n Attributes:\n display_name: Display name of the component.\n description: Brief component description.\n icon: Icon to represent the component.\n name: Identifier for the component.\n inputs: Inputs required by the component.\n outputs: Output of the component after processing files.\n \"\"\"\n\n display_name = \"File\"\n description = \"Load a file to be used in your project.\"\n icon = \"file-text\"\n name = \"File\"\n\n inputs = [\n FileInput(\n name=\"path\",\n display_name=\"Path\",\n file_types=[*TEXT_FILE_TYPES, \"zip\"],\n info=f\"Supported file types: {', '.join([*TEXT_FILE_TYPES, 'zip'])}\",\n ),\n BoolInput(\n name=\"silent_errors\",\n display_name=\"Silent Errors\",\n advanced=True,\n info=\"If true, errors will not raise an exception.\",\n ),\n BoolInput(\n name=\"use_multithreading\",\n display_name=\"Use Multithreading\",\n advanced=True,\n info=\"If true, parallel processing will be enabled for zip files.\",\n ),\n IntInput(\n name=\"concurrency_multithreading\",\n display_name=\"Multithreading Concurrency\",\n advanced=True,\n info=\"The maximum number of workers to use, if concurrency is enabled\",\n value=4,\n ),\n ]\n\n outputs = [Output(display_name=\"Data\", name=\"data\", method=\"load_file\")]\n\n def load_file(self) -> Data:\n \"\"\"Load and parse file(s) from a zip archive.\n\n Raises:\n ValueError: If no file is uploaded or file path is invalid.\n\n Returns:\n Data: Parsed data from file(s).\n \"\"\"\n # Check if the file path is provided\n if not self.path:\n self.log(\"File path is missing.\")\n msg = \"Please upload a file for processing.\"\n\n raise ValueError(msg)\n\n resolved_path = Path(self.resolve_path(self.path))\n try:\n # Check if the file is a zip archive\n if is_zipfile(resolved_path):\n self.log(f\"Processing zip file: {resolved_path.name}.\")\n\n return self._process_zip_file(\n resolved_path,\n silent_errors=self.silent_errors,\n parallel=self.use_multithreading,\n )\n\n self.log(f\"Processing single file: {resolved_path.name}.\")\n\n return self._process_single_file(resolved_path, silent_errors=self.silent_errors)\n except FileNotFoundError:\n self.log(f\"File not found: {resolved_path.name}.\")\n\n raise\n\n def _process_zip_file(self, zip_path: Path, *, silent_errors: bool = False, parallel: bool = False) -> Data:\n \"\"\"Process text files within a zip archive.\n\n Args:\n zip_path: Path to the zip file.\n silent_errors: Suppresses errors if True.\n parallel: Enables parallel processing if True.\n\n Returns:\n list[Data]: Combined data from all valid files.\n\n Raises:\n ValueError: If no valid files found in the archive.\n \"\"\"\n data: list[Data] = []\n with ZipFile(zip_path, \"r\") as zip_file:\n # Filter file names based on extensions in TEXT_FILE_TYPES and ignore hidden files\n valid_files = [\n name\n for name in zip_file.namelist()\n if (\n any(name.endswith(ext) for ext in TEXT_FILE_TYPES)\n and not name.startswith(\"__MACOSX\")\n and not name.startswith(\".\")\n )\n ]\n\n # Raise an error if no valid files found\n if not valid_files:\n self.log(\"No valid files in the zip archive.\")\n\n # Return empty data if silent_errors is True\n if silent_errors:\n return data # type: ignore[return-value]\n\n # Raise an error if no valid files found\n msg = \"No valid files in the zip archive.\"\n raise ValueError(msg)\n\n # Define a function to process each file\n def process_file(file_name, silent_errors=silent_errors):\n with NamedTemporaryFile(delete=False) as temp_file:\n temp_path = Path(temp_file.name).with_name(file_name)\n with zip_file.open(file_name) as file_content:\n temp_path.write_bytes(file_content.read())\n try:\n return self._process_single_file(temp_path, silent_errors=silent_errors)\n finally:\n temp_path.unlink()\n\n # Process files in parallel if specified\n if parallel:\n self.log(\n f\"Initializing parallel Thread Pool Executor with max workers: \"\n f\"{self.concurrency_multithreading}.\"\n )\n\n # Process files in parallel\n initial_data = parallel_load_data(\n valid_files,\n silent_errors=silent_errors,\n load_function=process_file,\n max_concurrency=self.concurrency_multithreading,\n )\n\n # Filter out empty data\n data = list(filter(None, initial_data))\n else:\n # Sequential processing\n data = [process_file(file_name) for file_name in valid_files]\n\n self.log(f\"Successfully processed zip file: {zip_path.name}.\")\n\n return data # type: ignore[return-value]\n\n def _process_single_file(self, file_path: Path, *, silent_errors: bool = False) -> Data:\n \"\"\"Process a single file.\n\n Args:\n file_path: Path to the file.\n silent_errors: Suppresses errors if True.\n\n Returns:\n Data: Parsed data from the file.\n\n Raises:\n ValueError: For unsupported file formats.\n \"\"\"\n # Check if the file type is supported\n if not any(file_path.suffix == ext for ext in [\".\" + f for f in TEXT_FILE_TYPES]):\n self.log(f\"Unsupported file type: {file_path.suffix}\")\n\n # Return empty data if silent_errors is True\n if silent_errors:\n return Data()\n\n msg = f\"Unsupported file type: {file_path.suffix}\"\n raise ValueError(msg)\n\n try:\n # Parse the text file as appropriate\n data = parse_text_file_to_data(str(file_path), silent_errors=silent_errors) # type: ignore[assignment]\n if not data:\n data = Data()\n\n self.log(f\"Successfully processed file: {file_path.name}.\")\n except Exception as e:\n self.log(f\"Error processing file {file_path.name}: {e}\")\n\n # Return empty data if silent_errors is True\n if not silent_errors:\n raise\n\n data = Data()\n\n return data\n",
"fileTypes": [],
"file_path": "",
"password": false,
"name": "code",
"advanced": true,
"dynamic": true,
"info": "",
"load_from_db": false,
"title_case": false
},
"concurrency_multithreading": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "concurrency_multithreading",
"value": 4,
"display_name": "Multithreading Concurrency",
"advanced": true,
"dynamic": false,
"info": "The maximum number of workers to use, if concurrency is enabled",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"silent_errors": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "silent_errors",
"value": false,
"display_name": "Silent Errors",
"advanced": true,
"dynamic": false,
"info": "If true, errors will not raise an exception.",
"title_case": false,
"type": "bool",
"_input_type": "BoolInput"
},
"use_multithreading": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "use_multithreading",
"value": false,
"display_name": "Use Multithreading",
"advanced": true,
"dynamic": false,
"info": "If true, parallel processing will be enabled for zip files.",
"title_case": false,
"type": "bool",
"_input_type": "BoolInput"
}
},
"description": "Load a file to be used in your project.",
"icon": "file-text",
"base_classes": [
"Data"
],
"display_name": "File",
"documentation": "",
"custom_fields": {},
"output_types": [],
"pinned": false,
"conditional_paths": [],
"frozen": false,
"outputs": [
{
"types": [
"Data"
],
"selected": "Data",
"name": "data",
"display_name": "Data",
"method": "load_file",
"value": "__UNDEFINED__",
"cache": true
}
],
"field_order": [
"path",
"silent_errors",
"use_multithreading",
"concurrency_multithreading"
],
"beta": false,
"legacy": false,
"edited": false,
"metadata": {},
"tool_mode": false,
"lf_version": "1.1.1"
},
"type": "File",
"id": "File-AV9bI"
},
"selected": false,
"width": 320,
"height": 231,
"dragging": false
},
{
"id": "AstraDB-ivIdG",
"type": "genericNode",
"position": {
"x": 863.2658045638084,
"y": 833.2118158052117
},
"data": {
"node": {
"template": {
"_type": "Component",
"embedding_model": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "embedding_model",
"value": "",
"display_name": "Embedding Model",
"advanced": false,
"input_types": [
"Embeddings"
],
"dynamic": false,
"info": "Allows an embedding model configuration.",
"title_case": false,
"type": "other",
"_input_type": "HandleInput"
},
"ingest_data": {
"tool_mode": false,
"trace_as_metadata": true,
"list": true,
"trace_as_input": true,
"required": false,
"placeholder": "",
"show": true,
"name": "ingest_data",
"value": "",
"display_name": "Ingest Data",
"advanced": false,
"input_types": [
"Data"
],
"dynamic": false,
"info": "",
"title_case": false,
"type": "other",
"_input_type": "DataInput"
},
"advanced_search_filter": {
"trace_as_input": true,
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "advanced_search_filter",
"value": {},
"display_name": "Search Metadata Filter",
"advanced": true,
"dynamic": false,
"info": "Optional dictionary of filters to apply to the search query.",
"title_case": false,
"type": "NestedDict",
"_input_type": "NestedDictInput"
},
"api_endpoint": {
"load_from_db": false,
"required": true,
"placeholder": "",
"show": true,
"name": "api_endpoint",
"value": "",
"display_name": "API Endpoint",
"advanced": false,
"input_types": [
"Message"
],
"dynamic": false,
"info": "API endpoint URL for the Astra DB service.",
"title_case": false,
"password": true,
"type": "str",
"_input_type": "SecretStrInput"
},
"batch_size": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "batch_size",
"value": "",
"display_name": "Batch Size",
"advanced": true,
"dynamic": false,
"info": "Optional number of data to process in a single batch.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"bulk_delete_concurrency": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "bulk_delete_concurrency",
"value": "",
"display_name": "Bulk Delete Concurrency",
"advanced": true,
"dynamic": false,
"info": "Optional concurrency level for bulk delete operations.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"bulk_insert_batch_concurrency": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "bulk_insert_batch_concurrency",
"value": "",
"display_name": "Bulk Insert Batch Concurrency",
"advanced": true,
"dynamic": false,
"info": "Optional concurrency level for bulk insert operations.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"bulk_insert_overwrite_concurrency": {
"trace_as_metadata": true,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "bulk_insert_overwrite_concurrency",
"value": "",
"display_name": "Bulk Insert Overwrite Concurrency",
"advanced": true,
"dynamic": false,
"info": "Optional concurrency level for bulk insert operations that overwrite existing data.",
"title_case": false,
"type": "int",
"_input_type": "IntInput"
},
"code": {
"type": "code",
"required": true,
"placeholder": "",
"list": false,
"show": true,
"multiline": true,
"value": "import os\nfrom collections import defaultdict\n\nimport orjson\nfrom astrapy import DataAPIClient\nfrom astrapy.admin import parse_api_endpoint\nfrom langchain_astradb import AstraDBVectorStore\n\nfrom langflow.base.vectorstores.model import LCVectorStoreComponent, check_cached_vector_store\nfrom langflow.helpers import docs_to_data\nfrom langflow.inputs import DictInput, FloatInput, MessageTextInput, NestedDictInput\nfrom langflow.io import (\n BoolInput,\n DataInput,\n DropdownInput,\n HandleInput,\n IntInput,\n MultilineInput,\n SecretStrInput,\n StrInput,\n)\nfrom langflow.schema import Data\n\n\nclass AstraVectorStoreComponent(LCVectorStoreComponent):\n display_name: str = \"Astra DB\"\n description: str = \"Implementation of Vector Store using Astra DB with search capabilities\"\n documentation: str = \"https://docs.langflow.org/starter-projects-vector-store-rag\"\n name = \"AstraDB\"\n icon: str = \"AstraDB\"\n\n _cached_vector_store: AstraDBVectorStore | None = None\n\n VECTORIZE_PROVIDERS_MAPPING = defaultdict(\n list,\n {\n \"Azure OpenAI\": [\n \"azureOpenAI\",\n [\"text-embedding-3-small\", \"text-embedding-3-large\", \"text-embedding-ada-002\"],\n ],\n \"Hugging Face - Dedicated\": [\"huggingfaceDedicated\", [\"endpoint-defined-model\"]],\n \"Hugging Face - Serverless\": [\n \"huggingface\",\n [\n \"sentence-transformers/all-MiniLM-L6-v2\",\n \"intfloat/multilingual-e5-large\",\n \"intfloat/multilingual-e5-large-instruct\",\n \"BAAI/bge-small-en-v1.5\",\n \"BAAI/bge-base-en-v1.5\",\n \"BAAI/bge-large-en-v1.5\",\n ],\n ],\n \"Jina AI\": [\n \"jinaAI\",\n [\n \"jina-embeddings-v2-base-en\",\n \"jina-embeddings-v2-base-de\",\n \"jina-embeddings-v2-base-es\",\n \"jina-embeddings-v2-base-code\",\n \"jina-embeddings-v2-base-zh\",\n ],\n ],\n \"Mistral AI\": [\"mistral\", [\"mistral-embed\"]],\n \"NVIDIA\": [\"nvidia\", [\"NV-Embed-QA\"]],\n \"OpenAI\": [\"openai\", [\"text-embedding-3-small\", \"text-embedding-3-large\", \"text-embedding-ada-002\"]],\n \"Upstage\": [\"upstageAI\", [\"solar-embedding-1-large\"]],\n \"Voyage AI\": [\n \"voyageAI\",\n [\"voyage-large-2-instruct\", \"voyage-law-2\", \"voyage-code-2\", \"voyage-large-2\", \"voyage-2\"],\n ],\n },\n )\n\n inputs = [\n SecretStrInput(\n name=\"token\",\n display_name=\"Astra DB Application Token\",\n info=\"Authentication token for accessing Astra DB.\",\n value=\"ASTRA_DB_APPLICATION_TOKEN\",\n required=True,\n advanced=os.getenv(\"ASTRA_ENHANCED\", \"false\").lower() == \"true\",\n ),\n SecretStrInput(\n name=\"api_endpoint\",\n display_name=\"Database\" if os.getenv(\"ASTRA_ENHANCED\", \"false\").lower() == \"true\" else \"API Endpoint\",\n info=\"API endpoint URL for the Astra DB service.\",\n value=\"ASTRA_DB_API_ENDPOINT\",\n required=True,\n ),\n StrInput(\n name=\"collection_name\",\n display_name=\"Collection Name\",\n info=\"The name of the collection within Astra DB where the vectors will be stored.\",\n required=True,\n ),\n MultilineInput(\n name=\"search_input\",\n display_name=\"Search Input\",\n ),\n DataInput(\n name=\"ingest_data\",\n display_name=\"Ingest Data\",\n is_list=True,\n ),\n StrInput(\n name=\"keyspace\",\n display_name=\"Keyspace\",\n info=\"Optional keyspace within Astra DB to use for the collection.\",\n advanced=True,\n ),\n DropdownInput(\n name=\"embedding_choice\",\n display_name=\"Embedding Model or Astra Vectorize\",\n info=\"Determines whether to use Astra Vectorize for the collection.\",\n options=[\"Embedding Model\", \"Astra Vectorize\"],\n real_time_refresh=True,\n value=\"Embedding Model\",\n ),\n HandleInput(\n name=\"embedding_model\",\n display_name=\"Embedding Model\",\n input_types=[\"Embeddings\"],\n info=\"Allows an embedding model configuration.\",\n ),\n DropdownInput(\n name=\"metric\",\n display_name=\"Metric\",\n info=\"Optional distance metric for vector comparisons in the vector store.\",\n options=[\"cosine\", \"dot_product\", \"euclidean\"],\n value=\"cosine\",\n advanced=True,\n ),\n IntInput(\n name=\"batch_size\",\n display_name=\"Batch Size\",\n info=\"Optional number of data to process in a single batch.\",\n advanced=True,\n ),\n IntInput(\n name=\"bulk_insert_batch_concurrency\",\n display_name=\"Bulk Insert Batch Concurrency\",\n info=\"Optional concurrency level for bulk insert operations.\",\n advanced=True,\n ),\n IntInput(\n name=\"bulk_insert_overwrite_concurrency\",\n display_name=\"Bulk Insert Overwrite Concurrency\",\n info=\"Optional concurrency level for bulk insert operations that overwrite existing data.\",\n advanced=True,\n ),\n IntInput(\n name=\"bulk_delete_concurrency\",\n display_name=\"Bulk Delete Concurrency\",\n info=\"Optional concurrency level for bulk delete operations.\",\n advanced=True,\n ),\n DropdownInput(\n name=\"setup_mode\",\n display_name=\"Setup Mode\",\n info=\"Configuration mode for setting up the vector store, with options like 'Sync' or 'Off'.\",\n options=[\"Sync\", \"Off\"],\n advanced=True,\n value=\"Sync\",\n ),\n BoolInput(\n name=\"pre_delete_collection\",\n display_name=\"Pre Delete Collection\",\n info=\"Boolean flag to determine whether to delete the collection before creating a new one.\",\n advanced=True,\n ),\n StrInput(\n name=\"metadata_indexing_include\",\n display_name=\"Metadata Indexing Include\",\n info=\"Optional list of metadata fields to include in the indexing.\",\n is_list=True,\n advanced=True,\n ),\n StrInput(\n name=\"metadata_indexing_exclude\",\n display_name=\"Metadata Indexing Exclude\",\n info=\"Optional list of metadata fields to exclude from the indexing.\",\n is_list=True,\n advanced=True,\n ),\n StrInput(\n name=\"collection_indexing_policy\",\n display_name=\"Collection Indexing Policy\",\n info='Optional JSON string for the \"indexing\" field of the collection. '\n \"See https://docs.datastax.com/en/astra-db-serverless/api-reference/collections.html#the-indexing-option\",\n advanced=True,\n ),\n IntInput(\n name=\"number_of_results\",\n display_name=\"Number of Results\",\n info=\"Number of results to return.\",\n advanced=True,\n value=4,\n ),\n DropdownInput(\n name=\"search_type\",\n display_name=\"Search Type\",\n info=\"Search type to use\",\n options=[\"Similarity\", \"Similarity with score threshold\", \"MMR (Max Marginal Relevance)\"],\n value=\"Similarity\",\n advanced=True,\n ),\n FloatInput(\n name=\"search_score_threshold\",\n display_name=\"Search Score Threshold\",\n info=\"Minimum similarity score threshold for search results. \"\n \"(when using 'Similarity with score threshold')\",\n value=0,\n advanced=True,\n ),\n NestedDictInput(\n name=\"advanced_search_filter\",\n display_name=\"Search Metadata Filter\",\n info=\"Optional dictionary of filters to apply to the search query.\",\n advanced=True,\n ),\n DictInput(\n name=\"search_filter\",\n display_name=\"[DEPRECATED] Search Metadata Filter\",\n info=\"Deprecated: use advanced_search_filter. Optional dictionary of filters to apply to the search query.\",\n advanced=True,\n is_list=True,\n ),\n ]\n\n def del_fields(self, build_config, field_list):\n for field in field_list:\n if field in build_config:\n del build_config[field]\n\n return build_config\n\n def insert_in_dict(self, build_config, field_name, new_parameters):\n # Insert the new key-value pair after the found key\n for new_field_name, new_parameter in new_parameters.items():\n # Get all the items as a list of tuples (key, value)\n items = list(build_config.items())\n\n # Find the index of the key to insert after\n idx = len(items)\n for i, (key, _) in enumerate(items):\n if key == field_name:\n idx = i + 1\n break\n\n items.insert(idx, (new_field_name, new_parameter))\n\n # Clear the original dictionary and update with the modified items\n build_config.clear()\n build_config.update(items)\n\n return build_config\n\n def update_providers_mapping(self):\n # If we don't have token or api_endpoint, we can't fetch the list of providers\n if not self.token or not self.api_endpoint:\n self.log(\"Astra DB token and API endpoint are required to fetch the list of Vectorize providers.\")\n\n return self.VECTORIZE_PROVIDERS_MAPPING\n\n try:\n self.log(\"Dynamically updating list of Vectorize providers.\")\n\n # Get the admin object\n client = DataAPIClient(token=self.token)\n admin = client.get_admin()\n\n # Get the embedding providers\n db_admin = admin.get_database_admin(self.api_endpoint)\n embedding_providers = db_admin.find_embedding_providers().as_dict()\n\n vectorize_providers_mapping = {}\n\n # Map the provider display name to the provider key and models\n for provider_key, provider_data in embedding_providers[\"embeddingProviders\"].items():\n display_name = provider_data[\"displayName\"]\n models = [model[\"name\"] for model in provider_data[\"models\"]]\n\n vectorize_providers_mapping[display_name] = [provider_key, models]\n\n # Sort the resulting dictionary\n return defaultdict(list, dict(sorted(vectorize_providers_mapping.items())))\n except Exception as e: # noqa: BLE001\n self.log(f\"Error fetching Vectorize providers: {e}\")\n\n return self.VECTORIZE_PROVIDERS_MAPPING\n\n def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None):\n if field_name == \"embedding_choice\":\n if field_value == \"Astra Vectorize\":\n self.del_fields(build_config, [\"embedding_model\"])\n\n # Update the providers mapping\n vectorize_providers = self.update_providers_mapping()\n\n new_parameter = DropdownInput(\n name=\"embedding_provider\",\n display_name=\"Embedding Provider\",\n options=vectorize_providers.keys(),\n value=\"\",\n required=True,\n real_time_refresh=True,\n ).to_dict()\n\n self.insert_in_dict(build_config, \"embedding_choice\", {\"embedding_provider\": new_parameter})\n else:\n self.del_fields(\n build_config,\n [\n \"embedding_provider\",\n \"model\",\n \"z_01_model_parameters\",\n \"z_02_api_key_name\",\n \"z_03_provider_api_key\",\n \"z_04_authentication\",\n ],\n )\n\n new_parameter = HandleInput(\n name=\"embedding_model\",\n display_name=\"Embedding Model\",\n input_types=[\"Embeddings\"],\n info=\"Allows an embedding model configuration.\",\n ).to_dict()\n\n self.insert_in_dict(build_config, \"embedding_choice\", {\"embedding_model\": new_parameter})\n\n elif field_name == \"embedding_provider\":\n self.del_fields(\n build_config,\n [\"model\", \"z_01_model_parameters\", \"z_02_api_key_name\", \"z_03_provider_api_key\", \"z_04_authentication\"],\n )\n\n # Update the providers mapping\n vectorize_providers = self.update_providers_mapping()\n model_options = vectorize_providers[field_value][1]\n\n new_parameter = DropdownInput(\n name=\"model\",\n display_name=\"Model\",\n info=\"The embedding model to use for the selected provider. Each provider has a different set of \"\n \"models available (full list at \"\n \"https://docs.datastax.com/en/astra-db-serverless/databases/embedding-generation.html):\\n\\n\"\n f\"{', '.join(model_options)}\",\n options=model_options,\n value=None,\n required=True,\n real_time_refresh=True,\n ).to_dict()\n\n self.insert_in_dict(build_config, \"embedding_provider\", {\"model\": new_parameter})\n\n elif field_name == \"model\":\n self.del_fields(\n build_config,\n [\"z_01_model_parameters\", \"z_02_api_key_name\", \"z_03_provider_api_key\", \"z_04_authentication\"],\n )\n\n new_parameter_1 = DictInput(\n name=\"z_01_model_parameters\",\n display_name=\"Model Parameters\",\n is_list=True,\n ).to_dict()\n\n new_parameter_2 = MessageTextInput(\n name=\"z_02_api_key_name\",\n display_name=\"API Key Name\",\n info=\"The name of the embeddings provider API key stored on Astra. \"\n \"If set, it will override the 'ProviderKey' in the authentication parameters.\",\n ).to_dict()\n\n new_parameter_3 = SecretStrInput(\n load_from_db=False,\n name=\"z_03_provider_api_key\",\n display_name=\"Provider API Key\",\n info=\"An alternative to the Astra Authentication that passes an API key for the provider \"\n \"with each request to Astra DB. \"\n \"This may be used when Vectorize is configured for the collection, \"\n \"but no corresponding provider secret is stored within Astra's key management system.\",\n ).to_dict()\n\n new_parameter_4 = DictInput(\n name=\"z_04_authentication\",\n display_name=\"Authentication Parameters\",\n is_list=True,\n ).to_dict()\n\n self.insert_in_dict(\n build_config,\n \"model\",\n {\n \"z_01_model_parameters\": new_parameter_1,\n \"z_02_api_key_name\": new_parameter_2,\n \"z_03_provider_api_key\": new_parameter_3,\n \"z_04_authentication\": new_parameter_4,\n },\n )\n\n return build_config\n\n def build_vectorize_options(self, **kwargs):\n for attribute in [\n \"embedding_provider\",\n \"model\",\n \"z_01_model_parameters\",\n \"z_02_api_key_name\",\n \"z_03_provider_api_key\",\n \"z_04_authentication\",\n ]:\n if not hasattr(self, attribute):\n setattr(self, attribute, None)\n\n # Fetch values from kwargs if any self.* attributes are None\n provider_value = self.VECTORIZE_PROVIDERS_MAPPING.get(self.embedding_provider, [None])[0] or kwargs.get(\n \"embedding_provider\"\n )\n model_name = self.model or kwargs.get(\"model\")\n authentication = {**(self.z_04_authentication or kwargs.get(\"z_04_authentication\", {}))}\n parameters = self.z_01_model_parameters or kwargs.get(\"z_01_model_parameters\", {})\n\n # Set the API key name if provided\n api_key_name = self.z_02_api_key_name or kwargs.get(\"z_02_api_key_name\")\n provider_key = self.z_03_provider_api_key or kwargs.get(\"z_03_provider_api_key\")\n if api_key_name:\n authentication[\"providerKey\"] = api_key_name\n\n # Set authentication and parameters to None if no values are provided\n if not authentication:\n authentication = None\n if not parameters:\n parameters = None\n\n return {\n # must match astrapy.info.CollectionVectorServiceOptions\n \"collection_vector_service_options\": {\n \"provider\": provider_value,\n \"modelName\": model_name,\n \"authentication\": authentication,\n \"parameters\": parameters,\n },\n \"collection_embedding_api_key\": provider_key,\n }\n\n @check_cached_vector_store\n def build_vector_store(self, vectorize_options=None):\n try:\n from langchain_astradb import AstraDBVectorStore\n from langchain_astradb.utils.astradb import SetupMode\n except ImportError as e:\n msg = (\n \"Could not import langchain Astra DB integration package. \"\n \"Please install it with `pip install langchain-astradb`.\"\n )\n raise ImportError(msg) from e\n\n try:\n if not self.setup_mode:\n self.setup_mode = self._inputs[\"setup_mode\"].options[0]\n\n setup_mode_value = SetupMode[self.setup_mode.upper()]\n except KeyError as e:\n msg = f\"Invalid setup mode: {self.setup_mode}\"\n raise ValueError(msg) from e\n\n if self.embedding_choice == \"Embedding Model\":\n embedding_dict = {\"embedding\": self.embedding_model}\n else:\n from astrapy.info import CollectionVectorServiceOptions\n\n # Fetch values from kwargs if any self.* attributes are None\n dict_options = vectorize_options or self.build_vectorize_options()\n\n # Set the embedding dictionary\n embedding_dict = {\n \"collection_vector_service_options\": CollectionVectorServiceOptions.from_dict(\n dict_options.get(\"collection_vector_service_options\")\n ),\n \"collection_embedding_api_key\": dict_options.get(\"collection_embedding_api_key\"),\n }\n\n try:\n vector_store = AstraDBVectorStore(\n collection_name=self.collection_name,\n token=self.token,\n api_endpoint=self.api_endpoint,\n namespace=self.keyspace or None,\n environment=parse_api_endpoint(self.api_endpoint).environment if self.api_endpoint else None,\n metric=self.metric or None,\n batch_size=self.batch_size or None,\n bulk_insert_batch_concurrency=self.bulk_insert_batch_concurrency or None,\n bulk_insert_overwrite_concurrency=self.bulk_insert_overwrite_concurrency or None,\n bulk_delete_concurrency=self.bulk_delete_concurrency or None,\n setup_mode=setup_mode_value,\n pre_delete_collection=self.pre_delete_collection,\n metadata_indexing_include=[s for s in self.metadata_indexing_include if s] or None,\n metadata_indexing_exclude=[s for s in self.metadata_indexing_exclude if s] or None,\n collection_indexing_policy=orjson.dumps(self.collection_indexing_policy)\n if self.collection_indexing_policy\n else None,\n **embedding_dict,\n )\n except Exception as e:\n msg = f\"Error initializing AstraDBVectorStore: {e}\"\n raise ValueError(msg) from e\n\n self._add_documents_to_vector_store(vector_store)\n\n return vector_store\n\n def _add_documents_to_vector_store(self, vector_store) -> None:\n documents = []\n for _input in self.ingest_data or []:\n if isinstance(_input, Data):\n documents.append(_input.to_lc_document())\n else:\n msg = \"Vector Store Inputs must be Data objects.\"\n raise TypeError(msg)\n\n if documents:\n self.log(f\"Adding {len(documents)} documents to the Vector Store.\")\n try:\n vector_store.add_documents(documents)\n except Exception as e:\n msg = f\"Error adding documents to AstraDBVectorStore: {e}\"\n raise ValueError(msg) from e\n else:\n self.log(\"No documents to add to the Vector Store.\")\n\n def _map_search_type(self) -> str:\n if self.search_type == \"Similarity with score threshold\":\n return \"similarity_score_threshold\"\n if self.search_type == \"MMR (Max Marginal Relevance)\":\n return \"mmr\"\n return \"similarity\"\n\n def _build_search_args(self):\n query = self.search_input if isinstance(self.search_input, str) and self.search_input.strip() else None\n search_filter = (\n {k: v for k, v in self.search_filter.items() if k and v and k.strip()} if self.search_filter else None\n )\n\n if query:\n args = {\n \"query\": query,\n \"search_type\": self._map_search_type(),\n \"k\": self.number_of_results,\n \"score_threshold\": self.search_score_threshold,\n }\n elif self.advanced_search_filter or search_filter:\n args = {\n \"n\": self.number_of_results,\n }\n else:\n return {}\n\n filter_arg = self.advanced_search_filter or {}\n\n if search_filter:\n self.log(self.log(f\"`search_filter` is deprecated. Use `advanced_search_filter`. Cleaned: {search_filter}\"))\n filter_arg.update(search_filter)\n\n if filter_arg:\n args[\"filter\"] = filter_arg\n\n return args\n\n def search_documents(self, vector_store=None) -> list[Data]:\n vector_store = vector_store or self.build_vector_store()\n\n self.log(f\"Search input: {self.search_input}\")\n self.log(f\"Search type: {self.search_type}\")\n self.log(f\"Number of results: {self.number_of_results}\")\n\n try:\n search_args = self._build_search_args()\n except Exception as e:\n msg = f\"Error in AstraDBVectorStore._build_search_args: {e}\"\n raise ValueError(msg) from e\n\n if not search_args:\n self.log(\"No search input or filters provided. Skipping search.\")\n return []\n\n docs = []\n search_method = \"search\" if \"query\" in search_args else \"metadata_search\"\n\n try:\n self.log(f\"Calling vector_store.{search_method} with args: {search_args}\")\n docs = getattr(vector_store, search_method)(**search_args)\n except Exception as e:\n msg = f\"Error performing {search_method} in AstraDBVectorStore: {e}\"\n raise ValueError(msg) from e\n\n self.log(f\"Retrieved documents: {len(docs)}\")\n\n data = docs_to_data(docs)\n self.log(f\"Converted documents to data: {len(data)}\")\n self.status = data\n return data\n\n def get_retriever_kwargs(self):\n search_args = self._build_search_args()\n return {\n \"search_type\": self._map_search_type(),\n \"search_kwargs\": search_args,\n }\n",
"fileTypes": [],
"file_path": "",
"password": false,
"name": "code",
"advanced": true,
"dynamic": true,
"info": "",
"load_from_db": false,
"title_case": false
},
"collection_indexing_policy": {
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": false,
"placeholder": "",
"show": true,
"name": "collection_indexing_policy",
"value": "",
"display_name": "Collection Indexing Policy",
"advanced": true,
"dynamic": false,
"info": "Optional JSON string for the \"indexing\" field of the collection. See https://docs.datastax.com/en/astra-db-serverless/api-reference/collections.html#the-indexing-option",
"title_case": false,
"type": "str",
"_input_type": "StrInput"
},
"collection_name": {
"trace_as_metadata": true,
"load_from_db": false,
"list": false,
"required": true,
"placeholder": "",
"show": true,
"name": "collection_name",
"value": "data_sme",
"display_name": "Collection Name",
"advanced": false,
"dynamic": false,
"info": "The name of the collection within Astra DB where the vectors will be stored.",
"title_case": false,
"type": "str",
"_input_type": "StrInput"
},
"embedding_choice": {
"tool_mode": false,
"trace_as_metadata": true,
"options": [
"Embedding Model",
"Astra Vectorize"
],
"combobox": false,
"required": false,
"placeholder": "",
"show": true,
"name": "embedding_choice",
"value": "Embedding Model",