ADBAgent API User Guide

更新时间:
复制 MD 格式

Use the ADBAgent RESTful API to programmatically access AI-powered data analysis capabilities, including authentication, session management, data analysis, data source management, and skill management.

Overview

The ADBAgent API is served through the instance's public IP and port. Requests and responses use JSON format. Two interaction modes are available for retrieving analysis results:

  • Polling: After sending a prompt, use the returned roundId to poll for the analysis status and results. Best for scripts and backend integrations.

  • SSE (Server-Sent Events): Receive analysis progress and results in real time via an event stream. Best for building interactive chat interfaces.

Preparation

Before calling the API, complete the following steps:

  1. Enable ADBAgent

    On the cluster details page in the AnalyticDB MySQL console, choose ADBClaw (AI Assistant) and click Add Service to create an ADBClaw instance. For details, see ADBAgent.

  2. Add IP to the whitelist

    On the ADBClaw (AI Assistant) page, click Details in the Actions column for the target service, choose the Whitelist Settings tab, and click Add Whitelist Group to add the public IP of the machine that calls the API.

    Note

    Run curl ifconfig.me in a terminal to find your public IP.

  3. Get login credentials

    On the ADBClaw (AI Assistant) page, click Credentials in the Actions column for the target service to view the default username and password. These credentials are used to call the login endpoint and obtain a token. To change the password, log in to ADBClaw and modify it on the user management page.

Quick start

Follow these steps to complete a full data analysis workflow through the API.

Step 1: Get the access URL

Find the public IP address and port number on the ADBAgent console page. Set an environment variable:

export BASE="http://<PUBLIC_IP>:3001"
Note

Replace <PUBLIC_IP> with the actual public IP address from the ADBAgent console.

Step 2: Log in and get a token

Call the login endpoint to obtain an authentication token. All subsequent API requests require this token in the Authorization header. The username and password are the default credentials of the target service on the ADBClaw (AI Assistant) page. Click Credentials in the Actions column to view them.

