Assist high-code instrumentation by using a coding agent and a dedicated skill

Updated at:

If you build your AI Agent on a fully custom framework, Alibaba Cloud agents may not be able to fully collect high-quality execution traces of the AI Agent. In this case, we recommend that you connect the AI Agent by using manual instrumentation. Manual instrumentation requires additional development effort. To reduce this effort, you can follow this topic to use your coding agent to assist with instrumentation.

Procedure

Step 1: Install and configure Alibaba Cloud CLI

If Alibaba Cloud CLI is not installed, see Install Alibaba Cloud CLI.

# Make sure that the CLI version is 3.3.15 or later
aliyun version

# Verify that the cms2 plug-in is available
aliyun cms2 --help

If the cms2 command is unavailable, run the following command:

aliyun plugin update

Configure access credentials:

aliyun configure

Note

We recommend that you use a RAM user and grant it the required permissions on AgentLoop (cms2 API), ARMS, and Container Service. In Kubernetes scenarios, ACK managed clusters are usually authorized by using an ARMS Addon Token without an AccessKey pair. ACK dedicated clusters or ACS clusters may require you to configure an AccessKey pair by using ack-onepilot. For more information, see the authorization section in Install the Java agent in ACK and ACS clusters by using the ack-onepilot component.

Step 2: Install the alibabacloud-agentloop-management Skill

  1. Open the Skill marketplace page: alibabacloud-agentloop-management.

  2. Follow the instructions on the page to install the Skill in Cursor, Claude Code, or QoderWork.

  3. After the installation is complete, restart the AI assistant or confirm in a conversation that the Skill is loaded.

Step 3: Start instrumentation by using natural language

Basic scenario

The following custom AI Agent program written in Python is used as an example:

"""A small ReAct-style agent with manual JSON-line instrumentation."""

from __future__ import annotations

import argparse
import ast
import json
import os
import sys
import time
import uuid
from datetime import datetime, timezone
from typing import Any

from openai import OpenAI


DEFAULT_BASE_URL = (
    "https://dashscope.aliyuncs.com/compatible-mode/v1"
)
DEFAULT_MODEL = "qwen3.7-plus"

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Calculate a basic arithmetic expression with +, -, *, /, and parentheses.",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "Example: (12 + 3) / 5"}
                },
                "required": ["expression"],
                "additionalProperties": False,
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_utc_time",
            "description": "Get the current UTC date and time.",
            "parameters": {
                "type": "object",
                "properties": {},
                "additionalProperties": False,
            },
        },
    },
]

SYSTEM_PROMPT = (
    "You are a helpful assistant. Use tools when they help answer the question. "
    "Use calculate for arithmetic and get_utc_time for the current time. "
    "After observing tool results, give a concise final answer. "
    "Do not invent tool results."
)


def emit(trace_id: str, event: str, **fields: Any) -> None:
    """Manual instrumentation; never include credentials or request headers."""
    record = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "trace_id": trace_id,
        "event": event,
        **fields,
    }
    print(json.dumps(record, ensure_ascii=False), file=sys.stderr, flush=True)


def calculate(expression: str) -> float | int:
    """Evaluate arithmetic without eval(), imports, names, or function calls."""
    if len(expression) > 200:
        raise ValueError("Expression is too long")
    tree = ast.parse(expression, mode="eval")

    def visit(node: ast.AST, depth: int = 0) -> float | int:
        if depth > 20:
            raise ValueError("Expression is too deeply nested")
        if isinstance(node, ast.Expression):
            return visit(node.body, depth + 1)
        if isinstance(node, ast.Constant) and type(node.value) in (int, float):
            if abs(node.value) > 1e12:
                raise ValueError("Number is too large")
            return node.value
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
            value = visit(node.operand, depth + 1)
            return value if isinstance(node.op, ast.UAdd) else -value
        if isinstance(node, ast.BinOp) and isinstance(
            node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)
        ):
            left = visit(node.left, depth + 1)
            right = visit(node.right, depth + 1)
            if isinstance(node.op, ast.Add):
                result = left + right
            elif isinstance(node.op, ast.Sub):
                result = left - right
            elif isinstance(node.op, ast.Mult):
                result = left * right
            else:
                result = left / right
            if abs(result) > 1e15:
                raise ValueError("Result is too large")
            return result
        raise ValueError("Only basic arithmetic is supported")

    return visit(tree)


