Skip to content
Merged
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
4 changes: 4 additions & 0 deletions docs/content/docs/framework/ve-tracing.en.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ volcengine:

The integration code is also nearly identical: construct the platform's exporter, pass it to `OpentelemetryTracer`, and attach the tracer to your agent.

VeADK-managed CozeLoop, APMPlus, and TLS exporters send trace requests with the default headers `veadk-source`, `veadk-version`, `User-Agent`, `X-Client-Request-Id`, and `x-is-encrypted`. APMPlus also sends them with metric requests. Set `MODEL_AGENT_CLIENT_REQ_ID` and `MODEL_AGENT_ENCRYPTED` to configure the last two, respectively. APMPlus uses gRPC, whose `User-Agent` includes both the VeADK and transport identifiers.

Each exporter's `headers` argument can override defaults or add headers. Platform authentication and routing fields take precedence. Custom model request headers apply only to model calls. Host-managed exporters use the host configuration.

## CozeLoop Platform

After connecting a VeADK agent to CozeLoop, you can observe its traces with CozeLoop's Trace feature, or evaluate the agent with its evaluation feature.
Expand Down
4 changes: 4 additions & 0 deletions docs/content/docs/framework/ve-tracing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ volcengine:

接入代码也基本一致:构造对应平台的 Exporter,交给 `OpentelemetryTracer`,再挂载到 Agent 上。

VeADK 创建的 CozeLoop、APMPlus 和 TLS exporter 会在 Trace 上报请求中默认携带以下五个请求头,`veadk-source`、`veadk-version`、`User-Agent`、`X-Client-Request-Id` 和 `x-is-encrypted`。APMPlus 的 Metric 上报也携带这组请求头。通过环境变量 `MODEL_AGENT_CLIENT_REQ_ID` 和 `MODEL_AGENT_ENCRYPTED` 可分别设置后两项。APMPlus 使用 gRPC,`User-Agent` 包含 VeADK 和底层传输标识。

每个 exporter 的 `headers` 参数可以覆盖默认值或添加请求头,平台配置中的鉴权和路由字段优先。Agent 的模型请求自定义头仅用于模型调用。宿主自行创建的 exporter 使用宿主配置。

## CozeLoop 平台

将 VeADK 开发的智能体接入扣子罗盘后,你可以通过扣子罗盘的 Trace 功能观测调用链路,或通过其评测功能对 Agent 进行评测。
Expand Down
45 changes: 44 additions & 1 deletion tests/test_portal_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import time
from types import SimpleNamespace
from unittest.mock import patch

import pytest
from google.adk.agents.run_config import RunConfig, StreamingMode
Expand All @@ -26,6 +27,7 @@
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.util._once import Once

from veadk.consts import default_request_headers
from veadk.tools.skills_tools.skills_tool import SkillsTool
from veadk.tracing.telemetry import portal_metrics, telemetry
from veadk.tracing.telemetry.exporters import (
Expand All @@ -37,6 +39,7 @@
ensure_apmplus_meter_provider,
)
from veadk.tracing.telemetry.portal_metrics import PortalMetricRecorder
from veadk.version import VERSION


class FakePortalMetricRecorder:
Expand Down Expand Up @@ -273,6 +276,43 @@ def test_apmplus_installs_global_provider_when_none_exists(
}


def test_apmplus_trace_and_metric_export_headers(
fresh_global_meter_provider, monkeypatch
):
monkeypatch.delenv("MODEL_AGENT_CLIENT_REQ_ID", raising=False)
monkeypatch.delenv("MODEL_AGENT_ENCRYPTED", raising=False)
reader = InMemoryMetricReader()
monkeypatch.setattr(
apmplus_exporter_module,
"PeriodicExportingMetricReader",
lambda exporter: reader,
)
with (
patch.object(apmplus_exporter_module, "OTLPSpanExporter") as span_transport,
patch.object(apmplus_exporter_module, "OTLPMetricExporter") as metric_transport,
):
exporter = APMPlusExporter(
config=APMPlusExporterConfig(
endpoint="http://localhost", app_key="test", service_name="service"
),
headers={"X-ByteAPM-AppKey": "wrong", "X-Extra": "extra"},
)
exporter.processor.shutdown()
for transport in (span_transport, metric_transport):
assert transport.call_args.kwargs["headers"] == {
"veadk-source": "veadk",
"veadk-version": VERSION,
"x-is-encrypted": "true",
"x-client-request-id": f"veadk/{VERSION}",
"x-extra": "extra",
"x-byteapm-appkey": "test",
}
assert (
"grpc.secondary_user_agent",
f"VeADK/{VERSION}",
) in transport.call_args.kwargs["channel_options"]


