techlist.io

Prompt Caching

6 posts

GitHub2026-06-173 min readCurated summary

Getting more from each token: How Copilot improves context handling and model routing

GitHub is improving Copilot’s efficiency by optimizing both how context is handled and which model performs each task. Prompt caching and deferred tool loading reduce repeated overhead in long agentic sessions, while Auto selects models based on task complexity and real-time system conditions. The goal is to preserve quality while using tokens, compute, and cost more intelligently. ## Prompt Caching and Deferred Tools - Copilot sessions repeatedly include instructions, repository context, conversation history, tool definitions, and task state. - Prompt caching allows repeated prompt prefixes to reuse model state instead of being recomputed on every request. - Tool search loads tool definitions only when needed, rather than placing every full schema into context on every turn. - This is especially valuable for sessions involving MCP tools, terminal commands, file operations, workspace search, and other actions. - The approach reduces fixed per-turn overhead while preserving access to a broad toolset. ## Auto Model Selection - Copilot Auto chooses a model based on the task rather than requiring developers to select one manually. - Quick explanations, focused edits, and complex multi-file changes often benefit from different levels of reasoning. - Evaluations found that no single model consistently performs best across all tasks. - Auto uses more efficient models when they can achieve comparable results and selects stronger reasoning models when the task demands them. - The objective is not simply lower cost, but matching model capability to the work. ## How Auto Routes Tasks Auto combines two signals: - **Real-time model health** - Considers availability, utilization, response speed, error rates, and cost. - Avoids selecting a model that is technically capable but currently overloaded or unreliable. - **Task-aware routing with HyDRA** - Evaluates reasoning depth, code complexity, debugging difficulty, and tool-orchestration requirements. - Identifies models capable of meeting the task’s quality threshold, then chooses the best fit among them. - The system can be tuned toward maximum quality or greater cost savings. ## Cache-Aware Routing - Switching models during every turn can reduce efficiency by invalidating cached prompt prefixes. - Auto therefore keeps the same model during a conversation so the cache can continue building. - It changes models at natural cache boundaries: - The first turn, when no cache exists yet. - After context compaction, when older turns are summarized and the prompt prefix resets. ## Multilingual Routing - Copilot’s routing system was trained on conversations spanning 16 language families, including CJK and European languages. - Evaluations covered production VS Code chat data across 19 languages. - Routing accuracy remained within four points of the English baseline across language groups. - No statistically significant quality gap was observed between the language groups. Copilot’s efficiency strategy combines smarter context management with adaptive model selection. Caching and on-demand tools reduce repeated work, while cache-aware Auto routing chooses an appropriate model without unnecessarily sacrificing quality or session efficiency.

GitLab2026-05-282 min readCurated summary

Claude Opus 4.8 on GitLab: Complex agentic work, less disruption

Claude Opus 4.8 is now available in GitLab Duo Agent Platform for complex, multi-step coding and agentic workflows. The model is designed to follow instructions more precisely over extended autonomous runs, reducing the need for human correction and intervention. It also supports mid-conversation system-prompt updates without invalidating the prompt cache, making it better suited to changing contexts. ## Improved Long-Horizon Agentic Execution - Handles complex workflows involving multiple tools and extended sequences. - Provides more comprehensive planning and reasoning. - Produces more accurate end states with fewer interruptions or redirects. - Interprets instructions more precisely than previous models. - Supports professional tasks beyond coding, including: - Document drafting - Data analysis - Structured knowledge work ## Mid-Conversation System Prompts - System instructions can change during an active session. - Prompt-cache validity is preserved when context changes. - This is useful when: - Files change on disk - Token budgets shift - User context is updated - Asynchronous information arrives ## Availability and Pricing - Available through model selection in Agentic Chat and across GitLab Duo agent workflows. - Runs on GitLab Credits. - GitLab Premium and Ultimate subscribers can use included credits. - New users can access it through a GitLab Duo Agent Platform trial or the GitLab Free tier. Teams seeking more reliable autonomous coding and documentation workflows can use Opus 4.8 in GitLab Duo to reduce manual oversight while agents complete longer, more complex tasks.

Anthropic2026-04-233 min readCurated summary

An update on Claude Code quality reports

