Skip to content
Open
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 @@ -454,7 +454,7 @@ private ModelResponse invokeModel(ModelRequest request, UsageAccumulator usage,
try (AutoCloseable ignored = context.control().onLoss(() -> future.cancel(true))) {
ChatResponse response = await(future);
usage.add(response.usage());
emit(new AgentEvent.UsageUpdate(response.usage()));
emit(new AgentEvent.UsageUpdate(usage.value()));
return ModelResponse.of(response);
}
catch (Exception error) {
Expand Down Expand Up @@ -505,7 +505,7 @@ public void onNext(ChatEvent event) {
context.control().assertActive();
switch (event.type()) {
case TEXT_DELTA -> emit(new AgentEvent.MessageDelta("model-stream", event.text()));
case USAGE -> emit(new AgentEvent.UsageUpdate(event.usage()));
case USAGE -> emit(new AgentEvent.UsageUpdate(usage.valueIncluding(event.usage())));
case RESPONSE -> response = event.response();
case TOOL_CALL -> emit(new AgentEvent.Progress("model.tool-call", Map.of("name",
event.toolCall().name())));
Expand All @@ -531,6 +531,7 @@ public void onComplete() {
});
ChatResponse response = await(future);
usage.add(response.usage());
emit(new AgentEvent.UsageUpdate(usage.value()));
return response;
}
catch (Exception error) {
Expand Down Expand Up @@ -711,6 +712,12 @@ private Usage value() {
return new Usage(input, output, total);
}

private Usage valueIncluding(Usage currentTurn) {
// Current-turn snapshots replace one another; only the final response is committed.
return new Usage(add(input, currentTurn.inputTokens()), add(output, currentTurn.outputTokens()),
add(total, currentTurn.totalTokens()));
}

private static Long add(Long left, Long right) {
return left == null || right == null ? null : left + right;
}
Expand Down
Loading
Loading