TOKEN=$(curl -s -X POST "$BASE/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"<USERNAME>", "password":"<PASSWORD>", "expiresIn":86400}' | jq -r .token)

echo $TOKEN

Request parameters:

Parameter

Type

Required

Description

username

string

Yes

Login username.

password

string

Yes

Login password.

expiresIn

number

No

Token expiration time in seconds. Default: 14400 (4 hours).

Response example:

{
  "token": "owt_xxxxx",
  "scope": "collaborator",
  "userId": "usr_xxxxx",
  "username": "admin",
  "expiresIn": 86400,
  "expiresAt": "2026-01-02T10:00:00.000Z"
}
Important

Re-authenticate when the token expires. Keep your token secure and do not expose it publicly.

Step 3: List available models

Query the available large language models.

curl -s "$BASE/api/v1/models" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response example:

{
  "models": [
    {
      "id": "adb-qwen3.5-plus/qwen3.5-plus",
      "name": "qwen3.5-plus",
      "provider": "adb-qwen3.5-plus"
    }
  ]
}

Step 4: Create a session

All conversations happen within sessions. You must create a session before sending prompts.

SID=$(curl -s -X POST "$BASE/api/v1/sessions" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"My analysis task"}' | jq -r '.sessionId')

echo "Session ID: $SID"

Request parameters:

Parameter

Type

Required

Description

title

string

Yes

Session title.

Response example:

{
  "sessionId": "ses_xxxxx",
  "title": "My analysis task",
  "createdAt": "2026-01-01T10:00:00.000Z"
}

Step 5: Send a prompt

Submit an analysis question in the session.

RID=$(curl -s -X POST "$BASE/api/v1/sessions/$SID/prompt" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text":"Show me the top selling products this month"}' | jq -r '.roundId')

echo "Round ID: $RID"

Request parameters:

Parameter

Type

Required

Description

text

string

Yes

The question or analysis request

model

string

No

Model identifier in provider/modelName format. Uses the default model if omitted.

Response example:

{
  "roundId": "rnd_msg_xxxxx"
}

Step 6: Get the response

Analysis runs asynchronously. Poll the round endpoint using the roundId until status becomes completed.

curl -s "$BASE/api/v1/sessions/$SID/rounds/$RID" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response example:

{
  "roundId": "rnd_msg_xxxxx",
  "status": "completed",
  "question": "Show me the top selling products this month",
  "answer": "Based on the analysis...",
  "model": "adb-qwen3.5-plus/qwen3.5-plus",
  "duration": 3200
}

Status field values:

Value

Meaning

Action

running

Analysis in progress

Continue polling (recommended interval: 2 seconds)

completed

Analysis finished

Read the answer field for results

error

Analysis failed

The answer field contains the error description

Step 7: SSE real-time event stream (optional)

In addition to polling, you can receive analysis progress and results in real time through SSE (Server-Sent Events). This mode is ideal for building interactive chat interfaces.

Subscribe to the event stream in one terminal and send a prompt in another:

# Terminal 1: Subscribe to the event stream (plain format, typewriter effect)
curl -N "$BASE/api/v1/sessions/$SID/events?format=plain" \
  -H "Authorization: Bearer $TOKEN"

# Terminal 2: Send a prompt (same as Step 5)
curl -s -X POST "$BASE/api/v1/sessions/$SID/prompt" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text":"Analyze order trends for the past 7 days"}'

The event stream pushes analysis progress and final results in real time. For detailed SSE format descriptions and frontend integration examples, see the SSE real-time event stream section.

API reference

Method

Path

Description

Authentication

POST

/api/v1/auth/login

Log in and get a token

Sessions

POST

/api/v1/sessions

Create a session

GET

/api/v1/sessions

List all sessions

DELETE

/api/v1/sessions/{sessionId}

Delete a session

GET

/api/v1/sessions/{sessionId}/messages

View message history

POST

/api/v1/sessions/{sessionId}/abort

Abort current analysis

Conversations

POST

/api/v1/sessions/{sessionId}/prompt

Send a prompt

GET

/api/v1/sessions/{sessionId}/rounds/{roundId}

Get round result (polling)

GET

/api/v1/sessions/{sessionId}/events

SSE event stream

Models

GET

/api/v1/models

List available models

GET

/api/v1/sessions/{sessionId}/model

View session default model

POST

/api/v1/sessions/{sessionId}/model

Set session default model

Data sources

GET

/api/v1/datasources

List all data sources

GET

/api/v1/datasources/{name}

Get data source details

GET

/api/v1/datasources/{name}/databases

List databases

GET

/api/v1/datasources/{name}/{database}/tables

List tables

POST

/api/v1/datasources

Create a data source

PUT

/api/v1/datasources/{name}

Update a data source

DELETE

/api/v1/datasources/{name}

Delete a data source

Skills

GET

/api/v1/skills

List installed skills

GET

/api/v1/skills/{skillName}

Get skill details

POST

/api/v1/skills

Create or update a skill

DELETE

/api/v1/skills/{skillName}

Delete a skill

PATCH

/api/v1/skills/{skillName}/permission

Set skill permissions

POST

/api/v1/skills/upload

Upload a skill via ZIP

GET

/api/v1/skills/{skillName}/download

Export a skill as ZIP

Note

All endpoints except the login endpoint require the Authorization: Bearer $TOKEN header for authentication.

Session management

List all sessions

Request method: GET

Request path: /api/v1/sessions

Description: Retrieve all sessions for the current user.

Request example

curl -s "$BASE/api/v1/sessions" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response fields:

Field

Type

Description

sessions

array

Session list. Each element contains sessionId, title, model, createdAt, and updatedAt fields.

Response example:

{
  "sessions": [
    {
      "sessionId": "ses_xxxxx",
      "title": "My analysis task",
      "model": "adb-qwen3.5-plus/qwen3.5-plus",
      "createdAt": "2026-01-01T10:00:00.000Z",
      "updatedAt": "2026-01-01T12:00:00.000Z"
    }
  ]
}

View message history

Request method: GET

Request path: /api/v1/sessions/{sessionId}/messages

Description: Retrieve conversation history for the specified session.

Request parameters

Parameter

Type

Required

Description

limit

number

No

Number of messages to return. Default: 50.

Request example

curl -s "$BASE/api/v1/sessions/$SID/messages?limit=50" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response fields:

Field

Type

Description

messages

array

Message list. Each element contains role (user/assistant), content, and createdAt fields.

Response example:

{
  "messages": [
    {
      "role": "user",
      "content": "Analyze user activity trends for the past 7 days",
      "createdAt": "2026-01-01T10:00:00.000Z"
    },
    {
      "role": "assistant",
      "content": "Based on the analysis of the user_activity table...",
      "createdAt": "2026-01-01T10:00:05.000Z"
    }
  ]
}

Abort current analysis

Request method: POST

Request path: /api/v1/sessions/{sessionId}/abort

Description: Stop an in-progress analysis task for the specified session.

Request example

curl -s -X POST "$BASE/api/v1/sessions/$SID/abort" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Returns HTTP 200 on success:

{"success": true}

Delete a session

Request method: DELETE

Request path: /api/v1/sessions/{sessionId}

Description: Permanently delete a session and all its messages. This action cannot be undone.

Request example

curl -s -X DELETE "$BASE/api/v1/sessions/$SID" \
  -H "Authorization: Bearer $TOKEN"
# Returns HTTP 204

Retrieving responses

ADBAgent offers two ways to get analysis results: polling and SSE streaming.

Polling

Request method: GET

Request path: /api/v1/sessions/{sessionId}/rounds/{roundId}

Description: After sending a prompt, poll the round endpoint using the returned roundId until the status becomes completed or error.

Response

Response fields:

Field

Type

Description

roundId

string

Round identifier.

status

string

Analysis status: running, completed, or error.

question

string

The original question.

answer

string

Analysis result or error description.

model

string

Model used for the analysis.

duration

number

Analysis duration in milliseconds.

Polling example script

The following script automates the polling loop:

poll_round() {
  local sid=$1 rid=$2
  while true; do
    RESP=$(curl -s "$BASE/api/v1/sessions/$sid/rounds/$rid" \
      -H "Authorization: Bearer $TOKEN")
    STATUS=$(echo "$RESP" | jq -r '.status')
    case $STATUS in
      completed)
        echo "$RESP" | jq '{question, answer, model, duration}'
        return 0 ;;
      error)
        echo "$RESP" | jq '{question, answer, status}'
        return 1 ;;
      *)
        sleep 2 ;;
    esac
  done
}

