Skip to content
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ var tracer = TraceAI.Register(opts =>
| [`traceAI-claude-agent-sdk`](https://pypi.org/project/traceAI-claude-agent-sdk/) | Claude Agent SDK | [![PyPI](https://img.shields.io/pypi/v/traceAI-claude-agent-sdk)](https://pypi.org/project/traceAI-claude-agent-sdk/) |
| [`traceAI-strands`](https://pypi.org/project/traceAI-strands/) | AWS Strands Agents | [![PyPI](https://img.shields.io/pypi/v/traceAI-strands)](https://pypi.org/project/traceAI-strands/) |
| [`traceAI-beeai`](https://pypi.org/project/traceAI-beeai/) | IBM BeeAI | [![PyPI](https://img.shields.io/pypi/v/traceAI-beeai)](https://pypi.org/project/traceAI-beeai/) |
| [`traceai-semantic-kernel`](https://pypi.org/project/traceai-semantic-kernel/) | Microsoft Semantic Kernel | [![PyPI](https://img.shields.io/pypi/v/traceai-semantic-kernel)](https://pypi.org/project/traceai-semantic-kernel/) |

#### Tools and Libraries

Expand Down
5 changes: 5 additions & 0 deletions python/frameworks/semantic-kernel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## 0.1.0

- Initial release of traceai-semantic-kernel
28 changes: 28 additions & 0 deletions python/frameworks/semantic-kernel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# TraceAI Instrumentation for Microsoft Semantic Kernel

This package provides OpenTelemetry instrumentation for the [Semantic Kernel](https://github.com/microsoft/semantic-kernel) framework in Python.

## Installation

```bash
pip install traceai-semantic-kernel
```

## Usage

```python
import asyncio
from semantic_kernel import Kernel
from traceai_semantic_kernel import SemanticKernelInstrumentor

# Instrument Semantic Kernel
SemanticKernelInstrumentor().instrument()

async def main():
kernel = Kernel()
# Add plugins and services to the kernel...
# result = await kernel.invoke(function, inputs...)

if __name__ == "__main__":
asyncio.run(main())
```
12 changes: 12 additions & 0 deletions python/frameworks/semantic-kernel/examples/basic_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import asyncio
from semantic_kernel import Kernel
from traceai_semantic_kernel import SemanticKernelInstrumentor

SemanticKernelInstrumentor().instrument()

async def main():
kernel = Kernel()
print("Semantic Kernel initialized and instrumented!")

if __name__ == "__main__":
asyncio.run(main())
4,108 changes: 4,108 additions & 0 deletions python/frameworks/semantic-kernel/poetry.lock

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions python/frameworks/semantic-kernel/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[tool.poetry]
name = "traceai-semantic-kernel"
version = "0.1.0"
description = "TraceAI Instrumentation for Microsoft Semantic Kernel"
authors = ["Future AGI <hello@futureagi.com>"]
readme = "README.md"
packages = [{include = "traceai_semantic_kernel"}]

[tool.poetry.dependencies]
python = ">=3.10,<3.14"
fi-instrumentation-otel = "^0.1.0"
semantic-kernel = "^1.5.0"
wrapt = "^1.16.0"

[tool.poetry.group.dev.dependencies]
pytest = "^8.0.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
1 change: 1 addition & 0 deletions python/frameworks/semantic-kernel/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#
5 changes: 5 additions & 0 deletions python/frameworks/semantic-kernel/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import pytest

@pytest.fixture
def mock_kernel():
pass
10 changes: 10 additions & 0 deletions python/frameworks/semantic-kernel/tests/test_instrumentor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import pytest
from traceai_semantic_kernel import SemanticKernelInstrumentor
from semantic_kernel.kernel import Kernel

def test_instrumentor():
instrumentor = SemanticKernelInstrumentor()
instrumentor.instrument()
assert instrumentor._original_kernel_invoke is not None
instrumentor.uninstrument()
assert instrumentor._original_kernel_invoke is None
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import logging
from importlib import import_module
from typing import Any, Collection

from fi_instrumentation import FITracer, TraceConfig
from opentelemetry import trace as trace_api
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
from traceai_semantic_kernel._wrappers import (
_KernelInvokeWrapper,
_FunctionInvokeWrapper,
)
from traceai_semantic_kernel.version import __version__
from wrapt import wrap_function_wrapper

_instruments = ("semantic-kernel >= 1.5.0",)

logger = logging.getLogger(__name__)


class SemanticKernelInstrumentor(BaseInstrumentor): # type: ignore
__slots__ = (
"_original_kernel_invoke",
"_original_function_invoke",
"_tracer",
)

def instrumentation_dependencies(self) -> Collection[str]:
return _instruments

def _instrument(self, **kwargs: Any) -> None:
if not (tracer_provider := kwargs.get("tracer_provider")):
tracer_provider = trace_api.get_tracer_provider()
if not (config := kwargs.get("config")):
config = TraceConfig()
else:
assert isinstance(config, TraceConfig)
self._tracer = FITracer(
trace_api.get_tracer(__name__, __version__, tracer_provider),
config=config,
)

try:
# Wrap Kernel.invoke
kernel_invoke_wrapper = _KernelInvokeWrapper(tracer=self._tracer)
self._original_kernel_invoke = getattr(
import_module("semantic_kernel.kernel"), "Kernel.invoke", None
)
wrap_function_wrapper(
module="semantic_kernel.kernel",
name="Kernel.invoke",
wrapper=kernel_invoke_wrapper,
)
except Exception as e:
logger.debug(f"Failed to instrument Kernel.invoke: {e}")
self._original_kernel_invoke = None

try:
# Wrap KernelFunction.invoke
function_invoke_wrapper = _FunctionInvokeWrapper(tracer=self._tracer)
self._original_function_invoke = getattr(
import_module("semantic_kernel.functions.kernel_function"), "KernelFunction.invoke", None
)
wrap_function_wrapper(
module="semantic_kernel.functions.kernel_function",
name="KernelFunction.invoke",
wrapper=function_invoke_wrapper,
)
except Exception as e:
logger.debug(f"Failed to instrument KernelFunction.invoke: {e}")
self._original_function_invoke = None

def _uninstrument(self, **kwargs: Any) -> None:
if self._original_kernel_invoke is not None:
kernel_module = import_module("semantic_kernel.kernel")
kernel_module.Kernel.invoke = self._original_kernel_invoke
self._original_kernel_invoke = None

if self._original_function_invoke is not None:
function_module = import_module("semantic_kernel.functions.kernel_function")
function_module.KernelFunction.invoke = self._original_function_invoke
self._original_function_invoke = None
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import logging
from typing import Any, Callable

from fi_instrumentation import FITracer
from fi_instrumentation.fi_types import SpanAttributes
from opentelemetry.trace import SpanKind
from opentelemetry.trace.status import Status, StatusCode

logger = logging.getLogger(__name__)


class _KernelInvokeWrapper:
def __init__(self, tracer: FITracer):
self._tracer = tracer

async def __call__(
self,
wrapped: Callable[..., Any],
instance: Any,
args: Any,
kwargs: Any,
) -> Any:
span_name = "Kernel.invoke"
with self._tracer.start_as_current_span(
name=span_name,
kind=SpanKind.INTERNAL,
) as span:
try:
span.set_attribute(SpanAttributes.FI_AGENT_NAME, "SemanticKernel")
result = await wrapped(*args, **kwargs)
if result:
span.set_attribute(SpanAttributes.FI_AGENT_OUTPUT, str(result))
return result
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
raise


class _FunctionInvokeWrapper:
def __init__(self, tracer: FITracer):
self._tracer = tracer

async def __call__(
self,
wrapped: Callable[..., Any],
instance: Any,
args: Any,
kwargs: Any,
) -> Any:
span_name = "KernelFunction.invoke"
with self._tracer.start_as_current_span(
name=span_name,
kind=SpanKind.INTERNAL,
) as span:
try:
if hasattr(instance, "name"):
span.set_attribute(SpanAttributes.FI_TOOL_NAME, instance.name)
result = await wrapped(*args, **kwargs)
if result:
span.set_attribute(SpanAttributes.FI_TOOL_OUTPUT, str(result))
return result
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
raise
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "0.1.0"