def run_tool(name: str, raw_arguments: str) -> str:
    try:
        arguments = json.loads(raw_arguments)
        if not isinstance(arguments, dict):
            raise ValueError("Arguments must be a JSON object")
        if name == "calculate":
            if set(arguments) != {"expression"} or not isinstance(
                arguments["expression"], str
            ):
                raise ValueError("calculate requires a string expression")
            result: Any = calculate(arguments["expression"])
        elif name == "get_utc_time":
            if arguments:
                raise ValueError("get_utc_time takes no arguments")
            result = datetime.now(timezone.utc).isoformat()
        else:
            raise ValueError(f"Unknown tool: {name}")
        return json.dumps({"result": result}, ensure_ascii=False)
    except (ValueError, SyntaxError, ZeroDivisionError, OverflowError) as exc:
        return json.dumps({"error": str(exc)}, ensure_ascii=False)


def run_agent(client: OpenAI, question: str, model: str, max_steps: int = 6) -> str:
    trace_id = uuid.uuid4().hex
    messages: list[dict[str, Any]] = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": question},
    ]
    emit(trace_id, "agent.start", model=model, max_steps=max_steps)

    for step in range(1, max_steps + 1):
        started = time.perf_counter()
        emit(trace_id, "llm.start", step=step, message_count=len(messages))
        try:
            completion = client.chat.completions.create(
                model=model,
                messages=messages,
                tools=TOOLS,
                tool_choice="auto",
            )
        except Exception as exc:
            emit(
                trace_id,
                "llm.error",
                step=step,
                duration_ms=round((time.perf_counter() - started) * 1000, 1),
                error_type=type(exc).__name__,
            )
            raise

        if not completion.choices:
            raise RuntimeError("Model returned no choices")
        message = completion.choices[0].message

        calls = message.tool_calls or [ ]

        usage = completion.usage
        emit(
            trace_id,
            "llm.end",
            step=step,
            duration_ms=round((time.perf_counter() - started) * 1000, 1),
            tool_count=len(calls),
            prompt_tokens=usage.prompt_tokens if usage else None,
            completion_tokens=usage.completion_tokens if usage else None,
        )
        messages.append(message.model_dump(exclude_none=True))

        if not calls:
            answer = message.content or "(The model returned an empty answer.)"
            emit(trace_id, "agent.end", step=step, status="complete")
            return answer

        for call in calls:
            tool_started = time.perf_counter()
            name = call.function.name
            emit(trace_id, "tool.start", step=step, tool=name, call_id=call.id)
            result = run_tool(name, call.function.arguments)
            emit(
                trace_id,
                "tool.end",
                step=step,
                tool=name,
                call_id=call.id,
                duration_ms=round((time.perf_counter() - tool_started) * 1000, 1),
                ok="error" not in json.loads(result),
            )
            messages.append(
                {"role": "tool", "tool_call_id": call.id, "content": result}
            )

    emit(trace_id, "agent.end", step=max_steps, status="step_limit")
    return f"Stopped after {max_steps} model requests without a final answer."


