All Products
Search
Document Center

E-MapReduce:Call the EMR AI Assistant API

Last Updated:Aug 20, 2026

EMR AI Assistant is a conversational AI service. You can use natural language to submit requests through an API to automatically perform slow SQL diagnosis and health checks on your Serverless StarRocks instances and receive optimization suggestions. This topic describes how to call the EMR AI Assistant API using the Python SDK.

Features

EMR AI Assistant provides the following core features:

  • Slow SQL diagnosis: Identifies the longest-running queries, pinpoints performance bottlenecks, and provides optimization suggestions.

  • Health check: Performs a comprehensive check on your instance, and outputs a health score, a list of issues, and improvement suggestions.

You can submit requests in natural language without having to manually construct API calls or configure task parameters.

Step 1: Install dependencies

Run the following command to install the Alibaba Cloud OpenAPI SDK:

pip install alibabacloud_tea_openapi alibabacloud_tea_util

Step 2: Configure your AccessKey

Configure your Alibaba Cloud AccessKey using environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your_access_key_id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your_access_key_secret>
Important
  • The EMR AI Assistant uses this account's identity to access data and can only access instances owned by the account. Ensure the EMR AI Assistant service is activated for this account and that it has permission to access the target instance.

  • Do not hard-code your AccessKey in your code. We recommend passing credentials using environment variables for improved security.

Step 3: Write the client code

Replace ENDPOINT in the following code with the endpoint for your instance's region.

Supported regions

Region

Region ID

Endpoint

China (Hangzhou)

cn-hangzhou

emrassistant.cn-hangzhou.aliyuncs.com

China (Shanghai)

cn-shanghai

emrassistant.cn-shanghai.aliyuncs.com

China (Qingdao)

cn-qingdao

emrassistant.cn-qingdao.aliyuncs.com

China (Beijing)

cn-beijing

emrassistant.cn-beijing.aliyuncs.com

China (Hohhot)

cn-huhehaote

emrassistant.cn-huhehaote.aliyuncs.com

China (Ulanqab)

cn-wulanchabu

emrassistant.cn-wulanchabu.aliyuncs.com

China (Shenzhen)

cn-shenzhen

emrassistant.cn-shenzhen.aliyuncs.com

China (Chengdu)

cn-chengdu

emrassistant.cn-chengdu.aliyuncs.com

Singapore

ap-southeast-1

emrassistant.ap-southeast-1.aliyuncs.com

Complete client code

import json
import os
import sys

from alibabacloud_tea_openapi.client import Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models

# ENDPOINT: The endpoint for your instance's region. 
# For a complete list, see the table above.
ENDPOINT = "emrassistant.cn-hangzhou.aliyuncs.com"


def create_client() -> Client:
    return Client(open_api_models.Config(
        access_key_id=os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
        access_key_secret=os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
        endpoint=ENDPOINT,
    ))


_PARAMS = open_api_models.Params(
    action="ChatCompletion", version="2025-07-23", protocol="HTTPS",
    method="POST", pathname="/v1/chat/completions",
    auth_type="AK", style="ROA", req_body_type="json", body_type="json",
)


def chat(client: Client, question: str, session_id: str = None) -> str:
    """Sends a question to the assistant and streams the response. Returns a session ID for follow-up questions."""
    body = {"stream": True, "messages": [{"role": "user", "content": question}]}
    if session_id:
        body["sessionId"] = session_id

    request = open_api_models.OpenApiRequest(body=body)
    runtime = util_models.RuntimeOptions(connect_timeout=10_000, read_timeout=300_000)

    try:
        for resp in client.call_sseapi(_PARAMS, request, runtime):
            data = resp.event.data if resp.event else None
            if not data or data == "[DONE]":      # [DONE]: Marks the end of the response stream.
                continue
            msg = json.loads(data)
            if msg.get("type") == "run_started":
                session_id = msg.get("sessionId")        # Capture the session ID.
            elif msg.get("type") == "text":
                sys.stdout.write(msg.get("text", ""))    # Stream output in real time.
                sys.stdout.flush()
    except Exception as e:
        print(f"\n[API call failed] {e}", file=sys.stderr)
        print("Check that your AccessKey is correct, the EMR AI Assistant service is activated, "
              "and the endpoint matches your instance's region.", file=sys.stderr)
        return session_id
    print()
    return session_id

Usage examples

Provide the instance ID (starting with c-) and its region in your question. The assistant uses this information to automatically locate the target instance.

Slow SQL diagnosis

client = create_client()
chat(client,
     "My Serverless StarRocks instance c-xxxxxxxx (cn-hangzhou) has been slow recently. "
     "Help me diagnose the top slow SQL queries, identify bottlenecks, and provide optimization suggestions.")

