> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coze.cn/llms.txt
> Use this file to discover all available pages before exploring further.

本文介绍如何使用 OpenTelemetry 协议将 [AutoGen](https://microsoft.github.io/autogen/stable/) 的 Trace 数据自动上报到扣子罗盘。
# 功能介绍 {#feature_intro}
AutoGen 是微软推出的一个用于构建 LLM 应用的框架，支持多个 Agent 之间的对话与协作。结合 OpenInference SDK 和 OpenTelemetry SDK，你可以全面追踪 AutoGen 应用的运行状态，包括 Agent 交互、工具调用等。Trace 数据将以标准 OpenTelemetry Trace 格式上报至扣子罗盘平台，实现完整的可观测性监控。
# 准备工作 {#preparation}
你需要先安装以下 Python 库：

* **autogen**：AutoGen 核心库。
* **opentelemetry-sdk**：OpenTelemetry Python SDK，用于向扣子罗盘上报符合 OpenTelemetry 标准的 Trace 数据。
   :::tip 说明
   OpenTelemetry Python SDK 要求 Python 必须是 3.9.0 或更高版本。
   :::
* **opentelemetry-exporter-otlp**：OpenTelemetry Python SDK 的 OTLP 导出器，用于将 Trace 数据导出到支持 OTLP 协议的后端服务。
* **openinference-instrumentation-autogen**：针对 AutoGen 的 OpenInference SDK，用于追踪 AutoGen。
* **openinference-instrumentation-openai**：针对 OpenAI 的 OpenInference SDK，用于追踪 AutoGen 中调用的 OpenAI 客户端请求。

```Python
pip install autogen
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp
pip install openinference-instrumentation-autogen
pip install openinference-instrumentation-openai
```

# 操作步骤 {#fe212827}
## 步骤一：配置环境变量 {#step1}
在上报 Trace 数据前，你需要正确配置环境变量，以确保 Trace 数据能够正确发送到指定的扣子罗盘空间中。环境变量配置格式及说明如下：
```Python
OTEL_EXPORTER_OTLP_HEADERS=cozeloop-workspace-id={扣子罗盘工作空间ID},Authorization=Bearer {个人访问令牌或服务访问令牌}
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.coze.cn/v1/loop/opentelemetry/v1/traces
OPENAI_BASE_URL=***
OPENAI_API_KEY=***
OPENAI_MODEL_NAME=***
```

<!-- @cols-width: 322,595 -->
| | | \
|**环境变量** |**说明** |
|---|---|
| | | \
|OTEL_EXPORTER_OTLP_HEADERS |OpenTelemetry SDK 数据上报的认证头信息，包括以下参数： |\
| | |\
| |* **cozeloop-workspace-id**：扣子罗盘的工作空间 ID。获取方法参考 [获取扣子罗盘空间 ID](/cozeloop/get_workspace_id_and_token)。 |\
| |* **Authorization**：扣子罗盘的个人访问令牌或服务访问令牌，获取方法参考 [配置个人访问令牌](/cozeloop/authentication-for-sdk#05d27a86) 或 [配置服务访问令牌](/cozeloop/authentication-for-sdk#83f924a1)。 |
| | | \
|OTEL_EXPORTER_OTLP_TRACES_ENDPOINT |OpenTelemetry SDK 的数据上报地址，固定为 `https://api.coze.cn/v1/loop/opentelemetry/v1/traces`。 |
| | | \
|OPENAI_BASE_URL |配置 OpenAI 模型服务的 Base URL。推荐使用火山方舟模型服务：`https://ark.cn-beijing.volces.com/api/v3`。 |
| | | \
|OPENAI_API_KEY |配置 OpenAI 模型服务的 API Key。如果使用火山方舟模型，请参考 [获取 API Key](https://www.volcengine.com/docs/82379/1361424)。 |
| | | \
|OPENAI_MODEL_NAME |模型名称，例如 `openai/doubao-1-5-pro-256k-250115`。使用模型提供方作为前缀，例如 `openai/`。 |

## 步骤二：上报 Trace {#step2}
你可以结合使用 OpenInference Python SDK 与 OpenTelemetry Python SDK，将 Agent 的 Trace 数据上报至扣子罗盘。
下方的示例代码演示如何通过 OpenInference Python SDK 追踪 Agent 的运行状态并生成符合 OpenTelemetry 标准的 Trace 数据，然后使用 OpenTelemetry Python SDK 将 Trace 数据上报到扣子罗盘。
```Python
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

# OpenAI env
os.environ['OPENAI_BASE_URL'] = 'https://ark.cn-beijing.volces.com/api/v3' # use ark model url by default, from https://www.volcengine.com/docs/82379/1361424
os.environ['OPENAI_API_KEY'] = 'xxx'  # your api key
os.environ['OPENAI_MODEL_NAME'] = 'xxx' # your model name, like doubao-1-5-vision-pro-32k-250115

# OTEL env
os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = "https://api.coze.cn/v1/loop/opentelemetry/v1/traces" # cozeloop otel endpoint
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = "cozeloop-workspace-id=xxx,Authorization=Bearer pat_xxx" # set your 'spaceID' and 'pat or sat token'

# OTEL configuration
otlp_exporter = OTLPSpanExporter(
    timeout=10,
)
trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(otlp_exporter)
)
tracer = trace.get_tracer(__name__)

# OpenInference auto-detection for AutoGen
try:
    from openinference.instrumentation.autogen import AutogenInstrumentor
    from openinference.instrumentation.openai import OpenAIInstrumentor
    AutogenInstrumentor().instrument()
    OpenAIInstrumentor().instrument()
    print("✅ OpenInference AutoGen instrumentation enabled")
except ImportError as e:
    print(f"⚠️  OpenInference AutoGen instrumentation import failed: {e}")
    print("Program will continue running, but without OTEL tracing functionality")

from autogen import AssistantAgent, UserProxyAgent

def main():
    # Define LLM configuration
    llm_config = {
        "config_list": [
            {
                "model": os.environ.get('OPENAI_MODEL_NAME'),
                "api_key": os.environ.get("OPENAI_API_KEY"),
            }
        ],
        "temperature": 0,
    }

    # Create agents
    assistant = AssistantAgent(
        name="assistant",
        llm_config=llm_config,
    )

    user_proxy = UserProxyAgent(
        name="user_proxy",
        human_input_mode="NEVER",
        max_consecutive_auto_reply=1,
        is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
        code_execution_config=False,
    )

    # Set custom span, name is root_span
    with tracer.start_as_current_span("root_span") as span:
        span.set_attribute("cozeloop.span_type", "custom")

        # Start the conversation
        user_proxy.initiate_chat(
            assistant,
            message="Explain the concept of 'Retrieval-Augmented Generation' in 2 sentences.",
        )

if __name__ == "__main__":
    main()
```

### 自定义 Span {#bb94f3b4}
OpenInference Python SDK 会自动生成符合 [OpenInference 标准](https://arize-ai.github.io/openinference/spec/)的 Span。同时，你也可以使用 OpenTelemetry Python SDK 自定义 Span。
示例代码演示了如何使用 OpenTelemetry Python SDK 自定义一个 Span（即示例代码中的 `root_span`）。OpenInference Python SDK 自动生成的 Span 会与你自定义的 Span 自动关联，并显示在同一条 Trace 中。自定义 Span 时，其 `attribute` 和 `event` 需符合 [OpenTelemetry 字段映射](/cozeloop/opentelemetry_field_mapping) 中的规范。参考 [步骤三：查看 Trace](/cozeloop/ccepfu6a#73a00648) 查看示例代码所生成的 Trace 数据。
```Python
    # Set custom span, name is root_span
    with tracer.start_as_current_span("root_span") as span:
        span.set_attribute("cozeloop.span_type", "custom")

        # Start the conversation
        user_proxy.initiate_chat(
            assistant,
            message="Explain the concept of 'Retrieval-Augmented Generation' in 2 sentences.",
        )
```

## 步骤三：查看 Trace {#73a00648}
上报 Trace 数据后，你可以在[扣子罗盘](https://loop.coze.cn/)的 **Trace** 页面，找到并查看 Agent 上报的 Trace 数据。
<div style="text-align: center"><img src="https://p9-arcosite.byteimg.com/tos-cn-i-goo7wpa0wc/952eaad39ff44e039a127a1aa74cd050~tplv-goo7wpa0wc-image.image" width="3006px" height="1766px" /></div>

# 示例地址 {#b40e14c1}
要获取上报 Trace 数据的完整示例代码，参考 [autogen](https://github.com/coze-dev/cozeloop-examples/tree/main/python/integration/framework/autogen)。
