快速开始
通义千问
说明
支持的领域 / 任务:aigc
重要
通义千问2.1(qwen-max千亿级别模型)API 限时免费开放中。
通义千问是阿里云自主研发的大语言模型,能够在用户自然语言输入的基础上,通过自然语言理解和语义分析,在不同领域、任务内为用户提供服务和帮助。
模型具备的能力包括但不限于:
创作文字,如写故事、写公文、写邮件、写剧本、写诗歌等
编写代码
提供各类语言的翻译服务,如英语、日语、法语、西班牙语等
进行文本润色和文本摘要等工作
扮演角色进行对话
制作图表
快速开始
前提条件
已开通服务并获得API-KEY:开通DashScope并创建API-KEY。
已安装最新版SDK:安装DashScope SDK。
示例代码
以下示例展示了调用通义千问API对一个用户指令进行响应的代码。
说明
需要使用您的API-KEY替换示例中的 YOUR_DASHSCOPE_API_KEY,代码才能正常运行。
python sdk version: dashscope>=1.10.0
java sdk version: >=2.5.0
设置API-KEY
export DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY
通过messages调用(推荐)
# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html
from http import HTTPStatus
import dashscope
def call_with_messages():
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '如何做炒西红柿鸡蛋?'}]
response = dashscope.Generation.call(
dashscope.Generation.Models.qwen_turbo,
messages=messages,
result_format='message', # set the result to be "message" format.
)
if response.status_code == HTTPStatus.OK:
print(response)
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
if __name__ == '__main__':
call_with_messages()
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMessage()
throws NoApiKeyException, ApiException, InputRequiredException {
Generation gen = new Generation();
MessageManager msgManager = new MessageManager(10);
Message systemMsg =
Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("如何做西红柿鸡蛋?").build();
msgManager.add(systemMsg);
msgManager.add(userMsg);
QwenParam param =
QwenParam.builder().model(Generation.Models.QWEN_TURBO).messages(msgManager.get())
.resultFormat(QwenParam.ResultFormat.MESSAGE)
.topP(0.8)
.enableSearch(true)
.build();
GenerationResult result = gen.call(param);
System.out.println(result);
}
public static void main(String[] args){
try {
callWithMessage();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
python调用成功,将输出如下结果
{
"status_code": 200,
"request_id": "9da1ba31-b22a-9540-be18-793672d1ac8f",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "做西红柿鸡蛋的步骤如下:\n\n材料:\n- 鸡蛋 3 个\n- 西红柿 2 个\n-葱 适量\n- 蒜 适量\n- 盐 适量\n- 生抽 适量\n- 糖 适量\n- 胡椒粉 适量\n- 水淀粉 适量\n\n步骤:\n1. 西红柿去皮,切块;鸡蛋打散,加入适量盐和胡椒粉调味;\n2. 锅中加入适量油,倒入鸡蛋液,炒散;\n3. 加入葱蒜末,翻炒均匀;\n4. 加入西红柿块,翻炒至软烂;\n5. 加入适量生抽和糖,翻炒均匀;\n6. 最后加入适量水淀粉,翻炒均匀即可。"
}
}
]
},
"usage": {
"input_tokens": 31,
"output_tokens": 183
}
}
通过prompt调用
# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html
from http import HTTPStatus
import dashscope
def call_with_prompt():
response = dashscope.Generation.call(
model=dashscope.Generation.Models.qwen_turbo,
prompt='如何做炒西红柿鸡蛋?'
)
# The response status_code is HTTPStatus.OK indicate success,
# otherwise indicate request is failed, you can get error code
# and message from code and message.
if response.status_code == HTTPStatus.OK:
print(response.output) # The output text
print(response.usage) # The usage information
else:
print(response.code) # The error code.
print(response.message) # The error message.
if __name__ == '__main__':
call_with_prompt()
// Copyright (c) Alibaba, Inc. and its affiliates.
import java.util.concurrent.Semaphore;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
private final static String PROMPT = "就当前的海洋污染的情况,写一份限塑的倡议书提纲,需要有理有据地号召大家克制地使用塑料制品";
public static void qwenQuickStart()
throws NoApiKeyException, ApiException, InputRequiredException {
Generation gen = new Generation();
QwenParam param = QwenParam.builder().model(Generation.Models.QWEN_TURBO).prompt(PROMPT)
.topP(0.8).build();
GenerationResult result = gen.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void qwenQuickStartCallback()
throws NoApiKeyException, ApiException, InputRequiredException, InterruptedException {
Generation gen = new Generation();
QwenParam param = QwenParam.builder().model(Generation.Models.QWEN_TURBO).prompt(PROMPT)
.topP(0.8).build();
Semaphore semaphore = new Semaphore(0);
gen.call(param, new ResultCallback<GenerationResult>() {
@Override
public void onEvent(GenerationResult message) {
System.out.println(message);
}
@Override
public void onError(Exception ex){
System.out.println(ex.getMessage());
semaphore.release();
}
@Override
public void onComplete(){
System.out.println("onComplete");
semaphore.release();
}
});
semaphore.acquire();
}
public static void main(String[] args) {
try {
qwenQuickStart();
qwenQuickStartCallback();
} catch (ApiException | NoApiKeyException | InputRequiredException | InterruptedException e) {
System.out.println(String.format("Exception %s", e.getMessage()));
}
System.exit(0);
}
}
调用成功后,将会返回如下示例结果。
{"text": "材料:\n西红柿2个,鸡蛋3个,葱花适量,盐适量,糖适量,食用油适量\n\n做法:\n1. 西红柿洗净切块,鸡蛋打入碗中搅拌均匀备用。\n2. 热锅凉油,油热后加入葱花爆香。\n3. 加入西红柿块翻炒,炒至西红柿出汁。\n4. 加入适量的盐和糖,继续翻炒均匀。\n5. 倒入鸡蛋液,用铲子快速翻炒均匀,使鸡蛋液均匀地裹在西红柿上。\n6. 炒至鸡蛋熟透即可出锅。\n\n提示:\n1. 炒西红柿时可以适当加一些水,可以使西红柿更加鲜美。\n2. 炒鸡蛋时要快速翻炒,使鸡蛋均匀地裹在西红柿上,避免炒糊。\n3. 可以根据个人口味调整盐和糖的用量。", "finish_reason": "stop", "choices": null}
{"input_tokens": 6, "output_tokens": 193, "total_tokens": 199}
了解更多
有关通义千问模型API的详细调用文档可前往API详情页面进行了解。