Skip to content

Add missing usage collection to BedrockAnthropic3ChatModel call with prompt #1520

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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 @@ -18,11 +18,13 @@
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.metadata.ChatResponseMetadata;
import org.springframework.ai.chat.metadata.Usage;
import reactor.core.publisher.Flux;

import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi;
Expand Down Expand Up @@ -82,11 +84,17 @@ public ChatResponse call(Prompt prompt) {
AnthropicChatResponse response = this.anthropicChatApi.chatCompletion(request);

List<Generation> generations = response.content().stream().map(content -> {
return new Generation(content.text(), Map.of())
.withGenerationMetadata(ChatGenerationMetadata.from(response.stopReason(), null));
return new Generation(new AssistantMessage(content.text()),
ChatGenerationMetadata.from(response.stopReason(), null));
}).toList();

return new ChatResponse(generations);
ChatResponseMetadata metadata = ChatResponseMetadata.builder()
.withId(response.id())
.withModel(response.model())
.withUsage(extractUsage(response.usage()))
.build();

return new ChatResponse(generations, metadata);
}

@Override
Expand Down Expand Up @@ -116,6 +124,21 @@ public Flux<ChatResponse> stream(Prompt prompt) {
});
}

private Usage extractUsage(Anthropic3ChatBedrockApi.AnthropicUsage usage) {
return new Usage() {

@Override
public Long getPromptTokens() {
return usage.inputTokens().longValue();
}

@Override
public Long getGenerationTokens() {
return usage.outputTokens().longValue();
}
};
}

/**
* Accessible for testing.
*/
Expand Down