すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:Assistant API の使用を開始する

最終更新日:Oct 16, 2025

Assistant API は、開発者に会話メッセージとツールの使用を管理するための一連のツールを提供します。このトピックでは、ペイントアシスタントをゼロから作成する手順を追いながら、Assistant API の基本的なコーディングテクニックについて説明します。

一般的なプロセス

アシスタントを開発するための一般的なプロセスは次のとおりです。

  1. アシスタントの作成: アシスタントを作成する際、モデルを選択し、命令を入力し、コードインタープリター、関数呼び出しなどのツールを追加します。

  2. スレッドの作成: ユーザーが対話を開始したときに、会話の継続性を維持するためにセッションスレッドを作成します。

  3. スレッドへのメッセージ送信: ユーザーメッセージをセッションスレッドに 1 つずつ追加します。

  4. 実行の開始: セッションスレッドでアシスタントを実行します。アシスタントはメッセージを解釈し、適切なツールやサービスを使用して応答を生成し、ユーザーに応答を配信します。

シナリオ例

テキスト生成モデルだけでは画像を生成できません。代わりに、テキストから画像を生成するには text-to-image モデルが必要です。Assistant API で構築されたアシスタントは、ユーザーが提供したプロンプトを自動的に改善し、text-to-image ツールを使用して高品質の画像を生成できます。

手順

次のセクションは、非ストリーミング出力モードでの Python の包括的なガイドです。Python と Java のストリーミング出力と非ストリーミング出力の両方の完全なサンプルコードは、このトピックの最後にあります。詳細については、「完全なサンプルコード」をご参照ください。

image

ステップ 1: 開発環境の準備

  • プラグインの申請: まず、画像生成ツールを申請する必要があります。[プラグイン] に移動し、[画像生成] を見つけて [適用] をクリックします。

  • Python インタープリター: Assistant API には、Python インタープリターバージョン 3.8 以降が必要です。Python のバージョンを確認したり、特定のバージョンをインストールしたりするには、Python のダウンロードにアクセスしてください。

  • DashScope SDK: Assistant API には、DashScope SDK バージョン 1.17.0 以降が必要です。サンプルコマンドを実行してバージョンを確認するか、DashScope SDK をインストールします。

  • API キー: Assistant API には Model Studio の API キーが必要です。ここで API キーを取得します。また、漏洩を防ぐために API キーを環境変数として設定することをお勧めします。

# Python インタープリターのバージョンを確認
python --version 
# DashScope SDK を確認
pip list | grep dashscope 
# DashScope SDK バージョン 1.17.0 をインストール
pip install dashscope==1.17.0

ステップ 2: アシスタントの作成

DashScope SDK をインポートした後、アシスタントクラスの create メソッドを使用してアシスタントを作成します。次の主要なパラメーターを指定します。

  • model: アシスタントに使用されるモデルの名前。

  • name: アシスタントの名前。

  • description: アシスタントの機能説明。

  • instructions: 自然言語でアシスタントのロールとタスクを定義する命令。

  • tools: アシスタントに設定されたツール。

text-to-image ツールは高い言語理解要件を持つため、アシスタントのセマンティック理解とテキスト生成能力を向上させるために、テキスト推論モデルとして Qwen-Max が選択されています。

アシスタントの名前、機能説明、命令などの詳細は、サンプルコードに表示されます。

公式プラグイン 画像生成 は、アシスタントがテキスト記述に基づいて自動的に画像を生成できるように設定されています。

アシスタントは無制限に作成できます。ただし、単一のモデルへの頻繁な呼び出しは、レート制限をトリガーする可能性があります。シナリオに基づいて、アシスタントに異なるモデルを設定できます。

使用ガイドについては、「アシスタント」をご参照ください。

import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Qwen-Max でペイントアシスタントを作成
painting_assistant = dashscope.Assistants.create(
    model='qwen-max',  # 理解能力を向上させるために Qwen-Max を使用します。モデルリスト: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    name='Art Maestro',  # アシスタントの名前
    description='AI assistant for painting and art knowledge',
    instructions='''Provide information on painting techniques, art history, and creative guidance.''',
    tools=[
        {
            'type': 'text_to_image',  # 説明に基づいて画像を生成するツール
            'description': 'Use this tool to create visual examples of a painting style, technique, or art concept.'
        }
    ]
)

# アシスタント ID を出力して確認
print(f"Art Maestro created, ID: {painting_assistant.id}")

