Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.alibaba.dashscope.agentstudio.resource.Security;
import com.alibaba.dashscope.agentstudio.resource.Sessions;
import com.alibaba.dashscope.agentstudio.resource.Skills;
import com.alibaba.dashscope.agentstudio.resource.Usage;
import com.alibaba.dashscope.agentstudio.resource.Vaults;
import com.alibaba.dashscope.agentstudio.resource.WebhookEndpoints;
import com.alibaba.dashscope.protocol.ConnectionOptions;
Expand All @@ -29,6 +30,7 @@ public class AgentStudioClient implements Closeable {
private final Files files;
private final WebhookEndpoints webhookEndpoints;
private final Security security;
private final Usage usage;
private final String baseUrl;

public AgentStudioClient() {
Expand Down Expand Up @@ -61,6 +63,7 @@ public AgentStudioClient(
this.memoryStores = new MemoryStores(this.baseUrl, connectionOptions, apiKey);
this.webhookEndpoints = new WebhookEndpoints(this.baseUrl, connectionOptions, apiKey);
this.security = new Security(this.baseUrl, connectionOptions, apiKey);
this.usage = new Usage(this.baseUrl, connectionOptions, apiKey);
}

public static Builder builder() {
Expand Down Expand Up @@ -148,6 +151,10 @@ public Security security() {
return security;
}

public Usage usage() {
return usage;
}

public String getBaseUrl() {
return baseUrl;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.agentstudio.param;

import com.alibaba.dashscope.base.FlattenHalfDuplexParamBase;
import com.google.gson.JsonObject;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.experimental.SuperBuilder;

/** Body fields shared by usage summary and trend; dimension-specific validation is server-side. */
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public class UsageQueryParam extends FlattenHalfDuplexParamBase {
@NonNull private String dimension;
private String agentId;
private String agentVersion;
private String sessionId;
private TimeRange timeRange;
private String granularity;
private Integer pageSize;
private String pageToken;

@Data
@Builder
public static class TimeRange {
@NonNull private String startTime;
@NonNull private String endTime;
}

@Override
public JsonObject getHttpBody() {
JsonObject body = new JsonObject();
body.addProperty("dimension", dimension);
if (agentId != null) body.addProperty("agent_id", agentId);
if (agentVersion != null) body.addProperty("agent_version", agentVersion);
if (sessionId != null) body.addProperty("session_id", sessionId);
if (granularity != null) body.addProperty("granularity", granularity);
if (pageSize != null) body.addProperty("page_size", pageSize);
if (pageToken != null) body.addProperty("page_token", pageToken);
if (timeRange != null) {
JsonObject range = new JsonObject();
range.addProperty("start_time", timeRange.getStartTime());
range.addProperty("end_time", timeRange.getEndTime());
body.add("time_range", range);
}
addExtraBody(body);
return body;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.agentstudio.resource;

import com.alibaba.dashscope.agentstudio.AgentStudioConstants;
import com.alibaba.dashscope.agentstudio.param.UsageQueryParam;
import com.alibaba.dashscope.api.GeneralApi;
import com.alibaba.dashscope.base.HalfDuplexParamBase;
import com.alibaba.dashscope.common.FlattenResultBase;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.protocol.ConnectionOptions;
import com.alibaba.dashscope.protocol.GeneralServiceOption;
import com.alibaba.dashscope.protocol.HttpMethod;
import com.google.gson.JsonObject;
import java.util.concurrent.CompletableFuture;
import lombok.Data;
import lombok.EqualsAndHashCode;

/** Usage totals and cursor-paginated trends, using the shared GeneralApi HTTP implementation. */
public final class Usage {
private final GeneralApi<HalfDuplexParamBase> api;
private final String baseUrl;
private final String apiKey;

public Usage(String baseUrl, ConnectionOptions connectionOptions, String apiKey) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.api = connectionOptions != null ? new GeneralApi<>(connectionOptions) : new GeneralApi<>();
}

public Result summary(UsageQueryParam param) {
return AsyncHelper.joinAndUnwrap(summaryAsync(param));
}

public Result trend(UsageQueryParam param) {
return AsyncHelper.joinAndUnwrap(trendAsync(param));
}

public CompletableFuture<Result> summaryAsync(UsageQueryParam param) {
return query("usage/summary", param);
}

public CompletableFuture<Result> trendAsync(UsageQueryParam param) {
return query("usage/trend", param);
}

private CompletableFuture<Result> query(String path, UsageQueryParam param) {
if (param == null) {
return AsyncHelper.failedFuture(new InputRequiredException("param is required!"));
}
GeneralServiceOption opt =
AgentStudioConstants.newServiceOption(HttpMethod.POST, path, baseUrl);
return AsyncHelper.callAsync(api, AgentStudioConstants.withApiKey(apiKey, param), opt)
.thenApply(r -> FlattenResultBase.fromDashScopeResult(r, Result.class));
}

/** Complete data envelope, retaining null metrics, units, breakdowns and opaque page tokens. */
@Data
@EqualsAndHashCode(callSuper = true)
public static class Result extends FlattenResultBase {
private JsonObject data;
}
}
128 changes: 128 additions & 0 deletions src/test/java/com/alibaba/dashscope/TestAgentStudioUsage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.alibaba.dashscope;

import static org.junit.jupiter.api.Assertions.*;

import com.alibaba.dashscope.agentstudio.AgentStudioClient;
import com.alibaba.dashscope.agentstudio.param.UsageQueryParam;
import com.alibaba.dashscope.agentstudio.resource.Usage;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.google.gson.JsonObject;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.Test;

public class TestAgentStudioUsage {
@Test
public void sessionSummaryPreservesNullAndUnits() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.start();
server.enqueue(
json(
"{\"request_id\":\"req-summary\",\"data\":{\"usage\":{\"total\":{\"total_tokens\":{\"value\":null,\"unit\":\"tokens\"}},\"models\":[],\"tools\":[]}}}"));
try (AgentStudioClient client = client(server)) {
Usage.Result result =
client
.usage()
.summary(
UsageQueryParam.builder().dimension("session").sessionId("sesn-test").build());
assertEquals("req-summary", result.getRequestId());
assertTrue(
result
.getData()
.getAsJsonObject("usage")
.getAsJsonObject("total")
.getAsJsonObject("total_tokens")
.get("value")
.isJsonNull());
RecordedRequest request = server.takeRequest(5, TimeUnit.SECONDS);
assertEquals("POST", request.getMethod());
assertEquals("/agentstudio/usage/summary", request.getPath());
assertEquals("Bearer test-key", request.getHeader("Authorization"));
JsonObject body = JsonUtils.parse(request.getBody().readUtf8());
assertEquals(2, body.size());
assertEquals("sesn-test", body.get("session_id").getAsString());
}
}
}

@Test
public void asyncTrendKeepsBodyAndCursor() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.start();
server.enqueue(
json(
"{\"request_id\":\"req-trend\",\"data\":{\"points\":[],\"has_more\":true,\"next_page_token\":\"opaque+/=\"}}"));
server.enqueue(
json(
"{\"request_id\":\"req-last\",\"data\":{\"points\":[],\"has_more\":false,\"next_page_token\":null}}"));
try (AgentStudioClient client = client(server)) {
UsageQueryParam param =
UsageQueryParam.builder()
.dimension("agent")
.agentId("agent-test")
.agentVersion("1")
.granularity("hour")
.pageSize(1)
.timeRange(
UsageQueryParam.TimeRange.builder()
.startTime("2026-11-02T10:15:30+08:00")
.endTime("2026-11-02T14:00:01+08:00")
.build())
.build();
Usage.Result first = client.usage().trendAsync(param).get(5, TimeUnit.SECONDS);
param.setPageToken(first.getData().get("next_page_token").getAsString());
Usage.Result last = client.usage().trend(param);
assertFalse(last.getData().get("has_more").getAsBoolean());
assertTrue(last.getData().get("next_page_token").isJsonNull());
RecordedRequest request = server.takeRequest(5, TimeUnit.SECONDS);
assertEquals("/agentstudio/usage/trend", request.getPath());
JsonObject body = JsonUtils.parse(request.getBody().readUtf8());
assertFalse(body.has("page_token"));
assertEquals(
"2026-11-02T10:15:30+08:00",
body.getAsJsonObject("time_range").get("start_time").getAsString());
JsonObject next =
JsonUtils.parse(server.takeRequest(5, TimeUnit.SECONDS).getBody().readUtf8());
assertEquals("opaque+/=", next.remove("page_token").getAsString());
assertEquals(body, next);
}
}
}

@Test
public void summaryAsyncAndServiceErrors() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.start();
server.enqueue(
json(
"{\"request_id\":\"req-large\",\"data\":{\"value\":9007199254740993,\"ratio\":0.4}}"));
server.enqueue(
json("{\"type\":\"error\",\"error\":{\"code\":\"page_token_expired\",\"message\":\"expired\"},\"request_id\":\"req-error\"}")
.setResponseCode(410));
try (AgentStudioClient client = client(server)) {
UsageQueryParam param = UsageQueryParam.builder().dimension("workspace").build();
Usage.Result result = client.usage().summaryAsync(param).get(5, TimeUnit.SECONDS);
assertEquals(9007199254740993L, result.getData().get("value").getAsLong());
assertEquals(0.4, result.getData().get("ratio").getAsDouble());
assertThrows(ApiException.class, () -> client.usage().trend(param));
ApiException missing = assertThrows(ApiException.class, () -> client.usage().summary(null));
assertTrue(missing.getCause() instanceof InputRequiredException);
}
}
}

private AgentStudioClient client(MockWebServer server) {
return AgentStudioClient.builder()
.baseUrl(server.url("/agentstudio").toString())
.apiKey("test-key")
.build();
}

private MockResponse json(String body) {
return new MockResponse().setHeader("Content-Type", "application/json").setBody(body);
}
}
Loading