Skip to content
LangSmith 文档版本 跟随上游 源快照 484b920c 更新于 2026-10-18

追踪 Semantic Kernel 应用

LangSmith 可以使用 Semantic Kernel 内置的 OpenTelemetry 支持捕获其生成的追踪。本指南展示如何自动捕获 Semantic Kernel 应用的追踪,并将其发送到 LangSmith 进行监控和分析。

安装

使用你偏好的包管理器安装所需依赖包:

bash
pip install langsmith semantic-kernel opentelemetry-instrumentation-openai
bash
uv add langsmith semantic-kernel opentelemetry-instrumentation-openai

设置

1. 配置环境变量

设置你的 API key 和项目名称:

bash
export LANGSMITH_API_KEY=<your_langsmith_api_key>
export LANGSMITH_PROJECT=<your_project_name>
export OPENAI_API_KEY=<your_openai_api_key>

2. 配置 OpenTelemetry 集成

在你的 Semantic Kernel 应用中,配置 LangSmith OpenTelemetry 集成以及 OpenAI instrumentor:

python
from langsmith.integrations.otel import configure
from opentelemetry.instrumentation.openai import OpenAIInstrumentor

# Configure LangSmith tracing
configure(project_name="semantic-kernel-demo")

# Instrument OpenAI calls
OpenAIInstrumentor().instrument()

NOTE

你无需设置任何 OpenTelemetry 环境变量,也无需手动配置 exporter——configure() 会自动处理一切。

3. 创建并运行你的 Semantic Kernel 应用

配置完成后,你的 Semantic Kernel 应用会自动将追踪发送到 LangSmith:

python
import asyncio
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.prompt_template import InputVariable, PromptTemplateConfig
from langsmith.integrations.otel import configure
from opentelemetry.instrumentation.openai import OpenAIInstrumentor

# Configure LangSmith tracing
configure(project_name="semantic-kernel-assistant")

# Instrument OpenAI calls
OpenAIInstrumentor().instrument()

# Configure Semantic Kernel
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Create a prompt template
code_analysis_prompt = """
Analyze the following code and provide insights:

Code: {{$code}}

Please provide:
1. A brief summary of what the code does
2. Any potential improvements
3. Code quality assessment
"""

prompt_template_config = PromptTemplateConfig(
    template=code_analysis_prompt,
    name="code_analyzer",
    template_format="semantic-kernel",
    input_variables=[
        InputVariable(name="code", description="The code to analyze", is_required=True),
    ],
)

# Add the function to the kernel
code_analyzer = kernel.add_function(
    function_name="analyzeCode",
    plugin_name="codeAnalysisPlugin",
    prompt_template_config=prompt_template_config,
)

async def main():
    sample_code = """
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
    """

    result = await kernel.invoke(code_analyzer, code=sample_code)
    print("Code Analysis:")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

高级用法

自定义元数据和标签

你可以通过设置 span 属性为追踪添加自定义元数据:

python
from opentelemetry import trace

tracer = trace.get_tracer(__name__)

async def analyze_with_metadata(code: str):
    with tracer.start_as_current_span("semantic_kernel_workflow") as span:
        span.set_attribute("langsmith.metadata.workflow_type", "code_analysis")
        span.set_attribute("langsmith.metadata.user_id", "developer_123")
        span.set_attribute("langsmith.span.tags", "semantic-kernel,code-analysis")

        result = await kernel.invoke(code_analyzer, code=code)
        return result

与其他 instrumentor 组合使用

你可以将 Semantic Kernel 追踪与其他 OpenTelemetry instrumentor 组合使用:

python
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

# Initialize multiple instrumentors
OpenAIInstrumentor().instrument()
HTTPXClientInstrumentor().instrument()

资源


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。