def main() -> int:
    parser = argparse.ArgumentParser(description="Small instrumented ReAct agent")
    parser.add_argument("question", nargs="?", help="Question to ask the agent")
    parser.add_argument("--model", default=DEFAULT_MODEL)
    parser.add_argument("--max-steps", type=int, default=6)
    args = parser.parse_args()

    if args.max_steps < 1:
        parser.error("--max-steps must be at least 1")
    question = args.question or input("Question: ").strip()
    if not question:
        parser.error("Question cannot be empty")
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        parser.error("Set DASHSCOPE_API_KEY in your environment")

    client = OpenAI(
        api_key=api_key,
        base_url=os.getenv("DASHSCOPE_BASE_URL", DEFAULT_BASE_URL),
        timeout=30.0,
    )
    try:
        print(run_agent(client, question, args.model, args.max_steps))
    except Exception as exc:
        print(f"Agent failed: {type(exc).__name__}: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Enter the following prompt in your AI Agent, such as Qoder:

Use the /alibabacloud-agentloop-management Skill to add instrumentation to this high-code Agent written in Python.

The following code shows the result after the AI Agent adds instrumentation:

"""A ReAct agent with LoongSuite GenAI and OpenTelemetry instrumentation."""

from __future__ import annotations

import argparse
import ast
import json
import os
import sys
import time
from datetime import datetime, timezone
from typing import Any

from openai import OpenAI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
    ConsoleSpanExporter,
    SimpleSpanProcessor,
)
from opentelemetry.util.genai.extended_handler import (
    ExtendedTelemetryHandler,
    get_extended_telemetry_handler,
)
from opentelemetry.util.genai.extended_types import (
    EntryInvocation,
    ExecuteToolInvocation,
    InvokeAgentInvocation,
    ReactStepInvocation,
)
from opentelemetry.util.genai.types import (
    InputMessage,
    LLMInvocation,
    OutputMessage,
    Text,
    ToolCall,
    ToolCallResponse,
)


DEFAULT_BASE_URL = (
    "https://dashscope.aliyuncs.com/compatible-mode/v1"
)
DEFAULT_MODEL = "qwen3.7-plus"

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Calculate a basic arithmetic expression with +, -, *, /, and parentheses.",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "Example: (12 + 3) / 5"}
                },
                "required": ["expression"],
                "additionalProperties": False,
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_utc_time",
            "description": "Get the current UTC date and time.",
            "parameters": {
                "type": "object",
                "properties": {},
                "additionalProperties": False,
            },
        },
    },
]

SYSTEM_PROMPT = (
    "You are a helpful assistant. Use tools when they help answer the question. "
    "Use calculate for arithmetic and get_utc_time for the current time. "
    "After observing tool results, give a concise final answer. "
    "Do not invent tool results."
)


def configure_tracing() -> tuple[TracerProvider, ExtendedTelemetryHandler]:
    """Own one SDK provider; export to OTLP when configured, otherwise stderr."""
    resource = Resource.create(
        {
            "service.name": os.getenv("OTEL_SERVICE_NAME", "manual-react-agent"),
            "acs.arms.service.feature": "genai_app",
            "gen_ai.instrumentation.sdk.name": "loongsuite-genai-utils",
        }
    )
    provider = TracerProvider(resource=resource)
    if os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") or os.getenv(
        "OTEL_EXPORTER_OTLP_ENDPOINT"
    ):
        provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    else:
        provider.add_span_processor(
            SimpleSpanProcessor(ConsoleSpanExporter(out=sys.stderr))
        )
    trace.set_tracer_provider(provider)
    handler = get_extended_telemetry_handler(tracer_provider=provider)
    return provider, handler


def json_or_text(value: str) -> Any:
    try:
        return json.loads(value)
    except ValueError:
        return value


def input_messages(messages: list[dict[str, Any]]) -> list[InputMessage]:
    """Keep the same order and tool-call structure as the OpenAI request."""

    converted: list[InputMessage] = [ ]

    for message in messages:

        parts: list[Any] = [ ]

        if message.get("content"):
            parts.append(Text(content=str(message["content"])))

        for call in message.get("tool_calls", [ ]):

            parts.append(
                ToolCall(
                    id=call["id"],
                    name=call["function"]["name"],
                    arguments=json_or_text(call["function"]["arguments"]),
                )
            )
        if message["role"] == "tool":
            parts.append(
                ToolCallResponse(
                    id=message["tool_call_id"],
                    response=json_or_text(message["content"]),
                )
            )
        if parts:
            converted.append(InputMessage(role=message["role"], parts=parts))
    return converted


