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
7 changes: 6 additions & 1 deletion Sources/LLMProviderKit/Models/LLMModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,18 @@ public struct LLMUsage: Sendable, Equatable {
/// Responses `input_tokens_details.cached_tokens`, Anthropic
/// `cache_read_input_tokens`. nil = the provider didn't say.
public let cachedTokens: Int?
/// Prompt tokens written into the prompt cache on this call (also a subset
/// of `promptTokens`): Anthropic `cache_creation_input_tokens`, billed above
/// the plain input rate. nil = the provider didn't say or doesn't bill writes.
public let cacheWriteTokens: Int?

public init(promptTokens: Int? = nil, completionTokens: Int? = nil, totalTokens: Int? = nil,
cachedTokens: Int? = nil) {
cachedTokens: Int? = nil, cacheWriteTokens: Int? = nil) {
self.promptTokens = promptTokens
self.completionTokens = completionTokens
self.totalTokens = totalTokens
self.cachedTokens = cachedTokens
self.cacheWriteTokens = cacheWriteTokens
}
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/LLMProviderKitAnthropic/AnthropicProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,8 @@ public struct AnthropicProvider: LLMProvider {
let parts = [input, cacheRead, cacheWrite].compactMap { $0 }
let prompt: Int? = parts.isEmpty ? nil : parts.reduce(0, +)
return LLMUsage(promptTokens: prompt, completionTokens: output,
totalTokens: (prompt ?? 0) + (output ?? 0), cachedTokens: cacheRead)
totalTokens: (prompt ?? 0) + (output ?? 0), cachedTokens: cacheRead,
cacheWriteTokens: cacheWrite)
}

/// Put a cache breakpoint on the last content block of the last message.
Expand Down
10 changes: 10 additions & 0 deletions Tests/LLMProviderKitTests/AnthropicUsageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,14 @@ struct AnthropicUsageTests {
#expect(AnthropicProvider.usage(input: nil, output: 3, cacheRead: nil, cacheWrite: nil).promptTokens == nil)
#expect(AnthropicProvider.usage(input: nil, output: nil, cacheRead: 7, cacheWrite: nil).promptTokens == 7)
}

/// Cache writes cost more than plain input (1.25x for 5-minute writes), so
/// a cost estimate needs them apart from the rest of the prompt.
@Test func cacheWritesAreReportedApart() {
let u = AnthropicProvider.usage(input: 50, output: 3, cacheRead: 900, cacheWrite: 40)
#expect(u.promptTokens == 990)
#expect(u.cachedTokens == 900)
#expect(u.cacheWriteTokens == 40)
#expect(LLMUsage(promptTokens: 1).cacheWriteTokens == nil)
}
}
Loading