Skip to main content

呼び出しの例 (非推奨)

このドキュメントでは、エージェントの使用方法を示す例を紹介します。

Assistant API は非推奨になりつつあります。代替として Responses API に移行してください。Responses API には、複数の組み込みツールが含まれており、マルチターンのコンテキスト管理をサポートしています。
以下の例を実行するには、Python SDK 1.18.0 以降および Java SDK 2.14.2 以降が必要です。Python SDK を更新するには、pip install -U dashscope コマンドを実行してください。

シンプルな Assistant の例

import os
import json
import sys
from http import HTTPStatus

from dashscope import Assistants, Messages, Runs, Threads
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def create_assistant():
    # 情報を使用してアシスタントを作成
    assistant = Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant.',  # noqa E501
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        print('Failed: ')
        print(res)
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant()
    print(assistant)
    verify_status_code(assistant)

    # スレッドを作成
    thread = Threads.create(
        messages=[{
            'role': 'user',
            'content': 'How to make delicious beef and potato stew?'
        }])
    print(thread)
    verify_status_code(thread)

    # 実行を作成
    run = Runs.create(thread.id, assistant_id=assistant.id)
    print(run)
    verify_status_code(run)
    # 実行が完了するか requires_action になるまで待機
    run_status = Runs.wait(run.id, thread_id=thread.id)
    print(run_status)

    # スレッドメッセージを取得
    msgs = Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))

シンプルな Assistant の例 (ストリーミング出力)

import os
import json
import sys
from http import HTTPStatus

from dashscope import Assistants, Messages, Runs, Threads
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def create_assistant():
    # 情報を使用してアシスタントを作成
    assistant = Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant.',  # noqa E501
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        print('Failed: ')
        print(res)
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant()
    print(assistant)
    verify_status_code(assistant)

    # スレッドを作成
    thread = Threads.create(
        messages=[{
            'role': 'user',
            'content': 'How to make delicious beef and potato stew?'
        }])
    print(thread)
    verify_status_code(thread)

    # ストリームで実行を作成
    run_iterator = Runs.create(thread.id,
                      assistant_id=assistant.id,
                      stream=True)
    # イベントとメッセージをイテレート
    for event, msg in run_iterator:
        print(event)
        print(msg)
    # スレッドメッセージを取得
    msgs = Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))

Assistant を使用した関数呼び出し

import os
import json
import sys
from http import HTTPStatus

from dashscope import Assistants, Messages, Runs, Steps, Threads
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def create_assistant_call_function():
    # 情報を使用してアシスタントを作成
    assistant = Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant. When asked a question, use tools wherever possible.',  # noqa E501
        tools=[{
            'type': 'function',
            'function': {
                'name': 'big_add',
                'description': 'Add to number',
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'left': {
                            'type': 'integer',
                            'description': 'The left operator'
                        },
                        'right': {
                            'type': 'integer',
                            'description': 'The right operator.'
                        }
                    },
                    'required': ['left', 'right']
                }
            }
        }],
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        print('Failed: ')
        print(res)
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant_call_function()
    print(assistant)
    verify_status_code(assistant)

    # スレッドを作成
    thread = Threads.create()
    print(thread)
    verify_status_code(thread)

    # メッセージを作成
    message = Messages.create(thread.id, content='Add 87787 to 788988737.')
    print(message)
    verify_status_code(message)

    # 新しい実行を作成してメッセージを実行

    message_run = Runs.create(thread.id, assistant_id=assistant.id)
    print(message_run)
    verify_status_code(message_run)

    # 実行ステータスを取得
    run_status = Runs.get(message_run.id, thread_id=thread.id)
    print(run_status)
    verify_status_code(run_status)

    # 実行が完了するか requires_action になるまで待機
    run_status = Runs.wait(message_run.id, thread_id=thread.id)
    print(run_status)

    # プロンプトがツール結果を入力する場合、ツール結果を送信
    # should call big_add
    if run_status.required_action:
        tool_outputs = [{
            'output':
            '789076524'
        }]
        run = Runs.submit_tool_outputs(message_run.id,
                                       thread_id=thread.id,
                                       tool_outputs=tool_outputs)
        print(run)
        verify_status_code(run)

        # 実行が完了するか requires_action になるまで待機
        run_status = Runs.wait(message_run.id, thread_id=thread.id)
        print(run_status)
        verify_status_code(run_status)

    run_steps = Steps.list(run.id,  thread_id=thread.id)
    print(run_steps)
    verify_status_code(run_steps)

    # スレッドメッセージを取得
    msgs = Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))

Assistant を使用した関数呼び出し (ストリーミング出力)

このセクションの Java の例では、description フィールドの実装を含む JSON スキーマの生成方法を示します。
# yapf: disable
import os
import json
import sys
from http import HTTPStatus