The assistant automatically identifies the longest-running queries, locates SQL patterns that consume high resources, analyzes trends, and provides optimization suggestions for specific slow queries.

Health check

client = create_client()
chat(client,
     "Perform a health check on Serverless StarRocks instance c-xxxxxxxx (cn-hangzhou) and generate a report.")

The assistant performs a comprehensive check on the instance and outputs a health score, a list of anomalies, and improvement suggestions.

Sample output

The following examples show the actual output. Instance information is redacted for privacy.

Slow SQL diagnosis output

The assistant automatically locates the instance, retrieves the queries that recently consumed the most resources, and provides a profile-level diagnosis:

Instance: c-xxxxxxxx (StarRocks 3.2.4, Running)
Most CPU-intensive query in the last hour: An information_schema metadata query
Diagnosis: Total time 102 ms / CPU 43.5 ms / Peak memory 3.21 MB / Wait ratio 80.88%
Bottleneck operators: SCHEMA_SCAN(node 7) 9.26 ms, SCHEMA_SCAN(node 0) 8.16 ms, HASH_JOIN(node 5) 1.28 MB
Conclusion: This query has a low workload and does not require optimization. If it occurs frequently, we recommend that you cache metadata on the client or use a connection pool.

Health check output

Instance: c-xxxxxxxx (StarRocks 3.2.4, onBareMetal / lakehouse, Running)
Health score: 100/100
Key metrics: Last 24h: Critical 0 / Warning 0 / Info 0. The overall stability is excellent.
Anomalies: None
Improvement suggestions: Evaluate a version upgrade, enable automatic minor version upgrades, set up regular health checks and alerts, and assess resource specifications based on business growth.

Multi-turn conversations

The chat() function returns a session ID. You can pass this ID in subsequent calls to continue the conversation in the same context. For example, if you do not specify an instance in your first request, the assistant asks for it, and you can provide the information in the next turn:

client = create_client()

# Turn 1: No instance is specified, so the assistant asks which instance to diagnose.
sid = chat(client, "Help me diagnose slow SQL queries in StarRocks.")

# Turn 2: Pass the session ID back and provide the instance information.
chat(client, "The instance is c-xxxxxxxx, in cn-hangzhou", session_id=sid)

Best practices

Specify the task and target

The assistant decides whether to call the diagnostic API based on your prompt. Include both an action and a target:

  • Action: Use clear verbs, such as check, diagnose, identify, or optimize.

  • Target: The instance ID (which starts with c-) and its region.

If you provide both, the assistant triggers a diagnosis. If either is missing, the request falls back to knowledge-based Q&A, and no instance data is retrieved.

Type

Example prompt

Assistant behavior

Instance diagnosis

"Perform a health check on instance c-xxxxxxxx (cn-wulanchabu)."

Connects to the instance and retrieves real data.

Knowledge-based Q&A

"What is the difference between the shared-data architecture and shared-nothing architecture in StarRocks?"

Answers based on product knowledge without calling the diagnostic API.

Understand the response

The data collected and the results returned vary based on your request:

Request

Data collected

Output

Health check

Health events and monitoring metrics, such as CPU, memory, JVM, disk I/O, and query performance.

A health score, a list of issues, and improvement suggestions.

Slow SQL diagnosis

FE audit log and aggregated SQL pattern data.

Top slow queries, bottleneck identification, and optimization suggestions.

Interpret empty results correctly

If an instance has a low query volume, a slow SQL diagnosis may return "no significant slow queries found", and a health check may report "low workload and sufficient resources". This means the instance is healthy and does not indicate an API call failure.

Advanced: Directly route to the StarRocks agent

By default, EMR AI Assistant first identifies your intent and then forwards the request to the appropriate sub-assistant. If your workflow involves only Serverless StarRocks, you can specify ServerlessStarrocksV3Agent for the model parameter in the request body. This bypasses the intent routing process, improving diagnostic stability:

# Add the model field to the existing body.
body = {
    "stream": True,
    "model": "ServerlessStarrocksV3Agent",   # Directly route the request to the StarRocks agent.
    "messages": [{"role": "user",
                  "content": "Perform a health check on instance c-xxxxxxxx (cn-wulanchabu) and generate a report."}],
}

Model parameter

Description

Not specified or set to emr-assistant

The default intent routing is used. This is suitable for scenarios where it is difficult to determine the target agent.

ServerlessStarrocksV3Agent

The request is sent directly to the StarRocks agent. This is suitable for dedicated workflows that involve only StarRocks diagnosis or health checks.