Metadata-Version: 2.4
Name: biblia
Version: 0.9.5
Summary: Biblical study assistant with AI-powered analysis and research
Author-email: Victor Jotham Ashioya <victorashioya960@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/ashioyajotham/bible
Project-URL: Repository, https://github.com/ashioyajotham/bible
Project-URL: Issues, https://github.com/ashioyajotham/bible/issues
Keywords: bible,ai,theology,exegesis,research
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Religion
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Religion
Classifier: Topic :: Education
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.30.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: google-generativeai>=0.8.0
Requires-Dist: rich>=13.0.0
Requires-Dist: colorama>=0.4.6
Requires-Dist: keyring>=24.0.0
Requires-Dist: fpdf2>=2.7.0
Dynamic: license-file

# Biblia

A terminal-based biblical research assistant built on an agentic pipeline architecture. Each study session uses Google Gemini 2.5 Flash as an editorial curator — not a search engine — informed by web context, authoritative ESV scripture, the liturgical calendar, and a persistent personal memory graph that grows with every session.

---

## Research Background

### Why an agent, not a chatbot?

A chatbot answers a single prompt in isolation. An agent maintains state, calls external tools, and feeds the outputs of each tool into the inputs of the next. Biblia is structured as a **tool-dispatch pipeline**: every Gemini call in the teaching sequence receives a *growing* context object — the previous call's output becomes part of the next call's prompt.

By the time Gemini writes a prayer, it holds:

- The original question
- Web search snippets from Serper (what commentators are saying)
- The theological analysis it just produced
- Actual ESV verse texts fetched from the API for each inferred reference
- The application points it generated in the preceding step
- A formatted block from the MemoryGraph: past topics, their key verses, how they relate

This is the distinction between a language model as a *generator* and a language model as a *curator and synthesizer*. The model is not answering in a vacuum — it is editing, weighting, and composing across heterogeneous inputs.

### Personalization through the memory graph

Biblical study is not a sequence of independent queries. Doctrine builds on doctrine; a teaching on grace should know you have already studied the law. The MemoryGraph (`~/.biblia/memory.json`) records every topic taught and every verse read as a concept node. Nodes link to co-occurring concepts studied in the same session. On every subsequent query, the graph scores stored concepts by word-overlap with the new query and injects the most relevant past teachings as context.

This means:
- The application section of a teaching on "sanctification" cites your prior study of "justification"
- The verse selection for Friday avoids passages you read on Monday
- A reflection after three sessions on Pauline theology is grounded in the cumulative arc, not just the last command

### Verse selection as editorial curation

The `verse` command does not draw randomly from a fixed list. Gemini receives the liturgical day context (season, day of week, their thematic character) alongside the memory graph and recently read references, then selects one passage and provides a one-sentence rationale. The ESV API fetches the authoritative text. The devotional's first paragraph makes the editorial reasoning explicit — *why this verse, today, for this student*.

The liturgical calendar is computed from first principles using the Anonymous Gregorian Easter algorithm, covering Advent, Christmas, Epiphany, Lent, Holy Week, Eastertide, Pentecost, and Ordinary Time.

---

## Architecture

### Pipeline overview

```mermaid
flowchart TD
    User([User]) --> REPL[REPL\nmain.py]

    REPL -->|teach| TP[Teach Pipeline]
    REPL -->|verse| VP[Verse Pipeline]
    REPL -->|reflect| RP[Reflect Pipeline]
    REPL -->|history| HP[History View]

    subgraph TP [Teach Pipeline]
        direction TB
        T1[Serper: web search] --> T2[Gemini: theological insights\nquery + snippets + memory]
        T2 --> T3[Gemini: infer references\nfrom insights]
        T3 --> T4[ESV API: fetch verse texts]
        T4 --> T5[Gemini: application\ninsights + scripture + memory]
        T5 --> T6[Gemini: prayer\neverything accumulated]
        T6 --> T7[MemoryGraph.add_teaching]
    end

    subgraph VP [Verse Pipeline]
        direction TB
        V1[Liturgical Calendar\nseason + day theme] --> V2[MemoryGraph: recent context\n+ recently read refs]
        V2 --> V3[Gemini: select ONE reference\n+ rationale]
        V3 --> V4[ESV API: fetch text]
        V4 --> V5[Gemini: devotional\nwith personalised rationale]
        V5 --> V6[MemoryGraph.add_verse]
    end

    subgraph RP [Reflect Pipeline]
        direction TB
        R1[StudySession: session history] --> R2[MemoryGraph: related context]
        R2 --> R3[Gemini: reflection\nINSIGHTS / APPLICATION / PRAYER]
    end

    subgraph HP [History View]
        direction TB
        H1[StudySession: current session\ntimeline]
        H2[MemoryGraph: past teachings\n+ past verses]
    end

    MG[(MemoryGraph\n~/.biblia/memory.json)] --> T2
    MG --> T5
    MG --> T6
    MG --> V2
    MG --> R2
    T7 --> MG
    V6 --> MG
```

### Data flow through a teach session

```mermaid
sequenceDiagram
    actor User
    participant Agent as BibleAgent
    participant Serper
    participant Gemini
    participant ESV as ESV API
    participant MG as MemoryGraph

    User->>Agent: teach → "love and passion"
    Agent->>MG: get_context("love and passion")
    MG-->>Agent: prior study context

    Agent->>Serper: search("love and passion")
    Serper-->>Agent: web snippets

    Agent->>Gemini: insights prompt\n[query + snippets + memory]
    Gemini-->>Agent: theological analysis

    Agent->>Gemini: refs prompt [insights]
    Gemini-->>Agent: "1 Cor 13:4, John 3:16, ..."

    Agent->>ESV: fetch_many(references)
    ESV-->>Agent: actual verse texts

    Agent->>Gemini: application prompt\n[insights + verse texts + memory]
    Gemini-->>Agent: practical application

    Agent->>Gemini: prayer prompt\n[query + insights + scripture + application + memory]
    Gemini-->>Agent: composed prayer

    Agent->>MG: add_teaching(query, insights, refs)
    Agent->>User: display full teaching
```