def output_message(message: Any, finish_reason: str | None) -> OutputMessage:

    parts: list[Any] = [ ]

    if message.content:
        parts.append(Text(content=message.content))

    for call in message.tool_calls or [ ]:

        parts.append(
            ToolCall(
                id=call.id,
                name=call.function.name,
                arguments=json_or_text(call.function.arguments),
            )
        )
    return OutputMessage(
        role="assistant", parts=parts, finish_reason=finish_reason or "stop"
    )


def emit(trace_id: str, event: str, **fields: Any) -> None:
    """Manual instrumentation; never include credentials or request headers."""
    record = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "trace_id": trace_id,
        "event": event,
        **fields,
    }
    print(json.dumps(record, ensure_ascii=False), file=sys.stderr, flush=True)


def calculate(expression: str) -> float | int:
    """Evaluate arithmetic without eval(), imports, names, or function calls."""
    if len(expression) > 200:
        raise ValueError("Expression is too long")
    tree = ast.parse(expression, mode="eval")

    def visit(node: ast.AST, depth: int = 0) -> float | int:
        if depth > 20:
            raise ValueError("Expression is too deeply nested")
        if isinstance(node, ast.Expression):
            return visit(node.body, depth + 1)
        if isinstance(node, ast.Constant) and type(node.value) in (int, float):
            if abs(node.value) > 1e12:
                raise ValueError("Number is too large")
            return node.value
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
            value = visit(node.operand, depth + 1)
            return value if isinstance(node.op, ast.UAdd) else -value
        if isinstance(node, ast.BinOp) and isinstance(
            node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)
        ):
            left = visit(node.left, depth + 1)
            right = visit(node.right, depth + 1)
            if isinstance(node.op, ast.Add):
                result = left + right
            elif isinstance(node.op, ast.Sub):
                result = left - right
            elif isinstance(node.op, ast.Mult):
                result = left * right
            else:
                result = left / right
            if abs(result) > 1e15:
                raise ValueError("Result is too large")
            return result
        raise ValueError("Only basic arithmetic is supported")

    return visit(tree)


def run_tool(name: str, raw_arguments: str) -> str:
    arguments = json.loads(raw_arguments)
    if not isinstance(arguments, dict):
        raise ValueError("Arguments must be a JSON object")
    if name == "calculate":
        if set(arguments) != {"expression"} or not isinstance(
            arguments["expression"], str
        ):
            raise ValueError("calculate requires a string expression")
        result: Any = calculate(arguments["expression"])
    elif name == "get_utc_time":
        if arguments:
            raise ValueError("get_utc_time takes no arguments")
        result = datetime.now(timezone.utc).isoformat()
    else:
        raise ValueError(f"Unknown tool: {name}")
    return json.dumps({"result": result}, ensure_ascii=False)


