openlit 1.34.24__py3-none-any.whl → 1.34.26__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.
@@ -1,5 +1,7 @@
1
- # pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
2
- """Initializer of Auto Instrumentation of Chromadb Functions"""
1
+ """
2
+ OpenLIT ChromaDB Instrumentation
3
+ """
4
+
3
5
  from typing import Collection
4
6
  import importlib.metadata
5
7
  from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
@@ -10,77 +12,79 @@ from openlit.instrumentation.chroma.chroma import general_wrap
10
12
  _instruments = ("chromadb >= 0.4.0",)
11
13
 
12
14
  class ChromaInstrumentor(BaseInstrumentor):
13
- """An instrumentor for Chromadb's client library."""
15
+ """
16
+ An instrumentor for ChromaDB client library.
17
+ """
14
18
 
15
19
  def instrumentation_dependencies(self) -> Collection[str]:
16
20
  return _instruments
17
21
 
18
22
  def _instrument(self, **kwargs):
19
- application_name = kwargs.get("application_name")
20
- environment = kwargs.get("environment")
23
+ version = importlib.metadata.version("chromadb")
24
+ environment = kwargs.get("environment", "default")
25
+ application_name = kwargs.get("application_name", "default")
21
26
  tracer = kwargs.get("tracer")
27
+ pricing_info = kwargs.get("pricing_info", {})
28
+ capture_message_content = kwargs.get("capture_message_content", False)
22
29
  metrics = kwargs.get("metrics_dict")
23
- pricing_info = kwargs.get("pricing_info")
24
- capture_message_content = kwargs.get("capture_message_content")
25
30
  disable_metrics = kwargs.get("disable_metrics")
26
- version = importlib.metadata.version("chromadb")
27
31
 
