Skip to content
01Home 02Capability Matrix 03Tools 04Benchmark Rankings 05Tracks 06About Us
Code Under Repair · AI coverage organised as a matrix of capability × stage. Not sorted by tool, but by where you are right now.
Updated every Wednesday

How to Build a Reusable Starter Template for Python LLM Applications

Stop rebuilding the same LLM plumbing for every project. Create a reusable Python LLM starter template with clean configuration, a shared API client, testable services, and a project structure that can grow without becoming a framework.

Nov 16, 2026
How to Build a Reusable Starter Template for Python LLM Applications Open-Source Projects

Starting every LLM project from an empty Python file feels quick until the third project. You end up copying API setup, environment variables, prompt strings, error handling, and test code from one repository to another. Eventually, the copied versions drift apart—and a small configuration change becomes a debugging session.

A reusable Python LLM starter template solves this problem by giving every new project the same dependable foundation. The goal is not to build a complicated framework. It is to create a small structure that separates configuration, API access, application logic, and tests while keeping model-specific decisions easy to change.

This guide builds a practical starter template using Python, the official OpenAI SDK, environment-based configuration, and pytest. You can adapt the same structure to other LLM providers without tying your entire application to one API client.


Table of Contents

  • What a Python LLM starter template should include

  • Set up a clean project structure

  • Move configuration and API access into separate modules

  • Build a reusable LLM service

  • Add tests before copying the template

  • Make the starter template useful across projects


Python LLM starter project folder structure

What a Python LLM Starter Template Should Include

A starter template should remove repetitive setup, not hide how the application works. For a small LLM-powered application, I would begin with five responsibilities:

  • Configuration: Read API keys, model names, and runtime settings from environment variables.

  • Client setup: Create the API client in one predictable location.

  • Application services: Keep model calls and business logic out of route handlers or command-line scripts.

  • Prompts and schemas: Store reusable instructions and structured data definitions separately when they grow.

  • Tests: Verify application behavior without making a real paid API request every time.

Do not start by adding a database, queue, agent framework, vector store, or web server. Add those only when the project needs them. A template that requires ten services before its first request is not a useful starting point for a small experiment.

Set Up a Clean Project Structure

Create a directory that can grow without becoming difficult to navigate:

python-llm-starter/
├── app/
│   ├── __init__.py
│   ├── config.py
│   ├── client.py
│   └── services/
│       ├── __init__.py
│       └── text_generation.py
├── tests/
│   ├── __init__.py
│   └── test_text_generation.py
├── .env.example
├── .gitignore
├── pyproject.toml
└── README.md

The app directory contains code that belongs to the application. The tests directory contains automated checks. Configuration examples and dependency declarations stay at the project root.

Create a virtual environment and install the initial dependencies:

python -m venv .venv

# macOS or Linux
source .venv/bin/activate

# Windows PowerShell
.venv\Scripts\Activate.ps1

python -m pip install --upgrade pip
pip install openai pytest python-dotenv

For a reusable project, declare dependencies in pyproject.toml instead of relying only on a manually maintained installation command:

[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "python-llm-starter"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
    "openai",
    "python-dotenv"
]

[project.optional-dependencies]
dev = [
    "pytest"
]

This keeps runtime dependencies separate from development tools. You can install both groups with pip install -e ".[dev]". The Python Packaging User Guide documents the role of project metadata and optional dependencies in pyproject.toml. [Source: Python Packaging User Guide]

Create .env.example with placeholder values, not real credentials:

OPENAI_API_KEY=replace_with_your_key
OPENAI_MODEL=your_supported_model_name

Then make sure your actual .env file is ignored by Git:

.venv/
.env
__pycache__/
.pytest_cache/
.coverage
htmlcov/

Move Configuration and API Access Into Separate Modules

Configuration should be read once through a small module. This prevents API keys and model names from being scattered across unrelated files.

In app/config.py:

import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()


@dataclass(frozen=True)
class Settings:
    api_key: str
    model: str