def run_agent(
    client: OpenAI,
    handler: ExtendedTelemetryHandler,
    question: str,
    model: str,
    max_steps: int = 6,
) -> str:
    messages: list[dict[str, Any]] = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": question},
    ]
    entry = EntryInvocation(input_messages=[InputMessage(role="user", parts=[Text(question)])])
    agent = InvokeAgentInvocation(
        provider="dashscope",
        agent_name="ManualReActAgent",
        agent_description="Small ReAct agent with arithmetic and time tools",
        request_model=model,
        input_messages=[InputMessage(role="user", parts=[Text(question)])],
    )
    total_input_tokens = 0
    total_output_tokens = 0
    usage_complete = True

    with handler.entry(entry):
        trace_id = format(trace.get_current_span().get_span_context().trace_id, "032x")
        emit(trace_id, "agent.start", model=model, max_steps=max_steps)
        with handler.invoke_agent(agent):
            for step in range(1, max_steps + 1):
                react = ReactStepInvocation(round=step)
                with handler.react_step(react):
                    llm = LLMInvocation(
                        provider="dashscope",
                        request_model=model,
                        input_messages=input_messages(messages),
                    )
                    started = time.perf_counter()
                    emit(trace_id, "llm.start", step=step, message_count=len(messages))
                    try:
                        with handler.llm(llm):
                            completion = client.chat.completions.create(
                                model=model,
                                messages=messages,
                                tools=TOOLS,
                                tool_choice="auto",
                            )
                            if not completion.choices:
                                raise RuntimeError("Model returned no choices")
                            choice = completion.choices[0]
                            message = choice.message
                            llm.response_id = completion.id
                            llm.response_model_name = completion.model
                            llm.finish_reasons = [choice.finish_reason]
                            llm.output_messages = [
                                output_message(message, choice.finish_reason)
                            ]
                            usage = completion.usage
                            if usage:
                                llm.input_tokens = usage.prompt_tokens
                                llm.output_tokens = usage.completion_tokens
                                total_input_tokens += usage.prompt_tokens
                                total_output_tokens += usage.completion_tokens
                            else:
                                usage_complete = False
                    except Exception as exc:
                        emit(
                            trace_id,
                            "llm.error",
                            step=step,
                            duration_ms=round((time.perf_counter() - started) * 1000, 1),
                            error_type=type(exc).__name__,
                        )
                        raise


                    calls = message.tool_calls or [ ]

                    emit(
                        trace_id,
                        "llm.end",
                        step=step,
                        duration_ms=round((time.perf_counter() - started) * 1000, 1),
                        tool_count=len(calls),
                        prompt_tokens=usage.prompt_tokens if usage else None,
                        completion_tokens=usage.completion_tokens if usage else None,
                    )
                    messages.append(message.model_dump(exclude_none=True))

                    if not calls:
                        answer = message.content or "(The model returned an empty answer.)"
                        react.finish_reason = "stop"
                        if usage_complete:
                            agent.input_tokens = total_input_tokens
                            agent.output_tokens = total_output_tokens
                        agent.output_messages = [
                            OutputMessage(
                                role="assistant",
                                parts=[Text(answer)],
                                finish_reason="stop",
                            )
                        ]
                        entry.output_messages = agent.output_messages
                        emit(trace_id, "agent.end", step=step, status="complete")
                        return answer

                    for call in calls:
                        tool_started = time.perf_counter()
                        name = call.function.name
                        emit(trace_id, "tool.start", step=step, tool=name, call_id=call.id)
                        tool_inv = ExecuteToolInvocation(
                            tool_name=name,
                            tool_call_id=call.id,
                            tool_type="function",
                            tool_call_arguments=call.function.arguments,
                        )
                        try:
                            with handler.execute_tool(tool_inv):
                                result = run_tool(name, call.function.arguments)
                                tool_inv.tool_call_result = result
                        except (ValueError, SyntaxError, ZeroDivisionError, OverflowError) as exc:
                            result = json.dumps({"error": str(exc)}, ensure_ascii=False)
                        emit(
                            trace_id,
                            "tool.end",
                            step=step,
                            tool=name,
                            call_id=call.id,
                            duration_ms=round((time.perf_counter() - tool_started) * 1000, 1),
                            ok="error" not in json.loads(result),
                        )
                        messages.append(
                            {"role": "tool", "tool_call_id": call.id, "content": result}
                        )
                    react.finish_reason = "continue"

            answer = f"Stopped after {max_steps} model requests without a final answer."
            if usage_complete:
                agent.input_tokens = total_input_tokens
                agent.output_tokens = total_output_tokens
            agent.output_messages = [
                OutputMessage(role="assistant", parts=[Text(answer)], finish_reason="stop")
            ]
            entry.output_messages = agent.output_messages
            emit(trace_id, "agent.end", step=max_steps, status="step_limit")
            return answer


def main() -> int:
    parser = argparse.ArgumentParser(description="Small instrumented ReAct agent")
    parser.add_argument("question", nargs="?", help="Question to ask the agent")
    parser.add_argument("--model", default=DEFAULT_MODEL)
    parser.add_argument("--max-steps", type=int, default=6)
    args = parser.parse_args()

    if args.max_steps < 1:
        parser.error("--max-steps must be at least 1")
    question = args.question or input("Question: ").strip()
    if not question:
        parser.error("Question cannot be empty")
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        parser.error("Set DASHSCOPE_API_KEY in your environment")

    provider, handler = configure_tracing()
    client = OpenAI(
        api_key=api_key,
        base_url=os.getenv("DASHSCOPE_BASE_URL", DEFAULT_BASE_URL),
        timeout=30.0,
    )
    try:
        print(run_agent(client, handler, question, args.model, args.max_steps))
    except Exception as exc:
        print(f"Agent failed: {type(exc).__name__}: {exc}", file=sys.stderr)
        return 1
    finally:
        provider.shutdown()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Key actions of the AI Agent, such as LLM calls and tool calls, are now wrapped by instrumentation. Run the demo. You can change the reporting endpoint to your actual endpoint as described in the Integration Center. The following trace is generated:

