Skip to content

Build an AI Painting Assistant with Assistant API

Reference, synced 2026-06-13.

flowchart TD
  n0["Models"]
  n1["Overview"]
  n2["Products"]
  n3["Solutions"]
  n4["Pricing"]
  n5["Resources"]
  n6["Partners"]
  n7["Support"]
  n8["Language"]
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n3 --> n4
  n4 --> n5
  n5 --> n6
  n6 --> n7
  n7 --> n8

Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works

Models

Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.

Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.

Try Visual Model \ Supports image understanding, image generation, and video generation.

Models

HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt

Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance

Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support

Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning

GenAI Application

Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.

AI Service

Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.

AI Use Case

AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.

AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.

Overview

As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.

Why Alibaba Cloud

About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.

Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure

Customers and Insights

Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud

What's New

Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases

Products

Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack

Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users

Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime

Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need

Solutions

Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions

Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability

New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey

Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech

Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies

Pricing

Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.

Overview & Tools

Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.

Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing

Optimize your cost

Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos

Resources

Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.

Technical Resources

Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI

Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology

Training&Certification

Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.

Developer Hub

Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community

Partners

Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.

Marketplace

AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner

Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs

Find a Partner

Partner Hub \ Find your ideal partner in no time

Become a Partner

Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs

Support

Full-lifecycle support and expert services, from cloud advisory and migration to operations.

Support & Professional Services

Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise

Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution

Contact us

Connect With Us \

Talk to a sales expert and get a custom quote for your business

Language

  • English
  • 简体中文
  • 繁體中文
  • 日本語
  • Bahasa Indonesia

Locale

Visit aliyun.com

Documentation

Alibaba Cloud Model Studio

User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)

Search for Help Content

Getting Started

The Beginner's Guide

Well-Architected Framework

AI & Machine Learning

Platform For AI

Alibaba Cloud Model Studio

DashVector

Artificial Intelligence Recommendation

OpenSearch

Image Search

Machine Translation

Intelligent Speech Interaction

Optimization Solver

Intelligent Computing LINGJUN

Computing

Elastic Compute Service

Elastic GPU Service

Elastic Container Instance

Dedicated Host

Compute Nest

Simple Application Server

Cloud Box

Auto Scaling

Elastic High Performance Computing

Batch Compute (Deprecated)

Function Compute

Serverless App Engine

ENS

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

Edge Network Acceleration

Alibaba Cloud Linux

AgentBay

Container

Container Service for Kubernetes

Container Compute Service

Container Registry

Storage

Object Storage Service

Cloud Parallel File Storage

File Storage NAS

Tablestore

Storage Capacity Unit

Simple Log Service

Cloud Backup

Intelligent Media Management

Drive and Photo Service

Data Transport

Cloud Storage Gateway

Data Online Migration

Hybrid Cloud Storage Array

Storage Services Overview

Backup and Disaster Recovery Center

Networking and CDN

Server Load Balancer

Elastic IP Address

Internet Shared Bandwidth

Data Transfer Plan

Virtual Private Cloud

NAT Gateway

PrivateLink

Alibaba Cloud DNS PrivateZone

Network Intelligence Service

Cloud Data Transfer

IPv6 Gateway

Anycast Elastic IP Address

Cloud Enterprise Network

Global Accelerator

VPN Gateway

Smart Access Gateway

Express Connect

CDN

Edge Security Acceleration

Cloud Network Well-architected Design Guidelines

Security

Anti-DDoS

Web Application Firewall

Cloud Firewall

Security Center

Bastionhost

Secure Access Service Edge

Certificate Management Service

Key Management Service

Data Security Center

Identity as a Service

Fraud Detection

AI Guardrails

Captcha

Blockchain as a Service

ID Verification

Managed Security Service

Middleware

Enterprise Distributed Application Service

Microservices Engine

Alibaba Cloud Service Mesh

SchedulerX

ApsaraMQ for RocketMQ

ApsaraMQ for Kafka

ApsaraMQ for RabbitMQ