# Usage: send a prompt and wait for results
RID=$(curl -s -X POST "$BASE/api/v1/sessions/$SID/prompt" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text":"Analyze user activity trends for the past 7 days"}' | jq -r '.roundId')
poll_round "$SID" "$RID"

SSE streaming

Request method: GET

Request path: /api/v1/sessions/{sessionId}/events?format=<format>

Description: Receive analysis progress and results in real time via an SSE (Server-Sent Events) stream.

Request parameters

Three output formats are supported:

Format

Content-Type

Description

raw

text/event-stream

Full SSE event stream with event types like message.part.delta, message.part.updated, and session.idle. Distinguishes between reasoning and final answer. Best for clients that need fine-grained control.

text

text/event-stream

Simplified SSE with three event types: delta (content chunk), done (generation complete), and error. Reasoning content is filtered out. Best for simple clients that only need the final answer.

plain

text/plain

Plain text stream (not SSE format). Outputs text fragments directly, including reasoning content. Best for terminal or curl debugging with a typewriter effect.

Request example

Subscribe to the event stream first, then send the prompt.

# Typewriter effect in the terminal (plain format)
curl -N "$BASE/api/v1/sessions/$SID/events?format=plain" \
  -H "Authorization: Bearer $TOKEN"
Note

When using SSE, establish the event stream connection first, then send the prompt via the prompt endpoint. The stream delivers the analysis process and results in real time.

Frontend integration example

The following JavaScript example consumes the SSE text format stream:

async function streamChat(base, token, sessionId, question) {
  const controller = new AbortController();

  // 1. Subscribe to the SSE stream
  const eventRes = await fetch(
    `${base}/api/v1/sessions/${sessionId}/events?format=text`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
      signal: controller.signal
    }
  );

  // 2. Send the prompt
  await fetch(`${base}/api/v1/sessions/${sessionId}/prompt`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ text: question })
  });

  // 3. Read the event stream
  const reader = eventRes.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  let answer = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    const chunks = buffer.split('\n\n');
    buffer = chunks.pop() ?? '';

    for (const chunk of chunks) {
      const dataLine = chunk.split('\n')
        .find(l => l.startsWith('data:'));
      if (!dataLine) continue;
      const event = JSON.parse(dataLine.slice(5).trim());

      if (event.type === 'delta') {
        answer += event.content ?? '';
        console.log(event.content);  // Real-time output
      } else if (event.type === 'done') {
        controller.abort();
        return answer;
      } else if (event.type === 'error') {
        throw new Error(event.message);
      }
    }
  }
  return answer;
}

Default model settings

Each session can have a default model. When set, all prompts in that session use the specified model.

View the default model

Request method: GET

Request path: /api/v1/sessions/{sessionId}/model

Description: Retrieve the default model configuration for the specified session.

Request example

curl -s "$BASE/api/v1/sessions/$SID/model" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response fields:

Field

Type

Description

model

string

Session-level default model.

globalDefault

string

Global-level default model.

effective

string

The model actually in use (session-level takes priority).

Response example:

{
  "sessionId": "ses_xxxxx",
  "model": "adb-qwen3.5-plus/qwen3.5-plus",
  "globalDefault": "adb-qwen3.5-plus/qwen3.5-plus",
  "effective": "adb-qwen3.5-plus/qwen3.5-plus"
}