image.png

Complex scenarios such as multi-Agent trace propagation

The following example uses Client → Agent A (HTTP service) → Agent B (HTTP service) → Model Studio model to show how to connect traces across custom Agents. A and B run in separate processes. B calls qwen3.7-plus by using an OpenAI-compatible SDK.

Logic without context propagation

The original business logic can be simplified to the following code. When A calls B, A sends only business data, and B directly creates its own server span. Although both sides create Agent spans, B cannot obtain the trace context of A.

# Agent A: Call Agent B after receiving a /ask request
with tracer.start_as_current_span("POST /ask", kind=trace.SpanKind.SERVER):
    with handler.invoke_agent(agent_a_invocation):
        with tracer.start_as_current_span("POST AgentB /answer", kind=trace.SpanKind.CLIENT):
            request = Request(
                agent_b_url,
                data=json.dumps({"question": question}).encode("utf-8"),
                headers={"Content-Type": "application/json"},
                method="POST",
            )
            with urlopen(request) as response:
                result = json.load(response)

# Agent B: Call the model after receiving a /answer request
with tracer.start_as_current_span("POST /answer", kind=trace.SpanKind.SERVER):
    with handler.invoke_agent(agent_b_invocation):
        with handler.llm(llm_invocation):
            answer = call_qwen_model()

The preceding code omits HTTP service initialization and the Invocation parameters. Because the request headers do not contain traceparent, the server span created by B becomes the root of a separate trace, and Agent A and Agent B cannot be connected on the observability platform.

Prompt for the AI Agent
Use the /alibabacloud-agentloop-management Skill to connect traces across processes between Python Agent A and Agent B as required.
Code modified by the AI Agent

The following is the complete server.py file. A calls propagate.inject within the HTTP client span. B calls propagate.extract before it creates the HTTP server span, and calls detach after the request ends. Each process creates its own Agent span, and B also creates an LLM span for the actual LLM request. The W3C TraceContext and Baggage propagators use the same configuration on both sides. By default, the code exports spans to the console. After you configure OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and the authentication headers, the code reports spans over OTLP instead.

"""Two small HTTP agents with manual W3C Trace Context propagation."""

from __future__ import annotations

import argparse
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
from urllib.request import Request, urlopen

from openai import OpenAI
from opentelemetry import context, propagate, trace
from opentelemetry.baggage.propagation import W3CBaggagePropagator
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.propagators.composite import CompositePropagator
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
    ConsoleSpanExporter,
    SimpleSpanProcessor,
)
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.extended_types import InvokeAgentInvocation
from opentelemetry.util.genai.types import InputMessage, LLMInvocation, OutputMessage, Text


MODEL = "qwen3.7-plus"
BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"


def setup_tracing(service_name: str) -> TracerProvider:
    # Set before the GenAI handler is created; callers can override either value.
    os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "gen_ai_latest_experimental")
    os.environ.setdefault("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "SPAN_ONLY")
    propagate.set_global_textmap(
        CompositePropagator([TraceContextTextMapPropagator(), W3CBaggagePropagator()])
    )
    provider = TracerProvider(
        resource=Resource.create(
            {
                "service.name": service_name,
                "acs.arms.service.feature": "genai_app",
                "gen_ai.instrumentation.sdk.name": "loongsuite-genai-utils",
            }
        )
    )
    if os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") or os.getenv(
        "OTEL_EXPORTER_OTLP_ENDPOINT"
    ):
        provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    else:
        provider.add_span_processor(
            SimpleSpanProcessor(ConsoleSpanExporter(out=sys.stderr))
        )
    trace.set_tracer_provider(provider)
    return provider