32
+ # Sync operations
28
33
  wrap_function_wrapper(
29
- "chromadb.db",
30
- "DB.create_collection",
34
+ "chromadb.db",
35
+ "DB.create_collection",
31
36
  general_wrap("chroma.create_collection", version, environment, application_name,
32
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
37
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
33
38
  )
34
39
 
35
40
  wrap_function_wrapper(
36
- "chromadb",
37
- "Collection.add",
41
+ "chromadb",
42
+ "Collection.add",
38
43
  general_wrap("chroma.add", version, environment, application_name,
39
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
44
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
40
45
  )
41
46
 
42
47
  wrap_function_wrapper(
43
- "chromadb",
44
- "Collection.get",
48
+ "chromadb",
49
+ "Collection.get",
45
50
  general_wrap("chroma.get", version, environment, application_name,
46
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
51
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
47
52
  )
48
53
 
49
54
  wrap_function_wrapper(
50
- "chromadb",
51
- "Collection.peek",
55
+ "chromadb",
56
+ "Collection.peek",
52
57
  general_wrap("chroma.peek", version, environment, application_name,
53
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
58
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
54
59
  )
55
60
 
56
61
  wrap_function_wrapper(
57
- "chromadb",
58
- "Collection.query",
62
+ "chromadb",
63
+ "Collection.query",
59
64
  general_wrap("chroma.query", version, environment, application_name,
60
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
65
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
61
66
  )
62
67
 
63
68
  wrap_function_wrapper(
64
- "chromadb",
65
- "Collection.update",
69
+ "chromadb",
70
+ "Collection.update",
66
71
  general_wrap("chroma.update", version, environment, application_name,
67
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
72
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
68
73
  )
69
74
 
70
75
  wrap_function_wrapper(
71
- "chromadb",
72
- "Collection.upsert",
76
+ "chromadb",
77
+ "Collection.upsert",
73
78
  general_wrap("chroma.upsert", version, environment, application_name,
74
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
79
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
75
80
  )
81
+
76
82
  wrap_function_wrapper(
77
- "chromadb",
78
- "Collection.delete",
83
+ "chromadb",
84
+ "Collection.delete",
79
85
  general_wrap("chroma.delete", version, environment, application_name,
80
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
86
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
81
87
  )
82
88
 
83
-
84
- @staticmethod
85
89
  def _uninstrument(self, **kwargs):
86
90
  pass
@@ -1,199 +1,57 @@
1
- # pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment
2
1
  """
3
- Module for monitoring ChromaDB.
2
+ Module for monitoring ChromaDB API calls.
4
3
  """
5
4
 
6
- import logging
7
- from opentelemetry.trace import SpanKind, Status, StatusCode
8
- from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
5
+ import time
6
+ from opentelemetry.trace import SpanKind
7
+ from opentelemetry import context as context_api
9
8
  from openlit.__helpers import handle_exception
10
- from openlit.semcov import SemanticConvention
11
-
12
- # Initialize logger for logging potential issues and operations
13
- logger = logging.getLogger(__name__)
14
-
15
- def object_count(obj):
16
- """
17
- Counts Length of object if it exists, Else returns None
18
- """
19
- try:
20
- cnt = len(obj)
21
- # pylint: disable=bare-except
22
- except:
23
- cnt = 0
24
-
25
- return cnt
9
+ from openlit.instrumentation.chroma.utils import (
10
+ process_vectordb_response,
11
+ DB_OPERATION_MAP,
12
+ set_server_address_and_port,
13
+ )
26
14
 
27
15
  def general_wrap(gen_ai_endpoint, version, environment, application_name,
28
- tracer, pricing_info, capture_message_content, metrics, disable_metrics):
16
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):
29
17
  """
30
- Creates a wrapper around a function call to trace and log its execution metrics.
31
-
32
- This function wraps any given function to measure its execution time,
33
- log its operation, and trace its execution using OpenTelemetry.
34
-
35
- Parameters:
36
- - gen_ai_endpoint (str): A descriptor or name for the endpoint being traced.
37
- - version (str): The version of the Langchain application.
38
- - environment (str): The deployment environment (e.g., 'production', 'development').
39
- - application_name (str): Name of the Langchain application.
40
- - tracer (opentelemetry.trace.Tracer): The tracer object used for OpenTelemetry tracing.
41
- - pricing_info (dict): Information about the pricing for internal metrics (currently not used).
42
- - capture_message_content (bool): Flag indicating whether to trace the content of the response.
43
-
44
- Returns:
45
- - function: A higher-order function that takes a function 'wrapped' and returns
46
- a new function that wraps 'wrapped' with additional tracing and logging.
18
+ Generates a telemetry wrapper for ChromaDB function calls.
47
19
  """
48
20
 
49
21
  def wrapper(wrapped, instance, args, kwargs):
50
22
  """
51
- An inner wrapper function that executes the wrapped function, measures execution
52
- time, and records trace data using OpenTelemetry.
53
-
54
- Parameters:
55
- - wrapped (Callable): The original function that this wrapper will execute.
56
- - instance (object): The instance to which the wrapped function belongs. This
57
- is used for instance methods. For static and classmethods,
58
- this may be None.
59
- - args (tuple): Positional arguments passed to the wrapped function.
60
- - kwargs (dict): Keyword arguments passed to the wrapped function.
61
-
62
- Returns:
63
- - The result of the wrapped function call.
64
-
65
- The wrapper initiates a span with the provided tracer, sets various attributes
66
- on the span based on the function's execution and response, and ensures
67
- errors are handled and logged appropriately.
23
+ Wraps the ChromaDB function call.
68
24
  """
69
- with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
70
- response = wrapped(*args, **kwargs)
71
25
 
72
- try:
73
- span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
74
- span.set_attribute(SemanticConvention.GEN_AI_ENDPOINT,
75
- gen_ai_endpoint)
76
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
77
- environment)
78
- span.set_attribute(SERVICE_NAME,
79
- application_name)
80
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
81
- SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB)
82
- span.set_attribute(SemanticConvention.DB_SYSTEM_NAME,
83
- SemanticConvention.DB_SYSTEM_CHROMA)
84
- span.set_attribute(SemanticConvention.DB_COLLECTION_NAME,
85
- instance.name)
26
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
27
+ return wrapped(*args, **kwargs)
86
28
 
87
- if gen_ai_endpoint == "chroma.add":
88
- db_operation = SemanticConvention.DB_OPERATION_ADD
89
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
90
- SemanticConvention.DB_OPERATION_ADD)
91
- span.set_attribute(SemanticConvention.DB_ID_COUNT,
92
- object_count(kwargs.get("ids", [])))
93
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
94
- object_count(kwargs.get("embeddings", [])))
95
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
96
- object_count(kwargs.get("metadatas", [])))
97
- span.set_attribute(SemanticConvention.DB_DOCUMENTS_COUNT,
98
- object_count(kwargs.get("documents", [])))
29
+ # Get server address and port using the standard helper
30
+ server_address, server_port = set_server_address_and_port(instance)
99
31
 
100
- elif gen_ai_endpoint == "chroma.get":
101
- db_operation = SemanticConvention.DB_OPERATION_GET
102
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
103
- SemanticConvention.DB_OPERATION_GET)
104
- span.set_attribute(SemanticConvention.DB_ID_COUNT,
105
- object_count(kwargs.get("ids", [])))
106
- span.set_attribute(SemanticConvention.DB_QUERY_LIMIT,
107
- kwargs.get("limit", ""))
108
- span.set_attribute(SemanticConvention.DB_OFFSET,
109
- kwargs.get("offset", ""))
110
- span.set_attribute(SemanticConvention.DB_WHERE_DOCUMENT,
111
- str(kwargs.get("where_document", "")))
32
+ db_operation = DB_OPERATION_MAP.get(gen_ai_endpoint, "unknown")
33
+ if db_operation == "create_collection":
34
+ namespace = kwargs.get("name") or (args[0] if args else "unknown")
35
+ else:
36
+ namespace = getattr(instance, "name", "unknown")
37
+ span_name = f"{db_operation} {namespace}"
112
38
 
113
- elif gen_ai_endpoint == "chroma.query":
114
- db_operation = SemanticConvention.DB_OPERATION_QUERY
115
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
116
- SemanticConvention.DB_OPERATION_QUERY)
117
- span.set_attribute(SemanticConvention.DB_STATEMENT,
118
- str(kwargs.get("query_texts", "")))
119
- span.set_attribute(SemanticConvention.DB_N_RESULTS,
120
- kwargs.get("n_results", ""))
121
- span.set_attribute(SemanticConvention.DB_FILTER,
122
- str(kwargs.get("where", "")))
123
- span.set_attribute(SemanticConvention.DB_WHERE_DOCUMENT,
124
- str(kwargs.get("where_document", "")))
125
-
126
- elif gen_ai_endpoint == "chroma.update":
127
- db_operation = SemanticConvention.DB_OPERATION_UPDATE
128
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
129
- SemanticConvention.DB_OPERATION_UPDATE)
130
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
131
- object_count(kwargs.get("embeddings", [])))
132
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
133
- object_count(kwargs.get("metadatas", [])))
134
- span.set_attribute(SemanticConvention.DB_ID_COUNT,
135
- object_count(kwargs.get("ids", [])))
136
- span.set_attribute(SemanticConvention.DB_DOCUMENTS_COUNT,
137
- object_count(kwargs.get("documents", [])))
138
-
139
- elif gen_ai_endpoint == "chroma.upsert":
140
- db_operation = SemanticConvention.DB_OPERATION_UPSERT
141
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
142
- SemanticConvention.DB_OPERATION_UPSERT)
143
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
144
- object_count(kwargs.get("embeddings", [])))
145
- span.set_attribute(SemanticConvention.DB_VECTOR_COUNT,
146
- object_count(kwargs.get("metadatas", [])))
147
- span.set_attribute(SemanticConvention.DB_ID_COUNT,
148
- object_count(kwargs.get("ids", [])))
149
- span.set_attribute(SemanticConvention.DB_DOCUMENTS_COUNT,
150
- object_count(kwargs.get("documents", [])))
151
-
152
- elif gen_ai_endpoint == "chroma.delete":
153
- db_operation = SemanticConvention.DB_OPERATION_DELETE
154
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
155
- SemanticConvention.DB_OPERATION_DELETE)
156
- span.set_attribute(SemanticConvention.DB_ID_COUNT,
157
- object_count(kwargs.get("ids", [])))
158
- span.set_attribute(SemanticConvention.DB_FILTER,
159
- str(kwargs.get("where", "")))
160
- span.set_attribute(SemanticConvention.DB_DELETE_ALL,
161
- kwargs.get("delete_all", False))
162
- span.set_attribute(SemanticConvention.DB_WHERE_DOCUMENT,
163
- str(kwargs.get("where_document", "")))
164
-
165
- elif gen_ai_endpoint == "chroma.peek":
166
- db_operation = SemanticConvention.DB_OPERATION_PEEK
167
- span.set_attribute(SemanticConvention.DB_OPERATION_NAME,
168
- SemanticConvention.DB_OPERATION_PEEK)
169
-
170
- span.set_status(Status(StatusCode.OK))
171
-
172
- if disable_metrics is False:
173
- attributes = {
174
- TELEMETRY_SDK_NAME:
175
- "openlit",
176
- SERVICE_NAME:
177
- application_name,
178
- SemanticConvention.DB_SYSTEM_NAME:
179
- SemanticConvention.DB_SYSTEM_CHROMA,
180
- DEPLOYMENT_ENVIRONMENT:
181
- environment,
182
- SemanticConvention.GEN_AI_OPERATION:
183
- SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB,
184
- SemanticConvention.DB_OPERATION_NAME:
185
- db_operation
186
- }
187
-
188
- metrics["db_requests"].add(1, attributes)
39
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
40
+ start_time = time.time()
41
+ response = wrapped(*args, **kwargs)
189
42
 
