跳转至内容

AgentStudio

AgentStudio 是托管智能体平台:环境、智能体、会话、事件、文件、记忆库、凭据库、技能、Webhook 与定时部署。它由 2.x 与 3.0 两代 SDK 共享,不在废弃之列。

client.agentStudio() 惰性挂载一个共享的 AgentStudioClient —— workspace 与 region 从客户端 配置转发,但 3.0 的 baseUrl 不作用于它;用 DASHSCOPE_AGENTSTUDIO_URL 覆盖其端点。该子区 自行分配 HTTP client;错误使用 3.0 unchecked 异常族。

资源

访问器(studio.*) 管理内容
environments() 沙箱执行环境
agents() 智能体定义(系统提示词、模型、工具)
sessions() 会话;sessions().events() 发送/流式读取事件
deployments() / deploymentRuns() 定时智能体部署及其运行
memoryStores() 持久记忆:memories()、memoryVersions()
files() 会话/智能体文件
vaults() 凭据库
skills() 可复用技能
webhookEndpoints() Webhook 订阅
security() / usage() 安全设置与用量报告

端到端快速上手

创建环境 → 创建智能体 → 创建会话 → 发送消息 → 流式读取事件 → 归档。改编自 AgentStudioQuickStart:

import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
import com.alibaba.dashscope.applications.agentstudio.message.ClientEvents;
import com.alibaba.dashscope.applications.agentstudio.model.Agent;
import com.alibaba.dashscope.applications.agentstudio.model.Environment;
import com.alibaba.dashscope.applications.agentstudio.model.Session;
import com.alibaba.dashscope.applications.agentstudio.param.AgentCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.EnvironmentCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.SessionCreateParam;
import com.alibaba.dashscope.applications.agentstudio.resource.AgentStudioEventStream;

try (DashScopeClient client = DashScopeClient.builder()
    .workspace("trial")    // DASHSCOPE_WORKSPACE 选择 AgentStudio 工作空间
    .build()) {
  AgentStudioClient studio = client.agentStudio();

  Environment env = studio.environments().create(
      EnvironmentCreateParam.builder().name("quickstart-env").config(config).build());
  Agent agent = studio.agents().create(
      AgentCreateParam.builder()
          .name("quickstart-agent")
          .systemPrompt("You are a friendly demo agent. Reply briefly.")
          .model("qwen3.8-max")
          .tools(tools)
          .build());
  Session session = studio.sessions().create(
      SessionCreateParam.builder()
          .agent(agent.getId()).environmentId(env.getId()).title("quickstart").build());

  studio.sessions().events().send(session.getId(),
      Collections.singletonList(ClientEvents.userMessage("Tell me a fun fact about Hangzhou.")));

  try (AgentStudioEventStream stream = studio.sessions().events().stream(session.getId())) {
    for (String text : stream.textStream()) {
      System.out.print(text);
    }
  }
}
完整可运行示例:AgentStudioQuickStart.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.recipes.agentstudio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
import com.alibaba.dashscope.applications.agentstudio.message.ClientEvents;
import com.alibaba.dashscope.applications.agentstudio.model.Agent;
import com.alibaba.dashscope.applications.agentstudio.model.Configs;
import com.alibaba.dashscope.applications.agentstudio.model.Environment;
import com.alibaba.dashscope.applications.agentstudio.model.Session;
import com.alibaba.dashscope.applications.agentstudio.param.AgentCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.EnvironmentCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.SessionCreateParam;
import com.alibaba.dashscope.applications.agentstudio.resource.AgentStudioEventStream;
import com.alibaba.dashscope.examples.ExampleSupport;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Agent recipe: AgentStudio end-to-end quickstart. Flow: create environment -> create agent ->
 * create session -> send message -> stream events -> archive session.
 *
 * <p>AgentStudio is shared by the 2.x and 3.0 SDK generations: {@code client.agentStudio()} lazily
 * mounts a single shared {@link AgentStudioClient} (workspace and region forward from the client
 * config; the 3.0 {@code baseUrl} does not apply to it), so one {@code DashScopeClient} covers both
 * the 3.0 resources and AgentStudio.
 *
 * <p>The Python example's opt-in {@code memory_stores_demo} flow (create store -> write memory ->
 * list -> update -> list versions -> delete) is already covered by the Java sample {@code
 * legacy_2x/AgentStudioMemoryStores.java}, so it is not duplicated here.
 *
 * <p>Translation of the Python blueprint example 03_agent_recipes/agentstudio.py.
 *
 * <p>Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the AgentStudio workspace (defaults to
 * trial).
 */
public final class AgentStudioQuickStart {

  private AgentStudioQuickStart() {}

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