ステップ 3: スレッドの作成

Assistant API では、スレッドは継続的な会話コンテキストを表します。

アシスタントはスレッドを使用して会話コンテキストを理解し、より一貫性のある関連性の高い応答を提供します。

次のことをお勧めします。

  • 新しいユーザーまたは会話トピックごとに新しいスレッドを作成します。

  • コンテキストを維持するために同じスレッドを使用します。

  • コンテキストの混乱を防ぐために、会話トピックが大幅に変更された場合は、新しいスレッドの作成を検討してください。

ペイントアシスタントのシナリオでは、スレッドは以下を含むプロセス全体を追跡します。

  • ユーザーの最初のリクエスト

  • アシスタントからの提案

  • ユーザーのフィードバック

  • 最終的なペイント結果

これにより、プロセスの一貫性と追跡可能性が保証されます。

使用ガイドについては、「スレッド」をご参照ください。

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

# 空のスレッドを作成
thread = dashscope.Threads.create()

# スレッドが作成されたかどうかを確認
if thread.status_code == HTTPStatus.OK:
    print(f"Thread created, ID: {thread.id}")
    print("You can now start your dialogue with the assistant")
else:
    print(f"Failed to create thread. Status code: {thread.status_code}")
    print(f"Error code: {thread.code}")
    print(f"Error message: {thread.message}")

# 注: この空のスレッドは、ラグドール猫や他のペイント主題に関する将来のメッセージを含む、
# 議論のコンテキストを維持するために使用できます。

ステップ 4: スレッドにメッセージを追加

ユーザーからの入力メッセージは、メッセージオブジェクトを介して渡されます。Assistant API は、単一のスレッドに複数のメッセージを送信することをサポートしています。メッセージを作成する際には、次のパラメーターを指定します。

  • thread_id: スレッド ID。

  • content: メッセージの内容。

スレッドが受信できるトークンの数に制限はありません。ただし、モデルに渡されるトークンは、モデルの最大入力長に制限されます。詳細については、「テキスト生成モデルの概要」をご参照ください。

ペイントアシスタントのシナリオでは、メッセージを作成し、スレッドで「ラグドール猫の絵を描いてください。」と送信します。

使用ガイドについては、「メッセージ」をご参照ください。

説明

Messages.create() メソッドは、実行後に自動的にメッセージをスレッドに追加し、バックグラウンド処理をトリガーします。これにより、メッセージの作成と送信の両方の操作が同時に実行されます。これは API のデフォルトの動作です。

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

# アシスタントに何をするかを伝えるメッセージを作成
message = dashscope.Messages.create(thread.id, content='Draw a picture of a ragdoll cat.')

# メッセージが作成されたかどうかを確認
if message.status_code == HTTPStatus.OK:
    print('Message created, ID: %s' % message.id)
else:
    print('Failed to create message. Status code: %s, error code: %s, error message: %s' % (message.status_code, message.code, message.message))

ステップ 5: 実行の作成と実行

メッセージが特定のスレッドに割り当てられた後、実行を開始してアシスタントをアクティブ化します。アシスタントは、指定されたモデルとプラグインをインテリジェントに使用して、コンテキストに基づいて質問に答えます。その後、アシスタントは応答をスレッドのメッセージシーケンスに挿入します。

次のステップを実行します。

  1. 実行オブジェクトを初期化してペイントアシスタントをアクティブ化し、スレッド ID (thread.id) とアシスタント ID (assistant.id) を渡します。

  2. Run.wait メソッドを使用して、実行が完了するまで待機します。

  3. Messages.list メソッドを使用して、アシスタントから描画された画像を取得します。

この一連の操作により、質問の受け入れから結果の生成まで、アシスタントの処理フローが自動化されます。

使用ガイドについては、「実行」をご参照ください。

説明

複数のユーザーが同時にモデルを使用する可能性があり、処理時間が長くなる可能性があるため、続行する前にステータスが「complete」になるまで待機することをお勧めします。

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

