Integrate a Claude Agent SDK (Python) application

Updated at:

You can use the Python agent to enable large model observability for Claude Agent SDK (Python) applications. The Python agent, developed by Alibaba Cloud, is a proprietary observability agent that provides automatic instrumentation based on the OpenTelemetry standard. This topic describes how to connect a Claude Agent SDK (Python) application to Cloud Monitor 2.0 to gain real-time insights into your AI application's performance and behavior.

Framework

The following Claude Agent SDK (Python) framework is supported:

  • Python SDK (claude-agent-sdk-python): An open-source agent framework from Anthropic that provides a simple API for building AI agents with tool use capabilities. The SDK natively supports Skills and includes built-in system tools like Bash, Glob, Grep, and Read, making it suitable for building agent applications for tasks such as code analysis and document-based Q&A.

Language

Package

Supported version range

Python

claude-agent-sdk

Python 3.9 to 3.14

After integration, the following capabilities are automatically monitored:

  • Agent queries, including the model name, token usage, and input and output

  • tool call chains, including Bash, Glob, Grep, Read, and custom tools

  • Sub-agent inference

  • Error and exception capture

Integration methods

Integration methods

Integrate with Container Service for Kubernetes (ACK) and Container Compute Service (ACS)

Step 1: Install the agent integration assistant (ack-onepilot)

  1. Log on to the ACK console. On the Clusters page, click the name of the cluster.

  2. In the left-side navigation pane, click add-ons. Then, in the upper-right corner, search for ack-onepilot.

  3. On the ack-onepilot card, click Install. Configure the parameters. Use the default values unless otherwise required. Click Confirm.

    Note

    Ensure that the ack-onepilot component version is 5.1.1 or later. The current version appears in step 3. If you have an earlier version installed, repeat steps 1 and 2, then click Upgrade in step 3.

Step 2: Modify configuration to enable AI application monitoring

  1. Log on to the Container Service console or the . In the left navigation pane, select Clusters.

  2. On the Clusters page, click the name of your destination cluster. In the left navigation pane, choose Workloads > Deployments.

  3. Switch to the appropriate namespace, locate the workload to monitor, click the More icon p1029481 in the Actions column on the far right, and then click Edit YAML in the dialog box.

  4. In the YAML file, add the following labels under spec > template > metadata. After adding them, click Update.

    labels:
      aliyun.com/app-language: python # Required for Python applications. Indicates this is a Python application.
      armsPilotAutoEnable: 'on'
      armsPilotCreateAppName: "deployment-name"    # Display name of the application in ARMS
      armsPilotAppWorkspace: "workspace"    # Replace with your current workspace name. If not specified, the default workspace is used.

    image

Manually integrate the agent

Step 1: Download the agent installer aliyun-bootstrap

Download the agent installer from the PyPI repository.

pip3 install aliyun-bootstrap

Step 2: Configure environment variables

You must manually add the following environment variables for your Python application:

# Method 1: Add environment variables for all processes in the current shell.
export ARMS_APP_NAME=<your-app-name>        # Specifies a custom name for your application.
export ARMS_WORKSPACE=<your-workspace-name> # Specifies the workspace to which data is reported.
export ARMS_REGION_ID=<your-region-id>      # Specifies the Region ID of your workspace.
export ARMS_LICENSE_KEY=<your-license-key>  # Specifies the license key for authentication.
# Method 2: Add environment variables for a specific process.
ARMS_APP_NAME=<your-app-name> ARMS_WORKSPACE=<your-workspace-name> ARMS_REGION_ID=<your-region-id> ARMS_LICENSE_KEY=<your-license-key> aliyun-instrument <your-app-file>.py

To obtain the license key, see the authToken field in the response of the GetApplicationObservability API operation.

(Optional) Docker installation reference

For Docker environments, modify your Dockerfile based on the following example.

# Add environment variables
ENV ARMS_APP_NAME={your-app-name}
ENV ARMS_REGION_ID={your-region-id}
ENV ARMS_LICENSE_KEY={your-license-key}
ENV ARMS_WORKSPACE={your-workspace-name}

