Skip to content

feat(tools): implement tactful extraction for token efficiency - #18924

Closed
adamfweidman wants to merge 10 commits into
mainfrom
afw/read-exp-v3
Closed

adamfweidman wants to merge 10 commits into
mainfrom
afw/read-exp-v3

Conversation

@adamfweidman

@adamfweidman adamfweidman commented Feb 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR implements the "Tactful Extraction" rework, designed to optimize token efficiency. By moving away from broad "firehose" file reads toward surgical, targeted exploration, we successfully reduced overall token consumption by 6.9% while matching the main branch resolution baseline.

Details

1. Tool & API Rework

  • read_file (Precision API): Swapped to a 1-based start_line/end_line API for Gemini 3 models. This removes the 0-based offset mental math and aligns with standard Unix output (e.g., grep -n).
  • run_shell_command (The Scalpel): Explicitly framed as the preferred tool for surgical extraction. Centralized guidance in coreTools.ts now includes specific sed regex examples for semantic block extraction (e.g., class/function boundaries).
  • grep_search (Primary Discovery): Re-framed as the primary scout. Encouraged using context flags (before/after) to "find and read" in a single turn, reducing the need for follow-up read_file calls.

2. System Prompt & Efficiency Mandate

  • "Be Token-Frugal": Codified a strict mandate in snippets.ts explaining that context persists and that unnecessary early-trial bloat carries a permanent "tax" on every turn.
  • Workflow Alignment: Updated the Research and Understand lifecycle steps to favor context-based search and precise range reads over broad, assumption-based reads.

3. Integrated Frugal Search

📊 Performance Impact (vs. main)

  • Intelligence: Matches main baseline resolution.
  • Cost: -6.9% total input tokens (~60M tokens saved across sweep).
  • Context: ~3k–5k reduction in average context size per turn.

Related Issues

Fixes #17545
Fixes #17542

How to Validate

  1. Unit Tests: Run npm test -w @google/gemini-cli-core to verify 1-based range logic and snapshot accuracy.
  2. Build: Run npm run build to verify full workspace integrity.
  3. Trajectory Check: Verify that models effectively use sed -n '/pattern1/,/pattern2/p' for semantic block extraction.

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Validated on required platforms/methods:
    • MacOS
      • npm run

- Use dynamic schema to hide offset/limit for 3.0 models.
- Update truncation guidance for 3.0 models to encourage shell tools.
- Maintain legacy behavior for 2.5 models.
- Add TODO for signature cleanup in fileUtils.ts.
- Restore precision to read_file with 1-based start_line and end_line for Gemini 3.
- Update tool descriptions to establish extraction hierarchy (rg > shell/sed > read_file).
- Codify 'Be Token-Frugal' mandate in system prompt snippets.
- Refine research workflow to allow context-based validation via search tools.
- Update unit tests and verified build integrity.
- Centralized tool definitions in coreTools.ts with improved surgical extraction guidance.
- Resolved conflicts in read-file.ts, shell.ts, glob.ts, and ripGrep.ts.
- Merged Search Frugality instructions from main with our Token Frugality mandate.
- Updated unit tests and snapshots.
This PR optimizes how the agent explores and reads code by providing precision extraction tools and mandating token frugality.

Key Changes:
- Restore precision to read_file with 1-based start_line and end_line for Gemini 3.
- Update tool descriptions to establish extraction hierarchy (rg > shell/sed > read_file).
- Codify 'Be Token-Frugal' mandate in system prompt snippets.
- Refine research workflow to allow context-based validation via search tools.
- Merge latest main improvements including Search Frugality parameters.
- Update unit tests and verified build integrity.
@adamfweidman
adamfweidman requested review from a team as code owners February 12, 2026 16:43
@gemini-cli

gemini-cli Bot commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

Hi @adamfweidman, thank you so much for your contribution to Gemini CLI! We really appreciate the time and effort you've put into this.

We're making some updates to our contribution process to improve how we track and review changes. Please take a moment to review our recent discussion post: Improving Our Contribution Process & Introducing New Guidelines.

Key Update: Starting January 26, 2026, the Gemini CLI project will require all pull requests to be associated with an existing issue. Any pull requests not linked to an issue by that date will be automatically closed.

Thank you for your understanding and for being a part of our community!

@github-actions

github-actions Bot commented Feb 12, 2026 •

Copy link
Copy Markdown

Size Change: +7.48 kB (+0.03%)

Total Size: 24.3 MB

Filename Size Change
./bundle/gemini.js 24.3 MB +7.48 kB (+0.03%)
ℹ️ View Unchanged
Filename Size
./bundle/sandbox-macos-permissive-closed.sb 1.03 kB
./bundle/sandbox-macos-permissive-open.sb 890 B
./bundle/sandbox-macos-permissive-proxied.sb 1.31 kB
./bundle/sandbox-macos-restrictive-closed.sb 3.29 kB
./bundle/sandbox-macos-restrictive-open.sb 3.36 kB
./bundle/sandbox-macos-restrictive-proxied.sb 3.56 kB

