How to Beginner to Intermediate · 3 min read

How to prompt AI to debug code

Quick answer
To prompt AI to debug code, provide the code snippet along with a clear instruction like "Find and fix bugs in this code." Use explicit context such as the programming language and expected behavior. For example, prompt with: "Debug this Python function that calculates factorial."

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python package and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

Use the gpt-4o model with a prompt that includes the buggy code and a clear debugging instruction. The example below shows a complete script that sends a prompt to the OpenAI API and prints the debugged code.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

buggy_code = '''
def factorial(n):
    if n == 0:
        return 0
    else:
        return n * factorial(n-1)
'''

prompt = f"Debug this Python function and fix any errors:\n{buggy_code}"

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print("Debugged code:\n", response.choices[0].message.content)
output
Debugged code:
 def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Common variations

You can use other models like claude-3-5-sonnet-20241022 or enable streaming for real-time output. Async calls are also supported in the latest SDKs.

python
import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

buggy_code = '''
def add_numbers(a, b):
    return a - b
'''

system_prompt = "You are a helpful assistant that debugs code."
user_prompt = f"Debug this Python function and fix any errors:\n{buggy_code}"

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=200,
    system=system_prompt,
    messages=[{"role": "user", "content": user_prompt}]
)

print("Debugged code:\n", message.content[0].text)
output
Debugged code:
 def add_numbers(a, b):
    return a + b

Troubleshooting

  • If the AI returns unrelated text, clarify the prompt by adding "Only provide corrected code without explanations."
  • If the output is incomplete, increase max_tokens or use streaming.
  • For ambiguous bugs, provide expected input/output examples in the prompt.

Key Takeaways

  • Always include the buggy code and a clear debugging instruction in your prompt.
  • Specify the programming language and expected behavior to guide the AI.
  • Use the latest SDK patterns with environment variables for API keys.
  • Try different models like gpt-4o or claude-3-5-sonnet-20241022 for best debugging results.
  • Add constraints in the prompt to avoid verbose or unrelated outputs.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