Alibaba Cloud の Model Studio が提供する Qwen モデルは、OpenAI 互換のインターフェイスをサポートしています。既存の OpenAI コードは、API キー、base_url、モデル名を更新するだけで Model Studio に移行できます。
必要な情報
base_url
base_url は、モデルサービスのネットワークエンドポイントです。このアドレスにより、サービスが提供する機能やデータにアクセスできます。Web サービスや API を使用する場合、base_url は通常、API のルート URL であり、特定のエンドポイントが追加されます。OpenAI 互換インターフェイスを使用して Model Studio を呼び出す際には、base_url を設定する必要があります。
OpenAI SDK またはその他の OpenAI 互換 SDK を使用して呼び出しを行う場合、base_url を次のように設定します。
シンガポール:https://dashscope-intl.aliyuncs.com/compatible-mode/v1 バージニア:https://dashscope-us.aliyuncs.com/compatible-mode/v1 北京:https://dashscope.aliyuncs.com/compatible-mode/v1HTTP リクエストを使用して呼び出しを行う場合は、完全なアクセスエンドポイントを次のように設定します。
シンガポール:POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions バージニア:POST https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions 北京:POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
サポートされているモデル
次の表に、OpenAI 互換インターフェイスで現在サポートされている Qwen モデルを示します。
グローバル
商用版
Qwen-Max シリーズ:qwen3-max、qwen3-max-preview、qwen3-max-2025-09-23 以降のスナップショットモデル
Qwen-Plus シリーズ:qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25 以降のスナップショットモデル
Qwen-Flash シリーズ:qwen-flash、qwen-flash-2025-07-28 以降のスナップショットモデル
オープンソース版
qwen3-next-80b-a3b-thinking、qwen3-next-80b-a3b-instruct、qwen3-235b-a22b-thinking-2507、qwen3-235b-a22b-instruct-2507、qwen3-30b-a3b-thinking-2507、qwen3-30b-a3b-instruct-2507、qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b、qwen3-14b、qwen3-8b
国際
商用版
Qwen-Max シリーズ:qwen3-max、qwen3-max-preview、qwen3-max-2025-09-23 以降のスナップショットモデル、qwen-max、qwen-max-latest、qwen-max-2025-01-25 以降のスナップショットモデル
Qwen-Plus シリーズ:qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25 以降のスナップショットモデル
Qwen-Flash シリーズ:qwen-flash、qwen-flash-2025-07-28 以降のスナップショットモデル
Qwen-Turbo シリーズ:qwen-turbo、qwen-turbo-latest、qwen-turbo-2024-11-01 以降のスナップショットモデル
Qwen-Coder シリーズ:qwen3-coder-plus、qwen3-coder-plus-2025-07-22 以降のスナップショットモデル、qwen3-coder-flash、qwen3-coder-flash-2025-07-28 以降のスナップショットモデル
QwQ シリーズ:qwq-plus
オープンソース版
qwen3-next-80b-a3b-thinking、qwen3-next-80b-a3b-instruct、qwen3-235b-a22b-thinking-2507、qwen3-235b-a22b-instruct-2507、qwen3-30b-a3b-thinking-2507、qwen3-30b-a3b-instruct-2507、qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b、qwen3-14b、qwen3-8b、qwen3-4b、qwen3-1.7b、qwen3-0.6b
qwen2.5-14b-instruct-1m、qwen2.5-7b-instruct-1m、qwen2.5-72b-instruct、qwen2.5-32b-instruct、qwen2.5-14b-instruct、qwen2.5-7b-instruct
米国
商用版
Qwen-Plus シリーズ:qwen-plus-us、qwen-plus-2025-12-01-us 以降のスナップショットモデル
Qwen-Flash シリーズ:qwen-flash-us、qwen-flash-2025-07-28-us
中国本土
商用版
Qwen-Max シリーズ:qwen3-max、qwen3-max-preview、qwen3-max-2025-09-23 以降のスナップショットモデル、qwen-max、qwen-max-latest、qwen-max-2024-09-19 以降のスナップショットモデル
Qwen-Plus シリーズ:qwen-plus、qwen-plus-latest、qwen-plus-2024-08-06 以降のスナップショットモデル
Qwen-Flash シリーズ:qwen-flash、qwen-flash-2025-07-28 以降のスナップショットモデル
Qwen-Turbo シリーズ:qwen-turbo、qwen-turbo-latest、qwen-turbo-2025-04-28 以降のスナップショットモデル
Qwen-Coder シリーズ:qwen3-coder-plus、qwen3-coder-plus-2025-07-22 以降のスナップショットモデル、qwen3-coder-flash、qwen3-coder-flash-2025-07-28 以降のスナップショットモデル、qwen-coder-plus、qwen-coder-plus-latest、qwen-coder-plus-2024-11-06、qwen-coder-turbo、qwen-coder-turbo-latest、qwen-coder-turbo-2024-09-19
QwQ シリーズ:qwq-plus、qwq-plus-latest、qwq-plus-2025-03-05
Qwen-Math:qwen-math-plus、qwen-math-plus-latest、qwen-math-plus-2024-08-16 以降のスナップショットモデル、qwen-math-turbo、qwen-math-turbo-latest、qwen-math-turbo-2024-09-19
オープンソース版
qwen3-next-80b-a3b-thinking、qwen3-next-80b-a3b-instruct、qwen3-235b-a22b-thinking-2507、qwen3-235b-a22b-instruct-2507、qwen3-30b-a3b-thinking-2507、qwen3-30b-a3b-instruct-2507、qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b、qwen3-14b、qwen3-8b、qwen3-4b、qwen3-1.7b、qwen3-0.6b
qwen2.5-14b-instruct-1m、qwen2.5-7b-instruct-1m、qwen2.5-72b-instruct、qwen2.5-32b-instruct、qwen2.5-14b-instruct、qwen2.5-7b-instruct、qwen2.5-3b-instruct、qwen2.5-1.5b-instruct、qwen2.5-0.5b-instruct
OpenAI SDK を使用する
前提条件
お使いのコンピューターに Python 環境がインストールされていることを確認してください。
最新バージョンの OpenAI SDK をインストールします。
# 次のコマンドでエラーが報告された場合は、pip を pip3 に置き換えてください。 pip install -U openaiModel Studio をアクティベートし、API キーを作成します:API キーの取得。
API キーの漏洩リスクを減らすために、API キーを環境変数として設定することをお勧めします。詳細については、「API キーを環境変数として設定する」をご参照ください。コードで API キーを設定することもできますが、これにより漏洩のリスクが高まります。
使用するモデルを選択します:モデルの可用性。
使用方法
次の例は、OpenAI SDK を使用して Alibaba Cloud Model Studio の Qwen モデルにアクセスする方法を示しています。
非ストリーミング呼び出しの例
from openai import OpenAI
import os
def get_response():
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、この行を Model Studio の API キーを使用して api_key="sk-xxx" に置き換えてください。
# 以下はシンガポールリージョンの base_url です。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus", # この例では qwen-plus を使用します。必要に応じてモデル名を置き換えることができます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}]
)
print(completion.model_dump_json())
if __name__ == '__main__':
get_response()コードを実行すると、次の結果が生成されます。
{
"id": "chatcmpl-xxx",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"message": {
"content": "I am a large-scale pre-trained model from Alibaba Cloud. My name is Qwen.",
"role": "assistant",
"function_call": null,
"tool_calls": null
}
}
],
"created": 1716430652,
"model": "qwen-plus",
"object": "chat.completion",
"system_fingerprint": null,
"usage": {
"completion_tokens": 18,
"prompt_tokens": 22,
"total_tokens": 40
}
}ストリーミング呼び出しの例
from openai import OpenAI
import os
def get_response():
client = OpenAI(
# 環境変数を設定していない場合は、この行を Model Studio の API キーを使用して api_key="sk-xxx" に置き換えてください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下はシンガポールリージョンの base_url です。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus", # この例では qwen-plus を使用します。必要に応じてモデル名を置き換えることができます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}],
stream=True,
# 次の設定を使用して、ストリーミング出力の最終行にトークン使用情報を表示します。
stream_options={"include_usage": True}
)
for chunk in completion:
print(chunk.model_dump_json())
if __name__ == '__main__':
get_response()
コードを実行すると、次の結果が生成されます。
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"","function_call":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"I am a","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":" large language model from","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":" Alibaba","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":" Cloud.","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":" My name is Qwen.","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"","function_call":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[],"created":1719286190,"model":"qwen-plus","object":"chat.completion.chunk","system_fingerprint":null,"usage":{"completion_tokens":16,"prompt_tokens":22,"total_tokens":38}}関数呼び出しの例
このセクションでは、天気と時刻のクエリツールを使用して、OpenAI 互換インターフェイスでツール呼び出し機能を実装する方法の例を示します。サンプルコードは、複数ラウンドのツール呼び出しをサポートしています。
from openai import OpenAI
from datetime import datetime
import json
import os
client = OpenAI(
# 環境変数を設定していない場合は、この行を Model Studio の API キーを使用して api_key="sk-xxx" に置き換えてください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下はシンガポールリージョンの base_url です。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# ツールリストを定義します。モデルは、使用するツールを選択する際に、ツールの名前と説明を参照します。
tools = [
# ツール 1:現在時刻を取得します。
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "現在時刻を知りたいときに便利です。",
# 現在時刻の取得には入力パラメーターが不要なため、parameters は空の辞書です。
"parameters": {}
}
},
# ツール 2:指定された都市の天気を取得します。
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "特定の都市の天気を照会するのに便利です。",
"parameters": {
"type": "object",
"properties": {
# 天気を照会するには場所を指定する必要があるため、パラメーターは location に設定されます。
"location": {
"type": "string",
"description": "北京、杭州、余杭区などの都市または郡。"
}
}
},
"required": [
"location"
]
}
}
]
# 天気クエリツールをシミュレートします。サンプル結果:「今日の北京は雨です。」
def get_current_weather(location):
return f"今日の {location} は雨です。"
# 現在時刻を照会するツール。サンプル結果:「現在時刻:2024-04-15 17:15:18。」
def get_current_time():
# 現在の日付と時刻を取得します。
current_datetime = datetime.now()
# 現在の日付と時刻をフォーマットします。
formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
# フォーマットされた現在時刻を返します。
return f"現在時刻:{formatted_time}。"
# モデル応答関数をカプセル化します。
def get_response(messages):
completion = client.chat.completions.create(
model="qwen-plus", # この例では qwen-plus を使用します。必要に応じてモデル名を置き換えることができます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
messages=messages,
tools=tools
)
return completion.model_dump()
def call_with_messages():
print('\n')
messages = [
{
"content": input('クエリを入力してください:'), # サンプル質問:「今何時ですか?」「1時間後は何時になりますか?」「北京の天気は?」
"role": "user"
}
]
print("-"*60)
# モデル呼び出しの第 1 ラウンド。
i = 1
first_response = get_response(messages)
assistant_output = first_response['choices'][0]['message']
print(f"\n第 {i} ラウンドの大規模モデル出力:{first_response}\n")
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
# 呼び出すツールがない場合は、最終的な回答を直接返します。
if assistant_output['tool_calls'] == None: # モデルがツールを呼び出す必要がないと判断した場合、アシスタントの返信を直接出力します。モデル呼び出しの第 2 ラウンドは不要です。
print(f"ツール呼び出しは不要です。直接回答できます:{assistant_output['content']}")
return
# ツールを呼び出す必要がある場合は、モデルがツールを呼び出す必要がないと判断するまで、複数ラウンドのモデル呼び出しを実行します。
while assistant_output['tool_calls'] != None:
# モデルが天気クエリツールを呼び出す必要があると判断した場合、天気クエリツールを実行します。
if assistant_output['tool_calls'][0]['function']['name'] == 'get_current_weather':
tool_info = {"name": "get_current_weather", "role":"tool"}
# location パラメーター情報を抽出します。
location = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['location']
tool_info['content'] = get_current_weather(location)
# モデルが時刻クエリツールを呼び出す必要があると判断した場合、時刻クエリツールを実行します。
elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_time':
tool_info = {"name": "get_current_time", "role":"tool"}
tool_info['content'] = get_current_time()
print(f"ツール出力:{tool_info['content']}\n")
print("-"*60)
messages.append(tool_info)
assistant_output = get_response(messages)['choices'][0]['message']
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
i += 1
print(f"第 {i} ラウンドの大規模モデル出力:{assistant_output}\n")
print(f"最終回答:{assistant_output['content']}")
if __name__ == '__main__':
call_with_messages()How is the weather in Singapore? What time is it now? と入力すると、プログラムは次の出力を返します。

