Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions agentkit/apps/a2a_app/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@

logger = logging.getLogger("agentkit." + __name__)


class Telemetry:
def __init__(self):
self.tracer = get_tracer("agentkit.a2a_app")
Expand All @@ -58,6 +57,7 @@ def __init__(self):
explicit_bucket_boundaries_advisory=_GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS,
)


def trace_a2a_agent(
self,
func: Callable,
Expand All @@ -69,9 +69,7 @@ def trace_a2a_agent(
"""Get current span and set required attributes."""
trace_id = span.get_span_context().trace_id
span_id = span.get_span_context().span_id
logger.debug(
f"Set attributes for span with trace_id={trace_id}, span_id={span_id}"
)
logger.debug(f"Set attributes for span with trace_id={trace_id}, span_id={span_id}")

# ===============================
# Set attributes for current span
Expand All @@ -89,18 +87,12 @@ def trace_a2a_agent(
if user_id:
span.set_attribute(key="gen_ai.user.id", value=user_id)

span.set_attribute(
key="gen_ai.input",
value=safe_serialize_to_json_string(request.message.parts),
)
span.set_attribute(key="gen_ai.input", value=safe_serialize_to_json_string(request.message.parts))

span.set_attribute(key="gen_ai.span.kind", value="a2a_agent")
span.set_attribute(key="gen_ai.operation.name", value="invoke_agent")
span.set_attribute(key="gen_ai.operation.type", value="a2a_agent")
attributes = {
"gen_ai_operation_name": "invoke_agent",
"gen_ai_operation_type": "a2a_agent",
}
attributes={"gen_ai_operation_name": "invoke_agent", "gen_ai_operation_type": "a2a_agent"}

if exception:
self.handle_exception(span, exception)
Expand All @@ -124,3 +116,4 @@ def handle_exception(span: trace.Span, exception: Exception) -> None:


telemetry = Telemetry()

29 changes: 11 additions & 18 deletions agentkit/apps/mcp_app/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@

logger = logging.getLogger("agentkit." + __name__)


class Telemetry:
def __init__(self):
self.tracer = get_tracer("agentkit.mcp_app")
Expand All @@ -57,22 +56,20 @@ def __init__(self):
)

def trace_tool(
self,
func: Callable,
span: Span,
args: dict,
func_result: any,
operation_type: str,
exception: Exception,
self,
func: Callable,
span: Span,
args: dict,
func_result: any,
operation_type: str,
exception: Exception,
) -> None:
"""Get current span and set required attributes."""

trace_id = span.get_span_context().trace_id
span_id = span.get_span_context().span_id

logger.debug(
f"Set attributes for span with trace_id={trace_id}, span_id={span_id}"
)
logger.debug(f"Set attributes for span with trace_id={trace_id}, span_id={span_id}")

# ===============================
# Set attributes for current span
Expand All @@ -82,19 +79,14 @@ def trace_tool(

span.set_attribute(key="gen_ai.func_name", value=func.__name__)

span.set_attribute(
key="gen_ai.input", value=safe_serialize_to_json_string(args)
)
span.set_attribute(key="gen_ai.input", value=safe_serialize_to_json_string(args))
safe_result = safe_serialize_to_json_string(func_result)
span.set_attribute(key="gen_ai.output", value=safe_result)

span.set_attribute(key="gen_ai.span.kind", value="tool")
span.set_attribute(key="gen_ai.operation.name", value="tool")
span.set_attribute(key="gen_ai.operation.type", value=operation_type)
attributes = {
"gen_ai_operation_name": "tool",
"gen_ai_operation_type": operation_type,
}
attributes = {"gen_ai_operation_name": "tool", "gen_ai_operation_type": operation_type}

if exception:
self.handle_exception(span, exception)
Expand All @@ -118,3 +110,4 @@ def handle_exception(span: trace.Span, exception: Exception) -> None:


telemetry = Telemetry()

16 changes: 12 additions & 4 deletions agentkit/apps/simple_app/simple_app_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,14 @@ async def handle(self, request: Request) -> Response | StreamingResponse:

logger.info("Returning non-streaming response")
safe_json_string = safe_serialize_to_json_string(result)
telemetry.trace_agent_finish(safe_json_string, None)
telemetry.trace_agent_finish(
safe_json_string, None
)
except Exception as e:
logger.error("Invoke handler function failed: %s", e)
telemetry.trace_agent_finish("", e)
telemetry.trace_agent_finish(
"", e
)
raise e

return Response(safe_json_string, media_type="application/json")
Expand Down Expand Up @@ -156,7 +160,9 @@ def _sync_stream_with_error_handling(self, generator):
finally:
# finish trace span and record metrics
result = safe_serialize_to_json_string(last_value)
telemetry.trace_agent_finish(result, exception)
telemetry.trace_agent_finish(
result, exception
)

async def _stream_with_error_handling(self, generator):
"""Wrap async generator to handle errors and convert to SSE format."""
Expand All @@ -178,7 +184,9 @@ async def _stream_with_error_handling(self, generator):
finally:
# finish trace span and record metrics
result = safe_serialize_to_json_string(last_value)
telemetry.trace_agent_finish(result, exception)
telemetry.trace_agent_finish(
result, exception
)


class PingHandler(BaseHandler):
Expand Down
13 changes: 3 additions & 10 deletions agentkit/apps/simple_app/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@ def trace_agent(
trace_id = span.get_span_context().trace_id
span_id = span.get_span_context().span_id

logger.debug(
f"Set attributes for span with trace_id={trace_id}, span_id={span_id}"
)
logger.debug(f"Set attributes for span with trace_id={trace_id}, span_id={span_id}")

# ===============================
# Set attributes for current span
Expand All @@ -114,9 +112,7 @@ def trace_agent(
if user_id:
span.set_attribute(key="gen_ai.user.id", value=user_id)

span.set_attribute(
key="gen_ai.input", value=safe_serialize_to_json_string(payload)
)
span.set_attribute(key="gen_ai.input", value=safe_serialize_to_json_string(payload))

span.set_attribute(key="gen_ai.span.kind", value="workflow")
span.set_attribute(key="gen_ai.operation.name", value="invoke_agent")
Expand All @@ -132,10 +128,7 @@ def trace_agent_finish(

if span and span.is_recording():
span.set_attribute(key="gen_ai.output", value=func_result)
attributes = {
"gen_ai_operation_name": "invoke_agent",
"gen_ai_operation_type": "agent",
}
attributes={"gen_ai_operation_name": "invoke_agent", "gen_ai_operation_type": "agent"}
if exception:
self.handle_exception(span, exception)
attributes["error_type"] = exception.__class__.__name__
Expand Down
8 changes: 4 additions & 4 deletions agentkit/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from agentkit.client.base_iam_client import BaseIAMClient

__all__ = [
"BaseServiceClient",
"BaseAgentkitClient",
"BaseIAMClient",
"ApiConfig",
'BaseServiceClient',
'BaseAgentkitClient',
'BaseIAMClient',
'ApiConfig',
]
24 changes: 12 additions & 12 deletions agentkit/client/base_agentkit_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@
class BaseAgentkitClient(BaseServiceClient):
"""
Base client for all AgentKit services.

This class provides:
1. Common credential initialization
2. Unified API invocation logic with error handling
3. Automatic ApiInfo generation with flexible configuration

Subclasses should override API_ACTIONS with either:
- Simple dict mapping: {"ActionName": "ActionName"}
- Detailed ApiConfig: {"ActionName": ApiConfig(action="ActionName", method="GET", path="/custom")}
"""

# Subclasses should override this with their API action configurations
API_ACTIONS: Dict[str, Union[str, ApiConfig]] = {}

def __init__(
self,
access_key: str = "",
Expand All @@ -50,7 +50,7 @@ def __init__(
) -> None:
"""
Initialize the AgentKit client.

Args:
access_key: Volcengine access key
secret_key: Volcengine secret key
Expand All @@ -64,23 +64,23 @@ def __init__(
region=region,
session_token=session_token,
service_name=service_name,
credential_env_prefix="AGENTKIT",
credential_env_prefix='AGENTKIT',
)

def _get_service_config(self) -> Dict[str, str]:
"""
Get AgentKit service configuration.

Returns:
Dictionary with host, api_version, and service
"""
host, api_version, service = get_volc_agentkit_host_info()
return {
"host": host,
"api_version": api_version,
"service": service,
'host': host,
'api_version': api_version,
'service': service,
}

def _get(self, api_action: str, params: Dict[str, Any] = None) -> str:
"""Legacy method for GET requests."""
try:
Expand Down
26 changes: 13 additions & 13 deletions agentkit/client/base_iam_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,25 @@
class BaseIAMClient(BaseServiceClient):
"""
Base client for IAM services.

This class provides the same interface as BaseAgentkitClient but for IAM services:
1. Common credential initialization
2. Unified API invocation logic with error handling
3. Automatic ApiInfo generation with flexible configuration

Subclasses should override API_ACTIONS with either:
- Simple dict mapping: {"ActionName": "ActionName"}
- Detailed ApiConfig: {"ActionName": ApiConfig(action="ActionName", method="GET", path="/custom")}
"""

# Subclasses should override this with their API action configurations
API_ACTIONS: Dict[str, Union[str, ApiConfig]] = {}

# IAM service specific configuration
IAM_API_VERSION = "2018-01-01"
IAM_SERVICE_CODE = "iam"
IAM_HOST = "open.volcengineapi.com"

IAM_HOST ="open.volcengineapi.com"
def __init__(
self,
access_key: str = "",
Expand All @@ -54,7 +54,7 @@ def __init__(
) -> None:
"""
Initialize the IAM client.

Args:
access_key: Volcengine access key
secret_key: Volcengine secret key
Expand All @@ -68,18 +68,18 @@ def __init__(
region=region,
session_token=session_token,
service_name=service_name,
credential_env_prefix="IAM",
credential_env_prefix='IAM',
)

def _get_service_config(self) -> Dict[str, str]:
"""
Get IAM service configuration.

Returns:
Dictionary with host, api_version, and service
"""
return {
"host": self.IAM_HOST,
"api_version": self.IAM_API_VERSION,
"service": self.IAM_SERVICE_CODE,
'host': self.IAM_HOST,
'api_version': self.IAM_API_VERSION,
'service': self.IAM_SERVICE_CODE,
}
Loading