Anthropic investigated reports that Claude's responses had worsened in Claude Code, the Claude Agent SDK, and Claude Cowork over the past month. The company traced them to three separate changes in the product layer, not the API or inference layer, and resolved all three by April 20 (v2.1.116). Anthropic says it never intentionally degrades its models, and it is resetting usage limits for all subscribers. ## Default Reasoning Effort Lowered to Medium - On March 4, Claude Code's default effort changed from high to medium to reduce long latency that sometimes made the UI appear frozen. - In internal evals, medium was slightly less intelligent but much faster, with fewer long thinking tails and lower usage. - Users reported that Claude Code felt less intelligent. Design changes to surface the effort setting didn't stop most users from keeping medium. - Anthropic reversed the change on April 7. Opus 4.7 now defaults to xhigh effort, and other models default to high. ## Idle Session Thinking Cleared on Every Turn - A March 26 change was meant to clear old reasoning after a session had been idle for over an hour, reducing the cost of resuming it. It used the `clear_thinking_20251015` API header with `keep:1`. - A bug caused the clearing to happen on every turn for the rest of the session instead of once. Follow-up messages sent during a tool use also dropped the current turn's reasoning. - The result was a Claude that seemed forgetful, repetitive, and odd in its tool choices. Constant cache misses also likely drained usage limits faster than expected. - Two unrelated experiments hid the bug during testing, and it passed code reviews, unit tests, and end-to-end tests. Fixed April 10 in v2.1.101. - When back-tested, Opus 4.7 found the bug in Code Review when given the full repositories for context, while Opus 4.6 did not. Anthropic is adding support for more repositories as review context. ## Verbosity Limits in the System Prompt - Opus 4.7 tends to be verbose. To counter this, a system prompt addition capped text between tool calls at 25 words and final responses at 100 words, unless the task needed more detail. - The change shipped with Opus 4.7 on April 16. A broader ablation study later showed a 3% drop for both Opus 4.6 and 4.7, and the prompt was reverted on April 20. ## Process Changes Going Forward - More internal staff will use the public Claude Code build rather than pre-release builds. - Anthropic will ship its improved internal Code Review tool to customers. - Every system prompt change will get a per-model eval suite, ongoing line-by-line ablations, and new review tooling. Model-specific changes will be gated to their target models. - Changes that could trade off against intelligence will go through soak periods, broader evals, and gradual rollouts. - Anthropic launched @ClaudeDevs on X and will post matching updates in GitHub threads. Anthropic credited users who submitted reports through `/feedback` or posted reproducible examples online for helping identify the problems.

Cloudflare2026-04-163 min readCurated summary

Building the foundation for running extra-large language models

Cloudflare is building infrastructure for serving extra-large open-source language models efficiently, especially for agentic applications with long prompts and frequent tool calls. Its approach combines specialized hardware configurations, prefill/decode disaggregation, prompt caching, distributed KV-cache management, and speculative decoding. These optimizations substantially improve latency, throughput, and cost efficiency without requiring more GPUs. ## Hardware Configurations for Agent Workloads - Different applications stress models differently: - Content generation sends fewer input tokens but produces many output tokens. - Summarization sends very large inputs and generates relatively short outputs. - Agent workloads typically involve: - Large system prompts - Tool and MCP definitions - Accumulated conversation history - Generated code and previous interactions - Workers AI therefore prioritizes fast input processing and tool-calling performance. ## Prefill-Decode Disaggregation - LLM inference has two stages: - **Prefill:** Processes input tokens and populates the KV cache; generally compute-bound. - **Decode:** Generates output tokens; generally memory-bound. - Running both stages on one server can underutilize GPUs because they stress different resources. - Cloudflare separates them across dedicated inference servers: - A prefill server processes the request and stores its KV cache. - A decode server retrieves the cache and generates the response. - This enables independent tuning, scaling for input- or output-heavy traffic, and use of heterogeneous hardware. - The architecture requires a sophisticated load balancer that: - Transfers KV-cache metadata between stages. - Rewrites streaming SSE responses. - Handles different inference-server protocols. - Balances traffic based on estimated in-flight prefill and decode tokens. - After adopting this design, Cloudflare saw: - Lower p90 time to first token and reduced tail-latency variance. - Intertoken latency fall from roughly 100 ms to 20–30 ms. - About a threefold improvement while using the same number of GPUs. ## Prompt Caching and Session Affinity - Long agent conversations repeatedly reuse the same context, making prompt caching essential. - The `x-session-affinity` header routes requests toward regions containing previously computed input tensors. - Cloudflare added support for this header to agent harnesses such as OpenCode. - Cached prompts improve: - Overall throughput - Interactive response times - Pricing, with discounted cached tokens - GPU efficiency - Adoption by heavy internal users increased peak input-token cache hit rates from 60% to 80%. ## Distributed KV-Cache Optimization - Larger models span multiple GPUs, requiring KV caches to be shared across devices and nodes. - For Kimi, Cloudflare uses Moonshot AI’s: - **Mooncake Transfer Engine** for high-speed memory transfers using RDMA technologies such as NVLink and NVMe over Fabric. - **Mooncake Store** to extend cache storage beyond GPU VRAM onto NVMe. - Combined with LMCache or SGLang HiCache, the system can: - Reuse cached prompts from any node in a cluster. - Reduce reliance on session-aware routing. - Balance traffic more evenly. - Keep sessions cached longer. - Increase cache hit rates and supported throughput. ## Speculative Decoding - The post begins introducing speculative decoding as another optimization. - It describes the basic LLM process of predicting successive tokens, but the provided text ends before explaining the technique or its results. Cloudflare’s overall strategy is to match infrastructure to real usage patterns rather than rely on a single hardware configuration. Separating inference stages, maximizing cache reuse, and distributing KV caches are practical ways to make large-model hosting faster and more economical.

