GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(provider): add provider-specific cache configuration system (significant token usage reduction) by ormandj · Pull Request #5422 · anomalyco/opencode

Conversation

@ormandj

@ormandj ormandj commented Dec 12, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Summary

Implements comprehensive ProviderConfig system for provider-specific caching and prompt optimization.

Closes #5416

Test Results with Claude Opus 4.5 (my primary target for improvement)

A/B testing with identical prompts (same session, same agent) comparing legacy vs optimized behavior:

Metric Legacy Optimized Improvement
Cache writes (post-warmup) 18,417 tokens ~10,340 tokens 44% reduction
Effective cost (3rd prompt) 13,021 tokens 3,495 tokens 73% reduction
Initial cache write 16,211 tokens 17,987 tokens +11% (expected)
Cache hit rate 100% 100% Same

The slightly larger initial cache write (+11%) is quickly amortized by dramatically fewer cache invalidations in subsequent requests.

Provider testing

I tested with providers I have access to. I can confirm it works with with Anthropic (Opus 4.5), Google (Gemini 3 Pro preview), and Mistral (Devstral 2).

Changes

  • Add ProviderConfig namespace with defaults for 19+ providers
  • Support three caching paradigms:
    • Explicit breakpoint (Anthropic, Bedrock, Google Vertex Anthropic)
    • Automatic prefix (OpenAI, Azure, GitHub Copilot, DeepSeek)
    • Implicit/content-based (Google/Gemini)
  • Add tool sorting for cache consistency across requests
  • Add tool caching for explicit breakpoint providers
  • Add user config overrides via opencode.json (provider and agent level)
  • Simplify system message handling with combineSystemMessages boolean

Config Priority

Provider defaults → User provider config → User agent config

Area for future optimization

Currently, models.dev doesn't provide information regarding minimum cache requirements or prompt requirements, so this had to be written out as configuration. It would be ideal if the model definitions were updated with this detail. Until that point, as providers/models are added or updated, for optimal performance the configuration should be updated to match.

New Files

  • src/provider/config.ts (874 lines)
  • test/provider/config.test.ts (215 tests)

Example Config