import dashscope
from dashscope import Assistants, Messages, Runs, Steps, Threads
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def create_assistant_call_function():
    # 情報を使用してアシスタントを作成
    assistant = Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant. When asked a question, use tools wherever possible.',  # noqa E501
        tools=[{
            'type': 'function',
            'function': {
                'name': 'big_add',
                'description': 'Add to number',
                'parameters': {
                    'type': 'object',
                    'properties': {
                        'left': {
                            'type': 'integer',
                            'description': 'The left operator'
                        },
                        'right': {
                            'type': 'integer',
                            'description': 'The right operator.'
                        }
                    },
                    'required': ['left', 'right']
                }
            }
        }],
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        print('Failed: ')
        print(res)
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant_call_function()
    print(assistant)
    verify_status_code(assistant)

    # 実行を作成
    run_iterator = Runs.create_thread_and_run(thread={'messages': [{
            'role': 'user',
            'content': 'What is transformer? Explain it in simple terms.'
        }]}, assistant_id=assistant.id, stream=True)
    thread = None
    for event, run in run_iterator:
        print(event)
        print(run)
        if event == 'thread.created':
            thread = run
    verify_status_code(run)

    run_status = Runs.get(run.id, thread_id=thread.id)
    print(run_status)
    verify_status_code(run_status)

    # 実行ステップをリスト
    run_steps = Steps.list(run.id, thread_id=thread.id)
    print(run_steps)
    verify_status_code(run_steps)

    # メッセージを作成
    message = Messages.create(thread.id, content='Add 87787 to 788988737.')
    print(message)
    verify_status_code(message)

    # 新しい実行を作成してメッセージを実行
    responses = Runs.create(thread.id, assistant_id=assistant.id, stream=True)
    for event, message_run in responses:
        print(event)
        print(message_run)
    verify_status_code(message_run)

    # 実行ステータスを取得
    run_status = Runs.get(message_run.id, thread_id=thread.id)
    print(run_status)
    verify_status_code(run_status)

    # プロンプトがツール結果を入力する場合、ツール結果を送信
    # should call big_add
    if run_status.required_action:
        tool_outputs = [{
            'output':
            '789076524'
        }]
        # ストリームで出力を送信
        responses = Runs.submit_tool_outputs(message_run.id,
                                             thread_id=thread.id,
                                             tool_outputs=tool_outputs,
                                             stream=True)
        for event, run in responses:
            print(event)
            print(run)
        verify_status_code(run)

    run_status = Runs.get(run.id, thread_id=thread.id)
    print(run_status)
    verify_status_code(run_status)

    run_steps = Steps.list(run.id,  thread_id=thread.id)

    print(run_steps)
    verify_status_code(run_steps)

    # スレッドメッセージを取得
    msgs = Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, ensure_ascii=False, default=lambda o: o.__dict__, sort_keys=True, indent=4))

Assistant を使用したツールの呼び出し

ツールを使用するには、権限をリクエストする必要がある場合があります。

サポートされているツールの一覧

ツール

機能

text_to_image

Text-to-Image ツールを呼び出して、プロンプトに基づいて画像を生成します。

code_interpreter

Code Interpreter プラグイン。

Text-to-Image の例

import os
import json
import sys
from http import HTTPStatus

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

def create_assistant():
    # 情報を使用してアシスタントを作成
    assistant = dashscope.Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant. When asked a question, use tools wherever possible.',  # noqa E501
        tools=[{
            'type': 'text_to_image'
        }],
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant()
    print(assistant)
    verify_status_code(assistant)

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

    # メッセージを作成
    message = dashscope.Messages.create(thread.id, content='Draw a picture of a cute kitten lying on the sofa.')
    print(message)
    verify_status_code(message)

    # 新しい実行を作成してメッセージを実行
    message_run = dashscope.Runs.create(thread.id, assistant_id=assistant.id)
    print(message_run)
    verify_status_code(message_run)

    # 実行ステータスを取得
    run = dashscope.Runs.get(message_run.id, thread_id=thread.id)
    print(run)
    verify_status_code(run)
    # 実行ステータスを出力し、実行が完了したことを確認
    print(run.status)

    # 実行が完了するか requires_action になるまで待機
    run = dashscope.Runs.wait(run.id, thread_id=thread.id)
    print(run)

    run = dashscope.Runs.get(run.id, thread_id=thread.id)
    print(run)
    verify_status_code(run)

    run_steps = dashscope.Steps.list(run.id, thread_id=thread.id)

    print(run_steps)
    verify_status_code(run_steps)

    # スレッドメッセージを取得
    msgs = dashscope.Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4, ensure_ascii=False))

Code Interpreter プラグインの呼び出し

import os
import json
import sys
from http import HTTPStatus

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

def create_assistant():
    # 情報を使用してアシスタントを作成
    assistant = dashscope.Assistants.create(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # この例では qwen-max を使用します。必要に応じてモデル名を変更できます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
        model='qwen-max',
        name='smart helper',
        description='A tool helper.',
        instructions='You are a helpful assistant. When asked a question, use tools wherever possible.',  # noqa E501
        tools=[{
            'type': 'code_interpreter'
        }],
    )

    return assistant

def verify_status_code(res):
    if res.status_code != HTTPStatus.OK:
        sys.exit(res.status_code)

if __name__ == '__main__':
    # アシスタントを作成
    assistant = create_assistant()
    print(assistant)
    verify_status_code(assistant)

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

    # メッセージを作成
    message = dashscope.Messages.create(thread.id, content='There are some chickens and rabbits in a cage. From the top, there are 100 heads. From the bottom, there are 334 feet. Use a tool to calculate how many chickens and rabbits are in the cage.')
    print(message)
    verify_status_code(message)

    # 新しい実行を作成してメッセージを実行
    message_run = dashscope.Runs.create(thread.id, assistant_id=assistant.id)
    print(message_run)
    verify_status_code(message_run)

    # 実行ステータスを取得
    run = dashscope.Runs.get(message_run.id, thread_id=thread.id)
    print(run)
    verify_status_code(run)
    # 実行ステータスを出力し、実行が完了したことを確認
    print(run.status)

    # 実行が完了するか requires_action になるまで待機
    run = dashscope.Runs.wait(run.id, thread_id=thread.id)
    print(run)

    run = dashscope.Runs.get(run.id, thread_id=thread.id)
    print(run)
    verify_status_code(run)

    run_steps = dashscope.Steps.list(run.id, thread_id=thread.id)

    print(run_steps)
    verify_status_code(run_steps)

    # スレッドメッセージを取得
    msgs = dashscope.Messages.list(thread.id)
    print(msgs)
    print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4, ensure_ascii=False))