Portfolio

IA Rectory: the AI service shared by Rectory, Libro Digital and Status

A FastAPI microservice that handles every Google Gemini call in the Rectory ecosystem: 26 endpoints for 3 projects, from reports and regulation Q&A to ID card reading and a voice assistant. Stateless: it keeps no prompts, files or answers. Lead author (24 of 29 commits). Python, FastAPI, Gemini and AWS.

★ Featured In production Tech lead

Leer en español

IA Rectory: the AI service shared by Rectory, Libro Digital and Status

IA Rectory: the AI service shared by Rectory, Libro Digital and Status

Until August 2026, Rectory's AI lived inside its PHP controllers, and Libro Digital had to ask Rectory for every call. With a third project on the way, I split the AI into its own service: ai-service, published as IA Rectory at ai.rectory.cl. It receives prepared data, builds the prompt, asks Google Gemini and returns JSON. It stores nothing.

It's a service with no screens: other applications use it, not people. That's why this case study uses diagrams and screenshots of what the AI does inside each project.

In 30 seconds

  • What I built: a FastAPI AI microservice that handles every Gemini call in the Rectory ecosystem, in production on AWS.
  • My role: lead author (24 of 29 commits, 93% of the lines). Architecture, 16 of its 17 modules, deployment and documentation. My teammate built the lesson log assistant and the control over Gemini's reasoning.
  • Result: 26 endpoints for 3 projects, from reports and regulation Q&A to ID card reading and a voice assistant. The Gemini API key lives on a single server.
  • The surprise: accented letters and ñ arrived broken at Libro Digital. The JSON was fine; an HTTP header was missing one word.
  • Stack: Python, FastAPI, Pydantic, the google-genai SDK, nginx, systemd and AWS EC2.

Before: AI inside Rectory, with Libro Digital depending on it. After: three projects and a single service

Overview
RoleBackend developer, lead author (24 of 29 commits)
PeriodAugust 14 to November 24, 2026
TypeShared AI microservice with no UI of its own
StatusIn production (AWS EC2, Amazon Linux 2023)
CodePrivate; this case study uses diagrams, screenshots and selected snippets

Why split out the AI

Rectory called Gemini from a GeminiService.php, with prompts inside each controller. When Libro Digital needed AI, its calls went through Rectory, which only relayed them. Status Rectory was going to need its own for the daily bulletin.

I set three goals:

  1. Keep the Gemini API key on a single server.
  2. Keep the prompts in a single repository, with tests.
  3. Give each project its own secret, so a leak wouldn't open the door to the others.

What I built

PieceWhat I didWhy
Modules per consumerOne folder per project (rectory/, libro_digital_rectory/, status_rectory/) and four files per module: schemas, prompts, service and routerAdding a feature means copying a neighboring module
AuthenticationHMAC-SHA256 per action, with a different secret for each projectThe token for one action doesn't work for another
Gemini clientA single file talks to Google and exposes 8 methods: text, schema-bound JSON, files, web search, tool-calling chat, voiceSwitching models or SDKs happens in one place
Structured outputResponses validated against Pydantic models, truncation detection and retriesThe consumer gets valid JSON or an error that names the cause
FilesPDFs and photos sent to Gemini in the same request and dropped when it endsRead calendars, regulations and ID cards without keeping copies
VoiceEphemeral tokens for Gemini LiveThe browser talks to Google and the audio never touches the server
Deploymentnginx with TLS, uvicorn bound to 127.0.0.1, a systemd unit with a read-only file systemThe process can't leave files on the server
DocumentationArchitecture, development, deployment and a step-by-step guide for adding a moduleThe next developer doesn't need me

What the AI does across the ecosystem

The service has 26 endpoints in 17 modules. Rectory uses 20, Libro Digital 5 and Status Rectory 1. Some read files, some search the web with Google, and every newer one returns JSON validated against a schema.

Catalog: 26 endpoints in 17 modules for Rectory, Libro Digital and Status Rectory

The endpoints document themselves in Swagger, which FastAPI generates from the Pydantic schemas.

ai-service Swagger UI with Rectory's endpoints

The AI at work

People never see ai-service. They see what it returns, inside each application.

In Rectory, a school owner asks whether an expense can be charged to SEP funds. The answer cites the page and account number from the official manual.

Accounts manual Q&A in Rectory: the answer cites the manual's page and account

In Libro Digital, a teacher writes the class record and the AI improves it or drafts it from the learning objectives. My teammate built this module.

Lesson log writing assistant in Libro Digital

In Status Rectory, the AI writes a morning bulletin about the services from data that's already public.

Daily bulletin written with Gemini at status.rectory.cl

The interesting part: a service that remembers nothing

The decision that shaped the design most was keeping ai-service stateless: no database, no cache, no queue and no files. Each project decides what data to send and stores what it needs from the result. The service doesn't know which school is asking, or who.

For a school system, that answers the privacy question in one go: what does the AI keep? Nothing. I made that verifiable in the code and the configuration:

  • Files are read with await file.read() and sent to Gemini in the same request. For files over 1 MB, FastAPI keeps a temp file while the request lasts and then deletes it.
  • I don't log content: the logs only keep method, path and HTTP status.
  • The systemd unit makes the file system read-only for the process (ProtectSystem=strict, ProtectHome) and gives it a private /tmp (PrivateTmp). If a module tried to save a file on the server, it would fail.
  • For ID card reading at the school gate, the prompt asks only for the fields the gate staff needs, and the photo is dropped when the request ends.