{
  "provider": {
    "anthropic": {
      "cache": {
        "enabled": true,
        "ttl": "1h",
        "minTokens": 2048
      }
    }
  },
  "agent": {
    "plan": {
      "cache": {
        "ttl": "1h"
      }
    }
  }
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

MartinNowak, emagieika, and lmerz1 reacted with hooray emoji yamiteru, Sewer56, code-yeongyu, airtonix, olivierwilkinson, jinzhongjia, kostya9, konekohana, franroa, hakan-demirli, and 30 more reacted with heart emoji
All reactions
  • 🎉 3 reactions
  • ❤️ 40 reactions
@ormandj ormandj mentioned this pull request Dec 12, 2025
[FEATURE]: Anthropic (and others) caching improvement #5416
Closed
1 task done
@ormandj
ormandj force-pushed the provider-cache-optimization branch 2 times, most recently from ce7acc2 to 7b1f516 Compare December 12, 2025 06:28
@ormandj ormandj changed the title feat(provider): add provider-specific cache configuration system feat(provider): add provider-specific cache configuration system (significant token usage reduction) Dec 12, 2025
Sewer56
Sewer56 reviewed Dec 12, 2025
View reviewed changes

@Sewer56 Sewer56 left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a second pair of eyes but 👍 from me

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@yamiteru

yamiteru commented Dec 12, 2025

Copy link
Copy Markdown

Please merge this ❤️

I'm deciding whether we should use opencode in our company and I'm actually surprised this wasn't implemented up until now.

ShanePresley, anomatomato, emagieika, maujavier91, and sergey-cs reacted with thumbs up emoji
All reactions
  • 👍 5 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ormandj

ormandj commented Dec 12, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Author

I tested with providers I have access to. I can confirm it works with with Anthropic (Opus 4.5), Google (Gemini 3 Pro preview), and Mistral (Devstral 2).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ormandj
feat(provider): add provider-specific cache configuration system
d213e39
Implements comprehensive ProviderConfig system for provider-specific caching
and prompt optimization. Addresses cache configuration needs from anomalyco#5416.

- Add ProviderConfig namespace with defaults for 19+ providers
- Support three caching paradigms: explicit-breakpoint, automatic-prefix, implicit
- Add tool sorting and caching for cache consistency
- Add user config overrides via opencode.json (provider and agent level)
- Simplify system message handling with combineSystemMessages boolean
@ormandj
ormandj force-pushed the provider-cache-optimization branch from 7b1f516 to d213e39 Compare December 12, 2025 16:31
@ormandj

ormandj commented Dec 12, 2025

Copy link
Copy Markdown
Author

Updated one of the comments to be more clear, but no functional changes.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr

thdxr commented Dec 12, 2025

Copy link
Copy Markdown
Member

hey thanks for working on this - i'm actually currently mid refactor on a bunch of code where we call LLMs so we probably can't explicitly accept this PR (llm-centralization branch)

also i don't know if we want to go as far as making all this deeply configurable yet

could you lay out all the things you improved on top of what we have currently? then i can make sure those get included

yamiteru, gytis-ivaskevicius, tommyminds, Sophomoresty, anomatomato, kvn1351, and GIS-PuppetMaster reacted with thumbs down emoji yamiteru reacted with confused emoji
All reactions
  • 👎 7 reactions
  • 😕 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr

thdxr commented Dec 12, 2025

Copy link
Copy Markdown
Member

i can also just read the PR/have opencode summarize haha. i'll do a pass once that llm-centralization branch is merged

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ormandj

ormandj commented Dec 12, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Author

i can also just read the PR/have opencode summarize haha. i'll do a pass once that llm-centralization branch is merged

Ok, that's fine. I added comments throughout that should help your opencode summarization, but I'm happy to discuss if you need more clarity. I'm on discord if you need more input. I was initially going to refactor all of your provider handling, but it sounds like you're already doing this - I designed this PR to be a stepping stone towards that since I didn't want to make my very first PR be a massive rewrite of lots of things.

If you just want to take my work and fold it into your work, I understand, at the end of the day it's of huge benefit to the users, so I'll be happy. Thank you for taking the time to evaluate things and hope to see your rewrite soon! I can also just update this once you're done/merged in, just let me know what works best.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@gytis-ivaskevicius

gytis-ivaskevicius commented Dec 15, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Hey, thanks for this PR. I started playing around with it. Can you do me a favor and add the following patch to visualize token cache statistics on the sidebar? FYI: I am not 100% confident that this is the best way of calculating the percentage

Should this be shown in the sidebar?: I think it should, not only will it help us to spot issues, but also let users notice models that do not support caching

diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
index c1c29a73..afaaad73 100644
--- a/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
+++ b/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
@@ -42,9 +42,20 @@ export function Sidebar(props: { sessionID: string }) {
     const total =
       last.tokens.input + last.tokens.output + last.tokens.reasoning + last.tokens.cache.read + last.tokens.cache.write
     const model = sync.data.provider.find((x) => x.id === last.providerID)?.models[last.modelID]
+
+    // Calculate cache hit percentage
+    const cacheHitPercentage = total > 0 ? Math.round((last.tokens.cache.read / total) * 100) : 0
+    const cacheRead = last.tokens.cache.read
+    const cacheWrite = last.tokens.cache.write
+
     return {
       tokens: total.toLocaleString(),
       percentage: model?.limit.context ? Math.round((total / model.limit.context) * 100) : null,
+      cache: {
+        hitPercentage: cacheHitPercentage,
+        read: cacheRead,
+        write: cacheWrite,
+      },
     }
   })

