Tired of fixing endless linting errors? What if an AI could do it for you? In this post, we’ll walk through how to build a Python script that uses Google’s Gemini to automatically fix static analysis issues, exploring the process and the lessons learned along the way. This is a journey from a simple idea to a robust, agentic system.
The Problem: The Drudgery of Static Analysis
Static analysis tools like Detekt (for Android projects) or Checkstyle, ESLint etc are fantastic for maintaining code quality, but they can also generate a lot of noise. Fixing hundreds of minor issues for any project, big or small, can be a real drag on productivity.
An Example Detekt Problem
Consider a common Detekt error like LongMethod. Detekt will flag a function that has grown too long, making it difficult to read, understand, and maintain.
As a basic example of what detekt would find and report:
class ReportGenerator {
fun generateReport() {
// ... code to fetch data ...
// ... code to process data ...
// ... code to format report ...
// ... code to send report ...
}
}
The fix as a developer, would be to manually fix this by refactoring the long method, extracting the different steps into smaller, private functions.
Let’s get an LLM to do the same!
Part 1: The “One-Shot” Fix – A Not-So-Simple Solution
Our first thought is to automate the manual process. Why not give the entire static analysis output to an AI and ask it to fix everything at once? This “one-shot” approach is powerful, but we need to be mindful of the “context window” limitations of LLMs.
The Context Window Challenge
So, what is a “context window” and what are “tokens”?
A token is a piece of a word used for natural language processing. For example, the word “hamburger” gets broken up into “ham”, “bur”, and “ger”. For code, tokens can be parts of variable names, operators, or keywords.
The context window is the amount of text (measured in tokens) that a model can “see” at once. It’s the model’s short-term memory.
Most LLMs have a context window limit. For example, OpenAI’s GPT-4 Turbo has a 128,000 token context window, and Anthropic’s Claude 3.5 Sonnet has 200,000 tokens. For a mid-sized code change that touches several files, it’s surprisingly easy to hit these limits when you bundle up the Detekt output and the full content of all affected files.
This is where a model like Google’s Gemini 2.5, with its 1 million token context window, becomes a game-changer. It gives us the breathing room to send a rich, detailed context without worrying about hitting the limit for most common scenarios. (You can experiment with Google’s Gemini in AI Studio here.)
Step 1: Curate the Context (and Count the Tokens)
To curate a prompt that fixes static analysis, we need to think like a developer. What information would a developer use when fixing these issues manually? This is the same information an LLM would find useful. We provide:
– The full output from Detekt: This tells the AI what the problems are.
– The git diff of the current changes: This gives the AI context about the recent changes that might have introduced the errors.
– The full content of the files with errors: The AI needs to see the code to understand how to fix it.
Crucially, our script should also track the number of tokens being used to ensure we stay within the context window.
Step 2: Prompt the AI and Apply the Fix
With the curated prompt, we then call the Gemini API to get a unified diff. A unified diff is a standard format for code changes that can be easily applied with git apply. For our LongMethod example, the AI might return a diff like this:
diff --git a/ReportGenerator.kt b/ReportGenerator.kt
--- a/ReportGenerator.kt
+++ b/ReportGenerator.kt
@@ -1,7 +1,12 @@
class ReportGenerator {
fun generateReport() {
- // ... code to fetch data ...
- // ... code to process data ...
- // ... code to format report ...
- // ... code to send report ...
+ fetchData()
+ processData()
+ formatReport()
+ sendReport()
}
+ private fun fetchData() { /* ... code to fetch data ... */ }
+ private fun processData() { /* ... code to process data ... */ }
+ private fun formatReport() { /* ... code to format report ... */ }
+ private fun sendReport() { /* ... code to send report ... */ }
}
We can then use git to apply this diff to our codebase automatically.
The Agentic Pull Alternative
What if the changes are too big even for Gemini’s 1M context window? An alternative, more “agentic” approach would be for the AI to ask for the information it needs. Instead of us bundling everything, the agent would first see the list of errors and then request to see specific files, one by one. This is a more scalable approach, and a great direction for future iterations. It would be more powerful than the one-shot approach as the LLM would be able to view other files that perhaps reference the same code paths and make wider ranging changes and potential fixes.
Part 2: The Reality of AI-Generated Diffs
The above detekt example is a single static-analysis issue with a single diff fix. Imagine your typical code review when there are multiple issues. The diff the LLM generates would span multiple classes with multiple fixes. The one-shot approach works surprisingly well, but it’s not perfect. I quickly ran into a problem: AI-generated diffs sometimes fail to apply.
LLMs are not technically “creating” diffs; they are predicting a sequence of tokens that looks like a diff. This means they can sometimes make subtle mistakes, like incorrect line numbers, malformed hunk headers, or even trailing whitespace, that make the diff invalid. This happens more regularly as the complexity of the diff increases.
(Note: This is going to be a problem with any approach i.e. in the one-shot approach and the agentic pull approach.)
The Solution: Divide and Conquer (with AI’s help)
When a unified diff fails, what would a developer do? They would likely look at the error and try to isolate the problem. We can mimic this process with a multi-stage recovery system.
Step 1: Split and Retry
First, we split the large, unified diff into smaller, individual diffs for each file. Then, we try to apply them one by one. Often, the failure is isolated to just one or two files, and the other fixes can be applied successfully. This is like a developer strategy of commenting out parts of a patch to see what applies.
import re
def split_unified_diff(unified_diff_text: str) -> list[str]:
"""Splits a diff string into a list of individual file diffs."""
# Find the start of each diff, begins with "diff --git".
diff_start_indices = [
match.start()
for match in re.finditer(r'^diff --git', unified_diff_text, re.MULTILINE)
]
# If no "diff --git" found, treat as a single diff.
if not diff_start_indices:
return [unified_diff_text]
individual_diffs = []
# Iterate indices to slice the unified diff string.
for i in range(len(diff_start_indices) - 1):
start_index = diff_start_indices[i]
end_index = diff_start_indices[i + 1]
individual_diffs.append(unified_diff_text[start_index:end_index])
# Add the last diff, (last start index to string end)
last_diff_start_index = diff_start_indices[-1]
individual_diffs.append(unified_diff_text[last_diff_start_index:])
return individual_diffs
Step 2: The AI Correction Loop
For the split diffs that still fail, we go back to the AI. This time, we use a more targeted, agentic approach that mimics a developer asking for help on a specific problem. (you’ll notice with complexity, everything becomes an agentic approach … we need better naming 🙂 )
1. We generate a new prompt for each failing diff.
2. We get the latest contents of the file the diff is applying to.
3. This prompt says: “This diff is broken. Here is the diff, and here is the latest version of the file it should apply to. Please fix the diff.”
4. The AI then (hopefully) returns a corrected diff.
5. We attempt to apply this new, corrected diff.
Let’s see how this looks in a simplified Python example that shows the interaction with the Gemini API. Note that some functions (like apply or get_detekt_report) and variables are placeholders for your own implementation.
# A simplified example for interacting with the Gemini API
import google.generativeai as genai
import tiktoken # An open-source tokenizer
# This assumes you have the 'google-generativeai' and 'tiktoken' libraries installed.
# You would configure your API key (as a system env or cloud secret).
# genai.configure(api_key="YOUR_API_KEY")
# Example of initializing the model
# model = genai.GenerativeModel('gemini-pro') # Or another suitable model like Gemini 2.5 flash
def count_tokens(text):
"""Counts the number of tokens in a string."""
tokenizer = tiktoken.get_encoding("cl100k_base")
return len(tokenizer.encode(text))
def generate_initial_prompt(raw_output):
"""Generates the initial prompt with all the context."""
trimmed_console_output = filter_console_output(raw_output)
detekt_report = get_detekt_report()
files_in_detekt_report = find_files_in_report(detekt_report)
diff_against_main_for_files = get_diff_for_files(files_in_detekt_report)
# We would also check the token count here before sending.
return f"""
Here is a static analysis failure ```{trimmed_console_output}```, along with the files it is applicable to ```{files_in_detekt_report}```,
and a diff of those files against the branch we want to merge into ```{diff_against_main_for_files}```.
Return a git diff that fixes all issues, reply with the diff only and nothing else.
"""
def generate_correction_prompt(diff, file_content):
"""Generates a prompt to ask the AI to fix a failing diff."""
return f"Please fix this broken diff:\n```{diff}```\n\nfor this file:\n```{file_content}```"
def get_ai_suggestion(prompt):
"""Calls the Gemini API and extracts the response."""
response = model.generate_content(prompt)
return extract_diff_from_response(response.text)
# --- Main logic ---
initial_prompt = generate_initial_prompt(build_output)
initial_diff = get_ai_suggestion(initial_prompt)
if not git_apply(initial_diff):
# ... enter the correction loop ...
correction_prompt = generate_correction_prompt(failed_diff, file_content)
corrected_diff = get_ai_suggestion(correction_prompt)
git_apply(corrected_diff)
Tool Usage: The Next Frontier
This agentic correction loop could be made even more powerful if we incorporate tool use. This is a feature where the LLM can be given access to a set of tools (like functions in our code) that it can choose to call. (This interaction when formalised and expanded is often referred to as using “Model Context Protocol” (MCP)).
For example, instead of our script feeding the file content to the AI, we could give the AI a read_file(path) tool. The AI could then decide on its own to call this tool to get the latest version of the file before attempting a fix. We could even give it a run_linter(file_path) tool to verify its own generated code.
If you’ve used tools like the Gemini CLI or Claude Code, you have seen this in action. The AI assistant can run commands, read files, and interact with your development environment. This is what I’d like to do next, turning our script from a simple automator into a true AI software engineering assistant that can reason and act on its own.
Key Lessons Learned
Building this tool has been a great learning experience. Here are some of the key takeaways:
- Context is King: The quality of the AI’s output is directly proportional to the quality of the context you provide. Thinking like a developer to curate the right context is the most important part of the process.
- Expect and Handle Imperfection: LLMs are not perfect. They will make mistakes. Building robust recovery and correction mechanisms, like the multi-stage diff application process, is crucial for creating a reliable tool.
- Start Simple, Iterate Towards Agentic: The journey from a simple “one-shot” script to a more complex, agentic system is a natural one. Starting with a simple solution and then adding more intelligence and autonomy as you encounter new challenges is a great way to build powerful AI-powered tools.
- The Future is Agentic (and uses Tools): The real power of LLMs in software development will be unlocked when they can act as true agents, using tools to interact with the development environment. This is the most exciting area for my future exploration.
Conclusion: A Powerful, Time-Saving Assistant
Building this AI-powered static analysis fixer has been a journey. While not a silver bullet, it has proven to be an incredibly powerful tool.
By automating the tedious task of fixing minor linting issues, it saves a significant amount of time and allows me to focus on what really matters: building great features. The evolution from a simple one-shot approach to a more robust, multi-step agentic system shows the power and flexibility of Gemini (LLMs) in the software development lifecycle.
Final plot twist, if you copy paste this blog post into your favourite LLM , you can prompt it:
“Make the agentic python script that is described in this blog post: {ctrl + v}"
and it would do it. Enjoy! 🙂

