We are going to build a small code generation agent that reads a plain-English task, writes a Python module, checks the syntax, and automatically retries if the first draft is broken. It is useful for scaffolding glue scripts, data utilities, or repetitive boilerplate without switching contexts. I use a version of this internally to cut down on copy-paste setup.
What you'll need
- Python 3.10 or newer
pip install openai- An Oxlo.ai API key from https://portal.oxlo.ai
I will use DeepSeek V3.2 because it handles code and reasoning well, and Oxlo.ai offers it with request-based pricing. That means sending long error traces back for a retry does not inflate cost the way token-based billing would.
1. Set up the Oxlo.ai client and file writer
First, I initialize the OpenAI-compatible client pointing at Oxlo.ai and add a helper that extracts code from markdown fences and writes it to disk.
import os
import re
from openai import OpenAI
client = OpenAI(
base_url="https://api.oxlo.ai/v1",
api_key="YOUR_OXLO_API_KEY"
)
def extract_code(text: str) -> str:
match = re.search(r"
```python\n(.*?)```
", text, re.DOTALL)
if match:
return match.group(1).strip()
return text.strip()
def write_module(code: str, path: str) -> None:
with open(path, "w", encoding="utf-8") as f:
f.write(code)
print(f"Wrote {path}")
2. Define the system prompt
The system prompt keeps the model focused on producing only valid Python inside triple backticks. I keep it strict to avoid parsing headaches.
SYSTEM_PROMPT = """You are a senior Python engineer.
When given a task, write clean, correct Python code to solve it.
Output exactly one markdown code block using
```python fences.
Do not include explanations outside the code block.
If you need to include docstrings, use triple double quotes inside the code.
Always write complete, runnable code."""
3. Generate the first draft
Next, I create a generate function that sends the user task to DeepSeek V3.2 and returns the extracted code.
def generate_code(task: str) -> str:
response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": task},
],
)
raw = response.choices[0].message.content or ""
return extract_code(raw)
4. Validate and fix
I use py_compile to check for syntax errors. If the code fails, I feed the traceback back into the model and ask for a corrected version. Because Oxlo.ai uses flat per-request pricing, this retry loop stays cheap even when the error trace is long.
import py_compile
import tempfile
def validate_and_fix(task: str, code: str, path: str, max_retries: int = 2) -> str:
for attempt in range(max_retries + 1):
write_module(code, path)
try:
py_compile.compile(path, doraise=True)
print("Syntax check passed.")
return code
except py_compile.PyCompileError as e:
print(f"Syntax error on attempt {attempt + 1}: {e}")
if attempt == max_retries:
print("Max retries reached. Keeping last attempt.")
return code
fix_prompt = (
f"The following Python code has a syntax error.\n"
f"Error: {e}\n\n"
f"Code:\n```
python\n{code}\n
```\n\n"
f"Return the corrected code inside ```
python fences."
)
response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": fix_prompt},
],
)
code = extract_code(response.choices[0].message.content or "")
return code
5. Add a CLI entrypoint
Finally, I wire everything together with argparse so I can invoke the agent from the terminal.
import argparse
def main():
parser = argparse.ArgumentParser(description="Generate Python code from a task description.")
parser.add_argument("task", help="What the script should do")
parser.add_argument("-o", "--output", default="generated_script.py", help="Output file path")
args = parser.parse_args()
print("Generating code...")
code = generate_code(args.task)
validate_and_fix(args.task, code, args.output)
if __name__ == "__main__":
main()
Run it
Here is how I generate a CSV deduplication utility. The first draft compiles cleanly, so no retries are needed.
$ export OXLO_API_KEY="sk-..."
$ python codegen.py "Write a Python script that reads a CSV, removes duplicate rows based on the 'email' column, and writes the result to a new CSV"
Generating code...
Wrote generated_script.py
Syntax check passed.
The agent wrote a complete script using the csv module with DictReader and a set to track seen emails. Because Oxlo.ai exposes models like DeepSeek V3.2 and Llama 3.3 70B through a single OpenAI-compatible endpoint, swapping the model string is the only change needed if I want to test a different weights configuration.
Wrap-up
A concrete next step is to extend the validation layer to actually run pytest against the generated code and feed test failures back into the retry loop. Another is to package this as a pre-commit hook that regenerates boilerplate whenever a spec file changes.
Top comments (0)