def get_settings() -> Settings:
    api_key = os.getenv("OPENAI_API_KEY")
    model = os.getenv("OPENAI_MODEL")

    if not api_key:
        raise RuntimeError("OPENAI_API_KEY is not configured")

    if not model:
        raise RuntimeError("OPENAI_MODEL is not configured")

    return Settings(
        api_key=api_key,
        model=model,
    )

The validation is intentional. A missing API key should produce a clear configuration error, not a confusing failure several layers later. Keeping the settings object immutable also makes accidental runtime changes less likely.

Next, create app/client.py:

from openai import OpenAI

from app.config import get_settings


def create_client() -> OpenAI:
    settings = get_settings()

    return OpenAI(api_key=settings.api_key)

The client factory gives the rest of the application one place to obtain an API client. It also gives tests a clear seam where a fake client can be injected. The official Python SDK supports the Responses API and reads credentials from environment configuration when using its default setup. [Source: OpenAI SDK documentation]

Build a Reusable LLM Service

Now create app/services/text_generation.py. This module should know how to request a model response, but it should not know anything about a particular web framework or user interface.

from openai import OpenAI

from app.config import get_settings


def generate_text(
    client: OpenAI,
    prompt: str,
) -> str:
    if not prompt.strip():
        raise ValueError("Prompt cannot be empty")

    settings = get_settings()

    response = client.responses.create(
        model=settings.model,
        input=prompt,
    )

    return response.output_text

Passing the client as an argument is useful because the function does not have to create a new connection every time it runs. It also makes the service easier to test. In a larger application, you could inject the client through a dependency container or application startup routine.

Keep this first version deliberately small. You can later add timeouts, retry policies, structured outputs, usage tracking, and logging. Those features should be introduced when the application has clear requirements for them, rather than being added to every project automatically.

Add Tests Before Copying the Template

A starter template is only reusable if its basic behavior is easy to verify. You do not need a real API request to test input validation. You can also replace the client with a small fake object for a successful-response test.

Create tests/test_text_generation.py:

import pytest

from app.services.text_generation import generate_text


class FakeResponse:
    output_text = "A short generated answer."


class FakeResponses:
    def create(self, **kwargs):
        assert kwargs["input"] == "Explain Python imports."
        return FakeResponse()


class FakeClient:
    responses = FakeResponses()


def test_generate_text_returns_model_output(monkeypatch):
    monkeypatch.setattr(
        "app.services.text_generation.get_settings",
        lambda: type(
            "Settings",
            (),
            {"model": "test-model"}
        )(),
    )

    result = generate_text(
        FakeClient(),
        "Explain Python imports.",
    )

    assert result == "A short generated answer."


def test_generate_text_rejects_empty_prompt():
    with pytest.raises(ValueError):
        generate_text(FakeClient(), "   ")

Run the tests:

pytest -q

The fake client verifies how your application uses the SDK without sending a network request or spending API credits. It does not prove that the provider accepts your request or that your credentials work. Keep a separate, explicitly run integration check for those concerns.

Pytest results for a Python LLM starter project

Make the Starter Template Useful Across Projects

Before using the template for another application, check whether each component has a clear responsibility. If a new project needs document retrieval, add a retrieval service. If it needs a web API, add a route layer. If it needs background jobs, add a worker. Avoid placing all of these responsibilities inside one large main.py.

Write a short README that explains how to create the environment, install dependencies, configure variables, run tests, and start the application. Include a warning that .env.example contains placeholders and that real keys must never be committed.

Also document assumptions that are easy to overlook: the supported Python version, the expected model configuration, and which tests require network access. A template should make these decisions visible rather than forcing the next developer to reverse-engineer them.

A Practical Checklist Before Reusing It

  • Can a new developer install dependencies from the project metadata?

  • Does the application fail clearly when required configuration is missing?

  • Can the LLM client be replaced in unit tests?

  • Are real API keys excluded from version control?

  • Can tests run without network access?

  • Does the README explain the first successful run?

A good Python LLM starter template is not the one with the most abstractions. It is the one that removes repeated setup while leaving the important parts understandable. Start with configuration, a client factory, one service, and tests. Let the next real project—not speculation—tell you what to add.

Build it. Break it. Understand it. Fix it.

Reader responses

No responses on this piece yet.

Write what you observed