lfx-nightly 0.2.0.dev41__py3-none-any.whl → 0.3.0.dev3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. lfx/__main__.py +137 -6
  2. lfx/_assets/component_index.json +1 -1
  3. lfx/base/agents/agent.py +10 -6
  4. lfx/base/agents/altk_base_agent.py +5 -3
  5. lfx/base/agents/altk_tool_wrappers.py +1 -1
  6. lfx/base/agents/events.py +1 -1
  7. lfx/base/agents/utils.py +4 -0
  8. lfx/base/composio/composio_base.py +78 -41
  9. lfx/base/data/cloud_storage_utils.py +156 -0
  10. lfx/base/data/docling_utils.py +130 -55
  11. lfx/base/datastax/astradb_base.py +75 -64
  12. lfx/base/embeddings/embeddings_class.py +113 -0
  13. lfx/base/models/__init__.py +11 -1
  14. lfx/base/models/google_generative_ai_constants.py +33 -9
  15. lfx/base/models/model_metadata.py +6 -0
  16. lfx/base/models/ollama_constants.py +196 -30
  17. lfx/base/models/openai_constants.py +37 -10
  18. lfx/base/models/unified_models.py +1123 -0
  19. lfx/base/models/watsonx_constants.py +43 -4
  20. lfx/base/prompts/api_utils.py +40 -5
  21. lfx/base/tools/component_tool.py +2 -9
  22. lfx/cli/__init__.py +10 -2
  23. lfx/cli/commands.py +3 -0
  24. lfx/cli/run.py +65 -409
  25. lfx/cli/script_loader.py +18 -7
  26. lfx/cli/validation.py +6 -3
  27. lfx/components/__init__.py +0 -3
  28. lfx/components/composio/github_composio.py +1 -1
  29. lfx/components/cuga/cuga_agent.py +39 -27
  30. lfx/components/data_source/api_request.py +4 -2
  31. lfx/components/datastax/astradb_assistant_manager.py +4 -2
  32. lfx/components/docling/__init__.py +45 -11
  33. lfx/components/docling/docling_inline.py +39 -49
  34. lfx/components/docling/docling_remote.py +1 -0
  35. lfx/components/elastic/opensearch_multimodal.py +1733 -0
  36. lfx/components/files_and_knowledge/file.py +384 -36
  37. lfx/components/files_and_knowledge/ingestion.py +8 -0
  38. lfx/components/files_and_knowledge/retrieval.py +10 -0
  39. lfx/components/files_and_knowledge/save_file.py +91 -88
  40. lfx/components/langchain_utilities/ibm_granite_handler.py +211 -0
  41. lfx/components/langchain_utilities/tool_calling.py +37 -6
  42. lfx/components/llm_operations/batch_run.py +64 -18
  43. lfx/components/llm_operations/lambda_filter.py +213 -101
  44. lfx/components/llm_operations/llm_conditional_router.py +39 -7
  45. lfx/components/llm_operations/structured_output.py +38 -12
  46. lfx/components/models/__init__.py +16 -74
  47. lfx/components/models_and_agents/agent.py +51 -203
  48. lfx/components/models_and_agents/embedding_model.py +171 -255
  49. lfx/components/models_and_agents/language_model.py +54 -318
  50. lfx/components/models_and_agents/mcp_component.py +96 -10
  51. lfx/components/models_and_agents/prompt.py +105 -18
  52. lfx/components/ollama/ollama_embeddings.py +111 -29
  53. lfx/components/openai/openai_chat_model.py +1 -1
  54. lfx/components/processing/text_operations.py +580 -0
  55. lfx/components/vllm/__init__.py +37 -0
  56. lfx/components/vllm/vllm.py +141 -0
  57. lfx/components/vllm/vllm_embeddings.py +110 -0
  58. lfx/custom/custom_component/component.py +65 -10
  59. lfx/custom/custom_component/custom_component.py +8 -6
  60. lfx/events/observability/__init__.py +0 -0
  61. lfx/events/observability/lifecycle_events.py +111 -0
  62. lfx/field_typing/__init__.py +57 -58
  63. lfx/graph/graph/base.py +40 -1
  64. lfx/graph/utils.py +109 -30
  65. lfx/graph/vertex/base.py +75 -23
  66. lfx/graph/vertex/vertex_types.py +0 -5
  67. lfx/inputs/__init__.py +2 -0
  68. lfx/inputs/input_mixin.py +55 -0
  69. lfx/inputs/inputs.py +120 -0
  70. lfx/interface/components.py +24 -7
  71. lfx/interface/initialize/loading.py +42 -12
  72. lfx/io/__init__.py +2 -0
  73. lfx/run/__init__.py +5 -0
  74. lfx/run/base.py +464 -0
  75. lfx/schema/__init__.py +50 -0
  76. lfx/schema/data.py +1 -1
  77. lfx/schema/image.py +26 -7
  78. lfx/schema/message.py +104 -11
  79. lfx/schema/workflow.py +171 -0
  80. lfx/services/deps.py +12 -0
  81. lfx/services/interfaces.py +43 -1
  82. lfx/services/mcp_composer/service.py +7 -1
  83. lfx/services/schema.py +1 -0
  84. lfx/services/settings/auth.py +95 -4
  85. lfx/services/settings/base.py +11 -1
  86. lfx/services/settings/constants.py +2 -0
  87. lfx/services/settings/utils.py +82 -0
  88. lfx/services/storage/local.py +13 -8
  89. lfx/services/transaction/__init__.py +5 -0
  90. lfx/services/transaction/service.py +35 -0
  91. lfx/tests/unit/components/__init__.py +0 -0
  92. lfx/utils/constants.py +2 -0
  93. lfx/utils/mustache_security.py +79 -0
  94. lfx/utils/validate_cloud.py +81 -3
  95. {lfx_nightly-0.2.0.dev41.dist-info → lfx_nightly-0.3.0.dev3.dist-info}/METADATA +7 -2
  96. {lfx_nightly-0.2.0.dev41.dist-info → lfx_nightly-0.3.0.dev3.dist-info}/RECORD +98 -80
  97. {lfx_nightly-0.2.0.dev41.dist-info → lfx_nightly-0.3.0.dev3.dist-info}/WHEEL +0 -0
  98. {lfx_nightly-0.2.0.dev41.dist-info → lfx_nightly-0.3.0.dev3.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,1733 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import json
5
+ import time
6
+ import uuid
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from typing import Any
9
+
10
+ from opensearchpy import OpenSearch, helpers
11
+ from opensearchpy.exceptions import OpenSearchException, RequestError
12
+
13
+ from lfx.base.vectorstores.model import LCVectorStoreComponent, check_cached_vector_store
14
+ from lfx.base.vectorstores.vector_store_connection_decorator import vector_store_connection
15
+ from lfx.io import BoolInput, DropdownInput, HandleInput, IntInput, MultilineInput, SecretStrInput, StrInput, TableInput
16
+ from lfx.log import logger
17
+ from lfx.schema.data import Data
18
+
19
+
20
+ def normalize_model_name(model_name: str) -> str:
21
+ """Normalize embedding model name for use as field suffix.
22
+
23
+ Converts model names to valid OpenSearch field names by replacing
24
+ special characters and ensuring alphanumeric format.
25
+
26
+ Args:
27
+ model_name: Original embedding model name (e.g., "text-embedding-3-small")
28
+
29
+ Returns:
30
+ Normalized field suffix (e.g., "text_embedding_3_small")
31
+ """
32
+ normalized = model_name.lower()
33
+ # Replace common separators with underscores
34
+ normalized = normalized.replace("-", "_").replace(":", "_").replace("/", "_").replace(".", "_")
35
+ # Remove any non-alphanumeric characters except underscores
36
+ normalized = "".join(c if c.isalnum() or c == "_" else "_" for c in normalized)
37
+ # Remove duplicate underscores
38
+ while "__" in normalized:
39
+ normalized = normalized.replace("__", "_")
40
+ return normalized.strip("_")
41
+
42
+
43
+ def get_embedding_field_name(model_name: str) -> str:
44
+ """Get the dynamic embedding field name for a model.
45
+
46
+ Args:
47
+ model_name: Embedding model name
48
+
49
+ Returns:
50
+ Field name in format: chunk_embedding_{normalized_model_name}
51
+ """
52
+ logger.info(f"chunk_embedding_{normalize_model_name(model_name)}")
53
+ return f"chunk_embedding_{normalize_model_name(model_name)}"
54
+
55
+
56
+ @vector_store_connection
57
+ class OpenSearchVectorStoreComponentMultimodalMultiEmbedding(LCVectorStoreComponent):
58
+ """OpenSearch Vector Store Component with Multi-Model Hybrid Search Capabilities.
59
+
60
+ This component provides vector storage and retrieval using OpenSearch, combining semantic
61
+ similarity search (KNN) with keyword-based search for optimal results. It supports:
62
+ - Multiple embedding models per index with dynamic field names
63
+ - Automatic detection and querying of all available embedding models
64
+ - Parallel embedding generation for multi-model search
65
+ - Document ingestion with model tracking
66
+ - Advanced filtering and aggregations
67
+ - Flexible authentication options
68
+
69
+ Features:
70
+ - Multi-model vector storage with dynamic fields (chunk_embedding_{model_name})
71
+ - Hybrid search combining multiple KNN queries (dis_max) + keyword matching
72
+ - Auto-detection of available models in the index
73
+ - Parallel query embedding generation for all detected models
74
+ - Vector storage with configurable engines (jvector, nmslib, faiss, lucene)
75
+ - Flexible authentication (Basic auth, JWT tokens)
76
+
77
+ Model Name Resolution:
78
+ - Priority: deployment > model > model_name attributes
79
+ - This ensures correct matching between embedding objects and index fields
80
+ - When multiple embeddings are provided, specify embedding_model_name to select which one to use
81
+ - During search, each detected model in the index is matched to its corresponding embedding object
82
+ """
83
+
84
+ display_name: str = "OpenSearch (Multi-Model Multi-Embedding)"
85
+ icon: str = "OpenSearch"
86
+ description: str = (
87
+ "Store and search documents using OpenSearch with multi-model hybrid semantic and keyword search."
88
+ )
89
+
90
+ # Keys we consider baseline
91
+ default_keys: list[str] = [
92
+ "opensearch_url",
93
+ "index_name",
94
+ *[i.name for i in LCVectorStoreComponent.inputs], # search_query, add_documents, etc.
95
+ "embedding",
96
+ "embedding_model_name",
97
+ "vector_field",
98
+ "number_of_results",
99
+ "auth_mode",
100
+ "username",
101
+ "password",
102
+ "jwt_token",
103
+ "jwt_header",
104
+ "bearer_prefix",
105
+ "use_ssl",
106
+ "verify_certs",
107
+ "filter_expression",
108
+ "engine",
109
+ "space_type",
110
+ "ef_construction",
111
+ "m",
112
+ "num_candidates",
113
+ "docs_metadata",
114
+ ]
115
+
116
+ inputs = [
117
+ TableInput(
118
+ name="docs_metadata",
119
+ display_name="Document Metadata",
120
+ info=(
121
+ "Additional metadata key-value pairs to be added to all ingested documents. "
122
+ "Useful for tagging documents with source information, categories, or other custom attributes."
123
+ ),
124
+ table_schema=[
125
+ {
126
+ "name": "key",
127
+ "display_name": "Key",
128
+ "type": "str",
129
+ "description": "Key name",
130
+ },
131
+ {
132
+ "name": "value",
133
+ "display_name": "Value",
134
+ "type": "str",
135
+ "description": "Value of the metadata",
136
+ },
137
+ ],
138
+ value=[],
139
+ input_types=["Data"],
140
+ ),
141
+ StrInput(
142
+ name="opensearch_url",
143
+ display_name="OpenSearch URL",
144
+ value="http://localhost:9200",
145
+ info=(
146
+ "The connection URL for your OpenSearch cluster "
147
+ "(e.g., http://localhost:9200 for local development or your cloud endpoint)."
148
+ ),
149
+ ),
150
+ StrInput(
151
+ name="index_name",
152
+ display_name="Index Name",
153
+ value="langflow",
154
+ info=(
155
+ "The OpenSearch index name where documents will be stored and searched. "
156
+ "Will be created automatically if it doesn't exist."
157
+ ),
158
+ ),
159
+ DropdownInput(
160
+ name="engine",
161
+ display_name="Vector Engine",
162
+ options=["jvector", "nmslib", "faiss", "lucene"],
163
+ value="jvector",
164
+ info=(
165
+ "Vector search engine for similarity calculations. 'jvector' is recommended for most use cases. "
166
+ "Note: Amazon OpenSearch Serverless only supports 'nmslib' or 'faiss'."
167
+ ),
168
+ advanced=True,
169
+ ),
170
+ DropdownInput(
171
+ name="space_type",
172
+ display_name="Distance Metric",
173
+ options=["l2", "l1", "cosinesimil", "linf", "innerproduct"],
174
+ value="l2",
175
+ info=(
176
+ "Distance metric for calculating vector similarity. 'l2' (Euclidean) is most common, "
177
+ "'cosinesimil' for cosine similarity, 'innerproduct' for dot product."
178
+ ),
179
+ advanced=True,
180
+ ),
181
+ IntInput(
182
+ name="ef_construction",
183
+ display_name="EF Construction",
184
+ value=512,
185
+ info=(
186
+ "Size of the dynamic candidate list during index construction. "
187
+ "Higher values improve recall but increase indexing time and memory usage."
188
+ ),
189
+ advanced=True,
190
+ ),
191
+ IntInput(
192
+ name="m",
193
+ display_name="M Parameter",
194
+ value=16,
195
+ info=(
196
+ "Number of bidirectional connections for each vector in the HNSW graph. "
197
+ "Higher values improve search quality but increase memory usage and indexing time."
198
+ ),
199
+ advanced=True,
200
+ ),
201
+ IntInput(
202
+ name="num_candidates",
203
+ display_name="Candidate Pool Size",
204
+ value=1000,
205
+ info=(
206
+ "Number of approximate neighbors to consider for each KNN query. "
207
+ "Some OpenSearch deployments do not support this parameter; set to 0 to disable."
208
+ ),
209
+ advanced=True,
210
+ ),
211
+ *LCVectorStoreComponent.inputs, # includes search_query, add_documents, etc.
212
+ HandleInput(name="embedding", display_name="Embedding", input_types=["Embeddings"], is_list=True),
213
+ StrInput(
214
+ name="embedding_model_name",
215
+ display_name="Embedding Model Name",
216
+ value="",
217
+ info=(
218
+ "Name of the embedding model to use for ingestion. This selects which embedding from the list "
219
+ "will be used to embed documents. Matches on deployment, model, model_id, or model_name. "
220
+ "For duplicate deployments, use combined format: 'deployment:model' "
221
+ "(e.g., 'text-embedding-ada-002:text-embedding-3-large'). "
222
+ "Leave empty to use the first embedding. Error message will show all available identifiers."
223
+ ),
224
+ advanced=False,
225
+ ),
226
+ StrInput(
227
+ name="vector_field",
228
+ display_name="Legacy Vector Field Name",
229
+ value="chunk_embedding",
230
+ advanced=True,
231
+ info=(
232
+ "Legacy field name for backward compatibility. New documents use dynamic fields "
233
+ "(chunk_embedding_{model_name}) based on the embedding_model_name."
234
+ ),
235
+ ),
236
+ IntInput(
237
+ name="number_of_results",
238
+ display_name="Default Result Limit",
239
+ value=10,
240
+ advanced=True,
241
+ info=(
242
+ "Default maximum number of search results to return when no limit is "
243
+ "specified in the filter expression."
244
+ ),
245
+ ),
246
+ MultilineInput(
247
+ name="filter_expression",
248
+ display_name="Search Filters (JSON)",
249
+ value="",
250
+ info=(
251
+ "Optional JSON configuration for search filtering, result limits, and score thresholds.\n\n"
252
+ "Format 1 - Explicit filters:\n"
253
+ '{"filter": [{"term": {"filename":"doc.pdf"}}, '
254
+ '{"terms":{"owner":["user1","user2"]}}], "limit": 10, "score_threshold": 1.6}\n\n'
255
+ "Format 2 - Context-style mapping:\n"
256
+ '{"data_sources":["file.pdf"], "document_types":["application/pdf"], "owners":["user123"]}\n\n'
257
+ "Use __IMPOSSIBLE_VALUE__ as placeholder to ignore specific filters."
258
+ ),
259
+ ),
260
+ # ----- Auth controls (dynamic) -----
261
+ DropdownInput(
262
+ name="auth_mode",
263
+ display_name="Authentication Mode",
264
+ value="basic",
265
+ options=["basic", "jwt"],
266
+ info=(
267
+ "Authentication method: 'basic' for username/password authentication, "
268
+ "or 'jwt' for JSON Web Token (Bearer) authentication."
269
+ ),
270
+ real_time_refresh=True,
271
+ advanced=False,
272
+ ),
273
+ StrInput(
274
+ name="username",
275
+ display_name="Username",
276
+ value="admin",
277
+ show=True,
278
+ ),
279
+ SecretStrInput(
280
+ name="password",
281
+ display_name="OpenSearch Password",
282
+ value="admin",
283
+ show=True,
284
+ ),
285
+ SecretStrInput(
286
+ name="jwt_token",
287
+ display_name="JWT Token",
288
+ value="JWT",
289
+ load_from_db=False,
290
+ show=False,
291
+ info=(
292
+ "Valid JSON Web Token for authentication. "
293
+ "Will be sent in the Authorization header (with optional 'Bearer ' prefix)."
294
+ ),
295
+ ),
296
+ StrInput(
297
+ name="jwt_header",
298
+ display_name="JWT Header Name",
299
+ value="Authorization",
300
+ show=False,
301
+ advanced=True,
302
+ ),
303
+ BoolInput(
304
+ name="bearer_prefix",
305
+ display_name="Prefix 'Bearer '",
306
+ value=True,
307
+ show=False,
308
+ advanced=True,
309
+ ),
310
+ # ----- TLS -----
311
+ BoolInput(
312
+ name="use_ssl",
313
+ display_name="Use SSL/TLS",
314
+ value=True,
315
+ advanced=True,
316
+ info="Enable SSL/TLS encryption for secure connections to OpenSearch.",
317
+ ),
318
+ BoolInput(
319
+ name="verify_certs",
320
+ display_name="Verify SSL Certificates",
321
+ value=False,
322
+ advanced=True,
323
+ info=(
324
+ "Verify SSL certificates when connecting. "
325
+ "Disable for self-signed certificates in development environments."
326
+ ),
327
+ ),
328
+ ]
329
+
330
+ def _get_embedding_model_name(self, embedding_obj=None) -> str:
331
+ """Get the embedding model name from component config or embedding object.
332
+
333
+ Priority: deployment > model > model_id > model_name
334
+ This ensures we use the actual model being deployed, not just the configured model.
335
+ Supports multiple embedding providers (OpenAI, Watsonx, Cohere, etc.)
336
+
337
+ Args:
338
+ embedding_obj: Specific embedding object to get name from (optional)
339
+
340
+ Returns:
341
+ Embedding model name
342
+
343
+ Raises:
344
+ ValueError: If embedding model name cannot be determined
345
+ """
346
+ # First try explicit embedding_model_name input
347
+ if hasattr(self, "embedding_model_name") and self.embedding_model_name:
348
+ return self.embedding_model_name.strip()
349
+
350
+ # Try to get from provided embedding object
351
+ if embedding_obj:
352
+ # Priority: deployment > model > model_id > model_name
353
+ if hasattr(embedding_obj, "deployment") and embedding_obj.deployment:
354
+ return str(embedding_obj.deployment)
355
+ if hasattr(embedding_obj, "model") and embedding_obj.model:
356
+ return str(embedding_obj.model)
357
+ if hasattr(embedding_obj, "model_id") and embedding_obj.model_id:
358
+ return str(embedding_obj.model_id)
359
+ if hasattr(embedding_obj, "model_name") and embedding_obj.model_name:
360
+ return str(embedding_obj.model_name)
361
+
362
+ # Try to get from embedding component (legacy single embedding)
363
+ if hasattr(self, "embedding") and self.embedding:
364
+ # Handle list of embeddings
365
+ if isinstance(self.embedding, list) and len(self.embedding) > 0:
366
+ first_emb = self.embedding[0]
367
+ if hasattr(first_emb, "deployment") and first_emb.deployment:
368
+ return str(first_emb.deployment)
369
+ if hasattr(first_emb, "model") and first_emb.model:
370
+ return str(first_emb.model)
371
+ if hasattr(first_emb, "model_id") and first_emb.model_id:
372
+ return str(first_emb.model_id)
373
+ if hasattr(first_emb, "model_name") and first_emb.model_name:
374
+ return str(first_emb.model_name)
375
+ # Handle single embedding
376
+ elif not isinstance(self.embedding, list):
377
+ if hasattr(self.embedding, "deployment") and self.embedding.deployment:
378
+ return str(self.embedding.deployment)
379
+ if hasattr(self.embedding, "model") and self.embedding.model:
380
+ return str(self.embedding.model)
381
+ if hasattr(self.embedding, "model_id") and self.embedding.model_id:
382
+ return str(self.embedding.model_id)
383
+ if hasattr(self.embedding, "model_name") and self.embedding.model_name:
384
+ return str(self.embedding.model_name)
385
+
386
+ msg = (
387
+ "Could not determine embedding model name. "
388
+ "Please set the 'embedding_model_name' field or ensure the embedding component "
389
+ "has a 'deployment', 'model', 'model_id', or 'model_name' attribute."
390
+ )
391
+ raise ValueError(msg)
392
+
393
+ # ---------- helper functions for index management ----------
394
+ def _default_text_mapping(
395
+ self,
396
+ dim: int,
397
+ engine: str = "jvector",
398
+ space_type: str = "l2",
399
+ ef_search: int = 512,
400
+ ef_construction: int = 100,
401
+ m: int = 16,
402
+ vector_field: str = "vector_field",
403
+ ) -> dict[str, Any]:
404
+ """Create the default OpenSearch index mapping for vector search.
405
+
406
+ This method generates the index configuration with k-NN settings optimized
407
+ for approximate nearest neighbor search using the specified vector engine.
408
+ Includes the embedding_model keyword field for tracking which model was used.
409
+
410
+ Args:
411
+ dim: Dimensionality of the vector embeddings
412
+ engine: Vector search engine (jvector, nmslib, faiss, lucene)
413
+ space_type: Distance metric for similarity calculation
414
+ ef_search: Size of dynamic list used during search
415
+ ef_construction: Size of dynamic list used during index construction
416
+ m: Number of bidirectional links for each vector
417
+ vector_field: Name of the field storing vector embeddings
418
+
419
+ Returns:
420
+ Dictionary containing OpenSearch index mapping configuration
421
+ """
422
+ return {
423
+ "settings": {"index": {"knn": True, "knn.algo_param.ef_search": ef_search}},
424
+ "mappings": {
425
+ "properties": {
426
+ vector_field: {
427
+ "type": "knn_vector",
428
+ "dimension": dim,
429
+ "method": {
430
+ "name": "disk_ann",
431
+ "space_type": space_type,
432
+ "engine": engine,
433
+ "parameters": {"ef_construction": ef_construction, "m": m},
434
+ },
435
+ },
436
+ "embedding_model": {"type": "keyword"}, # Track which model was used
437
+ "embedding_dimensions": {"type": "integer"},
438
+ }
439
+ },
440
+ }
441
+
442
+ def _ensure_embedding_field_mapping(
443
+ self,
444
+ client: OpenSearch,
445
+ index_name: str,
446
+ field_name: str,
447
+ dim: int,
448
+ engine: str,
449
+ space_type: str,
450
+ ef_construction: int,
451
+ m: int,
452
+ ) -> None:
453
+ """Lazily add a dynamic embedding field to the index if it doesn't exist.
454
+
455
+ This allows adding new embedding models without recreating the entire index.
456
+ Also ensures the embedding_model tracking field exists.
457
+
458
+ Args:
459
+ client: OpenSearch client instance
460
+ index_name: Target index name
461
+ field_name: Dynamic field name for this embedding model
462
+ dim: Vector dimensionality
463
+ engine: Vector search engine
464
+ space_type: Distance metric
465
+ ef_construction: Construction parameter
466
+ m: HNSW parameter
467
+ """
468
+ try:
469
+ mapping = {
470
+ "properties": {
471
+ field_name: {
472
+ "type": "knn_vector",
473
+ "dimension": dim,
474
+ "method": {
475
+ "name": "disk_ann",
476
+ "space_type": space_type,
477
+ "engine": engine,
478
+ "parameters": {"ef_construction": ef_construction, "m": m},
479
+ },
480
+ },
481
+ # Also ensure the embedding_model tracking field exists as keyword
482
+ "embedding_model": {"type": "keyword"},
483
+ "embedding_dimensions": {"type": "integer"},
484
+ }
485
+ }
486
+ client.indices.put_mapping(index=index_name, body=mapping)
487
+ logger.info(f"Added/updated embedding field mapping: {field_name}")
488
+ except Exception as e:
489
+ logger.warning(f"Could not add embedding field mapping for {field_name}: {e}")
490
+ raise
491
+
492
+ properties = self._get_index_properties(client)
493
+ if not self._is_knn_vector_field(properties, field_name):
494
+ msg = f"Field '{field_name}' is not mapped as knn_vector. Current mapping: {properties.get(field_name)}"
495
+ logger.aerror(msg)
496
+ raise ValueError(msg)
497
+
498
+ def _validate_aoss_with_engines(self, *, is_aoss: bool, engine: str) -> None:
499
+ """Validate engine compatibility with Amazon OpenSearch Serverless (AOSS).
500
+
501
+ Amazon OpenSearch Serverless has restrictions on which vector engines
502
+ can be used. This method ensures the selected engine is compatible.
503
+
504
+ Args:
505
+ is_aoss: Whether the connection is to Amazon OpenSearch Serverless
506
+ engine: The selected vector search engine
507
+
508
+ Raises:
509
+ ValueError: If AOSS is used with an incompatible engine
510
+ """
511
+ if is_aoss and engine not in {"nmslib", "faiss"}:
512
+ msg = "Amazon OpenSearch Service Serverless only supports `nmslib` or `faiss` engines"
513
+ raise ValueError(msg)
514
+
515
+ def _is_aoss_enabled(self, http_auth: Any) -> bool:
516
+ """Determine if Amazon OpenSearch Serverless (AOSS) is being used.
517
+
518
+ Args:
519
+ http_auth: The HTTP authentication object
520
+
521
+ Returns:
522
+ True if AOSS is enabled, False otherwise
523
+ """
524
+ return http_auth is not None and hasattr(http_auth, "service") and http_auth.service == "aoss"
525
+
526
+ def _bulk_ingest_embeddings(
527
+ self,
528
+ client: OpenSearch,
529
+ index_name: str,
530
+ embeddings: list[list[float]],
531
+ texts: list[str],
532
+ metadatas: list[dict] | None = None,
533
+ ids: list[str] | None = None,
534
+ vector_field: str = "vector_field",
535
+ text_field: str = "text",
536
+ embedding_model: str = "unknown",
537
+ mapping: dict | None = None,
538
+ max_chunk_bytes: int | None = 1 * 1024 * 1024,
539
+ *,
540
+ is_aoss: bool = False,
541
+ ) -> list[str]:
542
+ """Efficiently ingest multiple documents with embeddings into OpenSearch.
543
+
544
+ This method uses bulk operations to insert documents with their vector
545
+ embeddings and metadata into the specified OpenSearch index. Each document
546
+ is tagged with the embedding_model name for tracking.
547
+
548
+ Args:
549
+ client: OpenSearch client instance
550
+ index_name: Target index for document storage
551
+ embeddings: List of vector embeddings for each document
552
+ texts: List of document texts
553
+ metadatas: Optional metadata dictionaries for each document
554
+ ids: Optional document IDs (UUIDs generated if not provided)
555
+ vector_field: Field name for storing vector embeddings
556
+ text_field: Field name for storing document text
557
+ embedding_model: Name of the embedding model used
558
+ mapping: Optional index mapping configuration
559
+ max_chunk_bytes: Maximum size per bulk request chunk
560
+ is_aoss: Whether using Amazon OpenSearch Serverless
561
+
562
+ Returns:
563
+ List of document IDs that were successfully ingested
564
+ """
565
+ if not mapping:
566
+ mapping = {}
567
+
568
+ requests = []
569
+ return_ids = []
570
+ vector_dimensions = len(embeddings[0]) if embeddings else None
571
+
572
+ for i, text in enumerate(texts):
573
+ metadata = metadatas[i] if metadatas else {}
574
+ if vector_dimensions is not None and "embedding_dimensions" not in metadata:
575
+ metadata = {**metadata, "embedding_dimensions": vector_dimensions}
576
+ _id = ids[i] if ids else str(uuid.uuid4())
577
+ request = {
578
+ "_op_type": "index",
579
+ "_index": index_name,
580
+ vector_field: embeddings[i],
581
+ text_field: text,
582
+ "embedding_model": embedding_model, # Track which model was used
583
+ **metadata,
584
+ }
585
+ if is_aoss:
586
+ request["id"] = _id
587
+ else:
588
+ request["_id"] = _id
589
+ requests.append(request)
590
+ return_ids.append(_id)
591
+ if metadatas:
592
+ self.log(f"Sample metadata: {metadatas[0] if metadatas else {}}")
593
+ helpers.bulk(client, requests, max_chunk_bytes=max_chunk_bytes)
594
+ return return_ids
595
+
596
+ # ---------- auth / client ----------
597
+ def _build_auth_kwargs(self) -> dict[str, Any]:
598
+ """Build authentication configuration for OpenSearch client.
599
+
600
+ Constructs the appropriate authentication parameters based on the
601
+ selected auth mode (basic username/password or JWT token).
602
+
603
+ Returns:
604
+ Dictionary containing authentication configuration
605
+
606
+ Raises:
607
+ ValueError: If required authentication parameters are missing
608
+ """
609
+ mode = (self.auth_mode or "basic").strip().lower()
610
+ if mode == "jwt":
611
+ token = (self.jwt_token or "").strip()
612
+ if not token:
613
+ msg = "Auth Mode is 'jwt' but no jwt_token was provided."
614
+ raise ValueError(msg)
615
+ header_name = (self.jwt_header or "Authorization").strip()
616
+ header_value = f"Bearer {token}" if self.bearer_prefix else token
617
+ return {"headers": {header_name: header_value}}
618
+ user = (self.username or "").strip()
619
+ pwd = (self.password or "").strip()
620
+ if not user or not pwd:
621
+ msg = "Auth Mode is 'basic' but username/password are missing."
622
+ raise ValueError(msg)
623
+ return {"http_auth": (user, pwd)}
624
+
625
+ def build_client(self) -> OpenSearch:
626
+ """Create and configure an OpenSearch client instance.
627
+
628
+ Returns:
629
+ Configured OpenSearch client ready for operations
630
+ """
631
+ auth_kwargs = self._build_auth_kwargs()
632
+ return OpenSearch(
633
+ hosts=[self.opensearch_url],
634
+ use_ssl=self.use_ssl,
635
+ verify_certs=self.verify_certs,
636
+ ssl_assert_hostname=False,
637
+ ssl_show_warn=False,
638
+ **auth_kwargs,
639
+ )
640
+
641
+ @check_cached_vector_store
642
+ def build_vector_store(self) -> OpenSearch:
643
+ # Return raw OpenSearch client as our "vector store."
644
+ client = self.build_client()
645
+
646
+ # Check if we're in ingestion-only mode (no search query)
647
+ has_search_query = bool((self.search_query or "").strip())
648
+ if not has_search_query:
649
+ logger.debug("Ingestion-only mode activated: search operations will be skipped")
650
+ logger.debug("Starting ingestion mode...")
651
+
652
+ logger.warning(f"Embedding: {self.embedding}")
653
+ self._add_documents_to_vector_store(client=client)
654
+ return client
655
+
656
+ # ---------- ingest ----------
657
+ def _add_documents_to_vector_store(self, client: OpenSearch) -> None:
658
+ """Process and ingest documents into the OpenSearch vector store.
659
+
660
+ This method handles the complete document ingestion pipeline:
661
+ - Prepares document data and metadata
662
+ - Generates vector embeddings using the selected model
663
+ - Creates appropriate index mappings with dynamic field names
664
+ - Bulk inserts documents with vectors and model tracking
665
+
666
+ Args:
667
+ client: OpenSearch client for performing operations
668
+ """
669
+ logger.debug("[INGESTION] _add_documents_to_vector_store called")
670
+ # Convert DataFrame to Data if needed using parent's method
671
+ self.ingest_data = self._prepare_ingest_data()
672
+
673
+ logger.debug(
674
+ f"[INGESTION] ingest_data type: "
675
+ f"{type(self.ingest_data)}, length: {len(self.ingest_data) if self.ingest_data else 0}"
676
+ )
677
+ logger.debug(
678
+ f"[INGESTION] ingest_data content: "
679
+ f"{self.ingest_data[:2] if self.ingest_data and len(self.ingest_data) > 0 else 'empty'}"
680
+ )
681
+
682
+ docs = self.ingest_data or []
683
+ if not docs:
684
+ logger.debug("Ingestion complete: No documents provided")
685
+ return
686
+
687
+ if not self.embedding:
688
+ msg = "Embedding handle is required to embed documents."
689
+ raise ValueError(msg)
690
+
691
+ # Normalize embedding to list first
692
+ embeddings_list = self.embedding if isinstance(self.embedding, list) else [self.embedding]
693
+
694
+ # Filter out None values (fail-safe mode) - do this BEFORE checking if empty
695
+ embeddings_list = [e for e in embeddings_list if e is not None]
696
+
697
+ # NOW check if we have any valid embeddings left after filtering
698
+ if not embeddings_list:
699
+ logger.warning("All embeddings returned None (fail-safe mode enabled). Skipping document ingestion.")
700
+ self.log("Embedding returned None (fail-safe mode enabled). Skipping document ingestion.")
701
+ return
702
+
703
+ logger.debug(f"[INGESTION] Valid embeddings after filtering: {len(embeddings_list)}")
704
+ self.log(f"Available embedding models: {len(embeddings_list)}")
705
+
706
+ # Select the embedding to use for ingestion
707
+ selected_embedding = None
708
+ embedding_model = None
709
+
710
+ # If embedding_model_name is specified, find matching embedding
711
+ if hasattr(self, "embedding_model_name") and self.embedding_model_name and self.embedding_model_name.strip():
712
+ target_model_name = self.embedding_model_name.strip()
713
+ self.log(f"Looking for embedding model: {target_model_name}")
714
+
715
+ for emb_obj in embeddings_list:
716
+ # Check all possible model identifiers (deployment, model, model_id, model_name)
717
+ # Also check available_models list from EmbeddingsWithModels
718
+ possible_names = []
719
+ deployment = getattr(emb_obj, "deployment", None)
720
+ model = getattr(emb_obj, "model", None)
721
+ model_id = getattr(emb_obj, "model_id", None)
722
+ model_name = getattr(emb_obj, "model_name", None)
723
+ available_models_attr = getattr(emb_obj, "available_models", None)
724
+
725
+ if deployment:
726
+ possible_names.append(str(deployment))
727
+ if model:
728
+ possible_names.append(str(model))
729
+ if model_id:
730
+ possible_names.append(str(model_id))
731
+ if model_name:
732
+ possible_names.append(str(model_name))
733
+
734
+ # Also add combined identifier
735
+ if deployment and model and deployment != model:
736
+ possible_names.append(f"{deployment}:{model}")
737
+
738
+ # Add all models from available_models dict
739
+ if available_models_attr and isinstance(available_models_attr, dict):
740
+ possible_names.extend(
741
+ str(model_key).strip()
742
+ for model_key in available_models_attr
743
+ if model_key and str(model_key).strip()
744
+ )
745
+
746
+ # Match if target matches any of the possible names
747
+ if target_model_name in possible_names:
748
+ # Check if target is in available_models dict - use dedicated instance
749
+ if (
750
+ available_models_attr
751
+ and isinstance(available_models_attr, dict)
752
+ and target_model_name in available_models_attr
753
+ ):
754
+ # Use the dedicated embedding instance from the dict
755
+ selected_embedding = available_models_attr[target_model_name]
756
+ embedding_model = target_model_name
757
+ self.log(f"Found dedicated embedding instance for '{embedding_model}' in available_models dict")
758
+ else:
759
+ # Traditional identifier match
760
+ selected_embedding = emb_obj
761
+ embedding_model = self._get_embedding_model_name(emb_obj)
762
+ self.log(f"Found matching embedding model: {embedding_model} (matched on: {target_model_name})")
763
+ break
764
+
765
+ if not selected_embedding:
766
+ # Build detailed list of available embeddings with all their identifiers
767
+ available_info = []
768
+ for idx, emb in enumerate(embeddings_list):
769
+ emb_type = type(emb).__name__
770
+ identifiers = []
771
+ deployment = getattr(emb, "deployment", None)
772
+ model = getattr(emb, "model", None)
773
+ model_id = getattr(emb, "model_id", None)
774
+ model_name = getattr(emb, "model_name", None)
775
+ available_models_attr = getattr(emb, "available_models", None)
776
+
777
+ if deployment:
778
+ identifiers.append(f"deployment='{deployment}'")
779
+ if model:
780
+ identifiers.append(f"model='{model}'")
781
+ if model_id:
782
+ identifiers.append(f"model_id='{model_id}'")
783
+ if model_name:
784
+ identifiers.append(f"model_name='{model_name}'")
785
+
786
+ # Add combined identifier as an option
787
+ if deployment and model and deployment != model:
788
+ identifiers.append(f"combined='{deployment}:{model}'")
789
+
790
+ # Add available_models dict if present
791
+ if available_models_attr and isinstance(available_models_attr, dict):
792
+ identifiers.append(f"available_models={list(available_models_attr.keys())}")
793
+
794
+ available_info.append(
795
+ f" [{idx}] {emb_type}: {', '.join(identifiers) if identifiers else 'No identifiers'}"
796
+ )
797
+
798
+ msg = (
799
+ f"Embedding model '{target_model_name}' not found in available embeddings.\n\n"
800
+ f"Available embeddings:\n" + "\n".join(available_info) + "\n\n"
801
+ "Please set 'embedding_model_name' to one of the identifier values shown above "
802
+ "(use the value after the '=' sign, without quotes).\n"
803
+ "For duplicate deployments, use the 'combined' format.\n"
804
+ "Or leave it empty to use the first embedding."
805
+ )
806
+ raise ValueError(msg)
807
+ else:
808
+ # Use first embedding if no model name specified
809
+ selected_embedding = embeddings_list[0]
810
+ embedding_model = self._get_embedding_model_name(selected_embedding)
811
+ self.log(f"No embedding_model_name specified, using first embedding: {embedding_model}")
812
+
813
+ dynamic_field_name = get_embedding_field_name(embedding_model)
814
+
815
+ logger.info(f"Selected embedding model for ingestion: '{embedding_model}'")
816
+ self.log(f"Using embedding model for ingestion: {embedding_model}")
817
+ self.log(f"Dynamic vector field: {dynamic_field_name}")
818
+
819
+ # Log embedding details for debugging
820
+ if hasattr(selected_embedding, "deployment"):
821
+ logger.info(f"Embedding deployment: {selected_embedding.deployment}")
822
+ if hasattr(selected_embedding, "model"):
823
+ logger.info(f"Embedding model: {selected_embedding.model}")
824
+ if hasattr(selected_embedding, "model_id"):
825
+ logger.info(f"Embedding model_id: {selected_embedding.model_id}")
826
+ if hasattr(selected_embedding, "dimensions"):
827
+ logger.info(f"Embedding dimensions: {selected_embedding.dimensions}")
828
+ if hasattr(selected_embedding, "available_models"):
829
+ logger.info(f"Embedding available_models: {selected_embedding.available_models}")
830
+
831
+ # No model switching needed - each model in available_models has its own dedicated instance
832
+ # The selected_embedding is already configured correctly for the target model
833
+ logger.info(f"Using embedding instance for '{embedding_model}' - pre-configured and ready to use")
834
+
835
+ # Extract texts and metadata from documents
836
+ texts = []
837
+ metadatas = []
838
+ # Process docs_metadata table input into a dict
839
+ additional_metadata = {}
840
+ logger.debug(f"[LF] Docs metadata {self.docs_metadata}")
841
+ if hasattr(self, "docs_metadata") and self.docs_metadata:
842
+ logger.info(f"[LF] Docs metadata {self.docs_metadata}")
843
+ if isinstance(self.docs_metadata[-1], Data):
844
+ logger.info(f"[LF] Docs metadata is a Data object {self.docs_metadata}")
845
+ self.docs_metadata = self.docs_metadata[-1].data
846
+ logger.info(f"[LF] Docs metadata is a Data object {self.docs_metadata}")
847
+ additional_metadata.update(self.docs_metadata)
848
+ else:
849
+ for item in self.docs_metadata:
850
+ if isinstance(item, dict) and "key" in item and "value" in item:
851
+ additional_metadata[item["key"]] = item["value"]
852
+ # Replace string "None" values with actual None
853
+ for key, value in additional_metadata.items():
854
+ if value == "None":
855
+ additional_metadata[key] = None
856
+ logger.info(f"[LF] Additional metadata {additional_metadata}")
857
+ for doc_obj in docs:
858
+ data_copy = json.loads(doc_obj.model_dump_json())
859
+ text = data_copy.pop(doc_obj.text_key, doc_obj.default_value)
860
+ texts.append(text)
861
+
862
+ # Merge additional metadata from table input
863
+ data_copy.update(additional_metadata)
864
+
865
+ metadatas.append(data_copy)
866
+ self.log(metadatas)
867
+
868
+ # Generate embeddings with rate-limit-aware retry logic using tenacity
869
+ from tenacity import (
870
+ retry,
871
+ retry_if_exception,
872
+ stop_after_attempt,
873
+ wait_exponential,
874
+ )
875
+
876
+ def is_rate_limit_error(exception: Exception) -> bool:
877
+ """Check if exception is a rate limit error (429)."""
878
+ error_str = str(exception).lower()
879
+ return "429" in error_str or "rate_limit" in error_str or "rate limit" in error_str
880
+
881
+ def is_other_retryable_error(exception: Exception) -> bool:
882
+ """Check if exception is retryable but not a rate limit error."""
883
+ # Retry on most exceptions except for specific non-retryable ones
884
+ # Add other non-retryable exceptions here if needed
885
+ return not is_rate_limit_error(exception)
886
+
887
+ # Create retry decorator for rate limit errors (longer backoff)
888
+ retry_on_rate_limit = retry(
889
+ retry=retry_if_exception(is_rate_limit_error),
890
+ stop=stop_after_attempt(5),
891
+ wait=wait_exponential(multiplier=2, min=2, max=30),
892
+ reraise=True,
893
+ before_sleep=lambda retry_state: logger.warning(
894
+ f"Rate limit hit for chunk (attempt {retry_state.attempt_number}/5), "
895
+ f"backing off for {retry_state.next_action.sleep:.1f}s"
896
+ ),
897
+ )
898
+
899
+ # Create retry decorator for other errors (shorter backoff)
900
+ retry_on_other_errors = retry(
901
+ retry=retry_if_exception(is_other_retryable_error),
902
+ stop=stop_after_attempt(3),
903
+ wait=wait_exponential(multiplier=1, min=1, max=8),
904
+ reraise=True,
905
+ before_sleep=lambda retry_state: logger.warning(
906
+ f"Error embedding chunk (attempt {retry_state.attempt_number}/3), "
907
+ f"retrying in {retry_state.next_action.sleep:.1f}s: {retry_state.outcome.exception()}"
908
+ ),
909
+ )
910
+
911
+ def embed_chunk_with_retry(chunk_text: str, chunk_idx: int) -> list[float]:
912
+ """Embed a single chunk with rate-limit-aware retry logic."""
913
+
914
+ @retry_on_rate_limit
915
+ @retry_on_other_errors
916
+ def _embed(text: str) -> list[float]:
917
+ return selected_embedding.embed_documents([text])[0]
918
+
919
+ try:
920
+ return _embed(chunk_text)
921
+ except Exception as e:
922
+ logger.error(
923
+ f"Failed to embed chunk {chunk_idx} after all retries: {e}",
924
+ error=str(e),
925
+ )
926
+ raise
927
+
928
+ # Restrict concurrency for IBM/Watsonx models to avoid rate limits
929
+ is_ibm = (embedding_model and "ibm" in str(embedding_model).lower()) or (
930
+ selected_embedding and "watsonx" in type(selected_embedding).__name__.lower()
931
+ )
932
+ logger.debug(f"Is IBM: {is_ibm}")
933
+
934
+ # For IBM models, use sequential processing with rate limiting
935
+ # For other models, use parallel processing
936
+ vectors: list[list[float]] = [None] * len(texts)
937
+
938
+ if is_ibm:
939
+ # Sequential processing with inter-request delay for IBM models
940
+ inter_request_delay = 0.6 # ~1.67 req/s, safely under 2 req/s limit
941
+ logger.info(f"Using sequential processing for IBM model with {inter_request_delay}s delay between requests")
942
+
943
+ for idx, chunk in enumerate(texts):
944
+ if idx > 0:
945
+ # Add delay between requests (but not before the first one)
946
+ time.sleep(inter_request_delay)
947
+ vectors[idx] = embed_chunk_with_retry(chunk, idx)
948
+ else:
949
+ # Parallel processing for non-IBM models
950
+ max_workers = min(max(len(texts), 1), 8)
951
+ logger.debug(f"Using parallel processing with {max_workers} workers")
952
+
953
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
954
+ futures = {executor.submit(embed_chunk_with_retry, chunk, idx): idx for idx, chunk in enumerate(texts)}
955
+ for future in as_completed(futures):
956
+ idx = futures[future]
957
+ vectors[idx] = future.result()
958
+
959
+ if not vectors:
960
+ self.log(f"No vectors generated from documents for model {embedding_model}.")
961
+ return
962
+
963
+ # Get vector dimension for mapping
964
+ dim = len(vectors[0]) if vectors else 768 # default fallback
965
+
966
+ # Check for AOSS
967
+ auth_kwargs = self._build_auth_kwargs()
968
+ is_aoss = self._is_aoss_enabled(auth_kwargs.get("http_auth"))
969
+
970
+ # Validate engine with AOSS
971
+ engine = getattr(self, "engine", "jvector")
972
+ self._validate_aoss_with_engines(is_aoss=is_aoss, engine=engine)
973
+
974
+ # Create mapping with proper KNN settings
975
+ space_type = getattr(self, "space_type", "l2")
976
+ ef_construction = getattr(self, "ef_construction", 512)
977
+ m = getattr(self, "m", 16)
978
+
979
+ mapping = self._default_text_mapping(
980
+ dim=dim,
981
+ engine=engine,
982
+ space_type=space_type,
983
+ ef_construction=ef_construction,
984
+ m=m,
985
+ vector_field=dynamic_field_name, # Use dynamic field name
986
+ )
987
+
988
+ # Ensure index exists with baseline mapping
989
+ try:
990
+ if not client.indices.exists(index=self.index_name):
991
+ self.log(f"Creating index '{self.index_name}' with base mapping")
992
+ client.indices.create(index=self.index_name, body=mapping)
993
+ except RequestError as creation_error:
994
+ if creation_error.error != "resource_already_exists_exception":
995
+ logger.warning(f"Failed to create index '{self.index_name}': {creation_error}")
996
+
997
+ # Ensure the dynamic field exists in the index
998
+ self._ensure_embedding_field_mapping(
999
+ client=client,
1000
+ index_name=self.index_name,
1001
+ field_name=dynamic_field_name,
1002
+ dim=dim,
1003
+ engine=engine,
1004
+ space_type=space_type,
1005
+ ef_construction=ef_construction,
1006
+ m=m,
1007
+ )
1008
+
1009
+ self.log(f"Indexing {len(texts)} documents into '{self.index_name}' with model '{embedding_model}'...")
1010
+ logger.info(f"Will store embeddings in field: {dynamic_field_name}")
1011
+ logger.info(f"Will tag documents with embedding_model: {embedding_model}")
1012
+
1013
+ # Use the bulk ingestion with model tracking
1014
+ return_ids = self._bulk_ingest_embeddings(
1015
+ client=client,
1016
+ index_name=self.index_name,
1017
+ embeddings=vectors,
1018
+ texts=texts,
1019
+ metadatas=metadatas,
1020
+ vector_field=dynamic_field_name, # Use dynamic field name
1021
+ text_field="text",
1022
+ embedding_model=embedding_model, # Track the model
1023
+ mapping=mapping,
1024
+ is_aoss=is_aoss,
1025
+ )
1026
+ self.log(metadatas)
1027
+
1028
+ logger.info(
1029
+ f"Ingestion complete: Successfully indexed {len(return_ids)} documents with model '{embedding_model}'"
1030
+ )
1031
+ self.log(f"Successfully indexed {len(return_ids)} documents with model {embedding_model}.")
1032
+
1033
+ # ---------- helpers for filters ----------
1034
+ def _is_placeholder_term(self, term_obj: dict) -> bool:
1035
+ # term_obj like {"filename": "__IMPOSSIBLE_VALUE__"}
1036
+ return any(v == "__IMPOSSIBLE_VALUE__" for v in term_obj.values())
1037
+
1038
+ def _coerce_filter_clauses(self, filter_obj: dict | None) -> list[dict]:
1039
+ """Convert filter expressions into OpenSearch-compatible filter clauses.
1040
+
1041
+ This method accepts two filter formats and converts them to standardized
1042
+ OpenSearch query clauses:
1043
+
1044
+ Format A - Explicit filters:
1045
+ {"filter": [{"term": {"field": "value"}}, {"terms": {"field": ["val1", "val2"]}}],
1046
+ "limit": 10, "score_threshold": 1.5}
1047
+
1048
+ Format B - Context-style mapping:
1049
+ {"data_sources": ["file1.pdf"], "document_types": ["pdf"], "owners": ["user1"]}
1050
+
1051
+ Args:
1052
+ filter_obj: Filter configuration dictionary or None
1053
+
1054
+ Returns:
1055
+ List of OpenSearch filter clauses (term/terms objects)
1056
+ Placeholder values with "__IMPOSSIBLE_VALUE__" are ignored
1057
+ """
1058
+ if not filter_obj:
1059
+ return []
1060
+
1061
+ # If it is a string, try to parse it once
1062
+ if isinstance(filter_obj, str):
1063
+ try:
1064
+ filter_obj = json.loads(filter_obj)
1065
+ except json.JSONDecodeError:
1066
+ # Not valid JSON - treat as no filters
1067
+ return []
1068
+
1069
+ # Case A: already an explicit list/dict under "filter"
1070
+ if "filter" in filter_obj:
1071
+ raw = filter_obj["filter"]
1072
+ if isinstance(raw, dict):
1073
+ raw = [raw]
1074
+ explicit_clauses: list[dict] = []
1075
+ for f in raw or []:
1076
+ if "term" in f and isinstance(f["term"], dict) and not self._is_placeholder_term(f["term"]):
1077
+ explicit_clauses.append(f)
1078
+ elif "terms" in f and isinstance(f["terms"], dict):
1079
+ field, vals = next(iter(f["terms"].items()))
1080
+ if isinstance(vals, list) and len(vals) > 0:
1081
+ explicit_clauses.append(f)
1082
+ return explicit_clauses
1083
+
1084
+ # Case B: convert context-style maps into clauses
1085
+ field_mapping = {
1086
+ "data_sources": "filename",
1087
+ "document_types": "mimetype",
1088
+ "owners": "owner",
1089
+ }
1090
+ context_clauses: list[dict] = []
1091
+ for k, values in filter_obj.items():
1092
+ if not isinstance(values, list):
1093
+ continue
1094
+ field = field_mapping.get(k, k)
1095
+ if len(values) == 0:
1096
+ # Match-nothing placeholder (kept to mirror your tool semantics)
1097
+ context_clauses.append({"term": {field: "__IMPOSSIBLE_VALUE__"}})
1098
+ elif len(values) == 1:
1099
+ if values[0] != "__IMPOSSIBLE_VALUE__":
1100
+ context_clauses.append({"term": {field: values[0]}})
1101
+ else:
1102
+ context_clauses.append({"terms": {field: values}})
1103
+ return context_clauses
1104
+
1105
+ def _detect_available_models(self, client: OpenSearch, filter_clauses: list[dict] | None = None) -> list[str]:
1106
+ """Detect which embedding models have documents in the index.
1107
+
1108
+ Uses aggregation to find all unique embedding_model values, optionally
1109
+ filtered to only documents matching the user's filter criteria.
1110
+
1111
+ Args:
1112
+ client: OpenSearch client instance
1113
+ filter_clauses: Optional filter clauses to scope model detection
1114
+
1115
+ Returns:
1116
+ List of embedding model names found in the index
1117
+ """
1118
+ try:
1119
+ agg_query = {"size": 0, "aggs": {"embedding_models": {"terms": {"field": "embedding_model", "size": 10}}}}
1120
+
1121
+ # Apply filters to model detection if any exist
1122
+ if filter_clauses:
1123
+ agg_query["query"] = {"bool": {"filter": filter_clauses}}
1124
+
1125
+ logger.debug(f"Model detection query: {agg_query}")
1126
+ result = client.search(
1127
+ index=self.index_name,
1128
+ body=agg_query,
1129
+ params={"terminate_after": 0},
1130
+ )
1131
+ buckets = result.get("aggregations", {}).get("embedding_models", {}).get("buckets", [])
1132
+ models = [b["key"] for b in buckets if b["key"]]
1133
+
1134
+ # Log detailed bucket info for debugging
1135
+ logger.info(
1136
+ f"Detected embedding models in corpus: {models}"
1137
+ + (f" (with {len(filter_clauses)} filters)" if filter_clauses else "")
1138
+ )
1139
+ if not models:
1140
+ total_hits = result.get("hits", {}).get("total", {})
1141
+ total_count = total_hits.get("value", 0) if isinstance(total_hits, dict) else total_hits
1142
+ logger.warning(
1143
+ f"No embedding_model values found in index '{self.index_name}'. "
1144
+ f"Total docs in index: {total_count}. "
1145
+ f"This may indicate documents were indexed without the embedding_model field."
1146
+ )
1147
+ except (OpenSearchException, KeyError, ValueError) as e:
1148
+ logger.warning(f"Failed to detect embedding models: {e}")
1149
+ # Fallback to current model
1150
+ fallback_model = self._get_embedding_model_name()
1151
+ logger.info(f"Using fallback model: {fallback_model}")
1152
+ return [fallback_model]
1153
+ else:
1154
+ return models
1155
+
1156
+ def _get_index_properties(self, client: OpenSearch) -> dict[str, Any] | None:
1157
+ """Retrieve flattened mapping properties for the current index."""
1158
+ try:
1159
+ mapping = client.indices.get_mapping(index=self.index_name)
1160
+ except OpenSearchException as e:
1161
+ logger.warning(
1162
+ f"Failed to fetch mapping for index '{self.index_name}': {e}. Proceeding without mapping metadata."
1163
+ )
1164
+ return None
1165
+
1166
+ properties: dict[str, Any] = {}
1167
+ for index_data in mapping.values():
1168
+ props = index_data.get("mappings", {}).get("properties", {})
1169
+ if isinstance(props, dict):
1170
+ properties.update(props)
1171
+ return properties
1172
+
1173
+ def _is_knn_vector_field(self, properties: dict[str, Any] | None, field_name: str) -> bool:
1174
+ """Check whether the field is mapped as a knn_vector."""
1175
+ if not field_name:
1176
+ return False
1177
+ if properties is None:
1178
+ logger.warning(f"Mapping metadata unavailable; assuming field '{field_name}' is usable.")
1179
+ return True
1180
+ field_def = properties.get(field_name)
1181
+ if not isinstance(field_def, dict):
1182
+ return False
1183
+ if field_def.get("type") == "knn_vector":
1184
+ return True
1185
+
1186
+ nested_props = field_def.get("properties")
1187
+ return bool(isinstance(nested_props, dict) and nested_props.get("type") == "knn_vector")
1188
+
1189
+ def _get_field_dimension(self, properties: dict[str, Any] | None, field_name: str) -> int | None:
1190
+ """Get the dimension of a knn_vector field from the index mapping.
1191
+
1192
+ Args:
1193
+ properties: Index properties from mapping
1194
+ field_name: Name of the vector field
1195
+
1196
+ Returns:
1197
+ Dimension of the field, or None if not found
1198
+ """
1199
+ if not field_name or properties is None:
1200
+ return None
1201
+
1202
+ field_def = properties.get(field_name)
1203
+ if not isinstance(field_def, dict):
1204
+ return None
1205
+
1206
+ # Check direct knn_vector field
1207
+ if field_def.get("type") == "knn_vector":
1208
+ return field_def.get("dimension")
1209
+
1210
+ # Check nested properties
1211
+ nested_props = field_def.get("properties")
1212
+ if isinstance(nested_props, dict) and nested_props.get("type") == "knn_vector":
1213
+ return nested_props.get("dimension")
1214
+
1215
+ return None
1216
+
1217
+ # ---------- search (multi-model hybrid) ----------
1218
+ def search(self, query: str | None = None) -> list[dict[str, Any]]:
1219
+ """Perform multi-model hybrid search combining multiple vector similarities and keyword matching.
1220
+
1221
+ This method executes a sophisticated search that:
1222
+ 1. Auto-detects all embedding models present in the index
1223
+ 2. Generates query embeddings for ALL detected models in parallel
1224
+ 3. Combines multiple KNN queries using dis_max (picks best match)
1225
+ 4. Adds keyword search with fuzzy matching (30% weight)
1226
+ 5. Applies optional filtering and score thresholds
1227
+ 6. Returns aggregations for faceted search
1228
+
1229
+ Search weights:
1230
+ - Semantic search (dis_max across all models): 70%
1231
+ - Keyword search: 30%
1232
+
1233
+ Args:
1234
+ query: Search query string (used for both vector embedding and keyword search)
1235
+
1236
+ Returns:
1237
+ List of search results with page_content, metadata, and relevance scores
1238
+
1239
+ Raises:
1240
+ ValueError: If embedding component is not provided or filter JSON is invalid
1241
+ """
1242
+ logger.info(self.ingest_data)
1243
+ client = self.build_client()
1244
+ q = (query or "").strip()
1245
+
1246
+ # Parse optional filter expression
1247
+ filter_obj = None
1248
+ if getattr(self, "filter_expression", "") and self.filter_expression.strip():
1249
+ try:
1250
+ filter_obj = json.loads(self.filter_expression)
1251
+ except json.JSONDecodeError as e:
1252
+ msg = f"Invalid filter_expression JSON: {e}"
1253
+ raise ValueError(msg) from e
1254
+
1255
+ if not self.embedding:
1256
+ msg = "Embedding is required to run hybrid search (KNN + keyword)."
1257
+ raise ValueError(msg)
1258
+
1259
+ # Check if embedding is None (fail-safe mode)
1260
+ if self.embedding is None or (isinstance(self.embedding, list) and all(e is None for e in self.embedding)):
1261
+ logger.error("Embedding returned None (fail-safe mode enabled). Cannot perform search.")
1262
+ return []
1263
+
1264
+ # Build filter clauses first so we can use them in model detection
1265
+ filter_clauses = self._coerce_filter_clauses(filter_obj)
1266
+
1267
+ # Detect available embedding models in the index (scoped by filters)
1268
+ available_models = self._detect_available_models(client, filter_clauses)
1269
+
1270
+ if not available_models:
1271
+ logger.warning("No embedding models found in index, using current model")
1272
+ available_models = [self._get_embedding_model_name()]
1273
+
1274
+ # Generate embeddings for ALL detected models
1275
+ query_embeddings = {}
1276
+
1277
+ # Normalize embedding to list
1278
+ embeddings_list = self.embedding if isinstance(self.embedding, list) else [self.embedding]
1279
+ # Filter out None values (fail-safe mode)
1280
+ embeddings_list = [e for e in embeddings_list if e is not None]
1281
+
1282
+ if not embeddings_list:
1283
+ logger.error(
1284
+ "No valid embeddings available after filtering None values (fail-safe mode). Cannot perform search."
1285
+ )
1286
+ return []
1287
+
1288
+ # Create a comprehensive map of model names to embedding objects
1289
+ # Check all possible identifiers (deployment, model, model_id, model_name)
1290
+ # Also leverage available_models list from EmbeddingsWithModels
1291
+ # Handle duplicate identifiers by creating combined keys
1292
+ embedding_by_model = {}
1293
+ identifier_conflicts = {} # Track which identifiers have conflicts
1294
+
1295
+ for idx, emb_obj in enumerate(embeddings_list):
1296
+ # Get all possible identifiers for this embedding
1297
+ identifiers = []
1298
+ deployment = getattr(emb_obj, "deployment", None)
1299
+ model = getattr(emb_obj, "model", None)
1300
+ model_id = getattr(emb_obj, "model_id", None)
1301
+ model_name = getattr(emb_obj, "model_name", None)
1302
+ dimensions = getattr(emb_obj, "dimensions", None)
1303
+ available_models_attr = getattr(emb_obj, "available_models", None)
1304
+
1305
+ logger.info(
1306
+ f"Embedding object {idx}: deployment={deployment}, model={model}, "
1307
+ f"model_id={model_id}, model_name={model_name}, dimensions={dimensions}, "
1308
+ f"available_models={available_models_attr}"
1309
+ )
1310
+
1311
+ # If this embedding has available_models dict, map all models to their dedicated instances
1312
+ if available_models_attr and isinstance(available_models_attr, dict):
1313
+ logger.info(
1314
+ f"Embedding object {idx} provides {len(available_models_attr)} models via available_models dict"
1315
+ )
1316
+ for model_name_key, dedicated_embedding in available_models_attr.items():
1317
+ if model_name_key and str(model_name_key).strip():
1318
+ model_str = str(model_name_key).strip()
1319
+ if model_str not in embedding_by_model:
1320
+ # Use the dedicated embedding instance from the dict
1321
+ embedding_by_model[model_str] = dedicated_embedding
1322
+ logger.info(f"Mapped available model '{model_str}' to dedicated embedding instance")
1323
+ else:
1324
+ # Conflict detected - track it
1325
+ if model_str not in identifier_conflicts:
1326
+ identifier_conflicts[model_str] = [embedding_by_model[model_str]]
1327
+ identifier_conflicts[model_str].append(dedicated_embedding)
1328
+ logger.warning(f"Available model '{model_str}' has conflict - used by multiple embeddings")
1329
+
1330
+ # Also map traditional identifiers (for backward compatibility)
1331
+ if deployment:
1332
+ identifiers.append(str(deployment))
1333
+ if model:
1334
+ identifiers.append(str(model))
1335
+ if model_id:
1336
+ identifiers.append(str(model_id))
1337
+ if model_name:
1338
+ identifiers.append(str(model_name))
1339
+
1340
+ # Map all identifiers to this embedding object
1341
+ for identifier in identifiers:
1342
+ if identifier not in embedding_by_model:
1343
+ embedding_by_model[identifier] = emb_obj
1344
+ logger.info(f"Mapped identifier '{identifier}' to embedding object {idx}")
1345
+ else:
1346
+ # Conflict detected - track it
1347
+ if identifier not in identifier_conflicts:
1348
+ identifier_conflicts[identifier] = [embedding_by_model[identifier]]
1349
+ identifier_conflicts[identifier].append(emb_obj)
1350
+ logger.warning(f"Identifier '{identifier}' has conflict - used by multiple embeddings")
1351
+
1352
+ # For embeddings with model+deployment, create combined identifier
1353
+ # This helps when deployment is the same but model differs
1354
+ if deployment and model and deployment != model:
1355
+ combined_id = f"{deployment}:{model}"
1356
+ if combined_id not in embedding_by_model:
1357
+ embedding_by_model[combined_id] = emb_obj
1358
+ logger.info(f"Created combined identifier '{combined_id}' for embedding object {idx}")
1359
+
1360
+ # Log conflicts
1361
+ if identifier_conflicts:
1362
+ logger.warning(
1363
+ f"Found {len(identifier_conflicts)} conflicting identifiers. "
1364
+ f"Consider using combined format 'deployment:model' or specifying unique model names."
1365
+ )
1366
+ for conflict_id, emb_list in identifier_conflicts.items():
1367
+ logger.warning(f" Conflict on '{conflict_id}': {len(emb_list)} embeddings use this identifier")
1368
+
1369
+ logger.info(f"Generating embeddings for {len(available_models)} models in index")
1370
+ logger.info(f"Available embedding identifiers: {list(embedding_by_model.keys())}")
1371
+ self.log(f"[SEARCH] Models detected in index: {available_models}")
1372
+ self.log(f"[SEARCH] Available embedding identifiers: {list(embedding_by_model.keys())}")
1373
+
1374
+ # Track matching status for debugging
1375
+ matched_models = []
1376
+ unmatched_models = []
1377
+
1378
+ for model_name in available_models:
1379
+ try:
1380
+ # Check if we have an embedding object for this model
1381
+ if model_name in embedding_by_model:
1382
+ # Use the matching embedding object directly
1383
+ emb_obj = embedding_by_model[model_name]
1384
+ emb_deployment = getattr(emb_obj, "deployment", None)
1385
+ emb_model = getattr(emb_obj, "model", None)
1386
+ emb_model_id = getattr(emb_obj, "model_id", None)
1387
+ emb_dimensions = getattr(emb_obj, "dimensions", None)
1388
+ emb_available_models = getattr(emb_obj, "available_models", None)
1389
+
1390
+ logger.info(
1391
+ f"Using embedding object for model '{model_name}': "
1392
+ f"deployment={emb_deployment}, model={emb_model}, model_id={emb_model_id}, "
1393
+ f"dimensions={emb_dimensions}"
1394
+ )
1395
+
1396
+ # Check if this is a dedicated instance from available_models dict
1397
+ if emb_available_models and isinstance(emb_available_models, dict):
1398
+ logger.info(
1399
+ f"Model '{model_name}' using dedicated instance from available_models dict "
1400
+ f"(pre-configured with correct model and dimensions)"
1401
+ )
1402
+
1403
+ # Use the embedding instance directly - no model switching needed!
1404
+ vec = emb_obj.embed_query(q)
1405
+ query_embeddings[model_name] = vec
1406
+ matched_models.append(model_name)
1407
+ logger.info(f"Generated embedding for model: {model_name} (actual dimensions: {len(vec)})")
1408
+ self.log(f"[MATCH] Model '{model_name}' - generated {len(vec)}-dim embedding")
1409
+ else:
1410
+ # No matching embedding found for this model
1411
+ unmatched_models.append(model_name)
1412
+ logger.warning(
1413
+ f"No matching embedding found for model '{model_name}'. "
1414
+ f"This model will be skipped. Available identifiers: {list(embedding_by_model.keys())}"
1415
+ )
1416
+ self.log(f"[NO MATCH] Model '{model_name}' - available: {list(embedding_by_model.keys())}")
1417
+ except (RuntimeError, ValueError, ConnectionError, TimeoutError, AttributeError, KeyError) as e:
1418
+ logger.warning(f"Failed to generate embedding for {model_name}: {e}")
1419
+ self.log(f"[ERROR] Embedding generation failed for '{model_name}': {e}")
1420
+
1421
+ # Log summary of model matching
1422
+ logger.info(f"Model matching summary: {len(matched_models)} matched, {len(unmatched_models)} unmatched")
1423
+ self.log(f"[SUMMARY] Model matching: {len(matched_models)} matched, {len(unmatched_models)} unmatched")
1424
+ if unmatched_models:
1425
+ self.log(f"[WARN] Unmatched models in index: {unmatched_models}")
1426
+
1427
+ if not query_embeddings:
1428
+ msg = (
1429
+ f"Failed to generate embeddings for any model. "
1430
+ f"Index has models: {available_models}, but no matching embedding objects found. "
1431
+ f"Available embedding identifiers: {list(embedding_by_model.keys())}"
1432
+ )
1433
+ self.log(f"[FAIL] Search failed: {msg}")
1434
+ raise ValueError(msg)
1435
+
1436
+ index_properties = self._get_index_properties(client)
1437
+ legacy_vector_field = getattr(self, "vector_field", "chunk_embedding")
1438
+
1439
+ # Build KNN queries for each model
1440
+ embedding_fields: list[str] = []
1441
+ knn_queries_with_candidates = []
1442
+ knn_queries_without_candidates = []
1443
+
1444
+ raw_num_candidates = getattr(self, "num_candidates", 1000)
1445
+ try:
1446
+ num_candidates = int(raw_num_candidates) if raw_num_candidates is not None else 0
1447
+ except (TypeError, ValueError):
1448
+ num_candidates = 0
1449
+ use_num_candidates = num_candidates > 0
1450
+
1451
+ for model_name, embedding_vector in query_embeddings.items():
1452
+ field_name = get_embedding_field_name(model_name)
1453
+ selected_field = field_name
1454
+ vector_dim = len(embedding_vector)
1455
+
1456
+ # Only use the expected dynamic field - no legacy fallback
1457
+ # This prevents dimension mismatches between models
1458
+ if not self._is_knn_vector_field(index_properties, selected_field):
1459
+ logger.warning(
1460
+ f"Skipping model {model_name}: field '{field_name}' is not mapped as knn_vector. "
1461
+ f"Documents must be indexed with this embedding model before querying."
1462
+ )
1463
+ self.log(f"[SKIP] Field '{selected_field}' not a knn_vector - skipping model '{model_name}'")
1464
+ continue
1465
+
1466
+ # Validate vector dimensions match the field dimensions
1467
+ field_dim = self._get_field_dimension(index_properties, selected_field)
1468
+ if field_dim is not None and field_dim != vector_dim:
1469
+ logger.error(
1470
+ f"Dimension mismatch for model '{model_name}': "
1471
+ f"Query vector has {vector_dim} dimensions but field '{selected_field}' expects {field_dim}. "
1472
+ f"Skipping this model to prevent search errors."
1473
+ )
1474
+ self.log(f"[DIM MISMATCH] Model '{model_name}': query={vector_dim} vs field={field_dim} - skipping")
1475
+ continue
1476
+
1477
+ logger.info(
1478
+ f"Adding KNN query for model '{model_name}': field='{selected_field}', "
1479
+ f"query_dims={vector_dim}, field_dims={field_dim or 'unknown'}"
1480
+ )
1481
+ embedding_fields.append(selected_field)
1482
+
1483
+ base_query = {
1484
+ "knn": {
1485
+ selected_field: {
1486
+ "vector": embedding_vector,
1487
+ "k": 50,
1488
+ }
1489
+ }
1490
+ }
1491
+
1492
+ if use_num_candidates:
1493
+ query_with_candidates = copy.deepcopy(base_query)
1494
+ query_with_candidates["knn"][selected_field]["num_candidates"] = num_candidates
1495
+ else:
1496
+ query_with_candidates = base_query
1497
+
1498
+ knn_queries_with_candidates.append(query_with_candidates)
1499
+ knn_queries_without_candidates.append(base_query)
1500
+
1501
+ if not knn_queries_with_candidates:
1502
+ # No valid fields found - this can happen when:
1503
+ # 1. Index is empty (no documents yet)
1504
+ # 2. Embedding model has changed and field doesn't exist yet
1505
+ # Return empty results instead of failing
1506
+ logger.warning(
1507
+ "No valid knn_vector fields found for embedding models. "
1508
+ "This may indicate an empty index or missing field mappings. "
1509
+ "Returning empty search results."
1510
+ )
1511
+ self.log(
1512
+ f"[WARN] No valid KNN queries could be built. "
1513
+ f"Query embeddings generated: {list(query_embeddings.keys())}, "
1514
+ f"but no matching knn_vector fields found in index."
1515
+ )
1516
+ return []
1517
+
1518
+ # Build exists filter - document must have at least one embedding field
1519
+ exists_any_embedding = {
1520
+ "bool": {"should": [{"exists": {"field": f}} for f in set(embedding_fields)], "minimum_should_match": 1}
1521
+ }
1522
+
1523
+ # Combine user filters with exists filter
1524
+ all_filters = [*filter_clauses, exists_any_embedding]
1525
+
1526
+ # Get limit and score threshold
1527
+ limit = (filter_obj or {}).get("limit", self.number_of_results)
1528
+ score_threshold = (filter_obj or {}).get("score_threshold", 0)
1529
+
1530
+ # Build multi-model hybrid query
1531
+ body = {
1532
+ "query": {
1533
+ "bool": {
1534
+ "should": [
1535
+ {
1536
+ "dis_max": {
1537
+ "tie_breaker": 0.0, # Take only the best match, no blending
1538
+ "boost": 0.7, # 70% weight for semantic search
1539
+ "queries": knn_queries_with_candidates,
1540
+ }
1541
+ },
1542
+ {
1543
+ "multi_match": {
1544
+ "query": q,
1545
+ "fields": ["text^2", "filename^1.5"],
1546
+ "type": "best_fields",
1547
+ "fuzziness": "AUTO",
1548
+ "boost": 0.3, # 30% weight for keyword search
1549
+ }
1550
+ },
1551
+ ],
1552
+ "minimum_should_match": 1,
1553
+ "filter": all_filters,
1554
+ }
1555
+ },
1556
+ "aggs": {
1557
+ "data_sources": {"terms": {"field": "filename", "size": 20}},
1558
+ "document_types": {"terms": {"field": "mimetype", "size": 10}},
1559
+ "owners": {"terms": {"field": "owner", "size": 10}},
1560
+ "embedding_models": {"terms": {"field": "embedding_model", "size": 10}},
1561
+ },
1562
+ "_source": [
1563
+ "filename",
1564
+ "mimetype",
1565
+ "page",
1566
+ "text",
1567
+ "source_url",
1568
+ "owner",
1569
+ "embedding_model",
1570
+ "allowed_users",
1571
+ "allowed_groups",
1572
+ ],
1573
+ "size": limit,
1574
+ }
1575
+
1576
+ if isinstance(score_threshold, (int, float)) and score_threshold > 0:
1577
+ body["min_score"] = score_threshold
1578
+
1579
+ logger.info(
1580
+ f"Executing multi-model hybrid search with {len(knn_queries_with_candidates)} embedding models: "
1581
+ f"{list(query_embeddings.keys())}"
1582
+ )
1583
+ self.log(f"[EXEC] Executing search with {len(knn_queries_with_candidates)} KNN queries, limit={limit}")
1584
+ self.log(f"[EXEC] Embedding models used: {list(query_embeddings.keys())}")
1585
+ self.log(f"[EXEC] KNN fields being queried: {embedding_fields}")
1586
+
1587
+ try:
1588
+ resp = client.search(index=self.index_name, body=body, params={"terminate_after": 0})
1589
+ except RequestError as e:
1590
+ error_message = str(e)
1591
+ lowered = error_message.lower()
1592
+ if use_num_candidates and "num_candidates" in lowered:
1593
+ logger.warning(
1594
+ "Retrying search without num_candidates parameter due to cluster capabilities",
1595
+ error=error_message,
1596
+ )
1597
+ fallback_body = copy.deepcopy(body)
1598
+ try:
1599
+ fallback_body["query"]["bool"]["should"][0]["dis_max"]["queries"] = knn_queries_without_candidates
1600
+ except (KeyError, IndexError, TypeError) as inner_err:
1601
+ raise e from inner_err
1602
+ resp = client.search(
1603
+ index=self.index_name,
1604
+ body=fallback_body,
1605
+ params={"terminate_after": 0},
1606
+ )
1607
+ elif "knn_vector" in lowered or ("field" in lowered and "knn" in lowered):
1608
+ fallback_vector = next(iter(query_embeddings.values()), None)
1609
+ if fallback_vector is None:
1610
+ raise
1611
+ fallback_field = legacy_vector_field or "chunk_embedding"
1612
+ logger.warning(
1613
+ "KNN search failed for dynamic fields; falling back to legacy field '%s'.",
1614
+ fallback_field,
1615
+ )
1616
+ fallback_body = copy.deepcopy(body)
1617
+ fallback_body["query"]["bool"]["filter"] = filter_clauses
1618
+ knn_fallback = {
1619
+ "knn": {
1620
+ fallback_field: {
1621
+ "vector": fallback_vector,
1622
+ "k": 50,
1623
+ }
1624
+ }
1625
+ }
1626
+ if use_num_candidates:
1627
+ knn_fallback["knn"][fallback_field]["num_candidates"] = num_candidates
1628
+ fallback_body["query"]["bool"]["should"][0]["dis_max"]["queries"] = [knn_fallback]
1629
+ resp = client.search(
1630
+ index=self.index_name,
1631
+ body=fallback_body,
1632
+ params={"terminate_after": 0},
1633
+ )
1634
+ else:
1635
+ raise
1636
+ hits = resp.get("hits", {}).get("hits", [])
1637
+
1638
+ logger.info(f"Found {len(hits)} results")
1639
+ self.log(f"[RESULT] Search complete: {len(hits)} results found")
1640
+
1641
+ if len(hits) == 0:
1642
+ self.log(
1643
+ f"[EMPTY] Debug info: "
1644
+ f"models_in_index={available_models}, "
1645
+ f"matched_models={matched_models}, "
1646
+ f"knn_fields={embedding_fields}, "
1647
+ f"filters={len(filter_clauses)} clauses"
1648
+ )
1649
+
1650
+ return [
1651
+ {
1652
+ "page_content": hit["_source"].get("text", ""),
1653
+ "metadata": {k: v for k, v in hit["_source"].items() if k != "text"},
1654
+ "score": hit.get("_score"),
1655
+ }
1656
+ for hit in hits
1657
+ ]
1658
+
1659
+ def search_documents(self) -> list[Data]:
1660
+ """Search documents and return results as Data objects.
1661
+
1662
+ This is the main interface method that performs the multi-model search using the
1663
+ configured search_query and returns results in Langflow's Data format.
1664
+
1665
+ Always builds the vector store (triggering ingestion if needed), then performs
1666
+ search only if a query is provided.
1667
+
1668
+ Returns:
1669
+ List of Data objects containing search results with text and metadata
1670
+
1671
+ Raises:
1672
+ Exception: If search operation fails
1673
+ """
1674
+ try:
1675
+ # Always build/cache the vector store to ensure ingestion happens
1676
+ logger.info(f"Search query: {self.search_query}")
1677
+ if self._cached_vector_store is None:
1678
+ self.build_vector_store()
1679
+
1680
+ # Only perform search if query is provided
1681
+ search_query = (self.search_query or "").strip()
1682
+ if not search_query:
1683
+ self.log("No search query provided - ingestion completed, returning empty results")
1684
+ return []
1685
+
1686
+ # Perform search with the provided query
1687
+ raw = self.search(search_query)
1688
+ return [Data(text=hit["page_content"], **hit["metadata"]) for hit in raw]
1689
+ except Exception as e:
1690
+ self.log(f"search_documents error: {e}")
1691
+ raise
1692
+
1693
+ # -------- dynamic UI handling (auth switch) --------
1694
+ async def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None) -> dict:
1695
+ """Dynamically update component configuration based on field changes.
1696
+
1697
+ This method handles real-time UI updates, particularly for authentication
1698
+ mode changes that show/hide relevant input fields.
1699
+
1700
+ Args:
1701
+ build_config: Current component configuration
1702
+ field_value: New value for the changed field
1703
+ field_name: Name of the field that changed
1704
+
1705
+ Returns:
1706
+ Updated build configuration with appropriate field visibility
1707
+ """
1708
+ try:
1709
+ if field_name == "auth_mode":
1710
+ mode = (field_value or "basic").strip().lower()
1711
+ is_basic = mode == "basic"
1712
+ is_jwt = mode == "jwt"
1713
+
1714
+ build_config["username"]["show"] = is_basic
1715
+ build_config["password"]["show"] = is_basic
1716
+
1717
+ build_config["jwt_token"]["show"] = is_jwt
1718
+ build_config["jwt_header"]["show"] = is_jwt
1719
+ build_config["bearer_prefix"]["show"] = is_jwt
1720
+
1721
+ build_config["username"]["required"] = is_basic
1722
+ build_config["password"]["required"] = is_basic
1723
+
1724
+ build_config["jwt_token"]["required"] = is_jwt
1725
+ build_config["jwt_header"]["required"] = is_jwt
1726
+ build_config["bearer_prefix"]["required"] = False
1727
+
1728
+ return build_config
1729
+
1730
+ except (KeyError, ValueError) as e:
1731
+ self.log(f"update_build_config error: {e}")
1732
+
1733
+ return build_config