|
| 1 | +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import time |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +from opentelemetry import trace |
| 20 | +from opentelemetry.trace import get_tracer |
| 21 | +from opentelemetry.metrics import get_meter |
| 22 | +from opentelemetry.trace.span import Span |
| 23 | + |
| 24 | +from agentkit.apps.utils import safe_serialize_to_json_string |
| 25 | + |
| 26 | +_INVOKE_PATH = ["/run_sse", "/run", "/invoke"] |
| 27 | + |
| 28 | +_GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS = [ |
| 29 | + 0.01, |
| 30 | + 0.02, |
| 31 | + 0.04, |
| 32 | + 0.08, |
| 33 | + 0.16, |
| 34 | + 0.32, |
| 35 | + 0.64, |
| 36 | + 1.28, |
| 37 | + 2.56, |
| 38 | + 5.12, |
| 39 | + 10.24, |
| 40 | + 20.48, |
| 41 | + 40.96, |
| 42 | + 81.92, |
| 43 | + 163.84, |
| 44 | +] |
| 45 | + |
| 46 | +logger = logging.getLogger("agentkit." + __name__) |
| 47 | + |
| 48 | + |
| 49 | +class Telemetry: |
| 50 | + def __init__(self): |
| 51 | + self.tracer = get_tracer("agentkit.agent_server_app") |
| 52 | + self.meter = get_meter("agentkit.agent_server_app") |
| 53 | + self.latency_histogram = self.meter.create_histogram( |
| 54 | + name="agentkit_runtime_operation_latency", |
| 55 | + description="operation latency", |
| 56 | + unit="s", |
| 57 | + explicit_bucket_boundaries_advisory=_GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS, |
| 58 | + ) |
| 59 | + |
| 60 | + def trace_agent_server( |
| 61 | + self, |
| 62 | + func_name: str, |
| 63 | + span: Span, |
| 64 | + headers: dict, |
| 65 | + text: str, |
| 66 | + ) -> None: |
| 67 | + span.set_attribute(key="gen_ai.system", value="agentkit") |
| 68 | + span.set_attribute(key="gen_ai.func_name", value=func_name) |
| 69 | + |
| 70 | + span.set_attribute( |
| 71 | + key="gen_ai.request.headers", |
| 72 | + value=safe_serialize_to_json_string(headers), |
| 73 | + ) |
| 74 | + |
| 75 | + session_id = headers.get("session_id") or headers.get("x-session-id") or "" |
| 76 | + if session_id: |
| 77 | + span.set_attribute(key="gen_ai.session.id", value=session_id) |
| 78 | + user_id = headers.get("user_id") or headers.get("x-user-id") or "" |
| 79 | + if user_id: |
| 80 | + span.set_attribute(key="gen_ai.user.id", value=user_id) |
| 81 | + |
| 82 | + # Currently unable to retrieve input |
| 83 | + # span.set_attribute( |
| 84 | + # key="gen_ai.input", value=safe_serialize_to_json_string(text) |
| 85 | + # ) |
| 86 | + |
| 87 | + span.set_attribute(key="gen_ai.span.kind", value="agent_server") |
| 88 | + span.set_attribute(key="gen_ai.operation.name", value="invoke_agent") |
| 89 | + span.set_attribute(key="gen_ai.operation.type", value="agent_server") |
| 90 | + |
| 91 | + def trace_agent_server_finish( |
| 92 | + self, |
| 93 | + path: str, |
| 94 | + func_result: str, |
| 95 | + exception: Optional[Exception], |
| 96 | + ) -> None: |
| 97 | + span = trace.get_current_span() |
| 98 | + if span and span.is_recording(): |
| 99 | + # Currently unable to retrieve output |
| 100 | + # span.set_attribute(key="gen_ai.output", value=func_result) |
| 101 | + |
| 102 | + attributes = { |
| 103 | + "gen_ai_operation_name": "invoke_agent", |
| 104 | + "gen_ai_operation_type": "agent_server", |
| 105 | + } |
| 106 | + if exception: |
| 107 | + self.handle_exception(span, exception) |
| 108 | + attributes["error_type"] = exception.__class__.__name__ |
| 109 | + |
| 110 | + # only record invoke request latency metrics |
| 111 | + if hasattr(span, "start_time") and self.latency_histogram and path in _INVOKE_PATH: |
| 112 | + duration = (time.time_ns() - span.start_time) / 1e9 # type: ignore |
| 113 | + self.latency_histogram.record(duration, attributes) |
| 114 | + span.end() |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def handle_exception(span: trace.Span, exception: Exception) -> None: |
| 118 | + status = trace.Status( |
| 119 | + status_code=trace.StatusCode.ERROR, |
| 120 | + description=f"{type(exception).__name__}: {exception}", |
| 121 | + ) |
| 122 | + span.set_status(status) |
| 123 | + span.record_exception(exception) |
| 124 | + |
| 125 | + |
| 126 | +telemetry = Telemetry() |
0 commit comments