def test_apmplus_exporter_only_bootstraps_meter_provider(monkeypatch):
bootstrap_calls = []
monkeypatch.setattr(
Expand All @@ -292,7 +332,10 @@ def test_apmplus_exporter_only_bootstraps_meter_provider(monkeypatch):
assert bootstrap_calls == [
{
"endpoint": "http://localhost:4319",
"headers": {"x-byteapm-appkey": "test-app-key"},
"headers": {
**default_request_headers(),
"x-byteapm-appkey": "test-app-key",
},
"resource_attributes": {"service.name": "test-service"},
}
]
53 changes: 53 additions & 0 deletions tests/test_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch

import pytest
from opentelemetry import context as context_api
Expand Down Expand Up @@ -53,6 +54,7 @@
TLSExporterConfig,
)
from veadk.tracing.telemetry.opentelemetry_tracer import OpentelemetryTracer
from veadk.version import VERSION

APP_NAME = "app"
USER_ID = "testuser"
Expand Down Expand Up @@ -169,6 +171,57 @@ def test_provider_registration_is_atomic_and_provider_scoped(monkeypatch):
second.shutdown()


@pytest.mark.parametrize(
("exporter_cls", "config", "platform_headers"),
[
(
CozeloopExporter,
CozeloopExporterConfig(
endpoint="http://localhost", space_id="space", token="test"
),
{"cozeloop-workspace-id": "space", "authorization": "Bearer test"},
),
(
TLSExporter,
TLSExporterConfig(
endpoint="http://localhost",
region="region",
topic_id="topic",
access_key="ak",
secret_key="sk",
),
{
"x-tls-otel-region": "region",
"x-tls-otel-tracetopic": "topic",
"x-tls-otel-ak": "ak",
"x-tls-otel-sk": "sk",
},
),
],
)
def test_http_export_headers(monkeypatch, exporter_cls, config, platform_headers):
monkeypatch.setenv("MODEL_AGENT_CLIENT_REQ_ID", "agentkit/test")
monkeypatch.setenv("MODEL_AGENT_ENCRYPTED", "false")
overrides = {"VEADK-Source": "custom", "X-Extra": "extra"}
overrides.update({name.upper(): "wrong" for name in platform_headers})
with patch(f"{exporter_cls.__module__}.OTLPSpanExporter") as transport:
exporter = exporter_cls(config=config, headers=overrides)
exporter.processor.shutdown()
headers = {
name.lower(): value
for name, value in transport.call_args.kwargs["headers"].items()
}
assert headers == {
"veadk-source": "custom",
"veadk-version": VERSION,
"user-agent": f"VeADK/{VERSION}",
"x-client-request-id": "agentkit/test",
"x-is-encrypted": "false",
"x-extra": "extra",
**platform_headers,
}