def trace_id(span: Any) -> str:
    return format(span.get_span_context().trace_id, "032x")


def span_id(span: Any) -> str:
    return format(span.get_span_context().span_id, "016x")


class AgentServer(BaseHTTPRequestHandler):
    role = ""
    agent_b_url = ""
    llm_client: OpenAI | None = None
    genai_handler: Any = None
    tracer: Any = None

    def reply(self, status: int, data: dict[str, Any]) -> None:
        body = json.dumps(data, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def read_question(self) -> str:
        length = int(self.headers.get("Content-Length", "0"))
        if not 0 < length <= 16_384:
            raise ValueError("Request body must be 1–16384 bytes")
        payload = json.loads(self.rfile.read(length))
        question = payload.get("question") if isinstance(payload, dict) else None
        if not isinstance(question, str) or not question.strip():
            raise ValueError("JSON body must contain a nonempty question")
        return question.strip()

    def do_POST(self) -> None:
        expected = "/ask" if self.role == "a" else "/answer"
        if self.path != expected:
            self.reply(404, {"error": "Not found"})
            return

        # HTTP header spelling may be normalized by clients, so make a
        # lowercase dict for the default OTel text-map getter.
        carrier = {key.lower(): value for key, value in self.headers.items()}
        token = context.attach(propagate.extract(carrier))
        try:
            with self.tracer.start_as_current_span(
                f"POST {expected}", kind=trace.SpanKind.SERVER
            ) as server_span:
                question = self.read_question()
                if self.role == "a":
                    result = self.run_agent_a(question, server_span)
                else:
                    result = self.run_agent_b(question, server_span)
            self.reply(200, result)
        except (ValueError, json.JSONDecodeError) as exc:
            self.reply(400, {"error": str(exc)})
        except Exception as exc:
            print(f"{self.role} request failed: {type(exc).__name__}", file=sys.stderr)
            self.reply(502, {"error": type(exc).__name__})
        finally:
            context.detach(token)

    def run_agent_a(self, question: str, server_span: Any) -> dict[str, Any]:
        invocation = InvokeAgentInvocation(
            provider="application",
            agent_name="AgentA",
            input_messages=[InputMessage(role="user", parts=[Text(question)])],
        )
        with self.genai_handler.invoke_agent(invocation):
            # The active CLIENT span must be injected, not the earlier Agent span.
            with self.tracer.start_as_current_span(
                "POST AgentB /answer", kind=trace.SpanKind.CLIENT
            ) as client_span:
                headers = {"Content-Type": "application/json"}
                propagate.inject(headers)
                request = Request(
                    self.agent_b_url,
                    data=json.dumps({"question": question}).encode("utf-8"),
                    headers=headers,
                    method="POST",
                )
                with urlopen(request, timeout=30) as response:
                    result = json.load(response)
                client_span_id = span_id(client_span)

            answer = result["answer"]
            invocation.output_messages = [
                OutputMessage(role="assistant", parts=[Text(answer)], finish_reason="stop")
            ]
            return {
                "answer": answer,
                "a_trace_id": trace_id(server_span),
                "a_client_span_id": client_span_id,
                "b_trace_id": result["b_trace_id"],
                "b_parent_span_id": result["b_parent_span_id"],
            }

    def run_agent_b(self, question: str, server_span: Any) -> dict[str, Any]:
        if self.llm_client is None:
            raise RuntimeError("Agent B requires DASHSCOPE_API_KEY")
        system_prompt = "Answer the user's question briefly."
        user_message = InputMessage(role="user", parts=[Text(question)])
        agent_inv = InvokeAgentInvocation(
            provider="dashscope",
            agent_name="AgentB",
            request_model=MODEL,
            input_messages=[user_message],
        )
        with self.genai_handler.invoke_agent(agent_inv):
            llm_inv = LLMInvocation(
                provider="dashscope",
                request_model=MODEL,
                input_messages=[
                    InputMessage(role="system", parts=[Text(system_prompt)]),
                    user_message,
                ],
            )
            with self.genai_handler.llm(llm_inv):
                completion = self.llm_client.chat.completions.create(
                    model=MODEL,
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": question},
                    ],
                )
                if not completion.choices:
                    raise RuntimeError("Model returned no choices")
                answer = completion.choices[0].message.content or ""
                if not answer:
                    raise RuntimeError("Model returned an empty answer")
                llm_inv.response_id = completion.id
                llm_inv.response_model_name = completion.model
                llm_inv.finish_reasons = [completion.choices[0].finish_reason]
                llm_inv.output_messages = [
                    OutputMessage(
                        role="assistant",
                        parts=[Text(answer)],
                        finish_reason=completion.choices[0].finish_reason,
                    )
                ]
                if completion.usage:
                    llm_inv.input_tokens = completion.usage.prompt_tokens
                    llm_inv.output_tokens = completion.usage.completion_tokens
                    agent_inv.input_tokens = completion.usage.prompt_tokens
                    agent_inv.output_tokens = completion.usage.completion_tokens

            agent_inv.output_messages = [
                OutputMessage(role="assistant", parts=[Text(answer)], finish_reason="stop")
            ]
        parent = server_span.parent
        return {
            "answer": answer,
            "b_trace_id": trace_id(server_span),
            "b_parent_span_id": format(parent.span_id, "016x") if parent else None,
        }


