Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

[FIX]: ollama instrumentation failed when using symbol imports before… (#720)

XlKsyt9f285555330a
diff --git a/.gitignore b/.gitignore
index 633ebe64..98be4062 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,4 +8,6 @@ venv/
path/
__pycache__/
**bun.lockb
-logs/
\ No newline at end of file
+logs/
+
+.vscode/
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 24e09aa2..042557ce 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.33.20"
+version = "1.33.21"
description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"
authors = ["OpenLIT"]
license = "Apache-2.0"
diff --git a/sdk/python/src/openlit/instrumentation/ollama/__init__.py b/sdk/python/src/openlit/instrumentation/ollama/__init__.py
index 85468c8f..08352255 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/__init__.py
@@ -16,6 +16,29 @@ from openlit.instrumentation.ollama.async_ollama import (
_instruments = ("ollama >= 0.2.0",)
+# Dispatch wrapper to route instrumentation to chat or embeddings based on path
+def _dispatch(sync_chat_wrap, sync_emb_wrap):
+ def wrapper(wrapped, instance, args, kwargs):
+ if len(args) > 2 and isinstance(args[2], str):
+ op = args[2].rstrip("/").split("/")[-1]
+ if op == "chat":
+ return sync_chat_wrap(wrapped, instance, args, kwargs)
+ if op == "embeddings":
+ return sync_emb_wrap(wrapped, instance, args, kwargs)
+ return wrapped(*args, **kwargs)
+ return wrapper
+
+def _dispatch_async(async_chat_wrap, async_emb_wrap):
+ async def wrapper(wrapped, instance, args, kwargs):
+ if len(args) > 2 and isinstance(args[2], str):
+ op = args[2].rstrip("/").split("/")[-1]
+ if op == "chat":
+ return await async_chat_wrap(wrapped, instance, args, kwargs)
+ if op == "embeddings":
+ return await async_emb_wrap(wrapped, instance, args, kwargs)
+ return await wrapped(*args, **kwargs)
+ return wrapper
+
class OllamaInstrumentor(BaseInstrumentor):
"""
An instrumentor for Ollama's client library.
@@ -35,48 +58,38 @@ class OllamaInstrumentor(BaseInstrumentor):
disable_metrics = kwargs.get("disable_metrics")
version = importlib.metadata.version("ollama")
- # sync chat
- wrap_function_wrapper(
- "ollama",
- "chat",
- chat(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ # Build wrapper factories for chat and embeddings
+ sync_chat_wrap = chat(
+ version, environment, application_name,
+ tracer, event_provider, pricing_info,
+ capture_message_content, metrics, disable_metrics
)
- wrap_function_wrapper(
- "ollama",
- "Client.chat",
- chat(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ sync_emb_wrap = embeddings(
+ version, environment, application_name,
+ tracer, event_provider, pricing_info,
+ capture_message_content, metrics, disable_metrics
)
-
- # sync embeddings
- wrap_function_wrapper(
- "ollama",
- "embeddings",
- embeddings(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ async_chat_wrap = async_chat(
+ version, environment, application_name,
+ tracer, event_provider, pricing_info,
+ capture_message_content, metrics, disable_metrics
)
- wrap_function_wrapper(
- "ollama",
- "Client.embeddings",
- embeddings(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ async_emb_wrap = async_embeddings(
+ version, environment, application_name,
+ tracer, event_provider, pricing_info,
+ capture_message_content, metrics, disable_metrics
)
- # async chat
+ # Patch underlying request methods to ensure instrumentation regardless of import order
wrap_function_wrapper(
- "ollama",
- "AsyncClient.chat",
- async_chat(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ "ollama._client",
+ "Client._request",
+ _dispatch(sync_chat_wrap, sync_emb_wrap),
)
-
- # async embeddings
wrap_function_wrapper(
- "ollama",
- "AsyncClient.embeddings",
- async_embeddings(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ "ollama._client",
+ "AsyncClient._request",
+ _dispatch_async(async_chat_wrap, async_emb_wrap),
)
def _uninstrument(self, **kwargs):
diff --git a/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py b/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py
index 9d8af092..3ba315c8 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py
@@ -106,7 +106,8 @@ def async_chat(version, environment, application_name,
streaming = kwargs.get("stream", False)
server_address, server_port = set_server_address_and_port(instance, "127.0.0.1", 11434)
- request_model = kwargs.get("model", "gpt-4o")
+ json_body = kwargs.get("json", {}) or {}
+ request_model = json_body.get("model") or kwargs.get("model")
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
@@ -154,7 +155,8 @@ def async_embeddings(version, environment, application_name,
"""
server_address, server_port = set_server_address_and_port(instance, '127.0.0.1', 11434)
- request_model = kwargs.get('model', 'all-minilm')
+ json_body = kwargs.get('json', {}) or {}
+ request_model = json_body.get('model') or kwargs.get('model')
span_name = f'{SemanticConvention.GEN_AI_OPERATION_TYPE_EMBEDDING} {request_model}'
diff --git a/sdk/python/src/openlit/instrumentation/ollama/ollama.py b/sdk/python/src/openlit/instrumentation/ollama/ollama.py
index 5864a186..a740e141 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/ollama.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/ollama.py
@@ -106,7 +106,8 @@ def chat(version, environment, application_name,
streaming = kwargs.get("stream", False)
server_address, server_port = set_server_address_and_port(instance, "127.0.0.1", 11434)
- request_model = kwargs.get("model", "gpt-4o")
+ json_body = kwargs.get("json", {}) or {}
+ request_model = json_body.get("model") or kwargs.get("model")
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
@@ -154,7 +155,8 @@ def embeddings(version, environment, application_name,
"""
server_address, server_port = set_server_address_and_port(instance, '127.0.0.1', 11434)
- request_model = kwargs.get('model', 'all-minilm')
+ json_body = kwargs.get('json', {}) or {}
+ request_model = json_body.get('model') or kwargs.get('model')
span_name = f'{SemanticConvention.GEN_AI_OPERATION_TYPE_EMBEDDING} {request_model}'
diff --git a/sdk/python/src/openlit/instrumentation/ollama/utils.py b/sdk/python/src/openlit/instrumentation/ollama/utils.py
index c5606b05..654b5e79 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/utils.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/utils.py
@@ -57,8 +57,10 @@ def common_chat_logic(scope, pricing_info, environment, application_name, metric
if len(scope._timestamps) > 1:
scope._tbt = calculate_tbt(scope._timestamps)
- formatted_messages = extract_and_format_input(scope._kwargs.get("messages", ""))
- request_model = scope._kwargs.get("model", "gpt-4o")
+ json_body = scope._kwargs.get("json", {}) or {}
+ request_model = json_body.get("model") or scope._kwargs.get("model")
+ messages = json_body.get("messages", scope._kwargs.get("messages", ""))
+ formatted_messages = extract_and_format_input(messages)
cost = get_chat_model_cost(request_model, pricing_info, scope._input_tokens, scope._output_tokens)
@@ -252,7 +254,9 @@ def process_embedding_response(response, request_model, pricing_info, server_por
end_time = time.time()
try:
- input_tokens = general_tokens(str(kwargs.get('prompt')))
+ json_body = kwargs.get("json", {}) or {}
+ prompt_val = json_body.get('prompt', kwargs.get('prompt', ''))
+ input_tokens = general_tokens(str(prompt_val))
# Calculate cost of the operation
cost = get_embed_model_cost(request_model,
@@ -293,7 +297,7 @@ def process_embedding_response(response, request_model, pricing_info, server_por
SemanticConvention.GEN_AI_SYSTEM: SemanticConvention.GEN_AI_SYSTEM_OLLAMA
},
body={
- **({"content": kwargs.get('prompt', '')} if capture_message_content else {}),
+ **({"content": prompt_val} if capture_message_content else {}),
"role": 'user'
}
)