### Key services

| Service | Role |
|---------|------|
| `GeminiLLM` | All generation — analysis, selection, composition. 429 quota errors handled with retry-after backoff. |
| `ESVService` | Authoritative verse text. All displayed scripture is fetched here, never hallucinated. |
| `SerperService` | Web search enrichment for teaching context. Result cached per query in-session. |
| `MemoryGraph` | Concept graph persisted to `~/.biblia/memory.json`. Nodes = topics + verse refs. Edges = co-occurrence within sessions. |
| `LiturgicalCalendar` | Pure date arithmetic — Easter algorithm, Advent start, all major seasons. No external calls. |

---

## Installation

```bash
pip install biblia
```

Or from source:

```bash
git clone https://github.com/ashioyajotham/bible.git
cd bible
pip install -e .
```

No GPU, no PyTorch, no HuggingFace stack. Install footprint ~50 MB.

---

## Configuration

Run `bible --setup` on first launch, or set keys directly:

```bash
bible --setup
```

Three keys are required:

| Key | Source | Purpose |
|-----|--------|---------|
| `GEMINI_API_KEY` | [Google AI Studio](https://aistudio.google.com/apikey) | All AI generation and curation |
| `SERPER_API_KEY` | [serper.dev](https://serper.dev) | Web search for teaching enrichment |
| `ESV_API_KEY` | [api.esv.org](https://api.esv.org) | Authoritative verse text |

Keys are stored in the system keyring (Windows Credential Manager / macOS Keychain / libsecret on Linux), with `~/.biblia/.env` as fallback. They load automatically on startup — no manual `export` required.

---

## Usage

```bash
bible [--theme dark|scholar|minimal] [--verbose] [--setup] [--health]
```

### CLI flags

| Flag | Description |
|------|-------------|
| `--theme dark\|scholar\|minimal` | UI colour theme (default: `dark`) |
| `--verbose` | Enable debug-level logging — shows full prompt/response traces, suppressed by default |
| `--setup` | Interactive API key setup; stores keys in system keyring and exits |
| `--health` | Run a one-shot service health check (key status, Gemini, Serper, ESV, memory graph) and exit |

### REPL commands

| Command | Alias | Description |
|---------|-------|-------------|
| `teach` | `t` | Full theological analysis: web search → synthesis → scripture → application → prayer |
| `verse` | `v` | Liturgically-aware daily passage selected by Gemini; devotional with rationale |
| `reflect` | `r` | Synthesise the session into insights, application, and prayer |
| `history` | `hi` | Browse teachings, verses, and reflections — current session and cross-session memory |
| `logs` | `log` | Agent health check: key status, service reachability, recent log entries |
| `export` | `e` | Export the session — Markdown or PDF; prompts for format and filename |
| `config` | `cfg` | View, set, or delete API keys without leaving the app |
| `help` | `h` | Command reference |
| `exit` | `q` | Quit |

### Themes

| Theme | Character |
|-------|-----------|
| `dark` | Cyan accents on dark background — default |
| `scholar` | Amber tones — warm, document-like |
| `minimal` | White borders only — maximum readability |

---

## Project structure

```
biblia/
├── agent/
│   ├── bible_agent.py          — command dispatch + full pipeline logic
│   ├── base_agent.py           — holds ModelManager, MemoryGraph, formatter, session
│   ├── search_agent.py         — thin Serper wrapper
│   └── components/
│       ├── memory.py           — MemoryGraph: concept nodes, edges, persistence
│       └── session.py          — StudySession: in-session teachings/verses/reflections
├── services/
│   ├── esv_service.py          — ESV Bible API: fetch() and fetch_many()
│   ├── serper_service.py       — Serper search API
│   ├── model_manager.py        — singleton GeminiLLM factory
│   └── llm/
│       ├── gemini_llm.py       — Gemini 2.5 Flash wrapper with 429 retry backoff
│       └── model_types.py
├── utils/
│   ├── health.py               — service health checks: keys, Gemini, Serper, ESV, memory
│   ├── liturgical.py           — Western Christian calendar: Easter algorithm, all seasons
│   └── formatters/
│       ├── console_formatter.py — Rich TUI renderer; theme-aware
│       └── markdown_formatter.py
├── config/
│   ├── keys.py                 — resolution chain: env → keyring → ~/.biblia/.env
│   ├── settings.py             — metaclass Config for live os.getenv() on every access
│   └── setup.py                — interactive key setup, config REPL command
├── models/
│   ├── verse.py
│   └── verse_categories.py
└── main.py                     — CLI entry point, REPL loop, --health / --setup flags
tests/
├── test_bible_agent.py         — unit tests (command dispatch, session management)
├── test_integration.py         — full pipeline tests (mocked APIs)
├── test_memory.py              — MemoryGraph: add, link, context, persistence
├── test_liturgical.py          — Easter dates, Advent start, season detection
└── conftest.py
```

---

## Running tests

```bash
pytest
```

All external APIs are mocked. No keys required to run the suite.

---

## Disclaimer

Biblia is a research and study tool. Output should be cross-referenced with authoritative theological sources, commentaries, and pastoral guidance. The ESV text is fetched directly from the API; all other content is AI-generated and should be treated accordingly.

---

## License

MIT — see [LICENSE](LICENSE).
