Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
[Feat]: add support for agno 2.x (#875)
Chai Zhenhua0a823419a949
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex 17aec540..e061ff4a 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.35.2"+version = "1.35.3"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/agno/__init__.py b/sdk/python/src/openlit/instrumentation/agno/__init__.pyindex 264008a4..ac7fb80d 100644--- a/sdk/python/src/openlit/instrumentation/agno/__init__.py+++ b/sdk/python/src/openlit/instrumentation/agno/__init__.py@@ -4,7 +4,9 @@ from typing import Collectionimport importlib.metadatafrom opentelemetry.instrumentation.instrumentor import BaseInstrumentorfrom wrapt import wrap_function_wrapper-+from openlit.instrumentation.agno.utils import (+ resolve_agno_knowledge_target,+ resolve_agno_memory_target)from openlit.instrumentation.agno.agno import (agent_run_wrap,agent_continue_run_wrap,@@ -33,6 +35,7 @@ from openlit.instrumentation.agno.async_agno import (async_agent_continue_run_wrap,async_function_execute_wrap,async_reasoning_wrap,+ async_team_run_stream_wrap,async_workflow_run_wrap,async_team_run_wrap,async_model_run_function_call_wrap,@@ -232,72 +235,48 @@ class AgnoInstrumentor(BaseInstrumentor):# Instrumenting the batch methods causes span hierarchy issues and is redundant# CRITICAL: Memory operations that bypass model bridge- wrap_function_wrapper(- "agno.memory.v2.memory",- "Memory.add_user_memory",- memory_operation_wrap(- "memory.add_user_memory",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.memory.v2.memory",- "Memory.search_user_memories",- memory_operation_wrap(- "memory.search_user_memories",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- # Memory Operations (v2)- wrap_function_wrapper(- "agno.memory.v2.memory",- "Memory.add_user_memory",- memory_add_wrap(- "memory.add_user_memory",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.memory.v2.memory",- "Memory.search_user_memories",- memory_search_wrap(- "memory.search_user_memories",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )- # Note: Memory class does not have async_add_user_memory or async_search_user_memories+ # Dynamically determine the correct memory module/class based on the installed+ # agno version. 2.x versions expose MemoryManager in ``agno.memory.manager``+ # while older 1.x versions expose Memory in ``agno.memory.v2.memory``.++ memory_module, memory_class = resolve_agno_memory_target()++ if memory_module is not None:++ # Wrap memory add/search exactly once using the dedicated wrappers to avoid+ # duplicate spans and performance overhead.+ wrap_function_wrapper(+ memory_module,+ f"{memory_class}.add_user_memory",+ memory_add_wrap(+ "memory.add_user_memory",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ wrap_function_wrapper(+ memory_module,+ f"{memory_class}.search_user_memories",+ memory_search_wrap(+ "memory.search_user_memories",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )# VectorDB Operations (base class)wrap_function_wrapper(@@ -332,87 +311,104 @@ class AgnoInstrumentor(BaseInstrumentor):),)- # Knowledge Operations- wrap_function_wrapper(- "agno.knowledge.agent",- "AgentKnowledge.search",- knowledge_search_wrap(- "knowledge.search",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.knowledge.agent",- "AgentKnowledge.load",- knowledge_add_wrap(- "knowledge.load",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.knowledge.agent",- "AgentKnowledge.add_document_to_knowledge_base",- knowledge_add_wrap(- "knowledge.add_document_to_knowledge_base",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- # Workflow Operations- wrap_function_wrapper(- "agno.workflow.workflow",- "Workflow.run",- workflow_run_wrap(- "workflow.run",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.workflow.workflow",- "Workflow.run_workflow",- workflow_run_wrap(- "workflow.run_workflow",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )+ # Dynamically determine the correct knowledge module/class based on the installed+ # agno version. 2.x versions expose `Knowledge` in `agno.knowledge.knowledge`+ # while older 1.x versions expose `AgentKnowledge` in `agno.knowledge.agent`.+ knowledge_module, knowledge_class = resolve_agno_knowledge_target()++ if knowledge_module is not None:+ # Knowledge Operations+ wrap_function_wrapper(+ knowledge_module,+ f"{knowledge_class}.search",+ knowledge_search_wrap(+ "knowledge.search",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ # agno 2.x versions do not have load method+ if hasattr(knowledge_class, "load"):++ wrap_function_wrapper(+ knowledge_module,+ f"{knowledge_class}.load",+ knowledge_add_wrap(+ "knowledge.load",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ # agno 2.x versions do not have add_document_to_knowledge_base method+ if hasattr(knowledge_class, "add_document_to_knowledge_base"):+ wrap_function_wrapper(+ knowledge_module,+ f"{knowledge_class}.add_document_to_knowledge_base",+ knowledge_add_wrap(+ "knowledge.add_document_to_knowledge_base",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ try:+ from agno.workflow.workflow import Workflow+ except ImportError:+ Workflow = None++ # agno 2.x versions do not have Workflow.run_workflow and Workflow.arun_workflow methods+ if Workflow is not None and hasattr(Workflow, "run_workflow"):+ wrap_function_wrapper(+ "agno.workflow.workflow",+ "Workflow.run_workflow",+ workflow_run_wrap(+ "workflow.run_workflow",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ wrap_function_wrapper(+ "agno.workflow.workflow",+ "Workflow.arun_workflow",+ async_workflow_run_wrap(+ "workflow.arun_workflow",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )# Async Workflow Operations (actual methods that exist)wrap_function_wrapper(@@ -431,23 +427,67 @@ class AgnoInstrumentor(BaseInstrumentor):),)- wrap_function_wrapper(- "agno.workflow.workflow",- "Workflow.arun_workflow",- async_workflow_run_wrap(- "workflow.arun_workflow",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )+# Team Operations++ try:+ from agno.team.team import Team # pylint: disable=import-error+ except ImportError:+ Team = None+ # agno 2.x versions do use Team._arun_stream and Team._arun methods+ if Team is not None and hasattr(Team, "_arun_stream"):+ wrap_function_wrapper(+ "agno.team.team",+ "Team._arun_stream",+ async_team_run_stream_wrap(+ "team._arun_stream",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ wrap_function_wrapper(+ "agno.team.team",+ "Team._arun",+ async_team_run_wrap(+ "team._arun",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ else:+ # agno 2.x versions do not have Team._arun_stream+ # Team Async Operations (actual methods that exist)+ wrap_function_wrapper(+ "agno.team.team",+ "Team.arun",+ async_team_run_wrap(+ "team.arun",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )+wrap_function_wrapper("agno.team.team","Team.run",@@ -464,23 +504,6 @@ class AgnoInstrumentor(BaseInstrumentor):),)- # Team Async Operations (actual methods that exist)- wrap_function_wrapper(- "agno.team.team",- "Team.arun",- async_team_run_wrap(- "team.arun",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-# Note: VectorDb class does not have async_search or async_upsert methods# Note: AgentKnowledge class does not have async_search method@@ -492,37 +515,44 @@ class AgnoInstrumentor(BaseInstrumentor):# without creating redundant spans for FunctionCall.execute/aexecute# Reasoning Operations- wrap_function_wrapper(- "agno.agent.agent",- "Agent.reason",- reasoning_wrap(- "agent.reason",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )-- wrap_function_wrapper(- "agno.agent.agent",- "Agent.areason",- async_reasoning_wrap(- "agent.areason",- version,- environment,- application_name,- tracer,- pricing_info,- capture_message_content,- metrics,- disable_metrics,- ),- )+ try:+ from agno.agent.agent import Agent+ except ImportError:+ Agent = None++ # agno 2.x versions do not have Agent.reason and Agent.areason methods+ if Agent is not None and hasattr(Agent, "reason"):+ wrap_function_wrapper(+ "agno.agent.agent",+ "Agent.reason",+ reasoning_wrap(+ "agent.reason",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )++ wrap_function_wrapper(+ "agno.agent.agent",+ "Agent.areason",+ async_reasoning_wrap(+ "agent.areason",+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ),+ )# Original Component Operationsif detailed_tracing:diff --git a/sdk/python/src/openlit/instrumentation/agno/async_agno.py b/sdk/python/src/openlit/instrumentation/agno/async_agno.pyindex 94a7d8f2..a83b0083 100644--- a/sdk/python/src/openlit/instrumentation/agno/async_agno.py+++ b/sdk/python/src/openlit/instrumentation/agno/async_agno.py@@ -237,7 +237,9 @@ def async_agent_run_stream_wrap(Wrap Agno Agent._arun_stream async generator method."""+async def wrapper(wrapped, instance, args, kwargs):+# CRITICAL: Suppression check to prevent recursive instrumentationif context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):async for response in wrapped(*args, **kwargs):@@ -254,13 +256,27 @@ def async_agent_run_stream_wrap(with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:start_time = time.time()-try:- async for response in wrapped(*args, **kwargs):- yield response-- # Get the final response after iteration completes- final_response = getattr(instance, "run_response", None)+ # agno 2.x: when `yield_run_response=True`, the final `RunOutput` is yielded+ # rather than stored on `instance.run_response`+ try:+ from agno.run.agent import RunOutput # noqa: WPS433 # pylint: disable=import-error+ except Exception: # noqa: WPS429+ RunOutput = None # type: ignore # pylint: disable=invalid-name+ yield_run_response = kwargs.get("yield_run_response", None)+ final_response = None+ new_kwargs = dict(kwargs)+ new_kwargs['yield_run_response'] = True+ async for response in wrapped(*args, **new_kwargs):+ if RunOutput and isinstance(response, RunOutput):+ final_response = response+ if yield_run_response:+ yield response+ else:+ yield response+ if not RunOutput:+ # Get the final response after iteration completes+ final_response = getattr(instance, "run_response", None)except Exception as e:handle_exception(span, e)logger.error("Error in async agent._arun_stream: %s", e)@@ -874,6 +890,86 @@ def async_team_run_wrap(return wrapper+def async_team_run_stream_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Wrap Team async stream run; request final RunOutput via yield_run_response=True.+ """++ async def wrapper(wrapped, instance, args, kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ async for item in wrapped(*args, **kwargs):+ yield item+ return++ team_name = getattr(instance, "name", "unknown_team")+ span_name = f"team {team_name}"++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()+ final_response = None+++ try:+ # agno 2.x: when `yield_run_response=True`, the final `TeamRunOutput` is yielded+ # rather than stored on `instance.run_response`+ try:+ from agno.run.team import TeamRunOutput # noqa: WPS433 # pylint: disable=import-error+ except Exception: # noqa: WPS429+ TeamRunOutput = None # type: ignore # pylint: disable=invalid-name++ yield_run_response = kwargs.get("yield_run_response", None)+ final_response = None+ new_kwargs = dict(kwargs)+ new_kwargs['yield_run_response'] = True+ async for response in wrapped(*args, **new_kwargs):+ if TeamRunOutput and isinstance(response, TeamRunOutput):+ final_response = response+ if yield_run_response:+ yield response+ else:+ yield response+ if not TeamRunOutput:+ # Get the final response after iteration completes+ final_response = getattr(instance, "run_response", None)+ except Exception as e:+ handle_exception(span, e)+ logger.error("Error in team stream run: %s", e)+ raise++ try:+ process_team_request(+ span,+ instance,+ args,+ kwargs,+ final_response,+ start_time,+ pricing_info,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ )+ span.set_status(Status(StatusCode.OK))+ except Exception as e:+ handle_exception(span, e)+ logger.error("Error creating team stream trace: %s", e)++ return wrapper++def async_agent_add_tool_wrap(gen_ai_endpoint,version,diff --git a/sdk/python/src/openlit/instrumentation/agno/utils.py b/sdk/python/src/openlit/instrumentation/agno/utils.pyindex 9d18c246..af5dbf0c 100644--- a/sdk/python/src/openlit/instrumentation/agno/utils.py+++ b/sdk/python/src/openlit/instrumentation/agno/utils.py@@ -2,6 +2,7 @@Utility functions for Agno instrumentation following OpenLIT patterns."""+import importlibimport loggingimport timefrom openlit.__helpers import (@@ -149,6 +150,17 @@ def process_agent_request(SemanticConvention.GEN_AI_CONTENT_PROMPT, str(args[0])[:1000])+ # agno 2.x versions agent.run use input instead of args[0]+ if kwargs and kwargs.get('input', None) and capture_message_content:+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_PROMPT, str(kwargs['input'])[:1000]+ )+ # agno 2.x versions team.run use input_message instead of args[0]+ if kwargs and kwargs.get('input_message', None) and capture_message_content:+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_PROMPT, str(kwargs['input_message'])[:1000]+ )+# User and session informationif "user_id" in kwargs and kwargs["user_id"]:span.set_attribute(SemanticConvention.GEN_AI_REQUEST_USER, kwargs["user_id"])@@ -158,6 +170,10 @@ def process_agent_request(if "session_id" in kwargs and kwargs["session_id"]:span.set_attribute(SemanticConvention.GEN_AI_SESSION_ID, kwargs["session_id"])+ # agno 2.x versions use session instead of session_id+ if "session" in kwargs and kwargs["session"] and hasattr(kwargs["session"], "session_id"):+ span.set_attribute(SemanticConvention.GEN_AI_SESSION_ID, kwargs["session"].session_id)+# Stream and reasoning attributesif "stream" in kwargs:span.set_attribute(@@ -758,6 +774,15 @@ def process_team_request(SemanticConvention.GEN_AI_TEAM_AGENT_COUNT, len(instance.agents))+ if hasattr(instance, "members") and instance.members:+ agent_names = [getattr(agent, "name", "unknown") for agent in instance.members]+ span.set_attribute(+ SemanticConvention.GEN_AI_TEAM_AGENTS, agent_names[:10]+ ) # Limit to 10+ span.set_attribute(+ SemanticConvention.GEN_AI_TEAM_AGENT_COUNT, len(instance.members)+ )+# Set execution metricsspan.set_attribute(SemanticConvention.GEN_AI_TEAM_EXECUTION_DURATION, execution_time@@ -765,3 +790,78 @@ def process_team_request(span.set_attribute(SemanticConvention.GEN_AI_TEAM_OPERATION_SUCCESS, response is not None)+++def resolve_agno_memory_target():+ """+ Resolve the appropriate Agno memory target class.++ Attempts to find and import the correct memory class from Agno framework.+ Tries multiple candidate modules in order of preference.++ Returns:+ tuple: (module_name, class_name) if successful, (None, None) if no valid target found++ Example:+ >>> module, class_name = resolve_agno_memory_target()+ >>> if module:+ ... print(f"Found memory class: {class_name} in {module}")+ """+ return resolve_target("agno.memory", (+ ("agno.memory.v2.memory", "Memory"),+ ("agno.memory.manager", "MemoryManager"),))+++def resolve_agno_knowledge_target():+ """+ Resolve the appropriate Agno knowledge target class.++ Attempts to find and import the correct knowledge class from Agno framework.+ Tries multiple candidate modules in order of preference.++ Returns:+ tuple: (module_name, class_name) if successful, (None, None) if no valid target found++ Example:+ >>> module, class_name = resolve_agno_knowledge_target()+ >>> if module:+ ... print(f"Found knowledge class: {class_name} in {module}")+ """+ return resolve_target("agno.knowledge", (+ ("agno.knowledge.agent", "AgentKnowledge"),+ ("agno.knowledge.knowledge", "Knowledge"),))++def resolve_target(target_name, candidates):+ """+ Resolve a target class by trying multiple candidate modules.++ This function attempts to import and find a specific class from a list of candidate+ modules. It tries each candidate in order until it finds a valid module and class.++ Args:+ target_name (str): Name of the target being resolved (used for logging)+ candidates (tuple): Tuple of (module_name, class_name) pairs to try++ Returns:+ tuple: (module_name, class_name) if successful, (None, None) if no valid target found++ Example:+ >>> candidates = (+ ... ("agno.memory.v2.memory", "Memory"),+ ... ("agno.memory.manager", "MemoryManager")+ ... )+ >>> module, class_name = resolve_target("agno.memory", candidates)+ >>> if module:+ ... print(f"Found: {class_name} in {module}")+ """+ for module_name, class_name in candidates:+ try:+ module = importlib.import_module(module_name)+ if hasattr(module, class_name):+ return module_name, class_name+ except ModuleNotFoundError:+ continue+ except Exception as e:+ logger.info(f"Skip {target_name} candidate %s due to: %s", module_name, e)+ continue+ return None, Nonediff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex 36dccfab..7106735a 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -84,6 +84,7 @@ class SemanticConvention:GEN_AI_OPERATION_TYPE_VECTORDB = "vectordb"GEN_AI_OPERATION_TYPE_FRAMEWORK = "workflow"GEN_AI_OPERATION_TYPE_AGENT = "invoke_agent"+ GEN_AI_OPERATION_TYPE_TEAM = "team"GEN_AI_OPERATION_TYPE_CREATE_AGENT = "create_agent"GEN_AI_OPERATION_TYPE_EXECUTE_AGENT_TASK = "execute_task"GEN_AI_OPERATION_TYPE_GRAPH_EXECUTION = "graph_execution"