Sitemap
Google Cloud - Community

A collection of technical articles and blogs published or curated by Google Cloud Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Let Gemini autonomously fix code for you

--

Image by author — Imagen3 + post editing by author

In the ever-evolving landscape of software development, automated tools that can help diagnose and fix code issues are becoming increasingly valuable. Today, I’m excited to share a project that leverages Google’s Gemini model to automatically detect and fix errors in Python code. This tool not only identifies issues but also provides reasoned explanations for its fixes, making it an excellent learning resource for developers.

The Challenge

Every developer has faced those frustrating moments when code doesn’t work as expected. While modern IDEs provide excellent static analysis, they often can’t catch runtime errors or suggest contextual fixes. What if we could create a tool that not only identifies these issues but also fixes them automatically while explaining its reasoning?

Enter the Gemini Code Fixer

The Gemini Code Fixer is a Python-based tool that combines the power of Google’s Gemini AI model with systematic error handling to create an intelligent code debugging assistant. The project consists of several modular components that work together to:

  1. Execute Python scripts and capture errors
  2. Parse stack traces using AI
  3. Analyze related files for context
  4. Generate and apply fixes
  5. Verify the solutions

Let’s dive into how each component works and how they come together to create a powerful debugging tool.

Architecture Overview

The project is structured into five main components:

1. Script Executor (script_executor.py)

At the heart of the system is the script executor, which runs Python code and captures both successful outputs and error traces:

def execute_script(script_path):
try:
process = subprocess.run(
['python', script_path],
capture_output=True,
text=True,
check=True
)
return True, process.stdout, None
except subprocess.CalledProcessError as e:
return False, e.stderr, e.stderr

This component provides the foundation for the entire system by capturing detailed error information when scripts fail.

2. Traceback Parser (traceback_parser.py)

The traceback parser is where AI first comes into play. It uses Gemini to analyze stack traces and extract relevant information:

  • Identifies files involved in the error
  • Recognizes error types and messages
  • Structures the information for further processing

3. File Handler (file_handler.py)

This component manages file operations:

  • Reads contents of affected files
  • Updates scripts with corrected code
  • Maintains file integrity throughout the process

4. Fix Suggester (fix_suggester.py)

The fix suggester is the brain of the system. It leverages Gemini’s capabilities to:

  • Analyze the original code
  • Consider the error context
  • Generate a reasoned fix
  • Provide a complete corrected script

The AI prompt is carefully structured to ensure high-quality responses:

  prompt = f"""
You are a coding assistant tasked with fixing errors in Python scripts.

Original Script ({original_script}):
```python
{file_contents.get(original_script, "File content not found.")}
```

Stack Trace:
```
{stack_trace}
```

Relevant File Contents:
"""
for file_path, content in file_contents.items():
if file_path != original_script:
prompt += f"```python\n# {file_path}\n{content}\n```\n\n"

prompt += """
Analyze the error and provide a solution. Your response must be a JSON object with the following structure:

{{
"reasoning": "Step-by-step reasoning of the error and the proposed fix.",
"suggested_fix": "A brief description of the changes needed.",
"full_corrected_script": "The complete, corrected Python script that fixes the error. It should keep same logic and structure of original script."
}}
"""

5. Main Orchestrator (main.py)

The main script ties everything together in an iterative process:

  1. Executes the target script
  2. 2. If an error occurs: — Parses the stack trace — Gathers relevant file contents — Requests and applies AI-suggested fixes
  3. 3. Logs all actions and results
  4. 4. Repeats until success or max iterations reached

Real-World Example

Let’s look at how the system handles a common error in a pandas DataFrame operation:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 28],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)

average_age = df['Aeg'].mean() # Typo in column name

When this script is run, the system:

  1. Captures the KeyError from the misspelled column name
  2. Uses Gemini to analyze the stack trace
  3. Identifies the typo and suggests the correction
  4. Provides a reasoning explaining the error
  5. Generates a fixed version of the script

Here are the truncated execution logs

Implementation Insights

Several key design decisions make the system robust:

  1. Iterative Approach: The system can make multiple attempts to fix a script, learning from each iteration.
  2. Comprehensive Logging: Every step is logged, providing transparency and debugging capability:
iteration_context = {
"iteration": iteration,
"success": success,
"output": output,
"stack_trace": stack_trace,
"parsed_traceback": parsed_traceback,
"ai_response": ai_response,
"file_contents": file_contents,
}

and finally Safety Measures: The system includes:

  • Maximum iteration limits
  • File backup capabilities
  • Structured AI responses through schema validation

Here is a truncated version of the execution log:

[
{
"iteration": 1,
"success": false,
"output": "Traceback (most recent call last):\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3805, in get_loc\n return self._engine.get_loc(casted_key)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"index.pyx\", line 167, in pandas._libs.index.IndexEngine.get_loc\n File \"index.pyx\", line 196, in pandas._libs.index.IndexEngine.get_loc\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item\nKeyError: 'Aeg'\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/Users/nemri/Desktop/tmp/interview/script.py\", line 8, in <module>\n average_age = df['Aeg'].mean()\n ~~^^^^^^^\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/frame.py\", line 4102, in __getitem__\n indexer = self.columns.get_loc(key)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3812, in get_loc\n raise KeyError(key) from err\nKeyError: 'Aeg'\n",
"stack_trace": "Traceback (most recent call last):\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3805, in get_loc\n return self._engine.get_loc(casted_key)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"index.pyx\", line 167, in pandas._libs.index.IndexEngine.get_loc\n File \"index.pyx\", line 196, in pandas._libs.index.IndexEngine.get_loc\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item\nKeyError: 'Aeg'\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/Users/nemri/Desktop/tmp/interview/script.py\", line 8, in <module>\n average_age = df['Aeg'].mean()\n ~~^^^^^^^\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/frame.py\", line 4102, in __getitem__\n indexer = self.columns.get_loc(key)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3812, in get_loc\n raise KeyError(key) from err\nKeyError: 'Aeg'\n",
"parsed_traceback": [
{
"content": "/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py",
"element": "file"
},
{
"content": "KeyError: 'Aeg'",
"element": "error"
},
{
"content": "index.pyx",
"element": "file"
},
{
"content": "/Users/nemri/Desktop/tmp/interview/script.py",
"element": "file"
},
{
"content": "KeyError: 'Aeg'",
"element": "error"
},
{
"content": "/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/frame.py",
"element": "file"
},
{
"content": "/Users/nemri/Desktop/tmp/interview/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py",
"element": "file"
},
{
"content": "KeyError: 'Aeg'",
"element": "error"
},
{
"content": "pandas/_libs/hashtable_class_helper.pxi",
"element": "file"
}
],
"ai_response": {
"full_corrected_script": "import pandas as pd\n\ndata = {'Name': ['Alice', 'Bob', 'Charlie'],\n 'Age': [25, 30, 28],\n 'City': ['New York', 'London', 'Paris']}\ndf = pd.DataFrame(data)\n\naverage_age = df['Age'].mean()\n\nprint(average_age)",
"reasoning": "The original script attempts to calculate the mean of a column named 'Aeg', but this column does not exist in the DataFrame. The DataFrame has columns 'Name', 'Age', and 'City'. The error message clearly indicates a KeyError: 'Aeg'. The solution is to correct the column name in the mean() function to 'Age', which contains the age data.",
"suggested_fix": "Change the column name in the average_age calculation from 'Aeg' to 'Age'."
},
"file_contents": {
["file1 ..."],
["file2 ..."],
["file3 ..."]
}
},
{
"iteration": 2,
"success": true,
"output": "27.666666666666668\n",
"stack_trace": null,
"parsed_traceback": null,
"ai_response": null,
"file_contents": {}
}
]

Future Enhancements

While the current implementation is powerful, there are several exciting possibilities for enhancement:

  1. Support for multiple programming languages
  2. Integration with version control systems
  3. Interactive mode for developer approval of fixes
  4. Learning from successful fixes to improve future suggestions
  5. Providing grounded responses using Google Search or internal knowledge bases

Conclusion

The Gemini Code Fixer demonstrates the potential of AI-assisted programming tools. By combining traditional error handling with AI-powered analysis and fix generation, we’ve created a tool that not only fixes code but also helps developers understand and learn from their mistakes.

The modular architecture and use of Google’s Gemini model make this project both practical and extensible. Whether you’re a beginner looking for learning support or an experienced developer seeking to automate routine debugging, this tool offers valuable assistance in the coding process.

You can find the complete project code and documentation on GitHub, and we welcome contributions and suggestions for improvement.

About me

I’m Chouaieb Nemri, a Generative AI BlackBelt Specialist at Google with over a decade of experience in data, cloud computing, AI, and electrical engineering. My passion lies in helping executives and tech leaders turbocharge their cloud-based AI, ML, and Generative AI initiatives. Before Google, I worked at AWS as a GenAI Lab Solutions Architect and served as an AI and Data Science consultant at Capgemini and Devoteam. I also led cloud data engineering training at the French startup DataScientest, directly collaborating with its CTO. Outside of work, I’m dedicated to mentoring aspiring tech professionals — especially people with disabilities — and I hold a 5-star mentor rating across platforms like MentorCruise, IGotAnOffer and ADPList.

If you like the article and would like to support me make sure to:

  • 👏 Clap for the story (50 claps) and follow me 👉
  • 📰 View more content on my medium profile
  • 💪 Have me as a Mentor on iGotAnoffer or MentorCruise
  • 🔔 Follow Me: LinkedIn | TikTok | Instagram | Medium | GitHub | Twitter
  • 🚀👉 Join the Medium membership program to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, at no extra cost to you.

--

--

Google Cloud - Community
Google Cloud - Community

Published in Google Cloud - Community

A collection of technical articles and blogs published or curated by Google Cloud Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Chouaieb Nemri
Chouaieb Nemri

Written by Chouaieb Nemri

Generative AI @ Google - xAWS - Georgia Tech Alumni - Opinions are my own

Responses (1)