跳转至内容

对话与流式

client.chat().completions() 是文本生成入口 —— 2.x Generation 的 3.0 替代物。以下代码均改编自 可运行的 chat 示例。

创建补全

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
import com.alibaba.dashscope.types.messages.Message;
import java.util.Arrays;
import java.util.List;

List<Message> messages = Arrays.asList(
    Message.system("You are a helpful assistant."),
    Message.user("请用一句话介绍杭州"));

try (DashScopeClient client = DashScopeClient.builder().build()) {
  ChatCompletion resp = client.chat().completions().create(
      ChatCompletionCreateParams.builder()
          .model("qwen-plus")
          .messages(messages)
          .build());
  System.out.println(resp.outputText());
  System.out.println("usage: " + resp.getUsage().getTotalTokens()
      + " tokens, request_id: " + resp.getRequestId());
}

Message 提供角色工厂:Message.system(...)、Message.user(...)、Message.assistant(...)、 Message.tool(...) —— 无需手写 role 字符串。

多轮对话

维护一个 List<Message> 并逐轮追加:用户输入,然后是助手回复 (Message.assistant(resp.outputText()))。API 是无状态的 —— 每次请求都携带完整历史。

流式

createStreaming 返回类型化的 ResponseStream<ChatCompletionChunk> —— 像普通集合一样遍历, 且实现了 AutoCloseable。每个 chunk 的 delta 携带内容增量(流式时 SDK 默认向服务端请求增量帧):

import com.alibaba.dashscope.types.common.ResponseStream;
import com.alibaba.dashscope.types.completions.ChatCompletionChunk;
import com.alibaba.dashscope.types.completions.Delta;

try (ResponseStream<ChatCompletionChunk> stream =
    client.chat().completions().createStreaming(
        ChatCompletionCreateParams.builder()
            .model("qwen-plus")
            .messages(messages)
            .build())) {
  for (ChatCompletionChunk chunk : stream) {
    Delta delta = chunk.delta();
    if (delta != null && delta.getContent() != null) {
      System.out.print(delta.getContent());
      System.out.flush();
    }
  }
}

流式永不自动重试(失败的流无法安全重放);流内错误帧以最后一个携带错误的 chunk 呈现。见 错误与诊断。

工具调用(agent 循环)

用 .tools(...) 发送工具 schema;每当模型要求调用工具(message.getToolCalls()),就在本地 执行,把结果作为 role="tool" 消息追加,然后再次调用 —— 直到模型返回普通答案。用轮数上限保护 循环。

import com.alibaba.dashscope.types.completions.ChatCompletionMessage;
import com.alibaba.dashscope.types.messages.ToolCall;

// tools:OpenAI 形状的 function schema(type=function, function={name, description, parameters})
List<Message> history = new ArrayList<>();
history.add(Message.system("你是一个助手,可以调用工具获取实时信息。"));
history.add(Message.user("杭州现在天气怎么样?"));

for (int turn = 0; turn < MAX_TURNS; turn++) {
  ChatCompletion resp = client.chat().completions().create(
      ChatCompletionCreateParams.builder()
          .model("qwen-plus")
          .messages(history)
          .tools(tools)
          .build());
  ChatCompletionMessage message = resp.getChoices().get(0).getMessage();
  if (message.getToolCalls() == null || message.getToolCalls().isEmpty()) {
    System.out.println("final: " + message.getContent());
    break;
  }
  // 原样回传助手的工具调用轮次……
  history.add(Message.assistant(message.getContent(), message.getToolCalls()));
  // ……然后执行每个工具并追加其 JSON 结果。
  for (ToolCall call : message.getToolCalls()) {
    String result = runTool(call.getFunction().getName(), call.getFunction().getArguments());
    history.add(Message.tool(result, call.getFunction().getName(), call.getId()));
  }
}

完整状态机(schema 构建、JSON 参数解析、错误结果、MAX_TURNS 保护)见可运行 recipe ToolCallLoop。

