agent-did-semantic-kernel 1.0.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_did_semantic_kernel/__init__.py +49 -0
- agent_did_semantic_kernel/config.py +30 -0
- agent_did_semantic_kernel/context.py +42 -0
- agent_did_semantic_kernel/integration.py +148 -0
- agent_did_semantic_kernel/observability.py +340 -0
- agent_did_semantic_kernel/runtime.py +87 -0
- agent_did_semantic_kernel/sanitization.py +101 -0
- agent_did_semantic_kernel/snapshot.py +52 -0
- agent_did_semantic_kernel/tools.py +530 -0
- agent_did_semantic_kernel-1.0.0rc1.dist-info/METADATA +346 -0
- agent_did_semantic_kernel-1.0.0rc1.dist-info/RECORD +13 -0
- agent_did_semantic_kernel-1.0.0rc1.dist-info/WHEEL +5 -0
- agent_did_semantic_kernel-1.0.0rc1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Public package surface for the Agent-DID Semantic Kernel integration."""
|
|
2
|
+
|
|
3
|
+
from .config import AgentDidExposureConfig, AgentDidSemanticKernelConfig
|
|
4
|
+
from .context import build_agent_did_instructions, compose_instructions
|
|
5
|
+
from .integration import (
|
|
6
|
+
AgentDidSemanticKernelIntegration,
|
|
7
|
+
create_agent_did_semantic_kernel_integration,
|
|
8
|
+
)
|
|
9
|
+
from .observability import (
|
|
10
|
+
AgentDidEventHandler,
|
|
11
|
+
AgentDidSemanticKernelObservabilityEvent,
|
|
12
|
+
compose_event_handlers,
|
|
13
|
+
create_json_logger_event_handler,
|
|
14
|
+
create_opentelemetry_event_handler,
|
|
15
|
+
create_opentelemetry_tracer,
|
|
16
|
+
sanitize_observability_attributes,
|
|
17
|
+
serialize_observability_event,
|
|
18
|
+
)
|
|
19
|
+
from .runtime import create_semantic_kernel_plugin
|
|
20
|
+
from .snapshot import AgentDidIdentitySnapshot, build_agent_did_identity_snapshot
|
|
21
|
+
from .tools import SemanticKernelTool, create_agent_did_tools, create_host_tool_specs
|
|
22
|
+
|
|
23
|
+
PACKAGE_STATUS = "functional"
|
|
24
|
+
createAgentDidSemanticKernelIntegration = create_agent_did_semantic_kernel_integration
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"PACKAGE_STATUS",
|
|
28
|
+
"AgentDidEventHandler",
|
|
29
|
+
"AgentDidExposureConfig",
|
|
30
|
+
"AgentDidIdentitySnapshot",
|
|
31
|
+
"AgentDidSemanticKernelConfig",
|
|
32
|
+
"AgentDidSemanticKernelIntegration",
|
|
33
|
+
"AgentDidSemanticKernelObservabilityEvent",
|
|
34
|
+
"SemanticKernelTool",
|
|
35
|
+
"build_agent_did_identity_snapshot",
|
|
36
|
+
"build_agent_did_instructions",
|
|
37
|
+
"compose_event_handlers",
|
|
38
|
+
"compose_instructions",
|
|
39
|
+
"createAgentDidSemanticKernelIntegration",
|
|
40
|
+
"create_agent_did_semantic_kernel_integration",
|
|
41
|
+
"create_agent_did_tools",
|
|
42
|
+
"create_host_tool_specs",
|
|
43
|
+
"create_json_logger_event_handler",
|
|
44
|
+
"create_opentelemetry_event_handler",
|
|
45
|
+
"create_opentelemetry_tracer",
|
|
46
|
+
"create_semantic_kernel_plugin",
|
|
47
|
+
"sanitize_observability_attributes",
|
|
48
|
+
"serialize_observability_event",
|
|
49
|
+
]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Public configuration models for the Agent-DID Semantic Kernel integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AgentDidExposureConfig(BaseModel):
|
|
9
|
+
"""Feature exposure flags with secure defaults."""
|
|
10
|
+
|
|
11
|
+
model_config = ConfigDict(extra="forbid")
|
|
12
|
+
|
|
13
|
+
current_identity: bool = True
|
|
14
|
+
resolve_did: bool = True
|
|
15
|
+
verify_signatures: bool = True
|
|
16
|
+
sign_http: bool = False
|
|
17
|
+
sign_payload: bool = False
|
|
18
|
+
rotate_keys: bool = False
|
|
19
|
+
document_history: bool = False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AgentDidSemanticKernelConfig(BaseModel):
|
|
23
|
+
"""Top-level integration config consumed by the public factory."""
|
|
24
|
+
|
|
25
|
+
model_config = ConfigDict(extra="forbid")
|
|
26
|
+
|
|
27
|
+
expose: AgentDidExposureConfig = Field(default_factory=AgentDidExposureConfig)
|
|
28
|
+
tool_prefix: str = "agent_did"
|
|
29
|
+
additional_instructions: str | None = None
|
|
30
|
+
allow_private_network_targets: bool = False
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Instruction composition utilities for Agent-DID identity context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .snapshot import AgentDidIdentitySnapshot
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_agent_did_instructions(
|
|
9
|
+
identity_snapshot: AgentDidIdentitySnapshot,
|
|
10
|
+
additional_instructions: str | None = None,
|
|
11
|
+
) -> str:
|
|
12
|
+
capabilities = ", ".join(identity_snapshot.capabilities) if identity_snapshot.capabilities else "none"
|
|
13
|
+
lines = [
|
|
14
|
+
"Agent-DID identity context:",
|
|
15
|
+
f"- did: {identity_snapshot.did}",
|
|
16
|
+
f"- controller: {identity_snapshot.controller}",
|
|
17
|
+
f"- name: {identity_snapshot.name}",
|
|
18
|
+
f"- version: {identity_snapshot.version}",
|
|
19
|
+
f"- capabilities: {capabilities}",
|
|
20
|
+
f"- member_of: {identity_snapshot.member_of or 'none'}",
|
|
21
|
+
f"- authentication_key_id: {identity_snapshot.authentication_key_id or 'unknown'}",
|
|
22
|
+
"Rules:",
|
|
23
|
+
"- Treat this DID as the authoritative identity of this agent.",
|
|
24
|
+
"- Never invent or substitute another DID for this agent.",
|
|
25
|
+
"- Use the dedicated Agent-DID tools for DID resolution, verification and signing tasks.",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
if additional_instructions and additional_instructions.strip():
|
|
29
|
+
lines.append(f"Additional identity policy: {additional_instructions.strip()}")
|
|
30
|
+
|
|
31
|
+
return "\n".join(lines)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def compose_instructions(
|
|
35
|
+
base_instructions: str | None,
|
|
36
|
+
identity_snapshot: AgentDidIdentitySnapshot,
|
|
37
|
+
additional_instructions: str | None = None,
|
|
38
|
+
) -> str:
|
|
39
|
+
identity_section = build_agent_did_instructions(identity_snapshot, additional_instructions)
|
|
40
|
+
if base_instructions and base_instructions.strip():
|
|
41
|
+
return f"{base_instructions.strip()}\n\n{identity_section}"
|
|
42
|
+
return identity_section
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Public integration assembly for Agent-DID and Semantic Kernel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from agent_did_sdk import AgentDIDDocument, AgentIdentity
|
|
11
|
+
|
|
12
|
+
from .config import AgentDidExposureConfig, AgentDidSemanticKernelConfig
|
|
13
|
+
from .context import compose_instructions
|
|
14
|
+
from .observability import AgentDidEventHandler, AgentDidObserver
|
|
15
|
+
from .snapshot import AgentDidIdentitySnapshot, RuntimeIdentity, build_agent_did_identity_snapshot
|
|
16
|
+
from .tools import SemanticKernelTool, create_agent_did_tools, create_host_tool_specs
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(slots=True)
|
|
20
|
+
class AgentDidSemanticKernelIntegration:
|
|
21
|
+
"""Ready-to-use integration bundle for Semantic Kernel hosts."""
|
|
22
|
+
|
|
23
|
+
agent_identity: AgentIdentity
|
|
24
|
+
runtime_identity: RuntimeIdentity
|
|
25
|
+
config: AgentDidSemanticKernelConfig
|
|
26
|
+
observer: AgentDidObserver
|
|
27
|
+
tools: list[SemanticKernelTool]
|
|
28
|
+
|
|
29
|
+
def _capture_identity_snapshot(self, reason: str) -> AgentDidIdentitySnapshot:
|
|
30
|
+
snapshot = build_agent_did_identity_snapshot(self.runtime_identity)
|
|
31
|
+
self.observer.emit(
|
|
32
|
+
"agent_did.identity_snapshot.refreshed",
|
|
33
|
+
attributes={
|
|
34
|
+
"did": snapshot.did,
|
|
35
|
+
"authentication_key_id": snapshot.authentication_key_id,
|
|
36
|
+
"reason": reason,
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
return snapshot
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def identity_snapshot(self) -> AgentDidIdentitySnapshot:
|
|
43
|
+
return self._capture_identity_snapshot("property_access")
|
|
44
|
+
|
|
45
|
+
def get_current_identity(self) -> dict[str, Any]:
|
|
46
|
+
return self._capture_identity_snapshot("get_current_identity").model_dump(exclude_none=True)
|
|
47
|
+
|
|
48
|
+
def get_current_document(self) -> AgentDIDDocument:
|
|
49
|
+
return self.runtime_identity.document
|
|
50
|
+
|
|
51
|
+
def compose_instructions(
|
|
52
|
+
self,
|
|
53
|
+
base_instructions: str | None = None,
|
|
54
|
+
additional_instructions: str | None = None,
|
|
55
|
+
) -> str:
|
|
56
|
+
effective_additional_instructions = additional_instructions or self.config.additional_instructions
|
|
57
|
+
return compose_instructions(
|
|
58
|
+
base_instructions,
|
|
59
|
+
self._capture_identity_snapshot("compose_instructions"),
|
|
60
|
+
effective_additional_instructions,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def create_session_context(self, base_context: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
64
|
+
merged_context = dict(base_context or {})
|
|
65
|
+
merged_context["agent_did"] = self._capture_identity_snapshot("create_session_context").model_dump(
|
|
66
|
+
exclude_none=True
|
|
67
|
+
)
|
|
68
|
+
self.observer.emit(
|
|
69
|
+
"agent_did.context.created",
|
|
70
|
+
attributes={"keys": sorted(merged_context.keys()), "did": self.runtime_identity.document.id},
|
|
71
|
+
)
|
|
72
|
+
return merged_context
|
|
73
|
+
|
|
74
|
+
def create_context_middleware(self, *, context_key: str = "agent_did") -> Any:
|
|
75
|
+
def middleware(base_context: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
76
|
+
merged_context = dict(base_context or {})
|
|
77
|
+
merged_context[context_key] = self._capture_identity_snapshot("middleware_context_injection").model_dump(
|
|
78
|
+
exclude_none=True
|
|
79
|
+
)
|
|
80
|
+
self.observer.emit(
|
|
81
|
+
"agent_did.middleware.context_injected",
|
|
82
|
+
attributes={"context_key": context_key, "did": self.runtime_identity.document.id},
|
|
83
|
+
)
|
|
84
|
+
return merged_context
|
|
85
|
+
|
|
86
|
+
return middleware
|
|
87
|
+
|
|
88
|
+
def create_agent_kwargs(self, base_instructions: str | None = None) -> dict[str, Any]:
|
|
89
|
+
return {
|
|
90
|
+
"tools": create_host_tool_specs(self.tools),
|
|
91
|
+
"instructions": self.compose_instructions(base_instructions),
|
|
92
|
+
"context": self.create_session_context(),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
def create_semantic_kernel_plugin(
|
|
96
|
+
self,
|
|
97
|
+
*,
|
|
98
|
+
plugin_name: str = "agent_did",
|
|
99
|
+
description: str | None = None,
|
|
100
|
+
) -> Any:
|
|
101
|
+
from .runtime import create_semantic_kernel_plugin
|
|
102
|
+
|
|
103
|
+
return create_semantic_kernel_plugin(
|
|
104
|
+
self.tools,
|
|
105
|
+
plugin_name=plugin_name,
|
|
106
|
+
description=description,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def create_agent_did_semantic_kernel_integration(
|
|
111
|
+
*,
|
|
112
|
+
agent_identity: AgentIdentity,
|
|
113
|
+
runtime_identity: RuntimeIdentity,
|
|
114
|
+
expose: AgentDidExposureConfig | dict[str, Any] | None = None,
|
|
115
|
+
tool_prefix: str = "agent_did",
|
|
116
|
+
additional_instructions: str | None = None,
|
|
117
|
+
allow_private_network_targets: bool = False,
|
|
118
|
+
observability_handler: AgentDidEventHandler | None = None,
|
|
119
|
+
logger: logging.Logger | None = None,
|
|
120
|
+
) -> AgentDidSemanticKernelIntegration:
|
|
121
|
+
exposure = (
|
|
122
|
+
expose
|
|
123
|
+
if isinstance(expose, AgentDidExposureConfig)
|
|
124
|
+
else AgentDidExposureConfig.model_validate(expose or {})
|
|
125
|
+
)
|
|
126
|
+
config = AgentDidSemanticKernelConfig(
|
|
127
|
+
expose=exposure,
|
|
128
|
+
tool_prefix=tool_prefix,
|
|
129
|
+
additional_instructions=additional_instructions,
|
|
130
|
+
allow_private_network_targets=allow_private_network_targets,
|
|
131
|
+
)
|
|
132
|
+
observer = AgentDidObserver(event_handler=observability_handler, logger=logger)
|
|
133
|
+
tools = create_agent_did_tools(
|
|
134
|
+
agent_identity=agent_identity,
|
|
135
|
+
runtime_identity=runtime_identity,
|
|
136
|
+
expose=config.expose,
|
|
137
|
+
tool_prefix=config.tool_prefix,
|
|
138
|
+
allow_private_network_targets=config.allow_private_network_targets,
|
|
139
|
+
observer=observer,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
return AgentDidSemanticKernelIntegration(
|
|
143
|
+
agent_identity=agent_identity,
|
|
144
|
+
runtime_identity=runtime_identity,
|
|
145
|
+
config=config,
|
|
146
|
+
observer=observer,
|
|
147
|
+
tools=tools,
|
|
148
|
+
)
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Structured observability primitives for the Semantic Kernel integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
14
|
+
|
|
15
|
+
from .sanitization import sanitize_observability_attributes
|
|
16
|
+
|
|
17
|
+
AgentDidEventHandler = Callable[["AgentDidSemanticKernelObservabilityEvent"], None]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AgentDidSemanticKernelObservabilityEvent(BaseModel):
|
|
21
|
+
"""Typed event emitted by tools, middleware and context helpers."""
|
|
22
|
+
|
|
23
|
+
model_config = ConfigDict(extra="forbid")
|
|
24
|
+
|
|
25
|
+
event_type: str
|
|
26
|
+
level: str = "info"
|
|
27
|
+
attributes: dict[str, Any] = Field(default_factory=dict)
|
|
28
|
+
source: str = "agent_did_semantic_kernel"
|
|
29
|
+
timestamp: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(slots=True)
|
|
33
|
+
class AgentDidObserver:
|
|
34
|
+
event_handler: AgentDidEventHandler | None = None
|
|
35
|
+
logger: logging.Logger | None = None
|
|
36
|
+
|
|
37
|
+
def emit(self, event_type: str, *, attributes: dict[str, Any] | None = None, level: str = "info") -> None:
|
|
38
|
+
event = AgentDidSemanticKernelObservabilityEvent(
|
|
39
|
+
event_type=event_type,
|
|
40
|
+
level=level,
|
|
41
|
+
attributes=sanitize_observability_attributes(attributes or {}),
|
|
42
|
+
)
|
|
43
|
+
if self.event_handler is not None:
|
|
44
|
+
self.event_handler(event)
|
|
45
|
+
if self.logger is not None:
|
|
46
|
+
log_method = getattr(self.logger, level.lower(), self.logger.info)
|
|
47
|
+
log_method(json.dumps(serialize_observability_event(event), sort_keys=True))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def compose_event_handlers(*handlers: AgentDidEventHandler | None) -> AgentDidEventHandler:
|
|
51
|
+
active_handlers = [handler for handler in handlers if handler is not None]
|
|
52
|
+
|
|
53
|
+
def _composed(event: AgentDidSemanticKernelObservabilityEvent) -> None:
|
|
54
|
+
for handler in active_handlers:
|
|
55
|
+
try:
|
|
56
|
+
handler(event)
|
|
57
|
+
except Exception:
|
|
58
|
+
continue
|
|
59
|
+
|
|
60
|
+
return _composed
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def serialize_observability_event(
|
|
64
|
+
event: AgentDidSemanticKernelObservabilityEvent,
|
|
65
|
+
*,
|
|
66
|
+
include_timestamp: bool = True,
|
|
67
|
+
extra_fields: Mapping[str, Any] | None = None,
|
|
68
|
+
) -> dict[str, Any]:
|
|
69
|
+
payload = event.model_dump(exclude_none=True)
|
|
70
|
+
payload["attributes"] = sanitize_observability_attributes(payload.get("attributes", {}))
|
|
71
|
+
if not include_timestamp:
|
|
72
|
+
payload.pop("timestamp", None)
|
|
73
|
+
if extra_fields:
|
|
74
|
+
payload.update(sanitize_observability_attributes(dict(extra_fields)))
|
|
75
|
+
return payload
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def create_json_logger_event_handler(
|
|
79
|
+
logger: logging.Logger,
|
|
80
|
+
*,
|
|
81
|
+
include_timestamp: bool = True,
|
|
82
|
+
extra_fields: Mapping[str, Any] | None = None,
|
|
83
|
+
) -> AgentDidEventHandler:
|
|
84
|
+
sanitized_extra_fields = sanitize_observability_attributes(dict(extra_fields or {}))
|
|
85
|
+
|
|
86
|
+
def _handler(event: AgentDidSemanticKernelObservabilityEvent) -> None:
|
|
87
|
+
payload = serialize_observability_event(
|
|
88
|
+
event,
|
|
89
|
+
include_timestamp=include_timestamp,
|
|
90
|
+
extra_fields=sanitized_extra_fields,
|
|
91
|
+
)
|
|
92
|
+
logger.info(json.dumps(payload, sort_keys=True))
|
|
93
|
+
|
|
94
|
+
return _handler
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def create_opentelemetry_tracer(
|
|
98
|
+
*,
|
|
99
|
+
name: str = "agent_did_semantic_kernel",
|
|
100
|
+
version: str | None = None,
|
|
101
|
+
tracer_provider: Any | None = None,
|
|
102
|
+
) -> Any:
|
|
103
|
+
try:
|
|
104
|
+
trace = importlib.import_module("opentelemetry.trace")
|
|
105
|
+
except ImportError as error: # pragma: no cover - depends on optional package install
|
|
106
|
+
raise RuntimeError(
|
|
107
|
+
"OpenTelemetry support requires installing agent-did-semantic-kernel[observability]"
|
|
108
|
+
) from error
|
|
109
|
+
|
|
110
|
+
if version is None:
|
|
111
|
+
return trace.get_tracer(name, tracer_provider=tracer_provider)
|
|
112
|
+
return trace.get_tracer(name, version, tracer_provider=tracer_provider)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def create_opentelemetry_event_handler(
|
|
116
|
+
tracer: Any,
|
|
117
|
+
*,
|
|
118
|
+
include_timestamp: bool = True,
|
|
119
|
+
extra_fields: Mapping[str, Any] | None = None,
|
|
120
|
+
attributes_namespace: str = "agent_did",
|
|
121
|
+
record_exception: bool = True,
|
|
122
|
+
) -> AgentDidEventHandler:
|
|
123
|
+
try:
|
|
124
|
+
trace_module = importlib.import_module("opentelemetry.trace")
|
|
125
|
+
Status = getattr(trace_module, "Status")
|
|
126
|
+
StatusCode = getattr(trace_module, "StatusCode")
|
|
127
|
+
except ImportError as error: # pragma: no cover - depends on optional package install
|
|
128
|
+
raise RuntimeError(
|
|
129
|
+
"OpenTelemetry support requires installing agent-did-semantic-kernel[observability]"
|
|
130
|
+
) from error
|
|
131
|
+
|
|
132
|
+
active_tool_spans: dict[tuple[str, str], Any] = {}
|
|
133
|
+
sanitized_extra_fields = sanitize_observability_attributes(dict(extra_fields or {}))
|
|
134
|
+
|
|
135
|
+
def _handler(event: AgentDidSemanticKernelObservabilityEvent) -> None:
|
|
136
|
+
record = serialize_observability_event(
|
|
137
|
+
event,
|
|
138
|
+
include_timestamp=include_timestamp,
|
|
139
|
+
extra_fields=sanitized_extra_fields,
|
|
140
|
+
)
|
|
141
|
+
span_attributes = _build_span_attributes(record, namespace=attributes_namespace)
|
|
142
|
+
event_attributes = _build_event_attributes(record, namespace=attributes_namespace)
|
|
143
|
+
|
|
144
|
+
raw_attributes = record.get("attributes", {})
|
|
145
|
+
if _is_tool_lifecycle_event(event.event_type, raw_attributes):
|
|
146
|
+
_handle_tool_lifecycle_event(
|
|
147
|
+
tracer,
|
|
148
|
+
active_tool_spans,
|
|
149
|
+
event.event_type,
|
|
150
|
+
raw_attributes,
|
|
151
|
+
span_attributes,
|
|
152
|
+
event_attributes,
|
|
153
|
+
record_exception=record_exception,
|
|
154
|
+
status_cls=Status,
|
|
155
|
+
status_code_cls=StatusCode,
|
|
156
|
+
)
|
|
157
|
+
return
|
|
158
|
+
|
|
159
|
+
_handle_generic_span_event(
|
|
160
|
+
tracer,
|
|
161
|
+
event.event_type,
|
|
162
|
+
event.level,
|
|
163
|
+
raw_attributes,
|
|
164
|
+
span_attributes,
|
|
165
|
+
event_attributes,
|
|
166
|
+
status_cls=Status,
|
|
167
|
+
status_code_cls=StatusCode,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
return _handler
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _is_tool_lifecycle_event(event_type: str, raw_attributes: Any) -> bool:
|
|
174
|
+
if not isinstance(raw_attributes, Mapping):
|
|
175
|
+
return False
|
|
176
|
+
return (
|
|
177
|
+
isinstance(raw_attributes.get("tool_name"), str)
|
|
178
|
+
and isinstance(raw_attributes.get("did"), str)
|
|
179
|
+
and event_type.startswith("agent_did.tool.")
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _handle_tool_lifecycle_event(
|
|
184
|
+
tracer: Any,
|
|
185
|
+
active_tool_spans: dict[tuple[str, str], Any],
|
|
186
|
+
event_type: str,
|
|
187
|
+
raw_attributes: Mapping[str, Any],
|
|
188
|
+
span_attributes: Mapping[str, Any],
|
|
189
|
+
event_attributes: Mapping[str, Any],
|
|
190
|
+
*,
|
|
191
|
+
record_exception: bool,
|
|
192
|
+
status_cls: Any,
|
|
193
|
+
status_code_cls: Any,
|
|
194
|
+
) -> None:
|
|
195
|
+
tool_name = str(raw_attributes["tool_name"])
|
|
196
|
+
did = str(raw_attributes["did"])
|
|
197
|
+
span_key = (tool_name, did)
|
|
198
|
+
|
|
199
|
+
if event_type.endswith(".started"):
|
|
200
|
+
span = tracer.start_span(tool_name)
|
|
201
|
+
_set_span_attributes(span, span_attributes)
|
|
202
|
+
span.add_event(event_type, event_attributes)
|
|
203
|
+
active_tool_spans[span_key] = span
|
|
204
|
+
return
|
|
205
|
+
|
|
206
|
+
span = active_tool_spans.pop(span_key, None)
|
|
207
|
+
if span is None:
|
|
208
|
+
span = tracer.start_span(tool_name)
|
|
209
|
+
_set_span_attributes(span, span_attributes)
|
|
210
|
+
span.add_event(event_type, event_attributes)
|
|
211
|
+
if event_type.endswith(".failed"):
|
|
212
|
+
error_message = str(raw_attributes.get("error") or "unknown error")
|
|
213
|
+
if record_exception:
|
|
214
|
+
span.record_exception(RuntimeError(error_message))
|
|
215
|
+
span.set_status(status_cls(status_code_cls.ERROR, error_message))
|
|
216
|
+
else:
|
|
217
|
+
span.set_status(status_cls(status_code_cls.OK))
|
|
218
|
+
span.end()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _handle_generic_span_event(
|
|
222
|
+
tracer: Any,
|
|
223
|
+
event_type: str,
|
|
224
|
+
level: str,
|
|
225
|
+
raw_attributes: Mapping[str, Any] | Any,
|
|
226
|
+
span_attributes: Mapping[str, Any],
|
|
227
|
+
event_attributes: Mapping[str, Any],
|
|
228
|
+
*,
|
|
229
|
+
status_cls: Any,
|
|
230
|
+
status_code_cls: Any,
|
|
231
|
+
) -> None:
|
|
232
|
+
span = tracer.start_span(event_type)
|
|
233
|
+
_set_span_attributes(span, span_attributes)
|
|
234
|
+
span.add_event(event_type, event_attributes)
|
|
235
|
+
if level.lower() == "error":
|
|
236
|
+
error_message = (
|
|
237
|
+
str(raw_attributes.get("error") or event_type)
|
|
238
|
+
if isinstance(raw_attributes, Mapping)
|
|
239
|
+
else event_type
|
|
240
|
+
)
|
|
241
|
+
span.set_status(status_cls(status_code_cls.ERROR, error_message))
|
|
242
|
+
else:
|
|
243
|
+
span.set_status(status_cls(status_code_cls.OK))
|
|
244
|
+
span.end()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _build_span_attributes(record: Mapping[str, Any], *, namespace: str) -> dict[str, Any]:
|
|
248
|
+
attributes: dict[str, Any] = {}
|
|
249
|
+
for key, value in record.items():
|
|
250
|
+
normalized_key = _normalize_key(str(key))
|
|
251
|
+
_flatten_span_value(f"{namespace}.{normalized_key}", value, attributes)
|
|
252
|
+
return attributes
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _build_event_attributes(record: Mapping[str, Any], *, namespace: str) -> dict[str, Any]:
|
|
256
|
+
event_attributes: dict[str, Any] = {}
|
|
257
|
+
for key, value in record.items():
|
|
258
|
+
if key == "attributes":
|
|
259
|
+
continue
|
|
260
|
+
if value is None:
|
|
261
|
+
continue
|
|
262
|
+
event_attributes[f"{namespace}.{_normalize_key(str(key))}"] = str(value)
|
|
263
|
+
raw_attributes = record.get("attributes")
|
|
264
|
+
if isinstance(raw_attributes, Mapping):
|
|
265
|
+
flattened_attributes: dict[str, Any] = {}
|
|
266
|
+
_flatten_span_value(f"{namespace}.attributes", raw_attributes, flattened_attributes)
|
|
267
|
+
for key, value in flattened_attributes.items():
|
|
268
|
+
event_attributes[key] = _coerce_event_value(value)
|
|
269
|
+
return event_attributes
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _flatten_span_value(prefix: str, value: Any, flattened: dict[str, Any]) -> None:
|
|
273
|
+
if value is None:
|
|
274
|
+
return
|
|
275
|
+
if isinstance(value, Mapping):
|
|
276
|
+
for key, item in value.items():
|
|
277
|
+
_flatten_span_value(f"{prefix}.{_normalize_key(str(key))}", item, flattened)
|
|
278
|
+
return
|
|
279
|
+
if isinstance(value, list):
|
|
280
|
+
coerced = _coerce_sequence(value)
|
|
281
|
+
if coerced is not None:
|
|
282
|
+
flattened[prefix] = coerced
|
|
283
|
+
return
|
|
284
|
+
for index, item in enumerate(value):
|
|
285
|
+
_flatten_span_value(f"{prefix}.{index}", item, flattened)
|
|
286
|
+
return
|
|
287
|
+
if isinstance(value, tuple):
|
|
288
|
+
coerced = _coerce_sequence(list(value))
|
|
289
|
+
if coerced is not None:
|
|
290
|
+
flattened[prefix] = coerced
|
|
291
|
+
return
|
|
292
|
+
for index, item in enumerate(value):
|
|
293
|
+
_flatten_span_value(f"{prefix}.{index}", item, flattened)
|
|
294
|
+
return
|
|
295
|
+
if isinstance(value, (str, int, float, bool)):
|
|
296
|
+
flattened[prefix] = value
|
|
297
|
+
return
|
|
298
|
+
flattened[prefix] = json.dumps(value, sort_keys=True, default=str)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _coerce_sequence(values: list[Any]) -> list[Any] | None:
|
|
302
|
+
coerced: list[Any] = []
|
|
303
|
+
for item in values:
|
|
304
|
+
if isinstance(item, (str, int, float, bool)):
|
|
305
|
+
coerced.append(item)
|
|
306
|
+
continue
|
|
307
|
+
if item is None:
|
|
308
|
+
continue
|
|
309
|
+
return None
|
|
310
|
+
return coerced
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _coerce_event_value(value: Any) -> Any:
|
|
314
|
+
if isinstance(value, (str, int, float, bool)):
|
|
315
|
+
return value
|
|
316
|
+
if isinstance(value, list):
|
|
317
|
+
return [str(item) for item in value]
|
|
318
|
+
return str(value)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _normalize_key(key: str) -> str:
|
|
322
|
+
return key.replace(" ", "_").replace("-", "_")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _set_span_attributes(span: Any, attributes: Mapping[str, Any]) -> None:
|
|
326
|
+
for key, value in attributes.items():
|
|
327
|
+
span.set_attribute(key, value)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
__all__ = [
|
|
331
|
+
"AgentDidEventHandler",
|
|
332
|
+
"AgentDidSemanticKernelObservabilityEvent",
|
|
333
|
+
"AgentDidObserver",
|
|
334
|
+
"compose_event_handlers",
|
|
335
|
+
"create_json_logger_event_handler",
|
|
336
|
+
"create_opentelemetry_event_handler",
|
|
337
|
+
"create_opentelemetry_tracer",
|
|
338
|
+
"sanitize_observability_attributes",
|
|
339
|
+
"serialize_observability_event",
|
|
340
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Optional semantic-kernel runtime helpers for the Agent-DID Semantic Kernel package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import inspect
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from functools import wraps
|
|
9
|
+
from typing import Any, cast, get_type_hints
|
|
10
|
+
|
|
11
|
+
from .tools import SemanticKernelTool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load_semantic_kernel_runtime() -> tuple[Any, Any, Any]:
|
|
15
|
+
try:
|
|
16
|
+
functions_module = importlib.import_module("semantic_kernel.functions")
|
|
17
|
+
decorator_module = importlib.import_module("semantic_kernel.functions.kernel_function_decorator")
|
|
18
|
+
method_module = importlib.import_module("semantic_kernel.functions.kernel_function_from_method")
|
|
19
|
+
except ImportError as error: # pragma: no cover - exercised through runtime smoke when extra is installed
|
|
20
|
+
raise RuntimeError(
|
|
21
|
+
"semantic-kernel runtime helpers require installing agent-did-semantic-kernel[runtime]"
|
|
22
|
+
) from error
|
|
23
|
+
|
|
24
|
+
return (
|
|
25
|
+
getattr(functions_module, "KernelPlugin"),
|
|
26
|
+
getattr(decorator_module, "kernel_function"),
|
|
27
|
+
getattr(method_module, "KernelFunctionFromMethod"),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _decorate_tool_handler(
|
|
32
|
+
tool: SemanticKernelTool,
|
|
33
|
+
kernel_function: Callable[..., Any],
|
|
34
|
+
) -> Callable[..., Any]:
|
|
35
|
+
handler = tool.coroutine or tool.func
|
|
36
|
+
if handler is None:
|
|
37
|
+
raise RuntimeError(f"Tool {tool.name} does not expose a callable handler")
|
|
38
|
+
|
|
39
|
+
if inspect.iscoroutinefunction(handler):
|
|
40
|
+
|
|
41
|
+
@wraps(handler)
|
|
42
|
+
async def runtime_handler(**kwargs: Any) -> Any:
|
|
43
|
+
return await handler(**kwargs)
|
|
44
|
+
|
|
45
|
+
else:
|
|
46
|
+
|
|
47
|
+
@wraps(handler)
|
|
48
|
+
def runtime_handler(**kwargs: Any) -> Any:
|
|
49
|
+
return handler(**kwargs)
|
|
50
|
+
|
|
51
|
+
signature = inspect.signature(handler)
|
|
52
|
+
resolved_type_hints = get_type_hints(handler)
|
|
53
|
+
runtime_handler.__signature__ = signature.replace( # type: ignore[attr-defined]
|
|
54
|
+
parameters=[
|
|
55
|
+
parameter.replace(annotation=resolved_type_hints.get(parameter.name, parameter.annotation))
|
|
56
|
+
for parameter in signature.parameters.values()
|
|
57
|
+
],
|
|
58
|
+
return_annotation=resolved_type_hints.get("return", signature.return_annotation),
|
|
59
|
+
)
|
|
60
|
+
decorated_handler = kernel_function(name=tool.name, description=tool.description)(runtime_handler)
|
|
61
|
+
return cast(Callable[..., Any], decorated_handler)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def create_semantic_kernel_plugin(
|
|
65
|
+
tools: list[SemanticKernelTool],
|
|
66
|
+
*,
|
|
67
|
+
plugin_name: str = "agent_did",
|
|
68
|
+
description: str | None = None,
|
|
69
|
+
) -> Any:
|
|
70
|
+
normalized_plugin_name = plugin_name.strip()
|
|
71
|
+
if not normalized_plugin_name:
|
|
72
|
+
raise ValueError("plugin_name must not be empty")
|
|
73
|
+
|
|
74
|
+
kernel_plugin_cls, kernel_function, kernel_function_from_method_cls = _load_semantic_kernel_runtime()
|
|
75
|
+
functions = [
|
|
76
|
+
kernel_function_from_method_cls(
|
|
77
|
+
method=_decorate_tool_handler(tool, kernel_function),
|
|
78
|
+
plugin_name=normalized_plugin_name,
|
|
79
|
+
)
|
|
80
|
+
for tool in tools
|
|
81
|
+
]
|
|
82
|
+
return kernel_plugin_cls(
|
|
83
|
+
name=normalized_plugin_name,
|
|
84
|
+
description=description,
|
|
85
|
+
functions=functions,
|
|
86
|
+
)
|
|
87
|
+
|