文档

快速开始

更新时间:

本文为您提供简单的示例代码,帮助您快速上手并调用通义千问模型服务。

前提条件

  • 已开通服务并获得API-KEY,具体操作,请参见开通服务并创建API-KEY

  • 已安装最新版SDK,具体操作,请参见安装DashScope SDK

  • 不同编程语言的DashScope SDK版本需满足以下条件:

    • Python:1.10.0及以上版本

    • Java:2.5.0及以上版本

示例代码

以下示例代码为您展示调用通义千问API对一个用户指令进行响应的操作。

设置API-KEY

执行如下命令设置API-KEY。

说明

YOUR_DASHSCOPE_API_KEY替换为您的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)
            .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详情

  • 本页导读 (0)
文档反馈