top of page

BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM

Oct 26
9 min read

Build Chapter 2.1: Building the Application Foundation

Part 1: Foundation and Repository Understanding   |   For engineers learning RAG   |   About 12 minutes to read, 25 to follow along


In Build Chapter 2 we created the Python 3.11 project with uv, installed the first dependencies, and laid out an empty src package. Now we add the shared pieces that every later component will reuse: custom exceptions, typed settings, structured logging, and a basic entry point.


This puts one of the Chapter 1 design principles into practice: configuration

stays external instead of hardcoded.


What you will take away


•   One error type, one settings class, and one logging setup that the whole project shares.

•   How to change settings with environment variables, without touching the code.

•   How to run the package with python -m github_rag and read its structured JSON log output.


Prerequisites: Build Chapter 2 completed. Series code: Link.

For technical leaders: the 60-second version

•    The decision. Build errors, configuration, and logging once, in one shared place, before any feature code. Every component then fails, reads settings, and reports in the same way.

•    The cost. A few small files and no visible feature. The payoff comes later, when the team adds components without each inventing its own error handling and log format.

•    The risk it reduces. Settings hardcoded in many places, failures that cannot be told apart, logs that cannot be searched, and secrets that end up in code instead of the environment.

•    Questions to ask your team. Can we change configuration without a code change? Do our logs have consistent fields we can query? Do errors say which category of failure occurred? Do logs avoid secrets and personal data?


1. What we will build

We create or update these files:


2. Why we need a shared foundation


Different parts of the system will need the same capabilities:


•   Repository connectors need configuration and logging.

•   File-policy loaders need meaningful configuration errors.

•   Inventory generation and parsers need structured processing logs and file-specific failures.

•   Chunking needs to report how many chunks it created, and retrieval needs to record latency and result counts.


Without a shared foundation, each package invents its own approach. One component prints, another raises a bare exception, a third hardcodes a folder name:

print("Repository processed")
raise Exception("Something went wrong")
artifacts_directory = "artifacts"

That inconsistency makes the application harder to maintain, test, and operate. The core package gives the project one common approach for exceptions, configuration, and logging.


3. Step 1: Create the custom exceptions


Create src\github_rag\core\exceptions.py:

"""Custom exceptions for the GitHub RAG application."""

class GitHubRagError(Exception):

    """Base exception for known GitHub RAG application errors."""

class ConfigurationError(GitHubRagError):

    """Raised when application configuration is missing or invalid."""

class RepositoryAccessError(GitHubRagError):

    """Raised when a repository cannot be accessed."""

class FilePolicyError(GitHubRagError):

    """Raised when file-policy configuration is invalid."""

class InventoryGenerationError(GitHubRagError):

    """Raised when a repository inventory cannot be generated."""

All application errors share one base class:

Exception
└── GitHubRagError
    ├── ConfigurationError
    ├── RepositoryAccessError
    ├── FilePolicyError
    └── InventoryGenerationError

Exception

Raise it when

Examples

GitHubRagError

Base class. Never raised on its own for a specific case.

Catch it to handle any expected application failure.

ConfigurationError

Configuration is missing, unreadable, or in the wrong format.

Missing file, invalid YAML, wrong value type.

RepositoryAccessError

A repository cannot be reached or read.

Path does not exist, not a directory, unauthorized GitHub request later.

FilePolicyError

The file-policy configuration is invalid.

Negative maximum file size, missing policy field, bad extension.

InventoryGenerationError

A whole repository inventory cannot be produced.

Individual bad files may be skipped later, but a complete failure stops the process.

The shared base class lets callers choose how specific to be (these two snippets are illustrations, not part of the project files):


try:
    process_repository()
except GitHubRagError as error:  # any expected application failure
    print(f"GitHub RAG operation failed: {error}")

try:
    access_repository()
except RepositoryAccessError as error:   # only this category
    print(f"Repository access failed: {error}")

Why are the classes empty? They contain only a docstring, which is valid Python. Each class inherits the behavior of Exception, and its name already says what went wrong. If an exception later needs extra context, such as a file path, we can add fields then.


Test the exceptions from the project root:

uv run python -c "from github_rag.core.exceptions import GitHubRagError, RepositoryAccessError; error = RepositoryAccessError('Repository not found'); print(type(error).__name__); print(isinstance(error, GitHubRagError))"