完整可运行示例:ToolCallLoop.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.recipes.chat;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
import com.alibaba.dashscope.types.completions.ChatCompletionMessage;
import com.alibaba.dashscope.types.messages.Message;
import com.alibaba.dashscope.types.messages.ToolCall;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * Agent recipe: a managed multi-turn tool-call loop — the classic agent state machine. Send the
 * conversation plus a tool schema; whenever the model asks to call a tool ({@code
 * message.tool_calls}), execute it locally, append the result as a {@code role="tool"} message, and
 * call the model again — until it returns a plain answer with no further tool calls. A {@code
 * MAX_TURNS} guard stops a misbehaving model from looping forever.
 *
 * <p>Translation of the Python blueprint example 03_agent_recipes/tool_call_loop.py.
 *
 * <p>Requires DASHSCOPE_API_KEY (it calls the real chat endpoint).
 */
public final class ToolCallLoop {

  private static final String MODEL = envOr("DASHSCOPE_MODEL", "qwen3.7-plus");
  private static final int MAX_TURNS = 5;
  private static final ObjectMapper MAPPER = new ObjectMapper();

  private ToolCallLoop() {}

  private static String envOr(String name, String fallback) {
    String value = System.getenv(name);
    return value == null || value.isEmpty() ? fallback : value;
  }

  /** One OpenAI-shaped function tool schema with a single string parameter. */
  private static Map<String, Object> functionTool(
      String name, String description, String paramName, String paramDescription) {
    Map<String, Object> property = new LinkedHashMap<>();
    property.put("type", "string");
    property.put("description", paramDescription);
    Map<String, Object> parameters = new LinkedHashMap<>();
    parameters.put("type", "object");
    parameters.put("properties", Collections.singletonMap(paramName, property));
    parameters.put("required", Collections.singletonList(paramName));
    Map<String, Object> function = new LinkedHashMap<>();
    function.put("name", name);
    function.put("description", description);
    function.put("parameters", parameters);
    Map<String, Object> tool = new LinkedHashMap<>();
    tool.put("type", "function");
    tool.put("function", function);
    return tool;
  }

  /**
   * Tool schemas the model may choose to call (OpenAI function shape, which the native gateway also
   * accepts).
   */
  private static final List<Map<String, Object>> TOOLS =
      Arrays.asList(
          functionTool("get_weather", "查询某个城市当前的天气", "city", "城市名,例如 杭州"),
          functionTool("get_population", "查询某个城市的常住人口(万人)", "city", "城市名"));

  // ---- local tool implementations (stand-ins for real services) ---- //

  private static String getWeather(String city) {
    Map<String, String> table = new LinkedHashMap<>();
    table.put("杭州", "晴,26℃");
    table.put("北京", "多云,21℃");
    return table.getOrDefault(city, "未知");
  }

  private static int getPopulation(String city) {
    Map<String, Integer> table = new LinkedHashMap<>();
    table.put("杭州", 1237);
    table.put("北京", 2184);
    return table.getOrDefault(city, 0);
  }

  private static final Map<String, Function<Map<String, Object>, Object>> TOOL_IMPL =
      new LinkedHashMap<>();

  static {
    TOOL_IMPL.put("get_weather", args -> getWeather((String) args.get("city")));
    TOOL_IMPL.put("get_population", args -> getPopulation((String) args.get("city")));
  }

  /** Execute one tool call, always returning a JSON string result. */
  private static String runTool(String name, String argumentsJson) {
    Map<String, Object> args;
    try {
      args =
          MAPPER.readValue(
              argumentsJson == null || argumentsJson.isEmpty() ? "{}" : argumentsJson,
              new TypeReference<Map<String, Object>>() {});
    } catch (JsonProcessingException e) {
      return "{\"error\":\"invalid JSON arguments\"}";
    }
    Function<Map<String, Object>, Object> impl = TOOL_IMPL.get(name);
    if (impl == null) {
      return toJson(Collections.singletonMap("error", "unknown tool: " + name));
    }
    try {
      return toJson(Collections.singletonMap("result", impl.apply(args)));
    } catch (RuntimeException e) {
      return toJson(Collections.singletonMap("error", "bad arguments: " + e.getMessage()));
    }
  }

  private static String toJson(Object value) {
    try {
      return MAPPER.writeValueAsString(value);
    } catch (JsonProcessingException e) {
      throw new IllegalStateException("failed to serialize tool result", e);
    }
  }

