We are going to build a code-review agent that ingests a messy Python module, audits it for bugs, complexity, and missing type safety, and emits a structured report with a rewritten patch. This saves senior engineers from manually triaging every draft PR. We will run the whole thing on Oxlo.ai using its OpenAI-compatible API and per-request pricing so long files do not inflate cost.
What you'll need
- Python 3.10 or newer
- The OpenAI SDK installed with
pip install openai - An Oxlo.ai API key from https://portal.oxlo.ai
Oxlo.ai uses flat per-request pricing, so sending a 500-line module into context for a deep audit costs the same as a 50-line snippet. That makes multi-pass audit and rewrite workflows predictable, and because there are no cold starts on popular models the loop feels instant in local development.
Step 1: Set up the Oxlo.ai client and sample code
First we initialize the OpenAI-compatible client pointing at Oxlo.ai and create a deliberately flawed Python file to audit.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.oxlo.ai/v1",
api_key=os.environ["OXLO_API_KEY"]
)
# Write a messy sample module to disk
SAMPLE_CODE = '''
import requests
def get_users(url):
r = requests.get(url)
data = r.json()
results = []
for item in data:
if item["active"] == True:
results.append(item)
return results
def save_csv(rows, fname):
f = open(fname, "w")
for row in rows:
f.write(str(row) + "\\n")
f.close()
'''
with open("messy_module.py", "w") as f:
f.write(SAMPLE_CODE)
print("messy_module.py written")
Step 2: Define the audit system prompt
The system prompt enforces a strict JSON schema so we can parse findings programmatically. I keep it in a constant so it is easy to iterate on without touching business logic.
SYSTEM_PROMPT = '''
You are a senior staff engineer performing a rigorous code review.
Read the provided Python code and audit it across four axes:
1. Bugs and error handling (unclosed resources, missing timeouts, bare exceptions)
2. Type safety (missing annotations, implicit casts)
3. Complexity (nested loops, deep nesting, unclear variable names)
4. Performance (inefficient data structures, redundant work)
Respond ONLY as a JSON object with this exact structure:
{
"summary": "one-sentence overall verdict",
"severity": "low|medium|high",
"findings": [
{"line": 0, "category": "bug|type|complexity|performance", "note": "...", "fix": "..."}
],
"rewritten_code": "the complete corrected module as a single string"
}
Do not wrap the JSON in markdown fences.
'''
Step 3: Send the code to Oxlo.ai for audit
We load the file, pack it into the messages array, and call the model. I use kimi-k2.6 because its long-context window and agentic coding strengths handle entire modules in one shot.
import json
def audit_code(filepath: str) -> dict:
with open(filepath, "r") as f:
source = f.read()
response = client.chat.completions.create(
model="kimi-k2.6",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Audit this Python module:\\n\\n
```python\\n{source}\\n```
"},
],
response_format={"type": "json_object"},
temperature=0.2,
)
return json.loads(response.choices[0].message.content)
report = audit_code("messy_module.py")
print(json.dumps(report, indent=2))
Step 4: Parse the report and write the patch
The model returned structured JSON, so we can programmatically separate the findings from the rewritten code. We write the new module to disk and print a human-readable summary.
def apply_patch(report: dict, out_path: str = "clean_module.py"):
with open(out_path, "w") as f:
f.write(report["rewritten_code"])
print(f"Severity: {report['severity']}")
print(f"Summary: {report['summary']}\\n")
print("Findings:")
for finding in report["findings"]:
print(f" Line ~{finding['line']} [{finding['category']}] {finding['note']}")
print(f" Suggested fix: {finding['fix']}\\n")
apply_patch(report)
Step 5: Run it
Executing the full pipeline against the messy module produces the following output. The agent caught the missing timeout, the unclosed file handle, the lack of type hints, and the inefficient list filter pattern.
$ python review_agent.py
messy_module.py written
Severity: high
Summary: The module has unclosed resources, missing error handling, and no type annotations.
Findings:
Line ~6 [bug] requests.get called without timeout parameter
Suggested fix: add timeout=10 to the get() call
Line ~12 [complexity] manual loop filter is verbose and unpythonic
Suggested fix: replace with list comprehension or filter()
Line ~16 [bug] file opened without context manager
Suggested fix: use with open(fname, "w") as f:
Line ~1 [type] missing import typing and function annotations
Suggested fix: add from typing import List, Dict and annotate signatures
clean_module.py written
Wrap-up and next steps
This agent gives you a reproducible first pass on every PR. Two concrete ways to extend it: wire the audit function into a GitHub Action so reviews run automatically on push, or add a second Oxlo.ai call that generates pytest unit tests for the rewritten module using deepseek-v3.2. Because Oxlo.ai charges per request rather than per token, running two-pass pipelines on large files stays predictable.
Top comments (0)