# メッセージを実行するための新しい実行を作成
run = dashscope.Runs.create(thread.id, assistant_id=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, ID: %s' % run.id)

# 実行が完了するか、操作が必要になるまで待機
run = dashscope.Runs.wait(run.id, thread_id=thread.id)
if run.status_code != HTTPStatus.OK:
    print('Failed to obtain run status. Status code: %s, error code: %s, error message: %s' % (run.status_code, run.code, run.message))
else:
    print(run)

# スレッドメッセージを取得して実行出力を取得
msgs = dashscope.Messages.list(thread.id)
if msgs.status_code != HTTPStatus.OK:
    print('Failed to retrieve 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))

完全なサンプルコード

非ストリーミング出力

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} succeeded.")
        return True
    else:
        print(f"{operation} failed. Status code: {component.status_code}, Error code: {component.code}, Error message: {component.message}")
        return False


# 1. ペイントアシスタントの作成
painting_assistant = dashscope.Assistants.create(
    # モデルリスト: 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 to generate images.''',
    tools=[
        {'type': 'text_to_image', 'description': 'For creating visual examples'}
    ]
)

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

# 2. 新しいスレッドの作成
thread = dashscope.Threads.create()

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

# 3. スレッドにメッセージを送信
message = dashscope.Messages.create(thread.id, content='Draw a picture of a ragdoll cat.')

if not check_status(message, "create a message"):
    exit()

# 4. スレッドでアシスタントを実行
run = dashscope.Runs.create(thread.id, assistant_id=painting_assistant.id)

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

# 5. 実行が完了するのを待機
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. アシスタントの応答を取得して表示
messages = dashscope.Messages.list(thread.id)

if check_status(messages, "Message retrieval"):
    if messages.data:
        # 最後のメッセージ (アシスタントの応答) の内容を表示
        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.")

# 注: このコードは、ペイントアシスタントを作成し、ラグドール猫の描画に関する会話を開始し、
# アシスタントの応答を表示します。
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 + " succeeded.");
            return true;
        } else {
            System.out.println(operation + " failed.");
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 1. ペイントアシスタントの作成
            Assistants assistants = new Assistants();
            AssistantParam assistantParam = AssistantParam.builder()
                    // モデルリスト: 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 to research and generate images.")
                    .tools(Arrays.asList(ToolQuarkSearch.builder().build(),Text2Image.builder().build()))
                    .build();

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

            // 2. 新しいスレッドの作成
            Threads threads = new Threads();
            AssistantThread thread = threads.create(ThreadParam.builder().build());
            if (!checkStatus(thread, "Thread creation")) {
                System.exit(1);
            }

            // 3. スレッドにメッセージを送信
            Messages messages = new Messages();
            ThreadMessage message = messages.create(thread.getId(),
                    TextMessageParam.builder()
                            .role("user")
                            .content("Draw a picture of a ragdoll cat.")
                            .build());
            if (!checkStatus(message, "create a message")) {
                System.exit(1);
            }

            // 4. スレッドでアシスタントを実行
            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. 実行が完了するのを待機
            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. アシスタントの応答を取得して表示
            ListResult<ThreadMessage> messagesList = messages.list(thread.getId(), GeneralListParam.builder().build());
            if (checkStatus(messagesList, "Message retrieval")) {
                if (!messagesList.getData().isEmpty()) {
                    // 最後のメッセージ (アシスタントの応答) を表示
                    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();
        }
    }
}

ストリーミング出力

現在、Java SDK はストリーミング出力モードでの画像生成ツールをサポートしていません。

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} succeeded.")
        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. ペイントアシスタントの作成
def create_painting_assistant():
    return dashscope.Assistants.create(
        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 to research and to generate images.''',
        tools=[
            {'type': 'text_to_image', 'description': 'For creating visual examples'}
        ]
    )

if __name__ == '__main__':
    # ペイントアシスタントの作成
    painting_assistant = create_painting_assistant()
    print(painting_assistant)
    check_status(painting_assistant, "Assistant creation")

    # 初期メッセージを含む新しいスレッドを作成
    thread = dashscope.Threads.create(
        messages=[{
            'role': 'user',
            'content': 'Draw a picture of a ragdoll cat.'
        }]
    )
    print(thread)
    check_status(thread, "Thread creation")

    # ストリーミング実行を作成
    run_iterator = dashscope.Runs.create(
        thread.id,
        assistant_id=painting_assistant.id,
        stream=True
    )

    # イベントとメッセージを反復処理
    print("Processing request...")
    for event, msg in run_iterator:
        print(event)
        print(msg)

    # アシスタントの応答を取得して表示
    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))

# 注: このスクリプトは、ストリーミングペイントアシスタントを作成し、ラグドール猫の描画に関する会話を開始し、
# アシスタントの応答をリアルタイムで表示します。

次のステップ

パラメーターの詳細については、「Assistant API」をご参照ください。