DEV Community

shashank ms
shashank ms

Posted on

Mastering Complex Coding: A Step-by-Step Tutorial

We are building a spec-to-code agent that turns a rough product idea into a structured Python project with typed modules, tests, and dependency manifests. It helps backend engineers and tech leads bootstrap microservices or internal tools without getting lost in boilerplate.

What you'll need

Before starting, make sure you have the following:

  • Python 3.10 or higher installed locally.
  • An Oxlo.ai API key from https://portal.oxlo.ai.
  • The OpenAI SDK installed: pip install openai.

1. Configure the Oxlo.ai client

Set up the OpenAI-compatible client pointing at Oxlo.ai. I use kimi-k2.6 here because its 131K context window and agentic coding strengths let us feed in long specifications and receive coherent, multi-file outputs in a single pass. Because Oxlo.ai uses flat per-request pricing, stuffing the full spec and examples into the context does not inflate costs the way token-based metering would.

import json
import os
import re
import py_compile
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")
MODEL = "kimi-k2.6"

2. Define the system prompt

The system prompt constrains the model to emit only valid JSON representing a file tree. This keeps the agent predictable when we parse its output later.

import json
import os
import re
import py_compile
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")
MODEL = "kimi-k2.6"

SYSTEM_PROMPT = """You are a senior staff engineer. Convert a user request into a production-ready Python project.

Rules:
1. Output ONLY a JSON object. Do not wrap it in markdown.
2. Use this structure: {"files": [{"path": "relative/path.py", "content": "full source code"}]}
3. Every Python file must include type hints, docstrings, and __all__ exports where appropriate.
4. Include a requirements.txt with exact dependencies.
5. Include a pytest test file for each module.
6. Do not include explanations outside the JSON."""

3. Add the specification expander

Before generating code, we ask the model to expand the user's one-liner into a detailed technical specification. This reduces hallucination in the later coding step.

import json
import os
import re
import py_compile
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")
MODEL = "kimi-k2.6"

SYSTEM_PROMPT = """You are a senior staff engineer. Convert a user request into a production-ready Python project.

Rules:
1. Output ONLY a JSON object. Do not wrap it in markdown.
2. Use this structure: {"files": [{"path": "relative/path.py", "content": "full source code"}]}
3. Every Python file must include type hints, docstrings, and __all__ exports where appropriate.
4. Include a requirements.txt with exact dependencies.
5. Include a pytest test file for each module.
6. Do not include explanations outside the JSON."""

def expand_spec(idea: str) -> str:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You are a pragmatic technical lead. Be specific and concise."},
            {"role": "user", "content": f"Expand this idea into a technical spec under 400 words: {idea}"},
        ],
        temperature=0.3,
    )
    return response.choices[0].message.content

4. Generate the project scaffold

Feed the expanded spec into the main agent and parse the JSON response. We strip accidental markdown fences because even disciplined models occasionally wrap JSON in triple backticks.

import json
import os
import re
import py_compile
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")
MODEL = "kimi-k2.6"

SYSTEM_PROMPT = """You are a senior staff engineer. Convert a user request into a production-ready Python project.

Rules:
1. Output ONLY a JSON object. Do not wrap it in markdown.
2. Use this structure: {"files": [{"path": "relative/path.py", "content": "full source code"}]}
3. Every Python file must include type hints, docstrings, and __all__ exports where appropriate.
4. Include a requirements.txt with exact dependencies.
5. Include a pytest test file for each module.
6. Do not include explanations outside the JSON."""

def expand_spec(idea: str) -> str:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You are a pragmatic technical lead. Be specific and concise."},
            {"role": "user", "content": f"Expand this idea into a technical spec under 400 words: {idea}"},
        ],
        temperature=0.3,
    )
    return response.choices[0].message.content

def generate_project(spec: str) -> dict:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": spec},
        ],
        temperature=0.2,
    )
    content = response.choices[0].message.content
    cleaned = re.sub(r"^

```json\s*|^```

\s*|

```$", "", content, flags=re.MULTILINE).strip()
    return json.loads(cleaned)

5. Write files and validate syntax

Persist the generated files to disk and run a quick syntax check with py_compile. This catches indentation errors or malformed f-strings before you ever open an editor.

import json
import os
import re
import py_compile
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")
MODEL = "kimi-k2.6"

SYSTEM_PROMPT = """You are a senior staff engineer. Convert a user request into a production-ready Python project.

Rules:
1. Output ONLY a JSON object. Do not wrap it in markdown.
2. Use this structure: {"files": [{"path": "relative/path.py", "content": "full source code"}]}
3. Every Python file must include type hints, docstrings, and __all__ exports where appropriate.
4. Include a requirements.txt with exact dependencies.
5. Include a pytest test file for each module.
6. Do not include explanations outside the JSON."""

def expand_spec(idea: str) -> str:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You are a pragmatic technical lead. Be specific and concise."},
            {"role": "user", "content": f"Expand this idea into a technical spec under 400 words: {idea}"},
        ],
        temperature=0.3,
    )
    return response.choices[0].message.content

def generate_project(spec: str) -> dict:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": spec},
        ],
        temperature=0.2,
    )
    content = response.choices[0].message.content
    cleaned = re.sub(r"^```

json\s*|^

```\s*|```

$", "", content, flags=re.MULTILINE).strip()
    return json.loads(cleaned)

def write_project(project: dict, out_dir: str = "generated_project"):
    os.makedirs(out_dir, exist_ok=True)
    for f in project["files"]:
        path = os.path.join(out_dir, f["path"])
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as fh:
            fh.write(f["content"])

    for f in project["files"]:
        if f["path"].endswith(".py"):
            py_compile.compile(os.path.join(out_dir, f["path"]), doraise=True)
    print(f"Wrote {len(project['files'])} files to ./{out_dir}")

if __name__ == "__main__":
    idea = (
        "Build a FastAPI service for managing book inventory with SQLite, "
        "Pydantic v2 models, and async SQLAlchemy. Include CRUD endpoints "
        "and a search endpoint by title or author."
    )
    spec = expand_spec(idea)
    project = generate_project(spec)
    write_project(project)

Run it

Export your key and execute the script. The agent expands the idea, generates the full tree, writes the files, and validates syntax.

export OXLO_API_KEY="sk-..."
python scaffold.py

Typical output looks like this:

Wrote 6 files to ./generated_project

generated_project/
├── main.py
├── models.py
├── schemas.py
├── database.py
├── test_main.py
└── requirements.txt

Inside generated_project/main.py you will find production-grade FastAPI routes with async SQLAlchemy sessions, and test_main.py will include pytest suites covering the CRUD surface.

Wrap-up

This agent gives you a repeatable way to bootstrap backend services from a sentence. Two concrete next steps: extend the SYSTEM_PROMPT to emit a Dockerfile and docker-compose.yml alongside the Python code, or wire the script into a CI pipeline that regenerates boilerplate whenever your OpenAPI spec changes. If you want to scale this to larger microservice fleets, Oxlo.ai's per-request pricing keeps long multi-file prompts economical compared to token-metered alternatives. You can view current plans at https://oxlo.ai/pricing.

Top comments (0)