190
- return response
43
+ try:
44
+ # Process response and generate telemetry
45
+ response = process_vectordb_response(
46
+ response, db_operation, server_address, server_port,
47
+ environment, application_name, metrics, start_time, span,
48
+ capture_message_content, disable_metrics, version, instance, args, endpoint=gen_ai_endpoint, **kwargs
49
+ )
191
50
 
192
51
  except Exception as e:
193
52
  handle_exception(span, e)
194
- logger.error("Error in trace creation: %s", e)
195
53
 
196
- # Return original response
197
- return response
54
+ return response
55
+
198
56
 
199
57
  return wrapper
@@ -0,0 +1,272 @@
1
+ """
2
+ ChromaDB OpenTelemetry instrumentation utility functions
3
+ """
4
+ import time
5
+ from urllib.parse import urlparse
6
+ from opentelemetry.trace import Status, StatusCode
7
+
8
+ from openlit.__helpers import (
9
+ common_db_span_attributes,
10
+ record_db_metrics,
11
+ )
12
+ from openlit.semcov import SemanticConvention
13
+
14
+ # Operation mapping for simple span naming
15
+ DB_OPERATION_MAP = {
16
+ "chroma.create_collection": SemanticConvention.DB_OPERATION_CREATE_COLLECTION,
17
+ "chroma.add": SemanticConvention.DB_OPERATION_INSERT,
18
+ "chroma.get": SemanticConvention.DB_OPERATION_GET,
19
+ "chroma.peek": SemanticConvention.DB_OPERATION_PEEK,
20
+ "chroma.query": SemanticConvention.DB_OPERATION_GET,
21
+ "chroma.update": SemanticConvention.DB_OPERATION_UPDATE,
22
+ "chroma.upsert": SemanticConvention.DB_OPERATION_UPSERT,
23
+ "chroma.delete": SemanticConvention.DB_OPERATION_DELETE,
24
+ }
25
+
26
+ def object_count(obj):
27
+ """
28
+ Counts length of object if it exists, else returns 0.
29
+ """
30
+ return len(obj) if obj else 0
31
+
32
+ def set_server_address_and_port(instance):
33
+ """
34
+ Extracts server address and port from ChromaDB client instance.
35
+
36
+ Args:
37
+ instance: ChromaDB client instance
38
+
39
+ Returns:
40
+ tuple: (server_address, server_port)
41
+ """
42
+ server_address = "localhost"
43
+ server_port = 8000
44
+
45
+ # Try getting base_url from multiple potential attributes
46
+ base_client = getattr(instance, "_client", None)
47
+ base_url = getattr(base_client, "base_url", None)
48
+
49
+ if not base_url:
50
+ # Attempt to get endpoint from instance._config.endpoint
51
+ config = getattr(instance, "_config", None)
52
+ base_url = getattr(config, "endpoint", None)
53
+
54
+ if not base_url:
55
+ # Attempt to get server_url from instance.sdk_configuration.server_url
56
+ config = getattr(instance, "sdk_configuration", None)
57
+ base_url = getattr(config, "server_url", None)
58
+
59
+ if base_url:
60
+ if isinstance(base_url, str):
61
+ # Check if it a full URL or just a hostname
62
+ if base_url.startswith(("http://", "https://")):
63
+ try:
64
+ url = urlparse(base_url)
65
+ if url.hostname:
66
+ server_address = url.hostname
67
+ if url.port:
68
+ server_port = url.port
69
+ except Exception:
70
+ pass
71
+ else:
72
+ # Just a hostname
73
+ server_address = base_url
74
+
75
+ return server_address, server_port
76
+
77
+ def common_vectordb_logic(scope, environment, application_name,
78
+ metrics, capture_message_content, disable_metrics, version, instance=None, endpoint=None):
79
+ """
80
+ Process vector database request and generate telemetry.
81
+ """
82
+
83
+ scope._end_time = time.time()
84
+
85
+ # Set common database span attributes using helper
86
+ common_db_span_attributes(scope, SemanticConvention.DB_SYSTEM_CHROMA, scope._server_address, scope._server_port,
87
+ environment, application_name, version)
88
+
89
+ # Set DB operation specific attributes
90
+ scope._span.set_attribute(SemanticConvention.DB_OPERATION_NAME, scope._db_operation)
91
+ scope._span.set_attribute(SemanticConvention.DB_CLIENT_OPERATION_DURATION, scope._end_time - scope._start_time)
92
+
93
+ # Set collection name from instance
94
+ if hasattr(instance, "name"):
95
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, instance.name)
96
+
97
+ # Set Create Collection operation specific attributes
98
+ if scope._db_operation == SemanticConvention.DB_OPERATION_CREATE_COLLECTION:
99
+ # Standard database attributes
100
+ collection_name = scope._kwargs.get("name") or (scope._args[0] if scope._args else "unknown")
101
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
102
+
103
+ # Vector database specific attributes (extensions)
104
+ metadata = scope._kwargs.get("metadata", {})
105
+ if metadata:
106
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_METADATA, str(metadata))
107
+
108
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_INSERT:
109
+ collection_name = getattr(instance, "name", "unknown")
110
+ query = scope._kwargs.get("ids", [])
111
+
112
+ # Standard database attributes
113
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, str(query))
114
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
115
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, object_count(query))
116
+
117
+ # Vector database specific attributes (extensions)
118
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
119
+ f"{scope._db_operation} {collection_name} "
120
+ f"ids={query} "
121
+ f"documents={scope._kwargs.get('documents', [])}")
122
+
123
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_GET:
124
+ collection_name = getattr(instance, "name", "unknown")
125
+
126
+ # Handle different GET operations based on endpoint
127
+ if endpoint == "chroma.get":
128
+ # Collection.get() - retrieve documents by IDs
129
+ query = scope._kwargs.get("ids", [])
130
+
131
+ # Standard database attributes
132
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, str(query))
133
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
134
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, object_count(query))
135
+
136
+ # Vector database specific attributes (extensions)
137
+ scope._span.set_attribute(SemanticConvention.DB_FILTER, str(scope._kwargs.get("where", "")))
138
+
139
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
140
+ f"{scope._db_operation} {collection_name} "
141
+ f"ids={query} "
142
+ f"limit={scope._kwargs.get('limit', 'None')} "
143
+ f"offset={scope._kwargs.get('offset', 'None')}")
144
+
145
+ elif endpoint == "chroma.query":
146
+ query_texts = scope._kwargs.get("query_texts", [])
147
+ query_embeddings = scope._kwargs.get("query_embeddings", [])
148
+
149
+ # Create comprehensive query text (can be either embeddings or texts)
150
+ if query_texts:
151
+ query_content = f"texts={query_texts}"
152
+ elif query_embeddings:
153
+ query_content = f"embeddings={len(query_embeddings) if query_embeddings else 0} vectors"
154
+ else:
155
+ query_content = "no query provided"
156
+
157
+ # Standard database attributes
158
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, query_content)
159
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
160
+
161
+ # Vector database specific attributes (extensions)
162
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_QUERY_TOP_K, scope._kwargs.get("n_results", 10))
163
+ scope._span.set_attribute(SemanticConvention.DB_FILTER, str(scope._kwargs.get("where", "")))
164
+
165
+ # Extract response metrics if available
166
+ if scope._response:
167
+ # Get number of results returned
168
+ if hasattr(scope._response, "get") and scope._response.get("ids"):
169
+ returned_rows = object_count(scope._response["ids"][0]) if scope._response["ids"] else 0
170
+ scope._span.set_attribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, returned_rows)
171
+
172
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
173
+ f"{scope._db_operation} {collection_name} "
174
+ f"n_results={scope._kwargs.get('n_results', 10)} "
175
+ f"{query_content} "
176
+ f"filter={scope._kwargs.get('where', 'None')}")
177
+
178
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_UPDATE:
179
+ collection_name = getattr(instance, "name", "unknown")
180
+ query = scope._kwargs.get("ids", [])
181
+
182
+ # Standard database attributes
183
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, str(query))
184
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
185
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, object_count(query))
186
+
187
+ # Vector database specific attributes (extensions)
188
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
189
+ f"{scope._db_operation} {collection_name} "
190
+ f"ids={query} "
191
+ f"embeddings={scope._kwargs.get('embeddings', 'None')} "
192
+ f"metadatas={scope._kwargs.get('metadatas', 'None')} "
193
+ f"documents={scope._kwargs.get('documents', 'None')}")
194
+
195
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_UPSERT:
196
+ collection_name = getattr(instance, "name", "unknown")
197
+ query = scope._kwargs.get("ids", [])
198
+
199
+ # Standard database attributes
200
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, str(query))
201
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
202
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, object_count(query))
203
+
204
+ # Vector database specific attributes (extensions)
205
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
206
+ f"{scope._db_operation} {collection_name} "
207
+ f"ids={query} "
208
+ f"embeddings={scope._kwargs.get('embeddings', 'None')} "
209
+ f"metadatas={scope._kwargs.get('metadatas', 'None')} "
210
+ f"documents={scope._kwargs.get('documents', 'None')}")
211
+
212
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_DELETE:
213
+ collection_name = getattr(instance, "name", "unknown")
214
+ query = scope._kwargs.get("ids", [])
215
+
216
+ # Standard database attributes
217
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, str(query))
218
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
219
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, object_count(query))
220
+
221
+ # Vector database specific attributes (extensions)
222
+ scope._span.set_attribute(SemanticConvention.DB_FILTER, str(scope._kwargs.get("where", "")))
223
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
224
+ f"{scope._db_operation} {collection_name} "
225
+ f"ids={query} "
226
+ f"filter={scope._kwargs.get('where', 'None')} "
227
+ f"delete_all={scope._kwargs.get('delete_all', False)}")
228
+
229
+ elif scope._db_operation == SemanticConvention.DB_OPERATION_PEEK:
230
+ collection_name = getattr(instance, "name", "unknown")
231
+ query = f"PEEK limit={scope._kwargs.get('limit', '')}"
232
+
233
+ # Standard database attributes
234
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, query)
235
+ scope._span.set_attribute(SemanticConvention.DB_COLLECTION_NAME, collection_name)
236
+ scope._span.set_attribute(SemanticConvention.DB_VECTOR_COUNT, scope._kwargs.get("limit", ""))
237
+
238
+ # Vector database specific attributes (extensions)
239
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_SUMMARY,
240
+ f"{scope._db_operation} {collection_name} "
241
+ f"limit={scope._kwargs.get('limit', 'None')}")
242
+
243
+ scope._span.set_status(Status(StatusCode.OK))
244
+
245
+ # Record metrics using helper
246
+ if not disable_metrics:
247
+ record_db_metrics(metrics, SemanticConvention.DB_SYSTEM_CHROMA, scope._server_address, scope._server_port,
248
+ environment, application_name, scope._start_time, scope._end_time)
249
+
250
+ def process_vectordb_response(response, db_operation, server_address, server_port,
251
+ environment, application_name, metrics, start_time, span,
252
+ capture_message_content=False, disable_metrics=False,
253
+ version="1.0.0", instance=None, args=None, endpoint=None, **kwargs):
254
+ """
255
+ Process vector database response and generate telemetry following OpenTelemetry conventions.
256
+ """
257
+
258
+ scope = type("GenericScope", (), {})()
259
+
260
+ scope._start_time = start_time
261
+ scope._span = span
262
+ scope._kwargs = kwargs
263
+ scope._args = args or []
264
+ scope._db_operation = db_operation
265
+ scope._response = response
266
+ scope._server_address = server_address
267
+ scope._server_port = server_port
268
+
269
+ common_vectordb_logic(scope, environment, application_name,
270
+ metrics, capture_message_content, disable_metrics, version, instance, endpoint)
271
+
272
+ return response