ApsaraMQ for MQTT

Simple Message Queue (formerly MNS)

CloudFlow

EventBridge

Application Real-Time Monitoring Service

Managed Service for Prometheus

Managed Service for Grafana

Managed Service for OpenTelemetry

Performance Testing

STAROps

Databases

ApsaraDB Console

PolarDB

ApsaraDB RDS

ApsaraDB for OceanBase (Deprecated)

Tair (Redis® OSS-Compatible)

Lindorm

Time Series Database

ApsaraDB for MongoDB

ApsaraDB for HBase

ApsaraDB for Memcache

ApsaraDB for MyBase

AnalyticDB

ApsaraDB for ClickHouse

ApsaraDB for SelectDB

Data Transmission Service

Database Autonomy Service

Data Management

Database Gateway - Deprecated

ApsaraDB for Cassandra - Deprecated

Analytics Computing

MaxCompute

Hologres

Realtime Compute for Apache Flink

Elasticsearch

Vector Retrieval Service for Milvus

E-MapReduce

Data Lake Formation

DataV

Quick BI

Quick Audience

Quick Tracking

DataWorks

DataHub

Dataphin

Media Services

ApsaraVideo VOD

ApsaraVideo Live

Intelligent Media Services

ApsaraVideo Media Processing

Apsara Video SDK

Enterprise Services & Cloud Communication

Energy Expert

CloudQuotation

Salesforce on Alibaba Cloud

GoChina ICP Filing Assistant

Marketplace

Alibaba Mail

Direct Mail

Short Message Service

Voice Service

Phone Number Verification Service

Cell Phone Number Service

Chat App Message Service

Financial Intelligence Engine

Domain Names and Websites

Domain Names

ICP Filing

Alibaba Cloud DNS

End User Computing

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

AgentBay

Internet of Things

IoT Platform

Serverless

Serverless App Engine

CloudFlow

EventBridge

Simple Message Queue (formerly MNS)

Function Compute

Developer Tools

OpenAPI Explorer

Alibaba Cloud SDK

Cloud Shell

Resource Orchestration Service

Alibaba Cloud CLI

BSS OpenAPI

Terraform

Pulumi

Ticket System API

Mobile Platform as a Service

Alibaba Cloud DevOps

API Gateway

Cloud Control API

AI Coding Assistant Lingma

Cloud Skills Portal

Migration & O&M Management

CloudOps Orchestration Service

Cloud Monitor

Intelligent Advisor

Cloud Governance Center

ActionTrail

Cloud Config

Resource Access Management

Resource Management

Cloud Architect Design Tools

Migration Hub

Server Migration Center

Service Catalog

Logic Composer

Quota Center

CloudSSO

HTTPDNS

Solutions

SAP

SuperApp

OpenLake

Membership Service

Expenses and Costs

Account Center

More

Support

Legal

Tech Share Terms and Conditions

After Sales Support

China Gateway Program

Service Level Objectives

Management Console

Security Control

The Assistant API provides a set of development tools to help you easily manage conversation messages and call tools. This topic uses the example of building a painting assistant from scratch to help you quickly learn the basic encoding methods of the Assistant API.

Important

The Assistant API is being deprecated. Migrate to the Responses API as an alternative. The Responses API includes multiple built-in tools and supports multi-turn context management.

Typical process

The following is a typical process for building an agent application (Assistant):

  1. Create an Assistant: When you create an assistant, select a model, provide instructions, and add tools, such as a code interpreter and function calling.

  2. Create a Thread: When a user starts a conversation, create a session thread to track the conversation history.

  3. Send a Message to the Thread: Add the user's message to the conversation.

  4. Start a Run: Run the assistant on the session thread. The assistant parses the message, calls the appropriate tools or services, generates a response, and returns it to you.

Example scenario