Anthropic2025-11-244 min readCurated summary

Introducing advanced tool use for Claude

# Anthropic's Advanced Tool Use: Tool Search, Programmatic Calling, and Usage Examples Anthropic argues that agents need to work with hundreds or thousands of tools without overloading their context window, call tools from code rather than one at a time, and learn correct usage from examples rather than schemas alone. To address this, the post introduces three beta features: Tool Search Tool, Programmatic Tool Calling, and Tool Use Examples. Internal testing shows these features cut token usage substantially while improving accuracy on tool-heavy tasks. ## Tool Search Tool Loading every tool definition upfront wastes context. A five-server MCP setup can consume about 55K tokens before a conversation starts, and Anthropic has seen definitions reach 134K tokens. Wrong tool selection is also common when names are similar, such as `notification-send-user` versus `notification-send-channel`. - Tools marked with `defer_loading: true` are excluded from the initial prompt. Claude sees only the search tool plus tools marked `defer_loading: false`. - When Claude needs a capability, it searches (regex, BM25, or a custom method such as embeddings), and only the matching tools expand into full definitions. - Entire MCP servers can be deferred with `mcp_toolset` configs, while frequently used tools stay loaded. - Because deferred tools are left out of the initial prompt, the system prompt and core tool definitions remain cacheable. - In the reported example, context use dropped from about 77K to 8.7K tokens, an 85% reduction. - Accuracy on MCP evaluations improved: Opus 4 went from 49% to 74%, and Opus 4.5 from 79.5% to 88.1%. - It suits setups with more than 10 tools or definitions over 10K tokens. It is less useful with fewer than 10 compact tools or tools used in every session, since the search step adds latency. ## Programmatic Tool Calling Conventional tool calling floods context with intermediate results and requires a full inference pass per call. Programmatic Tool Calling lets Claude write Python that orchestrates tools inside a sandboxed code execution environment, so Claude sees only the final output. - Tools opt in through `allowed_callers`, and the API exposes them as Python functions. - In the budget compliance example, a script fetches team members, budgets, and expenses for 20 people (about 200KB of raw data), and Claude receives only the one to three people who exceeded their limits (about 1KB). - Average token usage fell from 43,588 to 27,297 (37%) on complex research tasks, and accuracy improved on internal benchmarks. - Latency drops because 20+ tool calls can run in one code block instead of 20+ inference passes. - It is most useful for large datasets, workflows with three or more dependent calls, and parallel operations. Single calls and tasks where Claude must reason over every intermediate result gain little. - Claude for Excel uses this approach to handle spreadsheets with thousands of rows. ## Tool Use Examples JSON Schema defines structure but cannot show when optional parameters apply, which combinations make sense, or what format conventions an API expects. Ambiguous fields such as date formats, ID patterns, and nested objects often lead to malformed calls. - An `input_examples` array in the tool definition shows concrete calls, including minimal, partial, and full specifications. - Examples teach conventions such as `YYYY-MM-DD` dates, `USR-XXXXX` IDs, and which optional fields go with which priority levels. - In Anthropic's internal testing, accuracy on complex parameter handling rose from 72% to 90%. - Keep it to 1–5 realistic examples per tool, focused on ambiguity the schema doesn't resolve. Examples add tokens, so they are less useful for simple tools or standard formats like emails and URLs. ## Practical Recommendations Start with the bottleneck that limits your agent most: context bloat points to Tool Search, large intermediate results point to Programmatic Tool Calling, and parameter errors point to Tool Use Examples. The features complement each other, and clear tool names and descriptions improve search accuracy. The features are available in beta under the `advanced-tool-use-2025-11-20` header.

