Skip to content

Commit 2cd9b44

Browse files
authored
fix(kiro): restore estimated prompt-cache usage (#658)
fix(kiro): restore estimated prompt-cache usage
2 parents 60998b1 + e9325e6 commit 2cd9b44

11 files changed

Lines changed: 487 additions & 32 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
### English
2+
3+
- Kiro usage again reports estimated prompt-cache reads and writes. Kiro still does not send cache figures, so the gateway tracks prompt prefixes per account for five minutes and reports the repeated part as a cache read.
4+
5+
### 中文
6+
7+
- Kiro 用量再次附带估算的提示缓存读写。Kiro 本身仍不返回缓存数字,网关按账号把 prompt 前缀记五分钟,把重复部分报成缓存读取。

‎internal/providers/kiro/client.go‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,14 @@ type Client struct {
4444
mu sync.Mutex
4545
models map[string][]providers.ModelInfo
4646
logins map[string]*loginState
47+
48+
// cache estimates prompt-cache reads and writes Kiro does not report.
49+
// A nil cache (tests build Client directly) estimates nothing.
50+
cache *promptCache
4751
}
4852

4953
func NewClient(store Store) *Client {
50-
return &Client{store: store, http: &http.Client{}}
54+
return &Client{store: store, http: &http.Client{}, cache: newPromptCache()}
5155
}
5256

5357
func (c *Client) Adapter() providers.Adapter {
@@ -285,21 +289,22 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate
285289
return nil, providers.ResolvedChat{}, err
286290
}
287291
resolved := providers.ResolvedChat{ReasoningLevel: payload.Level}
292+
cache := c.cache.begin(accountID, payload)
288293
if c.useResponses(ctx, accountID, cred) {
289294
body, err := c.postResponses(ctx, client, cred, payload)
290295
if err != nil {
291296
return nil, providers.ResolvedChat{}, err
292297
}
293-
return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil
298+
return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil
294299
}
295300
body, kind, err := c.postLegacy(ctx, client, accountID, cred, payload)
296301
if err != nil {
297302
return nil, providers.ResolvedChat{}, err
298303
}
299304
if kind == streamResponses {
300-
return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil
305+
return writeOpenAIStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil
301306
}
302-
return writeEventStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools)), resolved, nil
307+
return writeEventStream(body, model, payload.clientNames(), armMarkupFilter(payload.Tools), cache), resolved, nil
303308
}
304309