Text generation models cannot generate images on their own. A specific text-to-image model is typically required to convert text into images. An agent application created with the Assistant API can automatically optimize the descriptive words provided by the user, call a text-to-image tool to generate high-quality images. For example, to generate a lifelike image of a pet cat, you only need to provide a basic description. The drawing assistant automatically refines the prompt and passes it directly to the text-to-image tool to efficiently complete the image creation task.

Procedure

The following steps guide you through the process in Python for the non-streaming output mode. For the complete Python and Java SDK code for both streaming and non-streaming output, see Complete code at the end of this topic.

### Step 1: Prepare the development environment - Request permission to use plugins: You must first request permission to use the Image Generation plugin. Go to the Plug-ins page in the Model Studio console and click Apply for Plug-in on the corresponding card. - Python interpreter: The Assistant API requires Python 3.8 or later. You can check your Python version. To install a specific version of Python, see Download Python. - DashScope SDK: We recommend that you use the latest version of the DashScope SDK. You can use the command on the right to check your version. To install a specific version of the DashScope SDK, use pip. - API key: The Assistant API requires an Alibaba Cloud Model Studio API key. You can get an API key here. When you use the DashScope SDK for the first time, we recommend that you configure the API key as an environment variable to avoid exposing sensitive information.bash # Check the Python interpreter version python --version ```bash # Check the DashScope SDK pip list
### Step 2: Create an Assistant After you import the Dashscope SDK, use the create method of the Assistant class to create an Assistant agent. This process involves setting the following key parameters: - model: the name of the large language model, used to configure the LLM for the agent - name: the name of the agent, used to distinguish it - description: a description of the agent's function - instructions: instructions in natural language that define the agent's role and task - tools: a list of tools configured for the agent In our example, the goal is to build an Assistant that focuses on painting. Because the text-to-image tool has high requirements for language understanding, we select Qwen-Max as the reasoning model to enhance the Assistant's semantic understanding and text generation capabilities. The configuration details of the agent, including its name, function description, and instructions, are clearly shown in the accompanying code snippet. To enrich the agent's functionality and practicality, we integrate the official pre-built plugin Image Generation. This ensures the agent can automatically generate corresponding image content based on the received text descriptions. You can create an unlimited number of Assistants. However, frequent calls to a single model may trigger rate limiting. We recommend that you configure different models for your Assistants based on their use cases. For more information about how to use the API, see Assistants API.python import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' # Create a new painting assistant using Qwen-Max painting_assistant = dashscope.Assistants.create( model='qwen-max', # Use the Qwen-Max model for enhanced understanding. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models name='Art Maestro', # The assistant's name is "Art Maestro" description='An AI assistant specializing in painting and art knowledge.', instructions='''You are an expert painting assistant. Provide detailed information about painting techniques, art history, and creative guidance.''', tools=[ { 'type': 'text_to_image', # A tool for generating images based on descriptions 'description': 'Use this tool to create visual examples of a painting style, technique, or art concept.' } ] ) # Print the assistant's ID to confirm successful creation print(f"Painting assistant 'Art Maestro' created successfully, ID: {painting_assistant.id}")