  /** The builtin_toolkit entry from the Python example: everything off except bash. */
  private static Configs.ToolConfig bashOnlyToolkit() {
    Configs.ToolConfig toolkit = new Configs.ToolConfig();
    toolkit.setType("builtin_toolkit");
    Configs.ToolConfig.DefaultConfig defaultConfig = new Configs.ToolConfig.DefaultConfig();
    defaultConfig.setEnabled(false);
    toolkit.setDefaultConfig(defaultConfig);
    Configs.ToolConfig.PerToolConfig bash = new Configs.ToolConfig.PerToolConfig();
    bash.setName("bash");
    bash.setEnabled(true);
    toolkit.setConfigs(Collections.singletonList(bash));
    return toolkit;
  }

  /** Run the full quickstart flow. */
  public static void main(String[] args) {
    try (DashScopeClient client =
        DashScopeClient.builder()
            .apiKey(ExampleSupport.requireApiKey())
            .workspace(envOr("DASHSCOPE_WORKSPACE", "trial"))
            .build()) {
      AgentStudioClient studio = client.agentStudio();

      System.out.println("==> creating environment");
      Map<String, Object> config = new HashMap<>();
      config.put("type", "cloud");
      config.put("networking", Collections.singletonMap("type", "unrestricted"));
      Environment env =
          studio
              .environments()
              .create(
                  EnvironmentCreateParam.builder().name("quickstart-env").config(config).build());
      System.out.println("   environment_id=" + env.getId());

      System.out.println("==> creating agent");
      Agent agent =
          studio
              .agents()
              .create(
                  AgentCreateParam.builder()
                      .name("quickstart-agent")
                      .systemPrompt("You are a friendly demo agent. Reply briefly.")
                      .model("qwen3.8-max")
                      .tools(Collections.singletonList(bashOnlyToolkit()))
                      .build());
      System.out.println("   agent_id=" + agent.getId());

      System.out.println("==> creating session");
      Session session =
          studio
              .sessions()
              .create(
                  SessionCreateParam.builder()
                      .agent(agent.getId())
                      .environmentId(env.getId())
                      .title("quickstart")
                      .build());
      System.out.println("   session_id=" + session.getId());

      System.out.println("==> sending user message");
      studio
          .sessions()
          .events()
          .send(
              session.getId(),
              Collections.singletonList(
                  ClientEvents.userMessage("Hello! Tell me one fun fact about Hangzhou.")));

      System.out.println("==> streaming events");
      try (AgentStudioEventStream stream = studio.sessions().events().stream(session.getId())) {
        for (String text : stream.textStream()) {
          System.out.print(text);
          System.out.flush();
        }
        System.out.println();
      }

      System.out.println("==> archiving session");
      studio.sessions().archive(session.getId());
      System.out.println("done.");
    }
  }
}

SSE 流语义

AgentStudioEventStream 是 Iterable<Message> + Closeable,带有刻意的约束:

  • 单次消费:队列只排入一个读取者;第二次 iterator() 抛 IllegalStateException。要重读 事件请另开一个流。
  • textStream() 产出终态全文;textDeltas() 只有在打开流时启用了 event_deltas 才产出增量 —— events().stream(sessionId, Arrays.asList("message"))(也接受 "reasoning")。
  • 空闲间隔超过流超时抛 ApiTimeoutException(与真正的流结束区分)。

记忆库

智能体可读取的持久化、带版本的记忆。改编自 AgentStudioMemoryStores:

MemoryStore store = studio.memoryStores().create(
    MemoryStoreCreateParam.builder()
        .name("demo-preferences")
        .description("Per-user preferences and project context.")  // 供智能体阅读
        .build());

Memory memory = studio.memoryStores().memories().create(store.getId(),
    MemoryCreateParam.builder()
        .path("/formatting_standards.md")
        .content("All reports use GAAP formatting.")
        .build());

// view=full 返回内容(默认 basic 只有元数据);遍历自动翻页。
CursorPage<Memory> page = studio.memoryStores().memories()
    .list(store.getId(), MemoryListParam.builder().view("full").build());

// 乐观锁更新:传入读到的 contentSha256。
Memory updated = studio.memoryStores().memories().update(store.getId(), memory.getId(),
    MemoryUpdateParam.builder()
        .content("All reports use GAAP formatting. ISO-8601 dates.")
        .contentSha256(memory.getContentSha256())
        .build());

// 每次变更都会产生版本快照;版本可被修订(redact)。
studio.memoryStores().memoryVersions().list(store.getId(), MemoryVersionListParam.builder().build());
studio.memoryStores().delete(store.getId());
完整可运行示例:AgentStudioMemoryStores.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.recipes.agentstudio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
import com.alibaba.dashscope.applications.agentstudio.model.AgentStudioDeletionStatus;
import com.alibaba.dashscope.applications.agentstudio.model.Memory;
import com.alibaba.dashscope.applications.agentstudio.model.MemoryStore;
import com.alibaba.dashscope.applications.agentstudio.model.MemoryVersion;
import com.alibaba.dashscope.applications.agentstudio.pagination.CursorPage;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryListParam;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryStoreCreateParam;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryStoreListParam;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryUpdateParam;
import com.alibaba.dashscope.applications.agentstudio.param.MemoryVersionListParam;
import com.alibaba.dashscope.examples.ExampleSupport;