305310
func (c *Client) postResponses(ctx context.Context, client *http.Client, cred Credential, payload conversation) (io.ReadCloser, error) {
@@ -466,12 +471,12 @@ func applyLegacyHeaders(req *http.Request, cred Credential, endpoint legacyEndpo
466471

467472
// writeEventStream reads a generateAssistantResponse body and writes the same
468473
// OpenAI chunks CreateResponse produces.
469-
func writeEventStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter) *http.Response {
474+
func writeEventStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter, cache *cacheTurn) *http.Response {
470475
pr, pw := io.Pipe()
471476
go func() {
472477
defer body.Close()
473478
defer pw.Close()
474-
writeConsumed(pw, model, eventStreamSource(body), names, filter)
479+
writeConsumed(pw, model, eventStreamSource(body), names, filter, cache)
475480
}()
476481
return &http.Response{
477482
StatusCode: http.StatusOK,

‎internal/providers/kiro/openai_stream.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ import (
1414
// relay opens a tool_use block on the first chunk that carries a name and then
1515
// treats every later arguments fragment as input_json_delta. Sending the name
1616
// before the JSON is finished would leave the client with a partial object.
17-
func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter) *http.Response {
17+
func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string, filter *markupFilter, cache *cacheTurn) *http.Response {
1818
pr, pw := io.Pipe()
1919
go func() {
2020
defer body.Close()
2121
defer pw.Close()
22-
writeConsumed(pw, model, responsesSSESource(body), names, filter)
22+
writeConsumed(pw, model, responsesSSESource(body), names, filter, cache)
2323
}()
2424
return &http.Response{
2525
StatusCode: http.StatusOK,
@@ -30,8 +30,9 @@ func writeOpenAIStream(body io.ReadCloser, model string, names map[string]string
3030

3131
// writeConsumed turns one event source into OpenAI chat chunks. Tool calls are
3232
// announced only after the upstream emits a complete call. names maps a Kiro
33-
// tool name back to the name the client declared.
34-
func writeConsumed(w io.Writer, model string, source eventSource, names map[string]string, filter *markupFilter) {
33+
// tool name back to the name the client declared. cache, when set, adds the
34+
// local prompt-cache estimate and is stored only after a clean stream.
35+
func writeConsumed(w io.Writer, model string, source eventSource, names map[string]string, filter *markupFilter, cache *cacheTurn) {
3536
index := 0
3637
var inputTokens, outputTokens int
3738
var credits, contextPct float64
@@ -90,7 +91,10 @@ func writeConsumed(w io.Writer, model string, source eventSource, names map[stri
9091
payload, _ := json.Marshal(map[string]any{"error": map[string]any{"message": err.Error(), "type": "upstream_error"}})
9192
fmt.Fprintf(w, "data: %s\n\n", payload)
9293
}
93-
usage := streamUsage(model, inputTokens, outputTokens, contextPct, produced.total(), credits, sawCredits)
94+
usage := streamUsage(model, inputTokens, outputTokens, contextPct, produced.total(), credits, sawCredits, cache.estimate())
95+
if err == nil {
96+
cache.commit()
97+
}
9498
done := map[string]any{
9599
"id": "chatcmpl-kiro", "object": "chat.completion.chunk", "created": time.Now().Unix(), "model": model,
96100
"choices": []map[string]any{{"index": 0, "delta": map[string]any{}, "finish_reason": finish}},
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
package kiro
2+
3+
import (
4+
"crypto/sha256"
5+
"encoding/json"
6+
"math"
7+
"strings"
8+
"sync"
9+
"time"
10+
)
11+
12+
// Kiro reports neither cache reads nor cache writes, so they are estimated
13+
// locally the way Kiro-Go does (proxy/cache_tracker.go): each request is cut
14+
// into a prelude (model, system, tools) and one block per turn, every block
15+
// end is fingerprinted with a running SHA-256, and a later request on the same
16+
// account that repeats a stored prefix reads it from "cache". Fingerprints
17+
// live in memory for the Anthropic default TTL of five minutes. The figures
18+
// are an estimate for the request log and the client, not a billing number.
19+
20+
const (
21+
promptCacheTTL = 5 * time.Minute
22+
// Anthropic does not cache prefixes shorter than this.
23+
minCacheableTokens = 1024
24+
opusMinCacheableTokens = 4096
25+
// The newest content in a request is never all served from cache.
26+
maxCacheReadShare = 0.85
27+
// Media is counted at a flat size instead of by its base64 length.
28+
mediaTokenEstimate = 1600
29+
)
30+
31+
// promptCacheUsage is one request's estimate. Total is the local estimate of
32+
// the whole prompt that Read and Write are measured against.
33+
type promptCacheUsage struct {
34+
Read, Write, Total int
35+
}
36+
37+
// scaled re-expresses the estimate against input, the prompt size the usage
38+
// chunk reports (Kiro's context share), so the shares stay the same while
39+
// read plus write never exceeds input.
40+
func (u *promptCacheUsage) scaled(input int) (int, int) {
41+
if u == nil || input <= 0 || u.Total <= 0 {
42+
return 0, 0
43+
}
44+
ratio := float64(input) / float64(u.Total)
45+
read := min(int(math.Round(float64(u.Read)*ratio)), input)
46+
write := min(int(math.Round(float64(u.Write)*ratio)), input-read)
47+
return read, write
48+
}
49+
50+
type cacheBreakpoint struct {
51+
fingerprint [32]byte
52+
tokens int // cumulative estimate up to and including this block
53+
}
54+
55+
type cacheProfile struct {
56+
model string
57+
breakpoints []cacheBreakpoint
58+
total int
59+
}
60+
61+
// buildCacheProfile fingerprints a conversation block by block. A user turn
62+
// hashes the same whether it is the current turn or a replayed history turn,
63+
// so this request's full prompt is the prefix the next turn looks up.
64+
func buildCacheProfile(c conversation) *cacheProfile {
65+
hasher := sha256.New()
66+
profile := &cacheProfile{model: c.Model}
67+
add := func(value any, tokens int) {
68+
encoded, err := json.Marshal(value)
69+
if err != nil {
70+
return
71+
}
72+
hasher.Write(encoded)
73+
hasher.Write([]byte{0})
74+
profile.total += tokens
75+
var fingerprint [32]byte
76+
copy(fingerprint[:], hasher.Sum(nil))
77+
profile.breakpoints = append(profile.breakpoints, cacheBreakpoint{fingerprint: fingerprint, tokens: profile.total})
78+
}
79+
prelude := struct {
80+
Model, System string
81+
Tools []toolSpec
82+
}{c.Model, c.System, c.Tools}
83+
add(prelude, preludeTokens(c))
84+
for _, turn := range c.History {
85+
switch {
86+
case turn.User != nil:
87+
add(turn.User, userTokens(*turn.User))
88+
case turn.Assistant != nil:
89+
add(turn.Assistant, assistantTokens(*turn.Assistant))
90+
}
91+
}
92+
add(c.Current, userTokens(c.Current))
93+
if len(profile.breakpoints) == 0 || profile.total <= 0 {
94+
return nil
95+
}
96+
return profile
97+
}
98+
99+
func preludeTokens(c conversation) int {
100+
total := estimateTokens(c.System)
101+
for _, tool := range c.Tools {
102+
total += estimateTokens(tool.Name) + estimateTokens(tool.Description)
103+
if schema, err := json.Marshal(tool.Parameters); err == nil {
104+
total += estimateTokens(string(schema))
105+
}
106+
}
107+
return total
108+
}
109+
110+
func userTokens(turn userTurn) int {
111+
total := estimateTokens(turn.Text) + mediaTokenEstimate*(len(turn.Images)+len(turn.Documents))
112+
for _, result := range turn.Results {
113+
total += estimateTokens(result.Output)
114+
}
115+
return total
116+
}
117+
118+
func assistantTokens(turn assistantTurn) int {
119+
total := estimateTokens(turn.Text)
120+
for _, block := range turn.Reasoning {
121+
total += estimateTokens(block.Text)
122+
}
123+
for _, call := range turn.ToolUses {
124+
total += estimateTokens(call.Name)
125+
if input, err := json.Marshal(call.Input); err == nil {
126+
total += estimateTokens(string(input))
127+
}
128+
}
129+
return total
130+
}
131+
132+
func minCacheableFor(model string) int {
133+
if strings.Contains(strings.ToLower(model), "opus") {
134+
return opusMinCacheableTokens
135+
}
136+
return minCacheableTokens
137+
}
138+
139+
// promptCache holds stored prefix fingerprints per account. The zero of a nil
140+
// *promptCache is valid and estimates nothing.
141+
type promptCache struct {
142+
mu sync.Mutex
143+
entries map[string]map[[32]byte]time.Time // account -> fingerprint -> expiry
144+
now func() time.Time
145+
}
146+
147+
func newPromptCache() *promptCache {
148+
return &promptCache{entries: map[string]map[[32]byte]time.Time{}, now: time.Now}
149+
}
150+
151+
// compute estimates cache use for profile without storing it. The first
152+
// cacheable request on an account writes the whole prompt. Later requests read
153+
// the longest stored prefix, capped so part of the prompt stays uncached, and
154+
// write the rest up to that cap.
155+
func (t *promptCache) compute(account string, profile *cacheProfile) promptCacheUsage {
156+
usage := promptCacheUsage{Total: profile.total}
157+
minTokens := minCacheableFor(profile.model)
158+
if profile.total < minTokens {
159+
return usage
160+
}
161+
now := t.now()
162+
t.mu.Lock()
163+
defer t.mu.Unlock()
164+
t.pruneLocked(now)
165+
entries := t.entries[account]
166+
if len(entries) == 0 {
167+
usage.Write = profile.total
168+
return usage
169+
}
170+
cacheable := int(float64(profile.total) * maxCacheReadShare)
171+
matched := 0
172+
for i := len(profile.breakpoints) - 1; i >= 0; i-- {
173+
point := profile.breakpoints[i]
174+
if point.tokens < minTokens {
175+
break
176+
}
177+
if _, ok := entries[point.fingerprint]; ok {
178+
matched = min(point.tokens, cacheable)
179+
break
180+
}
181+
}
182+
usage.Read = matched
183+
usage.Write = max(cacheable-matched, 0)
184+
return usage
185+
}
186+
187+
// update stores every cacheable prefix of profile for the TTL.
188+
func (t *promptCache) update(account string, profile *cacheProfile) {
189+
minTokens := minCacheableFor(profile.model)
190+
now := t.now()
191+
t.mu.Lock()
192+
defer t.mu.Unlock()
193+
t.pruneLocked(now)
194+
entries := t.entries[account]
195+
if entries == nil {
196+
entries = map[[32]byte]time.Time{}
197+
t.entries[account] = entries
198+
}
199+
for _, point := range profile.breakpoints {
200+
if point.tokens >= minTokens {
201+
entries[point.fingerprint] = now.Add(promptCacheTTL)
202+
}
203+
}
204+
if len(entries) == 0 {
205+
delete(t.entries, account)
206+
}
207+
}
208+
209+
func (t *promptCache) pruneLocked(now time.Time) {
210+
for account, entries := range t.entries {
211+
for fingerprint, expires := range entries {
212+
if !expires.After(now) {
213+
delete(entries, fingerprint)
214+
}
215+
}
216+
if len(entries) == 0 {
217+
delete(t.entries, account)
218+
}
219+
}
220+
}
221+
222+
// cacheTurn is one request's estimate. It is computed before the request is
223+
// sent and stored only after the stream completes, so a failed request never
224+
// seeds a hit for the next one.
225+
type cacheTurn struct {
226+
tracker *promptCache
227+
account string
228+
profile *cacheProfile
229+
usage promptCacheUsage
230+
}
231+
232+
func (t *promptCache) begin(account string, c conversation) *cacheTurn {
233+
if t == nil || account == "" {
234+
return nil
235+
}
236+
profile := buildCacheProfile(c)
237+
if profile == nil {
238+
return nil
239+
}
240+
return &cacheTurn{tracker: t, account: account, profile: profile, usage: t.compute(account, profile)}
241+
}
242+
243+
func (c *cacheTurn) estimate() *promptCacheUsage {
244+
if c == nil {
245+
return nil
246+
}
247+
usage := c.usage
248+
return &usage
249+
}
250+
251+
func (c *cacheTurn) commit() {
252+
if c == nil {
253+
return
254+
}
255+
c.tracker.update(c.account, c.profile)
256+
}

0 commit comments

Comments
 (0)