| ### Step 4: Add a Message to a Thread Your input is passed through a Message object. The Assistant API supports sending one or more messages to a single Thread. When you create a Message, consider the following parameters: - The unique ID of the Thread: thread_id - The content of the message: content Although there is no hard limit on the number of tokens a Thread can receive, the actual number of tokens passed to the LLM must comply with the model's maximum input length limit. For more information, see the official documentation for each Qwen series model regarding context length. In our scenario, you will send the first message in the Thread through a Message: "Please help me draw a picture of a ragdoll cat." You need to create a Message class. The detailed parameter settings are provided in the accompanying code snippet. For more information about how to use the API, see Messages. Note After the Messages.create() method is executed, it automatically adds the message to the thread and triggers spooling. This is equivalent to completing both the message creation and sending operations at the same time, which is the default behavior of the API. | python from http import HTTPStatus import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' # Create a message to tell the assistant what to do. message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a ragdoll cat.') # Check if the message was created successfully if message.status_code == HTTPStatus.OK: print('Message created successfully! Message ID: %s' % message.id) else: print('Message creation failed. Status code: %s, Error code: %s, Error message: %s' % (message.status_code, message.code, message.message)) | | ### Step 5: Create and execute a Run After a user assigns a message to a specific Thread, you can start a Run to activate the pre-set Assistant. The assistant uses all messages in the thread as context, utilizes the specified model and available plugins to intelligently respond to the user's questions, and inserts the generated answers into the thread's message sequence. In this scenario, perform the following steps: 1. Initialize a run object to drive the painting assistant, passing the thread ID (thread.id) and assistant ID (assistant.id). 2. Use the run object's wait method (Run.wait) until the execution is complete. 3. Use the message list method (Messages.list) to retrieve the pet cat picture drawn by the assistant. This series of operations ensures an automated processing flow for the assistant, from receiving a question to outputting a result. For more information about how to use the API, see Runs API. Note Many users may be using the model at the same time, which can extend the processing time. We recommend that you wait until the status shows "complete" before you perform the next operation to ensure a smooth process. | python from http import HTTPStatus import json import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' # Create a new run to execute the message run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id) if run.status_code != HTTPStatus.OK: print('Failed to create assistant, Status code: %s, Error code: %s, Error message: %s' % (run.status_code, run.code, run.message)) else: print('Assistant created successfully, ID: %s' % run.id) # Wait for the run to complete or require action run = dashscope.Runs.wait(run.id, thread_id=thread.id) if run.status_code != HTTPStatus.OK: print('Failed to get run status, Status code: %s, Error code: %s, Error message: %s' % (run.status_code, run.code, run.message)) else: print(run) # Get the thread messages to get the run output msgs = dashscope.Messages.list(thread.id) if msgs.status_code != HTTPStatus.OK: print('Failed to get messages, Status code: %s, Error code: %s, Error message: %s' % (msgs.status_code, msgs.code, msgs.message)) else: print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4)) |

Complete code

Non-streaming output

Streaming output

Python

Java

Python

python
import dashscope
from http import HTTPStatus
import json
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def check_status(component, operation):
    if component.status_code == HTTPStatus.OK:
        print(f"{operation} successful.")
        return True
    else:
        print(f"{operation} failed. Status code: {component.status_code}, Error code: {component.code}, Error message: {component.message}")
        return False

# 1. Create a painting assistant
painting_assistant = dashscope.Assistants.create(
    # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    model='qwen-max',
    name='Art Maestro',
    description='AI assistant for painting and art knowledge',
    instructions='''Provide information on painting techniques, art history, and creative guidance.
    Use tools for research and image generation.''',
    tools=[\
        {'type': 'text_to_image', 'description': 'For creating visual examples'}\
    ]
)

if not check_status(painting_assistant, "Assistant creation"):
    exit()

# 2. Create a new thread
thread = dashscope.Threads.create()

if not check_status(thread, "Thread creation"):
    exit()

# 3. Send a message to the thread
message = dashscope.Messages.create(thread.id, content='Please help me draw a picture of a ragdoll cat.')

if not check_status(message, "Message creation"):
    exit()

# 4. Run the assistant on the thread
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)

if not check_status(run, "Run creation"):
    exit()

# 5. Wait for the run to complete
print("Waiting for the assistant to process the request...")
run = dashscope.Runs.wait(run.id, thread_id=thread.id)

if check_status(run, "Run completion"):
    print(f"Run completed, status: {run.status}")
else:
    print("Run not completed.")
    exit()

# 6. Retrieve and display the assistant's response
messages = dashscope.Messages.list(thread.id)

if check_status(messages, "Message retrieval"):
    if messages.data:
        # Display the content of the last message (the assistant's response)
        last_message = messages.data[0]
        print("\nAssistant's response:")
        print(json.dumps(last_message, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))
    else:
        print("No messages found in the thread.")