  /** Drive the tool-call state machine until a final answer. */
  static String agentLoop(DashScopeClient client, String userInput) {
    List<Message> messages = new ArrayList<>();
    messages.add(Message.system("你是一个助手,可以调用工具获取实时信息。"));
    messages.add(Message.user(userInput));
    for (int turn = 0; turn < MAX_TURNS; turn++) {
      ChatCompletion resp =
          client
              .chat()
              .completions()
              .create(
                  ChatCompletionCreateParams.builder()
                      .model(MODEL)
                      .messages(messages)
                      .tools(TOOLS)
                      .build());
      ChatCompletionMessage message = resp.getChoices().get(0).getMessage();
      if (message.getToolCalls() == null || message.getToolCalls().isEmpty()) {
        System.out.println("[turn " + turn + "] final: " + message.getContent());
        return message.getContent();
      }

      // Echo the assistant tool-call turn back verbatim ...
      messages.add(Message.assistant(message.getContent(), message.getToolCalls()));
      // ... then run each tool and append its result.
      for (ToolCall call : message.getToolCalls()) {
        String name = call.getFunction().getName();
        String arguments = call.getFunction().getArguments();
        String result = runTool(name, arguments);
        System.out.println("[turn " + turn + "] " + name + "(" + arguments + ") -> " + result);
        messages.add(Message.tool(result, name, call.getId()));
      }
    }
    System.out.println("reached MAX_TURNS=" + MAX_TURNS + " without a final answer");
    return null;
  }

  /** Run the agent loop against the real chat endpoint. */
  public static void main(String[] args) {
    try (DashScopeClient client = ExampleSupport.client()) {
      agentLoop(client, "杭州现在天气怎么样?顺便说下它有多少人口。");
    }
  }
}

异步

DashScopeAsyncClient 以 CompletableFuture / Flowable 镜像此表面 —— 见 异步客户端。

可运行示例

示例 演示内容
ChatCompletionsCreate 非流式 + 流式
ChatCompletionsCreateAsync CompletableFuture + Flowable
ChatCompletionsCreateEncrypted 加密 HTTP 通道
ToolCallLoop 多轮工具调用 agent 循环
完整可运行示例:ChatCompletionsCreate.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.chat;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.common.ResponseStream;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import com.alibaba.dashscope.types.completions.ChatCompletionChunk;
import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
import com.alibaba.dashscope.types.completions.Delta;
import com.alibaba.dashscope.types.messages.Message;
import java.util.Arrays;
import java.util.List;

/**
 * Chat completions: non-streaming and streaming. Translation of the Python blueprint example
 * 01_atomic_capabilities/text_generation/chat.py.
 *
 * <p>The Python module-level one-call quickstart {@code dashscope.chat(model, prompt)} has no Java
 * 3.0 equivalent; the try-with-resources {@link DashScopeClient} below is the entry point.
 */
public final class ChatCompletionsCreate {

  public static void main(String[] args) throws Exception {
    String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.7-plus");
    List<Message> messages =
        Arrays.asList(Message.system("You are a helpful assistant."), Message.user("请用一句话介绍杭州"));

    try (DashScopeClient client = ExampleSupport.client()) {
      // Non-streaming
      System.out.println("----- non-streaming request -----");
      ChatCompletion resp =
          client
              .chat()
              .completions()
              .create(ChatCompletionCreateParams.builder().model(model).messages(messages).build());
      System.out.println(resp.outputText());
      System.out.println(
          "usage: "
              + resp.getUsage().getTotalTokens()
              + " tokens, request_id: "
              + resp.getRequestId());

      // Streaming: each chunk's delta carries a content increment (the SDK asks the server for
      // incremental frames by default when streaming).
      System.out.println("----- streaming request -----");
      try (ResponseStream<ChatCompletionChunk> stream =
          client
              .chat()
              .completions()
              .createStreaming(
                  ChatCompletionCreateParams.builder().model(model).messages(messages).build())) {
        for (ChatCompletionChunk chunk : stream) {
          Delta delta = chunk.delta();
          if (delta != null && delta.getContent() != null) {
            System.out.print(delta.getContent());
            System.out.flush();
          }
        }
      }
      System.out.println();
    }
  }
}