你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 OpenAI SDK 跟踪 AI 应用程序

跟踪行为可以捕获每个执行步骤的详细遥测数据,从而帮助深入了解应用程序的执行。 此类功能通过识别不准确的工具调用、误导性提示、高延迟、低质量评估分数等问题来帮助诊断问题并提高性能。

本文介绍如何在 Azure AI Foundry 中使用 OpenAI SDK 和 OpenTelemetry 实现 AI 应用程序的跟踪。

先决条件

需要满足以下条件才能完成本教程:

  • 已创建 Azure AI Foundry 项目。

  • 使用 OpenAI SDK 调用 Azure AI Foundry 中托管的模型的 AI 应用程序。

在项目中启用跟踪

Azure AI Foundry 使用 OpenTelemetry 将跟踪存储在 Azure Application Insight 资源中。 默认情况下,新的 Azure AI Foundry 资源不会预配这些资源。 可以将项目连接到现有的 Azure Application Insights 资源,也可以从项目中创建新项目。 每个 Azure AI Foundry 资源都执行此类配置一次。

以下步骤演示如何配置资源:

  1. 转到 Azure AI Foundry 门户 并导航到项目。

  2. 在侧导航栏上,选择“ 跟踪”。

  3. 如果 Azure Application Insights 资源未与 Azure AI Foundry 资源关联,请关联一个资源。

    显示如何将 Azure Application Insights 配置为 Azure AI Foundry 资源的屏幕截图。

  4. 若要重复使用现有的 Azure Application Insights,请使用下拉列表 Application Insights 资源名称 查找资源并选择 “连接”。

    小窍门

    若要连接到现有的 Azure Application Insights,至少需要对 Azure AI Foundry 资源(或中心)的参与者访问权限。

  5. 若要连接到新的 Azure Application Insights 资源,请选择“ 新建”选项。

    1. 使用配置向导配置新资源的名称。

    2. 默认情况下,新资源是在创建 Azure AI Foundry 资源的同一资源组中创建的。 使用 “高级设置” 选项配置其他资源组或订阅。

      小窍门

      若要创建新的 Azure Application Insight 资源,还需要为所选资源组(或默认资源组)提供参与者角色。

    3. 选择“ 创建 ”以创建资源并将其连接到 Azure AI Foundry 资源。

  6. 配置连接后,即可在资源中的任何项目中使用跟踪。

  7. 转到项目的登陆页并复制项目的终结点 URI。 本教程稍后需要用到它。

    显示如何复制项目终结点 URI 的屏幕截图。

    重要

    要使用项目的端点,需要在应用程序中配置 Microsoft Entra ID。 如果未配置 Entra ID,请使用本教程的步骤 3 所示的 Azure Application Insights 连接字符串。

检测 OpenAI SDK