@@ -81,6 +92,11 @@ export function Sidebar(props: { sessionID: string }) {
               </text>
               <text fg={theme.textMuted}>{context()?.tokens ?? 0} tokens</text>
               <text fg={theme.textMuted}>{context()?.percentage ?? 0}% used</text>
+              <Show when={context()?.cache !== undefined}>
+                <text style={{ fg: context()!.cache.hitPercentage > 0 ? theme.success : theme.textMuted }}>
+                  {context()!.cache.hitPercentage}% cached
+                </text>
+              </Show>
               <text fg={theme.textMuted}>{cost()} spent</text>
             </box>
             <Show when={mcpEntries().length > 0}>
(END)

Maybe the correct way would be to do something like this instead 🤔

  const totalInput = last.tokens.input + last.tokens.cache.read + last.tokens.cache.write
  const cacheHitPercentage = totalInput > 0 ? Math.round((last.tokens.cache.read / totalInput) * 100) : 0

Also, I think the whole ripgrep tree is introducing cache misses on file additions/deletions. Probably, it should be set on a per-session basis and not update automatically

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ormandj

ormandj commented Dec 15, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Author

Hey, thanks for this PR. I started playing around with it. Can you do me a favor and add the following patch to visualize token cache statistics on the sidebar? FYI: I am not 100% confident that this is the best way of calculating the percentage

Should this be shown in the sidebar?: I think it should, not only will it help us to spot issues, but also let users notice models that do not support caching

diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
index c1c29a73..afaaad73 100644
--- a/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
+++ b/packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx
@@ -42,9 +42,20 @@ export function Sidebar(props: { sessionID: string }) {
     const total =
       last.tokens.input + last.tokens.output + last.tokens.reasoning + last.tokens.cache.read + last.tokens.cache.write
     const model = sync.data.provider.find((x) => x.id === last.providerID)?.models[last.modelID]
+
+    // Calculate cache hit percentage
+    const cacheHitPercentage = total > 0 ? Math.round((last.tokens.cache.read / total) * 100) : 0
+    const cacheRead = last.tokens.cache.read
+    const cacheWrite = last.tokens.cache.write
+
     return {
       tokens: total.toLocaleString(),
       percentage: model?.limit.context ? Math.round((total / model.limit.context) * 100) : null,
+      cache: {
+        hitPercentage: cacheHitPercentage,
+        read: cacheRead,
+        write: cacheWrite,
+      },
     }
   })