Set the default model

Request method: POST

Request path: /api/v1/sessions/{sessionId}/model

Description: Set the default model for a session. Subsequent prompts in this session use the specified model.

Request parameters

Parameter

Type

Required

Description

model

string

Yes

Model identifier in provider/modelName format. Use /api/v1/models to list available models.

Request example

curl -s -X POST "$BASE/api/v1/sessions/$SID/model" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model":"adb-qwen3.5-plus/qwen3.5-plus"}' | jq .

Response

Response example:

{
  "sessionId": "ses_xxxxx",
  "model": "adb-qwen3.5-plus/qwen3.5-plus",
  "globalDefault": "adb-qwen3.5-plus/qwen3.5-plus",
  "effective": "adb-qwen3.5-plus/qwen3.5-plus"
}

Data source management

Use the data source API to list, create, test, update, and delete data source configurations.

Note

We recommend completing the initial data source setup through the ADBAgent console before using the API.

List all data sources

Request method: GET

Request path: /api/v1/datasources

Description: Retrieve all configured data sources.

Request example

curl -s "$BASE/api/v1/datasources" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response fields:

Field

Type

Description

name

string

Data source name.

type

string

Data source type (for example, adb_mysql).

enabled

boolean

Whether the data source is enabled.

gateway_status

string

Gateway connection status (for example, running).

Response example:

{
  "data_sources": [
    {
      "name": "adb_mysql_default",
      "type": "adb_mysql",
      "description": "",
      "enabled": true,
      "configured": true,
      "gateway_status": "running",
      "connection": {
        "host": "xxx",
        "port": 3306,
        "user": "xxx",
        "database": "xxx"
      }
    }
  ]
}

Get data source details

Request method: GET

Request path: /api/v1/datasources/{name}

Description: Retrieve the detailed configuration of a specific data source.

Request example

curl -s "$BASE/api/v1/datasources/adb_mysql_default" \
  -H "Authorization: Bearer $TOKEN" | jq .

List databases

Request method: GET

Request path: /api/v1/datasources/{name}/databases

Description: List all databases available in the specified data source.

Request example

curl -s "$BASE/api/v1/datasources/adb_mysql_default/databases" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response example:

{
  "databases": [
    "INFORMATION_SCHEMA",
    "my_database",
    "analytics_db"
  ]
}

List tables

Request method: GET

Request path: /api/v1/datasources/{name}/{database}/tables

Description: List all tables in the specified database of a data source.

Request parameters

Path parameters:

Parameter

Type

Required

Description

name

string

Yes

Data source name.

database

string

Yes

Database name.

Request example

curl -s "$BASE/api/v1/datasources/adb_mysql_default/my_database/tables" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response example:

{
  "tables": ["orders", "users", "products"]
}

Create a data source

Request method: POST

Request path: /api/v1/datasources

Description: Create a new data source connection.

Request parameters

Parameter

Type

Required

Description

name

string

Yes

Data source name.

type

string

Yes

Data source type (for example, adb_mysql).

connection

object

Yes

Connection settings including host, port, user, password, and database.

Request example

curl -s -X POST "$BASE/api/v1/datasources" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my_datasource",
    "type": "adb_mysql",
    "connection": {
      "host": "xxx.xxx.xxx.xxx",
      "port": 3306,
      "user": "db_user",
      "password": "db_password",
      "database": "my_database"
    }
  }' | jq .

Update a data source

Request method: PUT

Request path: /api/v1/datasources/{name}

Description: Update the connection configuration of an existing data source.

Request example

curl -s -X PUT "$BASE/api/v1/datasources/my_datasource" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "connection": {
      "host": "new-host.xxx.xxx",
      "port": 3306,
      "user": "new_user",
      "password": "new_password",
      "database": "new_database"
    }
  }' | jq .

Delete a data source

Request method: DELETE

Request path: /api/v1/datasources/{name}

Description: Permanently delete a data source configuration.

Request example

curl -s -X DELETE "$BASE/api/v1/datasources/my_datasource" \
  -H "Authorization: Bearer $TOKEN"
# Returns HTTP 204

Skill management

Skills are reusable instruction templates that enhance the AI model's capabilities in specific domains. The system includes built-in skills such as an ADB MySQL database assistant. You can also create and manage custom skills through the API.

Skill names must use kebab-case format (for example, adb-sql-review). Spaces and uppercase letters are not allowed.

List installed skills

Request method: GET

Request path: /api/v1/skills

Description: Retrieve a list of installed skills. Use the includeGlobal parameter to include global skills.

Request parameters

Parameter

Type

Required

Description

includeGlobal

boolean

No