Anthropic2024-09-194 min readCurated summary

Contextual retrieval in AI systems

# Contextual Retrieval: Improving RAG Accuracy by Adding Chunk Context The post argues that traditional RAG systems lose critical information when documents are split into chunks, causing retrieval failures. Its proposed fix, Contextual Retrieval, prepends chunk-specific explanatory context to each chunk before embedding and BM25 indexing. Combined with BM25 and reranking, this cuts the top-20-chunk retrieval failure rate from 5.7% to 1.9%, a 67% reduction. ## When Simple Prompting Is Enough - If the knowledge base is under about 200,000 tokens (roughly 500 pages), it can be placed directly in the prompt without RAG. - Prompt caching makes this approach faster and cheaper, with latency reduced by more than 2x and costs by up to 90%. - Larger knowledge bases still need a retrieval system. ## How Traditional RAG Works and Where It Falls Short - Documents are split into chunks of a few hundred tokens, converted to vector embeddings, and stored in a vector database for semantic search. - Embeddings can miss exact matches, such as an error code like "TS-999." BM25, a lexical ranking function built on TF-IDF, handles these well. - Combining embeddings and BM25 with rank fusion improves results, but chunks often lose context. A chunk like "The company's revenue grew by 3% over the previous quarter" doesn't name the company or the time period. ## Contextual Embeddings and Contextual BM25 - Each chunk is prepended with a short, 50–100 token context situating it within the whole document before embedding and BM25 indexing. - Claude (Claude 3 Haiku in the post) generates this context from the full document and the chunk, using a prompt that asks for a succinct explanation to improve search retrieval. - Manually annotating millions of chunks is impractical, so the model automates the process. - Other context-adding approaches, such as generic document summaries, hypothetical document embeddings, and summary-based indexing, showed limited gains in the authors' tests. ## Keeping Costs Down with Prompt Caching - The full document is cached once and referenced for every chunk, so it isn't resent each time. - With 800-token chunks, 8k-token documents, and 100 tokens of context per chunk, the one-time cost is about $1.02 per million document tokens. ## Experimental Results - Tests covered codebases, fiction, ArXiv papers, and science papers, across several embedding models and retrieval strategies. - Using Gemini Text 004 and top-20 retrieval, contextual embeddings alone reduced the failure rate by 35% (5.7% → 3.7%). - Contextual embeddings combined with contextual BM25 reduced it by 49% (5.7% → 2.9%). - Adding reranking brought the failure rate down to 1.9%, a 67% reduction. ## Implementation Considerations - Chunk size, boundaries, and overlap all affect retrieval performance. - Gemini and Voyage embeddings performed best among the models tested, though contextualization helped every model. - Custom contextualizer prompts, such as ones that include a glossary of domain terms, may improve results further. - Passing 20 chunks to the model outperformed 5 or 10, though more chunks can also distract the model. - Evaluate on your own use case, and consider clearly separating the context from the chunk text during response generation. ## Reranking - Initial retrieval fetches a larger candidate set (the authors used the top 150). - A reranking model, such as Cohere's, scores each chunk against the query, and the top 20 go to the generator. - Reranking improves accuracy and lowers the cost and latency of generation, but it adds a small amount of latency itself. The number of chunks to rerank is a trade-off between accuracy and speed. ## Practical Takeaway The authors recommend combining contextual embeddings (using Voyage or Gemini), contextual BM25, reranking, and passing the top 20 chunks to the model. They provide a cookbook for implementing the approach.