阿里雲百鍊的通義千問模型支援 OpenAI 相容介面,您只需調整 API Key、BASE_URL 和模型名稱,即可將原有 OpenAI 代碼遷移至阿里雲百鍊服務使用。
相容OpenAI需要資訊
BASE_URL
BASE_URL表示模型服務的網路訪問點或地址。通過該地址,您可以訪問服務提供的功能或資料。在Web服務或API的使用中,BASE_URL通常對應於服務的具體操作或資源的URL。當您使用OpenAI相容介面來使用阿里雲百鍊模型服務時,需要配置BASE_URL。
當您通過OpenAI SDK或其他OpenAI相容的SDK調用時,需要配置的BASE_URL如下:
新加坡:https://dashscope-intl.aliyuncs.com/compatible-mode/v1 華北2(北京):https://dashscope.aliyuncs.com/compatible-mode/v1當您通過HTTP請求調用時,需要配置的完整訪問endpoint如下:
新加坡:POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions 華北2(北京):POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
支援的模型列表
當前OpenAI相容介面支援的通義千問系列模型如下表所示。
模型分類 | 模型名稱 |
通義千問 | qwen-max qwen-max-latest qwen-max-2025-01-25 qwen-plus qwen-plus-latest qwen-plus-2025-04-28 qwen-plus-2025-01-25 qwen-turbo qwen-turbo-latest qwen-turbo-2025-04-28 qwen-turbo-2024-11-01 |
通義千問開源系列 | qwq-32b 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-72b-instruct qwen2-7b-instruct qwen1.5-110b-chat qwen1.5-72b-chat qwen1.5-32b-chat qwen1.5-14b-chat qwen1.5-7b-chat |
通過OpenAI SDK調用
前提條件
請確保您的電腦上安裝了Python環境。
請安裝最新版OpenAI SDK。
# 如果下述命令報錯,請將pip替換為pip3 pip install -U openai您需要開通阿里雲百鍊模型服務並獲得API-KEY,詳情請參考:準備工作:擷取與配置 API Key。
我們推薦您將API-KEY配置到環境變數中以降低API-KEY的泄露風險,配置方法可參考配置API Key到環境變數(準備下線,併入配置 API Key)。您也可以在代碼中配置API-KEY,但是泄露風險會提高。
請選擇您需要使用的模型:支援的模型列表。
使用方式
您可以參考以下樣本來使用OpenAI SDK訪問百鍊服務上的通義千問模型。
非流式調用樣本
from openai import OpenAI
import os
def get_response():
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您沒有配置環境變數,請用阿里雲百鍊API Key將本行替換為:api_key="sk-xxx"
# 填寫DashScope SDK的base_url,如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
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/zh/model-studio/getting-started/models
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是誰?'}]
)
print(completion.model_dump_json())
if __name__ == '__main__':
get_response()運行代碼可以獲得以下結果:
{
"id": "chatcmpl-xxx",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"message": {
"content": "我是來自阿里雲的超大規模預訓練模型,我叫通義千問。",
"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(
# 如果您沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 填寫DashScope SDK的base_url,如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
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/zh/model-studio/getting-started/models
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是誰?'}],
stream=True,
# 通過以下設定,在流式輸出的最後一行展示token使用資訊
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":"我是","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":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":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":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":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}}function call樣本
此處以天氣查詢工具與時間查詢工具為例,向您展示通過OpenAI介面相容實現function call的功能。範例程式碼可以實現多輪工具調用。
from openai import OpenAI
from datetime import datetime
import json
import os
client = OpenAI(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 填寫DashScope SDK的base_url,如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# 定義工具列表,模型在選擇使用哪個工具時會參考工具的name和description
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/zh/model-studio/getting-started/models
messages=messages,
tools=tools
)
return completion.model_dump()
def call_with_messages():
print('\n')
messages = [
{
"content": input('請輸入:'), # 提問樣本:"現在幾點了?" "一個小時後幾點" "北京天氣如何?"
"role": "user"
}
]
print("-"*60)
# 模型的第一輪調用
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: # 如果模型判斷無需調用工具,則將assistant的回複直接列印出來,無需進行模型的第二輪調用
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 = 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()當輸入:杭州和北京天氣怎麼樣?現在幾點了?時,程式會進行如下輸出:

輸入參數配置
輸入參數與OpenAI的介面參數對齊,當前已支援的參數如下:
參數 | 類型 | 預設值 | 說明 |
model | string | - | 使用者使用model參數指明對應的模型,可選的模型請見支援的模型列表。 |
messages | array | - | 使用者與模型的對話歷史。array中的每個元素形式為 |
top_p(可選) | float | - | 產生過程中的核採樣方法機率閾值,例如,取值為0.8時,僅保留機率加起來大於等於0.8的最可能token的最小集合作為候選集。取值範圍為(0,1.0),取值越大,產生的隨機性越高;取值越小,產生的確定性越高。 |
temperature(可選) | float | - | 用於控制模型回複的隨機性和多樣性。具體來說,temperature值控制了產生文本時對每個候選詞的機率分布進行平滑的程度。較高的temperature值會降低機率分布的峰值,使得更多的低機率詞被選擇,產生結果更加多樣化;而較低的temperature值則會增強機率分布的峰值,使得高機率詞更容易被選擇,產生結果更加確定。 取值範圍: [0, 2),不建議取值為0,無意義。 |
presence_penalty (可選) | float | - | 使用者控制模型產生時整個序列中的重複度。提高presence_penalty時可以降低模型產生的重複度,取值範圍[-2.0, 2.0]。 說明 目前僅在千問商業模型和qwen1.5及以後的開源模型上支援該參數。 |
n(可選) | integer | 1 | 產生響應的個數,取值範圍是 設定較大的 n 值不會增加輸入 Token 消耗,會增加輸出 Token 的消耗。 當前僅支援 qwen-plus 模型,且在傳入 tools 參數時固定為1。 |
max_tokens(可選) | integer | - | 指定模型可產生的最大token個數。例如模型最大輸出長度為2k,您可以設定為1k,防止模型輸出過長的內容。 不同的模型有不同的輸出上限,具體請參見模型列表。 |
seed(可選) | integer | - | 產生時使用的隨機數種子,用於控制模型產生內容的隨機性。seed支援無符號64位整數。 |
stream(可選) | boolean | False | 用於控制是否使用流式輸出。當以stream模式輸出結果時,介面返回結果為generator,需要通過迭代擷取結果,每次輸出為當前產生的增量序列。 |
stop(可選) | string or array | None | stop參數用於實現內容產生過程的精確控制,在模型產生的內容即將包含指定的字串或token_id時自動停止。stop可以為string類型或array類型。
|
tools(可選) | array | None | 用於指定可供模型調用的工具庫,一次function call流程模型會從中選擇其中一個工具。tools中每一個tool的結構如下:
在function call流程中,無論是發起function call的輪次,還是向模型提交工具函數的執行結果,均需設定tools參數。當前支援的模型包括qwen-turbo、qwen-plus和qwen-max。 說明 tools暫時無法與stream=True同時使用。 |
stream_options(可選) | object | None | 該參數用於配置在流式輸出時是否展示使用的token數目。只有當stream為True的時候該參數才會啟用生效。若您需要統計流式輸出模式下的token數目,可將該參數配置為 |
返回參數說明
返回參數 | 資料類型 | 說明 | 備忘 |
id | string | 系統產生的標識本次調用的id。 | 無 |
model | string | 本次調用的模型名。 | 無 |
system_fingerprint | string | 模型運行時使用的配置版本,當前暫時不支援,返回為空白字串“”。 | 無 |
choices | array | 模型產生內容的詳情。 | 無 |
choices[i].finish_reason | string | 有三種情況:
| |
choices[i].message | object | 模型輸出的訊息。 | |
choices[i].message.role | string | 模型的角色,固定為assistant。 | |
choices[i].message.content | string | 模型產生的文本。 | |
choices[i].index | integer | 產生的結果序列編號,預設為0。 | |
created | integer | 當前產生結果的時間戳記(s)。 | 無 |
usage | object | 計量資訊,表示本次請求所消耗的token資料。 | 無 |
usage.prompt_tokens | integer | 使用者輸入文本轉換成token後的長度。 | 無 |
usage.completion_tokens | integer | 模型產生回複轉換為token後的長度。 | 無 |
usage.total_tokens | integer | usage.prompt_tokens與usage.completion_tokens的總和。 | 無 |
通過langchain_openai SDK調用
前提條件
請確保您的電腦上安裝了Python環境。
通過運行以下命令安裝langchain_openai SDK。
# 如果下述命令報錯,請將pip替換為pip3 pip install -U langchain_openai
您需要開通阿里雲百鍊模型服務並獲得API-KEY,詳情請參考:準備工作:擷取與配置 API Key。
我們推薦您將API-KEY配置到環境變數中以降低API-KEY的泄露風險,詳情可參考配置API Key到環境變數(準備下線,併入配置 API Key)。您也可以在代碼中配置API-KEY,但是泄露風險會提高。
請選擇您需要使用的模型:支援的模型列表。
使用方式
您可以參考以下樣本來通過langchain_openai SDK使用阿里雲百鍊的千問模型。
非流式輸出
非流式輸出使用invoke方法實現,請參考以下範例程式碼:
from langchain_openai import ChatOpenAI
import os
def get_response():
llm = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您沒有配置環境變數,請用阿里雲百鍊API Key將本行替換為:api_key="sk-xxx"
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", # 如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
model="qwen-plus" # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"你是誰?"}
]
response = llm.invoke(messages)
print(response.json())
if __name__ == "__main__":
get_response()運行代碼,可以得到以下結果:
{
"content": "我是來自阿里雲的大規模語言模型,我叫通義千問。",
"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"), # 如果您沒有配置環境變數,請用阿里雲百鍊API Key將本行替換為:api_key="sk-xxx"
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", # 如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
model="qwen-plus", # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
stream_usage=True
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"你是誰?"},
]
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": "我是", "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": {}, "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": 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": 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": 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": 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": 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介面來調用阿里雲百鍊服務,獲得與通過HTTP介面調用OpenAI服務相同結構的返回結果。
前提條件
您需要開通阿里雲百鍊模型服務並獲得API-KEY,詳情請參考:準備工作:擷取與配置 API Key。
我們推薦您將API-KEY配置到環境變數中以降低API-KEY的泄露風險,配置方法可參考配置API Key到環境變數(準備下線,併入配置 API Key)。您也可以在代碼中配置API-KEY,但是泄露風險會提高。
提交介面調用
新加坡:POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
華北2(北京):POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions請求樣本
以下樣本展示通過cURL命令來調用API的指令碼。
如果您沒有配置API-KEY為環境變數,需將$DASHSCOPE_API_KEY更改為您的API-KEY。
非流式輸出
# 如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
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": "你是誰?"
}
]
}'
運行命令可得到以下結果:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "我是來自阿里雲的大規模語言模型,我叫通義千問。"
},
"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。
# 如果使用華北2(北京)地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
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": "你是誰?"
}
],
"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":"我是"},"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":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":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":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":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 - Invalid Request Error | 輸入請求錯誤,細節請參見具體報錯資訊。 |
401 - Incorrect API key provided | API key不正確。 |
429 - Rate limit reached for requests | QPS、QPM等超限。 |
429 - You exceeded your current quota, please check your plan and billing details | 額度超限或者欠費。 |
500 - The server had an error while processing your request | 服務端錯誤。 |
503 - The engine is currently overloaded, please try again later | 服務端負載過高,可重試。 |