@@ -81,6 +92,11 @@ export function Sidebar(props: { sessionID: string }) {
               </text>
               <text fg={theme.textMuted}>{context()?.tokens ?? 0} tokens</text>
               <text fg={theme.textMuted}>{context()?.percentage ?? 0}% used</text>
+              <Show when={context()?.cache !== undefined}>
+                <text style={{ fg: context()!.cache.hitPercentage > 0 ? theme.success : theme.textMuted }}>
+                  {context()!.cache.hitPercentage}% cached
+                </text>
+              </Show>
               <text fg={theme.textMuted}>{cost()} spent</text>
             </box>
             <Show when={mcpEntries().length > 0}>
(END)

Maybe the correct way would be to do something like this instead 🤔

  const totalInput = last.tokens.input + last.tokens.cache.read + last.tokens.cache.write
  const cacheHitPercentage = totalInput > 0 ? Math.round((last.tokens.cache.read / totalInput) * 100) : 0

Also, I think the whole ripgrep tree is introducing cache misses on file additions/deletions. Probably, there should be a toggle to get rid of it

I'd be happy to do this except I was informed by @thdxr they are reworking this application, so I assume they intend to take these ideas and just merge it into whatever they're working on. I'm leaving this open until I hear otherwise, but I'm not sure it makes sense for me to do more implementation at this point with @thdxr 's input. As far as doing cache statistics, I have a number of ideas that would work, but I don't want to invest time into it to have it closed out unmerged.

gytis-ivaskevicius, wienans, Sewer56, and anomatomato reacted with thumbs up emoji
All reactions
  • 👍 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Sewer56

Sewer56 commented Dec 16, 2025

Copy link
Copy Markdown
Contributor

Given that llm-centralization branch has been merged; is there any hope of bringing the improvements from here onto mainline? @thdxr

Seems the person opening the PR is waiting for feedback; and until there is any- it seems they're going to be left in the dark.

konekohana, gytis-ivaskevicius, Sewer56, rujialiu, LaurensBosscher, ShanePresley, JamieHaywood-Lyka, and anomatomato reacted with thumbs up emoji
All reactions
  • 👍 8 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@rdvo

rdvo commented Dec 29, 2025

Copy link
Copy Markdown

wait so opencode doesnt use prompt caching by default ? Or im confused here

yamiteru, thevinchi, ShanePresley, and anomatomato reacted with confused emoji
All reactions
  • 😕 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@rujialiu

rujialiu commented Jan 3, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Happy to see this PR and thank you for your work! @ormandj

I've just found a prefix caching issue when using opencode 1.0.223 with my locally served model with llama.cpp: The current system prompt contains the working directory's content very early, so when the directory is changing (e.g. the agent writes to a new file), the prefix caching is invalidated. For locally served models, this is especially serious because unless your hardware is extremely powerful, each miss is several minutes' delay.

gab reacted with confused emoji
All reactions
  • 😕 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Jan 5, 2026
fix(provider): add support for jp. prefix in Amazon Bedrock cross-region inference profiles #6916
Merged
feat(llm): optimize system prompt for better reasoning #7037
Closed
feat: implement smart pruning #7215
Closed
@github-actions github-actions Bot mentioned this pull request Jan 23, 2026
feat: add openai-compatible endpoint support for google-vertex provider #10303
Merged
@olivierwilkinson

olivierwilkinson commented Jan 26, 2026

Copy link
Copy Markdown

@thdxr now that llm-centralization is merged do you have a timeline for this PR? I'd love to switch back to opencode but until this work is merged I'm not able to.

yamiteru, thevinchi, weiyiguo9, anomatomato, and sergey-cs reacted with thumbs up emoji
All reactions
  • 👍 5 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot mentioned this pull request Jan 27, 2026
feat: Add TOON (Token-Oriented Object Notation) format for LLM prompt optimization #10772
Closed
@thevinchi

thevinchi commented Jan 27, 2026

Copy link
Copy Markdown
Contributor

tl;dr: is this work something that will reduce input token counts when using AWS Bedrock with Anthropic models? It appears caching is already in use (based on opencode stats reports).

--

We use AWS Bedrock with Anthropic models for product work exclusively. Some on our team use Claude Code, and some use Opencode. Those who use Opencode have orders of magnitude more input token counts, like hundreds of thousands more, in some cases millions.

I understand this is anecdata, but we're all doing similar work with similar tools with the same provider/models.

This has massive cost implications, of course. AWS just announced 1hr cache TTL support for Anthropic Claude.* 4.5 models as well. At the very least, this PR will allow us to toggle cache settings correct?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ormandj

ormandj commented Jan 28, 2026

Copy link
Copy Markdown
Author

Sorry folks, the maintainers made it clear when I first submitted this they had other plans. I don't know where they currently are on things, but I feel badly that you're all dealing with the poor caching/token behavior. I don't think it's a priority for them, and I'm not going to invest time in reworking the patch for their changes since it was made apparent they are not interested in the work and it wouldn't be accepted even if I did.

gamesover, jdanbrown, skerit, zqni, moelyman, borisnaidis, olivierwilkinson, johnnymo87, ShanePresley, JamieHaywood-Lyka, and 6 more reacted with confused emoji
All reactions
  • 😕 16 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr
thdxr force-pushed the dev branch from cbab81f to 2d3c7a0 Compare January 30, 2026 04:50
@opencode-agent
opencode-agent Bot force-pushed the dev branch from 00637c0 to 71e0ba2 Compare January 30, 2026 14:32
@thdxr
thdxr force-pushed the dev branch 2 times, most recently from f802701 to f1ae801 Compare January 30, 2026 14:36
This was referenced May 3, 2026
Release blocked: build failed for v1.14.33 johnnymo87/opencode-cached#42
Open
Release blocked: build failed for v1.14.34 johnnymo87/opencode-cached#43
Open
Release blocked: build failed for v1.14.37 johnnymo87/opencode-cached#44
Open
Release blocked: build failed for v1.14.39 johnnymo87/opencode-cached#45
Open
Release blocked: build failed for v1.14.40 johnnymo87/opencode-cached#46
Open
Release blocked: build failed for v1.14.41 johnnymo87/opencode-cached#47
Open
This was referenced May 10, 2026
Release blocked: build failed for v1.14.45 johnnymo87/opencode-cached#48
Open
Release blocked: build failed for v1.14.46 johnnymo87/opencode-cached#49
Open
Release blocked: build failed for v1.14.48 johnnymo87/opencode-cached#50
Open
This was referenced May 12, 2026
feat(cache): add cache token audit logging behind OPENCODE_EXPERIMENTAL_CACHE_AUDIT #27007
Closed
feat(cache): split system prompt into stable/dynamic blocks for independent caching #27377
Closed
fix(cache): stabilize system prefix behind OPENCODE_EXPERIMENTAL_CACHE_STABILIZATION #27378
Closed
This was referenced May 14, 2026
Release blocked: build failed for v1.14.49 johnnymo87/opencode-cached#51
Open
Release blocked: build failed for v1.14.50 johnnymo87/opencode-cached#52
Open
Release blocked: build failed for v1.15.0 johnnymo87/opencode-cached#53
Open
Release blocked: build failed for v1.15.1 johnnymo87/opencode-cached#54
Open
Release blocked: build failed for v1.15.3 johnnymo87/opencode-cached#55
Open
Release blocked: build failed for v1.15.4 johnnymo87/opencode-cached#56
Open
Release blocked: build failed for v1.15.5 johnnymo87/opencode-cached#57
Open
This was referenced May 21, 2026
Release blocked: build failed for v1.15.6 johnnymo87/opencode-cached#58
Open
Release blocked: build failed for v1.15.7 johnnymo87/opencode-cached#59
Open
Release blocked: build failed for v1.15.9 johnnymo87/opencode-cached#60
Open
Release blocked: build failed for v1.15.10 johnnymo87/opencode-cached#61
Open
@rikkarth rikkarth mentioned this pull request May 30, 2026
fix(session): move env block to tail of system prompt for cache stability #29949
Closed
3 tasks done
@johnnymo87 johnnymo87 mentioned this pull request Jun 2, 2026
Drop caching.patch; ride upstream applyCaching + tiny thinking-skip johnnymo87/opencode-patched#15
Merged
@github-actions github-actions Bot mentioned this pull request Jun 11, 2026
📊 AI CLI 工具社区动态日报 2026-06-11 zx0828/big_model_radar#104
Open
@github-actions github-actions Bot mentioned this pull request Jun 21, 2026
feat(core): make system prompt immutable after session creation #33246
Closed
3 of 6 tasks
@taziz-prophix taziz-prophix mentioned this pull request Sep 18, 2026
bug(bedrock): cachePoint after reasoning block still wedges sessions on 1.18.31 — a tested fix exists in auto-closed PR #36532 #49859
Closed
@thdxr

thdxr commented Oct 10, 2026

Copy link
Copy Markdown
Member

This branch has been upgraded to V2. We're no longer taking PRs for V1. If you think this is still relevant, please port it over and open it for V2.

— from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

ormandj reacted with thumbs down emoji
All reactions
  • 👎 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr thdxr closed this Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

1 more reviewer
@Sewer56 Sewer56 Sewer56 left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

[FEATURE]: Anthropic (and others) caching improvement

Uh oh!

There was an error while loading. Please reload this page.

15 participants

@ormandj @yamiteru @thdxr @gytis-ivaskevicius @Sewer56 @rdvo @rujialiu @olivierwilkinson @thevinchi @hazrid93 @JackDrogon @johnnymo87 @sircoderin @nazriel @kommander
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.