def main() -> None:
    parser = argparse.ArgumentParser(description="HTTP Agent A → Agent B trace demo")
    parser.add_argument("role", choices=("a", "b"))
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int)
    parser.add_argument("--agent-b-url", default="http://127.0.0.1:8001/answer")
    args = parser.parse_args()
    port = args.port or (8000 if args.role == "a" else 8001)

    provider = setup_tracing(f"http-agent-{args.role}")
    server_class = type(f"Agent{args.role.upper()}Server", (AgentServer,), {})
    server_class.role = args.role
    server_class.agent_b_url = args.agent_b_url
    server_class.tracer = trace.get_tracer(__name__)
    server_class.genai_handler = get_extended_telemetry_handler(tracer_provider=provider)
    if args.role == "b":
        api_key = os.getenv("DASHSCOPE_API_KEY")
        if not api_key:
            parser.error("Agent B needs DASHSCOPE_API_KEY")
        server_class.llm_client = OpenAI(
            api_key=api_key,
            base_url=os.getenv("DASHSCOPE_BASE_URL", BASE_URL),
            timeout=20,
        )

    http_server = ThreadingHTTPServer((args.host, port), server_class)
    print(f"Agent {args.role.upper()} listening on {args.host}:{port}", flush=True)
    try:
        http_server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        http_server.server_close()
        provider.shutdown()


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

Start processes A and B locally, make sure that they can call the Model Studio model, and then run the following command:

curl --fail-with-body -sS --max-time 45 http://127.0.0.1:8000/ask \
  -H 'Content-Type: application/json' \
  -d '{"question":"Explain OpenTelemetry in one sentence."}'

Sample response:

{
  "answer": "OpenTelemetry is an open source observability framework that standardizes how telemetry data such as traces, metrics, and logs is generated, collected, and exported, helping developers monitor and analyze software performance and troubleshoot issues.",
  "a_trace_id": "2682a5e8438069c8253d107ee1434835",
  "a_client_span_id": "9c98549a0f97cd53",
  "b_trace_id": "2682a5e8438069c8253d107ee1434835",
  "b_parent_span_id": "9c98549a0f97cd53"
}

The spans exported to the console also show that the client span ID of A is 9c98549a0f97cd53, which is the same as the parent span ID of the server span of B. The trace ID on both sides is 2682a5e8438069c8253d107ee1434835. The following figure shows the trace relationship: image.png

FAQ

What do I do if data reported by the AI Agent is still incomplete?

Check the data against the corresponding fields in LLM Trace field definitions. If optional fields are missing, you can ask the AI Agent to add them based on that topic.

Which programming languages does the Skill support?

The alibabacloud-agentloop-management Skill supports four mainstream programming languages: Java, Python, Go, and Node.js.