compressed-size-action

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @adamfweidman, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant 'Tactful Extraction' rework aimed at optimizing token efficiency by shifting from broad file reads to more surgical and targeted data exploration. The changes involve refining existing tools and updating system prompts to guide models towards more frugal token consumption, ultimately leading to substantial cost savings and reduced context size without compromising performance.

Highlights

  • Tool & API Rework for Token Efficiency: The read_file tool now uses a 1-based start_line/end_line API for Gemini 3 models, aligning with standard Unix output. The run_shell_command tool is explicitly framed as the preferred tool for surgical extraction, with guidance including sed regex examples. The grep_search tool is re-framed as the primary discovery tool, encouraging the use of context flags to reduce follow-up read_file calls.
  • System Prompt & Efficiency Mandate: A strict 'Be Token-Frugal' mandate has been codified in system prompts, explaining that context persists and unnecessary early-trial bloat incurs a permanent 'tax'. Workflow steps like 'Research' and 'Understand' have been updated to favor context-based search and precise range reads over broad assumptions.
  • Integrated Frugal Search Features: The pull request merges recent updates from main (PR Update prompt and grep tool definition to limit context size #18780), incorporating new exclude_pattern, names_only, and max_matches_per_file parameters, which further enhance surgical extraction guidance.
  • Performance Impact: This rework has resulted in a 6.9% reduction in total input tokens (approximately 60M tokens saved across sweep) and a 3k–5k reduction in average context size per turn, while maintaining the main branch resolution baseline for intelligence.
Changelog
  • package-lock.json
    • Updated various dependency entries to include the 'peer: true' flag.
  • packages/core/src/core/snapshots/prompts.test.ts.snap
    • Updated system prompt snapshots to reflect new token efficiency guidelines.
    • Modified 'Final Reminder' to suggest 'appropriate search and extraction tools' instead of specifically 'read_file'.
    • Updated 'Understand' workflow step to recommend 'grep_search with context or read_file with precise ranges'.
    • Added new sections for 'Shell tool output token efficiency' and 'Token Efficiency' mandates.
  • packages/core/src/prompts/promptProvider.ts
    • Removed an unnecessary eslint-disable comment.
  • packages/core/src/prompts/snippets.legacy.ts
    • Updated 'Final Reminder' text to generalize file reading advice to 'appropriate search and extraction tools'.
    • Modified 'Understand' workflow step to recommend 'grep_search with context or read_file with precise ranges'.
  • packages/core/src/prompts/snippets.ts
    • Added 'enableShellEfficiency' option to OperationalGuidelinesOptions interface.
    • Modified 'getCoreSystemPrompt' and 'renderOperationalGuidelines' to pass primary workflow options.
    • Updated 'renderCoreMandates' to conditionally include 'Context Efficiency' guidelines based on grep enablement.
    • Introduced 'shellEfficiencyGuidelines' function to generate shell output efficiency text.
    • Adjusted 'workflowStepResearch' to dynamically suggest search tools and validation clauses based on grep and read file capabilities.
  • packages/core/src/tools/snapshots/read-file.test.ts.snap
    • Updated snapshot descriptions for the 'read_file' tool to be more concise and include Gemini 3 specific guidance.
  • packages/core/src/tools/snapshots/shell.test.ts.snap
    • Updated snapshot descriptions for the 'run_shell_command' tool to include guidance for surgical code extraction using 'sed' and reordered efficiency guidelines.
  • packages/core/src/tools/definitions/snapshots/coreToolsModelSnapshots.test.ts.snap
    • Updated 'glob' tool description to discourage its use for simple file listing.
    • Revised 'grep_search' tool description to emphasize its role as a primary discovery tool with context parameters.
    • Modified 'read_file' tool description to include Gemini 3 specific line range parameters and token efficiency advice, adding 'start_line' and 'end_line' to its schema.
    • Enhanced 'run_shell_command' tool description with explicit guidance for surgical code block extraction using 'sed'.
  • packages/core/src/tools/definitions/coreTools.ts
    • Updated 'READ_FILE_DEFINITION' description and schema to support 1-based 'start_line' and 'end_line' for Gemini 3 models, and added token efficiency recommendations.
    • Modified 'GREP_DEFINITION' description to highlight its primary discovery role and context parameters.
    • Adjusted 'GLOB_DEFINITION' description to advise against using it solely for file listing.
    • Integrated surgical extraction guidance using 'sed' into the 'run_shell_command' tool description.
  • packages/core/src/tools/read-file.test.ts
    • Added mock for 'getActiveModel' in ReadFileTool configuration.
    • Implemented new test cases to verify schema changes for 'read_file' based on model ID (Gemini 2.5 vs. Gemini 3).
    • Added validation tests for 'start_line' and 'end_line' parameters.
    • Included tests to confirm 'start_line' and 'end_line' functionality and Gemini 3 specific truncation messages.
  • packages/core/src/tools/read-file.ts
    • Imported necessary types and utility functions for model-specific behavior.
    • Extended 'ReadFileToolParams' interface with 'start_line' and 'end_line' properties.
    • Updated 'toolLocations' method to prioritize 'start_line' over 'offset'.
    • Modified 'execute' method to conditionally apply 'offset'/'limit' or 'start_line'/'end_line' based on the active model, and to provide model-specific truncation messages with tool suggestions.
    • Overrode 'getSchema' method to dynamically generate the tool schema, including appropriate line range parameters and descriptions based on the active model.
    • Added validation logic for 'start_line' and 'end_line' parameters.
  • packages/core/src/tools/ripGrep.ts
    • Updated 'RipGrepTool' description to emphasize its role as a primary discovery tool with context parameters.
  • packages/core/src/utils/fileUtils.test.ts
    • Added test cases for 'processSingleFileContent' to ensure correct handling of 'startLine' and 'endLine' parameters.
  • packages/core/src/utils/fileUtils.ts
    • Modified 'processSingleFileContent' function to accept optional 'startLine' and 'endLine' parameters.
    • Adjusted file content slicing logic to correctly use 'startLine' and 'endLine' (1-based) or fall back to 'offset' and 'limit' (0-based) for text files.
    • Updated truncation detection and return display messages to reflect the new line range parameters.
Activity
  • The pull request author, adamfweidman, implemented the 'Tactful Extraction' rework.
  • The changes include a significant refactoring of tool descriptions and system prompts to enhance token efficiency.
  • The latest changes from main (PR Update prompt and grep tool definition to limit context size #18780) were merged into this branch.
  • Unit tests were added and updated to verify the new 1-based range logic and snapshot accuracy.
  • The build process was validated to ensure full workspace integrity.
  • Trajectory checks were performed to verify models effectively use sed for semantic block extraction.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a "Tactful Extraction" rework to improve token efficiency, which is a great initiative. The changes are well-aligned with this goal, promoting more surgical use of tools like grep_search and run_shell_command with sed, and updating the read_file tool to support 1-based line ranges for newer models. The system prompts have been updated effectively to guide the model towards more token-frugal behavior. The comment regarding a minor regression in the detail of a tool description is valid and should be addressed. Overall, this is a solid improvement.

Comment thread packages/core/src/tools/read-file.ts Outdated
@gemini-cli gemini-cli Bot added area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. labels Feb 12, 2026

IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.

- Always prefer command flags that reduce output verbosity when using ${formatToolName(

@gundermanc gundermanc Feb 12, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It'd be great to test these lines independently. I wonder how much of the context savings is just this line, for example, particularly if it's reducing the size of build output.

)}.
- Aim to minimize tool output tokens while still capturing necessary information.
- If a command is expected to produce a lot of output, use quiet or silent flags where available and appropriate.
- Always consider the trade-off between output verbosity and the need for information. If a command's full output is essential for understanding the result, avoid overly aggressive quieting that might obscure important details.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Consider adding a behavioral eval test that demonstrates the effectiveness of lines like this. The hope is this keeps our prompt focused and minimal.

- Aim to minimize tool output tokens while still capturing necessary information.
- If a command is expected to produce a lot of output, use quiet or silent flags where available and appropriate.
- Always consider the trade-off between output verbosity and the need for information. If a command's full output is essential for understanding the result, avoid overly aggressive quieting that might obscure important details.
- If a command does not have quiet/silent flags or for commands with potentially long output that may not be useful, redirect stdout and stderr to temp files in the project's temporary directory. For example: 'command > <temp_dir>/out.log 2> <temp_dir>/err.log'.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think there's a general feature being implemented that redirects shell outputs that are too long. Is it preferable to use that? I think by redirecting in the shell we lose the ability to have live updates in the UX.

Background PIDs: Only included if background processes were started.
Process Group PGID: Only included if available."
Process Group PGID: Only included if available.
**This is the preferred tool for surgical extraction of code blocks.** Use \`sed -n '50,100p' file\` for ranges, or \`sed -n '/class X/,/^}/p' file\` for semantic blocks. Avoid 'cat' on large files to prevent context bloat. Output is limited to the last 2,000 lines.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is another one that'd be great to test in isolation. I also wonder if we can achieve the same result without causing more approval prompts by exposing params to do the equivalent on a tool.

"Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).",
type: 'number',
},
start_line: {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's just rename these for Gemini 3 models.

- Integrate model-specific tool optimizations (isGemini3) into read-file and snippets.
- Reconcile prompt snippets with main's Context Efficiency mandates and experiment's discovery guidelines.
- Adopt main's refactored tool definition structure while retaining experiment's surgical extraction guidance.
- Resolve pagination and truncation logic in file utilities.
- Update snapshots and verify with full test suite.
- Fix ESLint errors in prompt provider and snippets.
- Integrate model-specific tool optimizations (isGemini3) into read-file and snippets.
- Reconcile prompt snippets with main's Context Efficiency mandates and experiment's discovery guidelines.
- Adopt main's refactored tool definition structure while retaining experiment's surgical extraction guidance.
- Resolve pagination and truncation logic in file utilities.
- Update snapshots and verify with full test suite.
- Align prompt provider and snippets with main's code style and linting patterns.
@sripasg sripasg added the size/l A large sized PR label Jun 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. size/l A large sized PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tool Improvement: Refine glob schema and description Tool Improvement: Refine read_file parameters and truncation handling

3 participants