Assistant API は、開発者に会話メッセージとツールの使用を管理するための一連のツールを提供します。このトピックでは、ペイントアシスタントをゼロから作成する手順を追いながら、Assistant API の基本的なコーディングテクニックについて説明します。
一般的なプロセス
アシスタントを開発するための一般的なプロセスは次のとおりです。
アシスタントの作成: アシスタントを作成する際、モデルを選択し、命令を入力し、コードインタープリター、関数呼び出しなどのツールを追加します。
スレッドの作成: ユーザーが対話を開始したときに、会話の継続性を維持するためにセッションスレッドを作成します。
スレッドへのメッセージ送信: ユーザーメッセージをセッションスレッドに 1 つずつ追加します。
実行の開始: セッションスレッドでアシスタントを実行します。アシスタントはメッセージを解釈し、適切なツールやサービスを使用して応答を生成し、ユーザーに応答を配信します。
シナリオ例
テキスト生成モデルだけでは画像を生成できません。代わりに、テキストから画像を生成するには text-to-image モデルが必要です。Assistant API で構築されたアシスタントは、ユーザーが提供したプロンプトを自動的に改善し、text-to-image ツールを使用して高品質の画像を生成できます。
手順
次のセクションは、非ストリーミング出力モードでの Python の包括的なガイドです。Python と Java のストリーミング出力と非ストリーミング出力の両方の完全なサンプルコードは、このトピックの最後にあります。詳細については、「完全なサンプルコード」をご参照ください。

ステップ 1: 開発環境の準備
| |
ステップ 2: アシスタントの作成DashScope SDK をインポートした後、アシスタントクラスの create メソッドを使用してアシスタントを作成します。次の主要なパラメーターを指定します。
text-to-image ツールは高い言語理解要件を持つため、アシスタントのセマンティック理解とテキスト生成能力を向上させるために、テキスト推論モデルとして Qwen-Max が選択されています。 アシスタントの名前、機能説明、命令などの詳細は、サンプルコードに表示されます。 公式プラグイン 画像生成 は、アシスタントがテキスト記述に基づいて自動的に画像を生成できるように設定されています。 アシスタントは無制限に作成できます。ただし、単一のモデルへの頻繁な呼び出しは、レート制限をトリガーする可能性があります。シナリオに基づいて、アシスタントに異なるモデルを設定できます。 使用ガイドについては、「アシスタント」をご参照ください。 | |
ステップ 3: スレッドの作成Assistant API では、スレッドは継続的な会話コンテキストを表します。 アシスタントはスレッドを使用して会話コンテキストを理解し、より一貫性のある関連性の高い応答を提供します。 次のことをお勧めします。
ペイントアシスタントのシナリオでは、スレッドは以下を含むプロセス全体を追跡します。
これにより、プロセスの一貫性と追跡可能性が保証されます。 使用ガイドについては、「スレッド」をご参照ください。 | |
ステップ 4: スレッドにメッセージを追加ユーザーからの入力メッセージは、メッセージオブジェクトを介して渡されます。Assistant API は、単一のスレッドに複数のメッセージを送信することをサポートしています。メッセージを作成する際には、次のパラメーターを指定します。
スレッドが受信できるトークンの数に制限はありません。ただし、モデルに渡されるトークンは、モデルの最大入力長に制限されます。詳細については、「テキスト生成モデルの概要」をご参照ください。 ペイントアシスタントのシナリオでは、メッセージを作成し、スレッドで「ラグドール猫の絵を描いてください。」と送信します。 使用ガイドについては、「メッセージ」をご参照ください。 説明 Messages.create() メソッドは、実行後に自動的にメッセージをスレッドに追加し、バックグラウンド処理をトリガーします。これにより、メッセージの作成と送信の両方の操作が同時に実行されます。これは API のデフォルトの動作です。 | |
ステップ 5: 実行の作成と実行メッセージが特定のスレッドに割り当てられた後、実行を開始してアシスタントをアクティブ化します。アシスタントは、指定されたモデルとプラグインをインテリジェントに使用して、コンテキストに基づいて質問に答えます。その後、アシスタントは応答をスレッドのメッセージシーケンスに挿入します。 次のステップを実行します。
この一連の操作により、質問の受け入れから結果の生成まで、アシスタントの処理フローが自動化されます。 使用ガイドについては、「実行」をご参照ください。 説明 複数のユーザーが同時にモデルを使用する可能性があり、処理時間が長くなる可能性があるため、続行する前にステータスが「complete」になるまで待機することをお勧めします。 | |
完全なサンプルコード
非ストリーミング出力
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」をご参照ください。