def init_exporters():
cozeloop_exporter = CozeloopExporter(
config=CozeloopExporterConfig(
Expand Down
13 changes: 10 additions & 3 deletions veadk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,22 @@
DEFAULT_MODEL_AGENT_NAME = "doubao-seed-2-1-pro-260628"
DEFAULT_MODEL_AGENT_PROVIDER = "openai"
DEFAULT_MODEL_AGENT_API_BASE = "https://ark.cn-beijing.volces.com/api/v3/"
DEFAULT_MODEL_EXTRA_CONFIG = {
"extra_headers": {


def default_request_headers() -> dict[str, str]:
"""Build the VeADK headers shared by model and telemetry requests."""
return {
"x-is-encrypted": os.getenv("MODEL_AGENT_ENCRYPTED") or "true",
"veadk-source": "veadk",
"veadk-version": VERSION,
"User-Agent": f"VeADK/{VERSION}",
"X-Client-Request-Id": os.getenv("MODEL_AGENT_CLIENT_REQ_ID")
or f"veadk/{VERSION}",
},
}


DEFAULT_MODEL_EXTRA_CONFIG = {
"extra_headers": default_request_headers(),
"extra_body": {
"caching": {
"type": os.getenv("MODEL_AGENT_CACHING") or "enabled",
Expand Down
18 changes: 15 additions & 3 deletions veadk/tracing/telemetry/exporters/apmplus_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@
logger = get_logger(__name__)


def _grpc_header_options(headers: dict) -> dict[str, Any]:
metadata = {key.lower(): value for key, value in headers.items()}
user_agent = metadata.pop("user-agent", None)
options: dict[str, Any] = {"headers": metadata}
if user_agent:
# gRPC constructs the wire User-Agent from channel options.
options["channel_options"] = (("grpc.secondary_user_agent", user_agent),)
return options


def ensure_apmplus_meter_provider(
endpoint: str,
headers: dict,
Expand All @@ -44,8 +54,8 @@ def ensure_apmplus_meter_provider(

exporter = OTLPMetricExporter(
endpoint=endpoint,
headers=headers,
insecure=True,
**_grpc_header_options(headers),
)
metric_reader = PeriodicExportingMetricReader(exporter)
provider = metrics_sdk.MeterProvider(
Expand Down Expand Up @@ -142,15 +152,17 @@ def model_post_init(self, context: Any) -> None:
headers = {
"x-byteapm-appkey": self.config.app_key,
}
self.headers |= headers
self._set_request_headers(headers)

resource_attributes = {
"service.name": self.config.service_name,
}
self.resource_attributes |= resource_attributes

self._exporter = OTLPSpanExporter(
endpoint=self.config.endpoint, insecure=True, headers=self.headers
endpoint=self.config.endpoint,
insecure=True,
**_grpc_header_options(self.headers),
)
self.processor = BatchSpanProcessor(self._exporter)

Expand Down
10 changes: 10 additions & 0 deletions veadk/tracing/telemetry/exporters/base_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.sdk.trace.export import SpanExporter
from pydantic import BaseModel, ConfigDict, Field
from requests.structures import CaseInsensitiveDict

from veadk.consts import default_request_headers


class BaseExporter(BaseModel):
Expand All @@ -38,6 +41,13 @@ class BaseExporter(BaseModel):
_registered_provider: TracerProvider | None = None
processor: SpanProcessor | None = None

def _set_request_headers(self, platform_headers: dict[str, str]) -> None:
"""Merge VeADK defaults, exporter overrides, and required platform headers."""
headers = CaseInsensitiveDict(default_request_headers())
headers.update(self.headers)
headers.update(platform_headers)
self.headers = dict(headers)

def register(self, provider: TracerProvider) -> bool:
"""Register this exporter's processor with a tracer provider once.

Expand Down
2 changes: 1 addition & 1 deletion veadk/tracing/telemetry/exporters/cozeloop_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def model_post_init(self, context: Any) -> None:
"cozeloop-workspace-id": self.config.space_id,
"authorization": f"Bearer {self.config.token}",
}
self.headers |= headers
self._set_request_headers(headers)

self._exporter = OTLPSpanExporter(
endpoint=self.config.endpoint,
Expand Down
4 changes: 2 additions & 2 deletions veadk/tracing/telemetry/exporters/tls_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,11 @@ def model_post_init(self, context: Any) -> None:
"x-tls-otel-sk": self.config.secret_key,
"x-tls-otel-region": self.config.region,
}
self.headers |= headers
self._set_request_headers(headers)

self._exporter = OTLPSpanExporter(
endpoint=self.config.endpoint,
headers=headers,
headers=self.headers,
timeout=10,
)

Expand Down
Loading