Expected output:
RepositoryAccessError
True

4. Step 2: Create typed application settings


Create src\github_rag\core\config.py:

"""Application configuration for the GitHub RAG project.""" 
from pathlib import Path
from pydantic_settings import BaseSettings
from pydantic_settings import SettingsConfigDict

class ApplicationSettings(BaseSettings):

    """Configuration values shared across the application."""

    project_name: str = "github-rag"
    log_level: str = "INFO"
    config_directory: Path = Path("config")
    artifacts_directory: Path = Path("artifacts")
 
    model_config = SettingsConfigDict(
        env_prefix="GITHUB_RAG_",
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

ApplicationSettings inherits from BaseSettings in pydantic-settings [1]. That gives us type validation, default values, loading from environment variables, and .env file support. We create the settings with settings = ApplicationSettings().


Field

Purpose

project_name

A human-readable application name. The annotation : str means it must be a string.

log_level

Which logging events are emitted: DEBUG, INFO, WARNING, ERROR, or CRITICAL. The default is INFO.

config_directory

Where external configuration files live. Path gives platform-independent file operations, for example settings.config_directory / "file_policy.yaml", which is config\file_policy.yaml on Windows.

artifacts_directory

Where generated outputs go: inventory JSON, extraction reports, parsed-document samples, chunk inspection results, evaluation reports.

A limit of this design. log_level is a plain string, so a value such as VERBOSE is not rejected. configure_logging() quietly falls back to INFO. That is acceptable for now, and a stricter type can tighten it later. 

What model_config does

Option

Effect

env_prefix="GITHUB_RAG_"

Every environment variable for this class starts with GITHUB_RAG_, so our settings do not clash with unrelated variables.

env_file=".env"

Settings can also come from a local .env file, read from the folder you run the command in.

env_file_encoding="utf-8"

The .env file is read as UTF-8.

extra="ignore"

Unrelated entries in the .env file are ignored instead of failing validation.

Settings are resolved in this order: environment variables, then the .env file, then the defaults in the class. The resulting variable names are:

Setting

Environment variable

Default

project_name

GITHUB_RAG_PROJECT_NAME

github-rag

log_level

GITHUB_RAG_LOG_LEVEL

INFO

config_directory

GITHUB_RAG_CONFIG_DIRECTORY

config

artifacts_directory

GITHUB_RAG_ARTIFACTS_DIRECTORY

artifacts

A future .env file might contain the two lines below. Never commit it to Git, because it may later hold sensitive settings. Chapter 2 already added it to .gitignore.

GITHUB_RAG_LOG_LEVEL=DEBUG
GITHUB_RAG_ARTIFACTS_DIRECTORY=local

Test the default settings:

uv run python -c "from github_rag.core.config import ApplicationSettings; settings = ApplicationSettings(); print(settings.project_name); print(settings.log_level); print(settings.config_directory); print(settings.artifacts_directory)"

Expected output:
github-rag
INFO
config
artifacts

Now test an override from the environment. Set the variable for the current terminal window only, run the check, then remove it:

Task

Windows CMD

macOS / Linux

Set the variable

set GITHUB_RAG_LOG_LEVEL=DEBUG

export GITHUB_RAG_LOG_LEVEL=DEBUG

Remove the variable

set GITHUB_RAG_LOG_LEVEL=

unset GITHUB_RAG_LOG_LEVEL

 

uv run python -c "from github_rag.core.config import ApplicationSettings; print(ApplicationSettings().log_level)" 

Expected output with the variable set:
DEBUG

Expected output after removing it:
INFO

In CMD, do not put spaces around the equals sign. This confirms that a setting can be controlled from outside, without changing Python code.


5. Step 3: Configure structured logging


Create src\github_rag\core\logging.py:

"""Structured logging for the GitHub RAG application."""

import logging
import structlog

def configure_logging(log_level: str = "INFO") -> None:

    """Configure structured JSON logging for the application."""

    normalized_log_level = log_level.upper() 
    numeric_log_level = logging.getLevelNamesMapping().get(
        normalized_log_level,
        logging.INFO,
    )
    logging.basicConfig(
        format="%(message)s",
        level=numeric_log_level,
    )
    structlog.configure(
        processors=[
            structlog.contextvars.merge_contextvars,
            structlog.processors.add_log_level,
            structlog.processors.TimeStamper(
                fmt="iso",
                utc=True,
            ),
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.JSONRenderer(),
        ],
        wrapper_class=structlog.make_filtering_bound_logger(
            numeric_log_level,
        ),
        logger_factory=structlog.PrintLoggerFactory(),
        cache_logger_on_first_use=True,
    )

def get_logger(name: str) -> structlog.typing.FilteringBoundLogger:

    """Return a structured logger bound to a component name."""
    return structlog.get_logger(
        component=name,
    )
A note on the file name. Our file is called logging.py, but inside it import logging still loads Python's standard library module, because Python 3 imports are absolute. The one trap is running the file directly, for example python src\github_rag\core\logging.py, which puts its own folder first on the import path. Always run the package with python -m github_rag. 

How configure_logging() works

•   Normalize. log_level.upper() makes info, Info, and INFO the same value.

•   Convert to a number. Python logging uses numeric levels. logging.getLevelNamesMapping() returns the name-to-number mapping [3] and needs Python 3.11 or newer, which is one concrete place where our version pin matters. An unsupported name falls back to INFO.

•   Standard-library logging. logging.basicConfig sets the level and format for the standard logging module, which third-party libraries we add later will use. structlog's own events do not pass through it. They are written to standard output by PrintLoggerFactory, and make_filtering_bound_logger drops events below the chosen level.

•   Caching. cache_logger_on_first_use=True builds each logger once, for speed [2]. It also means you should call configure_logging() once at startup, before the first log message.


The processors run in order and enrich every event before it is written:

Processor

What it adds

merge_contextvars

Values bound through structlog's context variables.

add_log_level

The severity, as the field level.

TimeStamper(fmt="iso", utc=True)

A UTC timestamp in ISO 8601 format.

StackInfoRenderer

Stack information, when it is requested.

format_exc_info

Formatted exception details, when an exception is logged.

JSONRenderer

Turns the finished event into one line of JSON. It must come last.


A structured event then looks like this (illustrative values):

{"component": "inventory_service", "repository": "example-repository",
 "eligible_files": 120, "event": "repository_inventory_generated",
 "level": "info", "timestamp": "2026-10-25T08:00:00.123456Z"}

In the real output this is a single line. get_logger(name) binds the component name to every event, so you can tell which part of the system produced it:

logger = get_logger("inventory_service")
logger.info("repository_inventory_generated", eligible_files=120)

Test structured logging:

uv run python -c "from github_rag.core.logging import configure_logging, get_logger; configure_logging('INFO'); logger = get_logger('setup_test'); logger.info('application_foundation_ready', status='success')"

Expected output (the timestamp will differ):

{"component": "setup_test", "status": "success", "event": "application_foundation_ready", "level": "info", "timestamp": "2026-10-25T08:00:00.123456Z"}

The order of the JSON fields may differ. That is not an error.


6. Step 4: Export the core components


Update src\github_rag\core\__init__.py, replacing its contents:

"""Core configuration, logging, and exception components."""

from github_rag.core.config import ApplicationSettings
from github_rag.core.exceptions import ConfigurationError
from github_rag.core.exceptions import FilePolicyError
from github_rag.core.exceptions import GitHubRagError
from github_rag.core.exceptions import InventoryGenerationError
from github_rag.core.exceptions import RepositoryAccessError
from github_rag.core.logging import configure_logging
from github_rag.core.logging import get_logger

all = [
    "ApplicationSettings",
    "ConfigurationError",
    "FilePolicyError",
    "GitHubRagError",
    "InventoryGenerationError",
    "RepositoryAccessError",
    "configure_logging",
    "get_logger",
]

Without exports, other code imports from the implementation module. With exports, it imports from the package, which is the public interface:

from github_rag.core.config import ApplicationSettings   # works, but exposes layout
from github_rag.core import ApplicationSettings          # preferred

"__all__" lists the names the package intentionally exposes. It does not make anything private or add security. It tells other developers, and tools, which names to treat as the public interface.


Test the package imports:

uv run python -c "from github_rag.core import ApplicationSettings, GitHubRagError, configure_logging, get_logger; settings = ApplicationSettings(); configure_logging(settings.log_level); logger = get_logger('core_test'); logger.info('core_package_ready', project=settings.project_name); print(GitHubRagError.__name__)"

Expected output:
{"component": "core_test", "project": "github-rag", "event": "core_package_ready", "level": "info", "timestamp": "..."}

GitHubRagError

7. Step 5: Create the application entry point


Create src\github_rag\__main__.py:

"""Command-line entry point for the GitHub RAG application."""

from github_rag.core import ApplicationSettings
from github_rag.core import configure_logging
from github_rag.core import get_logger
 
def main() -> None:

    """Initialize and run the GitHub RAG application."""

    settings = ApplicationSettings()
    configure_logging(
        log_level=settings.log_level,
    )
    logger = get_logger(__name__)
    logger.info(
        "github_rag_application_started",
        project_name=settings.project_name,
        config_directory=str(settings.config_directory),
        artifacts_directory=str(settings.artifacts_directory),
    )

if name == "__main__":
    main()

•   Load settings from environment variables, then the .env file, then the defaults.

•   Configure logging with the configured level, instead of hardcoding one separately.

•   Create the logger. name holds the current module name. When the package runs with python -m github_rag, that name is main, so it appears as the component.

•   Write the startup event with the active settings. Path values are converted to strings so they serialize cleanly as JSON.

•   The main guard, if name == "__main__":, runs main() only when the module is executed directly, and not when it is imported. Because the file is named main.py, python -m github_rag now runs the whole package.


8. Step 6: Run and verify


Run these checks from the project root. Use them as the checkpoint for this chapter.

uv run python -m github_rag
uv run python -m compileall src
uv run python -c "from github_rag.core import ApplicationSettings, GitHubRagError, RepositoryAccessError; print(ApplicationSettings().log_level); print(issubclass(RepositoryAccessError, GitHubRagError))"
tree src\github_rag /f

Expected: •   The first command prints one JSON line (illustrative, yours will differ in time):

{"component": "__main__", "project_name": "github-rag", "config_directory": "config", "artifacts_directory": "artifacts", "event": "github_rag_application_started", "level": "info", "timestamp": "2026-10-25T08:00:00.123456Z"}

•   The syntax check lists the new files, such as src\github_rag\__main__.py and src\github_rag\core\config.py, with no SyntaxError.

•   The third command prints INFO and True.

•   The tree should match this:


9. Common issues


Symptom

Likely cause

Fix

Environment override has no effect

Missing prefix, spaces around = in CMD, or a different terminal window.

Use GITHUB_RAG_LOG_LEVEL=DEBUG, not LOG_LEVEL, with no spaces, in the same window you run the command from.

NameError: name 'name' is not defined

name or "__main__" typed without the double underscores.

Use two underscores on each side: name and "__main__".

ModuleNotFoundError: No module named 'github_rag'

Not run from the project root, or the project was created without --package.

Run dir pyproject.toml, check that [build-system] exists, then run uv sync.

Cannot import ApplicationSettings from github_rag.core

core\__init__.py was not updated.

Check that it contains the config import and that the file name has double underscores.

.env values are ignored

The command was run from another folder.

The .env file is read from the folder you run in. Run from the project root.

Output appears on one line

This is expected.

JSON logs are one event per line, so log platforms can process each event separately.


Conclusion and next chapter


The project now has a reusable foundation: one family of exceptions, typed settings that can be overridden from the environment, structured JSON logging, and an entry point. None of these processes a repository yet. They give every later component the same behavior to build on. A repository connector can raise RepositoryAccessError, a policy loader can raise FilePolicyError, inventory generation can emit structured events, and every component reads the same ApplicationSettings.


Next, Build Chapter 3: Designing the Core Domain Models. 

It covers:

•   Why domain models are needed

•   RepositorySource, FileType, and FileEligibilityStatus

•   RepositoryReference, RepositoryFile, and RepositoryInventory

•   Pydantic validation, enum behavior, and JSON serialization

•   Small tests for each model

 

About SNPaul Infotech

We help engineering and data teams design, evaluate, and secure retrieval and GenAI systems like this one. If you are weighing RAG for your own repositories or documents, get in touch: www.snpaulinfotech.com


References

[2]  structlog. Configuration

Recent Posts

See All
BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM

Build Chapter 4: Classifying Files in a GitHub Repository Part 1: Foundation and Repository Understanding | For engineers learning RAG | About 12 minutes to read, 25 to follow along In Build C

 
 
 

Comments


bottom of page