|
| 1 | +""" |
| 2 | +Middleware that records agent metrics using OpenTelemetry. |
| 3 | +Tracks agent invocations, LLM calls, tool calls, and errors. |
| 4 | +
|
| 5 | +Token usage and operation duration are already provided by the built-in |
| 6 | +``agent_framework.observability`` telemetry layers and do not need to be |
| 7 | +duplicated here. |
| 8 | +""" |
| 9 | + |
| 10 | +from collections.abc import Awaitable, Callable |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +from agent_framework import ( |
| 14 | + AgentContext, |
| 15 | + AgentMiddleware, |
| 16 | + ChatContext, |
| 17 | + ChatMiddleware, |
| 18 | + FunctionInvocationContext, |
| 19 | + FunctionMiddleware, |
| 20 | + MiddlewareTypes, |
| 21 | +) |
| 22 | +from opentelemetry import metrics |
| 23 | + |
| 24 | +_meter = metrics.get_meter("agenticlayer.agent") |
| 25 | + |
| 26 | +_agent_invocations = _meter.create_counter( |
| 27 | + "agent.invocations", |
| 28 | + unit="{invocation}", |
| 29 | + description="Number of agent invocations", |
| 30 | +) |
| 31 | +_llm_calls = _meter.create_counter( |
| 32 | + "agent.llm.calls", |
| 33 | + unit="{call}", |
| 34 | + description="Number of LLM calls", |
| 35 | +) |
| 36 | +_tool_calls = _meter.create_counter( |
| 37 | + "agent.tool.calls", |
| 38 | + unit="{call}", |
| 39 | + description="Number of tool calls", |
| 40 | +) |
| 41 | +_agent_errors = _meter.create_counter( |
| 42 | + "agent.errors", |
| 43 | + unit="{error}", |
| 44 | + description="Number of agent errors", |
| 45 | +) |
| 46 | + |
| 47 | + |
| 48 | +class AgentInvocationMetrics(AgentMiddleware): |
| 49 | + """Counts agent invocations and errors.""" |
| 50 | + |
| 51 | + async def process( |
| 52 | + self, |
| 53 | + context: AgentContext, |
| 54 | + call_next: Callable[[], Awaitable[None]], |
| 55 | + ) -> None: |
| 56 | + agent_name = getattr(context.agent, "name", None) or "unknown" |
| 57 | + _agent_invocations.add(1, {"agent_name": agent_name}) |
| 58 | + try: |
| 59 | + await call_next() |
| 60 | + except Exception: |
| 61 | + _agent_errors.add(1, {"agent_name": agent_name, "error_source": "agent"}) |
| 62 | + raise |
| 63 | + |
| 64 | + |
| 65 | +class LlmCallMetrics(ChatMiddleware): |
| 66 | + """Counts LLM / chat-client calls and records model-level errors.""" |
| 67 | + |
| 68 | + async def process( |
| 69 | + self, |
| 70 | + context: ChatContext, |
| 71 | + call_next: Callable[[], Awaitable[None]], |
| 72 | + ) -> None: |
| 73 | + options = context.options or {} |
| 74 | + model: str = options.get("model_id") or getattr(context.client, "model_id", None) or "unknown" |
| 75 | + attrs: dict[str, Any] = {"model": model} |
| 76 | + _llm_calls.add(1, attrs) |
| 77 | + try: |
| 78 | + await call_next() |
| 79 | + except Exception: |
| 80 | + _agent_errors.add(1, {**attrs, "error_source": "model"}) |
| 81 | + raise |
| 82 | + |
| 83 | + |
| 84 | +class ToolCallMetrics(FunctionMiddleware): |
| 85 | + """Counts tool / function calls and records tool-level errors.""" |
| 86 | + |
| 87 | + async def process( |
| 88 | + self, |
| 89 | + context: FunctionInvocationContext, |
| 90 | + call_next: Callable[[], Awaitable[None]], |
| 91 | + ) -> None: |
| 92 | + tool_name = getattr(context.function, "name", None) or "unknown" |
| 93 | + _tool_calls.add(1, {"tool_name": tool_name}) |
| 94 | + try: |
| 95 | + await call_next() |
| 96 | + except Exception: |
| 97 | + _agent_errors.add(1, {"tool_name": tool_name, "error_source": "tool"}) |
| 98 | + raise |
| 99 | + |
| 100 | + |
| 101 | +def create_metrics_middleware() -> list[MiddlewareTypes]: |
| 102 | + """Return the full set of metrics middleware ready to pass to an Agent. |
| 103 | +
|
| 104 | + Example:: |
| 105 | +
|
| 106 | + from agent_framework import Agent |
| 107 | + from agenticlayer.msaf.metrics_middleware import create_metrics_middleware |
| 108 | +
|
| 109 | + agent = Agent( |
| 110 | + client=client, |
| 111 | + middleware=create_metrics_middleware(), |
| 112 | + ) |
| 113 | + """ |
| 114 | + return [AgentInvocationMetrics(), LlmCallMetrics(), ToolCallMetrics()] |
0 commit comments