使用 OpenAI SDK 进行开发时,可以检测代码,以便将跟踪发送到 Azure AI Foundry。 按照以下步骤检测代码:

  1. 在您的环境中安装azure-ai-projectsazure-monitor-opentelemetryopentelemetry-instrumentation-openai-v2。 下面的示例使用 pip

    pip install azure-ai-projects azure-monitor-opentelemetry opentelemetry-instrumentation-openai-v2
    
  2. 使用 OpenAIInstrumentor() 检测 OpenAI SDK:

    from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
    
    OpenAIInstrumentor().instrument()
    
  3. 获取与项目关联的 Azure Application Insights 资源的连接字符串:

    from azure.ai.projects import AIProjectClient
    from azure.identity import DefaultAzureCredential
    
    project_client = AIProjectClient.from_connection_string(
        credential=DefaultAzureCredential(),
        endpoint="https://<your-resource>.services.ai.azure.com/api/projects/<your-project>",
    )
    
    connection_string = project_client.telemetry.get_connection_string()
    

    小窍门

    Azure Application Insights 的连接字符串如下所示 InstrumentationKey=aaaa0a0a-bb1b-cc2c-dd3d-eeeee4e4e4e;...。 还可以从 Azure AI Foundry 门户中的 “跟踪 ”部分访问项目中使用的连接字符串。 在顶部导航栏中,选择“ 管理数据源 ”并复制 连接字符串。 在环境变量中配置连接字符串。

    显示如何将连接字符串从项目复制到基础 Azure Application Insights 资源的屏幕截图。

  4. 配置 OpenTelemetry 以将跟踪发送到 Azure Application Insights:

    from azure.monitor.opentelemetry import configure_azure_monitor
    
    configure_azure_monitor(connection_string=connection_string)
    
  5. 默认情况下,OpenTelemetry 不会捕获输入和输出。 使用环境变量 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true 捕获它们。 确保在运行代码的环境级别配置此环境变量。

  6. 像往常一样使用 OpenAI SDK:

    client = project_client.get_azure_openai_client()
    
    response = client.chat.completions.create(
        model="deepseek-v3-0324",
        messages=[
            {"role": "user", "content": "Write a short poem on open telemetry."},
        ],
    )
    
  7. 如果返回到 Azure AI Foundry 门户,你应会看到显示的跟踪:

    一个屏幕截图展示了简单聊天完成请求在追踪中的显示方式。

  8. 在开发复杂应用程序时,捕获将业务逻辑与模型混合的代码部分可能很有用。 OpenTelemetry 使用“跨度”的概念来捕获您感兴趣的部分。 若要开始生成自己的跨度,请获取当前 追踪器 对象的实例。

    from opentelemetry import trace
    
    tracer = trace.get_tracer(__name__)
    
  9. 然后,在方法中使用修饰器来捕获你感兴趣的代码中的特定场景。 此类修饰器自动生成跨度。 以下代码示例通过对声明列表进行迭代来检测一种称为 assess_claims_with_context 的方法,并使用 LLM 验证上下文是否支持声明。 此方法中进行的所有调用都在同一个跨度内捕获:

    def build_prompt_with_context(claim: str, context: str) -> str:
        return [{'role': 'system', 'content': "I will ask you to assess whether a particular scientific claim, based on evidence provided. Output only the text 'True' if the claim is true, 'False' if the claim is false, or 'NEE' if there's not enough evidence."},
                {'role': 'user', 'content': f"""
                    The evidence is the following: {context}
    
                    Assess the following claim on the basis of the evidence. Output only the text 'True' if the claim is true, 'False' if the claim is false, or 'NEE' if there's not enough evidence. Do not output any other text.
    
                    Claim:
                    {claim}
    
                    Assessment:
                """}]
    
    @tracer.start_as_current_span("assess_claims_with_context")
    def assess_claims_with_context(claims, contexts):
        responses = []
        for claim, context in zip(claims, contexts):
            response = client.chat.completions.create(
                model="gpt-4.5-preview",
                messages=build_prompt_with_context(claim=claim, context=context),
            )
            responses.append(response.choices[0].message.content.strip('., '))
    
        return responses
    
  10. 轨迹如下所示:

    显示使用修饰器的方法如何在跟踪中显示的屏幕截图。

  11. 可能还需要将额外信息添加到当前跨度。 OpenTelemetry 为此使用特性的概念。 使用trace对象来访问这些并包含额外信息。 assess_claims_with_context查看该方法是如何被修改以包含一个属性的:

    @tracer.start_as_current_span("assess_claims_with_context")
    def assess_claims_with_context(claims, contexts):
        responses = []
        current_span = trace.get_current_span()
    
        current_span.set_attribute("operation.claims_count", len(claims))
    
        for claim, context in zip(claims, contexts):
            response = client.chat.completions.create(
                model="gpt-4.5-preview",
                messages=build_prompt_with_context(claim=claim, context=context),
            )
            responses.append(response.choices[0].message.content.strip('., '))
    
        return responses
    

跟踪到控制台

此外,跟踪应用程序并将跟踪发送到本地执行控制台可能很有用。 使用自动化 CI/CD 管道在应用程序中运行单元测试或集成测试时,此方法可能会带来好处。 可以将跟踪信息发送到控制台,并由 CI/CD 工具捕获以进行进一步分析。

按如下所示配置跟踪:

  1. 像往常一样配置 OpenAI SDK:

    from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
    
    OpenAIInstrumentor().instrument()
    
  2. 配置 OpenTelemetry 以将跟踪发送到控制台:

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter
    
    span_exporter = ConsoleSpanExporter()
    tracer_provider = TracerProvider()
    tracer_provider.add_span_processor(SimpleSpanProcessor(span_exporter))
    trace.set_tracer_provider(tracer_provider)
    
  3. 像往常一样使用 OpenAI SDK:

    response = client.chat.completions.create(
        model="deepseek-v3-0324",
        messages=[
            {"role": "user", "content": "Write a short poem on open telemetry."},
        ],
    )
    
    {
        "name": "chat deepseek-v3-0324",
        "context": {
            "trace_id": "0xaaaa0a0abb1bcc2cdd3d",
            "span_id": "0xaaaa0a0abb1bcc2cdd3d",
            "trace_state": "[]"
        },
        "kind": "SpanKind.CLIENT",
        "parent_id": null,
        "start_time": "2025-06-13T00:02:04.271337Z",
        "end_time": "2025-06-13T00:02:06.537220Z",
        "status": {
            "status_code": "UNSET"
        },
        "attributes": {
            "gen_ai.operation.name": "chat",
            "gen_ai.system": "openai",
            "gen_ai.request.model": "deepseek-v3-0324",
            "server.address": "my-project.services.ai.azure.com",
            "gen_ai.response.model": "DeepSeek-V3-0324",
            "gen_ai.response.finish_reasons": [
                "stop"
            ],
            "gen_ai.response.id": "aaaa0a0abb1bcc2cdd3d",
            "gen_ai.usage.input_tokens": 14,
            "gen_ai.usage.output_tokens": 91
        },
        "events": [],
        "links": [],
        "resource": {
            "attributes": {
                "telemetry.sdk.language": "python",
                "telemetry.sdk.name": "opentelemetry",
                "telemetry.sdk.version": "1.31.1",
                "service.name": "unknown_service"
            },
            "schema_url": ""
        }
    }
    

后续步骤