/**
 * Agent recipe: AgentStudio memory stores end-to-end. Flow: create store -> seed memory -> list
 * with content (view=full, auto-pagination) -> update with optimistic lock -> list versions ->
 * redact a version -> list stores -> delete store.
 *
 * <p>3.0 port of {@code legacy_2x/AgentStudioMemoryStores.java}: same flow under {@code
 * com.alibaba.dashscope.applications.agentstudio}, mounted via {@code client.agentStudio()}, plus
 * the {@code redact()} audit step. Unlike the frozen legacy copy, this file is a compiled example
 * source and runs in the offline dry-run suite.
 *
 * <p>Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the AgentStudio workspace (defaults to
 * trial).
 */
public final class AgentStudioMemoryStores {

  private AgentStudioMemoryStores() {}

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

  /** Run the full memory-store flow. */
  public static void main(String[] args) {
    try (DashScopeClient client =
        DashScopeClient.builder()
            .apiKey(ExampleSupport.requireApiKey())
            .workspace(envOr("DASHSCOPE_WORKSPACE", "trial"))
            .build()) {
      AgentStudioClient studio = client.agentStudio();

      // 1. Create a store; description is read by the agent - write it for the model.
      System.out.println("==> creating memory store");
      MemoryStore store =
          studio
              .memoryStores()
              .create(
                  MemoryStoreCreateParam.builder()
                      .name("demo-preferences")
                      .description("Per-user preferences and project context.")
                      .build());
      System.out.println("   store_id=" + store.getId());

      // 2. Seed reference material before any session runs.
      System.out.println("==> seeding memory");
      Memory memory =
          studio
              .memoryStores()
              .memories()
              .create(
                  store.getId(),
                  MemoryCreateParam.builder()
                      .path("/formatting_standards.md")
                      .content("All reports use GAAP formatting.")
                      .build());
      System.out.printf(
          "   memory_id=%s path=%s size=%d%n",
          memory.getId(), memory.getPath(), memory.getContentSizeBytes());

      // 3. Read back with content (view=full; the default basic is metadata only). Print prefixes
      //    before iterating: the loop auto-paginates and prefixes are per page.
      System.out.println("==> listing memories (view=full)");
      CursorPage<Memory> page =
          studio
              .memoryStores()
              .memories()
              .list(store.getId(), MemoryListParam.builder().view("full").build());
      System.out.println("   prefixes=" + page.getPrefixes());
      for (Memory item : page) {
        System.out.printf("   %s -> %s%n", item.getPath(), item.getContent());
      }

      // 4. Update with the optimistic lock (contentSha256 from step 2).
      System.out.println("==> updating memory");
      Memory updated =
          studio
              .memoryStores()
              .memories()
              .update(
                  store.getId(),
                  memory.getId(),
                  MemoryUpdateParam.builder()
                      .content("All reports use GAAP formatting. ISO-8601 dates.")
                      .contentSha256(memory.getContentSha256())
                      .build());
      System.out.println("   updated_sha=" + updated.getContentSha256());

      // 5. Audit history: every mutation produced a memver_ snapshot (newest first).
      System.out.println("==> listing memory versions");
      String firstVersionId = null;
      for (MemoryVersion version :
          studio
              .memoryStores()
              .memoryVersions()
              .list(store.getId(), MemoryVersionListParam.builder().build())) {
        System.out.printf("   version=%s operation=%s%n", version.getId(), version.getOperation());
        if (firstVersionId == null) {
          firstVersionId = version.getId();
        }
      }

      // 6. Redact one snapshot: path/content/sha/size are cleared, the audit trail stays.
      if (firstVersionId != null) {
        System.out.println("==> redacting version " + firstVersionId);
        MemoryVersion redacted =
            studio.memoryStores().memoryVersions().redact(store.getId(), firstVersionId);
        System.out.printf(
            "   redacted_at=%s content=%s%n", redacted.getRedactedAt(), redacted.getContent());
      }

      // 7. List stores and clean up.
      System.out.println("==> listing stores");
      for (MemoryStore item :
          studio.memoryStores().list(MemoryStoreListParam.builder().limit(20).build())) {
        System.out.printf("   store=%s name=%s%n", item.getId(), item.getName());
      }
      AgentStudioDeletionStatus deleted = studio.memoryStores().delete(store.getId());
      System.out.println("   deleted=" + deleted.isDeleted());
      System.out.println("done.");
    }
  }
}

更多示例