else:
    print("Failed to retrieve the assistant's response.")

# Tip: This code creates a painting assistant, starts a conversation about how to draw a ragdoll cat,
# and displays the assistant's answer.

Java

java
package com.example;
import java.util.Arrays;
import com.alibaba.dashscope.protocol.Protocol;

import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.assistants.Assistants;
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.tools.T2Image.Text2Image;
import com.alibaba.dashscope.tools.search.ToolQuarkSearch;
import com.alibaba.dashscope.utils.Constants;

public class PaintingAssistant {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static boolean checkStatus(Object response, String operation) {
        if (response != null) {
            System.out.println(operation + " successful.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 1. Create a painting assistant
            Assistants assistants = new Assistants();
            AssistantParam assistantParam = AssistantParam.builder()
                    // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
                    .model("qwen-max")
                    .name("Art Maestro")
                    .description("AI assistant for painting and art knowledge")
                    .instructions("Provide information on painting techniques, art history, and creative guidance. Use tools for research and image generation.")
                    .tools(Arrays.asList(ToolQuarkSearch.builder().build(),Text2Image.builder().build()))
                    .build();

            Assistant paintingAssistant = assistants.create(assistantParam);
            if (!checkStatus(paintingAssistant, "Assistant creation")) {
                System.exit(1);
            }

            // 2. Create a new thread
            Threads threads = new Threads();
            AssistantThread thread = threads.create(ThreadParam.builder().build());
            if (!checkStatus(thread, "Thread creation")) {
                System.exit(1);
            }

            // 3. Send a message to the thread
            Messages messages = new Messages();
            ThreadMessage message = messages.create(thread.getId(),
                    TextMessageParam.builder()
                            .role("user")
                            .content("Please help me draw a picture of a ragdoll cat.")
                            .build());
            if (!checkStatus(message, "Message creation")) {
                System.exit(1);
            }

            // 4. Run the assistant on the thread
            Runs runs = new Runs();
            RunParam runParam = RunParam.builder().assistantId(paintingAssistant.getId()).build();
            Run run = runs.create(thread.getId(), runParam);
            if (!checkStatus(run, "Run creation")) {
                System.exit(1);
            }

            // 5. Wait for the run to complete
            System.out.println("Waiting for the assistant to process the request...");
            while (true) {
                if (run.getStatus().equals(Run.Status.COMPLETED) ||
                        run.getStatus().equals(Run.Status.FAILED) ||
                        run.getStatus().equals(Run.Status.CANCELLED) ||
                        run.getStatus().equals(Run.Status.REQUIRES_ACTION) ||
                        run.getStatus().equals(Run.Status.EXPIRED)) {
                    break;
                }
                Thread.sleep(1000);
                run = runs.retrieve(thread.getId(), run.getId());
            }

            if (checkStatus(run, "Run completion")) {
                System.out.println("Run completed, status: " + run.getStatus());
            } else {
                System.out.println("Run not completed.");
                System.exit(1);
            }

            // 6. Retrieve and display the assistant's response
            ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), GeneralListParam.builder().build());
            if (checkStatus(messagesList, "Message retrieval")) {
                if (!messagesList.getData().isEmpty()) {
                    // Display the last message (the assistant's response)
                    ThreadMessage lastMessage = messagesList.getData().get(0);
                    System.out.println("\nAssistant's response:");
                    System.out.println(lastMessage.getContent());
                } else {
                    System.out.println("No messages found in the thread.");
                }
            } else {
                System.out.println("Failed to retrieve the assistant's response.");
            }

        } catch (ApiException | NoApiKeyException | InputRequiredException | InvalidateParameter | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The Java SDK does not currently support streaming calls for the image generation tool.

Python

Java

Python

python
import dashscope
from http import HTTPStatus
import json
import sys
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def check_status(response, operation):
    if response.status_code == HTTPStatus.OK:
        print(f"{operation} successful.")
        return True
    else:
        print(f"{operation} failed. Status code: {response.status_code}, Error code: {response.code}, Error message: {response.message}")
        sys.exit(response.status_code)

# 1. Create a painting assistant
def create_painting_assistant():
    return dashscope.Assistants.create(
        # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        model='qwen-max',
        name='Art Maestro',
        description='AI assistant for painting and art knowledge',
        instructions='''Provide information on painting techniques, art history, and creative guidance.
        Use tools for research and image generation.''',
        tools=[\
            {'type': 'text_to_image', 'description': 'For creating visual examples'}\
        ]
    )

if __name__ == '__main__':
    # Create a painting assistant
    painting_assistant = create_painting_assistant()
    print(painting_assistant)
    check_status(painting_assistant, "Assistant creation")

    # Create a new thread with an initial message
    thread = dashscope.Threads.create(
        messages=[{\
            'role': 'user',\
            'content': 'Please help me draw a picture of a ragdoll cat.'\
        }]
    )
    print(thread)
    check_status(thread, "Thread creation")

    # Create a run with streaming output
    run_iterator = dashscope.Runs.create(
        thread.id,
        assistant_id=painting_assistant.id,
        stream=True
    )

    # Iterate over events and messages
    print("Processing request...")
    for event, msg in run_iterator:
        print(event)
        print(msg)

    # Retrieve and display the assistant's response
    messages = dashscope.Messages.list(thread.id)
    check_status(messages, "Message retrieval")

    print("\nAssistant's response:")
    print(json.dumps(messages, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))

# Tip: This script creates a painting assistant with streaming output, starts a conversation about drawing a ragdoll cat,
# and displays the assistant's responses in real time.

Java

java
import java.util.Arrays;
import com.alibaba.dashscope.protocol.Protocol;

import com.alibaba.dashscope.assistants.Assistant;
import com.alibaba.dashscope.assistants.AssistantParam;
import com.alibaba.dashscope.assistants.Assistants;
import com.alibaba.dashscope.common.GeneralListParam;
import com.alibaba.dashscope.common.ListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.InvalidateParameter;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.threads.AssistantThread;
import com.alibaba.dashscope.threads.ThreadParam;
import com.alibaba.dashscope.threads.Threads;
import com.alibaba.dashscope.threads.messages.Messages;
import com.alibaba.dashscope.threads.messages.TextMessageParam;
import com.alibaba.dashscope.threads.messages.ThreadMessage;
import com.alibaba.dashscope.threads.runs.AssistantStreamMessage;
import com.alibaba.dashscope.threads.runs.Run;
import com.alibaba.dashscope.threads.runs.RunParam;
import com.alibaba.dashscope.threads.runs.Runs;
import com.alibaba.dashscope.tools.T2Image.Text2Image;
import com.alibaba.dashscope.tools.search.ToolQuarkSearch;

import io.reactivex.Flowable;

public class PaintingAssistant {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static boolean checkStatus(Object response, String operation) {
        if (response != null) {
            System.out.println(operation + " successful.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    private static Assistant createPaintingAssistant() throws ApiException, NoApiKeyException {
        Assistants assistants = new Assistants();
        AssistantParam assistantParam = AssistantParam.builder()
            // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
            .model("qwen-max")
            .name("Art Maestro")
            .description("AI assistant for painting and art knowledge")
            .instructions("Provide information on painting techniques, art history, and creative guidance. Use tools for research and image generation.")
            .tools(Arrays.asList(ToolQuarkSearch.builder().build(), Text2Image.builder().build()))
            .build();

        return assistants.create(assistantParam);
    }

    private static void runPaintingAssistant(String assistantId) throws ApiException, NoApiKeyException, InvalidateParameter, InputRequiredException, InterruptedException {
        Threads threads = new Threads();
        AssistantThread thread = threads.create(ThreadParam.builder().build());
        if (!checkStatus(thread, "Thread creation")) {
            System.exit(1);
        }

        Messages messages = new Messages();
        ThreadMessage message = messages.create(thread.getId(),
            TextMessageParam.builder()
                .role("user")
                .content("Please help me draw a picture of a ragdoll cat.")
                .build());
        if (!checkStatus(message, "Message creation")) {
            System.exit(1);
        }

        Runs runs = new Runs();
        RunParam runParam = RunParam.builder().assistantId(assistantId).stream(true).build();

        try {
            System.out.println("Attempting to stream the assistant's response...");
            Flowable<AssistantStreamMessage> runFlowable = runs.createStream(thread.getId(), runParam);
            runFlowable.blockingForEach(assistantStreamMessage -> {
                System.out.println("Event: " + assistantStreamMessage.getEvent());
                System.out.println("Data: " + assistantStreamMessage.getData());
            });
        } catch (Exception e) {
            System.out.println("Streaming failed, switching to non-streaming method.");
            e.printStackTrace();

            // Switch to non-streaming method
            Run run = runs.create(thread.getId(), RunParam.builder().assistantId(assistantId).build());
            while (true) {
                if (run.getStatus().equals(Run.Status.COMPLETED) ||
                    run.getStatus().equals(Run.Status.FAILED) ||
                    run.getStatus().equals(Run.Status.CANCELLED) ||
                    run.getStatus().equals(Run.Status.REQUIRES_ACTION) ||
                    run.getStatus().equals(Run.Status.EXPIRED)) {
                    break;
                }
                Thread.sleep(1000);
                run = runs.retrieve(thread.getId(), run.getId());
            }
            System.out.println("Run completed, status: " + run.getStatus());
        }

        // Retrieve and display the assistant's response
        GeneralListParam listParam = GeneralListParam.builder().limit(100L).build();
        ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), listParam);
        if (checkStatus(messagesList, "Message retrieval")) {
            if (!messagesList.getData().isEmpty()) {
                System.out.println("\nAssistant's response:");
                for (ThreadMessage threadMessage : messagesList.getData()) {
                    System.out.println(threadMessage.getContent());
                }
            } else {
                System.out.println("No messages found in the thread.");
            }
        } else {
            System.out.println("Failed to retrieve the assistant's response.");
        }
    }

    public static void main(String[] args) {
        try {
            Assistant paintingAssistant = createPaintingAssistant();
            if (!checkStatus(paintingAssistant, "Assistant creation")) {
                System.exit(1);
            }

            runPaintingAssistant(paintingAssistant.getId());

        } catch (ApiException | NoApiKeyException | InputRequiredException | InvalidateParameter | InterruptedException e) {
            System.out.println("An error occurred while running the painting assistant:");
            e.printStackTrace();
        }
    }
}

What to do next

For detailed parameter explanations for Assistant API components, see Assistant API development reference.

Previous: FAQNext: Streaming output

Is this page helpful?

Typical process

Example scenario

Procedure

Step 1: Prepare the development environment

Step 2: Create an Assistant

Step 3: Create a Thread

Step 4: Add a Message to a Thread

Step 5: Create and execute a Run

Complete code

What to do next

Contact Us

Sales Support

Live-chat with our sales team or get in touch with a business development professional in your region.

Contact Sales

Technical Support

Open a ticket and get quick help from our technical team.

Open a Ticket >

Connect & Report Abuse

We look forward to your suggestion.

Post a Suggestion > Report Abuse >

\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.

Why Alibaba Cloud

About Alibaba Cloud

Asia Accelerator

Our Global Network

Global Offices

Trust Center

Case Studies

Analyst Reports

Products & Pricings

Pricing Calculator

ECS

SAS

Model Studio

Database

Security

SMS

Solutions

Financial Services

Retail Services

Media Services

Gaming Services

ISV Solutions

Engage

Developer Community

Partner Network

Startups

Marketplace

Join Alibaba Cloud

Resources & Support

Developer Learning Hub

Documentation Center

Training & Certification

Service Notices

Submit a Ticket

Security Report

Qwen Cloud

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links