以编程方式使用文档

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

安装

使用您偏好的包管理器安装所需包:

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

设置

1. 配置环境变量

设置您的 API 密钥 和项目名称:

2. 配置 OpenTelemetry 集成

在 Semantic Kernel 应用程序中,配置 LangSmith OpenTelemetry 集成以及 OpenAI 检测器:

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()

3. 创建并运行 Semantic Kernel 应用程序

配置完成后,Semantic Kernel 应用程序将自动向 LangSmith 发送追踪:

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())

高级用法

自定义元数据和标签

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

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

与其他检测器结合使用

您可以将 Semantic Kernel 追踪与其他 OpenTelemetry 检测器结合使用:

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

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

资源