入力パラメーター
入力パラメーターは OpenAI インターフェイスパラメーターと整合しています。次のパラメーターがサポートされています。
パラメーター | タイプ | デフォルト | 説明 |
model | string | - | 使用するモデルを指定します。利用可能なモデルのリストについては、「サポートされているモデルリスト」をご参照ください。 |
messages | array | - | ユーザーとモデル間の会話履歴。配列の各要素は |
top_p (オプション) | float | - | 核サンプリングの確率しきい値。たとえば、このパラメーターを 0.8 に設定すると、モデルは累積確率が 0.8 以上のトップトークンの最小セットからトークンを生成します。有効な値: (0, 1.0)。値が大きいほどランダム性が高くなります。値が小さいほど決定性が高くなります。 |
temperature (オプション) | float | - | モデルの応答のランダム性と多様性をコントロールします。temperature の値を高くすると、候補単語の確率分布が平滑化され、確率の低い単語が選択されやすくなり、より多様な結果が生成されます。temperature の値を低くすると、確率分布がシャープになり、確率の高い単語が選択されやすくなり、より決定的な結果が生成されます。 有効な値: [0, 2)。値を 0 に設定しないことをお勧めします。 |
presence_penalty (オプション) | float | - | 生成されたコンテンツ内のシーケンス全体の繰り返しをコントロールします。presence_penalty の値が高いほど、繰り返しが減少します。有効な値: [-2.0, 2.0]。 説明 現在、このパラメーターは Qwen 商用モデルおよび qwen1.5 以降のオープンソースモデルでのみサポートされています。 |
n (オプション) | integer | 1 | 生成する応答の数。有効な値: 1 から n の値を大きくしても入力トークンの消費量は増加しませんが、出力トークンの消費量は増加します。 現在、このパラメーターは qwen-plus モデルでのみサポートされています。tools パラメーターが渡される場合、値は 1 である必要があります。 |
max_tokens (オプション) | integer | - | モデルが生成できるトークンの最大数。たとえば、モデルの最大出力長が 2,000 トークンの場合、このパラメーターを 1,000 に設定して、モデルが過度に長いコンテンツを生成するのを防ぐことができます。 モデルによって出力制限は異なります。詳細については、モデルリストをご参照ください。 |
seed (オプション) | integer | - | 生成中に使用される乱数シードで、生成されるコンテンツのランダム性をコントロールします。seed パラメーターは、符号なし 64 ビット整数をサポートします。 |
stream (オプション) | boolean | False | ストリーミング出力を使用するかどうかを指定します。結果がストリーミングされると、API はジェネレーターを返します。結果を取得するには反復処理が必要です。各出力は、現在生成されている増分シーケンスです。 |
stop (オプション) | string or array | None | stop パラメーターは、コンテンツ生成プロシージャを正確にコントロールします。モデルは、指定された文字列またはトークン ID を含もうとすると、コンテンツの生成を自動的に停止します。stop パラメーターは、文字列または配列にすることができます。
|
tools (オプション) | array | None | モデルが呼び出すことができるツールライブラリを指定します。ツール呼び出しプロセスでは、モデルはライブラリから 1 つのツールを選択します。tools 配列内の各ツールの構造は次のとおりです。
ツール呼び出しプロセスでは、ツール呼び出しのラウンドを開始するときと、ツール関数の実行結果をモデルに送信するときの両方で tools パラメーターを設定する必要があります。現在サポートされているモデルには、qwen-turbo、qwen-plus、qwen-max があります。 説明 tools パラメーターは stream=True と同時に使用することはできません。 |
stream_options (オプション) | object | None | ストリーミング出力中に使用されたトークン数を表示するかどうかを設定します。このパラメーターは、stream が True に設定されている場合にのみ有効です。ストリーミング出力モードでトークン数をカウントするには、このパラメーターを |
応答パラメーター
戻りパラメーター | データ型 | 説明 | 注 |
id | string | この呼び出しに対してシステムが生成した ID。 | None |
model | string | 呼び出されるモデルの名前。 | None |
system_fingerprint | string | モデルランタイムで使用される構成バージョン。これは現在サポートされておらず、空の文字列 "" を返します。 | None |
choices | array | モデルによって生成されたコンテンツの詳細。 | None |
choices[i].finish_reason | string | 次の 3 つのケースが適用されます。
| |
choices[i].message | object | モデルが出力するメッセージ。 | |
choices[i].message.role | string | モデルのロール。assistant に固定されています。 | |
choices[i].message.content | string | モデルによって生成されたテキスト。 | |
choices[i].index | integer | 生成された結果のシーケンス番号。デフォルト値: 0。 | |
created | integer | 結果が生成されたときの UNIX タイムスタンプ (秒単位)。 | None |
usage | object | リクエストのトークン消費量。 | None |
usage.prompt_tokens | integer | 入力テキストのトークン数。 | None |
usage.completion_tokens | integer | 生成された応答のトークン数。 | None |
usage.total_tokens | integer | usage.prompt_tokens と usage.completion_tokens の合計。 | None |
langchain_openai SDK を使用したモデルの呼び出し
前提条件
お使いのコンピューターに Python 環境がインストールされていることを確認してください。
次のコマンドを実行して、langchain_openai SDK をインストールします。
# 次のコマンドでエラーが報告された場合は、pip を pip3 に置き換えてください。 pip install -U langchain_openai
Model Studio をアクティベートし、API キーを作成します:API キーの取得。
API キーの漏洩リスクを減らすために、API キーを環境変数として設定することをお勧めします。詳細については、「API キーを環境変数として設定する」をご参照ください。コードで API キーを設定することもできますが、これにより漏洩のリスクが高まります。
使用するモデルを選択します:モデルの可用性。
使用方法
次の例は、langchain_openai SDK を使用して Alibaba Cloud Model Studio の Qwen モデルを呼び出す方法を示しています。
非ストリーミング出力
非ストリーミング出力は invoke メソッドを使用して実装されます。以下はサンプルコードです。
from langchain_openai import ChatOpenAI
import os
def get_response():
llm = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、この行を Model Studio の API キーを使用して api_key="sk-xxx" に置き換えてください。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", # これはシンガポールリージョンの base_url です。
model="qwen-plus" # この例では qwen-plus を使用します。必要に応じてモデル名を置き換えることができます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"Who are you?"}
]
response = llm.invoke(messages)
print(response.json())
if __name__ == "__main__":
get_response()コードを実行すると、次の結果が生成されます。
{
"content": "I am a large language model from Alibaba Cloud. My name is Qwen.",
"additional_kwargs": {},
"response_metadata": {
"token_usage": {
"completion_tokens": 16,
"prompt_tokens": 22,
"total_tokens": 38
},
"model_name": "qwen-plus",
"system_fingerprint": "",
"finish_reason": "stop",
"logprobs": null
},
"type": "ai",
"name": null,
"id": "run-xxx",
"example": false,
"tool_calls": [],
"invalid_tool_calls": []
}ストリーミング出力
ストリーミング出力は stream メソッドを使用して実装されます。stream パラメーターを設定する必要はありません。
from langchain_openai import ChatOpenAI
import os
def get_response():
llm = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、この行を Model Studio の API キーを使用して api_key="sk-xxx" に置き換えてください。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", # これはシンガポールリージョンの base_url です。
model="qwen-plus", # この例では qwen-plus を使用します。必要に応じてモデル名を置き換えることができます。モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください。
stream_usage=True
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"Who are you?"},
]
response = llm.stream(messages)
for chunk in response:
print(chunk.model_dump_json())
if __name__ == "__main__":
get_response()コードを実行すると、次の結果が生成されます。
{"content": "", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "I am", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": " a large", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": " language model", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": " from", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": " Alibaba", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": " Cloud", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": ", and my name is Qwen.", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "", "additional_kwargs": {}, "response_metadata": {"finish_reason": "stop"}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": {"input_tokens": 22, "output_tokens": 16, "total_tokens": 38}, "tool_call_chunks": []}入力パラメーターの設定については、「リクエストパラメーター」をご参照ください。関連するパラメーターは ChatOpenAI オブジェクトで定義されます。
HTTP インターフェイスの使用
HTTP インターフェイスを使用して Alibaba Cloud Model Studio サービスを呼び出し、OpenAI サービスからの応答と同じ構造の応答を受け取ることができます。
前提条件
Model Studio をアクティベートし、API キーを作成します:API キーの取得。
API キーの漏洩リスクを減らすために、API キーを環境変数として設定することをお勧めします。詳細については、「API キーを環境変数として設定する」をご参照ください。コードで API キーを設定することもできますが、これにより漏洩のリスクが高まります。
API リクエストの送信
シンガポール、米国 (バージニア):POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
中国 (北京):POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completionsリクエストの例
次の例は、cURL コマンドを使用して API を呼び出すスクリプトを示しています。
API キーを環境変数として設定していない場合は、$DASHSCOPE_API_KEY を API キーに置き換える必要があります。
非ストリーミング出力
# これはシンガポールリージョンの base_url です。
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'
コマンドを実行すると、次の結果が生成されます。
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large language model from Alibaba Cloud. My name is Qwen."
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 11,
"completion_tokens": 16,
"total_tokens": 27
},
"created": 1715252778,
"system_fingerprint": "",
"model": "qwen-plus",
"id": "chatcmpl-xxx"
}ストリーミング出力
ストリーミング出力を使用する場合は、リクエストボディで stream パラメーターを true に設定します。
# これはシンガポールリージョンの base_url です。
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
],
"stream":true
}'コマンドを実行すると、次の結果が生成されます。
data: {"choices":[{"delta":{"content":"","role":"assistant"},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"finish_reason":null,"delta":{"content":"I am"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":" a large-scale"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":" language model"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":" from Alibaba Cloud"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":", and my name is Qwen."},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":""},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: [DONE]
入力パラメーターの詳細については、「リクエストパラメーター」をご参照ください。
異常な応答の例
リクエスト中にエラーが発生した場合、応答の code フィールドと message フィールドにエラーの原因が示されます。
{
"error": {
"message": "Incorrect API key provided. ",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}ステータスコード
エラーコード | 説明 |
400 - 無効なリクエストエラー | リクエストは無効です。詳細については、エラーメッセージをご参照ください。 |
401 - 提供された API キーが正しくありません | API キーが正しくありません。 |
429 - リクエストのレート制限に達しました | クエリ/秒 (QPS)、クエリ/分 (QPM)、またはその他の制限を超えています。 |
429 - 現在のクォータを超えました。プランと課金の詳細を確認してください | クォータを超えているか、アカウントに支払い遅延があります。 |
500 - リクエストの処理中にサーバーでエラーが発生しました | サーバー側でエラーが発生しました。 |
503 - エンジンは現在過負荷です。後でもう一度お試しください | サーバーが過負荷です。後でもう一度お試しください。 |