Life of a request: authenticate, validate, build the prompt, ask, check and answer without storing anything

Deep dive: the technical decisions

1. An HMAC token per action, not per project

There are no users or sessions. Each endpoint declares which project and which action it accepts, and the consumer signs the action name with its secret:

def require_bridge_token(consumer: str, action: str):
    full_action = f"{consumer}.{action}"

    def dependency(x_ai_bridge_token: Annotated[str | None, Header()] = None,
                   settings: Settings = Depends(get_settings)) -> None:
        if not x_ai_bridge_token:
            raise HTTPException(status_code=401, detail="Missing X-AI-Bridge-Token header")
        expected = _expected_token(full_action, settings.hmac_secret_for(consumer))
        if not hmac.compare_digest(expected, x_ai_bridge_token):
            raise HTTPException(status_code=403, detail="Invalid X-AI-Bridge-Token")

    return dependency
/media/portfolio/extras/9/router.post("/generate", dependencies=[Depends(require_bridge_token("rectory", "motd.generate"))])

The token for generating the message of the day can't read an ID card, and Libro Digital's secret can't call Rectory's endpoints. I reused the pattern Rectory already had in its bridges, so on the PHP side signing is a single hash_hmac line.

The token carries no timestamp and doesn't cover the request body. That's acceptable today because only our own servers call it over HTTPS. I documented the trade-off: if a consumer ever called from a browser, the token would need an expiry or a signed body.

2. A single file talks to Google

gemini_client.py is the only file that imports the Gemini SDK. Modules say what to send (prompt, files, schema, temperature) and the client decides how. It exposes 8 methods: text, schema-bound JSON, one or several files, Google search, tool-calling chat, text to speech and tokens for live voice.

Each module keeps the temperature the original PHP controller used. I ported many prompts almost word for word from Rectory, and each prompts.py docstring names its source controller. I did that so the migration wouldn't change results that were already tuned.

3. Schema-bound JSON, and errors that name the cause

Newer modules ask Gemini for structured output with a response_schema and validate the answer with Pydantic. Gemini still returns broken JSON now and then, and the usual cause is running out of tokens.

  • If the answer comes back truncated (finish_reason == "MAX_TOKENS"), the error says so. Without that, the message would read "field X is missing" and point at the wrong problem.
  • Surveys and remedial guides make two attempts: if the first comes back truncated or malformed, they retry at a lower temperature (0.5 → 0.2 and 0.4 → 0.2). Retrying inside the service costs less than making every consumer do it.
  • Reasoning models spend tokens from the same budget as the answer. My teammate added control over the reasoning level, and data extraction modules (ID card, calendar, protocols, bulletin) set it to "low".

4. Voice without exposing the API key

Rectory's assistant also talks through Gemini Live. Audio can't go through an intermediate server without adding latency, and the API key can't reach the browser.

The answer was an ephemeral token. Rectory asks ai-service for a single-use token that lasts 60 seconds. The instructions, tools and voice are locked inside the token, so the browser can't change them. With that token, the browser opens the websocket straight to Google. When the model asks for school data, Rectory checks permissions and runs the tool.

Live voice: ai-service only hands out the token; audio flows from the browser to Google

5. The surprise: broken ñ

When I connected Libro Digital, responses arrived with broken accents and ñ. The JSON was valid UTF-8. The problem was the header: Starlette, which FastAPI builds on, only adds charset= to text/* types, so it sends application/json without a charset. The JSON spec says it's always UTF-8, but Libro Digital's HTTP client assumed another encoding when the header was silent.

The fix was a default response class that declares the charset:

class UTF8JSONResponse(JSONResponse):
    media_type = "application/json; charset=utf-8"

I documented it with a warning: don't remove it. It taught me to check the headers, not only the body, when two systems don't understand each other.

6. Tests that never call Gemini

No test calls Gemini. Each module injects a fake client through FastAPI's dependency_overrides, which records the prompt it receives and returns a fixed answer. The tests check the assembled prompt, the response shape and the errors. Every module covers at least the success case, a request with no token (401) and an invalid token (403); structured modules also cover truncated and malformed answers. All 184 tests run in under a second.

By the numbers

MetricValue
PeriodAugust 14 to November 24, 2026
Commits29 on main: 24 mine and 5 from my teammate
Endpoints26, for 3 projects
Modules17 (12 for Rectory, 4 for Libro Digital, 1 for Status)
AI report types38
Tests184 across 21 files, under 1 second
Databases0
Uptime measured by Status Rectory100% in October, 99.973% in November (through the 30th)

What I take away

On the technical side, I value what a stateless service gave me. It simplified privacy, deployment and testing at once: no data to protect on the server, nothing to migrate and nothing to clean up between tests.

On teamwork, I learned to design so someone else could add to it without asking me. The guide for adding a module and the "one module, four files" rule let my teammate build the lesson log assistant in the same shape as everything else.

Diagrams built from ai-service's code and documentation (November 2026). The Rectory, Libro Digital and Status Rectory screenshots come from their own case studies in this portfolio.

Project screenshots

Screenshot 1 Screenshot 2 Screenshot 3 Screenshot 4 Screenshot 5 Screenshot 6 Screenshot 7 Screenshot 8 Screenshot 9 Screenshot 10 Screenshot 11 Screenshot 12
← All projects