codekingpro commited on
Commit
389466b
·
verified ·
1 Parent(s): 97ff9bc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/user_packages/Python313/site-packages/langchain_community/__pycache__/__init__.cpython-313.pyc +0 -0
  2. python/user_packages/Python313/site-packages/langchain_community/embeddings/__init__.py +454 -0
  3. python/user_packages/Python313/site-packages/langchain_community/embeddings/javelin_ai_gateway.py +109 -0
  4. python/user_packages/Python313/site-packages/langchain_community/embeddings/jina.py +124 -0
  5. python/user_packages/Python313/site-packages/langchain_community/embeddings/johnsnowlabs.py +91 -0
  6. python/user_packages/Python313/site-packages/langchain_community/embeddings/laser.py +89 -0
  7. python/user_packages/Python313/site-packages/langchain_community/embeddings/llamacpp.py +145 -0
  8. python/user_packages/Python313/site-packages/langchain_community/embeddings/llamafile.py +119 -0
  9. python/user_packages/Python313/site-packages/langchain_community/embeddings/llm_rails.py +74 -0
  10. python/user_packages/Python313/site-packages/langchain_community/embeddings/localai.py +347 -0
  11. python/user_packages/Python313/site-packages/langchain_community/embeddings/minimax.py +201 -0
  12. python/user_packages/Python313/site-packages/langchain_community/embeddings/mlflow.py +91 -0
  13. python/user_packages/Python313/site-packages/langchain_community/embeddings/mlflow_gateway.py +79 -0
  14. python/user_packages/Python313/site-packages/langchain_community/embeddings/model2vec.py +66 -0
  15. python/user_packages/Python313/site-packages/langchain_community/embeddings/modelscope_hub.py +70 -0
  16. python/user_packages/Python313/site-packages/langchain_community/embeddings/mosaicml.py +147 -0
  17. python/user_packages/Python313/site-packages/langchain_community/embeddings/naver.py +236 -0
  18. python/user_packages/Python313/site-packages/langchain_community/embeddings/nemo.py +190 -0
  19. python/user_packages/Python313/site-packages/langchain_community/embeddings/nlpcloud.py +75 -0
  20. python/user_packages/Python313/site-packages/langchain_community/embeddings/oci_generative_ai.py +232 -0
  21. python/user_packages/Python313/site-packages/langchain_community/embeddings/octoai_embeddings.py +86 -0
  22. python/user_packages/Python313/site-packages/langchain_community/embeddings/ollama.py +228 -0
  23. python/user_packages/Python313/site-packages/langchain_community/embeddings/openai.py +716 -0
  24. python/user_packages/Python313/site-packages/langchain_community/embeddings/openvino.py +351 -0
  25. python/user_packages/Python313/site-packages/langchain_community/embeddings/optimum_intel.py +208 -0
  26. python/user_packages/Python313/site-packages/langchain_community/embeddings/oracleai.py +194 -0
  27. python/user_packages/Python313/site-packages/langchain_community/embeddings/ovhcloud.py +115 -0
  28. python/user_packages/Python313/site-packages/langchain_community/embeddings/premai.py +130 -0
  29. python/user_packages/Python313/site-packages/langchain_community/embeddings/sagemaker_endpoint.py +210 -0
  30. python/user_packages/Python313/site-packages/langchain_community/embeddings/sambanova.py +324 -0
  31. python/user_packages/Python313/site-packages/langchain_community/embeddings/self_hosted.py +101 -0
  32. python/user_packages/Python313/site-packages/langchain_community/embeddings/self_hosted_hugging_face.py +168 -0
  33. python/user_packages/Python313/site-packages/langchain_community/embeddings/sentence_transformer.py +5 -0
  34. python/user_packages/Python313/site-packages/langchain_community/embeddings/solar.py +142 -0
  35. python/user_packages/Python313/site-packages/langchain_community/embeddings/spacy_embeddings.py +116 -0
  36. python/user_packages/Python313/site-packages/langchain_community/embeddings/sparkllm.py +276 -0
  37. python/user_packages/Python313/site-packages/langchain_community/embeddings/tensorflow_hub.py +75 -0
  38. python/user_packages/Python313/site-packages/langchain_community/embeddings/text2vec.py +81 -0
  39. python/user_packages/Python313/site-packages/langchain_community/embeddings/textembed.py +350 -0
  40. python/user_packages/Python313/site-packages/langchain_community/embeddings/titan_takeoff.py +210 -0
  41. python/user_packages/Python313/site-packages/langchain_community/embeddings/vertexai.py +361 -0
  42. python/user_packages/Python313/site-packages/langchain_community/embeddings/volcengine.py +128 -0
  43. python/user_packages/Python313/site-packages/langchain_community/embeddings/voyageai.py +230 -0
  44. python/user_packages/Python313/site-packages/langchain_community/embeddings/xinference.py +139 -0
  45. python/user_packages/Python313/site-packages/langchain_community/embeddings/yandex.py +214 -0
  46. python/user_packages/Python313/site-packages/langchain_community/embeddings/zhipuai.py +128 -0
  47. python/user_packages/Python313/site-packages/langchain_community/example_selectors/__init__.py +18 -0
  48. python/user_packages/Python313/site-packages/langchain_community/example_selectors/ngram_overlap.py +116 -0
  49. python/user_packages/Python313/site-packages/langchain_community/graph_vectorstores/__init__.py +157 -0
  50. python/user_packages/Python313/site-packages/langchain_community/graph_vectorstores/base.py +917 -0
python/user_packages/Python313/site-packages/langchain_community/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (505 Bytes). View file
 
python/user_packages/Python313/site-packages/langchain_community/embeddings/__init__.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Embedding models** are wrappers around embedding models
2
+ from different APIs and services.
3
+
4
+ **Embedding models** can be LLMs or not.
5
+
6
+ **Class hierarchy:**
7
+
8
+ .. code-block::
9
+
10
+ Embeddings --> <name>Embeddings # Examples: OpenAIEmbeddings, HuggingFaceEmbeddings
11
+ """
12
+
13
+ import importlib
14
+ import logging
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ if TYPE_CHECKING:
18
+ from langchain_community.embeddings.aleph_alpha import (
19
+ AlephAlphaAsymmetricSemanticEmbedding,
20
+ AlephAlphaSymmetricSemanticEmbedding,
21
+ )
22
+ from langchain_community.embeddings.anyscale import (
23
+ AnyscaleEmbeddings,
24
+ )
25
+ from langchain_community.embeddings.ascend import (
26
+ AscendEmbeddings,
27
+ )
28
+ from langchain_community.embeddings.awa import (
29
+ AwaEmbeddings,
30
+ )
31
+ from langchain_community.embeddings.azure_openai import (
32
+ AzureOpenAIEmbeddings,
33
+ )
34
+ from langchain_community.embeddings.baichuan import (
35
+ BaichuanTextEmbeddings,
36
+ )
37
+ from langchain_community.embeddings.baidu_qianfan_endpoint import (
38
+ QianfanEmbeddingsEndpoint,
39
+ )
40
+ from langchain_community.embeddings.bedrock import (
41
+ BedrockEmbeddings,
42
+ )
43
+ from langchain_community.embeddings.bookend import (
44
+ BookendEmbeddings,
45
+ )
46
+ from langchain_community.embeddings.clarifai import (
47
+ ClarifaiEmbeddings,
48
+ )
49
+ from langchain_community.embeddings.clova import (
50
+ ClovaEmbeddings,
51
+ )
52
+ from langchain_community.embeddings.cohere import (
53
+ CohereEmbeddings,
54
+ )
55
+ from langchain_community.embeddings.dashscope import (
56
+ DashScopeEmbeddings,
57
+ )
58
+ from langchain_community.embeddings.databricks import (
59
+ DatabricksEmbeddings,
60
+ )
61
+ from langchain_community.embeddings.deepinfra import (
62
+ DeepInfraEmbeddings,
63
+ )
64
+ from langchain_community.embeddings.edenai import (
65
+ EdenAiEmbeddings,
66
+ )
67
+ from langchain_community.embeddings.elasticsearch import (
68
+ ElasticsearchEmbeddings,
69
+ )
70
+ from langchain_community.embeddings.embaas import (
71
+ EmbaasEmbeddings,
72
+ )
73
+ from langchain_community.embeddings.ernie import (
74
+ ErnieEmbeddings,
75
+ )
76
+ from langchain_community.embeddings.fake import (
77
+ DeterministicFakeEmbedding,
78
+ FakeEmbeddings,
79
+ )
80
+ from langchain_community.embeddings.fastembed import (
81
+ FastEmbedEmbeddings,
82
+ )
83
+ from langchain_community.embeddings.gigachat import (
84
+ GigaChatEmbeddings,
85
+ )
86
+ from langchain_community.embeddings.google_palm import (
87
+ GooglePalmEmbeddings,
88
+ )
89
+ from langchain_community.embeddings.gpt4all import (
90
+ GPT4AllEmbeddings,
91
+ )
92
+ from langchain_community.embeddings.gradient_ai import (
93
+ GradientEmbeddings,
94
+ )
95
+ from langchain_community.embeddings.huggingface import (
96
+ HuggingFaceBgeEmbeddings,
97
+ HuggingFaceEmbeddings,
98
+ HuggingFaceInferenceAPIEmbeddings,
99
+ HuggingFaceInstructEmbeddings,
100
+ )
101
+ from langchain_community.embeddings.huggingface_hub import (
102
+ HuggingFaceHubEmbeddings,
103
+ )
104
+ from langchain_community.embeddings.hunyuan import (
105
+ HunyuanEmbeddings,
106
+ )
107
+ from langchain_community.embeddings.infinity import (
108
+ InfinityEmbeddings,
109
+ )
110
+ from langchain_community.embeddings.infinity_local import (
111
+ InfinityEmbeddingsLocal,
112
+ )
113
+ from langchain_community.embeddings.ipex_llm import IpexLLMBgeEmbeddings
114
+ from langchain_community.embeddings.itrex import (
115
+ QuantizedBgeEmbeddings,
116
+ )
117
+ from langchain_community.embeddings.javelin_ai_gateway import (
118
+ JavelinAIGatewayEmbeddings,
119
+ )
120
+ from langchain_community.embeddings.jina import (
121
+ JinaEmbeddings,
122
+ )
123
+ from langchain_community.embeddings.johnsnowlabs import (
124
+ JohnSnowLabsEmbeddings,
125
+ )
126
+ from langchain_community.embeddings.laser import (
127
+ LaserEmbeddings,
128
+ )
129
+ from langchain_community.embeddings.llamacpp import (
130
+ LlamaCppEmbeddings,
131
+ )
132
+ from langchain_community.embeddings.llamafile import (
133
+ LlamafileEmbeddings,
134
+ )
135
+ from langchain_community.embeddings.llm_rails import (
136
+ LLMRailsEmbeddings,
137
+ )
138
+ from langchain_community.embeddings.localai import (
139
+ LocalAIEmbeddings,
140
+ )
141
+ from langchain_community.embeddings.minimax import (
142
+ MiniMaxEmbeddings,
143
+ )
144
+ from langchain_community.embeddings.mlflow import (
145
+ MlflowCohereEmbeddings,
146
+ MlflowEmbeddings,
147
+ )
148
+ from langchain_community.embeddings.mlflow_gateway import (
149
+ MlflowAIGatewayEmbeddings,
150
+ )
151
+ from langchain_community.embeddings.model2vec import (
152
+ Model2vecEmbeddings,
153
+ )
154
+ from langchain_community.embeddings.modelscope_hub import (
155
+ ModelScopeEmbeddings,
156
+ )
157
+ from langchain_community.embeddings.mosaicml import (
158
+ MosaicMLInstructorEmbeddings,
159
+ )
160
+ from langchain_community.embeddings.naver import (
161
+ ClovaXEmbeddings,
162
+ )
163
+ from langchain_community.embeddings.nemo import (
164
+ NeMoEmbeddings,
165
+ )
166
+ from langchain_community.embeddings.nlpcloud import (
167
+ NLPCloudEmbeddings,
168
+ )
169
+ from langchain_community.embeddings.oci_generative_ai import (
170
+ OCIGenAIEmbeddings,
171
+ )
172
+ from langchain_community.embeddings.octoai_embeddings import (
173
+ OctoAIEmbeddings,
174
+ )
175
+ from langchain_community.embeddings.ollama import (
176
+ OllamaEmbeddings,
177
+ )
178
+ from langchain_community.embeddings.openai import (
179
+ OpenAIEmbeddings,
180
+ )
181
+ from langchain_community.embeddings.openvino import (
182
+ OpenVINOBgeEmbeddings,
183
+ OpenVINOEmbeddings,
184
+ )
185
+ from langchain_community.embeddings.optimum_intel import (
186
+ QuantizedBiEncoderEmbeddings,
187
+ )
188
+ from langchain_community.embeddings.oracleai import (
189
+ OracleEmbeddings,
190
+ )
191
+ from langchain_community.embeddings.ovhcloud import (
192
+ OVHCloudEmbeddings,
193
+ )
194
+ from langchain_community.embeddings.premai import (
195
+ PremAIEmbeddings,
196
+ )
197
+ from langchain_community.embeddings.sagemaker_endpoint import (
198
+ SagemakerEndpointEmbeddings,
199
+ )
200
+ from langchain_community.embeddings.sambanova import (
201
+ SambaStudioEmbeddings,
202
+ )
203
+ from langchain_community.embeddings.self_hosted import (
204
+ SelfHostedEmbeddings,
205
+ )
206
+ from langchain_community.embeddings.self_hosted_hugging_face import (
207
+ SelfHostedHuggingFaceEmbeddings,
208
+ SelfHostedHuggingFaceInstructEmbeddings,
209
+ )
210
+ from langchain_community.embeddings.sentence_transformer import (
211
+ SentenceTransformerEmbeddings,
212
+ )
213
+ from langchain_community.embeddings.solar import (
214
+ SolarEmbeddings,
215
+ )
216
+ from langchain_community.embeddings.spacy_embeddings import (
217
+ SpacyEmbeddings,
218
+ )
219
+ from langchain_community.embeddings.sparkllm import (
220
+ SparkLLMTextEmbeddings,
221
+ )
222
+ from langchain_community.embeddings.tensorflow_hub import (
223
+ TensorflowHubEmbeddings,
224
+ )
225
+ from langchain_community.embeddings.textembed import (
226
+ TextEmbedEmbeddings,
227
+ )
228
+ from langchain_community.embeddings.titan_takeoff import (
229
+ TitanTakeoffEmbed,
230
+ )
231
+ from langchain_community.embeddings.vertexai import (
232
+ VertexAIEmbeddings,
233
+ )
234
+ from langchain_community.embeddings.volcengine import (
235
+ VolcanoEmbeddings,
236
+ )
237
+ from langchain_community.embeddings.voyageai import (
238
+ VoyageEmbeddings,
239
+ )
240
+ from langchain_community.embeddings.xinference import (
241
+ XinferenceEmbeddings,
242
+ )
243
+ from langchain_community.embeddings.yandex import (
244
+ YandexGPTEmbeddings,
245
+ )
246
+ from langchain_community.embeddings.zhipuai import (
247
+ ZhipuAIEmbeddings,
248
+ )
249
+
250
+ __all__ = [
251
+ "AlephAlphaAsymmetricSemanticEmbedding",
252
+ "AlephAlphaSymmetricSemanticEmbedding",
253
+ "AnyscaleEmbeddings",
254
+ "AscendEmbeddings",
255
+ "AwaEmbeddings",
256
+ "AzureOpenAIEmbeddings",
257
+ "BaichuanTextEmbeddings",
258
+ "BedrockEmbeddings",
259
+ "BookendEmbeddings",
260
+ "ClarifaiEmbeddings",
261
+ "ClovaEmbeddings",
262
+ "ClovaXEmbeddings",
263
+ "CohereEmbeddings",
264
+ "DashScopeEmbeddings",
265
+ "DatabricksEmbeddings",
266
+ "DeepInfraEmbeddings",
267
+ "DeterministicFakeEmbedding",
268
+ "EdenAiEmbeddings",
269
+ "ElasticsearchEmbeddings",
270
+ "EmbaasEmbeddings",
271
+ "ErnieEmbeddings",
272
+ "FakeEmbeddings",
273
+ "FastEmbedEmbeddings",
274
+ "GPT4AllEmbeddings",
275
+ "GigaChatEmbeddings",
276
+ "GooglePalmEmbeddings",
277
+ "GradientEmbeddings",
278
+ "HuggingFaceBgeEmbeddings",
279
+ "HuggingFaceEmbeddings",
280
+ "HuggingFaceHubEmbeddings",
281
+ "HuggingFaceInferenceAPIEmbeddings",
282
+ "HuggingFaceInstructEmbeddings",
283
+ "InfinityEmbeddings",
284
+ "InfinityEmbeddingsLocal",
285
+ "IpexLLMBgeEmbeddings",
286
+ "JavelinAIGatewayEmbeddings",
287
+ "JinaEmbeddings",
288
+ "JohnSnowLabsEmbeddings",
289
+ "LLMRailsEmbeddings",
290
+ "LaserEmbeddings",
291
+ "LlamaCppEmbeddings",
292
+ "LlamafileEmbeddings",
293
+ "LocalAIEmbeddings",
294
+ "MiniMaxEmbeddings",
295
+ "MlflowAIGatewayEmbeddings",
296
+ "MlflowCohereEmbeddings",
297
+ "MlflowEmbeddings",
298
+ "Model2vecEmbeddings",
299
+ "ModelScopeEmbeddings",
300
+ "MosaicMLInstructorEmbeddings",
301
+ "NLPCloudEmbeddings",
302
+ "NeMoEmbeddings",
303
+ "OCIGenAIEmbeddings",
304
+ "OctoAIEmbeddings",
305
+ "OllamaEmbeddings",
306
+ "OpenAIEmbeddings",
307
+ "OpenVINOBgeEmbeddings",
308
+ "OpenVINOEmbeddings",
309
+ "OracleEmbeddings",
310
+ "OVHCloudEmbeddings",
311
+ "PremAIEmbeddings",
312
+ "QianfanEmbeddingsEndpoint",
313
+ "QuantizedBgeEmbeddings",
314
+ "QuantizedBiEncoderEmbeddings",
315
+ "SagemakerEndpointEmbeddings",
316
+ "SambaStudioEmbeddings",
317
+ "SelfHostedEmbeddings",
318
+ "SelfHostedHuggingFaceEmbeddings",
319
+ "SelfHostedHuggingFaceInstructEmbeddings",
320
+ "SentenceTransformerEmbeddings",
321
+ "SolarEmbeddings",
322
+ "SpacyEmbeddings",
323
+ "SparkLLMTextEmbeddings",
324
+ "TensorflowHubEmbeddings",
325
+ "TextEmbedEmbeddings",
326
+ "TitanTakeoffEmbed",
327
+ "VertexAIEmbeddings",
328
+ "VolcanoEmbeddings",
329
+ "VoyageEmbeddings",
330
+ "XinferenceEmbeddings",
331
+ "YandexGPTEmbeddings",
332
+ "ZhipuAIEmbeddings",
333
+ "HunyuanEmbeddings",
334
+ ]
335
+
336
+ _module_lookup = {
337
+ "AlephAlphaAsymmetricSemanticEmbedding": "langchain_community.embeddings.aleph_alpha", # noqa: E501
338
+ "AlephAlphaSymmetricSemanticEmbedding": "langchain_community.embeddings.aleph_alpha", # noqa: E501
339
+ "AnyscaleEmbeddings": "langchain_community.embeddings.anyscale",
340
+ "AwaEmbeddings": "langchain_community.embeddings.awa",
341
+ "AzureOpenAIEmbeddings": "langchain_community.embeddings.azure_openai",
342
+ "BaichuanTextEmbeddings": "langchain_community.embeddings.baichuan",
343
+ "BedrockEmbeddings": "langchain_community.embeddings.bedrock",
344
+ "BookendEmbeddings": "langchain_community.embeddings.bookend",
345
+ "ClarifaiEmbeddings": "langchain_community.embeddings.clarifai",
346
+ "ClovaEmbeddings": "langchain_community.embeddings.clova",
347
+ "ClovaXEmbeddings": "langchain_community.embeddings.naver",
348
+ "CohereEmbeddings": "langchain_community.embeddings.cohere",
349
+ "DashScopeEmbeddings": "langchain_community.embeddings.dashscope",
350
+ "DatabricksEmbeddings": "langchain_community.embeddings.databricks",
351
+ "DeepInfraEmbeddings": "langchain_community.embeddings.deepinfra",
352
+ "DeterministicFakeEmbedding": "langchain_community.embeddings.fake",
353
+ "EdenAiEmbeddings": "langchain_community.embeddings.edenai",
354
+ "ElasticsearchEmbeddings": "langchain_community.embeddings.elasticsearch",
355
+ "EmbaasEmbeddings": "langchain_community.embeddings.embaas",
356
+ "ErnieEmbeddings": "langchain_community.embeddings.ernie",
357
+ "FakeEmbeddings": "langchain_community.embeddings.fake",
358
+ "FastEmbedEmbeddings": "langchain_community.embeddings.fastembed",
359
+ "GPT4AllEmbeddings": "langchain_community.embeddings.gpt4all",
360
+ "GooglePalmEmbeddings": "langchain_community.embeddings.google_palm",
361
+ "GradientEmbeddings": "langchain_community.embeddings.gradient_ai",
362
+ "GigaChatEmbeddings": "langchain_community.embeddings.gigachat",
363
+ "HuggingFaceBgeEmbeddings": "langchain_community.embeddings.huggingface",
364
+ "HuggingFaceEmbeddings": "langchain_community.embeddings.huggingface",
365
+ "HuggingFaceHubEmbeddings": "langchain_community.embeddings.huggingface_hub",
366
+ "HuggingFaceInferenceAPIEmbeddings": "langchain_community.embeddings.huggingface",
367
+ "HuggingFaceInstructEmbeddings": "langchain_community.embeddings.huggingface",
368
+ "InfinityEmbeddings": "langchain_community.embeddings.infinity",
369
+ "InfinityEmbeddingsLocal": "langchain_community.embeddings.infinity_local",
370
+ "IpexLLMBgeEmbeddings": "langchain_community.embeddings.ipex_llm",
371
+ "JavelinAIGatewayEmbeddings": "langchain_community.embeddings.javelin_ai_gateway",
372
+ "JinaEmbeddings": "langchain_community.embeddings.jina",
373
+ "JohnSnowLabsEmbeddings": "langchain_community.embeddings.johnsnowlabs",
374
+ "LLMRailsEmbeddings": "langchain_community.embeddings.llm_rails",
375
+ "LaserEmbeddings": "langchain_community.embeddings.laser",
376
+ "LlamaCppEmbeddings": "langchain_community.embeddings.llamacpp",
377
+ "LlamafileEmbeddings": "langchain_community.embeddings.llamafile",
378
+ "LocalAIEmbeddings": "langchain_community.embeddings.localai",
379
+ "MiniMaxEmbeddings": "langchain_community.embeddings.minimax",
380
+ "MlflowAIGatewayEmbeddings": "langchain_community.embeddings.mlflow_gateway",
381
+ "MlflowCohereEmbeddings": "langchain_community.embeddings.mlflow",
382
+ "MlflowEmbeddings": "langchain_community.embeddings.mlflow",
383
+ "Model2vecEmbeddings": "langchain_community.embeddings.model2vec",
384
+ "ModelScopeEmbeddings": "langchain_community.embeddings.modelscope_hub",
385
+ "MosaicMLInstructorEmbeddings": "langchain_community.embeddings.mosaicml",
386
+ "NLPCloudEmbeddings": "langchain_community.embeddings.nlpcloud",
387
+ "NeMoEmbeddings": "langchain_community.embeddings.nemo",
388
+ "OCIGenAIEmbeddings": "langchain_community.embeddings.oci_generative_ai",
389
+ "OctoAIEmbeddings": "langchain_community.embeddings.octoai_embeddings",
390
+ "OllamaEmbeddings": "langchain_community.embeddings.ollama",
391
+ "OpenAIEmbeddings": "langchain_community.embeddings.openai",
392
+ "OpenVINOEmbeddings": "langchain_community.embeddings.openvino",
393
+ "OpenVINOBgeEmbeddings": "langchain_community.embeddings.openvino",
394
+ "QianfanEmbeddingsEndpoint": "langchain_community.embeddings.baidu_qianfan_endpoint", # noqa: E501
395
+ "QuantizedBgeEmbeddings": "langchain_community.embeddings.itrex",
396
+ "QuantizedBiEncoderEmbeddings": "langchain_community.embeddings.optimum_intel",
397
+ "OracleEmbeddings": "langchain_community.embeddings.oracleai",
398
+ "OVHCloudEmbeddings": "langchain_community.embeddings.ovhcloud",
399
+ "SagemakerEndpointEmbeddings": "langchain_community.embeddings.sagemaker_endpoint",
400
+ "SambaStudioEmbeddings": "langchain_community.embeddings.sambanova",
401
+ "SelfHostedEmbeddings": "langchain_community.embeddings.self_hosted",
402
+ "SelfHostedHuggingFaceEmbeddings": "langchain_community.embeddings.self_hosted_hugging_face", # noqa: E501
403
+ "SelfHostedHuggingFaceInstructEmbeddings": "langchain_community.embeddings.self_hosted_hugging_face", # noqa: E501
404
+ "SentenceTransformerEmbeddings": "langchain_community.embeddings.sentence_transformer", # noqa: E501
405
+ "SolarEmbeddings": "langchain_community.embeddings.solar",
406
+ "SpacyEmbeddings": "langchain_community.embeddings.spacy_embeddings",
407
+ "SparkLLMTextEmbeddings": "langchain_community.embeddings.sparkllm",
408
+ "TensorflowHubEmbeddings": "langchain_community.embeddings.tensorflow_hub",
409
+ "VertexAIEmbeddings": "langchain_community.embeddings.vertexai",
410
+ "VolcanoEmbeddings": "langchain_community.embeddings.volcengine",
411
+ "VoyageEmbeddings": "langchain_community.embeddings.voyageai",
412
+ "XinferenceEmbeddings": "langchain_community.embeddings.xinference",
413
+ "TextEmbedEmbeddings": "langchain_community.embeddings.textembed",
414
+ "TitanTakeoffEmbed": "langchain_community.embeddings.titan_takeoff",
415
+ "PremAIEmbeddings": "langchain_community.embeddings.premai",
416
+ "YandexGPTEmbeddings": "langchain_community.embeddings.yandex",
417
+ "AscendEmbeddings": "langchain_community.embeddings.ascend",
418
+ "ZhipuAIEmbeddings": "langchain_community.embeddings.zhipuai",
419
+ "HunyuanEmbeddings": "langchain_community.embeddings.hunyuan",
420
+ }
421
+
422
+
423
+ def __getattr__(name: str) -> Any:
424
+ if name in _module_lookup:
425
+ module = importlib.import_module(_module_lookup[name])
426
+ return getattr(module, name)
427
+ raise AttributeError(f"module {__name__} has no attribute {name}")
428
+
429
+
430
+ logger = logging.getLogger(__name__)
431
+
432
+
433
+ # TODO: this is in here to maintain backwards compatibility
434
+ class HypotheticalDocumentEmbedder:
435
+ def __init__(self, *args: Any, **kwargs: Any):
436
+ logger.warning(
437
+ "Using a deprecated class. Please use "
438
+ "`from langchain_classic.chains import HypotheticalDocumentEmbedder` "
439
+ "instead"
440
+ )
441
+ from langchain_classic.chains.hyde.base import HypotheticalDocumentEmbedder as H
442
+
443
+ return H(*args, **kwargs) # type: ignore[return-value]
444
+
445
+ @classmethod
446
+ def from_llm(cls, *args: Any, **kwargs: Any) -> Any:
447
+ logger.warning(
448
+ "Using a deprecated class. Please use "
449
+ "`from langchain_classic.chains import HypotheticalDocumentEmbedder` "
450
+ "instead"
451
+ )
452
+ from langchain_classic.chains.hyde.base import HypotheticalDocumentEmbedder as H
453
+
454
+ return H.from_llm(*args, **kwargs)
python/user_packages/Python313/site-packages/langchain_community/embeddings/javelin_ai_gateway.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Iterator, List, Optional
4
+
5
+ from langchain_core.embeddings import Embeddings
6
+ from pydantic import BaseModel
7
+
8
+
9
+ def _chunk(texts: List[str], size: int) -> Iterator[List[str]]:
10
+ for i in range(0, len(texts), size):
11
+ yield texts[i : i + size]
12
+
13
+
14
+ class JavelinAIGatewayEmbeddings(Embeddings, BaseModel):
15
+ """Javelin AI Gateway embeddings.
16
+
17
+ To use, you should have the ``javelin_sdk`` python package installed.
18
+ For more information, see https://docs.getjavelin.io
19
+
20
+ Example:
21
+ .. code-block:: python
22
+
23
+ from langchain_community.embeddings import JavelinAIGatewayEmbeddings
24
+
25
+ embeddings = JavelinAIGatewayEmbeddings(
26
+ gateway_uri="<javelin-ai-gateway-uri>",
27
+ route="<your-javelin-gateway-embeddings-route>"
28
+ )
29
+ """
30
+
31
+ client: Any
32
+ """javelin client."""
33
+
34
+ route: str
35
+ """The route to use for the Javelin AI Gateway API."""
36
+
37
+ gateway_uri: Optional[str] = None
38
+ """The URI for the Javelin AI Gateway API."""
39
+
40
+ javelin_api_key: Optional[str] = None
41
+ """The API key for the Javelin AI Gateway API."""
42
+
43
+ def __init__(self, **kwargs: Any):
44
+ try:
45
+ from javelin_sdk import (
46
+ JavelinClient,
47
+ UnauthorizedError,
48
+ )
49
+ except ImportError:
50
+ raise ImportError(
51
+ "Could not import javelin_sdk python package. "
52
+ "Please install it with `pip install javelin_sdk`."
53
+ )
54
+
55
+ super().__init__(**kwargs)
56
+ if self.gateway_uri:
57
+ try:
58
+ self.client = JavelinClient(
59
+ base_url=self.gateway_uri, api_key=self.javelin_api_key
60
+ )
61
+ except UnauthorizedError as e:
62
+ raise ValueError("Javelin: Incorrect API Key.") from e
63
+
64
+ def _query(self, texts: List[str]) -> List[List[float]]:
65
+ embeddings = []
66
+ for txt in _chunk(texts, 20):
67
+ try:
68
+ resp = self.client.query_route(self.route, query_body={"input": txt})
69
+ resp_dict = resp.dict()
70
+
71
+ embeddings_chunk = resp_dict.get("llm_response", {}).get("data", [])
72
+ for item in embeddings_chunk:
73
+ if "embedding" in item:
74
+ embeddings.append(item["embedding"])
75
+ except ValueError as e:
76
+ print("Failed to query route: " + str(e)) # noqa: T201
77
+
78
+ return embeddings
79
+
80
+ async def _aquery(self, texts: List[str]) -> List[List[float]]:
81
+ embeddings = []
82
+ for txt in _chunk(texts, 20):
83
+ try:
84
+ resp = await self.client.aquery_route(
85
+ self.route, query_body={"input": txt}
86
+ )
87
+ resp_dict = resp.dict()
88
+
89
+ embeddings_chunk = resp_dict.get("llm_response", {}).get("data", [])
90
+ for item in embeddings_chunk:
91
+ if "embedding" in item:
92
+ embeddings.append(item["embedding"])
93
+ except ValueError as e:
94
+ print("Failed to query route: " + str(e)) # noqa: T201
95
+
96
+ return embeddings
97
+
98
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
99
+ return self._query(texts)
100
+
101
+ def embed_query(self, text: str) -> List[float]:
102
+ return self._query([text])[0]
103
+
104
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
105
+ return await self._aquery(texts)
106
+
107
+ async def aembed_query(self, text: str) -> List[float]:
108
+ result = await self._aquery([text])
109
+ return result[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/jina.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ from os.path import exists
3
+ from typing import Any, Dict, List, Optional
4
+ from urllib.parse import urlparse
5
+
6
+ import requests
7
+ from langchain_core.embeddings import Embeddings
8
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
9
+ from pydantic import BaseModel, ConfigDict, SecretStr, model_validator
10
+
11
+ JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"
12
+
13
+
14
+ def is_local(url: str) -> bool:
15
+ """Check if a URL is a local file.
16
+
17
+ Args:
18
+ url (str): The URL to check.
19
+
20
+ Returns:
21
+ bool: True if the URL is a local file, False otherwise.
22
+ """
23
+ url_parsed = urlparse(url)
24
+ if url_parsed.scheme in ("file", ""): # Possibly a local file
25
+ return exists(url_parsed.path)
26
+ return False
27
+
28
+
29
+ def get_bytes_str(file_path: str) -> str:
30
+ """Get the bytes string of a file.
31
+
32
+ Args:
33
+ file_path (str): The path to the file.
34
+
35
+ Returns:
36
+ str: The bytes string of the file.
37
+ """
38
+ with open(file_path, "rb") as image_file:
39
+ return base64.b64encode(image_file.read()).decode("utf-8")
40
+
41
+
42
+ class JinaEmbeddings(BaseModel, Embeddings):
43
+ """Jina embedding models."""
44
+
45
+ session: Any #: :meta private:
46
+ model_name: str = "jina-embeddings-v2-base-en"
47
+ jina_api_key: Optional[SecretStr] = None
48
+
49
+ model_config = ConfigDict(protected_namespaces=())
50
+
51
+ @model_validator(mode="before")
52
+ @classmethod
53
+ def validate_environment(cls, values: Dict) -> Any:
54
+ """Validate that auth token exists in environment."""
55
+ try:
56
+ jina_api_key = convert_to_secret_str(
57
+ get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY")
58
+ )
59
+ except ValueError as original_exc:
60
+ try:
61
+ jina_api_key = convert_to_secret_str(
62
+ get_from_dict_or_env(values, "jina_auth_token", "JINA_AUTH_TOKEN")
63
+ )
64
+ except ValueError:
65
+ raise original_exc
66
+ session = requests.Session()
67
+ session.headers.update(
68
+ {
69
+ "Authorization": f"Bearer {jina_api_key.get_secret_value()}",
70
+ "Accept-Encoding": "identity",
71
+ "Content-type": "application/json",
72
+ }
73
+ )
74
+ values["session"] = session
75
+ return values
76
+
77
+ def _embed(self, input: Any) -> List[List[float]]:
78
+ # Call Jina AI Embedding API
79
+ resp = self.session.post(
80
+ JINA_API_URL, json={"input": input, "model": self.model_name}
81
+ ).json()
82
+ if "data" not in resp:
83
+ raise RuntimeError(resp["detail"])
84
+
85
+ embeddings = resp["data"]
86
+
87
+ # Sort resulting embeddings by index
88
+ sorted_embeddings = sorted(embeddings, key=lambda e: e["index"])
89
+
90
+ # Return just the embeddings
91
+ return [result["embedding"] for result in sorted_embeddings]
92
+
93
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
94
+ """Call out to Jina's embedding endpoint.
95
+ Args:
96
+ texts: The list of texts to embed.
97
+ Returns:
98
+ List of embeddings, one for each text.
99
+ """
100
+ return self._embed(texts)
101
+
102
+ def embed_query(self, text: str) -> List[float]:
103
+ """Call out to Jina's embedding endpoint.
104
+ Args:
105
+ text: The text to embed.
106
+ Returns:
107
+ Embeddings for the text.
108
+ """
109
+ return self._embed([text])[0]
110
+
111
+ def embed_images(self, uris: List[str]) -> List[List[float]]:
112
+ """Call out to Jina's image embedding endpoint.
113
+ Args:
114
+ uris: The list of uris to embed.
115
+ Returns:
116
+ List of embeddings, one for each text.
117
+ """
118
+ input = []
119
+ for uri in uris:
120
+ if is_local(uri):
121
+ input.append({"bytes": get_bytes_str(uri)})
122
+ else:
123
+ input.append({"url": uri})
124
+ return self._embed(input)
python/user_packages/Python313/site-packages/langchain_community/embeddings/johnsnowlabs.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import Any, List
4
+
5
+ from langchain_core.embeddings import Embeddings
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+
9
+ class JohnSnowLabsEmbeddings(BaseModel, Embeddings):
10
+ """JohnSnowLabs embedding models
11
+
12
+ To use, you should have the ``johnsnowlabs`` python package installed.
13
+ Example:
14
+ .. code-block:: python
15
+
16
+ from langchain_community.embeddings.johnsnowlabs import JohnSnowLabsEmbeddings
17
+
18
+ embedding = JohnSnowLabsEmbeddings(model='embed_sentence.bert')
19
+ output = embedding.embed_query("foo bar")
20
+ """ # noqa: E501
21
+
22
+ model: Any = "embed_sentence.bert"
23
+
24
+ def __init__(
25
+ self,
26
+ model: Any = "embed_sentence.bert",
27
+ hardware_target: str = "cpu",
28
+ **kwargs: Any,
29
+ ):
30
+ """Initialize the johnsnowlabs model."""
31
+ super().__init__(**kwargs)
32
+ # 1) Check imports
33
+ try:
34
+ from johnsnowlabs import nlp
35
+ from nlu.pipe.pipeline import NLUPipeline
36
+ except ImportError as exc:
37
+ raise ImportError(
38
+ "Could not import johnsnowlabs python package. "
39
+ "Please install it with `pip install johnsnowlabs`."
40
+ ) from exc
41
+
42
+ # 2) Start a Spark Session
43
+ try:
44
+ os.environ["PYSPARK_PYTHON"] = sys.executable
45
+ os.environ["PYSPARK_DRIVER_PYTHON"] = sys.executable
46
+ nlp.start(hardware_target=hardware_target)
47
+ except Exception as exc:
48
+ raise Exception("Failure starting Spark Session") from exc
49
+
50
+ # 3) Load the model
51
+ try:
52
+ if isinstance(model, str):
53
+ self.model = nlp.load(model)
54
+ elif isinstance(model, NLUPipeline):
55
+ self.model = model
56
+ else:
57
+ self.model = nlp.to_nlu_pipe(model)
58
+ except Exception as exc:
59
+ raise Exception("Failure loading model") from exc
60
+
61
+ model_config = ConfigDict(
62
+ extra="forbid",
63
+ )
64
+
65
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
66
+ """Compute doc embeddings using a JohnSnowLabs transformer model.
67
+
68
+ Args:
69
+ texts: The list of texts to embed.
70
+
71
+ Returns:
72
+ List of embeddings, one for each text.
73
+ """
74
+
75
+ df = self.model.predict(texts, output_level="document")
76
+ emb_col = None
77
+ for c in df.columns:
78
+ if "embedding" in c:
79
+ emb_col = c
80
+ return [vec.tolist() for vec in df[emb_col].tolist()]
81
+
82
+ def embed_query(self, text: str) -> List[float]:
83
+ """Compute query embeddings using a JohnSnowLabs transformer model.
84
+
85
+ Args:
86
+ text: The text to embed.
87
+
88
+ Returns:
89
+ Embeddings for the text.
90
+ """
91
+ return self.embed_documents([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/laser.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, cast
2
+
3
+ import numpy as np
4
+ from langchain_core.embeddings import Embeddings
5
+ from langchain_core.utils import pre_init
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+ LASER_MULTILINGUAL_MODEL: str = "laser2"
9
+
10
+
11
+ class LaserEmbeddings(BaseModel, Embeddings):
12
+ """LASER Language-Agnostic SEntence Representations.
13
+ LASER is a Python library developed by the Meta AI Research team
14
+ and used for creating multilingual sentence embeddings for over 147 languages
15
+ as of 2/25/2024
16
+ See more documentation at:
17
+ * https://github.com/facebookresearch/LASER/
18
+ * https://github.com/facebookresearch/LASER/tree/main/laser_encoders
19
+ * https://arxiv.org/abs/2205.12654
20
+
21
+ To use this class, you must install the `laser_encoders` Python package.
22
+
23
+ `pip install laser_encoders`
24
+ Example:
25
+ from laser_encoders import LaserEncoderPipeline
26
+ encoder = LaserEncoderPipeline(lang="eng_Latn")
27
+ embeddings = encoder.encode_sentences(["Hello", "World"])
28
+ """
29
+
30
+ lang: Optional[str] = None
31
+ """The language or language code you'd like to use
32
+ If empty, this implementation will default
33
+ to using a multilingual earlier LASER encoder model (called laser2)
34
+ Find the list of supported languages at
35
+ https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200
36
+ """
37
+
38
+ _encoder_pipeline: Any = None # : :meta private:
39
+
40
+ model_config = ConfigDict(
41
+ extra="forbid",
42
+ )
43
+
44
+ @pre_init
45
+ def validate_environment(cls, values: Dict) -> Dict:
46
+ """Validate that laser_encoders has been installed."""
47
+ try:
48
+ from laser_encoders import LaserEncoderPipeline
49
+
50
+ lang = values.get("lang")
51
+ if lang:
52
+ encoder_pipeline = LaserEncoderPipeline(lang=lang)
53
+ else:
54
+ encoder_pipeline = LaserEncoderPipeline(laser=LASER_MULTILINGUAL_MODEL)
55
+ values["_encoder_pipeline"] = encoder_pipeline
56
+
57
+ except ImportError as e:
58
+ raise ImportError(
59
+ "Could not import 'laser_encoders' Python package. "
60
+ "Please install it with `pip install laser_encoders`."
61
+ ) from e
62
+ return values
63
+
64
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
65
+ """Generate embeddings for documents using LASER.
66
+
67
+ Args:
68
+ texts: The list of texts to embed.
69
+
70
+ Returns:
71
+ List of embeddings, one for each text.
72
+ """
73
+ embeddings: np.ndarray
74
+ embeddings = self._encoder_pipeline.encode_sentences(texts)
75
+
76
+ return cast(List[List[float]], embeddings.tolist())
77
+
78
+ def embed_query(self, text: str) -> List[float]:
79
+ """Generate single query text embeddings using LASER.
80
+
81
+ Args:
82
+ text: The text to embed.
83
+
84
+ Returns:
85
+ Embeddings for the text.
86
+ """
87
+ query_embeddings: np.ndarray
88
+ query_embeddings = self._encoder_pipeline.encode_sentences([text])
89
+ return cast(List[List[float]], query_embeddings.tolist())[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/llamacpp.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
5
+ from typing_extensions import Self
6
+
7
+
8
+ class LlamaCppEmbeddings(BaseModel, Embeddings):
9
+ """llama.cpp embedding models.
10
+
11
+ To use, you should have the llama-cpp-python library installed, and provide the
12
+ path to the Llama model as a named parameter to the constructor.
13
+ Check out: https://github.com/abetlen/llama-cpp-python
14
+
15
+ Example:
16
+ .. code-block:: python
17
+
18
+ from langchain_community.embeddings import LlamaCppEmbeddings
19
+ llama = LlamaCppEmbeddings(model_path="/path/to/model.bin")
20
+ """
21
+
22
+ client: Any = None #: :meta private:
23
+ model_path: str = Field(default="")
24
+
25
+ n_ctx: int = Field(512, alias="n_ctx")
26
+ """Token context window."""
27
+
28
+ n_parts: int = Field(-1, alias="n_parts")
29
+ """Number of parts to split the model into.
30
+ If -1, the number of parts is automatically determined."""
31
+
32
+ seed: int = Field(-1, alias="seed")
33
+ """Seed. If -1, a random seed is used."""
34
+
35
+ f16_kv: bool = Field(False, alias="f16_kv")
36
+ """Use half-precision for key/value cache."""
37
+
38
+ logits_all: bool = Field(False, alias="logits_all")
39
+ """Return logits for all tokens, not just the last token."""
40
+
41
+ vocab_only: bool = Field(False, alias="vocab_only")
42
+ """Only load the vocabulary, no weights."""
43
+
44
+ use_mlock: bool = Field(False, alias="use_mlock")
45
+ """Force system to keep model in RAM."""
46
+
47
+ n_threads: Optional[int] = Field(None, alias="n_threads")
48
+ """Number of threads to use. If None, the number
49
+ of threads is automatically determined."""
50
+
51
+ n_batch: Optional[int] = Field(512, alias="n_batch")
52
+ """Number of tokens to process in parallel.
53
+ Should be a number between 1 and n_ctx."""
54
+
55
+ n_gpu_layers: Optional[int] = Field(None, alias="n_gpu_layers")
56
+ """Number of layers to be loaded into gpu memory. Default None."""
57
+
58
+ verbose: bool = Field(True, alias="verbose")
59
+ """Print verbose output to stderr."""
60
+
61
+ device: Optional[str] = Field(None, alias="device")
62
+ """Device type to use and pass to the model"""
63
+
64
+ model_config = ConfigDict(
65
+ extra="forbid",
66
+ protected_namespaces=(),
67
+ )
68
+
69
+ @model_validator(mode="after")
70
+ def validate_environment(self) -> Self:
71
+ """Validate that llama-cpp-python library is installed."""
72
+ model_path = self.model_path
73
+ model_param_names = [
74
+ "n_ctx",
75
+ "n_parts",
76
+ "seed",
77
+ "f16_kv",
78
+ "logits_all",
79
+ "vocab_only",
80
+ "use_mlock",
81
+ "n_threads",
82
+ "n_batch",
83
+ "verbose",
84
+ "device",
85
+ ]
86
+ model_params = {k: getattr(self, k) for k in model_param_names}
87
+ # For backwards compatibility, only include if non-null.
88
+ if self.n_gpu_layers is not None:
89
+ model_params["n_gpu_layers"] = self.n_gpu_layers
90
+
91
+ if not self.client:
92
+ try:
93
+ from llama_cpp import Llama
94
+
95
+ self.client = Llama(model_path, embedding=True, **model_params)
96
+ except ImportError:
97
+ raise ImportError(
98
+ "Could not import llama-cpp-python library. "
99
+ "Please install the llama-cpp-python library to "
100
+ "use this embedding model: pip install llama-cpp-python"
101
+ )
102
+ except Exception as e:
103
+ raise ValueError(
104
+ f"Could not load Llama model from path: {model_path}. "
105
+ f"Received error {e}"
106
+ )
107
+
108
+ return self
109
+
110
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
111
+ """Embed a list of documents using the Llama model.
112
+
113
+ Args:
114
+ texts: The list of texts to embed.
115
+
116
+ Returns:
117
+ List of embeddings, one for each text.
118
+ """
119
+ embeddings = self.client.create_embedding(texts)
120
+ final_embeddings = []
121
+ for e in embeddings["data"]:
122
+ try:
123
+ if isinstance(e["embedding"][0], list):
124
+ for data in e["embedding"]:
125
+ final_embeddings.append(list(map(float, data)))
126
+ else:
127
+ final_embeddings.append(list(map(float, e["embedding"])))
128
+ except (IndexError, TypeError):
129
+ final_embeddings.append(list(map(float, e["embedding"])))
130
+ return final_embeddings
131
+
132
+ def embed_query(self, text: str) -> List[float]:
133
+ """Embed a query using the Llama model.
134
+
135
+ Args:
136
+ text: The text to embed.
137
+
138
+ Returns:
139
+ Embeddings for the text.
140
+ """
141
+ embedding = self.client.embed(text)
142
+ if embedding and isinstance(embedding, list) and isinstance(embedding[0], list):
143
+ return list(map(float, embedding[0]))
144
+ else:
145
+ return list(map(float, embedding))
python/user_packages/Python313/site-packages/langchain_community/embeddings/llamafile.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import List, Optional
3
+
4
+ import requests
5
+ from langchain_core.embeddings import Embeddings
6
+ from pydantic import BaseModel
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class LlamafileEmbeddings(BaseModel, Embeddings):
12
+ """Llamafile lets you distribute and run large language models with a
13
+ single file.
14
+
15
+ To get started, see: https://github.com/Mozilla-Ocho/llamafile
16
+
17
+ To use this class, you will need to first:
18
+
19
+ 1. Download a llamafile.
20
+ 2. Make the downloaded file executable: `chmod +x path/to/model.llamafile`
21
+ 3. Start the llamafile in server mode with embeddings enabled:
22
+
23
+ `./path/to/model.llamafile --server --nobrowser --embedding`
24
+
25
+ Example:
26
+ .. code-block:: python
27
+
28
+ from langchain_community.embeddings import LlamafileEmbeddings
29
+ embedder = LlamafileEmbeddings()
30
+ doc_embeddings = embedder.embed_documents(
31
+ [
32
+ "Alpha is the first letter of the Greek alphabet",
33
+ "Beta is the second letter of the Greek alphabet",
34
+ ]
35
+ )
36
+ query_embedding = embedder.embed_query(
37
+ "What is the second letter of the Greek alphabet"
38
+ )
39
+
40
+ """
41
+
42
+ base_url: str = "http://localhost:8080"
43
+ """Base url where the llamafile server is listening."""
44
+
45
+ request_timeout: Optional[int] = None
46
+ """Timeout for server requests"""
47
+
48
+ def _embed(self, text: str) -> List[float]:
49
+ try:
50
+ response = requests.post(
51
+ url=f"{self.base_url}/embedding",
52
+ headers={
53
+ "Content-Type": "application/json",
54
+ },
55
+ json={
56
+ "content": text,
57
+ },
58
+ timeout=self.request_timeout,
59
+ )
60
+ except requests.exceptions.ConnectionError:
61
+ raise requests.exceptions.ConnectionError(
62
+ f"Could not connect to Llamafile server. Please make sure "
63
+ f"that a server is running at {self.base_url}."
64
+ )
65
+
66
+ # Raise exception if we got a bad (non-200) response status code
67
+ response.raise_for_status()
68
+
69
+ contents = response.json()
70
+ if "embedding" not in contents:
71
+ raise KeyError(
72
+ "Unexpected output from /embedding endpoint, output dict "
73
+ "missing 'embedding' key."
74
+ )
75
+
76
+ embedding = contents["embedding"]
77
+
78
+ # Sanity check the embedding vector:
79
+ # Prior to llamafile v0.6.2, if the server was not started with the
80
+ # `--embedding` option, the embedding endpoint would always return a
81
+ # 0-vector. See issue:
82
+ # https://github.com/Mozilla-Ocho/llamafile/issues/243
83
+ # So here we raise an exception if the vector sums to exactly 0.
84
+ if sum(embedding) == 0.0:
85
+ raise ValueError(
86
+ "Embedding sums to 0, did you start the llamafile server with "
87
+ "the `--embedding` option enabled?"
88
+ )
89
+
90
+ return embedding
91
+
92
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
93
+ """Embed documents using a llamafile server running at `self.base_url`.
94
+ llamafile server should be started in a separate process before invoking
95
+ this method.
96
+
97
+ Args:
98
+ texts: The list of texts to embed.
99
+
100
+ Returns:
101
+ List of embeddings, one for each text.
102
+ """
103
+ doc_embeddings = []
104
+ for text in texts:
105
+ doc_embeddings.append(self._embed(text))
106
+ return doc_embeddings
107
+
108
+ def embed_query(self, text: str) -> List[float]:
109
+ """Embed a query using a llamafile server running at `self.base_url`.
110
+ llamafile server should be started in a separate process before invoking
111
+ this method.
112
+
113
+ Args:
114
+ text: The text to embed.
115
+
116
+ Returns:
117
+ Embeddings for the text.
118
+ """
119
+ return self._embed(text)
python/user_packages/Python313/site-packages/langchain_community/embeddings/llm_rails.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This file is for LLMRails Embedding"""
2
+
3
+ from typing import Dict, List, Optional
4
+
5
+ import requests
6
+ from langchain_core.embeddings import Embeddings
7
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
8
+ from pydantic import BaseModel, ConfigDict, SecretStr
9
+
10
+
11
+ class LLMRailsEmbeddings(BaseModel, Embeddings):
12
+ """LLMRails embedding models.
13
+
14
+ To use, you should have the environment
15
+ variable ``LLM_RAILS_API_KEY`` set with your API key or pass it
16
+ as a named parameter to the constructor.
17
+
18
+ Model can be one of ["embedding-english-v1","embedding-multi-v1"]
19
+
20
+ Example:
21
+ .. code-block:: python
22
+
23
+ from langchain_community.embeddings import LLMRailsEmbeddings
24
+ cohere = LLMRailsEmbeddings(
25
+ model="embedding-english-v1", api_key="my-api-key"
26
+ )
27
+ """
28
+
29
+ model: str = "embedding-english-v1"
30
+ """Model name to use."""
31
+
32
+ api_key: Optional[SecretStr] = None
33
+ """LLMRails API key."""
34
+
35
+ model_config = ConfigDict(
36
+ extra="forbid",
37
+ )
38
+
39
+ @pre_init
40
+ def validate_environment(cls, values: Dict) -> Dict:
41
+ """Validate that api key exists in environment."""
42
+ api_key = convert_to_secret_str(
43
+ get_from_dict_or_env(values, "api_key", "LLM_RAILS_API_KEY")
44
+ )
45
+ values["api_key"] = api_key
46
+ return values
47
+
48
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
49
+ """Call out to Cohere's embedding endpoint.
50
+
51
+ Args:
52
+ texts: The list of texts to embed.
53
+
54
+ Returns:
55
+ List of embeddings, one for each text.
56
+ """
57
+ response = requests.post(
58
+ "https://api.llmrails.com/v1/embeddings",
59
+ headers={"X-API-KEY": self.api_key.get_secret_value()}, # type: ignore[union-attr]
60
+ json={"input": texts, "model": self.model},
61
+ timeout=60,
62
+ )
63
+ return [item["embedding"] for item in response.json()["data"]]
64
+
65
+ def embed_query(self, text: str) -> List[float]:
66
+ """Call out to Cohere's embedding endpoint.
67
+
68
+ Args:
69
+ text: The text to embed.
70
+
71
+ Returns:
72
+ Embeddings for the text.
73
+ """
74
+ return self.embed_documents([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/localai.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import warnings
5
+ from typing import (
6
+ Any,
7
+ Callable,
8
+ Dict,
9
+ List,
10
+ Literal,
11
+ Optional,
12
+ Sequence,
13
+ Set,
14
+ Tuple,
15
+ Union,
16
+ )
17
+
18
+ from langchain_core.embeddings import Embeddings
19
+ from langchain_core.utils import (
20
+ get_from_dict_or_env,
21
+ get_pydantic_field_names,
22
+ pre_init,
23
+ )
24
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
25
+ from tenacity import (
26
+ AsyncRetrying,
27
+ before_sleep_log,
28
+ retry,
29
+ retry_if_exception_type,
30
+ stop_after_attempt,
31
+ wait_exponential,
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ def _create_retry_decorator(embeddings: LocalAIEmbeddings) -> Callable[[Any], Any]:
38
+ import openai
39
+
40
+ min_seconds = 4
41
+ max_seconds = 10
42
+ # Wait 2^x * 1 second between each retry starting with
43
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
44
+ return retry(
45
+ reraise=True,
46
+ stop=stop_after_attempt(embeddings.max_retries),
47
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
48
+ retry=(
49
+ retry_if_exception_type(openai.error.Timeout)
50
+ | retry_if_exception_type(openai.error.APIError)
51
+ | retry_if_exception_type(openai.error.APIConnectionError)
52
+ | retry_if_exception_type(openai.error.RateLimitError)
53
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
54
+ ),
55
+ before_sleep=before_sleep_log(logger, logging.WARNING),
56
+ )
57
+
58
+
59
+ def _async_retry_decorator(embeddings: LocalAIEmbeddings) -> Any:
60
+ import openai
61
+
62
+ min_seconds = 4
63
+ max_seconds = 10
64
+ # Wait 2^x * 1 second between each retry starting with
65
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
66
+ async_retrying = AsyncRetrying(
67
+ reraise=True,
68
+ stop=stop_after_attempt(embeddings.max_retries),
69
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
70
+ retry=(
71
+ retry_if_exception_type(openai.error.Timeout)
72
+ | retry_if_exception_type(openai.error.APIError)
73
+ | retry_if_exception_type(openai.error.APIConnectionError)
74
+ | retry_if_exception_type(openai.error.RateLimitError)
75
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
76
+ ),
77
+ before_sleep=before_sleep_log(logger, logging.WARNING),
78
+ )
79
+
80
+ def wrap(func: Callable) -> Callable:
81
+ async def wrapped_f(*args: Any, **kwargs: Any) -> Callable:
82
+ async for _ in async_retrying:
83
+ return await func(*args, **kwargs)
84
+ raise AssertionError("this is unreachable")
85
+
86
+ return wrapped_f
87
+
88
+ return wrap
89
+
90
+
91
+ # https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings
92
+ def _check_response(response: dict) -> dict:
93
+ if any(len(d["embedding"]) == 1 for d in response["data"]):
94
+ import openai
95
+
96
+ raise openai.error.APIError("LocalAI API returned an empty embedding")
97
+ return response
98
+
99
+
100
+ def embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any:
101
+ """Use tenacity to retry the embedding call."""
102
+ retry_decorator = _create_retry_decorator(embeddings)
103
+
104
+ @retry_decorator
105
+ def _embed_with_retry(**kwargs: Any) -> Any:
106
+ response = embeddings.client.create(**kwargs)
107
+ return _check_response(response)
108
+
109
+ return _embed_with_retry(**kwargs)
110
+
111
+
112
+ async def async_embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any:
113
+ """Use tenacity to retry the embedding call."""
114
+
115
+ @_async_retry_decorator(embeddings)
116
+ async def _async_embed_with_retry(**kwargs: Any) -> Any:
117
+ response = await embeddings.client.acreate(**kwargs)
118
+ return _check_response(response)
119
+
120
+ return await _async_embed_with_retry(**kwargs)
121
+
122
+
123
+ class LocalAIEmbeddings(BaseModel, Embeddings):
124
+ """LocalAI embedding models.
125
+
126
+ Since LocalAI and OpenAI have 1:1 compatibility between APIs, this class
127
+ uses the ``openai`` Python package's ``openai.Embedding`` as its client.
128
+ Thus, you should have the ``openai`` python package installed, and defeat
129
+ the environment variable ``OPENAI_API_KEY`` by setting to a random string.
130
+ You also need to specify ``OPENAI_API_BASE`` to point to your LocalAI
131
+ service endpoint.
132
+
133
+ Example:
134
+ .. code-block:: python
135
+
136
+ from langchain_community.embeddings import LocalAIEmbeddings
137
+ openai = LocalAIEmbeddings(
138
+ openai_api_key="random-string",
139
+ openai_api_base="http://localhost:8080"
140
+ )
141
+
142
+ """
143
+
144
+ client: Any = None #: :meta private:
145
+ model: str = "text-embedding-ada-002"
146
+ deployment: str = model
147
+ openai_api_version: Optional[str] = None
148
+ openai_api_base: Optional[str] = None
149
+ # to support explicit proxy for LocalAI
150
+ openai_proxy: Optional[str] = None
151
+ embedding_ctx_length: int = 8191
152
+ """The maximum number of tokens to embed at once."""
153
+ openai_api_key: Optional[str] = None
154
+ openai_organization: Optional[str] = None
155
+ allowed_special: Union[Literal["all"], Set[str]] = set()
156
+ disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all"
157
+ chunk_size: int = 1000
158
+ """Maximum number of texts to embed in each batch"""
159
+ max_retries: int = 6
160
+ """Maximum number of retries to make when generating."""
161
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = None
162
+ """Timeout in seconds for the LocalAI request."""
163
+ headers: Any = None
164
+ show_progress_bar: bool = False
165
+ """Whether to show a progress bar when embedding."""
166
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
167
+ """Holds any model parameters valid for `create` call not explicitly specified."""
168
+
169
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
170
+
171
+ @model_validator(mode="before")
172
+ @classmethod
173
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
174
+ """Build extra kwargs from additional params that were passed in."""
175
+ all_required_field_names = get_pydantic_field_names(cls)
176
+ extra = values.get("model_kwargs", {})
177
+ for field_name in list(values):
178
+ if field_name in extra:
179
+ raise ValueError(f"Found {field_name} supplied twice.")
180
+ if field_name not in all_required_field_names:
181
+ warnings.warn(
182
+ f"""WARNING! {field_name} is not default parameter.
183
+ {field_name} was transferred to model_kwargs.
184
+ Please confirm that {field_name} is what you intended."""
185
+ )
186
+ extra[field_name] = values.pop(field_name)
187
+
188
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
189
+ if invalid_model_kwargs:
190
+ raise ValueError(
191
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
192
+ f"Instead they were passed in as part of `model_kwargs` parameter."
193
+ )
194
+
195
+ values["model_kwargs"] = extra
196
+ return values
197
+
198
+ @pre_init
199
+ def validate_environment(cls, values: Dict) -> Dict:
200
+ """Validate that api key and python package exists in environment."""
201
+ values["openai_api_key"] = get_from_dict_or_env(
202
+ values, "openai_api_key", "OPENAI_API_KEY"
203
+ )
204
+ values["openai_api_base"] = get_from_dict_or_env(
205
+ values,
206
+ "openai_api_base",
207
+ "OPENAI_API_BASE",
208
+ default="",
209
+ )
210
+ values["openai_proxy"] = get_from_dict_or_env(
211
+ values,
212
+ "openai_proxy",
213
+ "OPENAI_PROXY",
214
+ default="",
215
+ )
216
+
217
+ default_api_version = ""
218
+ values["openai_api_version"] = get_from_dict_or_env(
219
+ values,
220
+ "openai_api_version",
221
+ "OPENAI_API_VERSION",
222
+ default=default_api_version,
223
+ )
224
+ values["openai_organization"] = get_from_dict_or_env(
225
+ values,
226
+ "openai_organization",
227
+ "OPENAI_ORGANIZATION",
228
+ default="",
229
+ )
230
+ try:
231
+ import openai
232
+
233
+ values["client"] = openai.Embedding
234
+ except ImportError:
235
+ raise ImportError(
236
+ "Could not import openai python package. "
237
+ "Please install it with `pip install openai`."
238
+ )
239
+ return values
240
+
241
+ @property
242
+ def _invocation_params(self) -> Dict:
243
+ openai_args = {
244
+ "model": self.model,
245
+ "request_timeout": self.request_timeout,
246
+ "headers": self.headers,
247
+ "api_key": self.openai_api_key,
248
+ "organization": self.openai_organization,
249
+ "api_base": self.openai_api_base,
250
+ "api_version": self.openai_api_version,
251
+ **self.model_kwargs,
252
+ }
253
+ if self.openai_proxy:
254
+ import openai
255
+
256
+ openai.proxy = {
257
+ "http": self.openai_proxy,
258
+ "https": self.openai_proxy,
259
+ }
260
+ return openai_args
261
+
262
+ def _embedding_func(self, text: str, *, engine: str) -> List[float]:
263
+ """Call out to LocalAI's embedding endpoint."""
264
+ # handle large input text
265
+ if self.model.endswith("001"):
266
+ # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
267
+ # replace newlines, which can negatively affect performance.
268
+ text = text.replace("\n", " ")
269
+ return embed_with_retry(
270
+ self,
271
+ input=[text],
272
+ **self._invocation_params,
273
+ )["data"][0]["embedding"]
274
+
275
+ async def _aembedding_func(self, text: str, *, engine: str) -> List[float]:
276
+ """Call out to LocalAI's embedding endpoint."""
277
+ # handle large input text
278
+ if self.model.endswith("001"):
279
+ # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
280
+ # replace newlines, which can negatively affect performance.
281
+ text = text.replace("\n", " ")
282
+ return (
283
+ await async_embed_with_retry(
284
+ self,
285
+ input=[text],
286
+ **self._invocation_params,
287
+ )
288
+ )["data"][0]["embedding"]
289
+
290
+ def embed_documents(
291
+ self, texts: List[str], chunk_size: Optional[int] = 0
292
+ ) -> List[List[float]]:
293
+ """Call out to LocalAI's embedding endpoint for embedding search docs.
294
+
295
+ Args:
296
+ texts: The list of texts to embed.
297
+ chunk_size: The chunk size of embeddings. If None, will use the chunk size
298
+ specified by the class.
299
+
300
+ Returns:
301
+ List of embeddings, one for each text.
302
+ """
303
+ # call _embedding_func for each text
304
+ return [self._embedding_func(text, engine=self.deployment) for text in texts]
305
+
306
+ async def aembed_documents(
307
+ self, texts: List[str], chunk_size: Optional[int] = 0
308
+ ) -> List[List[float]]:
309
+ """Call out to LocalAI's embedding endpoint async for embedding search docs.
310
+
311
+ Args:
312
+ texts: The list of texts to embed.
313
+ chunk_size: The chunk size of embeddings. If None, will use the chunk size
314
+ specified by the class.
315
+
316
+ Returns:
317
+ List of embeddings, one for each text.
318
+ """
319
+ embeddings = []
320
+ for text in texts:
321
+ response = await self._aembedding_func(text, engine=self.deployment)
322
+ embeddings.append(response)
323
+ return embeddings
324
+
325
+ def embed_query(self, text: str) -> List[float]:
326
+ """Call out to LocalAI's embedding endpoint for embedding query text.
327
+
328
+ Args:
329
+ text: The text to embed.
330
+
331
+ Returns:
332
+ Embedding for the text.
333
+ """
334
+ embedding = self._embedding_func(text, engine=self.deployment)
335
+ return embedding
336
+
337
+ async def aembed_query(self, text: str) -> List[float]:
338
+ """Call out to LocalAI's embedding endpoint async for embedding query text.
339
+
340
+ Args:
341
+ text: The text to embed.
342
+
343
+ Returns:
344
+ Embedding for the text.
345
+ """
346
+ embedding = await self._aembedding_func(text, engine=self.deployment)
347
+ return embedding
python/user_packages/Python313/site-packages/langchain_community/embeddings/minimax.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Callable, Dict, List, Optional
5
+
6
+ import requests
7
+ from langchain_core.embeddings import Embeddings
8
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
9
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
10
+ from tenacity import (
11
+ before_sleep_log,
12
+ retry,
13
+ stop_after_attempt,
14
+ wait_exponential,
15
+ )
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def _create_retry_decorator() -> Callable[[Any], Any]:
21
+ """Returns a tenacity retry decorator."""
22
+
23
+ multiplier = 1
24
+ min_seconds = 1
25
+ max_seconds = 4
26
+ max_retries = 6
27
+
28
+ return retry(
29
+ reraise=True,
30
+ stop=stop_after_attempt(max_retries),
31
+ wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),
32
+ before_sleep=before_sleep_log(logger, logging.WARNING),
33
+ )
34
+
35
+
36
+ def embed_with_retry(embeddings: MiniMaxEmbeddings, *args: Any, **kwargs: Any) -> Any:
37
+ """Use tenacity to retry the completion call."""
38
+ retry_decorator = _create_retry_decorator()
39
+
40
+ @retry_decorator
41
+ def _embed_with_retry(*args: Any, **kwargs: Any) -> Any:
42
+ return embeddings.embed(*args, **kwargs)
43
+
44
+ return _embed_with_retry(*args, **kwargs)
45
+
46
+
47
+ class MiniMaxEmbeddings(BaseModel, Embeddings):
48
+ """MiniMax embedding model integration.
49
+
50
+ Setup:
51
+ To use, you should have the environment variable ``MINIMAX_GROUP_ID`` and
52
+ ``MINIMAX_API_KEY`` set with your API token.
53
+
54
+ .. code-block:: bash
55
+
56
+ export MINIMAX_API_KEY="your-api-key"
57
+ export MINIMAX_GROUP_ID="your-group-id"
58
+
59
+ Key init args — completion params:
60
+ model: Optional[str]
61
+ Name of ZhipuAI model to use.
62
+ api_key: Optional[str]
63
+ Automatically inferred from env var `MINIMAX_GROUP_ID` if not provided.
64
+ group_id: Optional[str]
65
+ Automatically inferred from env var `MINIMAX_GROUP_ID` if not provided.
66
+
67
+ See full list of supported init args and their descriptions in the params section.
68
+
69
+ Instantiate:
70
+
71
+ .. code-block:: python
72
+
73
+ from langchain_community.embeddings import MiniMaxEmbeddings
74
+
75
+ embed = MiniMaxEmbeddings(
76
+ model="embo-01",
77
+ # api_key="...",
78
+ # group_id="...",
79
+ # other
80
+ )
81
+
82
+ Embed single text:
83
+ .. code-block:: python
84
+
85
+ input_text = "The meaning of life is 42"
86
+ embed.embed_query(input_text)
87
+
88
+ .. code-block:: python
89
+
90
+ [0.03016241, 0.03617699, 0.0017198119, -0.002061239, -0.00029994643, -0.0061320597, -0.0043635326, ...]
91
+
92
+ Embed multiple text:
93
+ .. code-block:: python
94
+
95
+ input_texts = ["This is a test query1.", "This is a test query2."]
96
+ embed.embed_documents(input_texts)
97
+
98
+ .. code-block:: python
99
+
100
+ [
101
+ [-0.0021588828, -0.007608119, 0.029349545, -0.0038194496, 0.008031177, -0.004529633, -0.020150753, ...],
102
+ [ -0.00023150232, -0.011122423, 0.016930554, 0.0083089275, 0.012633711, 0.019683322, -0.005971041, ...]
103
+ ]
104
+ """ # noqa: E501
105
+
106
+ endpoint_url: str = "https://api.minimax.chat/v1/embeddings"
107
+ """Endpoint URL to use."""
108
+ model: str = "embo-01"
109
+ """Embeddings model name to use."""
110
+ embed_type_db: str = "db"
111
+ """For embed_documents"""
112
+ embed_type_query: str = "query"
113
+ """For embed_query"""
114
+
115
+ minimax_group_id: Optional[str] = Field(default=None, alias="group_id")
116
+ """Group ID for MiniMax API."""
117
+ minimax_api_key: Optional[SecretStr] = Field(default=None, alias="api_key")
118
+ """API Key for MiniMax API."""
119
+
120
+ model_config = ConfigDict(
121
+ populate_by_name=True,
122
+ extra="forbid",
123
+ )
124
+
125
+ @pre_init
126
+ def validate_environment(cls, values: Dict) -> Dict:
127
+ """Validate that group id and api key exists in environment."""
128
+ minimax_group_id = get_from_dict_or_env(
129
+ values, ["minimax_group_id", "group_id"], "MINIMAX_GROUP_ID"
130
+ )
131
+ minimax_api_key = convert_to_secret_str(
132
+ get_from_dict_or_env(
133
+ values, ["minimax_api_key", "api_key"], "MINIMAX_API_KEY"
134
+ )
135
+ )
136
+ values["minimax_group_id"] = minimax_group_id
137
+ values["minimax_api_key"] = minimax_api_key
138
+ return values
139
+
140
+ def embed(
141
+ self,
142
+ texts: List[str],
143
+ embed_type: str,
144
+ ) -> List[List[float]]:
145
+ payload = {
146
+ "model": self.model,
147
+ "type": embed_type,
148
+ "texts": texts,
149
+ }
150
+
151
+ # HTTP headers for authorization
152
+ headers = {
153
+ "Authorization": f"Bearer {self.minimax_api_key.get_secret_value()}", # type: ignore[union-attr]
154
+ "Content-Type": "application/json",
155
+ }
156
+
157
+ params = {
158
+ "GroupId": self.minimax_group_id,
159
+ }
160
+
161
+ # send request
162
+ response = requests.post(
163
+ self.endpoint_url, params=params, headers=headers, json=payload
164
+ )
165
+ parsed_response = response.json()
166
+
167
+ # check for errors
168
+ if parsed_response["base_resp"]["status_code"] != 0:
169
+ raise ValueError(
170
+ f"MiniMax API returned an error: {parsed_response['base_resp']}"
171
+ )
172
+
173
+ embeddings = parsed_response["vectors"]
174
+
175
+ return embeddings
176
+
177
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
178
+ """Embed documents using a MiniMax embedding endpoint.
179
+
180
+ Args:
181
+ texts: The list of texts to embed.
182
+
183
+ Returns:
184
+ List of embeddings, one for each text.
185
+ """
186
+ embeddings = embed_with_retry(self, texts=texts, embed_type=self.embed_type_db)
187
+ return embeddings
188
+
189
+ def embed_query(self, text: str) -> List[float]:
190
+ """Embed a query using a MiniMax embedding endpoint.
191
+
192
+ Args:
193
+ text: The text to embed.
194
+
195
+ Returns:
196
+ Embeddings for the text.
197
+ """
198
+ embeddings = embed_with_retry(
199
+ self, texts=[text], embed_type=self.embed_type_query
200
+ )
201
+ return embeddings[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/mlflow.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Iterator, List
4
+ from urllib.parse import urlparse
5
+
6
+ from langchain_core.embeddings import Embeddings
7
+ from pydantic import BaseModel, PrivateAttr
8
+
9
+
10
+ def _chunk(texts: List[str], size: int) -> Iterator[List[str]]:
11
+ for i in range(0, len(texts), size):
12
+ yield texts[i : i + size]
13
+
14
+
15
+ class MlflowEmbeddings(Embeddings, BaseModel):
16
+ """Embedding LLMs in MLflow.
17
+
18
+ To use, you should have the `mlflow[genai]` python package installed.
19
+ For more information, see https://mlflow.org/docs/latest/llms/deployments.
20
+
21
+ Example:
22
+ .. code-block:: python
23
+
24
+ from langchain_community.embeddings import MlflowEmbeddings
25
+
26
+ embeddings = MlflowEmbeddings(
27
+ target_uri="http://localhost:5000",
28
+ endpoint="embeddings",
29
+ )
30
+ """
31
+
32
+ endpoint: str
33
+ """The endpoint to use."""
34
+ target_uri: str
35
+ """The target URI to use."""
36
+ _client: Any = PrivateAttr()
37
+ """The parameters to use for queries."""
38
+ query_params: Dict[str, str] = {}
39
+ """The parameters to use for documents."""
40
+ documents_params: Dict[str, str] = {}
41
+
42
+ def __init__(self, **kwargs: Any):
43
+ super().__init__(**kwargs)
44
+ self._validate_uri()
45
+ try:
46
+ from mlflow.deployments import get_deploy_client
47
+
48
+ self._client = get_deploy_client(self.target_uri)
49
+ except ImportError as e:
50
+ raise ImportError(
51
+ "Failed to create the client. "
52
+ f"Please run `pip install mlflow{self._mlflow_extras}` to install "
53
+ "required dependencies."
54
+ ) from e
55
+
56
+ @property
57
+ def _mlflow_extras(self) -> str:
58
+ return "[genai]"
59
+
60
+ def _validate_uri(self) -> None:
61
+ if self.target_uri == "databricks":
62
+ return
63
+ allowed = ["http", "https", "databricks"]
64
+ if urlparse(self.target_uri).scheme not in allowed:
65
+ raise ValueError(
66
+ f"Invalid target URI: {self.target_uri}. "
67
+ f"The scheme must be one of {allowed}."
68
+ )
69
+
70
+ def embed(self, texts: List[str], params: Dict[str, str]) -> List[List[float]]:
71
+ embeddings: List[List[float]] = []
72
+ for txt in _chunk(texts, 20):
73
+ resp = self._client.predict(
74
+ endpoint=self.endpoint,
75
+ inputs={"input": txt, **params},
76
+ )
77
+ embeddings.extend(r["embedding"] for r in resp["data"])
78
+ return embeddings
79
+
80
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
81
+ return self.embed(texts, params=self.documents_params)
82
+
83
+ def embed_query(self, text: str) -> List[float]:
84
+ return self.embed([text], params=self.query_params)[0]
85
+
86
+
87
+ class MlflowCohereEmbeddings(MlflowEmbeddings):
88
+ """Cohere embedding LLMs in MLflow."""
89
+
90
+ query_params: Dict[str, str] = {"input_type": "search_query"}
91
+ documents_params: Dict[str, str] = {"input_type": "search_document"}
python/user_packages/Python313/site-packages/langchain_community/embeddings/mlflow_gateway.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+ from typing import Any, Iterator, List, Optional
5
+
6
+ from langchain_core.embeddings import Embeddings
7
+ from pydantic import BaseModel
8
+
9
+
10
+ def _chunk(texts: List[str], size: int) -> Iterator[List[str]]:
11
+ for i in range(0, len(texts), size):
12
+ yield texts[i : i + size]
13
+
14
+
15
+ class MlflowAIGatewayEmbeddings(Embeddings, BaseModel):
16
+ """MLflow AI Gateway embeddings.
17
+
18
+ To use, you should have the ``mlflow[gateway]`` python package installed.
19
+ For more information, see https://mlflow.org/docs/latest/gateway/index.html.
20
+
21
+ Example:
22
+ .. code-block:: python
23
+
24
+ from langchain_community.embeddings import MlflowAIGatewayEmbeddings
25
+
26
+ embeddings = MlflowAIGatewayEmbeddings(
27
+ gateway_uri="<your-mlflow-ai-gateway-uri>",
28
+ route="<your-mlflow-ai-gateway-embeddings-route>"
29
+ )
30
+ """
31
+
32
+ route: str
33
+ """The route to use for the MLflow AI Gateway API."""
34
+ gateway_uri: Optional[str] = None
35
+ """The URI for the MLflow AI Gateway API."""
36
+
37
+ def __init__(self, **kwargs: Any):
38
+ warnings.warn(
39
+ "`MlflowAIGatewayEmbeddings` is deprecated. Use `MlflowEmbeddings` or "
40
+ "`DatabricksEmbeddings` instead.",
41
+ DeprecationWarning,
42
+ )
43
+ try:
44
+ import mlflow.gateway
45
+ except ImportError as e:
46
+ raise ImportError(
47
+ "Could not import `mlflow.gateway` module. "
48
+ "Please install it with `pip install mlflow[gateway]`."
49
+ ) from e
50
+
51
+ super().__init__(**kwargs)
52
+ if self.gateway_uri:
53
+ mlflow.gateway.set_gateway_uri(self.gateway_uri)
54
+
55
+ def _query(self, texts: List[str]) -> List[List[float]]:
56
+ try:
57
+ import mlflow.gateway
58
+ except ImportError as e:
59
+ raise ImportError(
60
+ "Could not import `mlflow.gateway` module. "
61
+ "Please install it with `pip install mlflow[gateway]`."
62
+ ) from e
63
+
64
+ embeddings = []
65
+ for txt in _chunk(texts, 20):
66
+ resp = mlflow.gateway.query(self.route, data={"text": txt})
67
+ # response is List[List[float]]
68
+ if isinstance(resp["embeddings"][0], List):
69
+ embeddings.extend(resp["embeddings"])
70
+ # response is List[float]
71
+ else:
72
+ embeddings.append(resp["embeddings"])
73
+ return embeddings
74
+
75
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
76
+ return self._query(texts)
77
+
78
+ def embed_query(self, text: str) -> List[float]:
79
+ return self._query([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/model2vec.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper around model2vec embedding models."""
2
+
3
+ from typing import List
4
+
5
+ from langchain_core.embeddings import Embeddings
6
+
7
+
8
+ class Model2vecEmbeddings(Embeddings):
9
+ """Model2Vec embedding models.
10
+
11
+ Install model2vec first, run 'pip install -U model2vec'.
12
+ The github repository for model2vec is : https://github.com/MinishLab/model2vec
13
+
14
+ Example:
15
+ .. code-block:: python
16
+
17
+ from langchain_community.embeddings import Model2vecEmbeddings
18
+
19
+ embedding = Model2vecEmbeddings("minishlab/potion-base-8M")
20
+ embedding.embed_documents([
21
+ "It's dangerous to go alone!",
22
+ "It's a secret to everybody.",
23
+ ])
24
+ embedding.embed_query(
25
+ "Take this with you."
26
+ )
27
+ """
28
+
29
+ def __init__(self, model: str):
30
+ """Initialize embeddings.
31
+
32
+ Args:
33
+ model: Model name.
34
+ """
35
+ try:
36
+ from model2vec import StaticModel
37
+ except ImportError as e:
38
+ raise ImportError(
39
+ "Unable to import model2vec, please install with "
40
+ "`pip install -U model2vec`."
41
+ ) from e
42
+ self._model = StaticModel.from_pretrained(model)
43
+
44
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
45
+ """Embed documents using the model2vec embeddings model.
46
+
47
+ Args:
48
+ texts: The list of texts to embed.
49
+
50
+ Returns:
51
+ List of embeddings, one for each text.
52
+ """
53
+
54
+ return self._model.encode(texts).tolist()
55
+
56
+ def embed_query(self, text: str) -> List[float]:
57
+ """Embed a query using the model2vec embeddings model.
58
+
59
+ Args:
60
+ text: The text to embed.
61
+
62
+ Returns:
63
+ Embeddings for the text.
64
+ """
65
+
66
+ return self._model.encode(text).tolist()
python/user_packages/Python313/site-packages/langchain_community/embeddings/modelscope_hub.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+
7
+ class ModelScopeEmbeddings(BaseModel, Embeddings):
8
+ """ModelScopeHub embedding models.
9
+
10
+ To use, you should have the ``modelscope`` python package installed.
11
+
12
+ Example:
13
+ .. code-block:: python
14
+
15
+ from langchain_community.embeddings import ModelScopeEmbeddings
16
+ model_id = "damo/nlp_corom_sentence-embedding_english-base"
17
+ embed = ModelScopeEmbeddings(model_id=model_id, model_revision="v1.0.0")
18
+ """
19
+
20
+ embed: Any = None
21
+ model_id: str = "damo/nlp_corom_sentence-embedding_english-base"
22
+ """Model name to use."""
23
+ model_revision: Optional[str] = None
24
+
25
+ def __init__(self, **kwargs: Any):
26
+ """Initialize the modelscope"""
27
+ super().__init__(**kwargs)
28
+ try:
29
+ from modelscope.pipelines import pipeline
30
+ from modelscope.utils.constant import Tasks
31
+ except ImportError as e:
32
+ raise ImportError(
33
+ "Could not import some python packages."
34
+ "Please install it with `pip install modelscope`."
35
+ ) from e
36
+ self.embed = pipeline(
37
+ Tasks.sentence_embedding,
38
+ model=self.model_id,
39
+ model_revision=self.model_revision,
40
+ )
41
+
42
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
43
+
44
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
45
+ """Compute doc embeddings using a modelscope embedding model.
46
+
47
+ Args:
48
+ texts: The list of texts to embed.
49
+
50
+ Returns:
51
+ List of embeddings, one for each text.
52
+ """
53
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
54
+ inputs = {"source_sentence": texts}
55
+ embeddings = self.embed(input=inputs)["text_embedding"]
56
+ return embeddings.tolist()
57
+
58
+ def embed_query(self, text: str) -> List[float]:
59
+ """Compute query embeddings using a modelscope embedding model.
60
+
61
+ Args:
62
+ text: The text to embed.
63
+
64
+ Returns:
65
+ Embeddings for the text.
66
+ """
67
+ text = text.replace("\n", " ")
68
+ inputs = {"source_sentence": [text]}
69
+ embedding = self.embed(input=inputs)["text_embedding"][0]
70
+ return embedding.tolist()
python/user_packages/Python313/site-packages/langchain_community/embeddings/mosaicml.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Mapping, Optional, Tuple
2
+
3
+ import requests
4
+ from langchain_core.embeddings import Embeddings
5
+ from langchain_core.utils import get_from_dict_or_env
6
+ from pydantic import BaseModel, ConfigDict, model_validator
7
+
8
+
9
+ class MosaicMLInstructorEmbeddings(BaseModel, Embeddings):
10
+ """MosaicML embedding service.
11
+
12
+ To use, you should have the
13
+ environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass
14
+ it as a named parameter to the constructor.
15
+
16
+ Example:
17
+ .. code-block:: python
18
+
19
+ from langchain_community.llms import MosaicMLInstructorEmbeddings
20
+ endpoint_url = (
21
+ "https://models.hosted-on.mosaicml.hosting/instructor-large/v1/predict"
22
+ )
23
+ mosaic_llm = MosaicMLInstructorEmbeddings(
24
+ endpoint_url=endpoint_url,
25
+ mosaicml_api_token="my-api-key"
26
+ )
27
+ """
28
+
29
+ endpoint_url: str = (
30
+ "https://models.hosted-on.mosaicml.hosting/instructor-xl/v1/predict"
31
+ )
32
+ """Endpoint URL to use."""
33
+ embed_instruction: str = "Represent the document for retrieval: "
34
+ """Instruction used to embed documents."""
35
+ query_instruction: str = (
36
+ "Represent the question for retrieving supporting documents: "
37
+ )
38
+ """Instruction used to embed the query."""
39
+ retry_sleep: float = 1.0
40
+ """How long to try sleeping for if a rate limit is encountered"""
41
+
42
+ mosaicml_api_token: Optional[str] = None
43
+
44
+ model_config = ConfigDict(
45
+ extra="forbid",
46
+ )
47
+
48
+ @model_validator(mode="before")
49
+ @classmethod
50
+ def validate_environment(cls, values: Dict) -> Any:
51
+ """Validate that api key and python package exists in environment."""
52
+ mosaicml_api_token = get_from_dict_or_env(
53
+ values, "mosaicml_api_token", "MOSAICML_API_TOKEN"
54
+ )
55
+ values["mosaicml_api_token"] = mosaicml_api_token
56
+ return values
57
+
58
+ @property
59
+ def _identifying_params(self) -> Mapping[str, Any]:
60
+ """Get the identifying parameters."""
61
+ return {"endpoint_url": self.endpoint_url}
62
+
63
+ def _embed(
64
+ self, input: List[Tuple[str, str]], is_retry: bool = False
65
+ ) -> List[List[float]]:
66
+ payload = {"inputs": input}
67
+
68
+ # HTTP headers for authorization
69
+ headers = {
70
+ "Authorization": f"{self.mosaicml_api_token}",
71
+ "Content-Type": "application/json",
72
+ }
73
+
74
+ # send request
75
+ try:
76
+ response = requests.post(self.endpoint_url, headers=headers, json=payload)
77
+ except requests.exceptions.RequestException as e:
78
+ raise ValueError(f"Error raised by inference endpoint: {e}")
79
+
80
+ try:
81
+ if response.status_code == 429:
82
+ if not is_retry:
83
+ import time
84
+
85
+ time.sleep(self.retry_sleep)
86
+
87
+ return self._embed(input, is_retry=True)
88
+
89
+ raise ValueError(
90
+ f"Error raised by inference API: rate limit exceeded.\nResponse: "
91
+ f"{response.text}"
92
+ )
93
+
94
+ parsed_response = response.json()
95
+
96
+ # The inference API has changed a couple of times, so we add some handling
97
+ # to be robust to multiple response formats.
98
+ if isinstance(parsed_response, dict):
99
+ output_keys = ["data", "output", "outputs"]
100
+ for key in output_keys:
101
+ if key in parsed_response:
102
+ output_item = parsed_response[key]
103
+ break
104
+ else:
105
+ raise ValueError(
106
+ f"No key data or output in response: {parsed_response}"
107
+ )
108
+
109
+ if isinstance(output_item, list) and isinstance(output_item[0], list):
110
+ embeddings = output_item
111
+ else:
112
+ embeddings = [output_item]
113
+ else:
114
+ raise ValueError(f"Unexpected response type: {parsed_response}")
115
+
116
+ except requests.exceptions.JSONDecodeError as e:
117
+ raise ValueError(
118
+ f"Error raised by inference API: {e}.\nResponse: {response.text}"
119
+ )
120
+
121
+ return embeddings
122
+
123
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
124
+ """Embed documents using a MosaicML deployed instructor embedding model.
125
+
126
+ Args:
127
+ texts: The list of texts to embed.
128
+
129
+ Returns:
130
+ List of embeddings, one for each text.
131
+ """
132
+ instruction_pairs = [(self.embed_instruction, text) for text in texts]
133
+ embeddings = self._embed(instruction_pairs)
134
+ return embeddings
135
+
136
+ def embed_query(self, text: str) -> List[float]:
137
+ """Embed a query using a MosaicML deployed instructor embedding model.
138
+
139
+ Args:
140
+ text: The text to embed.
141
+
142
+ Returns:
143
+ Embeddings for the text.
144
+ """
145
+ instruction_pair = (self.query_instruction, text)
146
+ embedding = self._embed([instruction_pair])[0]
147
+ return embedding
python/user_packages/Python313/site-packages/langchain_community/embeddings/naver.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Dict, List, Optional, cast
3
+
4
+ import httpx
5
+ from langchain_core.embeddings import Embeddings
6
+ from langchain_core.utils import convert_to_secret_str, get_from_env
7
+ from pydantic import (
8
+ AliasChoices,
9
+ BaseModel,
10
+ ConfigDict,
11
+ Field,
12
+ SecretStr,
13
+ model_validator,
14
+ )
15
+ from typing_extensions import Self
16
+
17
+ _DEFAULT_BASE_URL = "https://clovastudio.apigw.ntruss.com"
18
+ _DEFAULT_BASE_URL_ON_NEW_API_KEY = "https://clovastudio.stream.ntruss.com"
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _raise_on_error(response: httpx.Response) -> None:
24
+ """Raise an error if the response is an error."""
25
+ if httpx.codes.is_error(response.status_code):
26
+ error_message = response.read().decode("utf-8")
27
+ raise httpx.HTTPStatusError(
28
+ f"Error response {response.status_code} "
29
+ f"while fetching {response.url}: {error_message}",
30
+ request=response.request,
31
+ response=response,
32
+ )
33
+
34
+
35
+ async def _araise_on_error(response: httpx.Response) -> None:
36
+ """Raise an error if the response is an error."""
37
+ if httpx.codes.is_error(response.status_code):
38
+ error_message = (await response.aread()).decode("utf-8")
39
+ raise httpx.HTTPStatusError(
40
+ f"Error response {response.status_code} "
41
+ f"while fetching {response.url}: {error_message}",
42
+ request=response.request,
43
+ response=response,
44
+ )
45
+
46
+
47
+ class ClovaXEmbeddings(BaseModel, Embeddings):
48
+ """`NCP ClovaStudio` Embedding API.
49
+
50
+ following environment variables set or passed in constructor in lower case:
51
+ - ``NCP_CLOVASTUDIO_API_KEY``
52
+ - ``NCP_APIGW_API_KEY``
53
+ - ``NCP_CLOVASTUDIO_APP_ID``
54
+
55
+ Example:
56
+ .. code-block:: python
57
+
58
+ from langchain_community import ClovaXEmbeddings
59
+
60
+ model = ClovaXEmbeddings(model="clir-emb-dolphin")
61
+ output = embedding.embed_documents(documents)
62
+ """ # noqa: E501
63
+
64
+ client: Optional[httpx.Client] = Field(default=None) #: :meta private:
65
+ async_client: Optional[httpx.AsyncClient] = Field(default=None) #: :meta private:
66
+
67
+ ncp_clovastudio_api_key: Optional[SecretStr] = Field(default=None, alias="api_key")
68
+ """Automatically inferred from env are `NCP_CLOVASTUDIO_API_KEY` if not provided."""
69
+
70
+ ncp_apigw_api_key: Optional[SecretStr] = Field(default=None, alias="apigw_api_key")
71
+ """Automatically inferred from env are `NCP_APIGW_API_KEY` if not provided."""
72
+
73
+ base_url: Optional[str] = Field(default=None, alias="base_url")
74
+ """
75
+ Automatically inferred from env are `NCP_CLOVASTUDIO_API_BASE_URL` if not provided.
76
+ """
77
+
78
+ app_id: Optional[str] = Field(default=None)
79
+ service_app: bool = Field(
80
+ default=False,
81
+ description="false: use testapp, true: use service app on NCP Clova Studio",
82
+ )
83
+ model_name: str = Field(
84
+ default="clir-emb-dolphin",
85
+ validation_alias=AliasChoices("model_name", "model"),
86
+ description="NCP ClovaStudio embedding model name",
87
+ )
88
+
89
+ timeout: int = Field(gt=0, default=60)
90
+
91
+ model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())
92
+
93
+ @property
94
+ def lc_secrets(self) -> Dict[str, str]:
95
+ if not self._is_new_api_key():
96
+ return {
97
+ "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY",
98
+ }
99
+ else:
100
+ return {
101
+ "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY",
102
+ "ncp_apigw_api_key": "NCP_APIGW_API_KEY",
103
+ }
104
+
105
+ @property
106
+ def _api_url(self) -> str:
107
+ """GET embedding api url"""
108
+ app_type = "serviceapp" if self.service_app else "testapp"
109
+ model_name = self.model_name if self.model_name != "bge-m3" else "v2"
110
+ if self._is_new_api_key():
111
+ return f"{self.base_url}/{app_type}/v1/api-tools/embedding/{model_name}"
112
+ else:
113
+ return (
114
+ f"{self.base_url}/{app_type}"
115
+ f"/v1/api-tools/embedding/{model_name}/{self.app_id}"
116
+ )
117
+
118
+ @model_validator(mode="after")
119
+ def validate_model_after(self) -> Self:
120
+ if not self.ncp_clovastudio_api_key:
121
+ self.ncp_clovastudio_api_key = convert_to_secret_str(
122
+ get_from_env("ncp_clovastudio_api_key", "NCP_CLOVASTUDIO_API_KEY")
123
+ )
124
+
125
+ if self._is_new_api_key():
126
+ self._init_fields_on_new_api_key()
127
+ else:
128
+ self._init_fields_on_old_api_key()
129
+
130
+ if not self.base_url:
131
+ raise ValueError("base_url dose not exist.")
132
+
133
+ if not self.client:
134
+ self.client = httpx.Client(
135
+ base_url=self.base_url,
136
+ headers=self.default_headers(),
137
+ timeout=self.timeout,
138
+ )
139
+
140
+ if not self.async_client and self.base_url:
141
+ self.async_client = httpx.AsyncClient(
142
+ base_url=self.base_url,
143
+ headers=self.default_headers(),
144
+ timeout=self.timeout,
145
+ )
146
+
147
+ return self
148
+
149
+ def _is_new_api_key(self) -> bool:
150
+ if self.ncp_clovastudio_api_key:
151
+ return self.ncp_clovastudio_api_key.get_secret_value().startswith("nv-")
152
+ else:
153
+ return False
154
+
155
+ def _init_fields_on_new_api_key(self) -> None:
156
+ if not self.base_url:
157
+ self.base_url = get_from_env(
158
+ "base_url",
159
+ "NCP_CLOVASTUDIO_API_BASE_URL",
160
+ _DEFAULT_BASE_URL_ON_NEW_API_KEY,
161
+ )
162
+
163
+ def _init_fields_on_old_api_key(self) -> None:
164
+ if not self.ncp_apigw_api_key:
165
+ self.ncp_apigw_api_key = convert_to_secret_str(
166
+ get_from_env("ncp_apigw_api_key", "NCP_APIGW_API_KEY", "")
167
+ )
168
+ if not self.base_url:
169
+ self.base_url = get_from_env(
170
+ "base_url", "NCP_CLOVASTUDIO_API_BASE_URL", _DEFAULT_BASE_URL
171
+ )
172
+ if not self.app_id:
173
+ self.app_id = get_from_env("app_id", "NCP_CLOVASTUDIO_APP_ID")
174
+
175
+ def default_headers(self) -> Dict[str, Any]:
176
+ headers = {
177
+ "Content-Type": "application/json",
178
+ "Accept": "application/json",
179
+ }
180
+
181
+ clovastudio_api_key = (
182
+ self.ncp_clovastudio_api_key.get_secret_value()
183
+ if self.ncp_clovastudio_api_key
184
+ else None
185
+ )
186
+
187
+ if self._is_new_api_key():
188
+ ### headers on new api key
189
+ headers["Authorization"] = f"Bearer {clovastudio_api_key}"
190
+ else:
191
+ ### headers on old api key
192
+ if clovastudio_api_key:
193
+ headers["X-NCP-CLOVASTUDIO-API-KEY"] = clovastudio_api_key
194
+
195
+ apigw_api_key = (
196
+ self.ncp_apigw_api_key.get_secret_value()
197
+ if self.ncp_apigw_api_key
198
+ else None
199
+ )
200
+ if apigw_api_key:
201
+ headers["X-NCP-APIGW-API-KEY"] = apigw_api_key
202
+
203
+ return headers
204
+
205
+ def _embed_text(self, text: str) -> List[float]:
206
+ payload = {"text": text}
207
+ client = cast(httpx.Client, self.client)
208
+ response = client.post(url=self._api_url, json=payload)
209
+ _raise_on_error(response)
210
+ return response.json()["result"]["embedding"]
211
+
212
+ async def _aembed_text(self, text: str) -> List[float]:
213
+ payload = {"text": text}
214
+ async_client = cast(httpx.AsyncClient, self.async_client)
215
+ response = await async_client.post(url=self._api_url, json=payload)
216
+ await _araise_on_error(response)
217
+ return response.json()["result"]["embedding"]
218
+
219
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
220
+ embeddings = []
221
+ for text in texts:
222
+ embeddings.append(self._embed_text(text))
223
+ return embeddings
224
+
225
+ def embed_query(self, text: str) -> List[float]:
226
+ return self._embed_text(text)
227
+
228
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
229
+ embeddings = []
230
+ for text in texts:
231
+ embedding = await self._aembed_text(text)
232
+ embeddings.append(embedding)
233
+ return embeddings
234
+
235
+ async def aembed_query(self, text: str) -> List[float]:
236
+ return await self._aembed_text(text)
python/user_packages/Python313/site-packages/langchain_community/embeddings/nemo.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ import aiohttp
8
+ import requests
9
+ from langchain_core._api.deprecation import deprecated
10
+ from langchain_core.embeddings import Embeddings
11
+ from langchain_core.utils import pre_init
12
+ from pydantic import BaseModel
13
+
14
+
15
+ def is_endpoint_live(url: str, headers: Optional[dict], payload: Any) -> bool:
16
+ """
17
+ Check if an endpoint is live by sending a GET request to the specified URL.
18
+
19
+ Args:
20
+ url (str): The URL of the endpoint to check.
21
+
22
+ Returns:
23
+ bool: True if the endpoint is live (status code 200), False otherwise.
24
+
25
+ Raises:
26
+ Exception: If the endpoint returns a non-successful status code or if there is
27
+ an error querying the endpoint.
28
+ """
29
+ try:
30
+ response = requests.request("POST", url, headers=headers, data=payload)
31
+
32
+ # Check if the status code is 200 (OK)
33
+ if response.status_code == 200:
34
+ return True
35
+ else:
36
+ # Raise an exception if the status code is not 200
37
+ raise Exception(
38
+ f"Endpoint returned a non-successful status code: "
39
+ f"{response.status_code}"
40
+ )
41
+ except requests.exceptions.RequestException as e:
42
+ # Handle any exceptions (e.g., connection errors)
43
+ raise Exception(f"Error querying the endpoint: {e}")
44
+
45
+
46
+ @deprecated(
47
+ since="0.0.37",
48
+ removal="1.0.0",
49
+ message=(
50
+ "Directly instantiating a NeMoEmbeddings from langchain-community is "
51
+ "deprecated. Please use langchain-nvidia-ai-endpoints NVIDIAEmbeddings "
52
+ "interface."
53
+ ),
54
+ )
55
+ class NeMoEmbeddings(BaseModel, Embeddings):
56
+ """NeMo embedding models."""
57
+
58
+ batch_size: int = 16
59
+ model: str = "NV-Embed-QA-003"
60
+ api_endpoint_url: str = "http://localhost:8088/v1/embeddings"
61
+
62
+ @pre_init
63
+ def validate_environment(cls, values: Dict) -> Dict:
64
+ """Validate that the end point is alive using the values that are provided."""
65
+
66
+ url = values["api_endpoint_url"]
67
+ model = values["model"]
68
+
69
+ # Optional: A minimal test payload and headers required by the endpoint
70
+ headers = {"Content-Type": "application/json"}
71
+ payload = json.dumps(
72
+ {
73
+ "input": "Hello World",
74
+ "model": model,
75
+ "input_type": "query",
76
+ }
77
+ )
78
+
79
+ is_endpoint_live(url, headers, payload)
80
+
81
+ return values
82
+
83
+ async def _aembedding_func(
84
+ self, session: Any, text: str, input_type: str
85
+ ) -> List[float]:
86
+ """Async call out to embedding endpoint.
87
+
88
+ Args:
89
+ text: The text to embed.
90
+
91
+ Returns:
92
+ Embeddings for the text.
93
+ """
94
+
95
+ headers = {"Content-Type": "application/json"}
96
+
97
+ async with session.post(
98
+ self.api_endpoint_url,
99
+ json={"input": text, "model": self.model, "input_type": input_type},
100
+ headers=headers,
101
+ ) as response:
102
+ response.raise_for_status()
103
+ answer = await response.text()
104
+ answer = json.loads(answer)
105
+ return answer["data"][0]["embedding"]
106
+
107
+ def _embedding_func(self, text: str, input_type: str) -> List[float]:
108
+ """Call out to Cohere's embedding endpoint.
109
+
110
+ Args:
111
+ text: The text to embed.
112
+
113
+ Returns:
114
+ Embeddings for the text.
115
+ """
116
+
117
+ payload = json.dumps(
118
+ {
119
+ "input": text,
120
+ "model": self.model,
121
+ "input_type": input_type,
122
+ }
123
+ )
124
+ headers = {"Content-Type": "application/json"}
125
+
126
+ response = requests.request(
127
+ "POST", self.api_endpoint_url, headers=headers, data=payload
128
+ )
129
+ response_json = json.loads(response.text)
130
+ embedding = response_json["data"][0]["embedding"]
131
+
132
+ return embedding
133
+
134
+ def embed_documents(self, documents: List[str]) -> List[List[float]]:
135
+ """Embed a list of document texts.
136
+
137
+ Args:
138
+ texts: The list of texts to embed.
139
+
140
+ Returns:
141
+ List of embeddings, one for each text.
142
+ """
143
+ return [self._embedding_func(text, input_type="passage") for text in documents]
144
+
145
+ def embed_query(self, text: str) -> List[float]:
146
+ return self._embedding_func(text, input_type="query")
147
+
148
+ async def aembed_query(self, text: str) -> List[float]:
149
+ """Call out to NeMo's embedding endpoint async for embedding query text.
150
+
151
+ Args:
152
+ text: The text to embed.
153
+
154
+ Returns:
155
+ Embedding for the text.
156
+ """
157
+
158
+ async with aiohttp.ClientSession() as session:
159
+ embedding = await self._aembedding_func(session, text, "passage")
160
+ return embedding
161
+
162
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
163
+ """Call out to NeMo's embedding endpoint async for embedding search docs.
164
+
165
+ Args:
166
+ texts: The list of texts to embed.
167
+
168
+ Returns:
169
+ List of embeddings, one for each text.
170
+ """
171
+ embeddings = []
172
+
173
+ async with aiohttp.ClientSession() as session:
174
+ for batch in range(0, len(texts), self.batch_size):
175
+ text_batch = texts[batch : batch + self.batch_size]
176
+
177
+ for text in text_batch:
178
+ # Create tasks for all texts in the batch
179
+ tasks = [
180
+ self._aembedding_func(session, text, "passage")
181
+ for text in text_batch
182
+ ]
183
+
184
+ # Run all tasks concurrently
185
+ batch_results = await asyncio.gather(*tasks)
186
+
187
+ # Extend the embeddings list with results from this batch
188
+ embeddings.extend(batch_results)
189
+
190
+ return embeddings
python/user_packages/Python313/site-packages/langchain_community/embeddings/nlpcloud.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from langchain_core.utils import get_from_dict_or_env, pre_init
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+
8
+ class NLPCloudEmbeddings(BaseModel, Embeddings):
9
+ """NLP Cloud embedding models.
10
+
11
+ To use, you should have the nlpcloud python package installed
12
+
13
+ Example:
14
+ .. code-block:: python
15
+
16
+ from langchain_community.embeddings import NLPCloudEmbeddings
17
+
18
+ embeddings = NLPCloudEmbeddings()
19
+ """
20
+
21
+ model_name: str # Define model_name as a class attribute
22
+ gpu: bool # Define gpu as a class attribute
23
+ client: Any #: :meta private:
24
+
25
+ model_config = ConfigDict(protected_namespaces=())
26
+
27
+ def __init__(
28
+ self,
29
+ model_name: str = "paraphrase-multilingual-mpnet-base-v2",
30
+ gpu: bool = False,
31
+ **kwargs: Any,
32
+ ) -> None:
33
+ super().__init__(model_name=model_name, gpu=gpu, **kwargs)
34
+
35
+ @pre_init
36
+ def validate_environment(cls, values: Dict) -> Dict:
37
+ """Validate that api key and python package exists in environment."""
38
+ nlpcloud_api_key = get_from_dict_or_env(
39
+ values, "nlpcloud_api_key", "NLPCLOUD_API_KEY"
40
+ )
41
+ try:
42
+ import nlpcloud
43
+
44
+ values["client"] = nlpcloud.Client(
45
+ values["model_name"], nlpcloud_api_key, gpu=values["gpu"], lang="en"
46
+ )
47
+ except ImportError:
48
+ raise ImportError(
49
+ "Could not import nlpcloud python package. "
50
+ "Please install it with `pip install nlpcloud`."
51
+ )
52
+ return values
53
+
54
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
55
+ """Embed a list of documents using NLP Cloud.
56
+
57
+ Args:
58
+ texts: The list of texts to embed.
59
+
60
+ Returns:
61
+ List of embeddings, one for each text.
62
+ """
63
+
64
+ return self.client.embeddings(texts)["embeddings"]
65
+
66
+ def embed_query(self, text: str) -> List[float]:
67
+ """Embed a query using NLP Cloud.
68
+
69
+ Args:
70
+ text: The text to embed.
71
+
72
+ Returns:
73
+ Embeddings for the text.
74
+ """
75
+ return self.client.embeddings([text])["embeddings"][0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/oci_generative_ai.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, Optional
3
+
4
+ from langchain_core.embeddings import Embeddings
5
+ from langchain_core.utils import pre_init
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+ if TYPE_CHECKING:
9
+ import oci
10
+
11
+ CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
12
+
13
+
14
+ class OCIAuthType(Enum):
15
+ """OCI authentication types as enumerator."""
16
+
17
+ API_KEY = 1
18
+ SECURITY_TOKEN = 2
19
+ INSTANCE_PRINCIPAL = 3
20
+ RESOURCE_PRINCIPAL = 4
21
+
22
+
23
+ class OCIGenAIEmbeddings(BaseModel, Embeddings):
24
+ """OCI embedding models.
25
+
26
+ To authenticate, the OCI client uses the methods described in
27
+ https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm
28
+
29
+ The authentifcation method is passed through auth_type and should be one of:
30
+ API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPLE, RESOURCE_PRINCIPLE
31
+
32
+ Make sure you have the required policies (profile/roles) to
33
+ access the OCI Generative AI service. If a specific config profile is used,
34
+ you must pass the name of the profile (~/.oci/config) through auth_profile.
35
+ If a specific config file location is used, you must pass
36
+ the file location where profile name configs present
37
+ through auth_file_location
38
+
39
+ To use, you must provide the compartment id
40
+ along with the endpoint url, and model id
41
+ as named parameters to the constructor.
42
+
43
+ Example:
44
+ .. code-block:: python
45
+
46
+ from langchain_classic.embeddings import OCIGenAIEmbeddings
47
+
48
+ embeddings = OCIGenAIEmbeddings(
49
+ model_id="MY_EMBEDDING_MODEL",
50
+ service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
51
+ compartment_id="MY_OCID"
52
+ )
53
+ """
54
+
55
+ client: Any = None #: :meta private:
56
+
57
+ service_models: Any = None #: :meta private:
58
+
59
+ auth_type: Optional[str] = "API_KEY"
60
+ """Authentication type, could be
61
+
62
+ API_KEY,
63
+ SECURITY_TOKEN,
64
+ INSTANCE_PRINCIPLE,
65
+ RESOURCE_PRINCIPLE
66
+
67
+ If not specified, API_KEY will be used
68
+ """
69
+
70
+ auth_profile: Optional[str] = "DEFAULT"
71
+ """The name of the profile in ~/.oci/config
72
+ If not specified , DEFAULT will be used
73
+ """
74
+
75
+ auth_file_location: Optional[str] = "~/.oci/config"
76
+ """Path to the config file.
77
+ If not specified, ~/.oci/config will be used
78
+ """
79
+
80
+ model_id: Optional[str] = None
81
+ """Id of the model to call, e.g., cohere.embed-english-light-v2.0"""
82
+
83
+ model_kwargs: Optional[Dict] = None
84
+ """Keyword arguments to pass to the model"""
85
+
86
+ service_endpoint: Optional[str] = None
87
+ """service endpoint url"""
88
+
89
+ compartment_id: Optional[str] = None
90
+ """OCID of compartment"""
91
+
92
+ truncate: Optional[str] = "END"
93
+ """Truncate embeddings that are too long from start or end ("NONE"|"START"|"END")"""
94
+
95
+ batch_size: int = 96
96
+ """Batch size of OCI GenAI embedding requests. OCI GenAI may handle up to 96 texts
97
+ per request"""
98
+
99
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
100
+
101
+ @pre_init
102
+ def validate_environment(cls, values: Dict) -> Dict: # pylint: disable=no-self-argument
103
+ """Validate that OCI config and python package exists in environment."""
104
+
105
+ # Skip creating new client if passed in constructor
106
+ if values["client"] is not None:
107
+ return values
108
+
109
+ try:
110
+ import oci
111
+
112
+ client_kwargs = {
113
+ "config": {},
114
+ "signer": None,
115
+ "service_endpoint": values["service_endpoint"],
116
+ "retry_strategy": oci.retry.DEFAULT_RETRY_STRATEGY,
117
+ "timeout": (10, 240), # default timeout config for OCI Gen AI service
118
+ }
119
+
120
+ if values["auth_type"] == OCIAuthType(1).name:
121
+ client_kwargs["config"] = oci.config.from_file(
122
+ file_location=values["auth_file_location"],
123
+ profile_name=values["auth_profile"],
124
+ )
125
+ client_kwargs.pop("signer", None)
126
+ elif values["auth_type"] == OCIAuthType(2).name:
127
+
128
+ def make_security_token_signer(
129
+ oci_config: dict[str, Any],
130
+ ) -> "oci.auth.signers.SecurityTokenSigner":
131
+ pk = oci.signer.load_private_key_from_file(
132
+ oci_config.get("key_file"), None
133
+ )
134
+ with open(
135
+ str(oci_config.get("security_token_file")), encoding="utf-8"
136
+ ) as f:
137
+ st_string = f.read()
138
+ return oci.auth.signers.SecurityTokenSigner(st_string, pk)
139
+
140
+ client_kwargs["config"] = oci.config.from_file(
141
+ file_location=values["auth_file_location"],
142
+ profile_name=values["auth_profile"],
143
+ )
144
+ client_kwargs["signer"] = make_security_token_signer(
145
+ oci_config=client_kwargs["config"]
146
+ )
147
+ elif values["auth_type"] == OCIAuthType(3).name:
148
+ client_kwargs["signer"] = (
149
+ oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
150
+ )
151
+ elif values["auth_type"] == OCIAuthType(4).name:
152
+ client_kwargs["signer"] = (
153
+ oci.auth.signers.get_resource_principals_signer()
154
+ )
155
+ else:
156
+ raise ValueError("Please provide valid value to auth_type")
157
+
158
+ values["client"] = oci.generative_ai_inference.GenerativeAiInferenceClient(
159
+ **client_kwargs
160
+ )
161
+
162
+ except ImportError as ex:
163
+ raise ImportError(
164
+ "Could not import oci python package. "
165
+ "Please make sure you have the oci package installed."
166
+ ) from ex
167
+ except Exception as e:
168
+ raise ValueError(
169
+ """Could not authenticate with OCI client.
170
+ If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used,
171
+ please check the specified
172
+ auth_profile, auth_file_location and auth_type are valid.""",
173
+ e,
174
+ ) from e
175
+
176
+ return values
177
+
178
+ @property
179
+ def _identifying_params(self) -> Mapping[str, Any]:
180
+ """Get the identifying parameters."""
181
+ _model_kwargs = self.model_kwargs or {}
182
+ return {
183
+ **{"model_kwargs": _model_kwargs},
184
+ }
185
+
186
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
187
+ """Call out to OCIGenAI's embedding endpoint.
188
+
189
+ Args:
190
+ texts: The list of texts to embed.
191
+
192
+ Returns:
193
+ List of embeddings, one for each text.
194
+ """
195
+ from oci.generative_ai_inference import models
196
+
197
+ if not self.model_id:
198
+ raise ValueError("Model ID is required to embed documents")
199
+
200
+ if self.model_id.startswith(CUSTOM_ENDPOINT_PREFIX):
201
+ serving_mode = models.DedicatedServingMode(endpoint_id=self.model_id)
202
+ else:
203
+ serving_mode = models.OnDemandServingMode(model_id=self.model_id)
204
+
205
+ embeddings = []
206
+
207
+ def split_texts() -> Iterator[List[str]]:
208
+ for i in range(0, len(texts), self.batch_size):
209
+ yield texts[i : i + self.batch_size]
210
+
211
+ for chunk in split_texts():
212
+ invocation_obj = models.EmbedTextDetails(
213
+ serving_mode=serving_mode,
214
+ compartment_id=self.compartment_id,
215
+ truncate=self.truncate,
216
+ inputs=chunk,
217
+ )
218
+ response = self.client.embed_text(invocation_obj)
219
+ embeddings.extend(response.data.embeddings)
220
+
221
+ return embeddings
222
+
223
+ def embed_query(self, text: str) -> List[float]:
224
+ """Call out to OCIGenAI's embedding endpoint.
225
+
226
+ Args:
227
+ text: The text to embed.
228
+
229
+ Returns:
230
+ Embeddings for the text.
231
+ """
232
+ return self.embed_documents([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/octoai_embeddings.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional
2
+
3
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
4
+ from pydantic import Field, SecretStr
5
+
6
+ from langchain_community.embeddings.openai import OpenAIEmbeddings
7
+ from langchain_community.utils.openai import is_openai_v1
8
+
9
+ DEFAULT_API_BASE = "https://text.octoai.run/v1/"
10
+ DEFAULT_MODEL = "thenlper/gte-large"
11
+
12
+
13
+ class OctoAIEmbeddings(OpenAIEmbeddings):
14
+ """OctoAI Compute Service embedding models.
15
+
16
+ See https://octo.ai/ for information about OctoAI.
17
+
18
+ To use, you should have the ``openai`` python package installed and the
19
+ environment variable ``OCTOAI_API_TOKEN`` set with your API token.
20
+ Alternatively, you can use the octoai_api_token keyword argument.
21
+ """
22
+
23
+ octoai_api_token: Optional[SecretStr] = Field(default=None)
24
+ """OctoAI Endpoints API keys."""
25
+ endpoint_url: str = Field(default=DEFAULT_API_BASE)
26
+ """Base URL path for API requests."""
27
+ model: str = Field(default=DEFAULT_MODEL)
28
+ """Model name to use."""
29
+ tiktoken_enabled: bool = False
30
+ """Set this to False for non-OpenAI implementations of the embeddings API"""
31
+
32
+ @property
33
+ def _llm_type(self) -> str:
34
+ """Return type of embeddings model."""
35
+ return "octoai-embeddings"
36
+
37
+ @property
38
+ def lc_secrets(self) -> Dict[str, str]:
39
+ return {"octoai_api_token": "OCTOAI_API_TOKEN"}
40
+
41
+ @pre_init
42
+ def validate_environment(cls, values: dict) -> dict:
43
+ """Validate that api key and python package exists in environment."""
44
+ values["endpoint_url"] = get_from_dict_or_env(
45
+ values,
46
+ "endpoint_url",
47
+ "ENDPOINT_URL",
48
+ default=DEFAULT_API_BASE,
49
+ )
50
+ values["octoai_api_token"] = convert_to_secret_str(
51
+ get_from_dict_or_env(values, "octoai_api_token", "OCTOAI_API_TOKEN")
52
+ )
53
+ values["model"] = get_from_dict_or_env(
54
+ values,
55
+ "model",
56
+ "MODEL",
57
+ default=DEFAULT_MODEL,
58
+ )
59
+
60
+ try:
61
+ import openai
62
+
63
+ if is_openai_v1():
64
+ client_params = {
65
+ "api_key": values["octoai_api_token"].get_secret_value(),
66
+ "base_url": values["endpoint_url"],
67
+ }
68
+ if not values.get("client"):
69
+ values["client"] = openai.OpenAI(**client_params).embeddings
70
+ if not values.get("async_client"):
71
+ values["async_client"] = openai.AsyncOpenAI(
72
+ **client_params
73
+ ).embeddings
74
+ else:
75
+ values["openai_api_base"] = values["endpoint_url"]
76
+ values["openai_api_key"] = values["octoai_api_token"].get_secret_value()
77
+ values["client"] = openai.Embedding
78
+ values["async_client"] = openai.Embedding
79
+
80
+ except ImportError:
81
+ raise ImportError(
82
+ "Could not import openai python package. "
83
+ "Please install it with `pip install openai`."
84
+ )
85
+
86
+ return values
python/user_packages/Python313/site-packages/langchain_community/embeddings/ollama.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Dict, List, Mapping, Optional
3
+
4
+ import requests
5
+ from langchain_core._api.deprecation import deprecated
6
+ from langchain_core.embeddings import Embeddings
7
+ from pydantic import BaseModel, ConfigDict
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ @deprecated(
13
+ since="0.3.1",
14
+ removal="1.0.0",
15
+ alternative_import="langchain_ollama.OllamaEmbeddings",
16
+ )
17
+ class OllamaEmbeddings(BaseModel, Embeddings):
18
+ """Ollama locally runs large language models.
19
+
20
+ To use, follow the instructions at https://ollama.ai/.
21
+
22
+ Example:
23
+ .. code-block:: python
24
+
25
+ from langchain_community.embeddings import OllamaEmbeddings
26
+ ollama_emb = OllamaEmbeddings(
27
+ model="llama:7b",
28
+ )
29
+ r1 = ollama_emb.embed_documents(
30
+ [
31
+ "Alpha is the first letter of Greek alphabet",
32
+ "Beta is the second letter of Greek alphabet",
33
+ ]
34
+ )
35
+ r2 = ollama_emb.embed_query(
36
+ "What is the second letter of Greek alphabet"
37
+ )
38
+
39
+ """
40
+
41
+ base_url: str = "http://localhost:11434"
42
+ """Base url the model is hosted under."""
43
+ model: str = "llama2"
44
+ """Model name to use."""
45
+
46
+ embed_instruction: str = "passage: "
47
+ """Instruction used to embed documents."""
48
+ query_instruction: str = "query: "
49
+ """Instruction used to embed the query."""
50
+
51
+ mirostat: Optional[int] = None
52
+ """Enable Mirostat sampling for controlling perplexity.
53
+ (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)"""
54
+
55
+ mirostat_eta: Optional[float] = None
56
+ """Influences how quickly the algorithm responds to feedback
57
+ from the generated text. A lower learning rate will result in
58
+ slower adjustments, while a higher learning rate will make
59
+ the algorithm more responsive. (Default: 0.1)"""
60
+
61
+ mirostat_tau: Optional[float] = None
62
+ """Controls the balance between coherence and diversity
63
+ of the output. A lower value will result in more focused and
64
+ coherent text. (Default: 5.0)"""
65
+
66
+ num_ctx: Optional[int] = None
67
+ """Sets the size of the context window used to generate the
68
+ next token. (Default: 2048) """
69
+
70
+ num_gpu: Optional[int] = None
71
+ """The number of GPUs to use. On macOS it defaults to 1 to
72
+ enable metal support, 0 to disable."""
73
+
74
+ num_thread: Optional[int] = None
75
+ """Sets the number of threads to use during computation.
76
+ By default, Ollama will detect this for optimal performance.
77
+ It is recommended to set this value to the number of physical
78
+ CPU cores your system has (as opposed to the logical number of cores)."""
79
+
80
+ repeat_last_n: Optional[int] = None
81
+ """Sets how far back for the model to look back to prevent
82
+ repetition. (Default: 64, 0 = disabled, -1 = num_ctx)"""
83
+
84
+ repeat_penalty: Optional[float] = None
85
+ """Sets how strongly to penalize repetitions. A higher value (e.g., 1.5)
86
+ will penalize repetitions more strongly, while a lower value (e.g., 0.9)
87
+ will be more lenient. (Default: 1.1)"""
88
+
89
+ temperature: Optional[float] = None
90
+ """The temperature of the model. Increasing the temperature will
91
+ make the model answer more creatively. (Default: 0.8)"""
92
+
93
+ stop: Optional[List[str]] = None
94
+ """Sets the stop tokens to use."""
95
+
96
+ tfs_z: Optional[float] = None
97
+ """Tail free sampling is used to reduce the impact of less probable
98
+ tokens from the output. A higher value (e.g., 2.0) will reduce the
99
+ impact more, while a value of 1.0 disables this setting. (default: 1)"""
100
+
101
+ top_k: Optional[int] = None
102
+ """Reduces the probability of generating nonsense. A higher value (e.g. 100)
103
+ will give more diverse answers, while a lower value (e.g. 10)
104
+ will be more conservative. (Default: 40)"""
105
+
106
+ top_p: Optional[float] = None
107
+ """Works together with top-k. A higher value (e.g., 0.95) will lead
108
+ to more diverse text, while a lower value (e.g., 0.5) will
109
+ generate more focused and conservative text. (Default: 0.9)"""
110
+
111
+ show_progress: bool = False
112
+ """Whether to show a tqdm progress bar. Must have `tqdm` installed."""
113
+
114
+ headers: Optional[dict] = None
115
+ """Additional headers to pass to endpoint (e.g. Authorization, Referer).
116
+ This is useful when Ollama is hosted on cloud services that require
117
+ tokens for authentication.
118
+ """
119
+
120
+ @property
121
+ def _default_params(self) -> Dict[str, Any]:
122
+ """Get the default parameters for calling Ollama."""
123
+ return {
124
+ "model": self.model,
125
+ "options": {
126
+ "mirostat": self.mirostat,
127
+ "mirostat_eta": self.mirostat_eta,
128
+ "mirostat_tau": self.mirostat_tau,
129
+ "num_ctx": self.num_ctx,
130
+ "num_gpu": self.num_gpu,
131
+ "num_thread": self.num_thread,
132
+ "repeat_last_n": self.repeat_last_n,
133
+ "repeat_penalty": self.repeat_penalty,
134
+ "temperature": self.temperature,
135
+ "stop": self.stop,
136
+ "tfs_z": self.tfs_z,
137
+ "top_k": self.top_k,
138
+ "top_p": self.top_p,
139
+ },
140
+ }
141
+
142
+ model_kwargs: Optional[dict] = None
143
+ """Other model keyword args"""
144
+
145
+ @property
146
+ def _identifying_params(self) -> Mapping[str, Any]:
147
+ """Get the identifying parameters."""
148
+ return {**{"model": self.model}, **self._default_params}
149
+
150
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
151
+
152
+ def _process_emb_response(self, input: str) -> List[float]:
153
+ """Process a response from the API.
154
+
155
+ Args:
156
+ response: The response from the API.
157
+
158
+ Returns:
159
+ The response as a dictionary.
160
+ """
161
+ headers = {
162
+ "Content-Type": "application/json",
163
+ **(self.headers or {}),
164
+ }
165
+
166
+ try:
167
+ res = requests.post(
168
+ f"{self.base_url}/api/embeddings",
169
+ headers=headers,
170
+ json={"model": self.model, "prompt": input, **self._default_params},
171
+ )
172
+ except requests.exceptions.RequestException as e:
173
+ raise ValueError(f"Error raised by inference endpoint: {e}")
174
+
175
+ if res.status_code != 200:
176
+ raise ValueError(
177
+ "Error raised by inference API HTTP code: %s, %s"
178
+ % (res.status_code, res.text)
179
+ )
180
+ try:
181
+ t = res.json()
182
+ return t["embedding"]
183
+ except requests.exceptions.JSONDecodeError as e:
184
+ raise ValueError(
185
+ f"Error raised by inference API: {e}.\nResponse: {res.text}"
186
+ )
187
+
188
+ def _embed(self, input: List[str]) -> List[List[float]]:
189
+ if self.show_progress:
190
+ try:
191
+ from tqdm import tqdm
192
+
193
+ iter_ = tqdm(input, desc="OllamaEmbeddings")
194
+ except ImportError:
195
+ logger.warning(
196
+ "Unable to show progress bar because tqdm could not be imported. "
197
+ "Please install with `pip install tqdm`."
198
+ )
199
+ iter_ = input
200
+ else:
201
+ iter_ = input
202
+ return [self._process_emb_response(prompt) for prompt in iter_]
203
+
204
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
205
+ """Embed documents using an Ollama deployed embedding model.
206
+
207
+ Args:
208
+ texts: The list of texts to embed.
209
+
210
+ Returns:
211
+ List of embeddings, one for each text.
212
+ """
213
+ instruction_pairs = [f"{self.embed_instruction}{text}" for text in texts]
214
+ embeddings = self._embed(instruction_pairs)
215
+ return embeddings
216
+
217
+ def embed_query(self, text: str) -> List[float]:
218
+ """Embed a query using a Ollama deployed embedding model.
219
+
220
+ Args:
221
+ text: The text to embed.
222
+
223
+ Returns:
224
+ Embeddings for the text.
225
+ """
226
+ instruction_pair = f"{self.query_instruction}{text}"
227
+ embedding = self._embed([instruction_pair])[0]
228
+ return embedding
python/user_packages/Python313/site-packages/langchain_community/embeddings/openai.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import warnings
6
+ from typing import (
7
+ Any,
8
+ Callable,
9
+ Dict,
10
+ List,
11
+ Literal,
12
+ Mapping,
13
+ Optional,
14
+ Sequence,
15
+ Set,
16
+ Tuple,
17
+ Union,
18
+ cast,
19
+ )
20
+
21
+ import numpy as np
22
+ from langchain_core._api.deprecation import deprecated
23
+ from langchain_core.embeddings import Embeddings
24
+ from langchain_core.utils import (
25
+ get_from_dict_or_env,
26
+ get_pydantic_field_names,
27
+ pre_init,
28
+ )
29
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
30
+ from tenacity import (
31
+ AsyncRetrying,
32
+ before_sleep_log,
33
+ retry,
34
+ retry_if_exception_type,
35
+ stop_after_attempt,
36
+ wait_exponential,
37
+ )
38
+
39
+ from langchain_community.utils.openai import is_openai_v1
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ def _create_retry_decorator(embeddings: OpenAIEmbeddings) -> Callable[[Any], Any]:
45
+ import openai
46
+
47
+ # Wait 2^x * 1 second between each retry starting with
48
+ # retry_min_seconds seconds, then up to retry_max_seconds seconds,
49
+ # then retry_max_seconds seconds afterwards
50
+ # retry_min_seconds and retry_max_seconds are optional arguments of
51
+ # OpenAIEmbeddings
52
+ return retry(
53
+ reraise=True,
54
+ stop=stop_after_attempt(embeddings.max_retries),
55
+ wait=wait_exponential(
56
+ multiplier=1,
57
+ min=embeddings.retry_min_seconds,
58
+ max=embeddings.retry_max_seconds,
59
+ ),
60
+ retry=(
61
+ retry_if_exception_type(openai.error.Timeout)
62
+ | retry_if_exception_type(openai.error.APIError)
63
+ | retry_if_exception_type(openai.error.APIConnectionError)
64
+ | retry_if_exception_type(openai.error.RateLimitError)
65
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
66
+ ),
67
+ before_sleep=before_sleep_log(logger, logging.WARNING),
68
+ )
69
+
70
+
71
+ def _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any:
72
+ import openai
73
+
74
+ # Wait 2^x * 1 second between each retry starting with
75
+ # retry_min_seconds seconds, then up to retry_max_seconds seconds,
76
+ # then retry_max_seconds seconds afterwards
77
+ # retry_min_seconds and retry_max_seconds are optional arguments of
78
+ # OpenAIEmbeddings
79
+ async_retrying = AsyncRetrying(
80
+ reraise=True,
81
+ stop=stop_after_attempt(embeddings.max_retries),
82
+ wait=wait_exponential(
83
+ multiplier=1,
84
+ min=embeddings.retry_min_seconds,
85
+ max=embeddings.retry_max_seconds,
86
+ ),
87
+ retry=(
88
+ retry_if_exception_type(openai.error.Timeout)
89
+ | retry_if_exception_type(openai.error.APIError)
90
+ | retry_if_exception_type(openai.error.APIConnectionError)
91
+ | retry_if_exception_type(openai.error.RateLimitError)
92
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
93
+ ),
94
+ before_sleep=before_sleep_log(logger, logging.WARNING),
95
+ )
96
+
97
+ def wrap(func: Callable) -> Callable:
98
+ async def wrapped_f(*args: Any, **kwargs: Any) -> Callable:
99
+ async for _ in async_retrying:
100
+ return await func(*args, **kwargs)
101
+ raise AssertionError("this is unreachable")
102
+
103
+ return wrapped_f
104
+
105
+ return wrap
106
+
107
+
108
+ # https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings
109
+ def _check_response(response: dict, skip_empty: bool = False) -> dict:
110
+ if any(len(d["embedding"]) == 1 for d in response["data"]) and not skip_empty:
111
+ import openai
112
+
113
+ raise openai.error.APIError("OpenAI API returned an empty embedding")
114
+ return response
115
+
116
+
117
+ def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any:
118
+ """Use tenacity to retry the embedding call."""
119
+ if is_openai_v1():
120
+ return embeddings.client.create(**kwargs)
121
+ retry_decorator = _create_retry_decorator(embeddings)
122
+
123
+ @retry_decorator
124
+ def _embed_with_retry(**kwargs: Any) -> Any:
125
+ response = embeddings.client.create(**kwargs)
126
+ return _check_response(response, skip_empty=embeddings.skip_empty)
127
+
128
+ return _embed_with_retry(**kwargs)
129
+
130
+
131
+ async def async_embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any:
132
+ """Use tenacity to retry the embedding call."""
133
+
134
+ if is_openai_v1():
135
+ return await embeddings.async_client.create(**kwargs)
136
+
137
+ @_async_retry_decorator(embeddings)
138
+ async def _async_embed_with_retry(**kwargs: Any) -> Any:
139
+ response = await embeddings.client.acreate(**kwargs)
140
+ return _check_response(response, skip_empty=embeddings.skip_empty)
141
+
142
+ return await _async_embed_with_retry(**kwargs)
143
+
144
+
145
+ @deprecated(
146
+ since="0.0.9",
147
+ removal="1.0",
148
+ alternative_import="langchain_openai.OpenAIEmbeddings",
149
+ )
150
+ class OpenAIEmbeddings(BaseModel, Embeddings):
151
+ """OpenAI embedding models.
152
+
153
+ To use, you should have the ``openai`` python package installed, and the
154
+ environment variable ``OPENAI_API_KEY`` set with your API key or pass it
155
+ as a named parameter to the constructor.
156
+
157
+ Example:
158
+ .. code-block:: python
159
+
160
+ from langchain_community.embeddings import OpenAIEmbeddings
161
+ openai = OpenAIEmbeddings(openai_api_key="my-api-key")
162
+
163
+ In order to use the library with Microsoft Azure endpoints, you need to set
164
+ the OPENAI_API_TYPE, OPENAI_API_BASE, OPENAI_API_KEY and OPENAI_API_VERSION.
165
+ The OPENAI_API_TYPE must be set to 'azure' and the others correspond to
166
+ the properties of your endpoint.
167
+ In addition, the deployment name must be passed as the model parameter.
168
+
169
+ Example:
170
+ .. code-block:: python
171
+
172
+ import os
173
+
174
+ os.environ["OPENAI_API_TYPE"] = "azure"
175
+ os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"
176
+ os.environ["OPENAI_API_KEY"] = "your AzureOpenAI key"
177
+ os.environ["OPENAI_API_VERSION"] = "2023-05-15"
178
+ os.environ["OPENAI_PROXY"] = "http://your-corporate-proxy:8080"
179
+
180
+ from langchain_community.embeddings.openai import OpenAIEmbeddings
181
+ embeddings = OpenAIEmbeddings(
182
+ deployment="your-embeddings-deployment-name",
183
+ model="your-embeddings-model-name",
184
+ openai_api_base="https://your-endpoint.openai.azure.com/",
185
+ openai_api_type="azure",
186
+ )
187
+ text = "This is a test query."
188
+ query_result = embeddings.embed_query(text)
189
+
190
+ """
191
+
192
+ client: Any = Field(default=None, exclude=True) #: :meta private:
193
+ async_client: Any = Field(default=None, exclude=True) #: :meta private:
194
+ model: str = "text-embedding-ada-002"
195
+ # to support Azure OpenAI Service custom deployment names
196
+ deployment: Optional[str] = model
197
+ # TODO: Move to AzureOpenAIEmbeddings.
198
+ openai_api_version: Optional[str] = Field(default=None, alias="api_version")
199
+ """Automatically inferred from env var `OPENAI_API_VERSION` if not provided."""
200
+ # to support Azure OpenAI Service custom endpoints
201
+ openai_api_base: Optional[str] = Field(default=None, alias="base_url")
202
+ """Base URL path for API requests, leave blank if not using a proxy or service
203
+ emulator."""
204
+ # to support Azure OpenAI Service custom endpoints
205
+ openai_api_type: Optional[str] = None
206
+ # to support explicit proxy for OpenAI
207
+ openai_proxy: Optional[str] = None
208
+ embedding_ctx_length: int = 8191
209
+ """The maximum number of tokens to embed at once."""
210
+ openai_api_key: Optional[str] = Field(default=None, alias="api_key")
211
+ """Automatically inferred from env var `OPENAI_API_KEY` if not provided."""
212
+ openai_organization: Optional[str] = Field(default=None, alias="organization")
213
+ """Automatically inferred from env var `OPENAI_ORG_ID` if not provided."""
214
+ allowed_special: Union[Literal["all"], Set[str]] = set()
215
+ disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all"
216
+ chunk_size: int = 1000
217
+ """Maximum number of texts to embed in each batch"""
218
+ max_retries: int = 2
219
+ """Maximum number of retries to make when generating."""
220
+ request_timeout: Optional[Union[float, Tuple[float, float], Any]] = Field(
221
+ default=None, alias="timeout"
222
+ )
223
+ """Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or
224
+ None."""
225
+ headers: Any = None
226
+ tiktoken_enabled: bool = True
227
+ """Set this to False for non-OpenAI implementations of the embeddings API, e.g.
228
+ the `--extensions openai` extension for `text-generation-webui`"""
229
+ tiktoken_model_name: Optional[str] = None
230
+ """The model name to pass to tiktoken when using this class.
231
+ Tiktoken is used to count the number of tokens in documents to constrain
232
+ them to be under a certain limit. By default, when set to None, this will
233
+ be the same as the embedding model name. However, there are some cases
234
+ where you may want to use this Embedding class with a model name not
235
+ supported by tiktoken. This can include when using Azure embeddings or
236
+ when using one of the many model providers that expose an OpenAI-like
237
+ API but with different models. In those cases, in order to avoid erroring
238
+ when tiktoken is called, you can specify a model name to use here."""
239
+ show_progress_bar: bool = False
240
+ """Whether to show a progress bar when embedding."""
241
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
242
+ """Holds any model parameters valid for `create` call not explicitly specified."""
243
+ skip_empty: bool = False
244
+ """Whether to skip empty strings when embedding or raise an error.
245
+ Defaults to not skipping."""
246
+ default_headers: Union[Mapping[str, str], None] = None
247
+ default_query: Union[Mapping[str, object], None] = None
248
+ # Configure a custom httpx client. See the
249
+ # [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
250
+ retry_min_seconds: int = 4
251
+ """Min number of seconds to wait between retries"""
252
+ retry_max_seconds: int = 20
253
+ """Max number of seconds to wait between retries"""
254
+ http_client: Union[Any, None] = None
255
+ """Optional httpx.Client."""
256
+
257
+ model_config = ConfigDict(
258
+ populate_by_name=True, extra="forbid", protected_namespaces=()
259
+ )
260
+
261
+ @model_validator(mode="before")
262
+ @classmethod
263
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
264
+ """Build extra kwargs from additional params that were passed in."""
265
+ all_required_field_names = get_pydantic_field_names(cls)
266
+ extra = values.get("model_kwargs", {})
267
+ for field_name in list(values):
268
+ if field_name in extra:
269
+ raise ValueError(f"Found {field_name} supplied twice.")
270
+ if field_name not in all_required_field_names:
271
+ warnings.warn(
272
+ f"""WARNING! {field_name} is not default parameter.
273
+ {field_name} was transferred to model_kwargs.
274
+ Please confirm that {field_name} is what you intended."""
275
+ )
276
+ extra[field_name] = values.pop(field_name)
277
+
278
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
279
+ if invalid_model_kwargs:
280
+ raise ValueError(
281
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
282
+ f"Instead they were passed in as part of `model_kwargs` parameter."
283
+ )
284
+
285
+ values["model_kwargs"] = extra
286
+ return values
287
+
288
+ @pre_init
289
+ def validate_environment(cls, values: Dict) -> Dict:
290
+ """Validate that api key and python package exists in environment."""
291
+ values["openai_api_key"] = get_from_dict_or_env(
292
+ values, "openai_api_key", "OPENAI_API_KEY"
293
+ )
294
+ values["openai_api_base"] = values["openai_api_base"] or os.getenv(
295
+ "OPENAI_API_BASE"
296
+ )
297
+ values["openai_api_type"] = get_from_dict_or_env(
298
+ values,
299
+ "openai_api_type",
300
+ "OPENAI_API_TYPE",
301
+ default="",
302
+ )
303
+ values["openai_proxy"] = get_from_dict_or_env(
304
+ values,
305
+ "openai_proxy",
306
+ "OPENAI_PROXY",
307
+ default="",
308
+ )
309
+ if values["openai_api_type"] in ("azure", "azure_ad", "azuread"):
310
+ default_api_version = "2023-05-15"
311
+ # Azure OpenAI embedding models allow a maximum of 2048
312
+ # texts at a time in each batch
313
+ # See: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings
314
+ values["chunk_size"] = min(values["chunk_size"], 2048)
315
+ else:
316
+ default_api_version = ""
317
+ values["openai_api_version"] = get_from_dict_or_env(
318
+ values,
319
+ "openai_api_version",
320
+ "OPENAI_API_VERSION",
321
+ default=default_api_version,
322
+ )
323
+ # Check OPENAI_ORGANIZATION for backwards compatibility.
324
+ values["openai_organization"] = (
325
+ values["openai_organization"]
326
+ or os.getenv("OPENAI_ORG_ID")
327
+ or os.getenv("OPENAI_ORGANIZATION")
328
+ )
329
+ try:
330
+ import openai
331
+ except ImportError:
332
+ raise ImportError(
333
+ "Could not import openai python package. "
334
+ "Please install it with `pip install openai`."
335
+ )
336
+ else:
337
+ if is_openai_v1():
338
+ if values["openai_api_type"] in ("azure", "azure_ad", "azuread"):
339
+ warnings.warn(
340
+ "If you have openai>=1.0.0 installed and are using Azure, "
341
+ "please use the `AzureOpenAIEmbeddings` class."
342
+ )
343
+ client_params = {
344
+ "api_key": values["openai_api_key"],
345
+ "organization": values["openai_organization"],
346
+ "base_url": values["openai_api_base"],
347
+ "timeout": values["request_timeout"],
348
+ "max_retries": values["max_retries"],
349
+ "default_headers": values["default_headers"],
350
+ "default_query": values["default_query"],
351
+ "http_client": values["http_client"],
352
+ }
353
+ if not values.get("client"):
354
+ values["client"] = openai.OpenAI(**client_params).embeddings
355
+ if not values.get("async_client"):
356
+ values["async_client"] = openai.AsyncOpenAI(
357
+ **client_params
358
+ ).embeddings
359
+ elif not values.get("client"):
360
+ values["client"] = openai.Embedding
361
+ else:
362
+ pass
363
+ return values
364
+
365
+ @property
366
+ def _invocation_params(self) -> Dict[str, Any]:
367
+ if is_openai_v1():
368
+ openai_args: Dict = {"model": self.model, **self.model_kwargs}
369
+ else:
370
+ openai_args = {
371
+ "model": self.model,
372
+ "request_timeout": self.request_timeout,
373
+ "headers": self.headers,
374
+ "api_key": self.openai_api_key,
375
+ "organization": self.openai_organization,
376
+ "api_base": self.openai_api_base,
377
+ "api_type": self.openai_api_type,
378
+ "api_version": self.openai_api_version,
379
+ **self.model_kwargs,
380
+ }
381
+ if self.openai_api_type in ("azure", "azure_ad", "azuread"):
382
+ openai_args["engine"] = self.deployment
383
+ # TODO: Look into proxy with openai v1.
384
+ if self.openai_proxy:
385
+ try:
386
+ import openai
387
+ except ImportError:
388
+ raise ImportError(
389
+ "Could not import openai python package. "
390
+ "Please install it with `pip install openai`."
391
+ )
392
+
393
+ openai.proxy = {
394
+ "http": self.openai_proxy,
395
+ "https": self.openai_proxy,
396
+ }
397
+ return openai_args
398
+
399
+ # please refer to
400
+ # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb
401
+ def _get_len_safe_embeddings(
402
+ self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None
403
+ ) -> List[List[float]]:
404
+ """
405
+ Generate length-safe embeddings for a list of texts.
406
+
407
+ This method handles tokenization and embedding generation, respecting the
408
+ set embedding context length and chunk size. It supports both tiktoken
409
+ and HuggingFace tokenizer based on the tiktoken_enabled flag.
410
+
411
+ Args:
412
+ texts (List[str]): A list of texts to embed.
413
+ engine (str): The engine or model to use for embeddings.
414
+ chunk_size (Optional[int]): The size of chunks for processing embeddings.
415
+
416
+ Returns:
417
+ List[List[float]]: A list of embeddings for each input text.
418
+ """
419
+
420
+ tokens = []
421
+ indices = []
422
+ model_name = self.tiktoken_model_name or self.model
423
+ _chunk_size = chunk_size or self.chunk_size
424
+
425
+ # If tiktoken flag set to False
426
+ if not self.tiktoken_enabled:
427
+ try:
428
+ from transformers import AutoTokenizer
429
+ except ImportError:
430
+ raise ImportError(
431
+ "Could not import transformers python package. "
432
+ "This is needed in order to for OpenAIEmbeddings without "
433
+ "`tiktoken`. Please install it with `pip install transformers`. "
434
+ )
435
+
436
+ tokenizer = AutoTokenizer.from_pretrained(
437
+ pretrained_model_name_or_path=model_name
438
+ )
439
+ for i, text in enumerate(texts):
440
+ # Tokenize the text using HuggingFace transformers
441
+ tokenized = tokenizer.encode(text, add_special_tokens=False)
442
+
443
+ # Split tokens into chunks respecting the embedding_ctx_length
444
+ for j in range(0, len(tokenized), self.embedding_ctx_length):
445
+ token_chunk = tokenized[j : j + self.embedding_ctx_length]
446
+
447
+ # Convert token IDs back to a string
448
+ chunk_text = tokenizer.decode(token_chunk)
449
+ tokens.append(chunk_text)
450
+ indices.append(i)
451
+ else:
452
+ try:
453
+ import tiktoken
454
+ except ImportError:
455
+ raise ImportError(
456
+ "Could not import tiktoken python package. "
457
+ "This is needed in order to for OpenAIEmbeddings. "
458
+ "Please install it with `pip install tiktoken`."
459
+ )
460
+
461
+ try:
462
+ encoding = tiktoken.encoding_for_model(model_name)
463
+ except KeyError:
464
+ logger.warning("Warning: model not found. Using cl100k_base encoding.")
465
+ model = "cl100k_base"
466
+ encoding = tiktoken.get_encoding(model)
467
+ for i, text in enumerate(texts):
468
+ if self.model.endswith("001"):
469
+ # See: https://github.com/openai/openai-python/
470
+ # issues/418#issuecomment-1525939500
471
+ # replace newlines, which can negatively affect performance.
472
+ text = text.replace("\n", " ")
473
+
474
+ token = encoding.encode(
475
+ text=text,
476
+ allowed_special=self.allowed_special,
477
+ disallowed_special=self.disallowed_special,
478
+ )
479
+
480
+ # Split tokens into chunks respecting the embedding_ctx_length
481
+ for j in range(0, len(token), self.embedding_ctx_length):
482
+ tokens.append(token[j : j + self.embedding_ctx_length])
483
+ indices.append(i)
484
+
485
+ if self.show_progress_bar:
486
+ try:
487
+ from tqdm.auto import tqdm
488
+
489
+ _iter = tqdm(range(0, len(tokens), _chunk_size))
490
+ except ImportError:
491
+ _iter = range(0, len(tokens), _chunk_size)
492
+ else:
493
+ _iter = range(0, len(tokens), _chunk_size)
494
+
495
+ batched_embeddings: List[List[float]] = []
496
+ for i in _iter:
497
+ response = embed_with_retry(
498
+ self,
499
+ input=tokens[i : i + _chunk_size],
500
+ **self._invocation_params,
501
+ )
502
+ if not isinstance(response, dict):
503
+ response = response.dict()
504
+ batched_embeddings.extend(r["embedding"] for r in response["data"])
505
+
506
+ results: List[List[List[float]]] = [[] for _ in range(len(texts))]
507
+ num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))]
508
+ for i in range(len(indices)):
509
+ if self.skip_empty and len(batched_embeddings[i]) == 1:
510
+ continue
511
+ results[indices[i]].append(batched_embeddings[i])
512
+ num_tokens_in_batch[indices[i]].append(len(tokens[i]))
513
+
514
+ embeddings: List[List[float]] = [[] for _ in range(len(texts))]
515
+ for i in range(len(texts)):
516
+ _result = results[i]
517
+ if len(_result) == 0:
518
+ average_embedded = embed_with_retry(
519
+ self,
520
+ input="",
521
+ **self._invocation_params,
522
+ )
523
+ if not isinstance(average_embedded, dict):
524
+ average_embedded = average_embedded.dict()
525
+ average = average_embedded["data"][0]["embedding"]
526
+ else:
527
+ average = np.average(_result, axis=0, weights=num_tokens_in_batch[i])
528
+ embeddings[i] = (average / np.linalg.norm(average)).tolist()
529
+
530
+ return embeddings
531
+
532
+ # please refer to
533
+ # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb
534
+ async def _aget_len_safe_embeddings(
535
+ self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None
536
+ ) -> List[List[float]]:
537
+ """
538
+ Asynchronously generate length-safe embeddings for a list of texts.
539
+
540
+ This method handles tokenization and asynchronous embedding generation,
541
+ respecting the set embedding context length and chunk size. It supports both
542
+ `tiktoken` and HuggingFace `tokenizer` based on the tiktoken_enabled flag.
543
+
544
+ Args:
545
+ texts (List[str]): A list of texts to embed.
546
+ engine (str): The engine or model to use for embeddings.
547
+ chunk_size (Optional[int]): The size of chunks for processing embeddings.
548
+
549
+ Returns:
550
+ List[List[float]]: A list of embeddings for each input text.
551
+ """
552
+
553
+ tokens = []
554
+ indices = []
555
+ model_name = self.tiktoken_model_name or self.model
556
+ _chunk_size = chunk_size or self.chunk_size
557
+
558
+ # If tiktoken flag set to False
559
+ if not self.tiktoken_enabled:
560
+ try:
561
+ from transformers import AutoTokenizer
562
+ except ImportError:
563
+ raise ImportError(
564
+ "Could not import transformers python package. "
565
+ "This is needed in order to for OpenAIEmbeddings without "
566
+ " `tiktoken`. Please install it with `pip install transformers`."
567
+ )
568
+
569
+ tokenizer = AutoTokenizer.from_pretrained(
570
+ pretrained_model_name_or_path=model_name
571
+ )
572
+ for i, text in enumerate(texts):
573
+ # Tokenize the text using HuggingFace transformers
574
+ tokenized = tokenizer.encode(text, add_special_tokens=False)
575
+
576
+ # Split tokens into chunks respecting the embedding_ctx_length
577
+ for j in range(0, len(tokenized), self.embedding_ctx_length):
578
+ token_chunk = tokenized[j : j + self.embedding_ctx_length]
579
+
580
+ # Convert token IDs back to a string
581
+ chunk_text = tokenizer.decode(token_chunk)
582
+ tokens.append(chunk_text)
583
+ indices.append(i)
584
+ else:
585
+ try:
586
+ import tiktoken
587
+ except ImportError:
588
+ raise ImportError(
589
+ "Could not import tiktoken python package. "
590
+ "This is needed in order to for OpenAIEmbeddings. "
591
+ "Please install it with `pip install tiktoken`."
592
+ )
593
+
594
+ try:
595
+ encoding = tiktoken.encoding_for_model(model_name)
596
+ except KeyError:
597
+ logger.warning("Warning: model not found. Using cl100k_base encoding.")
598
+ model = "cl100k_base"
599
+ encoding = tiktoken.get_encoding(model)
600
+ for i, text in enumerate(texts):
601
+ if self.model.endswith("001"):
602
+ # See: https://github.com/openai/openai-python/
603
+ # issues/418#issuecomment-1525939500
604
+ # replace newlines, which can negatively affect performance.
605
+ text = text.replace("\n", " ")
606
+
607
+ token = encoding.encode(
608
+ text=text,
609
+ allowed_special=self.allowed_special,
610
+ disallowed_special=self.disallowed_special,
611
+ )
612
+
613
+ # Split tokens into chunks respecting the embedding_ctx_length
614
+ for j in range(0, len(token), self.embedding_ctx_length):
615
+ tokens.append(token[j : j + self.embedding_ctx_length])
616
+ indices.append(i)
617
+
618
+ batched_embeddings: List[List[float]] = []
619
+ _chunk_size = chunk_size or self.chunk_size
620
+ for i in range(0, len(tokens), _chunk_size):
621
+ response = await async_embed_with_retry(
622
+ self,
623
+ input=tokens[i : i + _chunk_size],
624
+ **self._invocation_params,
625
+ )
626
+
627
+ if not isinstance(response, dict):
628
+ response = response.dict()
629
+ batched_embeddings.extend(r["embedding"] for r in response["data"])
630
+
631
+ results: List[List[List[float]]] = [[] for _ in range(len(texts))]
632
+ num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))]
633
+ for i in range(len(indices)):
634
+ results[indices[i]].append(batched_embeddings[i])
635
+ num_tokens_in_batch[indices[i]].append(len(tokens[i]))
636
+
637
+ embeddings: List[List[float]] = [[] for _ in range(len(texts))]
638
+ for i in range(len(texts)):
639
+ _result = results[i]
640
+ if len(_result) == 0:
641
+ average_embedded = await async_embed_with_retry(
642
+ self,
643
+ input="",
644
+ **self._invocation_params,
645
+ )
646
+ if not isinstance(average_embedded, dict):
647
+ average_embedded = average_embedded.dict()
648
+ average = average_embedded["data"][0]["embedding"]
649
+ else:
650
+ average = np.average(_result, axis=0, weights=num_tokens_in_batch[i])
651
+ embeddings[i] = (average / np.linalg.norm(average)).tolist()
652
+
653
+ return embeddings
654
+
655
+ def embed_documents(
656
+ self, texts: List[str], chunk_size: Optional[int] = 0
657
+ ) -> List[List[float]]:
658
+ """Call out to OpenAI's embedding endpoint for embedding search docs.
659
+
660
+ Args:
661
+ texts: The list of texts to embed.
662
+ chunk_size: The chunk size of embeddings. If None, will use the chunk size
663
+ specified by the class.
664
+
665
+ Returns:
666
+ List of embeddings, one for each text.
667
+ """
668
+ # NOTE: to keep things simple, we assume the list may contain texts longer
669
+ # than the maximum context and use length-safe embedding function.
670
+ engine = cast(str, self.deployment)
671
+ return self._get_len_safe_embeddings(
672
+ texts, engine=engine, chunk_size=chunk_size
673
+ )
674
+
675
+ async def aembed_documents(
676
+ self, texts: List[str], chunk_size: Optional[int] = 0
677
+ ) -> List[List[float]]:
678
+ """Call out to OpenAI's embedding endpoint async for embedding search docs.
679
+
680
+ Args:
681
+ texts: The list of texts to embed.
682
+ chunk_size: The chunk size of embeddings. If None, will use the chunk size
683
+ specified by the class.
684
+
685
+ Returns:
686
+ List of embeddings, one for each text.
687
+ """
688
+ # NOTE: to keep things simple, we assume the list may contain texts longer
689
+ # than the maximum context and use length-safe embedding function.
690
+ engine = cast(str, self.deployment)
691
+ return self._get_len_safe_embeddings(
692
+ texts, engine=engine, chunk_size=chunk_size
693
+ )
694
+
695
+ def embed_query(self, text: str) -> List[float]:
696
+ """Call out to OpenAI's embedding endpoint for embedding query text.
697
+
698
+ Args:
699
+ text: The text to embed.
700
+
701
+ Returns:
702
+ Embedding for the text.
703
+ """
704
+ return self.embed_documents([text])[0]
705
+
706
+ async def aembed_query(self, text: str) -> List[float]:
707
+ """Call out to OpenAI's embedding endpoint async for embedding query text.
708
+
709
+ Args:
710
+ text: The text to embed.
711
+
712
+ Returns:
713
+ Embedding for the text.
714
+ """
715
+ embeddings = await self.aembed_documents([text])
716
+ return embeddings[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/openvino.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import Any, Dict, List
3
+
4
+ from langchain_core.embeddings import Embeddings
5
+ from pydantic import BaseModel, ConfigDict, Field
6
+
7
+ DEFAULT_QUERY_INSTRUCTION = (
8
+ "Represent the question for retrieving supporting documents: "
9
+ )
10
+ DEFAULT_QUERY_BGE_INSTRUCTION_EN = (
11
+ "Represent this question for searching relevant passages: "
12
+ )
13
+ DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:"
14
+
15
+
16
+ class OpenVINOEmbeddings(BaseModel, Embeddings):
17
+ """OpenVINO embedding models.
18
+
19
+ Example:
20
+ .. code-block:: python
21
+
22
+ from langchain_community.embeddings import OpenVINOEmbeddings
23
+
24
+ model_name = "sentence-transformers/all-mpnet-base-v2"
25
+ model_kwargs = {'device': 'CPU'}
26
+ encode_kwargs = {'normalize_embeddings': True}
27
+ ov = OpenVINOEmbeddings(
28
+ model_name_or_path=model_name,
29
+ model_kwargs=model_kwargs,
30
+ encode_kwargs=encode_kwargs
31
+ )
32
+ """
33
+
34
+ ov_model: Any = None
35
+ """OpenVINO model object."""
36
+ tokenizer: Any = None
37
+ """Tokenizer for embedding model."""
38
+ model_name_or_path: str
39
+ """HuggingFace model id."""
40
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
41
+ """Keyword arguments to pass to the model."""
42
+ encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
43
+ """Keyword arguments to pass when calling the `encode` method of the model."""
44
+ show_progress: bool = False
45
+ """Whether to show a progress bar."""
46
+
47
+ def __init__(self, **kwargs: Any):
48
+ """Initialize the sentence_transformer."""
49
+ super().__init__(**kwargs)
50
+
51
+ try:
52
+ from optimum.intel.openvino import OVModelForFeatureExtraction
53
+ except ImportError as e:
54
+ raise ImportError(
55
+ "Could not import optimum-intel python package. "
56
+ "Please install it with: "
57
+ "pip install -U 'optimum[openvino,nncf]'"
58
+ ) from e
59
+
60
+ try:
61
+ from huggingface_hub import HfApi
62
+ except ImportError as e:
63
+ raise ImportError(
64
+ "Could not import huggingface_hub python package. "
65
+ "Please install it with: "
66
+ "`pip install -U huggingface_hub`."
67
+ ) from e
68
+
69
+ def require_model_export(
70
+ model_id: str, revision: Any = None, subfolder: Any = None
71
+ ) -> bool:
72
+ model_dir = Path(model_id)
73
+ if subfolder is not None:
74
+ model_dir = model_dir / subfolder
75
+ if model_dir.is_dir():
76
+ return (
77
+ not (model_dir / "openvino_model.xml").exists()
78
+ or not (model_dir / "openvino_model.bin").exists()
79
+ )
80
+ hf_api = HfApi()
81
+ try:
82
+ model_info = hf_api.model_info(model_id, revision=revision or "main")
83
+ normalized_subfolder = (
84
+ None if subfolder is None else Path(subfolder).as_posix()
85
+ )
86
+ model_files = [
87
+ file.rfilename
88
+ for file in model_info.siblings
89
+ if normalized_subfolder is None
90
+ or file.rfilename.startswith(normalized_subfolder)
91
+ ]
92
+ ov_model_path = (
93
+ "openvino_model.xml"
94
+ if subfolder is None
95
+ else f"{normalized_subfolder}/openvino_model.xml"
96
+ )
97
+ return (
98
+ ov_model_path not in model_files
99
+ or ov_model_path.replace(".xml", ".bin") not in model_files
100
+ )
101
+ except Exception:
102
+ return True
103
+
104
+ if require_model_export(self.model_name_or_path):
105
+ # use remote model
106
+ self.ov_model = OVModelForFeatureExtraction.from_pretrained(
107
+ self.model_name_or_path, export=True, **self.model_kwargs
108
+ )
109
+ else:
110
+ # use local model
111
+ self.ov_model = OVModelForFeatureExtraction.from_pretrained(
112
+ self.model_name_or_path, **self.model_kwargs
113
+ )
114
+
115
+ try:
116
+ from transformers import AutoTokenizer
117
+ except ImportError as e:
118
+ raise ImportError(
119
+ "Unable to import transformers, please install with "
120
+ "`pip install -U transformers`."
121
+ ) from e
122
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path)
123
+
124
+ def _text_length(self, text: Any) -> int:
125
+ """
126
+ Help function to get the length for the input text. Text can be either
127
+ a list of ints (which means a single text as input), or a tuple of list of ints
128
+ (representing several text inputs to the model).
129
+ """
130
+
131
+ if isinstance(text, dict): # {key: value} case
132
+ return len(next(iter(text.values())))
133
+ elif not hasattr(text, "__len__"): # Object has no len() method
134
+ return 1
135
+ # Empty string or list of ints
136
+ elif len(text) == 0 or isinstance(text[0], int):
137
+ return len(text)
138
+ else:
139
+ # Sum of length of individual strings
140
+ return sum([len(t) for t in text])
141
+
142
+ def encode(
143
+ self,
144
+ sentences: Any,
145
+ batch_size: int = 4,
146
+ show_progress_bar: bool = False,
147
+ convert_to_numpy: bool = True,
148
+ convert_to_tensor: bool = False,
149
+ mean_pooling: bool = False,
150
+ normalize_embeddings: bool = True,
151
+ ) -> Any:
152
+ """
153
+ Computes sentence embeddings.
154
+
155
+ :param sentences: the sentences to embed.
156
+ :param batch_size: the batch size used for the computation.
157
+ :param show_progress_bar: Whether to output a progress bar.
158
+ :param convert_to_numpy: Whether the output should be a list of numpy vectors.
159
+ :param convert_to_tensor: Whether the output should be one large tensor.
160
+ :param mean_pooling: Whether to pool returned vectors.
161
+ :param normalize_embeddings: Whether to normalize returned vectors.
162
+
163
+ :return: By default, a 2d numpy array with shape [num_inputs, output_dimension].
164
+ """
165
+ try:
166
+ import numpy as np
167
+ except ImportError as e:
168
+ raise ImportError(
169
+ "Unable to import numpy, please install with `pip install -U numpy`."
170
+ ) from e
171
+ try:
172
+ from tqdm import trange
173
+ except ImportError as e:
174
+ raise ImportError(
175
+ "Unable to import tqdm, please install with `pip install -U tqdm`."
176
+ ) from e
177
+ try:
178
+ import torch
179
+ except ImportError as e:
180
+ raise ImportError(
181
+ "Unable to import torch, please install with `pip install -U torch`."
182
+ ) from e
183
+
184
+ def run_mean_pooling(model_output: Any, attention_mask: Any) -> Any:
185
+ token_embeddings = model_output[
186
+ 0
187
+ ] # First element of model_output contains all token embeddings
188
+ input_mask_expanded = (
189
+ attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
190
+ )
191
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
192
+ input_mask_expanded.sum(1), min=1e-9
193
+ )
194
+
195
+ if convert_to_tensor:
196
+ convert_to_numpy = False
197
+
198
+ input_was_string = False
199
+ if isinstance(sentences, str) or not hasattr(
200
+ sentences, "__len__"
201
+ ): # Cast an individual sentence to a list with length 1
202
+ sentences = [sentences]
203
+ input_was_string = True
204
+
205
+ all_embeddings: Any = []
206
+ length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences])
207
+ sentences_sorted = [sentences[idx] for idx in length_sorted_idx]
208
+
209
+ for start_index in trange(
210
+ 0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar
211
+ ):
212
+ sentences_batch = sentences_sorted[start_index : start_index + batch_size]
213
+
214
+ length = self.ov_model.request.inputs[0].get_partial_shape()[1]
215
+ if length.is_dynamic:
216
+ features = self.tokenizer(
217
+ sentences_batch, padding=True, truncation=True, return_tensors="pt"
218
+ )
219
+ else:
220
+ features = self.tokenizer(
221
+ sentences_batch,
222
+ padding="max_length",
223
+ max_length=length.get_length(),
224
+ truncation=True,
225
+ return_tensors="pt",
226
+ )
227
+
228
+ out_features = self.ov_model(**features)
229
+ if mean_pooling:
230
+ embeddings = run_mean_pooling(out_features, features["attention_mask"])
231
+ else:
232
+ embeddings = out_features[0][:, 0]
233
+ if normalize_embeddings:
234
+ embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
235
+
236
+ # fixes for #522 and #487 to avoid oom problems on gpu with large datasets
237
+ if convert_to_numpy:
238
+ embeddings = embeddings.cpu()
239
+
240
+ all_embeddings.extend(embeddings)
241
+
242
+ all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)]
243
+
244
+ if convert_to_tensor:
245
+ if len(all_embeddings):
246
+ all_embeddings = torch.stack(all_embeddings)
247
+ else:
248
+ all_embeddings = torch.Tensor()
249
+ elif convert_to_numpy:
250
+ all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
251
+
252
+ if input_was_string:
253
+ all_embeddings = all_embeddings[0]
254
+
255
+ return all_embeddings
256
+
257
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
258
+
259
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
260
+ """Compute doc embeddings using a HuggingFace transformer model.
261
+
262
+ Args:
263
+ texts: The list of texts to embed.
264
+
265
+ Returns:
266
+ List of embeddings, one for each text.
267
+ """
268
+
269
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
270
+ embeddings = self.encode(
271
+ texts, show_progress_bar=self.show_progress, **self.encode_kwargs
272
+ )
273
+
274
+ return embeddings.tolist()
275
+
276
+ def embed_query(self, text: str) -> List[float]:
277
+ """Compute query embeddings using a HuggingFace transformer model.
278
+
279
+ Args:
280
+ text: The text to embed.
281
+
282
+ Returns:
283
+ Embeddings for the text.
284
+ """
285
+ return self.embed_documents([text])[0]
286
+
287
+ def save_model(
288
+ self,
289
+ model_path: str,
290
+ ) -> bool:
291
+ self.ov_model.half()
292
+ self.ov_model.save_pretrained(model_path)
293
+ self.tokenizer.save_pretrained(model_path)
294
+ return True
295
+
296
+
297
+ class OpenVINOBgeEmbeddings(OpenVINOEmbeddings):
298
+ """OpenVNO BGE embedding models.
299
+
300
+ Bge Example:
301
+ .. code-block:: python
302
+
303
+ from langchain_community.embeddings import OpenVINOBgeEmbeddings
304
+
305
+ model_name = "BAAI/bge-large-en-v1.5"
306
+ model_kwargs = {'device': 'CPU'}
307
+ encode_kwargs = {'normalize_embeddings': True}
308
+ ov = OpenVINOBgeEmbeddings(
309
+ model_name_or_path=model_name,
310
+ model_kwargs=model_kwargs,
311
+ encode_kwargs=encode_kwargs
312
+ )
313
+ """
314
+
315
+ query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN
316
+ """Instruction to use for embedding query."""
317
+ embed_instruction: str = ""
318
+ """Instruction to use for embedding document."""
319
+
320
+ def __init__(self, **kwargs: Any):
321
+ """Initialize the sentence_transformer."""
322
+ super().__init__(**kwargs)
323
+
324
+ if "-zh" in self.model_name_or_path:
325
+ self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH
326
+
327
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
328
+ """Compute doc embeddings using a HuggingFace transformer model.
329
+
330
+ Args:
331
+ texts: The list of texts to embed.
332
+
333
+ Returns:
334
+ List of embeddings, one for each text.
335
+ """
336
+ texts = [self.embed_instruction + t.replace("\n", " ") for t in texts]
337
+ embeddings = self.encode(texts, **self.encode_kwargs)
338
+ return embeddings.tolist()
339
+
340
+ def embed_query(self, text: str) -> List[float]:
341
+ """Compute query embeddings using a HuggingFace transformer model.
342
+
343
+ Args:
344
+ text: The text to embed.
345
+
346
+ Returns:
347
+ Embeddings for the text.
348
+ """
349
+ text = text.replace("\n", " ")
350
+ embedding = self.encode(self.query_instruction + text, **self.encode_kwargs)
351
+ return embedding.tolist()
python/user_packages/Python313/site-packages/langchain_community/embeddings/optimum_intel.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+
7
+ class QuantizedBiEncoderEmbeddings(BaseModel, Embeddings):
8
+ """Quantized bi-encoders embedding models.
9
+
10
+ Please ensure that you have installed optimum-intel and ipex.
11
+
12
+ Input:
13
+ model_name: str = Model name.
14
+ max_seq_len: int = The maximum sequence length for tokenization. (default 512)
15
+ pooling_strategy: str =
16
+ "mean" or "cls", pooling strategy for the final layer. (default "mean")
17
+ query_instruction: Optional[str] =
18
+ An instruction to add to the query before embedding. (default None)
19
+ document_instruction: Optional[str] =
20
+ An instruction to add to each document before embedding. (default None)
21
+ padding: Optional[bool] =
22
+ Whether to add padding during tokenization or not. (default True)
23
+ model_kwargs: Optional[Dict] =
24
+ Parameters to add to the model during initialization. (default {})
25
+ encode_kwargs: Optional[Dict] =
26
+ Parameters to add during the embedding forward pass. (default {})
27
+
28
+ Example:
29
+
30
+ from langchain_community.embeddings import QuantizedBiEncoderEmbeddings
31
+
32
+ model_name = "Intel/bge-small-en-v1.5-rag-int8-static"
33
+ encode_kwargs = {'normalize_embeddings': True}
34
+ hf = QuantizedBiEncoderEmbeddings(
35
+ model_name,
36
+ encode_kwargs=encode_kwargs,
37
+ query_instruction="Represent this sentence for searching relevant passages: "
38
+ )
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ model_name: str,
44
+ max_seq_len: int = 512,
45
+ pooling_strategy: str = "mean", # "mean" or "cls"
46
+ query_instruction: Optional[str] = None,
47
+ document_instruction: Optional[str] = None,
48
+ padding: bool = True,
49
+ model_kwargs: Optional[Dict] = None,
50
+ encode_kwargs: Optional[Dict] = None,
51
+ **kwargs: Any,
52
+ ) -> None:
53
+ super().__init__(**kwargs)
54
+ self.model_name_or_path = model_name
55
+ self.max_seq_len = max_seq_len
56
+ self.pooling = pooling_strategy
57
+ self.padding = padding
58
+ self.encode_kwargs = encode_kwargs or {}
59
+ self.model_kwargs = model_kwargs or {}
60
+
61
+ self.normalize = self.encode_kwargs.get("normalize_embeddings", False)
62
+ self.batch_size = self.encode_kwargs.get("batch_size", 32)
63
+
64
+ self.query_instruction = query_instruction
65
+ self.document_instruction = document_instruction
66
+
67
+ self.load_model()
68
+
69
+ def load_model(self) -> None:
70
+ try:
71
+ from transformers import AutoTokenizer
72
+ except ImportError as e:
73
+ raise ImportError(
74
+ "Unable to import transformers, please install with "
75
+ "`pip install -U transformers`."
76
+ ) from e
77
+ try:
78
+ from optimum.intel import IPEXModel
79
+
80
+ self.transformer_model = IPEXModel.from_pretrained(
81
+ self.model_name_or_path, **self.model_kwargs
82
+ )
83
+ except Exception as e:
84
+ raise Exception(
85
+ f"""
86
+ Failed to load model {self.model_name_or_path}, due to the following error:
87
+ {e}
88
+ Please ensure that you have installed optimum-intel and ipex correctly,using:
89
+
90
+ pip install optimum[neural-compressor]
91
+ pip install intel_extension_for_pytorch
92
+
93
+ For more information, please visit:
94
+ * Install optimum-intel as shown here: https://github.com/huggingface/optimum-intel.
95
+ * Install IPEX as shown here: https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=cpu&version=v2.2.0%2Bcpu.
96
+ """
97
+ )
98
+ self.transformer_tokenizer = AutoTokenizer.from_pretrained(
99
+ pretrained_model_name_or_path=self.model_name_or_path,
100
+ )
101
+ self.transformer_model.eval()
102
+
103
+ model_config = ConfigDict(
104
+ extra="allow",
105
+ protected_namespaces=(),
106
+ )
107
+
108
+ def _embed(self, inputs: Any) -> Any:
109
+ try:
110
+ import torch
111
+ except ImportError as e:
112
+ raise ImportError(
113
+ "Unable to import torch, please install with `pip install -U torch`."
114
+ ) from e
115
+ with torch.inference_mode():
116
+ outputs = self.transformer_model(**inputs)
117
+ if self.pooling == "mean":
118
+ emb = self._mean_pooling(outputs, inputs["attention_mask"])
119
+ elif self.pooling == "cls":
120
+ emb = self._cls_pooling(outputs)
121
+ else:
122
+ raise ValueError("pooling method no supported")
123
+
124
+ if self.normalize:
125
+ emb = torch.nn.functional.normalize(emb, p=2, dim=1)
126
+ return emb
127
+
128
+ @staticmethod
129
+ def _cls_pooling(outputs: Any) -> Any:
130
+ if isinstance(outputs, dict):
131
+ token_embeddings = outputs["last_hidden_state"]
132
+ else:
133
+ token_embeddings = outputs[0]
134
+ return token_embeddings[:, 0]
135
+
136
+ @staticmethod
137
+ def _mean_pooling(outputs: Any, attention_mask: Any) -> Any:
138
+ try:
139
+ import torch
140
+ except ImportError as e:
141
+ raise ImportError(
142
+ "Unable to import torch, please install with `pip install -U torch`."
143
+ ) from e
144
+ if isinstance(outputs, dict):
145
+ token_embeddings = outputs["last_hidden_state"]
146
+ else:
147
+ # First element of model_output contains all token embeddings
148
+ token_embeddings = outputs[0]
149
+ input_mask_expanded = (
150
+ attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
151
+ )
152
+ sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)
153
+ sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
154
+ return sum_embeddings / sum_mask
155
+
156
+ def _embed_text(self, texts: List[str]) -> List[List[float]]:
157
+ inputs = self.transformer_tokenizer(
158
+ texts,
159
+ max_length=self.max_seq_len,
160
+ truncation=True,
161
+ padding=self.padding,
162
+ return_tensors="pt",
163
+ )
164
+ return self._embed(inputs).tolist()
165
+
166
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
167
+ """Embed a list of text documents using the Optimized Embedder model.
168
+
169
+ Input:
170
+ texts: List[str] = List of text documents to embed.
171
+ Output:
172
+ List[List[float]] = The embeddings of each text document.
173
+ """
174
+ try:
175
+ import pandas as pd
176
+ except ImportError as e:
177
+ raise ImportError(
178
+ "Unable to import pandas, please install with `pip install -U pandas`."
179
+ ) from e
180
+ try:
181
+ from tqdm import tqdm
182
+ except ImportError as e:
183
+ raise ImportError(
184
+ "Unable to import tqdm, please install with `pip install -U tqdm`."
185
+ ) from e
186
+ docs = [
187
+ self.document_instruction + d if self.document_instruction else d
188
+ for d in texts
189
+ ]
190
+
191
+ # group into batches
192
+ text_list_df = pd.DataFrame(docs, columns=["texts"]).reset_index()
193
+
194
+ # assign each example with its batch
195
+ text_list_df["batch_index"] = text_list_df["index"] // self.batch_size
196
+
197
+ # create groups
198
+ batches = list(text_list_df.groupby(["batch_index"])["texts"].apply(list))
199
+
200
+ vectors = []
201
+ for batch in tqdm(batches, desc="Batches"):
202
+ vectors += self._embed_text(batch)
203
+ return vectors
204
+
205
+ def embed_query(self, text: str) -> List[float]:
206
+ if self.query_instruction:
207
+ text = self.query_instruction + text
208
+ return self._embed_text([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/oracleai.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors:
2
+ # Harichandan Roy (hroy)
3
+ # David Jiang (ddjiang)
4
+ #
5
+ # -----------------------------------------------------------------------------
6
+ # oracleai.py
7
+ # -----------------------------------------------------------------------------
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ import traceback
14
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional
15
+
16
+ from langchain_core.embeddings import Embeddings
17
+ from pydantic import BaseModel, ConfigDict
18
+
19
+ if TYPE_CHECKING:
20
+ from oracledb import Connection
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ """OracleEmbeddings class"""
25
+
26
+
27
+ class OracleEmbeddings(BaseModel, Embeddings):
28
+ """Get Embeddings"""
29
+
30
+ """Oracle Connection"""
31
+ conn: Any = None
32
+ """Embedding Parameters"""
33
+ params: Dict[str, Any]
34
+ """Proxy"""
35
+ proxy: Optional[str] = None
36
+
37
+ def __init__(self, **kwargs: Any):
38
+ super().__init__(**kwargs)
39
+
40
+ model_config = ConfigDict(
41
+ extra="forbid",
42
+ )
43
+
44
+ """
45
+ 1 - user needs to have create procedure,
46
+ create mining model, create any directory privilege.
47
+ 2 - grant create procedure, create mining model,
48
+ create any directory to <user>;
49
+ """
50
+
51
+ @staticmethod
52
+ def load_onnx_model(
53
+ conn: Connection, dir: str, onnx_file: str, model_name: str
54
+ ) -> None:
55
+ """Load an ONNX model to Oracle Database.
56
+ Args:
57
+ conn: Oracle Connection,
58
+ dir: Oracle Directory,
59
+ onnx_file: ONNX file name,
60
+ model_name: Name of the model.
61
+ """
62
+
63
+ try:
64
+ if conn is None or dir is None or onnx_file is None or model_name is None:
65
+ raise Exception("Invalid input")
66
+
67
+ cursor = conn.cursor()
68
+ cursor.execute(
69
+ """
70
+ begin
71
+ dbms_data_mining.drop_model(model_name => :model, force => true);
72
+ SYS.DBMS_VECTOR.load_onnx_model(:path, :filename, :model,
73
+ json('{"function" : "embedding",
74
+ "embeddingOutput" : "embedding",
75
+ "input": {"input": ["DATA"]}}'));
76
+ end;""",
77
+ path=dir,
78
+ filename=onnx_file,
79
+ model=model_name,
80
+ )
81
+
82
+ cursor.close()
83
+
84
+ except Exception as ex:
85
+ logger.info(f"An exception occurred :: {ex}")
86
+ traceback.print_exc()
87
+ cursor.close()
88
+ raise
89
+
90
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
91
+ """Compute doc embeddings using an OracleEmbeddings.
92
+ Args:
93
+ texts: The list of texts to embed.
94
+ Returns:
95
+ List of embeddings, one for each input text.
96
+ """
97
+
98
+ try:
99
+ import oracledb
100
+ except ImportError as e:
101
+ raise ImportError(
102
+ "Unable to import oracledb, please install with "
103
+ "`pip install -U oracledb`."
104
+ ) from e
105
+
106
+ if texts is None:
107
+ return None
108
+
109
+ embeddings: List[List[float]] = []
110
+ try:
111
+ # returns strings or bytes instead of a locator
112
+ oracledb.defaults.fetch_lobs = False
113
+ cursor = self.conn.cursor()
114
+
115
+ if self.proxy:
116
+ cursor.execute(
117
+ "begin utl_http.set_proxy(:proxy); end;", proxy=self.proxy
118
+ )
119
+
120
+ chunks = []
121
+ for i, text in enumerate(texts, start=1):
122
+ chunk = {"chunk_id": i, "chunk_data": text}
123
+ chunks.append(json.dumps(chunk))
124
+
125
+ vector_array_type = self.conn.gettype("SYS.VECTOR_ARRAY_T")
126
+ inputs = vector_array_type.newobject(chunks)
127
+ cursor.execute(
128
+ "select t.* "
129
+ + "from dbms_vector_chain.utl_to_embeddings(:content, "
130
+ + "json(:params)) t",
131
+ content=inputs,
132
+ params=json.dumps(self.params),
133
+ )
134
+
135
+ for row in cursor:
136
+ if row is None:
137
+ embeddings.append([])
138
+ else:
139
+ rdata = json.loads(row[0])
140
+ # dereference string as array
141
+ vec = json.loads(rdata["embed_vector"])
142
+ embeddings.append(vec)
143
+
144
+ cursor.close()
145
+ return embeddings
146
+ except Exception as ex:
147
+ logger.info(f"An exception occurred :: {ex}")
148
+ traceback.print_exc()
149
+ cursor.close()
150
+ raise
151
+
152
+ def embed_query(self, text: str) -> List[float]:
153
+ """Compute query embedding using an OracleEmbeddings.
154
+ Args:
155
+ text: The text to embed.
156
+ Returns:
157
+ Embedding for the text.
158
+ """
159
+ return self.embed_documents([text])[0]
160
+
161
+
162
+ # uncomment the following code block to run the test
163
+
164
+ """
165
+ # A sample unit test.
166
+
167
+ import oracledb
168
+ # get the Oracle connection
169
+ conn = oracledb.connect(
170
+ user="<user>",
171
+ password="<password>",
172
+ dsn="<hostname>/<service_name>",
173
+ )
174
+ print("Oracle connection is established...")
175
+
176
+ # params
177
+ embedder_params = {"provider": "database", "model": "demo_model"}
178
+ proxy = ""
179
+
180
+ # instance
181
+ embedder = OracleEmbeddings(conn=conn, params=embedder_params, proxy=proxy)
182
+
183
+ docs = ["hello world!", "hi everyone!", "greetings!"]
184
+ embeds = embedder.embed_documents(docs)
185
+ print(f"Total Embeddings: {len(embeds)}")
186
+ print(f"Embedding generated by OracleEmbeddings: {embeds[0]}\n")
187
+
188
+ embed = embedder.embed_query("Hello World!")
189
+ print(f"Embedding generated by OracleEmbeddings: {embed}")
190
+
191
+ conn.close()
192
+ print("Connection is closed.")
193
+
194
+ """
python/user_packages/Python313/site-packages/langchain_community/embeddings/ovhcloud.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import time
4
+ from typing import Any, List
5
+
6
+ import requests
7
+ from langchain_core.embeddings import Embeddings
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class OVHCloudEmbeddings(BaseModel, Embeddings):
14
+ """
15
+ OVHcloud AI Endpoints Embeddings.
16
+ """
17
+
18
+ """ OVHcloud AI Endpoints Access Token"""
19
+ access_token: str = ""
20
+
21
+ """ OVHcloud AI Endpoints model name for embeddings generation"""
22
+ model_name: str = ""
23
+
24
+ """ OVHcloud AI Endpoints region"""
25
+ region: str = "kepler"
26
+
27
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
28
+
29
+ def __init__(self, **kwargs: Any):
30
+ super().__init__(**kwargs)
31
+ if self.access_token == "":
32
+ raise ValueError("Access token is required for OVHCloud embeddings.")
33
+ if self.model_name == "":
34
+ raise ValueError("Model name is required for OVHCloud embeddings.")
35
+ if self.region == "":
36
+ raise ValueError("Region is required for OVHCloud embeddings.")
37
+
38
+ def _generate_embedding(self, text: str) -> List[float]:
39
+ """Generate embeddings from OVHCLOUD AIE.
40
+ Args:
41
+ text (str): The text to embed.
42
+ Returns:
43
+ List[float]: Embeddings for the text.
44
+ """
45
+
46
+ return self._send_request_to_ai_endpoints("text/plain", text, "text2vec")
47
+
48
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
49
+ """Embed a list of documents.
50
+ Args:
51
+ texts (List[str]): The list of texts to embed.
52
+
53
+ Returns:
54
+ List[List[float]]: List of embeddings, one for each input text.
55
+
56
+ """
57
+
58
+ return self._send_request_to_ai_endpoints(
59
+ "application/json", json.dumps(texts), "batch_text2vec"
60
+ )
61
+
62
+ def embed_query(self, text: str) -> List[float]:
63
+ """Embed a single query text.
64
+ Args:
65
+ text (str): The text to embed.
66
+ Returns:
67
+ List[float]: Embeddings for the text.
68
+ """
69
+ return self._generate_embedding(text)
70
+
71
+ def _send_request_to_ai_endpoints(
72
+ self, contentType: str, payload: str, route: str
73
+ ) -> Any:
74
+ """Send a HTTPS request to OVHcloud AI Endpoints
75
+ Args:
76
+ contentType (str): The content type of the request, application/json or text/plain.
77
+ payload (str): The payload of the request.
78
+ route (str): The route of the request, batch_text2vec or text2vec.
79
+ """ # noqa: E501
80
+ headers = {
81
+ "content-type": contentType,
82
+ "Authorization": f"Bearer {self.access_token}",
83
+ }
84
+
85
+ session = requests.session()
86
+ while True:
87
+ response = session.post(
88
+ (
89
+ f"https://{self.model_name}.endpoints.{self.region}"
90
+ f".ai.cloud.ovh.net/api/{route}"
91
+ ),
92
+ headers=headers,
93
+ data=payload,
94
+ )
95
+ if response.status_code != 200:
96
+ if response.status_code == 429:
97
+ """Rate limit exceeded, wait for reset"""
98
+ reset_time = int(response.headers.get("RateLimit-Reset", 0))
99
+ logger.info("Rate limit exceeded. Waiting %d seconds.", reset_time)
100
+ if reset_time > 0:
101
+ time.sleep(reset_time)
102
+ continue
103
+ else:
104
+ """Rate limit reset time has passed, retry immediately"""
105
+ continue
106
+ if response.status_code == 401:
107
+ """ Unauthorized, retry with new token """
108
+ raise ValueError("Unauthorized, retry with new token")
109
+ """ Handle other non-200 status codes """
110
+ raise ValueError(
111
+ "Request failed with status code: {status_code}, {text}".format(
112
+ status_code=response.status_code, text=response.text
113
+ )
114
+ )
115
+ return response.json()
python/user_packages/Python313/site-packages/langchain_community/embeddings/premai.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Callable, Dict, List, Optional, Union
5
+
6
+ from langchain_core.embeddings import Embeddings
7
+ from langchain_core.language_models.llms import create_base_retry_decorator
8
+ from langchain_core.utils import get_from_dict_or_env, pre_init
9
+ from pydantic import BaseModel, SecretStr
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class PremAIEmbeddings(BaseModel, Embeddings):
15
+ """Prem's Embedding APIs"""
16
+
17
+ project_id: int
18
+ """The project ID in which the experiments or deployments are carried out.
19
+ You can find all your projects here: https://app.premai.io/projects/"""
20
+
21
+ premai_api_key: Optional[SecretStr] = None
22
+ """Prem AI API Key. Get it here: https://app.premai.io/api_keys/"""
23
+
24
+ model: str
25
+ """The Embedding model to choose from"""
26
+
27
+ show_progress_bar: bool = False
28
+ """Whether to show a tqdm progress bar. Must have `tqdm` installed."""
29
+
30
+ max_retries: int = 1
31
+ """Max number of retries for tenacity"""
32
+
33
+ client: Any
34
+
35
+ @pre_init
36
+ def validate_environments(cls, values: Dict) -> Dict:
37
+ """Validate that the package is installed and that the API token is valid"""
38
+ try:
39
+ from premai import Prem
40
+ except ImportError as error:
41
+ raise ImportError(
42
+ "Could not import Prem Python package."
43
+ "Please install it with: `pip install premai`"
44
+ ) from error
45
+
46
+ try:
47
+ premai_api_key = get_from_dict_or_env(
48
+ values, "premai_api_key", "PREMAI_API_KEY"
49
+ )
50
+ values["client"] = Prem(api_key=premai_api_key)
51
+ except Exception as error:
52
+ raise ValueError("Your API Key is incorrect. Please try again.") from error
53
+ return values
54
+
55
+ def embed_query(self, text: str) -> List[float]:
56
+ """Embed query text"""
57
+ embeddings = embed_with_retry(
58
+ self, model=self.model, project_id=self.project_id, input=text
59
+ )
60
+ return embeddings.data[0].embedding
61
+
62
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
63
+ embeddings = embed_with_retry(
64
+ self, model=self.model, project_id=self.project_id, input=texts
65
+ ).data
66
+
67
+ return [embedding.embedding for embedding in embeddings]
68
+
69
+
70
+ def create_prem_retry_decorator(
71
+ embedder: PremAIEmbeddings,
72
+ *,
73
+ max_retries: int = 1,
74
+ ) -> Callable[[Any], Any]:
75
+ """Create a retry decorator for PremAIEmbeddings.
76
+
77
+ Args:
78
+ embedder (PremAIEmbeddings): The PremAIEmbeddings instance
79
+ max_retries (int): The maximum number of retries
80
+
81
+ Returns:
82
+ Callable[[Any], Any]: The retry decorator
83
+ """
84
+ import premai.models
85
+
86
+ errors = [
87
+ premai.models.api_response_validation_error.APIResponseValidationError,
88
+ premai.models.conflict_error.ConflictError,
89
+ premai.models.model_not_found_error.ModelNotFoundError,
90
+ premai.models.permission_denied_error.PermissionDeniedError,
91
+ premai.models.provider_api_connection_error.ProviderAPIConnectionError,
92
+ premai.models.provider_api_status_error.ProviderAPIStatusError,
93
+ premai.models.provider_api_timeout_error.ProviderAPITimeoutError,
94
+ premai.models.provider_internal_server_error.ProviderInternalServerError,
95
+ premai.models.provider_not_found_error.ProviderNotFoundError,
96
+ premai.models.rate_limit_error.RateLimitError,
97
+ premai.models.unprocessable_entity_error.UnprocessableEntityError,
98
+ premai.models.validation_error.ValidationError,
99
+ ]
100
+
101
+ decorator = create_base_retry_decorator(
102
+ error_types=errors, max_retries=max_retries, run_manager=None
103
+ )
104
+ return decorator
105
+
106
+
107
+ def embed_with_retry(
108
+ embedder: PremAIEmbeddings,
109
+ model: str,
110
+ project_id: int,
111
+ input: Union[str, List[str]],
112
+ ) -> Any:
113
+ """Using tenacity for retry in embedding calls"""
114
+ retry_decorator = create_prem_retry_decorator(
115
+ embedder, max_retries=embedder.max_retries
116
+ )
117
+
118
+ @retry_decorator
119
+ def _embed_with_retry(
120
+ embedder: PremAIEmbeddings,
121
+ project_id: int,
122
+ model: str,
123
+ input: Union[str, List[str]],
124
+ ) -> Any:
125
+ embedding_response = embedder.client.embeddings.create(
126
+ project_id=project_id, model=model, input=input
127
+ )
128
+ return embedding_response
129
+
130
+ return _embed_with_retry(embedder, project_id=project_id, model=model, input=input)
python/user_packages/Python313/site-packages/langchain_community/embeddings/sagemaker_endpoint.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from langchain_core.utils import pre_init
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+ from langchain_community.llms.sagemaker_endpoint import ContentHandlerBase
8
+
9
+
10
+ class EmbeddingsContentHandler(ContentHandlerBase[List[str], List[List[float]]]):
11
+ """Content handler for LLM class."""
12
+
13
+
14
+ class SagemakerEndpointEmbeddings(BaseModel, Embeddings):
15
+ """Custom Sagemaker Inference Endpoints.
16
+
17
+ To use, you must supply the endpoint name from your deployed
18
+ Sagemaker model & the region where it is deployed.
19
+
20
+ To authenticate, the AWS client uses the following methods to
21
+ automatically load credentials:
22
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
23
+
24
+ If a specific credential profile should be used, you must pass
25
+ the name of the profile from the ~/.aws/credentials file that is to be used.
26
+
27
+ Make sure the credentials / roles used have the required policies to
28
+ access the Sagemaker endpoint.
29
+ See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html
30
+ """
31
+
32
+ """
33
+ Example:
34
+ .. code-block:: python
35
+
36
+ from langchain_community.embeddings import SagemakerEndpointEmbeddings
37
+ endpoint_name = (
38
+ "my-endpoint-name"
39
+ )
40
+ region_name = (
41
+ "us-west-2"
42
+ )
43
+ credentials_profile_name = (
44
+ "default"
45
+ )
46
+ se = SagemakerEndpointEmbeddings(
47
+ endpoint_name=endpoint_name,
48
+ region_name=region_name,
49
+ credentials_profile_name=credentials_profile_name
50
+ )
51
+
52
+ #Use with boto3 client
53
+ client = boto3.client(
54
+ "sagemaker-runtime",
55
+ region_name=region_name
56
+ )
57
+ se = SagemakerEndpointEmbeddings(
58
+ endpoint_name=endpoint_name,
59
+ client=client
60
+ )
61
+ """
62
+ client: Any = None
63
+
64
+ endpoint_name: str = ""
65
+ """The name of the endpoint from the deployed Sagemaker model.
66
+ Must be unique within an AWS Region."""
67
+
68
+ region_name: str = ""
69
+ """The aws region where the Sagemaker model is deployed, eg. `us-west-2`."""
70
+
71
+ credentials_profile_name: Optional[str] = None
72
+ """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
73
+ has either access keys or role information specified.
74
+ If not specified, the default credential profile or, if on an EC2 instance,
75
+ credentials from IMDS will be used.
76
+ See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
77
+ """
78
+
79
+ content_handler: EmbeddingsContentHandler
80
+ """The content handler class that provides an input and
81
+ output transform functions to handle formats between LLM
82
+ and the endpoint.
83
+ """
84
+
85
+ """
86
+ Example:
87
+ .. code-block:: python
88
+
89
+ from langchain_community.embeddings.sagemaker_endpoint import EmbeddingsContentHandler
90
+
91
+ class ContentHandler(EmbeddingsContentHandler):
92
+ content_type = "application/json"
93
+ accepts = "application/json"
94
+
95
+ def transform_input(self, prompts: List[str], model_kwargs: Dict) -> bytes:
96
+ input_str = json.dumps({prompts: prompts, **model_kwargs})
97
+ return input_str.encode('utf-8')
98
+
99
+ def transform_output(self, output: bytes) -> List[List[float]]:
100
+ response_json = json.loads(output.read().decode("utf-8"))
101
+ return response_json["vectors"]
102
+ """ # noqa: E501
103
+
104
+ model_kwargs: Optional[Dict] = None
105
+ """Keyword arguments to pass to the model."""
106
+
107
+ endpoint_kwargs: Optional[Dict] = None
108
+ """Optional attributes passed to the invoke_endpoint
109
+ function. See `boto3`_. docs for more info.
110
+ .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>
111
+ """
112
+
113
+ model_config = ConfigDict(
114
+ arbitrary_types_allowed=True, extra="forbid", protected_namespaces=()
115
+ )
116
+
117
+ @pre_init
118
+ def validate_environment(cls, values: Dict) -> Dict:
119
+ """Dont do anything if client provided externally"""
120
+ if values.get("client") is not None:
121
+ return values
122
+
123
+ """Validate that AWS credentials to and python package exists in environment."""
124
+ try:
125
+ import boto3
126
+
127
+ try:
128
+ if values["credentials_profile_name"] is not None:
129
+ session = boto3.Session(
130
+ profile_name=values["credentials_profile_name"]
131
+ )
132
+ else:
133
+ # use default credentials
134
+ session = boto3.Session()
135
+
136
+ values["client"] = session.client(
137
+ "sagemaker-runtime", region_name=values["region_name"]
138
+ )
139
+
140
+ except Exception as e:
141
+ raise ValueError(
142
+ "Could not load credentials to authenticate with AWS client. "
143
+ "Please check that credentials in the specified "
144
+ f"profile name are valid. {e}"
145
+ ) from e
146
+
147
+ except ImportError:
148
+ raise ImportError(
149
+ "Could not import boto3 python package. "
150
+ "Please install it with `pip install boto3`."
151
+ )
152
+ return values
153
+
154
+ def _embedding_func(self, texts: List[str]) -> List[List[float]]:
155
+ """Call out to SageMaker Inference embedding endpoint."""
156
+ # replace newlines, which can negatively affect performance.
157
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
158
+ _model_kwargs = self.model_kwargs or {}
159
+ _endpoint_kwargs = self.endpoint_kwargs or {}
160
+
161
+ body = self.content_handler.transform_input(texts, _model_kwargs)
162
+ content_type = self.content_handler.content_type
163
+ accepts = self.content_handler.accepts
164
+
165
+ # send request
166
+ try:
167
+ response = self.client.invoke_endpoint(
168
+ EndpointName=self.endpoint_name,
169
+ Body=body,
170
+ ContentType=content_type,
171
+ Accept=accepts,
172
+ **_endpoint_kwargs,
173
+ )
174
+ except Exception as e:
175
+ raise ValueError(f"Error raised by inference endpoint: {e}")
176
+
177
+ return self.content_handler.transform_output(response["Body"])
178
+
179
+ def embed_documents(
180
+ self, texts: List[str], chunk_size: int = 64
181
+ ) -> List[List[float]]:
182
+ """Compute doc embeddings using a SageMaker Inference Endpoint.
183
+
184
+ Args:
185
+ texts: The list of texts to embed.
186
+ chunk_size: The chunk size defines how many input texts will
187
+ be grouped together as request. If None, will use the
188
+ chunk size specified by the class.
189
+
190
+
191
+ Returns:
192
+ List of embeddings, one for each text.
193
+ """
194
+ results = []
195
+ _chunk_size = len(texts) if chunk_size > len(texts) else chunk_size
196
+ for i in range(0, len(texts), _chunk_size):
197
+ response = self._embedding_func(texts[i : i + _chunk_size])
198
+ results.extend(response)
199
+ return results
200
+
201
+ def embed_query(self, text: str) -> List[float]:
202
+ """Compute query embeddings using a SageMaker inference endpoint.
203
+
204
+ Args:
205
+ text: The text to embed.
206
+
207
+ Returns:
208
+ Embeddings for the text.
209
+ """
210
+ return self._embedding_func([text])[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/sambanova.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict, Generator, List, Optional
3
+
4
+ import requests
5
+ from langchain_core._api.deprecation import deprecated
6
+ from langchain_core.embeddings import Embeddings
7
+ from langchain_core.utils import get_from_dict_or_env, pre_init
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+
11
+ @deprecated(
12
+ since="0.3.16",
13
+ removal="1.0",
14
+ alternative_import="langchain_sambanova.SambaStudioEmbeddings",
15
+ )
16
+ class SambaStudioEmbeddings(BaseModel, Embeddings):
17
+ """SambaNova embedding models.
18
+
19
+ To use, you should have the environment variables
20
+ ``SAMBASTUDIO_EMBEDDINGS_BASE_URL``, ``SAMBASTUDIO_EMBEDDINGS_BASE_URI``
21
+ ``SAMBASTUDIO_EMBEDDINGS_PROJECT_ID``, ``SAMBASTUDIO_EMBEDDINGS_ENDPOINT_ID``,
22
+ ``SAMBASTUDIO_EMBEDDINGS_API_KEY``
23
+ set with your personal sambastudio variable or pass it as a named parameter
24
+ to the constructor.
25
+
26
+ Example:
27
+ .. code-block:: python
28
+
29
+ from langchain_community.embeddings import SambaStudioEmbeddings
30
+
31
+ embeddings = SambaStudioEmbeddings(sambastudio_embeddings_base_url=base_url,
32
+ sambastudio_embeddings_base_uri=base_uri,
33
+ sambastudio_embeddings_project_id=project_id,
34
+ sambastudio_embeddings_endpoint_id=endpoint_id,
35
+ sambastudio_embeddings_api_key=api_key,
36
+ batch_size=32)
37
+ (or)
38
+
39
+ embeddings = SambaStudioEmbeddings(batch_size=32)
40
+
41
+ (or)
42
+
43
+ # CoE example
44
+ embeddings = SambaStudioEmbeddings(
45
+ batch_size=1,
46
+ model_kwargs={
47
+ 'select_expert':'e5-mistral-7b-instruct'
48
+ }
49
+ )
50
+ """
51
+
52
+ sambastudio_embeddings_base_url: str = ""
53
+ """Base url to use"""
54
+
55
+ sambastudio_embeddings_base_uri: str = ""
56
+ """endpoint base uri"""
57
+
58
+ sambastudio_embeddings_project_id: str = ""
59
+ """Project id on sambastudio for model"""
60
+
61
+ sambastudio_embeddings_endpoint_id: str = ""
62
+ """endpoint id on sambastudio for model"""
63
+
64
+ sambastudio_embeddings_api_key: str = ""
65
+ """sambastudio api key"""
66
+
67
+ model_kwargs: dict = {}
68
+ """Key word arguments to pass to the model."""
69
+
70
+ batch_size: int = 32
71
+ """Batch size for the embedding models"""
72
+
73
+ model_config = ConfigDict(protected_namespaces=())
74
+
75
+ @pre_init
76
+ def validate_environment(cls, values: Dict) -> Dict:
77
+ """Validate that api key and python package exists in environment."""
78
+ values["sambastudio_embeddings_base_url"] = get_from_dict_or_env(
79
+ values, "sambastudio_embeddings_base_url", "SAMBASTUDIO_EMBEDDINGS_BASE_URL"
80
+ )
81
+ values["sambastudio_embeddings_base_uri"] = get_from_dict_or_env(
82
+ values,
83
+ "sambastudio_embeddings_base_uri",
84
+ "SAMBASTUDIO_EMBEDDINGS_BASE_URI",
85
+ default="api/predict/generic",
86
+ )
87
+ values["sambastudio_embeddings_project_id"] = get_from_dict_or_env(
88
+ values,
89
+ "sambastudio_embeddings_project_id",
90
+ "SAMBASTUDIO_EMBEDDINGS_PROJECT_ID",
91
+ )
92
+ values["sambastudio_embeddings_endpoint_id"] = get_from_dict_or_env(
93
+ values,
94
+ "sambastudio_embeddings_endpoint_id",
95
+ "SAMBASTUDIO_EMBEDDINGS_ENDPOINT_ID",
96
+ )
97
+ values["sambastudio_embeddings_api_key"] = get_from_dict_or_env(
98
+ values, "sambastudio_embeddings_api_key", "SAMBASTUDIO_EMBEDDINGS_API_KEY"
99
+ )
100
+ return values
101
+
102
+ def _get_tuning_params(self) -> str:
103
+ """
104
+ Get the tuning parameters to use when calling the model
105
+
106
+ Returns:
107
+ The tuning parameters as a JSON string.
108
+ """
109
+ if "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri:
110
+ tuning_params_dict = self.model_kwargs
111
+ else:
112
+ tuning_params_dict = {
113
+ k: {"type": type(v).__name__, "value": str(v)}
114
+ for k, v in (self.model_kwargs.items())
115
+ }
116
+ tuning_params = json.dumps(tuning_params_dict)
117
+ return tuning_params
118
+
119
+ def _get_full_url(self, path: str) -> str:
120
+ """
121
+ Return the full API URL for a given path.
122
+
123
+ :param str path: the sub-path
124
+ :returns: the full API URL for the sub-path
125
+ :rtype: str
126
+ """
127
+ return f"{self.sambastudio_embeddings_base_url}/{self.sambastudio_embeddings_base_uri}/{path}" # noqa: E501
128
+
129
+ def _iterate_over_batches(self, texts: List[str], batch_size: int) -> Generator:
130
+ """Generator for creating batches in the embed documents method
131
+ Args:
132
+ texts (List[str]): list of strings to embed
133
+ batch_size (int, optional): batch size to be used for the embedding model.
134
+ Will depend on the RDU endpoint used.
135
+ Yields:
136
+ List[str]: list (batch) of strings of size batch size
137
+ """
138
+ for i in range(0, len(texts), batch_size):
139
+ yield texts[i : i + batch_size]
140
+
141
+ def embed_documents(
142
+ self, texts: List[str], batch_size: Optional[int] = None
143
+ ) -> List[List[float]]:
144
+ """Returns a list of embeddings for the given sentences.
145
+ Args:
146
+ texts (`List[str]`): List of texts to encode
147
+ batch_size (`int`): Batch size for the encoding
148
+
149
+ Returns:
150
+ `List[np.ndarray]` or `List[tensor]`: List of embeddings
151
+ for the given sentences
152
+ """
153
+ if batch_size is None:
154
+ batch_size = self.batch_size
155
+ http_session = requests.Session()
156
+ url = self._get_full_url(
157
+ f"{self.sambastudio_embeddings_project_id}/{self.sambastudio_embeddings_endpoint_id}"
158
+ )
159
+ params = json.loads(self._get_tuning_params())
160
+ embeddings = []
161
+
162
+ if "api/predict/nlp" in self.sambastudio_embeddings_base_uri:
163
+ for batch in self._iterate_over_batches(texts, batch_size):
164
+ data = {"inputs": batch, "params": params}
165
+ response = http_session.post(
166
+ url,
167
+ headers={"key": self.sambastudio_embeddings_api_key},
168
+ json=data,
169
+ )
170
+ if response.status_code != 200:
171
+ raise RuntimeError(
172
+ f"Sambanova /complete call failed with status code "
173
+ f"{response.status_code}.\n Details: {response.text}"
174
+ )
175
+ try:
176
+ embedding = response.json()["data"]
177
+ embeddings.extend(embedding)
178
+ except KeyError:
179
+ raise KeyError(
180
+ "'data' not found in endpoint response",
181
+ response.json(),
182
+ )
183
+
184
+ elif "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri:
185
+ for batch in self._iterate_over_batches(texts, batch_size):
186
+ items = [
187
+ {"id": f"item{i}", "value": item} for i, item in enumerate(batch)
188
+ ]
189
+ data = {"items": items, "params": params}
190
+ response = http_session.post(
191
+ url,
192
+ headers={"key": self.sambastudio_embeddings_api_key},
193
+ json=data,
194
+ )
195
+ if response.status_code != 200:
196
+ raise RuntimeError(
197
+ f"Sambanova /complete call failed with status code "
198
+ f"{response.status_code}.\n Details: {response.text}"
199
+ )
200
+ try:
201
+ embedding = [item["value"] for item in response.json()["items"]]
202
+ embeddings.extend(embedding)
203
+ except KeyError:
204
+ raise KeyError(
205
+ "'items' not found in endpoint response",
206
+ response.json(),
207
+ )
208
+
209
+ elif "api/predict/generic" in self.sambastudio_embeddings_base_uri:
210
+ for batch in self._iterate_over_batches(texts, batch_size):
211
+ data = {"instances": batch, "params": params}
212
+ response = http_session.post(
213
+ url,
214
+ headers={"key": self.sambastudio_embeddings_api_key},
215
+ json=data,
216
+ )
217
+ if response.status_code != 200:
218
+ raise RuntimeError(
219
+ f"Sambanova /complete call failed with status code "
220
+ f"{response.status_code}.\n Details: {response.text}"
221
+ )
222
+ try:
223
+ if params.get("select_expert"):
224
+ embedding = response.json()["predictions"]
225
+ else:
226
+ embedding = response.json()["predictions"]
227
+ embeddings.extend(embedding)
228
+ except KeyError:
229
+ raise KeyError(
230
+ "'predictions' not found in endpoint response",
231
+ response.json(),
232
+ )
233
+
234
+ else:
235
+ raise ValueError(
236
+ f"handling of endpoint uri: {self.sambastudio_embeddings_base_uri} not implemented" # noqa: E501
237
+ )
238
+
239
+ return embeddings
240
+
241
+ def embed_query(self, text: str) -> List[float]:
242
+ """Returns a list of embeddings for the given sentences.
243
+ Args:
244
+ sentences (`List[str]`): List of sentences to encode
245
+
246
+ Returns:
247
+ `List[np.ndarray]` or `List[tensor]`: List of embeddings
248
+ for the given sentences
249
+ """
250
+ http_session = requests.Session()
251
+ url = self._get_full_url(
252
+ f"{self.sambastudio_embeddings_project_id}/{self.sambastudio_embeddings_endpoint_id}"
253
+ )
254
+ params = json.loads(self._get_tuning_params())
255
+
256
+ if "api/predict/nlp" in self.sambastudio_embeddings_base_uri:
257
+ data = {"inputs": [text], "params": params}
258
+ response = http_session.post(
259
+ url,
260
+ headers={"key": self.sambastudio_embeddings_api_key},
261
+ json=data,
262
+ )
263
+ if response.status_code != 200:
264
+ raise RuntimeError(
265
+ f"Sambanova /complete call failed with status code "
266
+ f"{response.status_code}.\n Details: {response.text}"
267
+ )
268
+ try:
269
+ embedding = response.json()["data"][0]
270
+ except KeyError:
271
+ raise KeyError(
272
+ "'data' not found in endpoint response",
273
+ response.json(),
274
+ )
275
+
276
+ elif "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri:
277
+ data = {"items": [{"id": "item0", "value": text}], "params": params}
278
+ response = http_session.post(
279
+ url,
280
+ headers={"key": self.sambastudio_embeddings_api_key},
281
+ json=data,
282
+ )
283
+ if response.status_code != 200:
284
+ raise RuntimeError(
285
+ f"Sambanova /complete call failed with status code "
286
+ f"{response.status_code}.\n Details: {response.text}"
287
+ )
288
+ try:
289
+ embedding = response.json()["items"][0]["value"]
290
+ except KeyError:
291
+ raise KeyError(
292
+ "'items' not found in endpoint response",
293
+ response.json(),
294
+ )
295
+
296
+ elif "api/predict/generic" in self.sambastudio_embeddings_base_uri:
297
+ data = {"instances": [text], "params": params}
298
+ response = http_session.post(
299
+ url,
300
+ headers={"key": self.sambastudio_embeddings_api_key},
301
+ json=data,
302
+ )
303
+ if response.status_code != 200:
304
+ raise RuntimeError(
305
+ f"Sambanova /complete call failed with status code "
306
+ f"{response.status_code}.\n Details: {response.text}"
307
+ )
308
+ try:
309
+ if params.get("select_expert"):
310
+ embedding = response.json()["predictions"][0]
311
+ else:
312
+ embedding = response.json()["predictions"][0]
313
+ except KeyError:
314
+ raise KeyError(
315
+ "'predictions' not found in endpoint response",
316
+ response.json(),
317
+ )
318
+
319
+ else:
320
+ raise ValueError(
321
+ f"handling of endpoint uri: {self.sambastudio_embeddings_base_uri} not implemented" # noqa: E501
322
+ )
323
+
324
+ return embedding
python/user_packages/Python313/site-packages/langchain_community/embeddings/self_hosted.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, List
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from pydantic import ConfigDict
5
+
6
+ from langchain_community.llms.self_hosted import SelfHostedPipeline
7
+
8
+
9
+ def _embed_documents(pipeline: Any, *args: Any, **kwargs: Any) -> List[List[float]]:
10
+ """Inference function to send to the remote hardware.
11
+
12
+ Accepts a sentence_transformer model_id and
13
+ returns a list of embeddings for each document in the batch.
14
+ """
15
+ return pipeline(*args, **kwargs)
16
+
17
+
18
+ class SelfHostedEmbeddings(SelfHostedPipeline, Embeddings):
19
+ """Custom embedding models on self-hosted remote hardware.
20
+
21
+ Supported hardware includes auto-launched instances on AWS, GCP, Azure,
22
+ and Lambda, as well as servers specified
23
+ by IP address and SSH credentials (such as on-prem, or another
24
+ cloud like Paperspace, Coreweave, etc.).
25
+
26
+ To use, you should have the ``runhouse`` python package installed.
27
+
28
+ Example using a model load function:
29
+ .. code-block:: python
30
+
31
+ from langchain_community.embeddings import SelfHostedEmbeddings
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
33
+ import runhouse as rh
34
+
35
+ gpu = rh.cluster(name="rh-a10x", instance_type="A100:1")
36
+ def get_pipeline():
37
+ model_id = "facebook/bart-large"
38
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
39
+ model = AutoModelForCausalLM.from_pretrained(model_id)
40
+ return pipeline("feature-extraction", model=model, tokenizer=tokenizer)
41
+ embeddings = SelfHostedEmbeddings(
42
+ model_load_fn=get_pipeline,
43
+ hardware=gpu
44
+ model_reqs=["./", "torch", "transformers"],
45
+ )
46
+ Example passing in a pipeline path:
47
+ .. code-block:: python
48
+
49
+ from langchain_community.embeddings import SelfHostedHFEmbeddings
50
+ import runhouse as rh
51
+ from transformers import pipeline
52
+
53
+ gpu = rh.cluster(name="rh-a10x", instance_type="A100:1")
54
+ pipeline = pipeline(model="bert-base-uncased", task="feature-extraction")
55
+ rh.blob(pickle.dumps(pipeline),
56
+ path="models/pipeline.pkl").save().to(gpu, path="models")
57
+ embeddings = SelfHostedHFEmbeddings.from_pipeline(
58
+ pipeline="models/pipeline.pkl",
59
+ hardware=gpu,
60
+ model_reqs=["./", "torch", "transformers"],
61
+ )
62
+ """
63
+
64
+ inference_fn: Callable = _embed_documents
65
+ """Inference function to extract the embeddings on the remote hardware."""
66
+ inference_kwargs: Any = None
67
+ """Any kwargs to pass to the model's inference function."""
68
+
69
+ model_config = ConfigDict(
70
+ extra="forbid",
71
+ )
72
+
73
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
74
+ """Compute doc embeddings using a HuggingFace transformer model.
75
+
76
+ Args:
77
+ texts: The list of texts to embed.s
78
+
79
+ Returns:
80
+ List of embeddings, one for each text.
81
+ """
82
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
83
+ embeddings = self.client(self.pipeline_ref, texts)
84
+ if not isinstance(embeddings, list):
85
+ return embeddings.tolist()
86
+ return embeddings
87
+
88
+ def embed_query(self, text: str) -> List[float]:
89
+ """Compute query embeddings using a HuggingFace transformer model.
90
+
91
+ Args:
92
+ text: The text to embed.
93
+
94
+ Returns:
95
+ Embeddings for the text.
96
+ """
97
+ text = text.replace("\n", " ")
98
+ embeddings = self.client(self.pipeline_ref, text)
99
+ if not isinstance(embeddings, list):
100
+ return embeddings.tolist()
101
+ return embeddings
python/user_packages/Python313/site-packages/langchain_community/embeddings/self_hosted_hugging_face.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import logging
3
+ from typing import Any, Callable, List, Optional
4
+
5
+ from langchain_community.embeddings.self_hosted import SelfHostedEmbeddings
6
+
7
+ DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
8
+ DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-large"
9
+ DEFAULT_EMBED_INSTRUCTION = "Represent the document for retrieval: "
10
+ DEFAULT_QUERY_INSTRUCTION = (
11
+ "Represent the question for retrieving supporting documents: "
12
+ )
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _embed_documents(client: Any, *args: Any, **kwargs: Any) -> List[List[float]]:
18
+ """Inference function to send to the remote hardware.
19
+
20
+ Accepts a sentence_transformer model_id and
21
+ returns a list of embeddings for each document in the batch.
22
+ """
23
+ return client.encode(*args, **kwargs)
24
+
25
+
26
+ def load_embedding_model(model_id: str, instruct: bool = False, device: int = 0) -> Any:
27
+ """Load the embedding model."""
28
+ if not instruct:
29
+ import sentence_transformers
30
+
31
+ client = sentence_transformers.SentenceTransformer(model_id)
32
+ else:
33
+ from InstructorEmbedding import INSTRUCTOR
34
+
35
+ client = INSTRUCTOR(model_id)
36
+
37
+ if importlib.util.find_spec("torch") is not None:
38
+ import torch
39
+
40
+ cuda_device_count = torch.cuda.device_count()
41
+ if device < -1 or (device >= cuda_device_count):
42
+ raise ValueError(
43
+ f"Got device=={device}, "
44
+ f"device is required to be within [-1, {cuda_device_count})"
45
+ )
46
+ if device < 0 and cuda_device_count > 0:
47
+ logger.warning(
48
+ "Device has %d GPUs available. "
49
+ "Provide device={deviceId} to `from_model_id` to use available"
50
+ "GPUs for execution. deviceId is -1 for CPU and "
51
+ "can be a positive integer associated with CUDA device id.",
52
+ cuda_device_count,
53
+ )
54
+
55
+ client = client.to(device)
56
+ return client
57
+
58
+
59
+ class SelfHostedHuggingFaceEmbeddings(SelfHostedEmbeddings):
60
+ """HuggingFace embedding models on self-hosted remote hardware.
61
+
62
+ Supported hardware includes auto-launched instances on AWS, GCP, Azure,
63
+ and Lambda, as well as servers specified
64
+ by IP address and SSH credentials (such as on-prem, or another cloud
65
+ like Paperspace, Coreweave, etc.).
66
+
67
+ To use, you should have the ``runhouse`` python package installed.
68
+
69
+ Example:
70
+ .. code-block:: python
71
+
72
+ from langchain_community.embeddings import SelfHostedHuggingFaceEmbeddings
73
+ import runhouse as rh
74
+ model_id = "sentence-transformers/all-mpnet-base-v2"
75
+ gpu = rh.cluster(name="rh-a10x", instance_type="A100:1")
76
+ hf = SelfHostedHuggingFaceEmbeddings(model_id=model_id, hardware=gpu)
77
+ """
78
+
79
+ client: Any #: :meta private:
80
+ model_id: str = DEFAULT_MODEL_NAME
81
+ """Model name to use."""
82
+ model_reqs: List[str] = ["./", "sentence_transformers", "torch"]
83
+ """Requirements to install on hardware to inference the model."""
84
+ hardware: Any
85
+ """Remote hardware to send the inference function to."""
86
+ model_load_fn: Callable = load_embedding_model
87
+ """Function to load the model remotely on the server."""
88
+ load_fn_kwargs: Optional[dict] = None
89
+ """Keyword arguments to pass to the model load function."""
90
+ inference_fn: Callable = _embed_documents
91
+ """Inference function to extract the embeddings."""
92
+
93
+ def __init__(self, **kwargs: Any):
94
+ """Initialize the remote inference function."""
95
+ load_fn_kwargs = kwargs.pop("load_fn_kwargs", {})
96
+ load_fn_kwargs["model_id"] = load_fn_kwargs.get("model_id", DEFAULT_MODEL_NAME)
97
+ load_fn_kwargs["instruct"] = load_fn_kwargs.get("instruct", False)
98
+ load_fn_kwargs["device"] = load_fn_kwargs.get("device", 0)
99
+ super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)
100
+
101
+
102
+ class SelfHostedHuggingFaceInstructEmbeddings(SelfHostedHuggingFaceEmbeddings):
103
+ """HuggingFace InstructEmbedding models on self-hosted remote hardware.
104
+
105
+ Supported hardware includes auto-launched instances on AWS, GCP, Azure,
106
+ and Lambda, as well as servers specified
107
+ by IP address and SSH credentials (such as on-prem, or another
108
+ cloud like Paperspace, Coreweave, etc.).
109
+
110
+ To use, you should have the ``runhouse`` python package installed.
111
+
112
+ Example:
113
+ .. code-block:: python
114
+
115
+ from langchain_community.embeddings import SelfHostedHuggingFaceInstructEmbeddings
116
+ import runhouse as rh
117
+ model_name = "hkunlp/instructor-large"
118
+ gpu = rh.cluster(name='rh-a10x', instance_type='A100:1')
119
+ hf = SelfHostedHuggingFaceInstructEmbeddings(
120
+ model_name=model_name, hardware=gpu)
121
+ """ # noqa: E501
122
+
123
+ model_id: str = DEFAULT_INSTRUCT_MODEL
124
+ """Model name to use."""
125
+ embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
126
+ """Instruction to use for embedding documents."""
127
+ query_instruction: str = DEFAULT_QUERY_INSTRUCTION
128
+ """Instruction to use for embedding query."""
129
+ model_reqs: List[str] = ["./", "InstructorEmbedding", "torch"]
130
+ """Requirements to install on hardware to inference the model."""
131
+
132
+ def __init__(self, **kwargs: Any):
133
+ """Initialize the remote inference function."""
134
+ load_fn_kwargs = kwargs.pop("load_fn_kwargs", {})
135
+ load_fn_kwargs["model_id"] = load_fn_kwargs.get(
136
+ "model_id", DEFAULT_INSTRUCT_MODEL
137
+ )
138
+ load_fn_kwargs["instruct"] = load_fn_kwargs.get("instruct", True)
139
+ load_fn_kwargs["device"] = load_fn_kwargs.get("device", 0)
140
+ super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)
141
+
142
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
143
+ """Compute doc embeddings using a HuggingFace instruct model.
144
+
145
+ Args:
146
+ texts: The list of texts to embed.
147
+
148
+ Returns:
149
+ List of embeddings, one for each text.
150
+ """
151
+ instruction_pairs = []
152
+ for text in texts:
153
+ instruction_pairs.append([self.embed_instruction, text])
154
+ embeddings = self.client(self.pipeline_ref, instruction_pairs)
155
+ return embeddings.tolist()
156
+
157
+ def embed_query(self, text: str) -> List[float]:
158
+ """Compute query embeddings using a HuggingFace instruct model.
159
+
160
+ Args:
161
+ text: The text to embed.
162
+
163
+ Returns:
164
+ Embeddings for the text.
165
+ """
166
+ instruction_pair = [self.query_instruction, text]
167
+ embedding = self.client(self.pipeline_ref, [instruction_pair])[0]
168
+ return embedding.tolist()
python/user_packages/Python313/site-packages/langchain_community/embeddings/sentence_transformer.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """HuggingFace sentence_transformer embedding models."""
2
+
3
+ from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings
4
+
5
+ SentenceTransformerEmbeddings = HuggingFaceEmbeddings
python/user_packages/Python313/site-packages/langchain_community/embeddings/solar.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Callable, Dict, List, Optional
5
+
6
+ import requests
7
+ from langchain_core._api import deprecated
8
+ from langchain_core.embeddings import Embeddings
9
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
10
+ from pydantic import BaseModel, ConfigDict, SecretStr
11
+ from tenacity import (
12
+ before_sleep_log,
13
+ retry,
14
+ stop_after_attempt,
15
+ wait_exponential,
16
+ )
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _create_retry_decorator() -> Callable[[Any], Any]:
22
+ """Returns a tenacity retry decorator."""
23
+
24
+ multiplier = 1
25
+ min_seconds = 1
26
+ max_seconds = 4
27
+ max_retries = 6
28
+
29
+ return retry(
30
+ reraise=True,
31
+ stop=stop_after_attempt(max_retries),
32
+ wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),
33
+ before_sleep=before_sleep_log(logger, logging.WARNING),
34
+ )
35
+
36
+
37
+ def embed_with_retry(embeddings: SolarEmbeddings, *args: Any, **kwargs: Any) -> Any:
38
+ """Use tenacity to retry the completion call."""
39
+ retry_decorator = _create_retry_decorator()
40
+
41
+ @retry_decorator
42
+ def _embed_with_retry(*args: Any, **kwargs: Any) -> Any:
43
+ return embeddings.embed(*args, **kwargs)
44
+
45
+ return _embed_with_retry(*args, **kwargs)
46
+
47
+
48
+ @deprecated(
49
+ since="0.0.34", removal="1.0", alternative_import="langchain_upstage.ChatUpstage"
50
+ )
51
+ class SolarEmbeddings(BaseModel, Embeddings):
52
+ """Solar's embedding service.
53
+
54
+ To use, you should have the environment variable``SOLAR_API_KEY`` set
55
+ with your API token, or pass it as a named parameter to the constructor.
56
+
57
+ Example:
58
+ .. code-block:: python
59
+
60
+ from langchain_community.embeddings import SolarEmbeddings
61
+ embeddings = SolarEmbeddings()
62
+
63
+ query_text = "This is a test query."
64
+ query_result = embeddings.embed_query(query_text)
65
+
66
+ document_text = "This is a test document."
67
+ document_result = embeddings.embed_documents([document_text])
68
+
69
+ """
70
+
71
+ endpoint_url: str = "https://api.upstage.ai/v1/solar/embeddings"
72
+ """Endpoint URL to use."""
73
+ model: str = "embedding-query"
74
+ """Embeddings model name to use."""
75
+ solar_api_key: Optional[SecretStr] = None
76
+ """API Key for Solar API."""
77
+
78
+ model_config = ConfigDict(
79
+ extra="forbid",
80
+ )
81
+
82
+ @pre_init
83
+ def validate_environment(cls, values: Dict) -> Dict:
84
+ """Validate api key exists in environment."""
85
+ solar_api_key = convert_to_secret_str(
86
+ get_from_dict_or_env(values, "solar_api_key", "SOLAR_API_KEY")
87
+ )
88
+ values["solar_api_key"] = solar_api_key
89
+ return values
90
+
91
+ def embed(
92
+ self,
93
+ text: str,
94
+ ) -> List[List[float]]:
95
+ payload = {
96
+ "model": self.model,
97
+ "input": text,
98
+ }
99
+
100
+ # HTTP headers for authorization
101
+ headers = {
102
+ "Authorization": f"Bearer {self.solar_api_key.get_secret_value()}", # type: ignore[union-attr]
103
+ "Content-Type": "application/json",
104
+ }
105
+
106
+ # send request
107
+ response = requests.post(self.endpoint_url, headers=headers, json=payload)
108
+ parsed_response = response.json()
109
+
110
+ # check for errors
111
+ if len(parsed_response["data"]) == 0:
112
+ raise ValueError(
113
+ f"Solar API returned an error: {parsed_response['base_resp']}"
114
+ )
115
+
116
+ embedding = parsed_response["data"][0]["embedding"]
117
+
118
+ return embedding
119
+
120
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
121
+ """Embed documents using a Solar embedding endpoint.
122
+
123
+ Args:
124
+ texts: The list of texts to embed.
125
+
126
+ Returns:
127
+ List of embeddings, one for each text.
128
+ """
129
+ embeddings = [embed_with_retry(self, text=text) for text in texts]
130
+ return embeddings
131
+
132
+ def embed_query(self, text: str) -> List[float]:
133
+ """Embed a query using a Solar embedding endpoint.
134
+
135
+ Args:
136
+ text: The text to embed.
137
+
138
+ Returns:
139
+ Embeddings for the text.
140
+ """
141
+ embedding = embed_with_retry(self, text=text)
142
+ return embedding
python/user_packages/Python313/site-packages/langchain_community/embeddings/spacy_embeddings.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ from langchain_core.embeddings import Embeddings
5
+ from pydantic import BaseModel, ConfigDict, model_validator
6
+
7
+
8
+ class SpacyEmbeddings(BaseModel, Embeddings):
9
+ """Embeddings by spaCy models.
10
+
11
+ Attributes:
12
+ model_name (str): Name of a spaCy model.
13
+ nlp (Any): The spaCy model loaded into memory.
14
+
15
+ Methods:
16
+ embed_documents(texts: List[str]) -> List[List[float]]:
17
+ Generates embeddings for a list of documents.
18
+ embed_query(text: str) -> List[float]:
19
+ Generates an embedding for a single piece of text.
20
+ """
21
+
22
+ model_name: str = "en_core_web_sm"
23
+ nlp: Optional[Any] = None
24
+
25
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
26
+
27
+ @model_validator(mode="before")
28
+ @classmethod
29
+ def validate_environment(cls, values: Dict) -> Any:
30
+ """
31
+ Validates that the spaCy package and the model are installed.
32
+
33
+ Args:
34
+ values (Dict): The values provided to the class constructor.
35
+
36
+ Returns:
37
+ The validated values.
38
+
39
+ Raises:
40
+ ValueError: If the spaCy package or the
41
+ model are not installed.
42
+ """
43
+ if values.get("model_name") is None:
44
+ values["model_name"] = "en_core_web_sm"
45
+
46
+ model_name = values.get("model_name")
47
+
48
+ # Check if the spaCy package is installed
49
+ if importlib.util.find_spec("spacy") is None:
50
+ raise ValueError(
51
+ "SpaCy package not found. Please install it with `pip install spacy`."
52
+ )
53
+ try:
54
+ # Try to load the spaCy model
55
+ import spacy
56
+
57
+ values["nlp"] = spacy.load(model_name)
58
+ except OSError:
59
+ # If the model is not found, raise a ValueError
60
+ raise ValueError(
61
+ f"SpaCy model '{model_name}' not found. "
62
+ f"Please install it with"
63
+ f" `python -m spacy download {model_name}`"
64
+ "or provide a valid spaCy model name."
65
+ )
66
+ return values # Return the validated values
67
+
68
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
69
+ """
70
+ Generates embeddings for a list of documents.
71
+
72
+ Args:
73
+ texts (List[str]): The documents to generate embeddings for.
74
+
75
+ Returns:
76
+ A list of embeddings, one for each document.
77
+ """
78
+ return [self.nlp(text).vector.tolist() for text in texts] # type: ignore[misc]
79
+
80
+ def embed_query(self, text: str) -> List[float]:
81
+ """
82
+ Generates an embedding for a single piece of text.
83
+
84
+ Args:
85
+ text (str): The text to generate an embedding for.
86
+
87
+ Returns:
88
+ The embedding for the text.
89
+ """
90
+ return self.nlp(text).vector.tolist() # type: ignore[misc]
91
+
92
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
93
+ """
94
+ Asynchronously generates embeddings for a list of documents.
95
+ This method is not implemented and raises a NotImplementedError.
96
+
97
+ Args:
98
+ texts (List[str]): The documents to generate embeddings for.
99
+
100
+ Raises:
101
+ NotImplementedError: This method is not implemented.
102
+ """
103
+ raise NotImplementedError("Asynchronous embedding generation is not supported.")
104
+
105
+ async def aembed_query(self, text: str) -> List[float]:
106
+ """
107
+ Asynchronously generates an embedding for a single piece of text.
108
+ This method is not implemented and raises a NotImplementedError.
109
+
110
+ Args:
111
+ text (str): The text to generate an embedding for.
112
+
113
+ Raises:
114
+ NotImplementedError: This method is not implemented.
115
+ """
116
+ raise NotImplementedError("Asynchronous embedding generation is not supported.")
python/user_packages/Python313/site-packages/langchain_community/embeddings/sparkllm.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import logging
6
+ from datetime import datetime
7
+ from time import mktime
8
+ from typing import Any, Dict, List, Literal, Optional
9
+ from urllib.parse import urlencode
10
+ from wsgiref.handlers import format_date_time
11
+
12
+ import numpy as np
13
+ import requests
14
+ from langchain_core.embeddings import Embeddings
15
+ from langchain_core.utils import (
16
+ secret_from_env,
17
+ )
18
+ from numpy import ndarray
19
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
20
+
21
+ # SparkLLMTextEmbeddings is an embedding model provided by iFLYTEK Co., Ltd.. (https://iflytek.com/en/).
22
+
23
+ # Official Website: https://www.xfyun.cn/doc/spark/Embedding_api.html
24
+ # Developers need to create an application in the console first, use the appid, APIKey,
25
+ # and APISecret provided in the application for authentication,
26
+ # and generate an authentication URL for handshake.
27
+ # You can get one by registering at https://console.xfyun.cn/services/bm3.
28
+ # SparkLLMTextEmbeddings support 2K token window and preduces vectors with
29
+ # 2560 dimensions.
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class Url:
35
+ """URL class for parsing the URL."""
36
+
37
+ def __init__(self, host: str, path: str, schema: str) -> None:
38
+ self.host = host
39
+ self.path = path
40
+ self.schema = schema
41
+ pass
42
+
43
+
44
+ class SparkLLMTextEmbeddings(BaseModel, Embeddings):
45
+ """SparkLLM embedding model integration.
46
+
47
+ Setup:
48
+ To use, you should have the environment variable "SPARK_APP_ID","SPARK_API_KEY"
49
+ and "SPARK_API_SECRET" set your APP_ID, API_KEY and API_SECRET or pass it
50
+ as a name parameter to the constructor.
51
+
52
+ .. code-block:: bash
53
+
54
+ export SPARK_APP_ID="your-api-id"
55
+ export SPARK_API_KEY="your-api-key"
56
+ export SPARK_API_SECRET="your-api-secret"
57
+
58
+ Key init args — completion params:
59
+ api_key: Optional[str]
60
+ Automatically inferred from env var `SPARK_API_KEY` if not provided.
61
+ app_id: Optional[str]
62
+ Automatically inferred from env var `SPARK_APP_ID` if not provided.
63
+ api_secret: Optional[str]
64
+ Automatically inferred from env var `SPARK_API_SECRET` if not provided.
65
+ base_url: Optional[str]
66
+ Base URL path for API requests.
67
+
68
+ See full list of supported init args and their descriptions in the params section.
69
+
70
+ Instantiate:
71
+
72
+ .. code-block:: python
73
+
74
+ from langchain_community.embeddings import SparkLLMTextEmbeddings
75
+
76
+ embed = SparkLLMTextEmbeddings(
77
+ api_key="...",
78
+ app_id="...",
79
+ api_secret="...",
80
+ # other
81
+ )
82
+
83
+ Embed single text:
84
+ .. code-block:: python
85
+
86
+ input_text = "The meaning of life is 42"
87
+ embed.embed_query(input_text)
88
+
89
+ .. code-block:: python
90
+
91
+ [-0.4912109375, 0.60595703125, 0.658203125, 0.3037109375, 0.6591796875, 0.60302734375, ...]
92
+
93
+ Embed multiple text:
94
+ .. code-block:: python
95
+
96
+ input_texts = ["This is a test query1.", "This is a test query2."]
97
+ embed.embed_documents(input_texts)
98
+
99
+ .. code-block:: python
100
+
101
+ [
102
+ [-0.1962890625, 0.94677734375, 0.7998046875, -0.1971435546875, 0.445556640625, 0.54638671875, ...],
103
+ [ -0.44970703125, 0.06585693359375, 0.7421875, -0.474609375, 0.62353515625, 1.0478515625, ...],
104
+ ]
105
+ """ # noqa: E501
106
+
107
+ spark_app_id: SecretStr = Field(
108
+ alias="app_id", default_factory=secret_from_env("SPARK_APP_ID")
109
+ )
110
+ """Automatically inferred from env var `SPARK_APP_ID` if not provided."""
111
+ spark_api_key: Optional[SecretStr] = Field(
112
+ alias="api_key", default_factory=secret_from_env("SPARK_API_KEY", default=None)
113
+ )
114
+ """Automatically inferred from env var `SPARK_API_KEY` if not provided."""
115
+ spark_api_secret: Optional[SecretStr] = Field(
116
+ alias="api_secret",
117
+ default_factory=secret_from_env("SPARK_API_SECRET", default=None),
118
+ )
119
+ """Automatically inferred from env var `SPARK_API_SECRET` if not provided."""
120
+ base_url: str = Field(default="https://emb-cn-huabei-1.xf-yun.com/")
121
+ """Base URL path for API requests"""
122
+ domain: Literal["para", "query"] = Field(default="para")
123
+ """This parameter is used for which Embedding this time belongs to.
124
+ If "para"(default), it belongs to document Embedding.
125
+ If "query", it belongs to query Embedding."""
126
+
127
+ model_config = ConfigDict(
128
+ populate_by_name=True,
129
+ )
130
+
131
+ def _embed(self, texts: List[str], host: str) -> Optional[List[List[float]]]:
132
+ """Internal method to call Spark Embedding API and return embeddings.
133
+
134
+ Args:
135
+ texts: A list of texts to embed.
136
+ host: Base URL path for API requests
137
+
138
+ Returns:
139
+ A list of list of floats representing the embeddings,
140
+ or list with value None if an error occurs.
141
+ """
142
+ app_id = ""
143
+ api_key = ""
144
+ api_secret = ""
145
+ if self.spark_app_id:
146
+ app_id = self.spark_app_id.get_secret_value()
147
+ if self.spark_api_key:
148
+ api_key = self.spark_api_key.get_secret_value()
149
+ if self.spark_api_secret:
150
+ api_secret = self.spark_api_secret.get_secret_value()
151
+ url = self._assemble_ws_auth_url(
152
+ request_url=host,
153
+ method="POST",
154
+ api_key=api_key,
155
+ api_secret=api_secret,
156
+ )
157
+ embed_result: list = []
158
+ for text in texts:
159
+ query_context = {"messages": [{"content": text, "role": "user"}]}
160
+ content = self._get_body(app_id, query_context)
161
+ response = requests.post(
162
+ url, json=content, headers={"content-type": "application/json"}
163
+ ).text
164
+ res_arr = self._parser_message(response)
165
+ if res_arr is not None:
166
+ embed_result.append(res_arr.tolist())
167
+ else:
168
+ embed_result.append(None)
169
+ return embed_result
170
+
171
+ def embed_documents(self, texts: List[str]) -> Optional[List[List[float]]]: # type: ignore[override]
172
+ """Public method to get embeddings for a list of documents.
173
+
174
+ Args:
175
+ texts: The list of texts to embed.
176
+
177
+ Returns:
178
+ A list of embeddings, one for each text, or None if an error occurs.
179
+ """
180
+ return self._embed(texts, self.base_url)
181
+
182
+ def embed_query(self, text: str) -> Optional[List[float]]: # type: ignore[override]
183
+ """Public method to get embedding for a single query text.
184
+
185
+ Args:
186
+ text: The text to embed.
187
+
188
+ Returns:
189
+ Embeddings for the text, or None if an error occurs.
190
+ """
191
+ result = self._embed([text], self.base_url)
192
+ return result[0] if result is not None else None
193
+
194
+ @staticmethod
195
+ def _assemble_ws_auth_url(
196
+ request_url: str, method: str = "GET", api_key: str = "", api_secret: str = ""
197
+ ) -> str:
198
+ u = SparkLLMTextEmbeddings._parse_url(request_url)
199
+ host = u.host
200
+ path = u.path
201
+ now = datetime.now()
202
+ date = format_date_time(mktime(now.timetuple()))
203
+ signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(
204
+ host, date, method, path
205
+ )
206
+ signature_sha = hmac.new(
207
+ api_secret.encode("utf-8"),
208
+ signature_origin.encode("utf-8"),
209
+ digestmod=hashlib.sha256,
210
+ ).digest()
211
+ signature_sha_str = base64.b64encode(signature_sha).decode(encoding="utf-8")
212
+ authorization_origin = (
213
+ 'api_key="%s", algorithm="%s", headers="%s", signature="%s"'
214
+ % (api_key, "hmac-sha256", "host date request-line", signature_sha_str)
215
+ )
216
+ authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
217
+ encoding="utf-8"
218
+ )
219
+ values = {"host": host, "date": date, "authorization": authorization}
220
+
221
+ return request_url + "?" + urlencode(values)
222
+
223
+ @staticmethod
224
+ def _parse_url(request_url: str) -> Url:
225
+ stidx = request_url.index("://")
226
+ host = request_url[stidx + 3 :]
227
+ schema = request_url[: stidx + 3]
228
+ edidx = host.index("/")
229
+ if edidx <= 0:
230
+ raise AssembleHeaderException("invalid request url:" + request_url)
231
+ path = host[edidx:]
232
+ host = host[:edidx]
233
+ u = Url(host, path, schema)
234
+ return u
235
+
236
+ def _get_body(self, appid: str, text: dict) -> Dict[str, Any]:
237
+ body = {
238
+ "header": {"app_id": appid, "uid": "39769795890", "status": 3},
239
+ "parameter": {
240
+ "emb": {"domain": self.domain, "feature": {"encoding": "utf8"}}
241
+ },
242
+ "payload": {
243
+ "messages": {
244
+ "text": base64.b64encode(json.dumps(text).encode("utf-8")).decode()
245
+ }
246
+ },
247
+ }
248
+ return body
249
+
250
+ @staticmethod
251
+ def _parser_message(
252
+ message: str,
253
+ ) -> Optional[ndarray]:
254
+ data = json.loads(message)
255
+ code = data["header"]["code"]
256
+ if code != 0:
257
+ logger.warning(f"Request error: {code}, {data}")
258
+ return None
259
+ else:
260
+ text_base = data["payload"]["feature"]["text"]
261
+ text_data = base64.b64decode(text_base)
262
+ dt = np.dtype(np.float32)
263
+ dt = dt.newbyteorder("<")
264
+ text = np.frombuffer(text_data, dtype=dt)
265
+ if len(text) > 2560:
266
+ array = text[:2560]
267
+ else:
268
+ array = text
269
+ return array
270
+
271
+
272
+ class AssembleHeaderException(Exception):
273
+ """Exception raised for errors in the header assembly."""
274
+
275
+ def __init__(self, msg: str) -> None:
276
+ self.message = msg
python/user_packages/Python313/site-packages/langchain_community/embeddings/tensorflow_hub.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+ DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
7
+
8
+
9
+ class TensorflowHubEmbeddings(BaseModel, Embeddings):
10
+ """TensorflowHub embedding models.
11
+
12
+ To use, you should have the ``tensorflow_text`` python package installed.
13
+
14
+ Example:
15
+ .. code-block:: python
16
+
17
+ from langchain_community.embeddings import TensorflowHubEmbeddings
18
+ url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
19
+ tf = TensorflowHubEmbeddings(model_url=url)
20
+ """
21
+
22
+ embed: Any = None #: :meta private:
23
+ model_url: str = DEFAULT_MODEL_URL
24
+ """Model name to use."""
25
+
26
+ def __init__(self, **kwargs: Any):
27
+ """Initialize the tensorflow_hub and tensorflow_text."""
28
+ super().__init__(**kwargs)
29
+ try:
30
+ import tensorflow_hub
31
+ except ImportError:
32
+ raise ImportError(
33
+ "Could not import tensorflow-hub python package. "
34
+ "Please install it with `pip install tensorflow-hub``."
35
+ )
36
+ try:
37
+ import tensorflow_text # noqa
38
+ except ImportError:
39
+ raise ImportError(
40
+ "Could not import tensorflow_text python package. "
41
+ "Please install it with `pip install tensorflow_text``."
42
+ )
43
+
44
+ self.embed = tensorflow_hub.load(self.model_url)
45
+
46
+ model_config = ConfigDict(
47
+ extra="forbid",
48
+ protected_namespaces=(),
49
+ )
50
+
51
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
52
+ """Compute doc embeddings using a TensorflowHub embedding model.
53
+
54
+ Args:
55
+ texts: The list of texts to embed.
56
+
57
+ Returns:
58
+ List of embeddings, one for each text.
59
+ """
60
+ texts = list(map(lambda x: x.replace("\n", " "), texts))
61
+ embeddings = self.embed(texts).numpy()
62
+ return embeddings.tolist()
63
+
64
+ def embed_query(self, text: str) -> List[float]:
65
+ """Compute query embeddings using a TensorflowHub embedding model.
66
+
67
+ Args:
68
+ text: The text to embed.
69
+
70
+ Returns:
71
+ Embeddings for the text.
72
+ """
73
+ text = text.replace("\n", " ")
74
+ embedding = self.embed([text]).numpy()[0]
75
+ return embedding.tolist()
python/user_packages/Python313/site-packages/langchain_community/embeddings/text2vec.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper around text2vec embedding models."""
2
+
3
+ from typing import Any, List, Optional
4
+
5
+ from langchain_core.embeddings import Embeddings
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+
9
+ class Text2vecEmbeddings(Embeddings, BaseModel):
10
+ """text2vec embedding models.
11
+
12
+ Install text2vec first, run 'pip install -U text2vec'.
13
+ The github repository for text2vec is : https://github.com/shibing624/text2vec
14
+
15
+ Example:
16
+ .. code-block:: python
17
+
18
+ from langchain_community.embeddings.text2vec import Text2vecEmbeddings
19
+
20
+ embedding = Text2vecEmbeddings()
21
+ embedding.embed_documents([
22
+ "This is a CoSENT(Cosine Sentence) model.",
23
+ "It maps sentences to a 768 dimensional dense vector space.",
24
+ ])
25
+ embedding.embed_query(
26
+ "It can be used for text matching or semantic search."
27
+ )
28
+ """
29
+
30
+ model_name_or_path: Optional[str] = None
31
+ encoder_type: Any = "MEAN"
32
+ max_seq_length: int = 256
33
+ device: Optional[str] = None
34
+ model: Any = None
35
+
36
+ model_config = ConfigDict(protected_namespaces=())
37
+
38
+ def __init__(
39
+ self,
40
+ *,
41
+ model: Any = None,
42
+ model_name_or_path: Optional[str] = None,
43
+ **kwargs: Any,
44
+ ):
45
+ try:
46
+ from text2vec import SentenceModel
47
+ except ImportError as e:
48
+ raise ImportError(
49
+ "Unable to import text2vec, please install with "
50
+ "`pip install -U text2vec`."
51
+ ) from e
52
+
53
+ model_kwargs = {}
54
+ if model_name_or_path is not None:
55
+ model_kwargs["model_name_or_path"] = model_name_or_path
56
+ model = model or SentenceModel(**model_kwargs, **kwargs)
57
+ super().__init__(model=model, model_name_or_path=model_name_or_path, **kwargs)
58
+
59
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
60
+ """Embed documents using the text2vec embeddings model.
61
+
62
+ Args:
63
+ texts: The list of texts to embed.
64
+
65
+ Returns:
66
+ List of embeddings, one for each text.
67
+ """
68
+
69
+ return self.model.encode(texts)
70
+
71
+ def embed_query(self, text: str) -> List[float]:
72
+ """Embed a query using the text2vec embeddings model.
73
+
74
+ Args:
75
+ text: The text to embed.
76
+
77
+ Returns:
78
+ Embeddings for the text.
79
+ """
80
+
81
+ return self.model.encode(text)
python/user_packages/Python313/site-packages/langchain_community/embeddings/textembed.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TextEmbed: Embedding Inference Server
3
+
4
+ TextEmbed provides a high-throughput, low-latency solution for serving embeddings.
5
+ It supports various sentence-transformer models.
6
+ Now, it includes the ability to deploy image embedding models.
7
+ TextEmbed offers flexibility and scalability for diverse applications.
8
+
9
+ TextEmbed is maintained by Keval Dekivadiya and is licensed under the Apache-2.0 license.
10
+ """ # noqa: E501
11
+
12
+ import asyncio
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
15
+
16
+ import aiohttp
17
+ import numpy as np
18
+ import requests
19
+ from langchain_core.embeddings import Embeddings
20
+ from langchain_core.utils import from_env, secret_from_env
21
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
22
+ from typing_extensions import Self
23
+
24
+ __all__ = ["TextEmbedEmbeddings"]
25
+
26
+
27
+ class TextEmbedEmbeddings(BaseModel, Embeddings):
28
+ """
29
+ A class to handle embedding requests to the TextEmbed API.
30
+
31
+ Attributes:
32
+ model : The TextEmbed model ID to use for embeddings.
33
+ api_url : The base URL for the TextEmbed API.
34
+ api_key : The API key for authenticating with the TextEmbed API.
35
+ client : The TextEmbed client instance.
36
+
37
+ Example:
38
+ .. code-block:: python
39
+
40
+ from langchain_community.embeddings import TextEmbedEmbeddings
41
+
42
+ embeddings = TextEmbedEmbeddings(
43
+ model="sentence-transformers/clip-ViT-B-32",
44
+ api_url="http://localhost:8000/v1",
45
+ api_key="<API_KEY>"
46
+ )
47
+
48
+ For more information: https://github.com/kevaldekivadiya2415/textembed/blob/main/docs/setup.md
49
+ """ # noqa: E501
50
+
51
+ model: str
52
+ """Underlying TextEmbed model id."""
53
+
54
+ api_url: str = Field(
55
+ default_factory=from_env(
56
+ "TEXTEMBED_API_URL", default="http://localhost:8000/v1"
57
+ )
58
+ )
59
+ """Endpoint URL to use."""
60
+
61
+ api_key: SecretStr = Field(default_factory=secret_from_env("TEXTEMBED_API_KEY"))
62
+ """API Key for authentication"""
63
+
64
+ client: Any = None
65
+ """TextEmbed client."""
66
+
67
+ model_config = ConfigDict(
68
+ extra="forbid",
69
+ )
70
+
71
+ @model_validator(mode="after")
72
+ def validate_environment(self) -> Self:
73
+ """Validate that api key and URL exist in the environment."""
74
+ self.client = AsyncOpenAITextEmbedEmbeddingClient(
75
+ host=self.api_url, api_key=self.api_key.get_secret_value()
76
+ )
77
+ return self
78
+
79
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
80
+ """Call out to TextEmbed's embedding endpoint.
81
+
82
+ Args:
83
+ texts (List[str]): The list of texts to embed.
84
+
85
+ Returns:
86
+ List[List[float]]: List of embeddings, one for each text.
87
+ """
88
+ embeddings = self.client.embed(
89
+ model=self.model,
90
+ texts=texts,
91
+ )
92
+ return embeddings
93
+
94
+ async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
95
+ """Async call out to TextEmbed's embedding endpoint.
96
+
97
+ Args:
98
+ texts (List[str]): The list of texts to embed.
99
+
100
+ Returns:
101
+ List[List[float]]: List of embeddings, one for each text.
102
+ """
103
+ embeddings = await self.client.aembed(
104
+ model=self.model,
105
+ texts=texts,
106
+ )
107
+ return embeddings
108
+
109
+ def embed_query(self, text: str) -> List[float]:
110
+ """Call out to TextEmbed's embedding endpoint for a single query.
111
+
112
+ Args:
113
+ text (str): The text to embed.
114
+
115
+ Returns:
116
+ List[float]: Embeddings for the text.
117
+ """
118
+ return self.embed_documents([text])[0]
119
+
120
+ async def aembed_query(self, text: str) -> List[float]:
121
+ """Async call out to TextEmbed's embedding endpoint for a single query.
122
+
123
+ Args:
124
+ text (str): The text to embed.
125
+
126
+ Returns:
127
+ List[float]: Embeddings for the text.
128
+ """
129
+ embeddings = await self.aembed_documents([text])
130
+ return embeddings[0]
131
+
132
+
133
+ class AsyncOpenAITextEmbedEmbeddingClient:
134
+ """
135
+ A client to handle synchronous and asynchronous requests to the TextEmbed API.
136
+
137
+ Attributes:
138
+ host (str): The base URL for the TextEmbed API.
139
+ api_key (str): The API key for authenticating with the TextEmbed API.
140
+ aiosession (Optional[aiohttp.ClientSession]): The aiohttp session for async requests.
141
+ _batch_size (int): Maximum batch size for a single request.
142
+ """ # noqa: E501
143
+
144
+ def __init__(
145
+ self,
146
+ host: str = "http://localhost:8000/v1",
147
+ api_key: Union[str, None] = None,
148
+ aiosession: Optional[aiohttp.ClientSession] = None,
149
+ ) -> None:
150
+ self.host = host
151
+ self.api_key = api_key
152
+ self.aiosession = aiosession
153
+
154
+ if self.host is None or len(self.host) < 3:
155
+ raise ValueError("Parameter `host` must be set to a valid URL")
156
+ self._batch_size = 256
157
+
158
+ @staticmethod
159
+ def _permute(
160
+ texts: List[str], sorter: Callable = len
161
+ ) -> Tuple[List[str], Callable]:
162
+ """
163
+ Sorts texts in ascending order and provides a function to restore the original order.
164
+
165
+ Args:
166
+ texts (List[str]): List of texts to sort.
167
+ sorter (Callable, optional): Sorting function, defaults to length.
168
+
169
+ Returns:
170
+ Tuple[List[str], Callable]: Sorted texts and a function to restore original order.
171
+ """ # noqa: E501
172
+ if len(texts) == 1:
173
+ return texts, lambda t: t
174
+ length_sorted_idx = np.argsort([-sorter(sen) for sen in texts])
175
+ texts_sorted = [texts[idx] for idx in length_sorted_idx]
176
+
177
+ return texts_sorted, lambda unsorted_embeddings: [
178
+ unsorted_embeddings[idx] for idx in np.argsort(length_sorted_idx)
179
+ ]
180
+
181
+ def _batch(self, texts: List[str]) -> List[List[str]]:
182
+ """
183
+ Splits a list of texts into batches of size max `self._batch_size`.
184
+
185
+ Args:
186
+ texts (List[str]): List of texts to split.
187
+
188
+ Returns:
189
+ List[List[str]]: List of batches of texts.
190
+ """
191
+ if len(texts) == 1:
192
+ return [texts]
193
+ batches = []
194
+ for start_index in range(0, len(texts), self._batch_size):
195
+ batches.append(texts[start_index : start_index + self._batch_size])
196
+ return batches
197
+
198
+ @staticmethod
199
+ def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]:
200
+ """
201
+ Merges batches of texts into a single list.
202
+
203
+ Args:
204
+ batch_of_texts (List[List[Any]]): List of batches of texts.
205
+
206
+ Returns:
207
+ List[Any]: Merged list of texts.
208
+ """
209
+ if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1:
210
+ return batch_of_texts[0]
211
+ texts = []
212
+ for sublist in batch_of_texts:
213
+ texts.extend(sublist)
214
+ return texts
215
+
216
+ def _kwargs_post_request(self, model: str, texts: List[str]) -> Dict[str, Any]:
217
+ """
218
+ Builds the kwargs for the POST request, used by sync method.
219
+
220
+ Args:
221
+ model (str): The model to use for embedding.
222
+ texts (List[str]): List of texts to embed.
223
+
224
+ Returns:
225
+ Dict[str, Any]: Dictionary of POST request parameters.
226
+ """
227
+ return dict(
228
+ url=f"{self.host}/embedding",
229
+ headers={
230
+ "accept": "application/json",
231
+ "content-type": "application/json",
232
+ "Authorization": f"Bearer {self.api_key}",
233
+ },
234
+ json=dict(
235
+ input=texts,
236
+ model=model,
237
+ ),
238
+ )
239
+
240
+ def _sync_request_embed(
241
+ self, model: str, batch_texts: List[str]
242
+ ) -> List[List[float]]:
243
+ """
244
+ Sends a synchronous request to the embedding endpoint.
245
+
246
+ Args:
247
+ model (str): The model to use for embedding.
248
+ batch_texts (List[str]): Batch of texts to embed.
249
+
250
+ Returns:
251
+ List[List[float]]: List of embeddings for the batch.
252
+
253
+ Raises:
254
+ Exception: If the response status is not 200.
255
+ """
256
+ response = requests.post(
257
+ **self._kwargs_post_request(model=model, texts=batch_texts)
258
+ )
259
+ if response.status_code != 200:
260
+ raise Exception(
261
+ f"TextEmbed responded with an unexpected status message "
262
+ f"{response.status_code}: {response.text}"
263
+ )
264
+ return [e["embedding"] for e in response.json()["data"]]
265
+
266
+ def embed(self, model: str, texts: List[str]) -> List[List[float]]:
267
+ """
268
+ Embeds a list of texts synchronously.
269
+
270
+ Args:
271
+ model (str): The model to use for embedding.
272
+ texts (List[str]): List of texts to embed.
273
+
274
+ Returns:
275
+ List[List[float]]: List of embeddings for the texts.
276
+ """
277
+ perm_texts, unpermute_func = self._permute(texts)
278
+ perm_texts_batched = self._batch(perm_texts)
279
+
280
+ # Request
281
+ map_args = (
282
+ self._sync_request_embed,
283
+ [model] * len(perm_texts_batched),
284
+ perm_texts_batched,
285
+ )
286
+ if len(perm_texts_batched) == 1:
287
+ embeddings_batch_perm = list(map(*map_args))
288
+ else:
289
+ with ThreadPoolExecutor(32) as p:
290
+ embeddings_batch_perm = list(p.map(*map_args))
291
+
292
+ embeddings_perm = self._unbatch(embeddings_batch_perm)
293
+ embeddings = unpermute_func(embeddings_perm)
294
+ return embeddings
295
+
296
+ async def _async_request(
297
+ self, session: aiohttp.ClientSession, **kwargs: Dict[str, Any]
298
+ ) -> List[List[float]]:
299
+ """
300
+ Sends an asynchronous request to the embedding endpoint.
301
+
302
+ Args:
303
+ session (aiohttp.ClientSession): The aiohttp session for the request.
304
+ kwargs (Dict[str, Any]): Dictionary of POST request parameters.
305
+
306
+ Returns:
307
+ List[List[float]]: List of embeddings for the request.
308
+
309
+ Raises:
310
+ Exception: If the response status is not 200.
311
+ """
312
+ async with session.post(**kwargs) as response: # type: ignore[arg-type]
313
+ if response.status != 200:
314
+ raise Exception(
315
+ f"TextEmbed responded with an unexpected status message "
316
+ f"{response.status}: {response.text}"
317
+ )
318
+ embedding = (await response.json())["data"]
319
+ return [e["embedding"] for e in embedding]
320
+
321
+ async def aembed(self, model: str, texts: List[str]) -> List[List[float]]:
322
+ """
323
+ Embeds a list of texts asynchronously.
324
+
325
+ Args:
326
+ model (str): The model to use for embedding.
327
+ texts (List[str]): List of texts to embed.
328
+
329
+ Returns:
330
+ List[List[float]]: List of embeddings for the texts.
331
+ """
332
+ perm_texts, unpermute_func = self._permute(texts)
333
+ perm_texts_batched = self._batch(perm_texts)
334
+
335
+ async with aiohttp.ClientSession(
336
+ connector=aiohttp.TCPConnector(limit=32)
337
+ ) as session:
338
+ embeddings_batch_perm = await asyncio.gather(
339
+ *[
340
+ self._async_request(
341
+ session=session,
342
+ **self._kwargs_post_request(model=model, texts=t),
343
+ )
344
+ for t in perm_texts_batched
345
+ ]
346
+ )
347
+
348
+ embeddings_perm = self._unbatch(embeddings_batch_perm)
349
+ embeddings = unpermute_func(embeddings_perm)
350
+ return embeddings
python/user_packages/Python313/site-packages/langchain_community/embeddings/titan_takeoff.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import Any, Dict, List, Optional, Set, Union
3
+
4
+ from langchain_core.embeddings import Embeddings
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+
8
+ class TakeoffEmbeddingException(Exception):
9
+ """Custom exception for interfacing with Takeoff Embedding class."""
10
+
11
+
12
+ class MissingConsumerGroup(TakeoffEmbeddingException):
13
+ """Exception raised when no consumer group is provided on initialization of
14
+ TitanTakeoffEmbed or in embed request."""
15
+
16
+
17
+ class Device(str, Enum):
18
+ """Device to use for inference, cuda or cpu."""
19
+
20
+ cuda = "cuda"
21
+ cpu = "cpu"
22
+
23
+
24
+ class ReaderConfig(BaseModel):
25
+ """Configuration for the reader to be deployed in Takeoff."""
26
+
27
+ model_config = ConfigDict(
28
+ protected_namespaces=(),
29
+ )
30
+
31
+ model_name: str
32
+ """The name of the model to use"""
33
+
34
+ device: Device = Device.cuda
35
+ """The device to use for inference, cuda or cpu"""
36
+
37
+ consumer_group: str = "primary"
38
+ """The consumer group to place the reader into"""
39
+
40
+
41
+ class TitanTakeoffEmbed(Embeddings):
42
+ """Interface with Takeoff Inference API for embedding models.
43
+
44
+ Use it to send embedding requests and to deploy embedding
45
+ readers with Takeoff.
46
+
47
+ Examples:
48
+ This is an example how to deploy an embedding model and send requests.
49
+
50
+ .. code-block:: python
51
+ # Import the TitanTakeoffEmbed class from community package
52
+ import time
53
+ from langchain_community.embeddings import TitanTakeoffEmbed
54
+
55
+ # Specify the embedding reader you'd like to deploy
56
+ reader_1 = {
57
+ "model_name": "avsolatorio/GIST-large-Embedding-v0",
58
+ "device": "cpu",
59
+ "consumer_group": "embed"
60
+ }
61
+
62
+ # For every reader you pass into models arg Takeoff will spin up a reader
63
+ # according to the specs you provide. If you don't specify the arg no models
64
+ # are spun up and it assumes you have already done this separately.
65
+ embed = TitanTakeoffEmbed(models=[reader_1])
66
+
67
+ # Wait for the reader to be deployed, time needed depends on the model size
68
+ # and your internet speed
69
+ time.sleep(60)
70
+
71
+ # Returns the embedded query, ie a List[float], sent to `embed` consumer
72
+ # group where we just spun up the embedding reader
73
+ print(embed.embed_query(
74
+ "Where can I see football?", consumer_group="embed"
75
+ ))
76
+
77
+ # Returns a List of embeddings, ie a List[List[float]], sent to `embed`
78
+ # consumer group where we just spun up the embedding reader
79
+ print(embed.embed_document(
80
+ ["Document1", "Document2"],
81
+ consumer_group="embed"
82
+ ))
83
+ """
84
+
85
+ base_url: str = "http://localhost"
86
+ """The base URL of the Titan Takeoff (Pro) server. Default = "http://localhost"."""
87
+
88
+ port: int = 3000
89
+ """The port of the Titan Takeoff (Pro) server. Default = 3000."""
90
+
91
+ mgmt_port: int = 3001
92
+ """The management port of the Titan Takeoff (Pro) server. Default = 3001."""
93
+
94
+ client: Any = None
95
+ """Takeoff Client Python SDK used to interact with Takeoff API"""
96
+
97
+ embed_consumer_groups: Set[str] = set()
98
+ """The consumer groups in Takeoff which contain embedding models"""
99
+
100
+ def __init__(
101
+ self,
102
+ base_url: str = "http://localhost",
103
+ port: int = 3000,
104
+ mgmt_port: int = 3001,
105
+ models: List[ReaderConfig] = [],
106
+ ):
107
+ """Initialize the Titan Takeoff embedding wrapper.
108
+
109
+ Args:
110
+ base_url (str, optional): The base url where Takeoff Inference Server is
111
+ listening. Defaults to "http://localhost".
112
+ port (int, optional): What port is Takeoff Inference API listening on.
113
+ Defaults to 3000.
114
+ mgmt_port (int, optional): What port is Takeoff Management API listening on.
115
+ Defaults to 3001.
116
+ models (List[ReaderConfig], optional): Any readers you'd like to spin up on.
117
+ Defaults to [].
118
+
119
+ Raises:
120
+ ImportError: If you haven't installed takeoff-client, you will get an
121
+ ImportError. To remedy run `pip install 'takeoff-client==0.4.0'`
122
+ """
123
+ self.base_url = base_url
124
+ self.port = port
125
+ self.mgmt_port = mgmt_port
126
+ try:
127
+ from takeoff_client import TakeoffClient
128
+ except ImportError:
129
+ raise ImportError(
130
+ "takeoff-client is required for TitanTakeoff. "
131
+ "Please install it with `pip install 'takeoff-client==0.4.0'`."
132
+ )
133
+ self.client = TakeoffClient(
134
+ self.base_url, port=self.port, mgmt_port=self.mgmt_port
135
+ )
136
+ for model in models:
137
+ self.client.create_reader(model)
138
+ if isinstance(model, dict):
139
+ self.embed_consumer_groups.add(model.get("consumer_group"))
140
+ else:
141
+ self.embed_consumer_groups.add(model.consumer_group)
142
+ super(TitanTakeoffEmbed, self).__init__()
143
+
144
+ def _embed(
145
+ self, input: Union[List[str], str], consumer_group: Optional[str]
146
+ ) -> Dict[str, Any]:
147
+ """Embed text.
148
+
149
+ Args:
150
+ input (Union[List[str], str]): prompt/document or list of prompts/documents
151
+ to embed
152
+ consumer_group (Optional[str]): what consumer group to send the embedding
153
+ request to. If not specified and there is only one
154
+ consumer group specified during initialization, it will be used. If there
155
+ are multiple consumer groups specified during initialization, you must
156
+ specify which one to use.
157
+
158
+ Raises:
159
+ MissingConsumerGroup: The consumer group can not be inferred from the
160
+ initialization and must be specified with request.
161
+
162
+ Returns:
163
+ Dict[str, Any]: Result of query, {"result": List[List[float]]} or
164
+ {"result": List[float]}
165
+ """
166
+ if not consumer_group:
167
+ if len(self.embed_consumer_groups) == 1:
168
+ consumer_group = list(self.embed_consumer_groups)[0]
169
+ elif len(self.embed_consumer_groups) > 1:
170
+ raise MissingConsumerGroup(
171
+ "TakeoffEmbedding was initialized with multiple embedding reader"
172
+ "groups, you must specify which one to use."
173
+ )
174
+ else:
175
+ raise MissingConsumerGroup(
176
+ "You must specify what consumer group you want to send embedding"
177
+ "response to as TitanTakeoffEmbed was not initialized with an "
178
+ "embedding reader."
179
+ )
180
+ return self.client.embed(input, consumer_group)
181
+
182
+ def embed_documents(
183
+ self, texts: List[str], consumer_group: Optional[str] = None
184
+ ) -> List[List[float]]:
185
+ """Embed documents.
186
+
187
+ Args:
188
+ texts (List[str]): List of prompts/documents to embed
189
+ consumer_group (Optional[str], optional): Consumer group to send request
190
+ to containing embedding model. Defaults to None.
191
+
192
+ Returns:
193
+ List[List[float]]: List of embeddings
194
+ """
195
+ return self._embed(texts, consumer_group)["result"]
196
+
197
+ def embed_query(
198
+ self, text: str, consumer_group: Optional[str] = None
199
+ ) -> List[float]:
200
+ """Embed query.
201
+
202
+ Args:
203
+ text (str): Prompt/document to embed
204
+ consumer_group (Optional[str], optional): Consumer group to send request
205
+ to containing embedding model. Defaults to None.
206
+
207
+ Returns:
208
+ List[float]: Embedding
209
+ """
210
+ return self._embed(text, consumer_group)["result"]
python/user_packages/Python313/site-packages/langchain_community/embeddings/vertexai.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ import string
4
+ import threading
5
+ from concurrent.futures import ThreadPoolExecutor, wait
6
+ from typing import Any, Dict, List, Literal, Optional, Tuple
7
+
8
+ from langchain_core._api.deprecation import deprecated
9
+ from langchain_core.embeddings import Embeddings
10
+ from langchain_core.language_models.llms import create_base_retry_decorator
11
+ from langchain_core.utils import pre_init
12
+
13
+ from langchain_community.llms.vertexai import _VertexAICommon
14
+ from langchain_community.utilities.vertexai import raise_vertex_import_error
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _MAX_TOKENS_PER_BATCH = 20000
19
+ _MAX_BATCH_SIZE = 250
20
+ _MIN_BATCH_SIZE = 5
21
+
22
+
23
+ @deprecated(
24
+ since="0.0.12",
25
+ removal="1.0",
26
+ alternative_import="langchain_google_vertexai.VertexAIEmbeddings",
27
+ )
28
+ class VertexAIEmbeddings(_VertexAICommon, Embeddings):
29
+ """Google Cloud VertexAI embedding models."""
30
+
31
+ # Instance context
32
+ instance: Dict[str, Any] = {} #: :meta private:
33
+ show_progress_bar: bool = False
34
+ """Whether to show a tqdm progress bar. Must have `tqdm` installed."""
35
+
36
+ @pre_init
37
+ def validate_environment(cls, values: Dict) -> Dict:
38
+ """Validates that the python package exists in environment."""
39
+ cls._try_init_vertexai(values)
40
+ if values["model_name"] == "textembedding-gecko-default":
41
+ logger.warning(
42
+ "Model_name will become a required arg for VertexAIEmbeddings "
43
+ "starting from Feb-01-2024. Currently the default is set to "
44
+ "textembedding-gecko@001"
45
+ )
46
+ values["model_name"] = "textembedding-gecko@001"
47
+ try:
48
+ from vertexai.language_models import TextEmbeddingModel
49
+ except ImportError:
50
+ raise_vertex_import_error()
51
+ values["client"] = TextEmbeddingModel.from_pretrained(values["model_name"])
52
+ return values
53
+
54
+ def __init__(
55
+ self,
56
+ # the default value would be removed after Feb-01-2024
57
+ model_name: str = "textembedding-gecko-default",
58
+ project: Optional[str] = None,
59
+ location: str = "us-central1",
60
+ request_parallelism: int = 5,
61
+ max_retries: int = 6,
62
+ credentials: Optional[Any] = None,
63
+ **kwargs: Any,
64
+ ):
65
+ """Initialize the sentence_transformer."""
66
+ super().__init__(
67
+ project=project,
68
+ location=location,
69
+ credentials=credentials,
70
+ request_parallelism=request_parallelism,
71
+ max_retries=max_retries,
72
+ model_name=model_name,
73
+ **kwargs,
74
+ )
75
+ self.instance["max_batch_size"] = kwargs.get("max_batch_size", _MAX_BATCH_SIZE)
76
+ self.instance["batch_size"] = self.instance["max_batch_size"]
77
+ self.instance["min_batch_size"] = kwargs.get("min_batch_size", _MIN_BATCH_SIZE)
78
+ self.instance["min_good_batch_size"] = self.instance["min_batch_size"]
79
+ self.instance["lock"] = threading.Lock()
80
+ self.instance["batch_size_validated"] = False
81
+ self.instance["task_executor"] = ThreadPoolExecutor(
82
+ max_workers=request_parallelism
83
+ )
84
+ self.instance[
85
+ "embeddings_task_type_supported"
86
+ ] = not self.client._endpoint_name.endswith("/textembedding-gecko@001")
87
+
88
+ @staticmethod
89
+ def _split_by_punctuation(text: str) -> List[str]:
90
+ """Splits a string by punctuation and whitespace characters."""
91
+ split_by = string.punctuation + "\t\n "
92
+ pattern = f"([{split_by}])"
93
+ # Using re.split to split the text based on the pattern
94
+ return [segment for segment in re.split(pattern, text) if segment]
95
+
96
+ @staticmethod
97
+ def _prepare_batches(texts: List[str], batch_size: int) -> List[List[str]]:
98
+ """Splits texts in batches based on current maximum batch size
99
+ and maximum tokens per request.
100
+ """
101
+ text_index = 0
102
+ texts_len = len(texts)
103
+ batch_token_len = 0
104
+ batches: List[List[str]] = []
105
+ current_batch: List[str] = []
106
+ if texts_len == 0:
107
+ return []
108
+ while text_index < texts_len:
109
+ current_text = texts[text_index]
110
+ # Number of tokens per a text is conservatively estimated
111
+ # as 2 times number of words, punctuation and whitespace characters.
112
+ # Using `count_tokens` API will make batching too expensive.
113
+ # Utilizing a tokenizer, would add a dependency that would not
114
+ # necessarily be reused by the application using this class.
115
+ current_text_token_cnt = (
116
+ len(VertexAIEmbeddings._split_by_punctuation(current_text)) * 2
117
+ )
118
+ end_of_batch = False
119
+ if current_text_token_cnt > _MAX_TOKENS_PER_BATCH:
120
+ # Current text is too big even for a single batch.
121
+ # Such request will fail, but we still make a batch
122
+ # so that the app can get the error from the API.
123
+ if len(current_batch) > 0:
124
+ # Adding current batch if not empty.
125
+ batches.append(current_batch)
126
+ current_batch = [current_text]
127
+ text_index += 1
128
+ end_of_batch = True
129
+ elif (
130
+ batch_token_len + current_text_token_cnt > _MAX_TOKENS_PER_BATCH
131
+ or len(current_batch) == batch_size
132
+ ):
133
+ end_of_batch = True
134
+ else:
135
+ if text_index == texts_len - 1:
136
+ # Last element - even though the batch may be not big,
137
+ # we still need to make it.
138
+ end_of_batch = True
139
+ batch_token_len += current_text_token_cnt
140
+ current_batch.append(current_text)
141
+ text_index += 1
142
+ if end_of_batch:
143
+ batches.append(current_batch)
144
+ current_batch = []
145
+ batch_token_len = 0
146
+ return batches
147
+
148
+ def _get_embeddings_with_retry(
149
+ self, texts: List[str], embeddings_type: Optional[str] = None
150
+ ) -> List[List[float]]:
151
+ """Makes a Vertex AI model request with retry logic."""
152
+ from google.api_core.exceptions import (
153
+ Aborted,
154
+ DeadlineExceeded,
155
+ ResourceExhausted,
156
+ ServiceUnavailable,
157
+ )
158
+
159
+ errors = [
160
+ ResourceExhausted,
161
+ ServiceUnavailable,
162
+ Aborted,
163
+ DeadlineExceeded,
164
+ ]
165
+ retry_decorator = create_base_retry_decorator(
166
+ error_types=errors,
167
+ max_retries=self.max_retries,
168
+ )
169
+
170
+ @retry_decorator
171
+ def _completion_with_retry(texts_to_process: List[str]) -> Any:
172
+ if embeddings_type and self.instance["embeddings_task_type_supported"]:
173
+ from vertexai.language_models import TextEmbeddingInput
174
+
175
+ requests = [
176
+ TextEmbeddingInput(text=t, task_type=embeddings_type)
177
+ for t in texts_to_process
178
+ ]
179
+ else:
180
+ requests = texts_to_process
181
+ embeddings = self.client.get_embeddings(requests)
182
+ return [embs.values for embs in embeddings]
183
+
184
+ return _completion_with_retry(texts)
185
+
186
+ def _prepare_and_validate_batches(
187
+ self, texts: List[str], embeddings_type: Optional[str] = None
188
+ ) -> Tuple[List[List[float]], List[List[str]]]:
189
+ """Prepares text batches with one-time validation of batch size.
190
+ Batch size varies between GCP regions and individual project quotas.
191
+ # Returns embeddings of the first text batch that went through,
192
+ # and text batches for the rest of the texts.
193
+ """
194
+ from google.api_core.exceptions import InvalidArgument
195
+
196
+ batches = VertexAIEmbeddings._prepare_batches(
197
+ texts, self.instance["batch_size"]
198
+ )
199
+ # If batch size if less or equal to one that went through before,
200
+ # then keep batches as they are.
201
+ if len(batches[0]) <= self.instance["min_good_batch_size"]:
202
+ return [], batches
203
+ with self.instance["lock"]:
204
+ # If largest possible batch size was validated
205
+ # while waiting for the lock, then check for rebuilding
206
+ # our batches, and return.
207
+ if self.instance["batch_size_validated"]:
208
+ if len(batches[0]) <= self.instance["batch_size"]:
209
+ return [], batches
210
+ else:
211
+ return [], VertexAIEmbeddings._prepare_batches(
212
+ texts, self.instance["batch_size"]
213
+ )
214
+ # Figure out largest possible batch size by trying to push
215
+ # batches and lowering their size in half after every failure.
216
+ first_batch = batches[0]
217
+ first_result = []
218
+ had_failure = False
219
+ while True:
220
+ try:
221
+ first_result = self._get_embeddings_with_retry(
222
+ first_batch, embeddings_type
223
+ )
224
+ break
225
+ except InvalidArgument:
226
+ had_failure = True
227
+ first_batch_len = len(first_batch)
228
+ if first_batch_len == self.instance["min_batch_size"]:
229
+ raise
230
+ first_batch_len = max(
231
+ self.instance["min_batch_size"], int(first_batch_len / 2)
232
+ )
233
+ first_batch = first_batch[:first_batch_len]
234
+ first_batch_len = len(first_batch)
235
+ self.instance["min_good_batch_size"] = max(
236
+ self.instance["min_good_batch_size"], first_batch_len
237
+ )
238
+ # If had a failure and recovered
239
+ # or went through with the max size, then it's a legit batch size.
240
+ if had_failure or first_batch_len == self.instance["max_batch_size"]:
241
+ self.instance["batch_size"] = first_batch_len
242
+ self.instance["batch_size_validated"] = True
243
+ # If batch size was updated,
244
+ # rebuild batches with the new batch size
245
+ # (texts that went through are excluded here).
246
+ if first_batch_len != self.instance["max_batch_size"]:
247
+ batches = VertexAIEmbeddings._prepare_batches(
248
+ texts[first_batch_len:], self.instance["batch_size"]
249
+ )
250
+ else:
251
+ # Still figuring out max batch size.
252
+ batches = batches[1:]
253
+ # Returning embeddings of the first text batch that went through,
254
+ # and text batches for the rest of texts.
255
+ return first_result, batches
256
+
257
+ def embed(
258
+ self,
259
+ texts: List[str],
260
+ batch_size: int = 0,
261
+ embeddings_task_type: Optional[
262
+ Literal[
263
+ "RETRIEVAL_QUERY",
264
+ "RETRIEVAL_DOCUMENT",
265
+ "SEMANTIC_SIMILARITY",
266
+ "CLASSIFICATION",
267
+ "CLUSTERING",
268
+ ]
269
+ ] = None,
270
+ ) -> List[List[float]]:
271
+ """Embed a list of strings.
272
+
273
+ Args:
274
+ texts: List[str] The list of strings to embed.
275
+ batch_size: [int] The batch size of embeddings to send to the model.
276
+ If zero, then the largest batch size will be detected dynamically
277
+ at the first request, starting from 250, down to 5.
278
+ embeddings_task_type: [str] optional embeddings task type,
279
+ one of the following
280
+ RETRIEVAL_QUERY - Text is a query
281
+ in a search/retrieval setting.
282
+ RETRIEVAL_DOCUMENT - Text is a document
283
+ in a search/retrieval setting.
284
+ SEMANTIC_SIMILARITY - Embeddings will be used
285
+ for Semantic Textual Similarity (STS).
286
+ CLASSIFICATION - Embeddings will be used for classification.
287
+ CLUSTERING - Embeddings will be used for clustering.
288
+
289
+ Returns:
290
+ List of embeddings, one for each text.
291
+ """
292
+ if len(texts) == 0:
293
+ return []
294
+ embeddings: List[List[float]] = []
295
+ first_batch_result: List[List[float]] = []
296
+ if batch_size > 0:
297
+ # Fixed batch size.
298
+ batches = VertexAIEmbeddings._prepare_batches(texts, batch_size)
299
+ else:
300
+ # Dynamic batch size, starting from 250 at the first call.
301
+ first_batch_result, batches = self._prepare_and_validate_batches(
302
+ texts, embeddings_task_type
303
+ )
304
+ # First batch result may have some embeddings already.
305
+ # In such case, batches have texts that were not processed yet.
306
+ embeddings.extend(first_batch_result)
307
+ tasks = []
308
+ if self.show_progress_bar:
309
+ try:
310
+ from tqdm import tqdm
311
+
312
+ iter_ = tqdm(batches, desc="VertexAIEmbeddings")
313
+ except ImportError:
314
+ logger.warning(
315
+ "Unable to show progress bar because tqdm could not be imported. "
316
+ "Please install with `pip install tqdm`."
317
+ )
318
+ iter_ = batches
319
+ else:
320
+ iter_ = batches
321
+ for batch in iter_:
322
+ tasks.append(
323
+ self.instance["task_executor"].submit(
324
+ self._get_embeddings_with_retry,
325
+ texts=batch,
326
+ embeddings_type=embeddings_task_type,
327
+ )
328
+ )
329
+ if len(tasks) > 0:
330
+ wait(tasks)
331
+ for t in tasks:
332
+ embeddings.extend(t.result())
333
+ return embeddings
334
+
335
+ def embed_documents(
336
+ self, texts: List[str], batch_size: int = 0
337
+ ) -> List[List[float]]:
338
+ """Embed a list of documents.
339
+
340
+ Args:
341
+ texts: List[str] The list of texts to embed.
342
+ batch_size: [int] The batch size of embeddings to send to the model.
343
+ If zero, then the largest batch size will be detected dynamically
344
+ at the first request, starting from 250, down to 5.
345
+
346
+ Returns:
347
+ List of embeddings, one for each text.
348
+ """
349
+ return self.embed(texts, batch_size, "RETRIEVAL_DOCUMENT")
350
+
351
+ def embed_query(self, text: str) -> List[float]:
352
+ """Embed a text.
353
+
354
+ Args:
355
+ text: The text to embed.
356
+
357
+ Returns:
358
+ Embedding for the text.
359
+ """
360
+ embeddings = self.embed([text], 1, "RETRIEVAL_QUERY")
361
+ return embeddings[0]
python/user_packages/Python313/site-packages/langchain_community/embeddings/volcengine.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from langchain_core.embeddings import Embeddings
7
+ from langchain_core.utils import get_from_dict_or_env, pre_init
8
+ from pydantic import BaseModel
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class VolcanoEmbeddings(BaseModel, Embeddings):
14
+ """`Volcengine Embeddings` embedding models."""
15
+
16
+ volcano_ak: Optional[str] = None
17
+ """volcano access key
18
+ learn more from: https://www.volcengine.com/docs/6459/76491#ak-sk"""
19
+
20
+ volcano_sk: Optional[str] = None
21
+ """volcano secret key
22
+ learn more from: https://www.volcengine.com/docs/6459/76491#ak-sk"""
23
+
24
+ host: str = "maas-api.ml-platform-cn-beijing.volces.com"
25
+ """host
26
+ learn more from https://www.volcengine.com/docs/82379/1174746"""
27
+ region: str = "cn-beijing"
28
+ """region
29
+ learn more from https://www.volcengine.com/docs/82379/1174746"""
30
+
31
+ model: str = "bge-large-zh"
32
+ """Model name
33
+ you could get from https://www.volcengine.com/docs/82379/1174746
34
+ for now, we support bge_large_zh
35
+ """
36
+
37
+ version: str = "1.0"
38
+ """ model version """
39
+
40
+ chunk_size: int = 100
41
+ """Chunk size when multiple texts are input"""
42
+
43
+ client: Any
44
+ """volcano client"""
45
+
46
+ @pre_init
47
+ def validate_environment(cls, values: Dict) -> Dict:
48
+ """
49
+ Validate whether volcano_ak and volcano_sk in the environment variables or
50
+ configuration file are available or not.
51
+
52
+ init volcano embedding client with `ak`, `sk`, `host`, `region`
53
+
54
+ Args:
55
+
56
+ values: a dictionary containing configuration information, must include the
57
+ fields of volcano_ak and volcano_sk
58
+ Returns:
59
+
60
+ a dictionary containing configuration information. If volcano_ak and
61
+ volcano_sk are not provided in the environment variables or configuration
62
+ file,the original values will be returned; otherwise, values containing
63
+ volcano_ak and volcano_sk will be returned.
64
+ Raises:
65
+
66
+ ValueError: volcengine package not found, please install it with
67
+ `pip install volcengine`
68
+ """
69
+ values["volcano_ak"] = get_from_dict_or_env(
70
+ values,
71
+ "volcano_ak",
72
+ "VOLC_ACCESSKEY",
73
+ )
74
+ values["volcano_sk"] = get_from_dict_or_env(
75
+ values,
76
+ "volcano_sk",
77
+ "VOLC_SECRETKEY",
78
+ )
79
+
80
+ try:
81
+ from volcengine.maas import MaasService
82
+
83
+ client = MaasService(values["host"], values["region"])
84
+ client.set_ak(values["volcano_ak"])
85
+ client.set_sk(values["volcano_sk"])
86
+ values["client"] = client
87
+ except ImportError:
88
+ raise ImportError(
89
+ "volcengine package not found, please install it with "
90
+ "`pip install volcengine`"
91
+ )
92
+ return values
93
+
94
+ def embed_query(self, text: str) -> List[float]:
95
+ return self.embed_documents([text])[0]
96
+
97
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
98
+ """
99
+ Embeds a list of text documents using the AutoVOT algorithm.
100
+
101
+ Args:
102
+ texts (List[str]): A list of text documents to embed.
103
+
104
+ Returns:
105
+ List[List[float]]: A list of embeddings for each document in the input list.
106
+ Each embedding is represented as a list of float values.
107
+ """
108
+ text_in_chunks = [
109
+ texts[i : i + self.chunk_size]
110
+ for i in range(0, len(texts), self.chunk_size)
111
+ ]
112
+ lst = []
113
+ for chunk in text_in_chunks:
114
+ req = {
115
+ "model": {
116
+ "name": self.model,
117
+ "version": self.version,
118
+ },
119
+ "input": chunk,
120
+ }
121
+ try:
122
+ from volcengine.maas import MaasException
123
+
124
+ resp = self.client.embeddings(req)
125
+ lst.extend([res["embedding"] for res in resp["data"]])
126
+ except MaasException as e:
127
+ raise ValueError(f"embed by volcengine Error: {e}")
128
+ return lst
python/user_packages/Python313/site-packages/langchain_community/embeddings/voyageai.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from typing import (
6
+ Any,
7
+ Callable,
8
+ Dict,
9
+ List,
10
+ Optional,
11
+ Tuple,
12
+ Union,
13
+ cast,
14
+ )
15
+
16
+ import requests
17
+ from langchain_core._api.deprecation import deprecated
18
+ from langchain_core.embeddings import Embeddings
19
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
20
+ from pydantic import BaseModel, ConfigDict, SecretStr, model_validator
21
+ from tenacity import (
22
+ before_sleep_log,
23
+ retry,
24
+ stop_after_attempt,
25
+ wait_exponential,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ def _create_retry_decorator(embeddings: VoyageEmbeddings) -> Callable[[Any], Any]:
32
+ min_seconds = 4
33
+ max_seconds = 10
34
+ # Wait 2^x * 1 second between each retry starting with
35
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
36
+ return retry(
37
+ reraise=True,
38
+ stop=stop_after_attempt(embeddings.max_retries),
39
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
40
+ before_sleep=before_sleep_log(logger, logging.WARNING),
41
+ )
42
+
43
+
44
+ def _check_response(response: dict) -> dict:
45
+ if "data" not in response:
46
+ raise RuntimeError(f"Voyage API Error. Message: {json.dumps(response)}")
47
+ return response
48
+
49
+
50
+ def embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) -> Any:
51
+ """Use tenacity to retry the embedding call."""
52
+ retry_decorator = _create_retry_decorator(embeddings)
53
+
54
+ @retry_decorator
55
+ def _embed_with_retry(**kwargs: Any) -> Any:
56
+ response = requests.post(**kwargs)
57
+ return _check_response(response.json())
58
+
59
+ return _embed_with_retry(**kwargs)
60
+
61
+
62
+ @deprecated(
63
+ since="0.0.29",
64
+ removal="1.0",
65
+ alternative_import="langchain_voyageai.VoyageAIEmbeddings",
66
+ )
67
+ class VoyageEmbeddings(BaseModel, Embeddings):
68
+ """Voyage embedding models.
69
+
70
+ To use, you should have the environment variable ``VOYAGE_API_KEY`` set with
71
+ your API key or pass it as a named parameter to the constructor.
72
+
73
+ Example:
74
+ .. code-block:: python
75
+
76
+ from langchain_community.embeddings import VoyageEmbeddings
77
+
78
+ voyage = VoyageEmbeddings(voyage_api_key="your-api-key", model="voyage-2")
79
+ text = "This is a test query."
80
+ query_result = voyage.embed_query(text)
81
+ """
82
+
83
+ model: str
84
+ voyage_api_base: str = "https://api.voyageai.com/v1/embeddings"
85
+ voyage_api_key: Optional[SecretStr] = None
86
+ batch_size: int
87
+ """Maximum number of texts to embed in each API request."""
88
+ max_retries: int = 6
89
+ """Maximum number of retries to make when generating."""
90
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = None
91
+ """Timeout in seconds for the API request."""
92
+ show_progress_bar: bool = False
93
+ """Whether to show a progress bar when embedding. Must have tqdm installed if set
94
+ to True."""
95
+ truncation: bool = True
96
+ """Whether to truncate the input texts to fit within the context length.
97
+
98
+ If True, over-length input texts will be truncated to fit within the context
99
+ length, before vectorized by the embedding model. If False, an error will be
100
+ raised if any given text exceeds the context length."""
101
+
102
+ model_config = ConfigDict(
103
+ extra="forbid",
104
+ )
105
+
106
+ @model_validator(mode="before")
107
+ @classmethod
108
+ def validate_environment(cls, values: Dict) -> Any:
109
+ """Validate that api key and python package exists in environment."""
110
+ values["voyage_api_key"] = convert_to_secret_str(
111
+ get_from_dict_or_env(values, "voyage_api_key", "VOYAGE_API_KEY")
112
+ )
113
+
114
+ if "model" not in values:
115
+ values["model"] = "voyage-01"
116
+ logger.warning(
117
+ "model will become a required arg for VoyageAIEmbeddings, "
118
+ "we recommend to specify it when using this class. "
119
+ "Currently the default is set to voyage-01."
120
+ )
121
+
122
+ if "batch_size" not in values:
123
+ values["batch_size"] = (
124
+ 72
125
+ if "model" in values and (values["model"] in ["voyage-2", "voyage-02"])
126
+ else 7
127
+ )
128
+
129
+ return values
130
+
131
+ def _invocation_params(
132
+ self, input: List[str], input_type: Optional[str] = None
133
+ ) -> Dict:
134
+ api_key = cast(SecretStr, self.voyage_api_key).get_secret_value()
135
+ params: Dict = {
136
+ "url": self.voyage_api_base,
137
+ "headers": {"Authorization": f"Bearer {api_key}"},
138
+ "json": {
139
+ "model": self.model,
140
+ "input": input,
141
+ "input_type": input_type,
142
+ "truncation": self.truncation,
143
+ },
144
+ "timeout": self.request_timeout,
145
+ }
146
+ return params
147
+
148
+ def _get_embeddings(
149
+ self,
150
+ texts: List[str],
151
+ batch_size: Optional[int] = None,
152
+ input_type: Optional[str] = None,
153
+ ) -> List[List[float]]:
154
+ embeddings: List[List[float]] = []
155
+
156
+ if batch_size is None:
157
+ batch_size = self.batch_size
158
+
159
+ if self.show_progress_bar:
160
+ try:
161
+ from tqdm.auto import tqdm
162
+ except ImportError as e:
163
+ raise ImportError(
164
+ "Must have tqdm installed if `show_progress_bar` is set to True. "
165
+ "Please install with `pip install tqdm`."
166
+ ) from e
167
+
168
+ _iter = tqdm(range(0, len(texts), batch_size))
169
+ else:
170
+ _iter = range(0, len(texts), batch_size)
171
+
172
+ if input_type and input_type not in ["query", "document"]:
173
+ raise ValueError(
174
+ f"input_type {input_type} is invalid. Options: None, 'query', "
175
+ "'document'."
176
+ )
177
+
178
+ for i in _iter:
179
+ response = embed_with_retry(
180
+ self,
181
+ **self._invocation_params(
182
+ input=texts[i : i + batch_size], input_type=input_type
183
+ ),
184
+ )
185
+ embeddings.extend(r["embedding"] for r in response["data"])
186
+
187
+ return embeddings
188
+
189
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
190
+ """Call out to Voyage Embedding endpoint for embedding search docs.
191
+
192
+ Args:
193
+ texts: The list of texts to embed.
194
+
195
+ Returns:
196
+ List of embeddings, one for each text.
197
+ """
198
+ return self._get_embeddings(
199
+ texts, batch_size=self.batch_size, input_type="document"
200
+ )
201
+
202
+ def embed_query(self, text: str) -> List[float]:
203
+ """Call out to Voyage Embedding endpoint for embedding query text.
204
+
205
+ Args:
206
+ text: The text to embed.
207
+
208
+ Returns:
209
+ Embedding for the text.
210
+ """
211
+ return self._get_embeddings(
212
+ [text], batch_size=self.batch_size, input_type="query"
213
+ )[0]
214
+
215
+ def embed_general_texts(
216
+ self, texts: List[str], *, input_type: Optional[str] = None
217
+ ) -> List[List[float]]:
218
+ """Call out to Voyage Embedding endpoint for embedding general text.
219
+
220
+ Args:
221
+ texts: The list of texts to embed.
222
+ input_type: Type of the input text. Default to None, meaning the type is
223
+ unspecified. Other options: query, document.
224
+
225
+ Returns:
226
+ Embedding for the text.
227
+ """
228
+ return self._get_embeddings(
229
+ texts, batch_size=self.batch_size, input_type=input_type
230
+ )
python/user_packages/Python313/site-packages/langchain_community/embeddings/xinference.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper around Xinference embedding models."""
2
+
3
+ from typing import Any, List, Optional
4
+
5
+ from langchain_core.embeddings import Embeddings
6
+
7
+
8
+ class XinferenceEmbeddings(Embeddings):
9
+ """Xinference embedding models.
10
+
11
+ To use, you should have the xinference library installed:
12
+
13
+ .. code-block:: bash
14
+
15
+ pip install xinference
16
+
17
+ If you're simply using the services provided by Xinference, you can utilize the xinference_client package:
18
+
19
+ .. code-block:: bash
20
+
21
+ pip install xinference_client
22
+
23
+ Check out: https://github.com/xorbitsai/inference
24
+ To run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers.
25
+
26
+ Example:
27
+ To start a local instance of Xinference, run
28
+
29
+ .. code-block:: bash
30
+
31
+ $ xinference
32
+
33
+ You can also deploy Xinference in a distributed cluster. Here are the steps:
34
+
35
+ Starting the supervisor:
36
+
37
+ .. code-block:: bash
38
+
39
+ $ xinference-supervisor
40
+
41
+ If you're simply using the services provided by Xinference, you can utilize the xinference_client package:
42
+
43
+ .. code-block:: bash
44
+
45
+ pip install xinference_client
46
+
47
+ Starting the worker:
48
+
49
+ .. code-block:: bash
50
+
51
+ $ xinference-worker
52
+
53
+ Then, launch a model using command line interface (CLI).
54
+
55
+ Example:
56
+
57
+ .. code-block:: bash
58
+
59
+ $ xinference launch -n orca -s 3 -q q4_0
60
+
61
+ It will return a model UID. Then you can use Xinference Embedding with LangChain.
62
+
63
+ Example:
64
+
65
+ .. code-block:: python
66
+
67
+ from langchain_community.embeddings import XinferenceEmbeddings
68
+
69
+ xinference = XinferenceEmbeddings(
70
+ server_url="http://0.0.0.0:9997",
71
+ model_uid = {model_uid} # replace model_uid with the model UID return from launching the model
72
+ )
73
+
74
+ """ # noqa: E501
75
+
76
+ client: Any
77
+ server_url: Optional[str]
78
+ """URL of the xinference server"""
79
+ model_uid: Optional[str]
80
+ """UID of the launched model"""
81
+
82
+ def __init__(
83
+ self, server_url: Optional[str] = None, model_uid: Optional[str] = None
84
+ ):
85
+ try:
86
+ from xinference.client import RESTfulClient
87
+ except ImportError:
88
+ try:
89
+ from xinference_client import RESTfulClient
90
+ except ImportError as e:
91
+ raise ImportError(
92
+ "Could not import RESTfulClient from xinference. Please install it"
93
+ " with `pip install xinference` or `pip install xinference_client`."
94
+ ) from e
95
+
96
+ super().__init__()
97
+
98
+ if server_url is None:
99
+ raise ValueError("Please provide server URL")
100
+
101
+ if model_uid is None:
102
+ raise ValueError("Please provide the model UID")
103
+
104
+ self.server_url = server_url
105
+
106
+ self.model_uid = model_uid
107
+
108
+ self.client = RESTfulClient(server_url)
109
+
110
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
111
+ """Embed a list of documents using Xinference.
112
+ Args:
113
+ texts: The list of texts to embed.
114
+ Returns:
115
+ List of embeddings, one for each text.
116
+ """
117
+
118
+ model = self.client.get_model(self.model_uid)
119
+
120
+ embeddings = [
121
+ model.create_embedding(text)["data"][0]["embedding"] for text in texts
122
+ ]
123
+ return [list(map(float, e)) for e in embeddings]
124
+
125
+ def embed_query(self, text: str) -> List[float]:
126
+ """Embed a query of documents using Xinference.
127
+ Args:
128
+ text: The text to embed.
129
+ Returns:
130
+ Embeddings for the text.
131
+ """
132
+
133
+ model = self.client.get_model(self.model_uid)
134
+
135
+ embedding_res = model.create_embedding(text)
136
+
137
+ embedding = embedding_res["data"][0]["embedding"]
138
+
139
+ return list(map(float, embedding))
python/user_packages/Python313/site-packages/langchain_community/embeddings/yandex.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper around YandexGPT embedding models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from typing import Any, Callable, Dict, List, Sequence
8
+
9
+ from langchain_core.embeddings import Embeddings
10
+ from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
11
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
12
+ from tenacity import (
13
+ before_sleep_log,
14
+ retry,
15
+ retry_if_exception_type,
16
+ stop_after_attempt,
17
+ wait_exponential,
18
+ )
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class YandexGPTEmbeddings(BaseModel, Embeddings):
24
+ """YandexGPT Embeddings models.
25
+
26
+ To use, you should have the ``yandexcloud`` python package installed.
27
+
28
+ There are two authentication options for the service account
29
+ with the ``ai.languageModels.user`` role:
30
+ - You can specify the token in a constructor parameter `iam_token`
31
+ or in an environment variable `YC_IAM_TOKEN`.
32
+ - You can specify the key in a constructor parameter `api_key`
33
+ or in an environment variable `YC_API_KEY`.
34
+
35
+ To use the default model specify the folder ID in a parameter `folder_id`
36
+ or in an environment variable `YC_FOLDER_ID`.
37
+
38
+ Example:
39
+ .. code-block:: python
40
+
41
+ from langchain_community.embeddings.yandex import YandexGPTEmbeddings
42
+ embeddings = YandexGPTEmbeddings(iam_token="t1.9eu...", folder_id=<folder-id>)
43
+ """ # noqa: E501
44
+
45
+ iam_token: SecretStr = "" # type: ignore[assignment]
46
+ """Yandex Cloud IAM token for service account
47
+ with the `ai.languageModels.user` role"""
48
+ api_key: SecretStr = "" # type: ignore[assignment]
49
+ """Yandex Cloud Api Key for service account
50
+ with the `ai.languageModels.user` role"""
51
+ model_uri: str = Field(default="", alias="query_model_uri")
52
+ """Query model uri to use."""
53
+ doc_model_uri: str = ""
54
+ """Doc model uri to use."""
55
+ folder_id: str = ""
56
+ """Yandex Cloud folder ID"""
57
+ doc_model_name: str = "text-search-doc"
58
+ """Doc model name to use."""
59
+ model_name: str = Field(default="text-search-query", alias="query_model_name")
60
+ """Query model name to use."""
61
+ model_version: str = "latest"
62
+ """Model version to use."""
63
+ url: str = "llm.api.cloud.yandex.net:443"
64
+ """The url of the API."""
65
+ max_retries: int = 6
66
+ """Maximum number of retries to make when generating."""
67
+ sleep_interval: float = 0.0
68
+ """Delay between API requests"""
69
+ disable_request_logging: bool = False
70
+ """YandexGPT API logs all request data by default.
71
+ If you provide personal data, confidential information, disable logging."""
72
+ grpc_metadata: Sequence
73
+
74
+ model_config = ConfigDict(populate_by_name=True, protected_namespaces=())
75
+
76
+ @pre_init
77
+ def validate_environment(cls, values: Dict) -> Dict:
78
+ """Validate that iam token exists in environment."""
79
+
80
+ iam_token = convert_to_secret_str(
81
+ get_from_dict_or_env(values, "iam_token", "YC_IAM_TOKEN", "")
82
+ )
83
+ values["iam_token"] = iam_token
84
+ api_key = convert_to_secret_str(
85
+ get_from_dict_or_env(values, "api_key", "YC_API_KEY", "")
86
+ )
87
+ values["api_key"] = api_key
88
+ folder_id = get_from_dict_or_env(values, "folder_id", "YC_FOLDER_ID", "")
89
+ values["folder_id"] = folder_id
90
+ if api_key.get_secret_value() == "" and iam_token.get_secret_value() == "":
91
+ raise ValueError("Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.")
92
+ if values["iam_token"]:
93
+ values["grpc_metadata"] = [
94
+ ("authorization", f"Bearer {values['iam_token'].get_secret_value()}")
95
+ ]
96
+ if values["folder_id"]:
97
+ values["grpc_metadata"].append(("x-folder-id", values["folder_id"]))
98
+ else:
99
+ values["grpc_metadata"] = [
100
+ ("authorization", f"Api-Key {values['api_key'].get_secret_value()}"),
101
+ ]
102
+
103
+ if not values.get("doc_model_uri"):
104
+ if values["folder_id"] == "":
105
+ raise ValueError("'doc_model_uri' or 'folder_id' must be provided.")
106
+ values["doc_model_uri"] = (
107
+ f"emb://{values['folder_id']}/{values['doc_model_name']}/{values['model_version']}"
108
+ )
109
+ if not values.get("model_uri"):
110
+ if values["folder_id"] == "":
111
+ raise ValueError("'model_uri' or 'folder_id' must be provided.")
112
+ values["model_uri"] = (
113
+ f"emb://{values['folder_id']}/{values['model_name']}/{values['model_version']}"
114
+ )
115
+ if values["disable_request_logging"]:
116
+ values["grpc_metadata"].append(
117
+ (
118
+ "x-data-logging-enabled",
119
+ "false",
120
+ )
121
+ )
122
+ return values
123
+
124
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
125
+ """Embed documents using a YandexGPT embeddings models.
126
+
127
+ Args:
128
+ texts: The list of texts to embed.
129
+
130
+ Returns:
131
+ List of embeddings, one for each text.
132
+ """
133
+
134
+ return _embed_with_retry(self, texts=texts)
135
+
136
+ def embed_query(self, text: str) -> List[float]:
137
+ """Embed a query using a YandexGPT embeddings models.
138
+
139
+ Args:
140
+ text: The text to embed.
141
+
142
+ Returns:
143
+ Embeddings for the text.
144
+ """
145
+ return _embed_with_retry(self, texts=[text], embed_query=True)[0]
146
+
147
+
148
+ def _create_retry_decorator(llm: YandexGPTEmbeddings) -> Callable[[Any], Any]:
149
+ from grpc import RpcError
150
+
151
+ min_seconds = 1
152
+ max_seconds = 60
153
+ return retry(
154
+ reraise=True,
155
+ stop=stop_after_attempt(llm.max_retries),
156
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
157
+ retry=(retry_if_exception_type((RpcError))),
158
+ before_sleep=before_sleep_log(logger, logging.WARNING),
159
+ )
160
+
161
+
162
+ def _embed_with_retry(llm: YandexGPTEmbeddings, **kwargs: Any) -> list[list[float]]:
163
+ """Use tenacity to retry the embedding call."""
164
+ retry_decorator = _create_retry_decorator(llm)
165
+
166
+ @retry_decorator
167
+ def _completion_with_retry(**_kwargs: Any) -> list[list[float]]:
168
+ return _make_request(llm, **_kwargs)
169
+
170
+ return _completion_with_retry(**kwargs)
171
+
172
+
173
+ def _make_request(
174
+ self: YandexGPTEmbeddings, texts: List[str], **kwargs: Any
175
+ ) -> list[list[float]]:
176
+ try:
177
+ import grpc
178
+
179
+ try:
180
+ from yandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2 import ( # noqa: E501
181
+ TextEmbeddingRequest,
182
+ )
183
+ from yandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2_grpc import ( # noqa: E501
184
+ EmbeddingsServiceStub,
185
+ )
186
+ except ModuleNotFoundError:
187
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501
188
+ TextEmbeddingRequest,
189
+ )
190
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501
191
+ EmbeddingsServiceStub,
192
+ )
193
+ except ImportError as e:
194
+ raise ImportError(
195
+ "Please install YandexCloud SDK with `pip install yandexcloud` \
196
+ or upgrade it to recent version."
197
+ ) from e
198
+ result = []
199
+ channel_credentials = grpc.ssl_channel_credentials()
200
+ channel = grpc.secure_channel(self.url, channel_credentials)
201
+ # Use the query model if embed_query is True
202
+ if kwargs.get("embed_query"):
203
+ model_uri = self.model_uri
204
+ else:
205
+ model_uri = self.doc_model_uri
206
+
207
+ for text in texts:
208
+ request = TextEmbeddingRequest(model_uri=model_uri, text=text)
209
+ stub = EmbeddingsServiceStub(channel)
210
+ res = stub.TextEmbedding(request, metadata=self.grpc_metadata)
211
+ result.append(list(res.embedding))
212
+ time.sleep(self.sleep_interval)
213
+
214
+ return result
python/user_packages/Python313/site-packages/langchain_community/embeddings/zhipuai.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ from langchain_core.embeddings import Embeddings
4
+ from langchain_core.utils import get_from_dict_or_env
5
+ from pydantic import BaseModel, Field, model_validator
6
+
7
+
8
+ class ZhipuAIEmbeddings(BaseModel, Embeddings):
9
+ """ZhipuAI embedding model integration.
10
+
11
+ Setup:
12
+
13
+ To use, you should have the ``zhipuai`` python package installed, and the
14
+ environment variable ``ZHIPU_API_KEY`` set with your API KEY.
15
+
16
+ More instructions about ZhipuAi Embeddings, you can get it
17
+ from https://open.bigmodel.cn/dev/api#vector
18
+
19
+ .. code-block:: bash
20
+
21
+ pip install -U zhipuai
22
+ export ZHIPU_API_KEY="your-api-key"
23
+
24
+ Key init args — completion params:
25
+ model: Optional[str]
26
+ Name of ZhipuAI model to use.
27
+ api_key: str
28
+ Automatically inferred from env var `ZHIPU_API_KEY` if not provided.
29
+
30
+ See full list of supported init args and their descriptions in the params section.
31
+
32
+ Instantiate:
33
+
34
+ .. code-block:: python
35
+
36
+ from langchain_community.embeddings import ZhipuAIEmbeddings
37
+
38
+ embed = ZhipuAIEmbeddings(
39
+ model="embedding-2",
40
+ # api_key="...",
41
+ )
42
+
43
+ Embed single text:
44
+ .. code-block:: python
45
+
46
+ input_text = "The meaning of life is 42"
47
+ embed.embed_query(input_text)
48
+
49
+ .. code-block:: python
50
+
51
+ [-0.003832892, 0.049372625, -0.035413884, -0.019301128, 0.0068899863, 0.01248398, -0.022153955, 0.006623926, 0.00778216, 0.009558191, ...]
52
+
53
+
54
+ Embed multiple text:
55
+ .. code-block:: python
56
+
57
+ input_texts = ["This is a test query1.", "This is a test query2."]
58
+ embed.embed_documents(input_texts)
59
+
60
+ .. code-block:: python
61
+
62
+ [
63
+ [0.0083934665, 0.037985895, -0.06684559, -0.039616987, 0.015481004, -0.023952313, ...],
64
+ [-0.02713102, -0.005470169, 0.032321047, 0.042484466, 0.023290444, 0.02170547, ...]
65
+ ]
66
+ """ # noqa: E501
67
+
68
+ client: Any = Field(default=None, exclude=True) #: :meta private:
69
+ model: str = Field(default="embedding-2")
70
+ """Model name"""
71
+ api_key: str
72
+ """Automatically inferred from env var `ZHIPU_API_KEY` if not provided."""
73
+ dimensions: Optional[int] = None
74
+ """The number of dimensions the resulting output embeddings should have.
75
+
76
+ Only supported in `embedding-3` and later models.
77
+ """
78
+
79
+ @model_validator(mode="before")
80
+ @classmethod
81
+ def validate_environment(cls, values: Dict) -> Any:
82
+ """Validate that auth token exists in environment."""
83
+ values["api_key"] = get_from_dict_or_env(values, "api_key", "ZHIPUAI_API_KEY")
84
+ try:
85
+ from zhipuai import ZhipuAI
86
+
87
+ values["client"] = ZhipuAI(api_key=values["api_key"])
88
+ except ImportError:
89
+ raise ImportError(
90
+ "Could not import zhipuai python package."
91
+ "Please install it with `pip install zhipuai`."
92
+ )
93
+ return values
94
+
95
+ def embed_query(self, text: str) -> List[float]:
96
+ """
97
+ Embeds a text using the AutoVOT algorithm.
98
+
99
+ Args:
100
+ text: A text to embed.
101
+
102
+ Returns:
103
+ Input document's embedded list.
104
+ """
105
+ resp = self.embed_documents([text])
106
+ return resp[0]
107
+
108
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
109
+ """
110
+ Embeds a list of text documents using the AutoVOT algorithm.
111
+
112
+ Args:
113
+ texts: A list of text documents to embed.
114
+
115
+ Returns:
116
+ A list of embeddings for each document in the input list.
117
+ Each embedding is represented as a list of float values.
118
+ """
119
+ if self.dimensions is not None:
120
+ resp = self.client.embeddings.create(
121
+ model=self.model,
122
+ input=texts,
123
+ dimensions=self.dimensions,
124
+ )
125
+ else:
126
+ resp = self.client.embeddings.create(model=self.model, input=texts)
127
+ embeddings = [r.embedding for r in resp.data]
128
+ return embeddings
python/user_packages/Python313/site-packages/langchain_community/example_selectors/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """**Example selector** implements logic for selecting examples to include them
2
+ in prompts.
3
+ This allows us to select examples that are most relevant to the input.
4
+
5
+ There could be multiple strategies for selecting examples. For example, one could
6
+ select examples based on the similarity of the input to the examples. Another
7
+ strategy could be to select examples based on the diversity of the examples.
8
+ """
9
+
10
+ from langchain_community.example_selectors.ngram_overlap import (
11
+ NGramOverlapExampleSelector,
12
+ ngram_overlap_score,
13
+ )
14
+
15
+ __all__ = [
16
+ "NGramOverlapExampleSelector",
17
+ "ngram_overlap_score",
18
+ ]
python/user_packages/Python313/site-packages/langchain_community/example_selectors/ngram_overlap.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Select and order examples based on ngram overlap score (sentence_bleu score).
2
+
3
+ https://www.nltk.org/_modules/nltk/translate/bleu_score.html
4
+ https://aclanthology.org/P02-1040.pdf
5
+ """
6
+
7
+ from typing import Any, Dict, List
8
+
9
+ import numpy as np
10
+ from langchain_core.example_selectors import BaseExampleSelector
11
+ from langchain_core.prompts import PromptTemplate
12
+ from pydantic import BaseModel, model_validator
13
+
14
+
15
+ def ngram_overlap_score(source: List[str], example: List[str]) -> float:
16
+ """Compute ngram overlap score of source and example as sentence_bleu score
17
+ from NLTK package.
18
+
19
+ Use sentence_bleu with method1 smoothing function and auto reweighting.
20
+ Return float value between 0.0 and 1.0 inclusive.
21
+ https://www.nltk.org/_modules/nltk/translate/bleu_score.html
22
+ https://aclanthology.org/P02-1040.pdf
23
+ """
24
+ from nltk.translate.bleu_score import (
25
+ SmoothingFunction,
26
+ sentence_bleu,
27
+ )
28
+
29
+ hypotheses = source[0].split()
30
+ references = [s.split() for s in example]
31
+
32
+ return float(
33
+ sentence_bleu(
34
+ references,
35
+ hypotheses,
36
+ smoothing_function=SmoothingFunction().method1,
37
+ auto_reweigh=True,
38
+ )
39
+ )
40
+
41
+
42
+ class NGramOverlapExampleSelector(BaseExampleSelector, BaseModel):
43
+ """Select and order examples based on ngram overlap score (sentence_bleu score
44
+ from NLTK package).
45
+
46
+ https://www.nltk.org/_modules/nltk/translate/bleu_score.html
47
+ https://aclanthology.org/P02-1040.pdf
48
+ """
49
+
50
+ examples: List[dict]
51
+ """A list of the examples that the prompt template expects."""
52
+
53
+ example_prompt: PromptTemplate
54
+ """Prompt template used to format the examples."""
55
+
56
+ threshold: float = -1.0
57
+ """Threshold at which algorithm stops. Set to -1.0 by default.
58
+
59
+ For negative threshold:
60
+ select_examples sorts examples by ngram_overlap_score, but excludes none.
61
+ For threshold greater than 1.0:
62
+ select_examples excludes all examples, and returns an empty list.
63
+ For threshold equal to 0.0:
64
+ select_examples sorts examples by ngram_overlap_score,
65
+ and excludes examples with no ngram overlap with input.
66
+ """
67
+
68
+ @model_validator(mode="before")
69
+ @classmethod
70
+ def check_dependencies(cls, values: Dict) -> Any:
71
+ """Check that valid dependencies exist."""
72
+ try:
73
+ from nltk.translate.bleu_score import ( # noqa: F401
74
+ SmoothingFunction,
75
+ sentence_bleu,
76
+ )
77
+ except ImportError as e:
78
+ raise ImportError(
79
+ "Not all the correct dependencies for this ExampleSelect exist."
80
+ "Please install nltk with `pip install nltk`."
81
+ ) from e
82
+
83
+ return values
84
+
85
+ def add_example(self, example: Dict[str, str]) -> None:
86
+ """Add new example to list."""
87
+ self.examples.append(example)
88
+
89
+ def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
90
+ """Return list of examples sorted by ngram_overlap_score with input.
91
+
92
+ Descending order.
93
+ Excludes any examples with ngram_overlap_score less than or equal to threshold.
94
+ """
95
+ inputs = list(input_variables.values())
96
+ examples = []
97
+ k = len(self.examples)
98
+ score = [0.0] * k
99
+ first_prompt_template_key = self.example_prompt.input_variables[0]
100
+
101
+ for i in range(k):
102
+ score[i] = ngram_overlap_score(
103
+ inputs, [self.examples[i][first_prompt_template_key]]
104
+ )
105
+
106
+ while True:
107
+ arg_max = np.argmax(score)
108
+ if (score[arg_max] < self.threshold) or abs(
109
+ score[arg_max] - self.threshold
110
+ ) < 1e-9:
111
+ break
112
+
113
+ examples.append(self.examples[arg_max])
114
+ score[arg_max] = self.threshold - 1.0
115
+
116
+ return examples
python/user_packages/Python313/site-packages/langchain_community/graph_vectorstores/__init__.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """.. title:: Graph Vector Store
2
+
3
+ Graph Vector Store
4
+ ==================
5
+
6
+ Sometimes embedding models don't capture all the important relationships between
7
+ documents.
8
+ Graph Vector Stores are an extension to both vector stores and retrievers that allow
9
+ documents to be explicitly connected to each other.
10
+
11
+ Graph vector store retrievers use both vector similarity and links to find documents
12
+ related to an unstructured query.
13
+
14
+ Graphs allow linking between documents.
15
+ Each document identifies tags that link to and from it.
16
+ For example, a paragraph of text may be linked to URLs based on the anchor tags in
17
+ it's content and linked from the URL(s) it is published at.
18
+
19
+ `Link extractors <langchain_community.graph_vectorstores.extractors.link_extractor.LinkExtractor>`
20
+ can be used to extract links from documents.
21
+
22
+ Example::
23
+
24
+ graph_vector_store = CassandraGraphVectorStore()
25
+ link_extractor = HtmlLinkExtractor()
26
+ links = link_extractor.extract_one(HtmlInput(document.page_content, "http://mysite"))
27
+ add_links(document, links)
28
+ graph_vector_store.add_document(document)
29
+
30
+ .. seealso::
31
+
32
+ - :class:`How to use a graph vector store as a retriever <langchain_community.graph_vectorstores.base.GraphVectorStoreRetriever>`
33
+ - :class:`How to create links between documents <langchain_community.graph_vectorstores.links.Link>`
34
+ - :class:`How to link Documents on hyperlinks in HTML <langchain_community.graph_vectorstores.extractors.html_link_extractor.HtmlLinkExtractor>`
35
+ - :class:`How to link Documents on common keywords (using KeyBERT) <langchain_community.graph_vectorstores.extractors.keybert_link_extractor.KeybertLinkExtractor>`
36
+ - :class:`How to link Documents on common named entities (using GliNER) <langchain_community.graph_vectorstores.extractors.gliner_link_extractor.GLiNERLinkExtractor>`
37
+ - `langchain-jieba: link extraction tailored for Chinese language <https://github.com/cqzyys/langchain-jieba>`_
38
+
39
+ Get started
40
+ -----------
41
+
42
+ We chunk the State of the Union text and split it into documents::
43
+
44
+ from langchain_community.document_loaders import TextLoader
45
+ from langchain_text_splitters import CharacterTextSplitter
46
+
47
+ raw_documents = TextLoader("state_of_the_union.txt").load()
48
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
49
+ documents = text_splitter.split_documents(raw_documents)
50
+
51
+ Links can be added to documents manually but it's easier to use a
52
+ :class:`~langchain_community.graph_vectorstores.extractors.link_extractor.LinkExtractor`.
53
+ Several common link extractors are available and you can build your own.
54
+ For this guide, we'll use the
55
+ :class:`~langchain_community.graph_vectorstores.extractors.keybert_link_extractor.KeybertLinkExtractor`
56
+ which uses the KeyBERT model to tag documents with keywords and uses these keywords to
57
+ create links between documents::
58
+
59
+ from langchain_community.graph_vectorstores.extractors import KeybertLinkExtractor
60
+ from langchain_community.graph_vectorstores.links import add_links
61
+
62
+ extractor = KeybertLinkExtractor()
63
+
64
+ for doc in documents:
65
+ add_links(doc, extractor.extract_one(doc))
66
+
67
+ Create the graph vector store and add documents
68
+ -----------------------------------------------
69
+
70
+ We'll use an Apache Cassandra or Astra DB database as an example.
71
+ We create a
72
+ :class:`~langchain_community.graph_vectorstores.cassandra.CassandraGraphVectorStore`
73
+ from the documents and an :class:`~langchain_openai.embeddings.base.OpenAIEmbeddings`
74
+ model::
75
+
76
+ import cassio
77
+ from langchain_community.graph_vectorstores import CassandraGraphVectorStore
78
+ from langchain_openai import OpenAIEmbeddings
79
+
80
+ # Initialize cassio and the Cassandra session from the environment variables
81
+ cassio.init(auto=True)
82
+
83
+ store = CassandraGraphVectorStore.from_documents(
84
+ embedding=OpenAIEmbeddings(),
85
+ documents=documents,
86
+ )
87
+
88
+
89
+ Similarity search
90
+ -----------------
91
+
92
+ If we don't traverse the graph, a graph vector store behaves like a regular vector
93
+ store.
94
+ So all methods available in a vector store are also available in a graph vector store.
95
+ The :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.similarity_search`
96
+ method returns documents similar to a query without considering
97
+ the links between documents::
98
+
99
+ docs = store.similarity_search(
100
+ "What did the president say about Ketanji Brown Jackson?"
101
+ )
102
+
103
+ Traversal search
104
+ ----------------
105
+
106
+ The :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.traversal_search`
107
+ method returns documents similar to a query considering the links
108
+ between documents. It first does a similarity search and then traverses the graph to
109
+ find linked documents::
110
+
111
+ docs = list(
112
+ store.traversal_search("What did the president say about Ketanji Brown Jackson?")
113
+ )
114
+
115
+ Async methods
116
+ -------------
117
+
118
+ The graph vector store has async versions of the methods prefixed with ``a``::
119
+
120
+ docs = [
121
+ doc
122
+ async for doc in store.atraversal_search(
123
+ "What did the president say about Ketanji Brown Jackson?"
124
+ )
125
+ ]
126
+
127
+ Graph vector store retriever
128
+ ----------------------------
129
+
130
+ The graph vector store can be converted to a retriever.
131
+ It is similar to the vector store retriever but it also has traversal search methods
132
+ such as ``traversal`` and ``mmr_traversal``::
133
+
134
+ retriever = store.as_retriever(search_type="mmr_traversal")
135
+ docs = retriever.invoke("What did the president say about Ketanji Brown Jackson?")
136
+
137
+ """ # noqa: E501
138
+
139
+ from langchain_community.graph_vectorstores.base import (
140
+ GraphVectorStore,
141
+ GraphVectorStoreRetriever,
142
+ Node,
143
+ )
144
+ from langchain_community.graph_vectorstores.cassandra import CassandraGraphVectorStore
145
+ from langchain_community.graph_vectorstores.links import (
146
+ Link,
147
+ )
148
+ from langchain_community.graph_vectorstores.mmr_helper import MmrHelper
149
+
150
+ __all__ = [
151
+ "GraphVectorStore",
152
+ "GraphVectorStoreRetriever",
153
+ "Node",
154
+ "Link",
155
+ "CassandraGraphVectorStore",
156
+ "MmrHelper",
157
+ ]
python/user_packages/Python313/site-packages/langchain_community/graph_vectorstores/base.py ADDED
@@ -0,0 +1,917 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from abc import abstractmethod
5
+ from collections.abc import AsyncIterable, Collection, Iterable, Iterator
6
+ from typing import (
7
+ Any,
8
+ ClassVar,
9
+ Optional,
10
+ Sequence,
11
+ cast,
12
+ )
13
+
14
+ from langchain_core._api import deprecated
15
+ from langchain_core.callbacks import (
16
+ AsyncCallbackManagerForRetrieverRun,
17
+ CallbackManagerForRetrieverRun,
18
+ )
19
+ from langchain_core.documents import Document
20
+ from langchain_core.load import Serializable
21
+ from langchain_core.runnables import run_in_executor
22
+ from langchain_core.vectorstores import VectorStore, VectorStoreRetriever
23
+ from pydantic import Field
24
+
25
+ from langchain_community.graph_vectorstores.links import METADATA_LINKS_KEY, Link
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ def _has_next(iterator: Iterator) -> bool:
31
+ """Checks if the iterator has more elements.
32
+ Warning: consumes an element from the iterator"""
33
+ sentinel = object()
34
+ return next(iterator, sentinel) is not sentinel
35
+
36
+
37
+ DEPRECATION_ADDENDUM = (
38
+ "See https://datastax.github.io/graph-rag/guide/migration/"
39
+ "#from-langchain-graphvectorstore for migration instructions."
40
+ )
41
+
42
+
43
+ @deprecated(
44
+ since="0.3.21",
45
+ removal="0.5",
46
+ addendum=DEPRECATION_ADDENDUM,
47
+ )
48
+ class Node(Serializable):
49
+ """Node in the GraphVectorStore.
50
+
51
+ Edges exist from nodes with an outgoing link to nodes with a matching incoming link.
52
+
53
+ For instance two nodes `a` and `b` connected over a hyperlink ``https://some-url``
54
+ would look like:
55
+
56
+ .. code-block:: python
57
+
58
+ [
59
+ Node(
60
+ id="a",
61
+ text="some text a",
62
+ links= [
63
+ Link(kind="hyperlink", tag="https://some-url", direction="incoming")
64
+ ],
65
+ ),
66
+ Node(
67
+ id="b",
68
+ text="some text b",
69
+ links= [
70
+ Link(kind="hyperlink", tag="https://some-url", direction="outgoing")
71
+ ],
72
+ )
73
+ ]
74
+ """
75
+
76
+ id: Optional[str] = None
77
+ """Unique ID for the node. Will be generated by the GraphVectorStore if not set."""
78
+ text: str
79
+ """Text contained by the node."""
80
+ metadata: dict = Field(default_factory=dict)
81
+ """Metadata for the node."""
82
+ links: list[Link] = Field(default_factory=list)
83
+ """Links associated with the node."""
84
+
85
+
86
+ def _texts_to_nodes(
87
+ texts: Iterable[str],
88
+ metadatas: Optional[Iterable[dict]],
89
+ ids: Optional[Iterable[str]],
90
+ ) -> Iterator[Node]:
91
+ metadatas_it = iter(metadatas) if metadatas else None
92
+ ids_it = iter(ids) if ids else None
93
+ for text in texts:
94
+ try:
95
+ _metadata = next(metadatas_it).copy() if metadatas_it else {}
96
+ except StopIteration as e:
97
+ raise ValueError("texts iterable longer than metadatas") from e
98
+ try:
99
+ _id = next(ids_it) if ids_it else None
100
+ except StopIteration as e:
101
+ raise ValueError("texts iterable longer than ids") from e
102
+
103
+ links = _metadata.pop(METADATA_LINKS_KEY, [])
104
+ if not isinstance(links, list):
105
+ links = list(links)
106
+ yield Node(
107
+ id=_id,
108
+ metadata=_metadata,
109
+ text=text,
110
+ links=links,
111
+ )
112
+ if ids_it and _has_next(ids_it):
113
+ raise ValueError("ids iterable longer than texts")
114
+ if metadatas_it and _has_next(metadatas_it):
115
+ raise ValueError("metadatas iterable longer than texts")
116
+
117
+
118
+ def _documents_to_nodes(documents: Iterable[Document]) -> Iterator[Node]:
119
+ for doc in documents:
120
+ metadata = doc.metadata.copy()
121
+ links = metadata.pop(METADATA_LINKS_KEY, [])
122
+ if not isinstance(links, list):
123
+ links = list(links)
124
+ yield Node(
125
+ id=doc.id,
126
+ metadata=metadata,
127
+ text=doc.page_content,
128
+ links=links,
129
+ )
130
+
131
+
132
+ @deprecated(
133
+ since="0.3.21",
134
+ removal="0.5",
135
+ addendum=DEPRECATION_ADDENDUM,
136
+ )
137
+ def nodes_to_documents(nodes: Iterable[Node]) -> Iterator[Document]:
138
+ """Convert nodes to documents.
139
+
140
+ Args:
141
+ nodes: The nodes to convert to documents.
142
+ Returns:
143
+ The documents generated from the nodes.
144
+ """
145
+ for node in nodes:
146
+ metadata = node.metadata.copy()
147
+ metadata[METADATA_LINKS_KEY] = [
148
+ # Convert the core `Link` (from the node) back to the local `Link`.
149
+ Link(kind=link.kind, direction=link.direction, tag=link.tag)
150
+ for link in node.links
151
+ ]
152
+
153
+ yield Document(
154
+ id=node.id,
155
+ page_content=node.text,
156
+ metadata=metadata,
157
+ )
158
+
159
+
160
+ @deprecated(
161
+ since="0.3.21",
162
+ removal="0.5",
163
+ addendum=DEPRECATION_ADDENDUM,
164
+ )
165
+ class GraphVectorStore(VectorStore):
166
+ """A hybrid vector-and-graph graph store.
167
+
168
+ Document chunks support vector-similarity search as well as edges linking
169
+ chunks based on structural and semantic properties.
170
+
171
+ .. versionadded:: 0.3.1
172
+ """
173
+
174
+ @abstractmethod
175
+ def add_nodes(
176
+ self,
177
+ nodes: Iterable[Node],
178
+ **kwargs: Any,
179
+ ) -> Iterable[str]:
180
+ """Add nodes to the graph store.
181
+
182
+ Args:
183
+ nodes: the nodes to add.
184
+ **kwargs: Additional keyword arguments.
185
+ """
186
+
187
+ async def aadd_nodes(
188
+ self,
189
+ nodes: Iterable[Node],
190
+ **kwargs: Any,
191
+ ) -> AsyncIterable[str]:
192
+ """Add nodes to the graph store.
193
+
194
+ Args:
195
+ nodes: the nodes to add.
196
+ **kwargs: Additional keyword arguments.
197
+ """
198
+ iterator = iter(await run_in_executor(None, self.add_nodes, nodes, **kwargs))
199
+ done = object()
200
+ while True:
201
+ doc = await run_in_executor(None, next, iterator, done)
202
+ if doc is done:
203
+ break
204
+ yield doc # type: ignore[misc]
205
+
206
+ def add_texts(
207
+ self,
208
+ texts: Iterable[str],
209
+ metadatas: Optional[Iterable[dict]] = None,
210
+ *,
211
+ ids: Optional[Iterable[str]] = None,
212
+ **kwargs: Any,
213
+ ) -> list[str]:
214
+ """Run more texts through the embeddings and add to the vector store.
215
+
216
+ The Links present in the metadata field `links` will be extracted to create
217
+ the `Node` links.
218
+
219
+ Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
220
+ function call would look like:
221
+
222
+ .. code-block:: python
223
+
224
+ store.add_texts(
225
+ ids=["a", "b"],
226
+ texts=["some text a", "some text b"],
227
+ metadatas=[
228
+ {
229
+ "links": [
230
+ Link.incoming(kind="hyperlink", tag="https://some-url")
231
+ ]
232
+ },
233
+ {
234
+ "links": [
235
+ Link.outgoing(kind="hyperlink", tag="https://some-url")
236
+ ]
237
+ },
238
+ ],
239
+ )
240
+
241
+ Args:
242
+ texts: Iterable of strings to add to the vector store.
243
+ metadatas: Optional list of metadatas associated with the texts.
244
+ The metadata key `links` shall be an iterable of
245
+ :py:class:`~langchain_community.graph_vectorstores.links.Link`.
246
+ ids: Optional list of IDs associated with the texts.
247
+ **kwargs: vector store specific parameters.
248
+
249
+ Returns:
250
+ List of ids from adding the texts into the vector store.
251
+ """
252
+ nodes = _texts_to_nodes(texts, metadatas, ids)
253
+ return list(self.add_nodes(nodes, **kwargs))
254
+
255
+ async def aadd_texts(
256
+ self,
257
+ texts: Iterable[str],
258
+ metadatas: Optional[Iterable[dict]] = None,
259
+ *,
260
+ ids: Optional[Iterable[str]] = None,
261
+ **kwargs: Any,
262
+ ) -> list[str]:
263
+ """Run more texts through the embeddings and add to the vector store.
264
+
265
+ The Links present in the metadata field `links` will be extracted to create
266
+ the `Node` links.
267
+
268
+ Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
269
+ function call would look like:
270
+
271
+ .. code-block:: python
272
+
273
+ await store.aadd_texts(
274
+ ids=["a", "b"],
275
+ texts=["some text a", "some text b"],
276
+ metadatas=[
277
+ {
278
+ "links": [
279
+ Link.incoming(kind="hyperlink", tag="https://some-url")
280
+ ]
281
+ },
282
+ {
283
+ "links": [
284
+ Link.outgoing(kind="hyperlink", tag="https://some-url")
285
+ ]
286
+ },
287
+ ],
288
+ )
289
+
290
+ Args:
291
+ texts: Iterable of strings to add to the vector store.
292
+ metadatas: Optional list of metadatas associated with the texts.
293
+ The metadata key `links` shall be an iterable of
294
+ :py:class:`~langchain_community.graph_vectorstores.links.Link`.
295
+ ids: Optional list of IDs associated with the texts.
296
+ **kwargs: vector store specific parameters.
297
+
298
+ Returns:
299
+ List of ids from adding the texts into the vector store.
300
+ """
301
+ nodes = _texts_to_nodes(texts, metadatas, ids)
302
+ return [_id async for _id in self.aadd_nodes(nodes, **kwargs)]
303
+
304
+ def add_documents(
305
+ self,
306
+ documents: Iterable[Document],
307
+ **kwargs: Any,
308
+ ) -> list[str]:
309
+ """Run more documents through the embeddings and add to the vector store.
310
+
311
+ The Links present in the document metadata field `links` will be extracted to
312
+ create the `Node` links.
313
+
314
+ Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
315
+ function call would look like:
316
+
317
+ .. code-block:: python
318
+
319
+ store.add_documents(
320
+ [
321
+ Document(
322
+ id="a",
323
+ page_content="some text a",
324
+ metadata={
325
+ "links": [
326
+ Link.incoming(kind="hyperlink", tag="http://some-url")
327
+ ]
328
+ }
329
+ ),
330
+ Document(
331
+ id="b",
332
+ page_content="some text b",
333
+ metadata={
334
+ "links": [
335
+ Link.outgoing(kind="hyperlink", tag="http://some-url")
336
+ ]
337
+ }
338
+ ),
339
+ ]
340
+
341
+ )
342
+
343
+ Args:
344
+ documents: Documents to add to the vector store.
345
+ The document's metadata key `links` shall be an iterable of
346
+ :py:class:`~langchain_community.graph_vectorstores.links.Link`.
347
+
348
+ Returns:
349
+ List of IDs of the added texts.
350
+ """
351
+ nodes = _documents_to_nodes(documents)
352
+ return list(self.add_nodes(nodes, **kwargs))
353
+
354
+ async def aadd_documents(
355
+ self,
356
+ documents: Iterable[Document],
357
+ **kwargs: Any,
358
+ ) -> list[str]:
359
+ """Run more documents through the embeddings and add to the vector store.
360
+
361
+ The Links present in the document metadata field `links` will be extracted to
362
+ create the `Node` links.
363
+
364
+ Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
365
+ function call would look like:
366
+
367
+ .. code-block:: python
368
+
369
+ store.add_documents(
370
+ [
371
+ Document(
372
+ id="a",
373
+ page_content="some text a",
374
+ metadata={
375
+ "links": [
376
+ Link.incoming(kind="hyperlink", tag="http://some-url")
377
+ ]
378
+ }
379
+ ),
380
+ Document(
381
+ id="b",
382
+ page_content="some text b",
383
+ metadata={
384
+ "links": [
385
+ Link.outgoing(kind="hyperlink", tag="http://some-url")
386
+ ]
387
+ }
388
+ ),
389
+ ]
390
+
391
+ )
392
+
393
+ Args:
394
+ documents: Documents to add to the vector store.
395
+ The document's metadata key `links` shall be an iterable of
396
+ :py:class:`~langchain_community.graph_vectorstores.links.Link`.
397
+
398
+ Returns:
399
+ List of IDs of the added texts.
400
+ """
401
+ nodes = _documents_to_nodes(documents)
402
+ return [_id async for _id in self.aadd_nodes(nodes, **kwargs)]
403
+
404
+ @abstractmethod
405
+ def traversal_search(
406
+ self,
407
+ query: str,
408
+ *,
409
+ k: int = 4,
410
+ depth: int = 1,
411
+ filter: dict[str, Any] | None = None, # noqa: A002
412
+ **kwargs: Any,
413
+ ) -> Iterable[Document]:
414
+ """Retrieve documents from traversing this graph store.
415
+
416
+ First, `k` nodes are retrieved using a search for each `query` string.
417
+ Then, additional nodes are discovered up to the given `depth` from those
418
+ starting nodes.
419
+
420
+ Args:
421
+ query: The query string.
422
+ k: The number of Documents to return from the initial search.
423
+ Defaults to 4. Applies to each of the query strings.
424
+ depth: The maximum depth of edges to traverse. Defaults to 1.
425
+ filter: Optional metadata to filter the results.
426
+ **kwargs: Additional keyword arguments.
427
+ Returns:
428
+ Collection of retrieved documents.
429
+ """
430
+
431
+ async def atraversal_search(
432
+ self,
433
+ query: str,
434
+ *,
435
+ k: int = 4,
436
+ depth: int = 1,
437
+ filter: dict[str, Any] | None = None, # noqa: A002
438
+ **kwargs: Any,
439
+ ) -> AsyncIterable[Document]:
440
+ """Retrieve documents from traversing this graph store.
441
+
442
+ First, `k` nodes are retrieved using a search for each `query` string.
443
+ Then, additional nodes are discovered up to the given `depth` from those
444
+ starting nodes.
445
+
446
+ Args:
447
+ query: The query string.
448
+ k: The number of Documents to return from the initial search.
449
+ Defaults to 4. Applies to each of the query strings.
450
+ depth: The maximum depth of edges to traverse. Defaults to 1.
451
+ filter: Optional metadata to filter the results.
452
+ **kwargs: Additional keyword arguments.
453
+ Returns:
454
+ Collection of retrieved documents.
455
+ """
456
+ iterator = iter(
457
+ await run_in_executor(
458
+ None,
459
+ self.traversal_search,
460
+ query,
461
+ k=k,
462
+ depth=depth,
463
+ filter=filter,
464
+ **kwargs,
465
+ )
466
+ )
467
+ done = object()
468
+ while True:
469
+ doc = await run_in_executor(None, next, iterator, done)
470
+ if doc is done:
471
+ break
472
+ yield doc # type: ignore[misc]
473
+
474
+ @abstractmethod
475
+ def mmr_traversal_search(
476
+ self,
477
+ query: str,
478
+ *,
479
+ initial_roots: Sequence[str] = (),
480
+ k: int = 4,
481
+ depth: int = 2,
482
+ fetch_k: int = 100,
483
+ adjacent_k: int = 10,
484
+ lambda_mult: float = 0.5,
485
+ score_threshold: float = float("-inf"),
486
+ filter: dict[str, Any] | None = None, # noqa: A002
487
+ **kwargs: Any,
488
+ ) -> Iterable[Document]:
489
+ """Retrieve documents from this graph store using MMR-traversal.
490
+
491
+ This strategy first retrieves the top `fetch_k` results by similarity to
492
+ the question. It then selects the top `k` results based on
493
+ maximum-marginal relevance using the given `lambda_mult`.
494
+
495
+ At each step, it considers the (remaining) documents from `fetch_k` as
496
+ well as any documents connected by edges to a selected document
497
+ retrieved based on similarity (a "root").
498
+
499
+ Args:
500
+ query: The query string to search for.
501
+ initial_roots: Optional list of document IDs to use for initializing search.
502
+ The top `adjacent_k` nodes adjacent to each initial root will be
503
+ included in the set of initial candidates. To fetch only in the
504
+ neighborhood of these nodes, set `fetch_k = 0`.
505
+ k: Number of Documents to return. Defaults to 4.
506
+ fetch_k: Number of Documents to fetch via similarity.
507
+ Defaults to 100.
508
+ adjacent_k: Number of adjacent Documents to fetch.
509
+ Defaults to 10.
510
+ depth: Maximum depth of a node (number of edges) from a node
511
+ retrieved via similarity. Defaults to 2.
512
+ lambda_mult: Number between 0 and 1 that determines the degree
513
+ of diversity among the results with 0 corresponding to maximum
514
+ diversity and 1 to minimum diversity. Defaults to 0.5.
515
+ score_threshold: Only documents with a score greater than or equal
516
+ this threshold will be chosen. Defaults to negative infinity.
517
+ filter: Optional metadata to filter the results.
518
+ **kwargs: Additional keyword arguments.
519
+ """
520
+
521
+ async def ammr_traversal_search(
522
+ self,
523
+ query: str,
524
+ *,
525
+ initial_roots: Sequence[str] = (),
526
+ k: int = 4,
527
+ depth: int = 2,
528
+ fetch_k: int = 100,
529
+ adjacent_k: int = 10,
530
+ lambda_mult: float = 0.5,
531
+ score_threshold: float = float("-inf"),
532
+ filter: dict[str, Any] | None = None, # noqa: A002
533
+ **kwargs: Any,
534
+ ) -> AsyncIterable[Document]:
535
+ """Retrieve documents from this graph store using MMR-traversal.
536
+
537
+ This strategy first retrieves the top `fetch_k` results by similarity to
538
+ the question. It then selects the top `k` results based on
539
+ maximum-marginal relevance using the given `lambda_mult`.
540
+
541
+ At each step, it considers the (remaining) documents from `fetch_k` as
542
+ well as any documents connected by edges to a selected document
543
+ retrieved based on similarity (a "root").
544
+
545
+ Args:
546
+ query: The query string to search for.
547
+ initial_roots: Optional list of document IDs to use for initializing search.
548
+ The top `adjacent_k` nodes adjacent to each initial root will be
549
+ included in the set of initial candidates. To fetch only in the
550
+ neighborhood of these nodes, set `fetch_k = 0`.
551
+ k: Number of Documents to return. Defaults to 4.
552
+ fetch_k: Number of Documents to fetch via similarity.
553
+ Defaults to 100.
554
+ adjacent_k: Number of adjacent Documents to fetch.
555
+ Defaults to 10.
556
+ depth: Maximum depth of a node (number of edges) from a node
557
+ retrieved via similarity. Defaults to 2.
558
+ lambda_mult: Number between 0 and 1 that determines the degree
559
+ of diversity among the results with 0 corresponding to maximum
560
+ diversity and 1 to minimum diversity. Defaults to 0.5.
561
+ score_threshold: Only documents with a score greater than or equal
562
+ this threshold will be chosen. Defaults to negative infinity.
563
+ filter: Optional metadata to filter the results.
564
+ **kwargs: Additional keyword arguments.
565
+ """
566
+ iterator = iter(
567
+ await run_in_executor(
568
+ None,
569
+ self.mmr_traversal_search,
570
+ query,
571
+ initial_roots=initial_roots,
572
+ k=k,
573
+ fetch_k=fetch_k,
574
+ adjacent_k=adjacent_k,
575
+ depth=depth,
576
+ lambda_mult=lambda_mult,
577
+ score_threshold=score_threshold,
578
+ filter=filter,
579
+ **kwargs,
580
+ )
581
+ )
582
+ done = object()
583
+ while True:
584
+ doc = await run_in_executor(None, next, iterator, done)
585
+ if doc is done:
586
+ break
587
+ yield doc # type: ignore[misc]
588
+
589
+ def similarity_search(
590
+ self, query: str, k: int = 4, **kwargs: Any
591
+ ) -> list[Document]:
592
+ return list(self.traversal_search(query, k=k, depth=0))
593
+
594
+ def max_marginal_relevance_search(
595
+ self,
596
+ query: str,
597
+ k: int = 4,
598
+ fetch_k: int = 20,
599
+ lambda_mult: float = 0.5,
600
+ **kwargs: Any,
601
+ ) -> list[Document]:
602
+ if kwargs.get("depth", 0) > 0:
603
+ logger.warning(
604
+ "'mmr' search started with depth > 0. "
605
+ "Maybe you meant to do a 'mmr_traversal' search?"
606
+ )
607
+ return list(
608
+ self.mmr_traversal_search(
609
+ query, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, depth=0
610
+ )
611
+ )
612
+
613
+ async def asimilarity_search(
614
+ self, query: str, k: int = 4, **kwargs: Any
615
+ ) -> list[Document]:
616
+ return [doc async for doc in self.atraversal_search(query, k=k, depth=0)]
617
+
618
+ def search(self, query: str, search_type: str, **kwargs: Any) -> list[Document]:
619
+ if search_type == "similarity":
620
+ return self.similarity_search(query, **kwargs)
621
+ elif search_type == "similarity_score_threshold":
622
+ docs_and_similarities = self.similarity_search_with_relevance_scores(
623
+ query, **kwargs
624
+ )
625
+ return [doc for doc, _ in docs_and_similarities]
626
+ elif search_type == "mmr":
627
+ return self.max_marginal_relevance_search(query, **kwargs)
628
+ elif search_type == "traversal":
629
+ return list(self.traversal_search(query, **kwargs))
630
+ elif search_type == "mmr_traversal":
631
+ return list(self.mmr_traversal_search(query, **kwargs))
632
+ else:
633
+ raise ValueError(
634
+ f"search_type of {search_type} not allowed. Expected "
635
+ "search_type to be 'similarity', 'similarity_score_threshold', "
636
+ "'mmr', 'traversal', or 'mmr_traversal'."
637
+ )
638
+
639
+ async def asearch(
640
+ self, query: str, search_type: str, **kwargs: Any
641
+ ) -> list[Document]:
642
+ if search_type == "similarity":
643
+ return await self.asimilarity_search(query, **kwargs)
644
+ elif search_type == "similarity_score_threshold":
645
+ docs_and_similarities = await self.asimilarity_search_with_relevance_scores(
646
+ query, **kwargs
647
+ )
648
+ return [doc for doc, _ in docs_and_similarities]
649
+ elif search_type == "mmr":
650
+ return await self.amax_marginal_relevance_search(query, **kwargs)
651
+ elif search_type == "traversal":
652
+ return [doc async for doc in self.atraversal_search(query, **kwargs)]
653
+ elif search_type == "mmr_traversal":
654
+ return [doc async for doc in self.ammr_traversal_search(query, **kwargs)]
655
+ else:
656
+ raise ValueError(
657
+ f"search_type of {search_type} not allowed. Expected "
658
+ "search_type to be 'similarity', 'similarity_score_threshold', "
659
+ "'mmr', 'traversal', or 'mmr_traversal'."
660
+ )
661
+
662
+ def as_retriever(self, **kwargs: Any) -> GraphVectorStoreRetriever:
663
+ """Return GraphVectorStoreRetriever initialized from this GraphVectorStore.
664
+
665
+ Args:
666
+ **kwargs: Keyword arguments to pass to the search function.
667
+ Can include:
668
+
669
+ - search_type (Optional[str]): Defines the type of search that
670
+ the Retriever should perform.
671
+ Can be ``traversal`` (default), ``similarity``, ``mmr``,
672
+ ``mmr_traversal``, or ``similarity_score_threshold``.
673
+ - search_kwargs (Optional[Dict]): Keyword arguments to pass to the
674
+ search function. Can include things like:
675
+
676
+ - k(int): Amount of documents to return (Default: 4).
677
+ - depth(int): The maximum depth of edges to traverse (Default: 1).
678
+ Only applies to search_type: ``traversal`` and ``mmr_traversal``.
679
+ - score_threshold(float): Minimum relevance threshold
680
+ for similarity_score_threshold.
681
+ - fetch_k(int): Amount of documents to pass to MMR algorithm
682
+ (Default: 20).
683
+ - lambda_mult(float): Diversity of results returned by MMR;
684
+ 1 for minimum diversity and 0 for maximum. (Default: 0.5).
685
+ Returns:
686
+ Retriever for this GraphVectorStore.
687
+
688
+ Examples:
689
+
690
+ .. code-block:: python
691
+
692
+ # Retrieve documents traversing edges
693
+ docsearch.as_retriever(
694
+ search_type="traversal",
695
+ search_kwargs={'k': 6, 'depth': 2}
696
+ )
697
+
698
+ # Retrieve documents with higher diversity
699
+ # Useful if your dataset has many similar documents
700
+ docsearch.as_retriever(
701
+ search_type="mmr_traversal",
702
+ search_kwargs={'k': 6, 'lambda_mult': 0.25, 'depth': 2}
703
+ )
704
+
705
+ # Fetch more documents for the MMR algorithm to consider
706
+ # But only return the top 5
707
+ docsearch.as_retriever(
708
+ search_type="mmr_traversal",
709
+ search_kwargs={'k': 5, 'fetch_k': 50, 'depth': 2}
710
+ )
711
+
712
+ # Only retrieve documents that have a relevance score
713
+ # Above a certain threshold
714
+ docsearch.as_retriever(
715
+ search_type="similarity_score_threshold",
716
+ search_kwargs={'score_threshold': 0.8}
717
+ )
718
+
719
+ # Only get the single most similar document from the dataset
720
+ docsearch.as_retriever(search_kwargs={'k': 1})
721
+
722
+ """
723
+ return GraphVectorStoreRetriever(vectorstore=self, **kwargs)
724
+
725
+
726
+ @deprecated(
727
+ since="0.3.21",
728
+ removal="0.5",
729
+ addendum=DEPRECATION_ADDENDUM,
730
+ )
731
+ class GraphVectorStoreRetriever(VectorStoreRetriever):
732
+ """Retriever for GraphVectorStore.
733
+
734
+ A graph vector store retriever is a retriever that uses a graph vector store to
735
+ retrieve documents.
736
+ It is similar to a vector store retriever, except that it uses both vector
737
+ similarity and graph connections to retrieve documents.
738
+ It uses the search methods implemented by a graph vector store, like traversal
739
+ search and MMR traversal search, to query the texts in the graph vector store.
740
+
741
+ Example::
742
+
743
+ store = CassandraGraphVectorStore(...)
744
+ retriever = store.as_retriever()
745
+ retriever.invoke("What is ...")
746
+
747
+ .. seealso::
748
+
749
+ :mod:`How to use a graph vector store <langchain_community.graph_vectorstores>`
750
+
751
+ How to use a graph vector store as a retriever
752
+ ==============================================
753
+
754
+ Creating a retriever from a graph vector store
755
+ ----------------------------------------------
756
+
757
+ You can build a retriever from a graph vector store using its
758
+ :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.as_retriever`
759
+ method.
760
+
761
+ First we instantiate a graph vector store.
762
+ We will use a store backed by Cassandra
763
+ :class:`~langchain_community.graph_vectorstores.cassandra.CassandraGraphVectorStore`
764
+ graph vector store::
765
+
766
+ from langchain_community.document_loaders import TextLoader
767
+ from langchain_community.graph_vectorstores import CassandraGraphVectorStore
768
+ from langchain_community.graph_vectorstores.extractors import (
769
+ KeybertLinkExtractor,
770
+ LinkExtractorTransformer,
771
+ )
772
+ from langchain_openai import OpenAIEmbeddings
773
+ from langchain_text_splitters import CharacterTextSplitter
774
+
775
+ loader = TextLoader("state_of_the_union.txt")
776
+ documents = loader.load()
777
+
778
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
779
+ texts = text_splitter.split_documents(documents)
780
+
781
+ pipeline = LinkExtractorTransformer([KeybertLinkExtractor()])
782
+ pipeline.transform_documents(texts)
783
+ embeddings = OpenAIEmbeddings()
784
+ graph_vectorstore = CassandraGraphVectorStore.from_documents(texts, embeddings)
785
+
786
+ We can then instantiate a retriever::
787
+
788
+ retriever = graph_vectorstore.as_retriever()
789
+
790
+ This creates a retriever (specifically a ``GraphVectorStoreRetriever``), which we
791
+ can use in the usual way::
792
+
793
+ docs = retriever.invoke("what did the president say about ketanji brown jackson?")
794
+
795
+ Maximum marginal relevance traversal retrieval
796
+ ----------------------------------------------
797
+
798
+ By default, the graph vector store retriever uses similarity search, then expands
799
+ the retrieved set by following a fixed number of graph edges.
800
+ If the underlying graph vector store supports maximum marginal relevance traversal,
801
+ you can specify that as the search type.
802
+
803
+ MMR-traversal is a retrieval method combining MMR and graph traversal.
804
+ The strategy first retrieves the top fetch_k results by similarity to the question.
805
+ It then iteratively expands the set of fetched documents by following adjacent_k
806
+ graph edges and selects the top k results based on maximum-marginal relevance using
807
+ the given ``lambda_mult``::
808
+
809
+ retriever = graph_vectorstore.as_retriever(search_type="mmr_traversal")
810
+
811
+ Passing search parameters
812
+ -------------------------
813
+
814
+ We can pass parameters to the underlying graph vector store's search methods using
815
+ ``search_kwargs``.
816
+
817
+ Specifying graph traversal depth
818
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
819
+
820
+ For example, we can set the graph traversal depth to only return documents
821
+ reachable through a given number of graph edges::
822
+
823
+ retriever = graph_vectorstore.as_retriever(search_kwargs={"depth": 3})
824
+
825
+ Specifying MMR parameters
826
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
827
+
828
+ When using search type ``mmr_traversal``, several parameters of the MMR algorithm
829
+ can be configured.
830
+
831
+ The ``fetch_k`` parameter determines how many documents are fetched using vector
832
+ similarity and ``adjacent_k`` parameter determines how many documents are fetched
833
+ using graph edges.
834
+ The ``lambda_mult`` parameter controls how the MMR re-ranking weights similarity to
835
+ the query string vs diversity among the retrieved documents as fetched documents
836
+ are selected for the set of ``k`` final results::
837
+
838
+ retriever = graph_vectorstore.as_retriever(
839
+ search_type="mmr",
840
+ search_kwargs={"fetch_k": 20, "adjacent_k": 20, "lambda_mult": 0.25},
841
+ )
842
+
843
+ Specifying top k
844
+ ^^^^^^^^^^^^^^^^
845
+
846
+ We can also limit the number of documents ``k`` returned by the retriever.
847
+
848
+ Note that if ``depth`` is greater than zero, the retriever may return more documents
849
+ than is specified by ``k``, since both the original ``k`` documents retrieved using
850
+ vector similarity and any documents connected via graph edges will be returned::
851
+
852
+ retriever = graph_vectorstore.as_retriever(search_kwargs={"k": 1})
853
+
854
+ Similarity score threshold retrieval
855
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
856
+
857
+ For example, we can set a similarity score threshold and only return documents with
858
+ a score above that threshold::
859
+
860
+ retriever = graph_vectorstore.as_retriever(search_kwargs={"score_threshold": 0.5})
861
+ """ # noqa: E501
862
+
863
+ vectorstore: VectorStore
864
+ """VectorStore to use for retrieval."""
865
+ search_type: str = "traversal"
866
+ """Type of search to perform. Defaults to "traversal"."""
867
+ allowed_search_types: ClassVar[Collection[str]] = (
868
+ "similarity",
869
+ "similarity_score_threshold",
870
+ "mmr",
871
+ "traversal",
872
+ "mmr_traversal",
873
+ )
874
+
875
+ @property
876
+ def graph_vectorstore(self) -> GraphVectorStore:
877
+ return cast(GraphVectorStore, self.vectorstore)
878
+
879
+ def _get_relevant_documents(
880
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any
881
+ ) -> list[Document]:
882
+ if self.search_type == "traversal":
883
+ return list(
884
+ self.graph_vectorstore.traversal_search(query, **self.search_kwargs)
885
+ )
886
+ elif self.search_type == "mmr_traversal":
887
+ return list(
888
+ self.graph_vectorstore.mmr_traversal_search(query, **self.search_kwargs)
889
+ )
890
+ else:
891
+ return super()._get_relevant_documents(query, run_manager=run_manager)
892
+
893
+ async def _aget_relevant_documents(
894
+ self,
895
+ query: str,
896
+ *,
897
+ run_manager: AsyncCallbackManagerForRetrieverRun,
898
+ **kwargs: Any,
899
+ ) -> list[Document]:
900
+ if self.search_type == "traversal":
901
+ return [
902
+ doc
903
+ async for doc in self.graph_vectorstore.atraversal_search(
904
+ query, **self.search_kwargs
905
+ )
906
+ ]
907
+ elif self.search_type == "mmr_traversal":
908
+ return [
909
+ doc
910
+ async for doc in self.graph_vectorstore.ammr_traversal_search(
911
+ query, **self.search_kwargs
912
+ )
913
+ ]
914
+ else:
915
+ return await super()._aget_relevant_documents(
916
+ query, run_manager=run_manager
917
+ )