## Add your original Dockerfile commands here
Step 3: Use aliyun-bootstrap to install the Python agent
  1. To speed up installation, run the following command to configure the mirror repository first.

    pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && pip config set install.trusted-host mirrors.aliyun.com
  2. Install the agent.

    aliyun-bootstrap -a install
Step 4: Start the application
Start the application using the ARMS Python agent
aliyun-instrument python app.py

Sample code

The following example uses read-only tools (Glob and Read) to list Python files in the current directory. This produces a complete Agent → LLM → Tool call chain that you can verify in Cloud Monitor 2.0.

Before running the example, set the following environment variables:

export ANTHROPIC_API_KEY=<your_api_key>
export ANTHROPIC_BASE_URL=<your_endpoint>      # Optional: set only if using a custom endpoint
export ARMS_APP_NAME=<your_app_name>
export ARMS_REGION_ID=<your_region_id>
export ARMS_LICENSE_KEY=<your_license_key>
export ARMS_WORKSPACE=<your_workspace_name>
import asyncio
import os
from claude_agent_sdk import AssistantMessage, query
from claude_agent_sdk.types import ClaudeAgentOptions, ResultMessage

async def main():
    options = ClaudeAgentOptions(
        model=os.environ.get("CLAUDE_MODEL", "claude-opus-4-5"),
        allowed_tools=["Glob", "Read"],
    )
    async for msg in query(
        prompt="List all Python files in the current directory and show the first 5 lines of each",
        options=options,
    ):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if hasattr(block, "text"):
                    print(block.text, flush=True)
        elif isinstance(msg, ResultMessage):
            print(f"\n[Done] {msg.result}")

asyncio.run(main())

Run the following command to start the application. Pass the API key via an environment variable — do not hardcode credentials in the code or command line.

aliyun-instrument python app.py
Note

The API syntax of the query function (including function signature and response message type field names) is subject to the actual released version of claude-agent-sdk. Refer to the package documentation when integrating. In production environments, inject credentials through OS environment variables or a secrets management service.

After the agent run completes, you can verify the following spans in AI Application Observability:

  • invoke_agent: Top-level agent call. Contains model name, total token usage, and agent output.

  • chat: Each LLM inference step. Contains input messages, model replies, and stop reason.

  • execute_tool: Each tool call (Glob or Read in this example). Contains tool name, input arguments, and output result.

  • Error attributes are captured on any span where an exception occurs.

View monitoring details

  1. Log on to the Cloud Monitor 2.0 console, select the target workspace, and in the left navigation bar, select All Features > AI Application Observability.

  2. On the AI application list page, click an application name to view detailed monitoring data.

image.png

On the Application Details page, go to the Trace Details page to view the complete AI call chain. The filter panel on the left lets you filter by Span Type (such as LLM, TOOL, or AGENT) and API Name. The central area displays summary metrics like total trace duration and total tokens, along with a waterfall timeline. This timeline visualizes the parent-child relationships and duration distribution of spans like invoke_agent, chat (LLM inference), and execute_tool (tool call). When you click a span, the details panel on the right shows metadata such as application name, API name, IP address, span ID, and timestamps. The Input Messages tab displays the multi-turn conversation history, including user inputs, model replies, and tool results.

To verify the Agent → LLM → Tool parent-child relationship for your latest request:

  1. In the waterfall timeline, locate the root invoke_agent span (AGENT type). All chat (LLM) spans and all execute_tool (TOOL) spans are its direct children. execute_tool spans are parallel to chat spans — they are NOT nested inside chat spans.

  2. Click a chat (LLM) span. The details panel on the right shows the model name that was actually used and the numbers of input tokens and output tokens for this call.

  3. Click a chat span to view the input messages sent to the model and the model reply, including any tool call requests issued by the model.

  4. Click an execute_tool span to verify the tool name (for example, Glob or Read), input arguments, and output result.

  5. If an error occurred, look for spans with an error indicator. The exception type and message are shown in the span details panel under the error attributes.

More information