The Best Code in AICodeAssitant Is the Code That Sleeps

A free-tier RAG app that reads your zip file, answers questions with file citations, and paces its Gemini calls through a homemade token budget that never overspends.

7 min read · Python, FastAPI, React • View on GitHub • More from bitnimbus24

A vast archive hall of filing cabinets with one drawer open, a mechanical arm lifting a single folder into a shaft of light while zipped boxes queue on the floor. It represents the app pulling a handful of relevant chunks out of an entire uploaded repository.
Ask a question about a repository and the app retrieves a small handful of chunks. Everything else stays in the cabinet.
Key Takeaways

The code that sleeps

Almost every retrieval-augmented generation tutorial spends its effort on the part that fetches. This repository spends its best effort on the part that waits. The single most sophisticated file in a code-assistant project is a scheduler that decides when not to call the model.

It lives in backend/app/services/embeddings.py. The embedding client processes chunks in batches of 16. Before each batch it estimates the cost with a crude but effective rule (len(text) // 4), keeps a sliding 60-second ledger of what it has already spent, and checks the running total against a budget of 24,000 tokens per minute. That budget sits deliberately under the 30,000 the comment cites for the free tier. If the next batch would push past it, the loop sleeps and re-checks.

while True:
    now = time.time()
    recent = [(ts, tokens) for ts, tokens in recent if now - ts < 60]
    used = sum(tokens for _, tokens in recent)
    if used + batch_tokens <= TOKENS_PER_MINUTE_BUDGET or not recent:
        break
    wait = max(1.0, 60.0 - (now - recent[0][0]) + 0.5)
    time.sleep(min(wait, 30.0))

The or not recent guard is the detail that earns the file its reputation. Without it, a single batch that exceeds the budget on its own would never satisfy the condition, and the loop would spin forever. With it, the pacer always makes progress. That is the kind of edge case most hobby RAG projects never reach, because they never wrote the pacer in the first place.

The surrounding retry logic is less careful. _retry_delay parses Google's suggested wait out of the error string with regular expressions, which breaks the moment the wording changes, and _is_rate_limit matches the bare substring "quota", so an unrelated quota error can be misread as a rate limit. The pacer is correct; the error handling around it is hopeful.

The pacing loop estimates each batch, checks a rolling 60-second ledger against a 24,000-token budget, and sleeps rather than overspend.

What AICodeAssitant actually does

Now the loop has a home. A user uploads a .zip of a repository or a single source file. The backend extracts the text-based files, splits them into fixed-size chunks, embeds those chunks with Gemini, and stores the vectors in a local file. A natural-language question is embedded the same way, matched against the stored vectors by cosine similarity, and the top chunks are handed to a chat model with instructions to cite file paths.

The target user is a developer onboarding onto an unfamiliar codebase. "Where is auth handled?" and "give me the architecture" are the questions this is built for. It is a personal or demo-scale tool, not a multi-tenant product, and the README says so in its own words: free-tier notes, ephemeral storage. The stack is FastAPI and Pydantic on the backend, React and Vite on the front, with Gemini reached through the OpenAI Python SDK pointed at Google's OpenAI-compatible endpoint.

The origin context here is thin on purpose. There is no verified maintainer identity, no interview, no launch thread. What the project offers instead is a README that volunteers its own ceilings, which reads as a statement of character rather than a gap.

What happens when you upload a zip

The ingestion path in routes/upload.py is the most important file in the backend, because it holds the filtering policy. Each archive entry passes a sequence of gates. Directories are skipped. Hidden entries are skipped, meaning any path component that starts with a dot. Ignored directories such as node_modules, venv, dist, and vendor are skipped. The extension is checked against the allowlist. The size is checked. Then the file cap is enforced.

Give the path-safety helper its due. _safe_parts normalizes backslashes, drops empty and . components, and rejects any ... An absolute path loses its leading slash because empty components are removed, so /etc/passwd becomes etc/passwd inside the workspace. That is a correct zip-slip defense, and it is the second place in the repo where someone thought about adversarial input.

There is also a dead entry. .env.example sits in the allowed extensions, but Path(".env.example").suffix is .example, so the entry can never match. The hidden-file check would drop it anyway. A small thing, but it shows the allowlist was assembled by feel rather than tested.

Eight hundred characters at a time

An extreme close-up of shears slicing diagonally through a stack of printed source-code pages, cutting a line of code in half, with an offset duplicate strip below showing the overlap. It shows how a fixed character window splits code at arbitrary, syntax-blind boundaries.
The chunker does not know what a function is. It counts characters, and sometimes the cut lands mid-statement.

The chunker is about twenty lines. It is a plain sliding window over characters with 120 characters of overlap, advancing by chunk_size - overlap each step. It is deterministic, cheap, and completely blind to syntax.

For a code-QA tool, that blindness is the quality limit that matters most. A function can be split mid-statement. The retrieved context can begin or end in the middle of a line, so the model is handed a fragment that starts with half an expression and no way to know it. The overlap softens this but does not fix it. The natural upgrade is line-boundary-aware splitting, or a real parser such as tree-sitter that cuts on syntax nodes instead of character counts.

The docstring claims the sizes were chosen to fit Gemini's embedding token limits. At roughly 800 characters a chunk is nowhere near any such limit, so the real tradeoff being made is retrieval granularity: smaller chunks retrieve more precisely but lose surrounding context, larger ones carry more but dilute the match. The rationale in the comment does not match the decision in the code.

The whole vector database is a pickle

Storage is an in-memory dictionary of chunk IDs to vectors, persisted to disk with Python's pickle and searched with NumPy cosine similarity. Chunk IDs take the form path:index, and the only metadata attached to each chunk is its file path.

chunk_id = f"{path}:{index}"
metadata = {"path": path}

What this buys is real: zero infrastructure, zero cost, and a store you can read end to end in an afternoon. What it costs is equally real. There are no incremental updates, so re-indexing means re-embedding. There is no metadata filtering, so you cannot ask for chunks from a directory or a language. There is no concurrent-writer story and no durability guarantee. And pickle is a format you should never load from an untrusted source, which is fine when the only writer is your own upload route. Because metadata is just the path, citations are file-level, never line-level.

There is a small config smell worth noting. Settings() is instantiated at module level in config.py and again in vector_store.py, so .env gets read twice. Harmless at this scale, but it marks where configuration was not centralized.

Where it breaks

These are the honest failure modes, stated without hedging.

Demo scale, honestly

Set the pacer next to the rest of the app and the contrast is the point. Every row below is a deliberate trade that is correct for one user and wrong for a hundred.

DimensionAICodeAssitantA production RAG service
Vector storePickled NumPy array on local diskpgvector, Qdrant, or similar, with indexes
ChunkingFixed 800-char window, 120-char overlapSyntax-aware splitting, line or AST boundaries
RetrievalCosine similarity over the whole storeHybrid search with metadata and reranking
CitationsFile-level paths onlyFile and line ranges
IngestionSynchronous request, minutes longBackground jobs with progress and cancellation
DurabilityEphemeral disk, rebuilt on restartPersistent store with backups
Quota handlingHomemade token-budget pacerQueue, backoff, and provider-level limits
ScaleOne user, 400 files, 250 chunksMany users, many repositories

Where it sits is a separate question from how it is built. IBM's watsonx-code-assistant is an Apache-2.0, Granite-based assistant working inside the IDE, with chat, completion, explanations, unit-test generation, and translation. AyinkxLab/ai-code-assistant is MIT-licensed and repository-oriented, covering GitHub issue and pull-request analysis, code review, team workspaces, and a plugin system. On the product side there is Cursor, Bolt, Replit, Copilot, and Tabnine. No source establishes any relationship between any of these and AICodeAssitant, and the target's own metrics are unverified here. The honest read is that this repo is not competing with them. It is a small, self-contained demonstration of one idea done carefully.

That idea is worth keeping. Most projects at this scale reach for a vector database and a retry decorator and call it done. This one looked at a hard external constraint, a free-tier quota, and built a scheduler that respects it. The rest of the app is a straight line, and the article should say so. But the line that sleeps is the one that shows the author was thinking about the system as a system.