Whether to include global skills. Default: false.

Request example

# Project-level skills only
curl -s "$BASE/api/v1/skills" \
  -H "Authorization: Bearer $TOKEN" | jq .

# Include global skills
curl -s "$BASE/api/v1/skills?includeGlobal=true" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

Response fields:

Field

Type

Description

name

string

Skill name in kebab-case format.

scope

string

project (project-level) or global (global-level).

builtIn

boolean

Whether the skill is built-in. Built-in skills cannot be modified, deleted, or exported.

permission

string

Permission state: allow (auto-allow), deny (blocked), or ask (prompt before use).

Response example:

{
  "skills": [
    {
      "name": "alibabacloud-analyticdb-mysql-copilot",
      "description": "ADB MySQL database AI assistant",
      "scope": "project",
      "builtIn": true,
      "permission": "allow"
    }
  ],
  "total": 1
}

Get skill details

Request method: GET

Request path: /api/v1/skills/{name}

Description: Retrieve the full details of a skill, including its SKILL.md content.

Request example

curl -s "$BASE/api/v1/skills/my-custom-skill" \
  -H "Authorization: Bearer $TOKEN" | jq .

Response

The content field in the response contains the full Markdown content of SKILL.md.

Create or update a skill

Request method: POST

Request path: /api/v1/skills

Description: Create or update a skill. If a skill with the same name already exists, it is updated; otherwise, a new skill is created.

Request parameters

Parameter

Type

Required

Description

name

string

Yes

Skill name in kebab-case (for example, adb-sql-review).

description

string

No

Skill description.

content

string

Yes

Full Markdown content of SKILL.md.

Request example

curl -s -X POST "$BASE/api/v1/skills" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "adb-sql-review",
    "description": "ADB MySQL SQL review skill",
    "content": "# ADB SQL Review\n\n## When to use\nUse when reviewing SQL performance.\n\n## Rules\n1. Check for SELECT *\n2. Check for missing WHERE clauses\n"
  }' | jq .

Response

Response example:

{
  "name": "adb-sql-review",
  "action": "added",
  "path": "/path/.opencode/skills/adb-sql-review/SKILL.md"
}

The action field is added for new skills or updated for existing ones.

Set skill permissions

Request method: PATCH

Request path: /api/v1/skills/{name}/permission

Description: Control whether a skill is automatically available in AI conversations.

Request parameters

Permission values:

Value

Description

allow

Automatically allowed (default).

deny

Blocked — AI will not load this skill.

ask

Prompt user for confirmation before use.

Request example

# Disable a skill
curl -s -X PATCH "$BASE/api/v1/skills/adb-sql-review/permission" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"permission": "deny"}' | jq .

# Enable a skill
curl -s -X PATCH "$BASE/api/v1/skills/adb-sql-review/permission" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"permission": "allow"}' | jq .

Upload a skill via ZIP

Request method: POST

Request path: /api/v1/skills/upload

Description: Install a skill by uploading a ZIP file. The ZIP must contain a SKILL.md file in one of these structures:

  • SKILL.md at the ZIP root.

  • SKILL.md inside a single top-level directory (for example, my-skill/SKILL.md).

Request example

# Prepare and upload a skill ZIP
mkdir -p adb-sql-review
cat > adb-sql-review/SKILL.md << 'EOF'
---
name: adb-sql-review
description: ADB MySQL SQL review skill
---

# ADB SQL Review

## When to use
Use when reviewing SQL queries.
EOF

cd adb-sql-review && zip -r /tmp/adb-sql-review.zip . && cd -

# Upload to install
curl -s -X POST "$BASE/api/v1/skills/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@/tmp/adb-sql-review.zip" | jq .

/api/v1/skills/install is equivalent to /api/v1/skills/upload — you can use either endpoint.

Export a skill as ZIP

Request method: GET

Request path: /api/v1/skills/{name}/download

Description: Download an installed custom skill as a ZIP file for backup or sharing.

Request example

curl -s -o adb-sql-review.zip \
  "$BASE/api/v1/skills/adb-sql-review/download" \
  -H "Authorization: Bearer $TOKEN"

# Check contents
unzip -l adb-sql-review.zip
Note

Built-in skills (builtIn: true) cannot be exported and return a 403 error.

Delete a skill

Request method: DELETE

Request path: /api/v1/skills/{name}

Description: Permanently delete a custom skill and all its related files. This action cannot be undone.

Request example

curl -s -X DELETE "$BASE/api/v1/skills/adb-sql-review" \
  -H "Authorization: Bearer $TOKEN"
# Returns HTTP 204
Note

Built-in skills (builtIn: true) cannot be deleted.