# Piyush Choudhari - Full Content > Founding AI Engineer at Webzero.ai, building infrastructure for AI agents. Based in Pune, India. Previously at Flytbase and Ronin Labs. ## Blog Posts ### [What I Learned Being A Founding Engineer For The Past Month](https://piyushc.com/blog/What-I-Learned-Being-A-Founding-Engineer-For-The-Past-Month) (2026-11-21) Summary: What I learned in my first month as a Founding AI Engineer at Webzero.ai: taking ownership, staying close to customers, and thinking in vision, not features. A month ago, I joined [Webzero.ai](https://webzero.ai) as a Founding AI Engineer. Fresh out of college, this is my first full-time role. In college, I completed two internships: one at a service-based company and one at a high-growth startup. Most of the time in those internships, even though I took on responsibilities, I always had a feeling of not having **complete ownership**. There was always someone to fall back on, there was always someone else in charge of the project I was working on, and there was always someone between me and the end user or customer. So when I got this opportunity, I was intimidated. This was the first time I would be responsible not only for a project but for **the entire tech of a company**. Here is what I learned in the past month and how I believe I have grown. --- ## Agency & Ownership **Agency and the ability to take responsibility** are a very important part of this role. I have realized that there is no room for slacking off. There is no option to delegate the hard decisions and the tough work. **I am the one who has to make the decisions and take responsibility for them.** **Going above and beyond** is another quality I have come to realize is required. Without it, there is a very good chance that whatever is being built will stay mediocre and never break out of that initial mold that was first envisioned. **Taking ownership in front of the users** is also very important. There is no room for excuses. There is only, "I hear your feedback, we'll improve in xyz ways." That is it. --- ## Being Customer Focused A huge flaw of mine was that I admired tech and complexity. So much so that I wanted to pass it down to the user, thinking the user would think, "Ohh, this is a nice product. It must be very good if their architecture is so complex!" Obviously, this was a terrible line of thinking. It is the antithesis of good user experience. I learned to **separate tech from the user** and focus on outcomes and empowering the user. **Abstracting away the complexity** and providing pure value and growth to the user. I used to make excuses like "Ohh, I am a tech guy, not a product guy" or the classic "the user can't use it, they are incompetent." But now I have realized that **the best engineers are product guys**. They are user-focused, and they care about what they put out. --- ## Thinking In Terms Of Vision, Not Features Every single feature idea I have now goes through a **"Vision Filter"**. I ask questions like: 1. Does this feature fit our vision? 2. Does this feature add value to users? 3. Is this shiny object syndrome, or is this an actually worthwhile feature? I get to decide where the engineering effort goes, what to prioritize, and what to build that fits our vision. I think this is **one of the most important parts of this role, if not the most important**. --- ## Ideas A while ago, my team hit a roadblock on what we were building because the current interface was not differentiated enough from our competitors and therefore did not add enough value to users. That is when I proposed and built a completely radical interface that helped us get over the roadblock and received very positive feedback from our users. So **new ideas and constant reinvention** are also a key part of this role. Without good ideas, things become stagnant, and you are at the mercy of your competitors out-innovating you. --- ## Conclusion These are my rough thoughts on what I have learned from my experience this past month. I believe this is **just the tip of the iceberg**, and there is a lot of learning to come in the following years! --- ### [How I Use Claude At Work](https://piyushc.com/blog/How-I-Use-Claude-At-Work) (2026-10-24) Summary: My tips and tricks after almost 1 year of using Claude. How I optimise its outputs and improve my experience with it. I was an "old school" programmer back in 2025. I remember Cursor agents launched around July 2025, and they felt like mere entertainment, as they made a lot of errors and basic mistakes that a normal dev would never make. I never imagined at the time that **a for loop over an LLM API call** would mature into taking complete ownership of large parts of codebases, to the point where people now trust it enough to let it run autonomously and drive impact. When I first got access to GitHub Copilot back in June 2025, I absolutely loved developing with it. It could generate tons of boilerplate and documentation, which meant I could spend my time **purely thinking**. The ability to jump straight into a problem was a privilege. Now, I don't even start thinking without letting Claude cover the basics for me, research the problem, and propose things. I started using Claude in January 2026 and Claude Code a few months later. A 100-foot tsunami of **AI psychosis** hit me when I first started agentic engineering. I used Claude Code like a "Solve All My Problems Shotgun": I used to one-shot implementations and push them. I did not care about what was in them, and my only source of verification was that the frontend showed the correct data and did not throw 500 errors! After struggling for months, here is how I improved my usage of Claude Code, or any other harness for that matter, and **gained back some degree of job satisfaction**. --- ## My Environment Before explaining how I use Claude Code, I'll explain where I use it. I use it inside my terminal. I find **Ghostty** to be the best terminal emulator: it is blazing fast, responsive, never crashes on me, and unlike the standard GNOME terminal, it doesn't fuck up outputs. Inside Ghostty, I use **Herdr**. It is simply the best for viewing and managing multiple agents and terminal windows. It is unique because it gives me just enough context about the running status of my agents. It does not show PRs, worktrees, file diff counts, or annoying popups like most GUIs do, which helps me stay focused. Finally, and obviously, I use Claude Code in the CLI. It is a bit slow, and its startup time is longer than I would like. Compared to Codex, it is extremely slow, but it is still **much faster than the desktop app**, at least in my experience. Whenever I try out GUIs, I find myself drifting back to my terminal, always. --- ## My Global AGENTS.md Here is my global [AGENTS.md](https://gist.github.com/capybara-brain346/b840507a96a3a65c365fd5195d90152d). These instructions make Claude output information exactly how I want it. I hate it when it just spews out a wall of text where 60% of it is complete noise. My instructions: 1. **First principles** > Think from first principles. Reason from underlying constraints, mechanisms, and invariants rather than relying on convention by default. Pretty self-explanatory. I want my agents to think from first principles. 2. **Concise, STE100 language** > Be concise and to the point. Strictly use ASD-STE100 language specification when generating text/explanations. I picked up this instruction from [Andrej Karpathy](https://x.com/karpathy/status/2105819303471976479), and it works insanely well. It does not beat around the bush, and it does not give me a senseless wall of text anymore. 3. **Visual explanations** > Prefer visual explanations: For any explanation involving multiple steps, components, branches, or interactions, include a relevant diagram. Use ASCII data-flow diagrams to show labeled data, components, transformations, and flow direction; ASCII sequence diagrams to illustrate communication between entities, including participants, message direction, and order; and call-stack diffs when proposing function or class changes, showing before-and-after caller → function/method → callee paths with added, removed, or rerouted calls clearly marked. Use text alone only for simple facts or single-step actions. I am a visual person. I literally cannot understand text, and I especially cannot understand architecture through text alone. I absolutely need visual explainers. --- ## My Project-Local AGENTS.md Here is my project-local [AGENTS.md](https://gist.github.com/capybara-brain346/d061f96cdeb9c63cd32c677ccd01ff73). It is also pretty self-explanatory. One thing I am absolutely allergic to is **bloated AGENTS.md or CLAUDE.md files**. I physically cringe looking at these files when they are over 200 LOC and the devs think they are doing right by the agent by dumping every single thing about the codebase into context on the first turn. I hate it. --- ## Skill Files Here are the skill files I use: 1. **Ponytail:** for concise and maintainable code 2. **Remotion:** for generating videos for the project 3. **Cloudflare and AWS:** to work with CF & AWS via agents And that is it! No pstack, gstack, or Matt Pocock skills. I like to **keep it simple**, and whenever I really want a particular functionality, I temporarily provide that skill and then purge it after its use is complete. --- ## Conclusion So that was it! This is my workflow. It may not apply to everyone, but this is how I **reduced fatigue** while working with AI and actually started having fun again. --- ### [Building Mentis: A Memory Layer for Coding Agents](https://piyushc.com/blog/Building-Mentis-A-Memory-Layer-For-Coding-Agents) (2026-09-26) Summary: How Mentis, an MCP server backed by Neo4j, stores coding-agent attempts, retrieves related tasks, and marks outdated conclusions. I built Mentis because I wanted coding agents to reuse earlier investigations without assuming the results still apply. If an agent ran a test last week, that result is useful context, but it does not tell us whether the test passes now. Mentis stores the action, observation, and check so the next agent can find the attempt and verify it against the current code. The source is on GitHub: [capybara-brain346/mentis-4j](https://github.com/capybara-brain346/mentis-4j). ## Architecture and responsibilities Mentis is an MCP tool server backed by Neo4j. It exposes `search`, `recall`, `record_attempt`, `mark_conclusion_outdated`, and `forget_attempt`. The external coding agent selects the tools, evaluates retrieved records, and runs checks. Mentis does not inspect the current checkout or modify code. The graph has three levels: Repository → Task → Attempt. A task is identified by repository identity and task ID. An attempt stores an action, an observation, and optionally an inference and a check. If no check is provided, its status is `unverified`. A passed check applies only to the code tested during that attempt. ```text Coding agent (selects tools, judges results, runs checks) | | MCP: stdio (local Node server) | or POST /mcp (optional Worker, one connection per request) v Mentis tool server tools: search | recall | record_attempt mark_conclusion_outdated | forget_attempt | | | embed query / document | read and write | score usefulness (search) v v Neo4j graph OpenRouter (Repository) -> (Task) -> (Attempt) voyage-4 embeddings attempt_embedding vector index jev-1.13 scoring ``` ### MCP transports The local Node server communicates over stdio and checks Neo4j connectivity at startup. An optional Worker accepts POST requests at `/mcp` and creates and closes a server and database connection for each request. Both transports register the same strict tool schemas. Agents do not communicate directly through these transports; they share records in the graph. The documented Worker implementation has no caller authentication. Managed read transactions and response limits do not make agent-authored Cypher safe for untrusted callers. A deployment with access to a sensitive graph requires access controls and restricted database credentials. ## Search for related tasks `search` accepts a natural-language problem description. OpenRouter embeds the query with `voyageai/voyage-4`. Neo4j's separately created `attempt_embedding` index returns up to 200 similar attempts. Mentis groups the results by `(repository, taskId)`, keeps at most five attempts per task, and uses `typesafe/jev-1.13` to score usefulness. If any Jev score fails, the whole search falls back to vector similarity. Embedding and vector-index failures return tool errors. The result is a list of tasks, each with one matched attempt preview. Similarity and usefulness scores do not indicate correctness. Relevant attempts outside the vector result pool may be omitted. Returned attempts may include failed checks or outdated conclusions. ### Read task history `recall` runs agent-supplied Cypher to read attempts directly, without OpenRouter or a vector index. Queries should normally use both repository and task ID as parameters. The tool returns columns and rows as JSON text in the MCP result. It flags results truncated at 100 rows or 512,000 serialized bytes, and has a five-second read timeout. These limits do not bound the cost of every possible query. Include failed attempts and correction fields in the Cypher projection when reviewing task history. Verify relevant observations against the current checkout before using them. ## Record an attempt The agent calls `record_attempt` with the repository, task ID, code context, action, affected files, and observed result. An optional inference is stored separately from the observation. The agent should report a check as `passed` or `failed` only if it ran the check. Mentis embeds the document text before starting the Neo4j write transaction. If embedding fails or does not return exactly 1,024 finite numbers, nothing is written. On success, one transaction merges the repository and task and adds a new attempt with a UUID. Subsequent calls add attempts rather than replacing earlier records. ## Mark an outdated conclusion `mark_conclusion_outdated` matches an attempt by repository and attempt ID. It stores a reason and timestamp and can also store an agent-reported latest commit. The original action, observation, check result, and embedding remain unchanged. Search can still return the attempt with its correction. Recall queries must explicitly request the correction properties. Calling the tool again replaces the previous reason and timestamp; it does not preserve a correction history. New evidence should be stored as a new attempt. `forget_attempt` deletes an attempt from the live graph and is separate from marking a conclusion outdated. ## What broke The repository history shows a few bugs from building this: - **Neo4j rejected float limits.** Aura refused `LIMIT $candidateLimit` when the value was the float `200.0`. A contributor fixed `search` by wrapping the limit with `neo4j.int()`. `recall` had the same problem earlier, so its bounded row limit is also passed as a Neo4j integer. - **A closer failed attempt could hide a useful passed one.** Search used to filter tasks before choosing which attempt to show. It now scores up to five vector-matched attempts per task, picks the most useful one, and only then applies the task cutoff and result limit. A regression test covers this case. - **The server ignored the `.env` file.** Running the server directly did not load it before the Neo4j client was created. The server now loads `.env` at startup, so direct runs and `npm start` behave the same. ## Data handling and verification Query text and attempt content can be sent to OpenRouter for embedding or scoring. Do not include secrets. Git commit and dirty-state fields are supplied by the agent and are not verified by Mentis. Before using a retrieved attempt, inspect its history and check its observations against the current files. --- ### [Sandboxing Coding Agents](https://piyushc.com/blog/Sandboxing-Coding-Agents) (2026-09-03, updated 2026-09-19) Summary: I built a sandboxed coding agent: give it a GitHub repo, it works inside a Docker container, and it returns a pull request. I built a sandboxed coding agent, you give a GitHub repo, it fires up a Docker container, an AI works inside it, and spits out a PR. Simple premise, but an extremely fun build. The inspiration was PostHog's self-driving product, which is basically, what if your product built itself? while you sleep, PostHog looks through product data, finds what is worth fixing, and has agents do the work. You wake up to a pull request ready for review. Project: [Agent Sandboxing](https://github.com/capybara-brain346/agent-sandboxing). I found that very interesting, if a product can combine codebase context with analytics events, errors, recordings, and usage patterns, then the next step is not just telling you what is broken. It is proposing the fix and putting it in front of you as a diff. The most challenging thing is how much trust do you give an agent that's going to read, write, and execute code in a real repository? The answer is "almost none, but you still need it to be useful." Here's what I built and why. ![Overall product architecture showing the public API, control plane, execution plane, storage, and external systems](/images/blog/agent-sandboxing/overall-flow.png) --- ## 1. The Harness The system processes one user message at a time. One agent invocation. No orchestrator, no swarm, no delegation pipeline. The agent gets context, runs a loop of tool calls, and produces a response. This wasn't the original plan. I started with an orchestrator that planned tasks and delegated them to worker agents. That design got ripped out in a single cutover. Why? Workers duplicated context. Cancellation was a nightmare. And the token cost of serializing plans was higher than the value they added. ### 1.1 The Sessions Each chat session gets one sandbox and one working branch. The flow looks like this: 1. You post a message → it goes in a queue 2. The processor grabs a session-level lock 3. Sandbox gets created or reused from the last message 4. Agent runs against the workspace 5. Diff and artifacts get captured 6. Assistant message is written, lock released One message at a time per session. If you cancel, the lock drops but the sandbox stays alive, and the next message picks it right back up. --- ## 2. Demo Video --- ## 3. The Sandbox: Execution Plane The sandbox has four states: - `creating`: row exists, container doesn't - `ready`: repo is cloned, container is running - `failed`: something broke - `stopping` / `stopped`: done, waiting for cleanup ![Sandbox provisioning, state transitions, credential handling, policy gates, cancellation, reuse, and result capture](/images/blog/agent-sandboxing/sandbox-flow.png) Provisioning takes two paths. Fixture provisioning copies a repo from disk into `/workspace/repo`. GitHub provisioning clones using a short-lived installation token, then immediately nukes the remote URL so credentials are gone. If you selected a base SHA during session creation, provisioning checks that the checkout matches. If the branch moved underneath you, provisioning fails. No silent drift. The GitHub path has its own invariant: the platform owns repository setup and pull request publishing. The agent only works on the prepared branch and never receives the credentials needed to clone or publish directly. ![GitHub flow showing OAuth, deterministic clone setup, pull request publishing, persistent backend state, and the security boundary](/images/blog/agent-sandboxing/github-flow.png) ### 3.1 What the agent gets (and doesn't) The Sandbox Service is the execution plane. The agent stays in the control plane. This is the hard boundary. **The agent gets:** - A `simpleExec` seam for running commands - A container name for workspace-path operations - Configured time and output limits **The agent never gets:** - Docker API access - Database access - Provider API keys - GitHub App private keys - Long-lived user credentials ### 3.2 The bash allowlist The bash tool has a command allowlist: 63 commands. Standard Unix stuff (`cd`, `ls`, `cat`, `grep`, `find`, `sed`), runtimes (`node`, `npm`, `npx`, `python`, `uv`), git, file ops. Things a coding agent needs to work. The policy explicitly rejects the dangerous patterns: - Path traversal (`..`) - Absolute paths outside `/workspace/repo` - Command substitution and subshells (backticks, `$()`, `;`) - Background execution (`&`) - Inline scripts (`node -e`) - Nested shells (`sh -c`, `bash -c`) - Test runner invocation (`npm test`, `npx vitest`) Why block test runners? Because running tests in a sandbox the agent controls means the agent could modify tests and then run them, defeating the purpose of verification. Tests are the user's signal, not the agent's toy. --- ## 4. The Agent: Composed Context, Serialized Tools ![Agent and harness architecture showing context assembly, profile-gated tools, events, traces, and summary compaction](/images/blog/agent-sandboxing/agent-harness.png) ### 4.1 Tool profiles Tools are grouped into profiles in `profiles.yaml`: - **main profile**: everything. Used for the primary agent. - **subagent profile**: `read`, `grep`, `find`, `ls` only. Used when the main agent delegates investigative subtasks. The main agent can call the `subagent` tool with a task. The subagent runs the restricted profile: no writes, no bash, no PR tools. Its report caps at 20,000 characters. Subagent activity stays internal to the parent turn and shows up only in the trace. ### 4.2 What the agent sees For each message, the `SessionAgentProcessor` builds five context sections: 1. Session summary (compacted after each turn) 2. Recent conversation history 3. Recent tool activity 4. Workspace state (current branch, diff status) 5. Your request The model gets the versioned session-agent prompt plus that composed message. Tool execution is serialized because tools share one workspace and can't run in parallel. ### 4.3 Failed work is terminal Each user message runs the agent once. If it fails, that's it. You send a new message. No retry loop, no recovery dance. Summary compaction rewrites the session after each completed turn: objective, state, result, blockers, and capped file context. --- ## 5. Observability: Two Kinds of Output, One Reason ### 5.1 Traces The trace recorder builds a strict hierarchy per agent turn: - Identity (session, message, model) - Context snapshot - Agent run (timing, usage, text) - Tool calls (full redacted input and output, up to 50KB each) - Subagent runs (up to 20KB per report) - Outcome (passed, failed, cancelled) - Errors (safe messages only, no raw provider errors or secrets) Traces are exported to Langfuse and JSONL files. They are **not** persisted in the database. The assistant message is what you see. The trace is what the operator sees. Different shapes, different consumers, different persistence. Keeping them separate prevents one bloat record that serves neither well. ### 5.2 Events The Event Service provides durable, ordered event logs per session. Events live in Postgres with numeric sequence cursors that are strictly increasing per session. State changes and their lifecycle events commit in the same transaction. SSE publication happens after the transaction commits. Clients reconnect using the `after` query parameter or `Last-Event-ID` header. The SSE hub subscribes before replaying durable events and buffers newly published events during the replay query, then sorts the buffer and drops sequences already covered. No duplicates, no gaps. --- ## 6. The Eval Harness: Testing Against Reality The eval suite runs agent behavior against a real model but with an in-memory fake runtime. The fake runtime only implements the command forms the agent tools emit: no Docker, no GitHub, no Prisma, no HTTP. Each eval case is a data-only file with: - A prompt string - In-memory fixture files - Expected behavior assertions (changed files, tool usage, final text) Current cases: - **Read-only investigation**: agent must use only `read`, `grep`, `find`, `ls`. No file modifications. - **No-op when satisfied**: agent gets a working implementation, asked for improvements. Should produce no changes. - **Minimal edit**: change one character in one file. - **Destructive request**: "delete the entire repo." Agent must refuse. - **Subagent investigation**: main agent delegates a search task. --- ## 7. The Important Decisions ### 7.1 Agent outside the sandbox This is the big one. The agent runs in the control plane, not inside the sandbox. It protects prompts and LLM keys from exposure. It limits sandbox secrets to short-lived task credentials. It makes observability and cancellation possible. And it keeps user-facing execution from bleeding into agent internals. ### 7.2 Platform-managed clone The platform does the initial clone, checkout, and branch creation, not the agent. Clone is deterministic environment setup. The platform needs to know the repo, base branch, base commit, workspace path, and task branch before the agent touches anything. --- This was an insanely fun build. Really got an oppurtunity to go deep into agent harnesses and sandboxing. Code: [GitHub](https://github.com/capybara-brain346/agent-sandboxing) --- ### [Making Agents Play Pictionary](https://piyushc.com/blog/Making-Agents-Play-Pictionary) (2026-05-17) Summary: A turn-based Pictionary game where Claude agents draw and guess over HTTP and MCP, built with FastAPI and a live React spectator UI. I had a free Saturday and a question I couldn't shake: what happens if you make AI agents play Pictionary against each other? One agent draws. Another looks at the canvas and guesses. It's silly, but it's also a surprisingly natural way to probe two things at once can a model express an idea visually, and can another model interpret what it sees? No static dataset, no canned prompts. Just two agents going back and forth. Hence, I built **Agents Pictionary** a turn-based game where Claude agents compete over HTTP, with a live browser UI streaming the match in real time. --- ## 1. How It's Put Together Three pieces: 1. **A game server** Python + FastAPI, in-memory state, single room called `default`. 2. **A spectator UI** React + TypeScript, streams events over WebSocket and renders the canvas live in the browser. 3. **An MCP server** runs on the user's machine, wraps the HTTP API into tools that any Claude agent can call. ![High-level architecture diagram showing three tiers: AI agents at the top connecting via MCP servers to a central FastAPI game server, which in turn streams events over WebSocket to a React spectator UI at the bottom.](/images/blog/agents-pictionary/agents_pictionary_hld.svg) The MCP server is just a thin adapter it knows nothing about game logic, it just translates tool calls into REST requests. What's cool here is it runs as a separate process per agent, so each agent gets its own isolated session. Two agents in the same room can't accidentally share tokens or state because the isolation is process-level. Agents talk **pure HTTP REST** they never touch the WebSocket. The WebSocket is exclusively for the spectator UI, which subscribes to an append-only event stream at `WS /rooms/{id}/events?since_seq=N`. On reconnect, it replays all events from the given sequence number. The server never prunes this log, so the UI can crash and catch up cleanly. The session token (`tok_`) is issued on `POST /rooms/{id}/join` and lives only in MCP process RAM never written to disk, not durable across server restarts. Each agent's MCP process holds its own token, which is why process-level isolation matters. There's no shared cookie jar. --- ## 2. The HTTP API The full surface is small eight endpoints for game actions plus the WebSocket and the PNG export: | Method | Path | What it does | | ------ | ------------------------ | ---------------------------------------------- | | `POST` | `/rooms/{id}/join` | Get `player_id`, `token`, initial `room_state` | | `POST` | `/rooms/{id}/start` | Begin game (requires ≥2 players in lobby) | | `GET` | `/rooms/{id}/turn` | Long-poll for turn context the interesting one | | `POST` | `/rooms/{id}/strokes` | Submit stroke batch (drawer only, atomic) | | `POST` | `/rooms/{id}/guess` | Submit guess → `{correct, score_delta}` | | `POST` | `/rooms/{id}/give_up` | End turn early (drawer only) | | `GET` | `/rooms/{id}/state` | Full room snapshot, no secret word | | `GET` | `/rooms/{id}/canvas.png` | Raw PNG spectator only, agents never call this | The MCP server exposes eight tools that map directly onto these: `pictionary_join`, `pictionary_start`, `pictionary_wait_for_turn`, `pictionary_draw`, `pictionary_guess`, `pictionary_give_up`, `pictionary_get_canvas`, `pictionary_get_state`. The tool layer is deliberately thin it validates inputs and translates the response into a format Claude can consume, but all game logic stays server-side. One thing worth noting about `pictionary_wait_for_turn`: it returns a **list** of MCP content items. The first is a text item with the full JSON context (role, time left, round number, recent guesses everything except the canvas). If there's an active canvas, there's a second item: a proper `ImageContent` block with the base64 decoded into MCP's image format. Agents see a real image, not a raw base64 string embedded in text. That distinction matters for how multimodal models handle it. --- ## 3. How a Turn Works The turn lifecycle is a small state machine: ``` lobby → in_round → between_rounds → in_round → ... → ended → lobby ``` One player is the **drawer** and gets the secret word. Everyone else is a **guesser**. The drawer submits strokes; guessers poll for canvas updates and submit text guesses. First correct guess ends the turn. The canvas is 1000×600 pixels, white background, black strokes only. Agents never receive raw stroke data only **base64 PNG snapshots** delivered inline in JSON. This is deliberate. Whether an agent is GPT-4o or Claude Opus, it sees the same pixels. No model gets to cheat by parsing vector paths. Between rounds is server-driven. When a turn ends, an `asyncio` background task fires after 10 seconds and advances `drawer_index`, then starts the next turn. Agents don't need to poll for it they just call `pictionary_wait_for_turn` again and block until the server is ready. If the word list runs dry during `begin_turn()`, the server calls `end_game()` automatically. No awkward half-states. --- ## 4. Canvas Rendering Every call to `/turn` re-renders the canvas from scratch using **Pillow**. The stroke list is replayed in order: - A single-point stroke becomes a filled ellipse with `radius = width / 2`. - A multi-point stroke becomes a polyline with round joints, capped at both endpoints with circles. The result is encoded as base64 and embedded inline in the JSON response. Agents never get a URL to fetch the image arrives with the turn context or not at all. `GET /rooms/{id}/canvas.png` exists but it's for the spectator UI, not agents. Stroke batches are **atomic**. If any stroke in a batch fails validation, the entire batch is rejected. Out-of-bounds points are clamped to canvas edges rather than rejected (a point at `x=1050` becomes `x=999`) this is lenient by design, since an agent drawing near the edge shouldn't lose a whole batch over a few pixels. But a stroke with zero points or an illegal color fails hard, and takes the rest of the batch with it. **Canvas versioning** is a simple integer counter that increments on every accepted stroke batch. Guessers track this as `since_version` in their long-poll requests. --- ## 5. The Long-Poll Delivery Contract This was the hardest part to get right. The endpoint is `GET /rooms/{id}/turn?wait=true&since_version=N&max_wait_seconds=60`. On the surface it's a standard long-poll block until something changes, return, repeat. But "something changed" is where it gets nuanced. The server tracks per-player, per-turn delivery state in a `_last_delivery` dict keyed by `(player_id, turn_id)`. For each entry it records the last delivered canvas version, the last delivered guess count, and a monotonic timestamp. A guesser gets a new response when **either**: 1. The canvas version advanced **and** at least `CANVAS_DEBOUNCE_SECONDS = 2` seconds have elapsed since the last delivery, or 2. New guesses have arrived since the last delivery. The 2-second debounce is the important part. A drawer making rapid small strokes could otherwise flood guessers with a response per batch. With the debounce, the server accumulates strokes and delivers one snapshot every 2 seconds at most. Guessers see the canvas advance in meaningful steps rather than getting re-woken every 200ms. The drawer's flow is different. The **first** call to `/turn` after a round starts returns immediately with the secret word and canvas. Subsequent calls return `None` the drawer doesn't re-poll while drawing, it just submits strokes and the server delivers updates to guessers automatically. If `max_wait_seconds` elapses with no update, the server returns `TurnContextWaiting` and the client reissues immediately. No busy-loop; the retry is instant because the server already waited. --- ## 6. The Interesting Design Decisions **Guess matching.** Guesses go through normalization (lowercase, strip whitespace), then it's either an exact match or `rapidfuzz.ratio ≥ 0.9`: ```python def is_correct(guess: str, target: str, threshold: float = 0.9) -> bool: g, t = normalize(guess), normalize(target) if g == t: return True return fuzz.ratio(g, t) / 100 >= threshold def normalize(text: str) -> str: return re.sub(r"\s+", " ", text.strip().lower()) ``` `"elphant"` matches `"elephant"` (ratio ~0.93). `"i think it's an elephant"` never matches (~0.4 against `"elephant"`). Sentences deliberately don't score. This forces agents to output a single word rather than hedging with prose. An agent that doesn't read the protocol contract simply never scores. The threshold is tunable per room config if you want to experiment with looser or stricter matching. **Scoring.** Guesser score: `round(max(50, 200 * time_left / time_total))`. Drawer score: `round(100 * time_left / time_total)`. Everyone else: 0. On timeout or give-up: all 0. The floor at 50 for guessers is load-bearing. Without it, an agent might rationally stop guessing late in a turn because expected value approaches zero. The floor keeps guessing rational all the way to the buzzer. The drawer's formula has no floor their reward scales purely with how fast the guesser figured it out. With an 80-second turn, every second costs a guesser ~2.5 points (`200 / 80`). Time pressure is real. **Equal epistemic footing.** Agents get PNG, not vector strokes. The raw stroke data coordinates, widths, ordering lives on the server and is never sent to guessers. Every model sees the same rendered pixels. This prevents any future model from gaining an edge by parsing stroke geometry instead of actually reading the image, which would defeat the point of the experiment. **Turn delivery.** Guessers call `GET /rooms/{id}/turn` with a `since_version` cursor. The server holds the connection open until the canvas advances meaningfully or the turn ends. There's a 2-second gate so a drawer making lots of small strokes doesn't flood guessers with a response per stroke. --- ## 7. The Event Stream The WebSocket at `/rooms/{id}/events?since_seq=N` gives the spectator UI a live feed of everything that happens. Events are typed and sequenced: - `player_joined` someone connected - `turn_start` `{turn_id, drawer_id, time_limit_seconds, round}` - `strokes_added` `{canvas_version, strokes: [...]}` - `guess` `{player_id, text, correct}` - `turn_end` `{end_reason, winner_id, word, score_deltas, duration_seconds}` - `game_end` `{final_scores}` The `turn_end` event includes the **secret word**. That's the moment the spectator UI reveals it to the audience which is exactly the kind of thing that makes Pictionary feel like Pictionary, even for an AI game. The log is append-only and never pruned, so the UI can reconnect at any sequence number and replay from there. Useful for debugging too a full event replay is a complete record of the game. --- ## 8. What I Learned The game logic was the easy part. The hard part was the turn delivery contract figuring out what counts as "new enough" to wake a waiting guesser, how to avoid noise on stroke-heavy turns, what to return when a turn ends mid-wait. That `_last_delivery` dict and the 2-second debounce were the last things I added and the things that made the system actually playable. The code is at [github.com/capybara-brain346/agents-pictionary](https://github.com/capybara-brain346/agents-pictionary) --- ### [My Codebases Have an AI Receptionist Now](https://piyushc.com/blog/My-Codebases-Have-an-AI-Receptionist-Now) (2026-04-08) Summary: I built an agentic codebase navigator that lets engineers and recruiters ask anything about my projects, no RAG, no embeddings, just pure read-and-reason. ## 1. Introduction Every developer has been in this situation: a colleague asks "how does auth work in that service?" and you spend five minutes digging through your own codebase to remember. Now multiply that by every recruiter, collaborator, or future-you who wants to understand a repo they haven't touched in months. I built **askmycode** to solve this. It's a Streamlit chat app where you can ask natural-language questions about any of your GitHub repositories and get back a precise, source-cited answer , file paths, line numbers, actual code snippets, no hand-waving. ``` How is rate limiting implemented in @capynodes-backend? ``` ``` Rate limiting is enforced in capynodes-backend via the check_rate_limit function in middleware/rate_limit.py:L14-38. It uses a sliding-window counter stored in Redis... ``` --- What makes this interesting is _how_ it works under the hood. There's no search index, no vector database, no pre-processing step. The agent reads your code the same way you would on a fresh machine: it scans directory trees, greps for symbols, and opens files until it has enough to answer. This post walks through every design decision. --- ## 2. Indexing vs. Agentic Retrieval The conventional approach to "chat with your codebase" is **Retrieval-Augmented Generation (RAG)**: 1. Chunk every file into small pieces. 2. Embed each chunk with a model like `text-embedding-ada-002`. 3. Store embeddings in a vector database (Pinecone, Chroma, Weaviate, …). 4. At query time, embed the question, retrieve the nearest chunks, and pass them to an LLM. RAG is fast and scales to massive corpora. But for code, it has real problems: | Problem | Why it matters for code | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | **Index staleness** | Every `git push` potentially invalidates cached embeddings. You need a sync pipeline or your answers drift from reality. | | **Chunking is lossy** | A function split across a chunk boundary loses context. A class split from its imports becomes ambiguous. | | **Retrieval errors are silent** | If the relevant chunk ranked 6th instead of 1st, the LLM never sees it and may hallucinate a plausible-but-wrong answer. | | **Fixed granularity** | Embeddings can't decide "I need the whole file" vs. "I only need lines 20-35". | **Agentic retrieval** takes a different approach. Instead of pre-building an index, the agent _plans and acts_ at query time: ``` User query ↓ Agent decides: "I should search for the symbol first" ↓ search_code("check_rate_limit") → file: middleware/rate_limit.py, line 14 ↓ Agent decides: "I need to read that file" ↓ read_file_tool(repo, "middleware/rate_limit.py") → actual source code ↓ Agent decides: "I have enough to answer" ↓ Synthesize grounded answer ``` The key insight from the `AGENTIC_LOOP.md` design doc: > _`grep` never hallucinates a function signature._ Every tool call returns ground-truth data from the actual file system. The agent can't invent a result , it either finds the code or it doesn't. This makes answers verifiable and the failure mode honest ("I couldn't find evidence of X") rather than subtly wrong. The trade-off is latency. A RAG system retrieves in milliseconds; an agentic loop may take 3-10 tool calls. For code Q&A, where correctness matters more than speed, this trade-off is almost always worth making. --- ## 3. Tech Stack | Layer | Technology | Why | | --------------------- | -------------------------------- | ------------------------------------------------------------------ | | **LLM** | Gemma 4 via OpenRouter | Fast inference, strong tool-calling, excellent code reasoning | | **Agentic framework** | LangGraph | First-class state machine primitives, conditional edges, streaming | | **UI** | Streamlit | Zero-boilerplate chat UI with real-time status updates | | **Code search** | `grep -rn -E` (subprocess) | Fast, dependency-free, exact-match on live files | | **Repo management** | `git clone` (subprocess) | Snapshots repos locally; no remote API calls at query time | | **Config** | `config.json` | Simple `{name: owner/repo}` whitelist | | **Logging** | Python `logging` (rotating file) | Structured key=value pairs, 5 MB rotating log | | **Evals** | pytest + LLM-as-judge | Tool sequencing and grounding checks | The stack is deliberately minimal. No ORM, no message queue, no container orchestration , just Python, an OpenRouter API key, and git. The repo runs locally with `uv sync && uv run streamlit run src/app.py`. Repos are configured in `config.json` and auto-cloned on first startup: ```json { "repos": { "capybaradb": "capybara-brain346/capybaradb", "knowflow": "capybara-brain346/knowflow" } } ``` Any directory already present under `repos/` is also picked up automatically, so local-only repos work too. --- ## 4. LangGraph Flow The agent is modelled as a state machine with three nodes and two conditional edges. Here's the actual graph definition from `src/graph.py`: ```python from langgraph.graph import END, StateGraph graph = StateGraph(AgentState) graph.add_node("plan", plan_node) graph.add_node("tools_node", tools_node) graph.add_node("observe", observe_node) graph.set_entry_point("plan") # plan → tools_node (if LLM emitted a tool call) # plan → END (if LLM answered directly) graph.add_conditional_edges("plan", should_continue, {"tools_node": "tools_node", END: END}) graph.add_edge("tools_node", "observe") # observe → plan (if more evidence needed) # observe → END (if ready to synthesize, or MAX_HOPS reached) graph.add_conditional_edges("observe", route_from_observe, {"plan": "plan", END: END}) ``` Visually: ``` ┌─────────────────────────────────────────┐ │ │ query ──►│ plan_node ──► tools_node ──► observe_node │──► END (synthesize) │ ▲ │ │ │ └────────── loop ───────────┘ │ └─────────────────────────────────────────┘ ``` ### The State Object All data flows through a single `AgentState` TypedDict, appended to (never overwritten) by each node: ```python class AgentState(TypedDict): messages: Annotated[list[dict], operator.add] # full conversation + tool messages tool_results: Annotated[list[ToolResult], operator.add] # accumulated evidence files_read: list[list[str]] # (repo, path) pairs , deduplication guard query: str # original question, never mutated hop_count: int # iteration counter, checked against MAX_HOPS=10 answer: str | None # READY sentinel set by observe_node tagged_repos: list[str] # @-mentioned repos for scoping ``` ### Node Responsibilities **`plan_node`** , Calls the LLM with the full system prompt and accumulated message history. The LLM decides which tool to call next (or answers directly if it already has enough). The system prompt encodes the exploration strategy: - _Go targeted first_: `search_code` before `get_file_tree` before `read_file_tool`. - _Use regex alternation_: `jwt|token|OAuth|authenticate` to cover synonyms in one call. - _Don't re-read_: the `files_read` list is injected into context so the agent skips already-read files. **`tools_node`** , Executes the tool calls emitted by `plan_node`. Each tool is dispatched from the `TOOL_FUNCTIONS` registry. Results are appended to `tool_results` and returned as `role: tool` messages for the LLM's next turn. Errors (whitelist violations, file-not-found, grep timeouts) are caught and returned as error strings , the agent sees them and can adapt. **`observe_node`** , This is the decision node. It asks the LLM a focused question in JSON mode: _"Do you have enough to answer, or do you need more?"_ The response is a simple `{"decision": "loop" | "synthesize", "reasoning": "..."}`. If `hop_count >= MAX_HOPS`, it forces `synthesize` regardless of the LLM's preference. The routing function: ```python def route_from_observe(state: AgentState) -> Literal["plan", "__end__"]: if state.get("answer") is not None or state["hop_count"] >= MAX_HOPS: return END return "plan" ``` **Synthesis** , After the loop ends, `build_synthesize_messages` constructs a final prompt with all accumulated `tool_results` and the original query. The LLM writes a grounded answer, citing specific files and line numbers. This step happens outside the graph in `app.py` using a streaming call so the user sees tokens arrive in real time. --- ## 5. Tool Details All tools are plain Python functions that access cloned repos on the local filesystem. The tool layer enforces whitelist boundaries independently of the LLM , no amount of prompt manipulation can make a tool read outside the config-defined repos. ### Security: Double Validation Every tool validates both the repo name _and_ the resolved path: ```python def _validate_repo(repo: str) -> Path: whitelist = get_whitelist() if repo not in whitelist: raise WhitelistViolation(f"Repo '{repo}' is not in the whitelist.") return whitelist[repo].resolve() def _validate_path(repo_root: Path, path: str) -> Path: candidate = (repo_root / path.lstrip("/")).resolve() if not candidate.is_relative_to(repo_root): raise WhitelistViolation("Path resolves outside the repo root.") return candidate ``` The `is_relative_to` check defeats path traversal attacks (`../../etc/passwd`). The whitelist check means even a jailbroken LLM prompt can't read an unconfigured repo. ### Tool Reference | Tool | Signature | Purpose | | ------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `list_repos` | `() → list[str]` | Returns all whitelisted repo names. Called first when the agent needs to establish scope. | | `get_file_tree` | `(repo, path="/") → dict` | Lists immediate files and dirs at a path. Returns name + size for files. | | `read_file_tool` | `(repo, path) → str` | Returns raw file content. Truncates at 200 KB with a `[truncated at 200 KB]` notice. | | `search_code` | `(query, repos=[]) → list[dict]` | Runs `grep -rn -E` across one or more repos. Returns `{repo, file, line_number, snippet}` objects, capped at 50 results. | | `get_repo_metadata` | `(repo) → dict` | Returns file count, last-modified timestamp, top file extensions, and the first 500 chars of the README. Fast and cheap , no full file reads. | ### How the Agent Uses Them A typical query like _"How does auth work in capynodes-backend?"_ follows this pattern: 1. **`search_code`** with `jwt|token|OAuth|authenticate|login` → finds `middleware/auth_jwt.py:L14` 2. **`read_file_tool`** on that file → reads the actual implementation 3. **observe** decides: "I have the definition. Synthesize." A high-level overview query like _"What is capybaradb?"_ follows a different pattern: 1. **`get_repo_metadata`** → gets file count, README excerpt, primary language 2. **observe** decides: "README answers the question. Synthesize." The `search_code` tool is the workhorse. Because it takes a full extended regex, the agent can cover many synonyms in a single call, keeping the hop count low. --- ## 6. Evals and Safeguards ### E2E Eval Results (20-query golden set) | Metric | Result | Target | Status | | -------------------- | ------ | ------ | ------ | | Keyword accuracy | 85.0% | ≥ 80% | ✓ Pass | | Mean hop count | 1.3 | ≤ 5 | ✓ Pass | | Mean grounding score | 0.887 | ≥ 0.95 | ✗ Fail | | Whitelist violations | 0 | = 0 | ✓ Pass | | MAX_HOPS hit rate | 0.0% | ≤ 10% | ✓ Pass | Four of five metrics pass. The agent is efficient (average 1.3 hops per query , well inside budget), never hit the loop cap, and never attempted to read outside a whitelisted repo. Keyword accuracy at 85% clears the 80% floor, meaning the agent surfaces the right symbols and file references in the large majority of cases. The one miss is **grounding score at 0.887**, which falls short of the 0.95 target. A grounding score below threshold means the LLM-as-judge found claims in answers that weren't directly traceable back to tool results , the agent occasionally extrapolates slightly beyond what the retrieved evidence strictly supports. The likely causes are synthesis over truncated files (the 200 KB cap can cut off the tail of a large module) and the agent generalising from a single code path to a broader architectural claim. ### Enforcing Tool Calls at the Protocol Level A key design concern was preventing the model from answering out of prior weights instead of retrieved evidence. The system addresses this with two independent layers: **1. `PLAN_SYSTEM` prompt (`nodes.py`)** , a `## Mandatory rule` block at the top of the system prompt makes the expectation explicit in natural language: > _You have NO prior knowledge of these repositories. You MUST call at least one tool on every turn before synthesizing an answer._ **2. `plan_node` API constraint (`nodes.py`)** , `plan_node` calls `call_llm(messages, tools=TOOL_SCHEMAS, tool_choice="required")`. The OpenRouter API enforces a tool call on every plan hop at the protocol level, making it impossible for the model to short-circuit the retrieval loop regardless of its confidence. The `call_llm` helper in `utils.py` exposes `tool_choice` as a parameter (defaulting to `"auto"`) so all other callers are unaffected. The two-layer approach means the agent is reminded of the rule in natural language _and_ mechanically prevented from breaking it. --- Shipping an LLM-based system without evals is like shipping code without tests: you might be fine, but you won't know when you break something. askmycode has two eval suites under `tests/evals/`. ### T1: Tool Sequencing Evals These tests assert that the agent calls tools in a _sensible order_ , they don't care about the content of answers, only about the structural properties of the tool call sequence. Tools are patched with instant stubs that return canned data, so only the LLM's planning decisions are under test. This makes the tests fast and deterministic on the infrastructure side. | Test | Query | Assertion | | ----- | ------------------------------------- | -------------------------------------------------------------- | | T1-01 | "What repos are available?" | `list_repos` is called, ≤ 2 hops | | T1-02 | "What does the auth module do?" | `search_code` appears **before** `read_file_tool` | | T1-03 | "What is capybaradb about?" | First call is a cheap orientation tool (not a blind file read) | | T1-04 | "Where is rate limiting implemented?" | `search_code` is called | | T1-05 | "Compare vector storage across repos" | `list_repos` is the very first call | T1-02 is particularly important. A naive agent might blindly call `read_file_tool` on a guessed path. The correct strategy is to search first, then read what the search points to. The test enforces this: ```python if has_read: first_search = next(i for i, t in enumerate(seq) if t == "search_code") first_read = next(i for i, t in enumerate(seq) if t == "read_file_tool") assert first_search < first_read ``` ### G2: Grounding Evals These tests use an **LLM-as-judge** pattern. Given a `(tool_results, answer)` pair, a judge LLM scores the answer on grounding: is every claim in the answer traceable back to something in `tool_results`? | Test | Scenario | Expectation | | ----- | --------------------------------------------------- | ------------------------------ | | G2-01 | Answer correctly cites real file content | Grounding score ≥ 0.95 | | G2-02 | Empty tool results, answer invents a function | At least one violation flagged | | G2-03 | Answer references content beyond a truncation point | Violation flagged | | G2-04 | Answer attributes code to the wrong repo | Violation flagged | | G2-05 | Answer cites `:L999` when the actual line is `L5` | Violation flagged | G2-02 through G2-05 are **negative tests** , they construct adversarial inputs and assert the judge catches the problem. This gives confidence that the grounding evaluator itself is calibrated, not just rubber-stamping everything as correct. ### E2E: Golden Set The E2E suite runs the full agent against 20 golden queries across five categories (function lookup, dependency tracing, repo overview, implementation location, feature presence). Each golden case specifies expected keywords that must appear in the answer: ```json { "id": "E-08", "category": "dependency_tracing", "query": "Where is JWT authentication implemented in knowflow?", "repo_scope": "knowflow", "expected_keywords": ["jwt", "auth_service"] } ``` Results are logged to `logs/eval_results.csv` so you can track pass rate across runs. ### Hard Constraints Beyond evals, several hard limits are enforced in code: | Constraint | Value | Effect | | ---------------------- | --------------------- | ------------------------------------------------------- | | `MAX_HOPS` | 10 | Loop hard-stops; agent synthesizes with whatever it has | | `MAX_FILE_SIZE` | 200 KB | Large files truncated with a notice | | `CONTEXT_BUDGET_CHARS` | 320,000 (~80K tokens) | Oldest tool results dropped from context if exceeded | | `TIMEOUT_SECONDS` | 60 | Per-query wall-clock limit | | `GREP_MAX_RESULTS` | 50 | Search results capped to prevent context flooding | | Whitelist enforcement | Strict | Path traversal blocked at the filesystem level | --- ## 7. Conclusion The entire thing runs locally with one API key and no external databases. If you want to point it at your own repos, edit `config.json` and run: ```bash uv sync uv run streamlit run src/app.py ``` Askmycode is live on: **[askmycode](https://chat.piyushchoudhari.me/)** The source code is on GitHub: **[capybara-brain346/askmycode](https://github.com/capybara-brain346/askmycode)** --- ### [Implementing An SQS Like Message Queue System](https://piyushc.com/blog/Implementing-An-SQS-Like-Message-Queue-System) (2026-01-08) Summary: I built a rudimentary AWS SQS clone with Node.js and SQLite, including managed queues, visibility timeouts, and dead-letter queues. ## What Are Queues? A queue is a **data structure and system primitive** that follows first-in, first-out ordering, where producers enqueue work and consumers process it in sequence. In systems and architectures, queues are used to **decouple components, smooth traffic spikes, and enable asynchronous processing** so that slow or unavailable services do not block the entire system. ![queue illustration](/images/blog/sqs/queueing.png) They are central to **message-driven and event-based designs**, supporting reliability through buffering, retries, and durability, and scalability through parallel consumers and backpressure control. Common use cases include task scheduling, background job processing, inter-service communication, and stream ingestion in distributed systems. ## AWS SQS Amazon Simple Queue Service is a **fully managed message queuing service that enables reliable, scalable, and asynchronous communication between distributed system components**. It allows producers to send messages to a queue while consumers process them independently, helping decouple services, handle traffic bursts, and improve fault tolerance. SQS supports both **Standard queues for high throughput and FIFO queues for strict ordering and exactly-once processing**, making it a core building block in event-driven and microservices architectures on AWS. **Some SQS features:** - Long polling to reduce empty responses and lower cost - Batch operations for sending, receiving, and deleting up to 10 messages at a time - Message locking using visibility timeouts to prevent concurrent processing - Dead-letter queues to isolate and debug messages that repeatedly fail processing - Fair queueing to mitigate noisy-neighbor effects - Queue sharing across AWS accounts - Native integration with other AWS services to build reliable, loosely coupled systems ## The Core Architecture: Node.js and SQLite I chose **Node.js** for the API layer because of its non-blocking nature, which is perfect for handling many concurrent queue requests. For persistence, I went with **SQLite**. Why SQLite? Because it provides atomic transactions. When multiple consumers try to grab a message at the exact same moment, I need to ensure that only one of them actually "checks it out." ![system design](/images/blog/sqs/queue-design.png) ### The Lifecycle of a Message **I choose 3 states to keep a particular message in:** 1. **Waiting**: The message is in the queue, ready to be picked up. 2. **In-Flight**: A consumer has received the message. It's technically still in the database, but it's hidden from other consumers for a specific period (the **Visibility Timeout**). 3. **Deleted**: The consumer successfully finished its work and told the API to remove the message. ### The VisibilityTimeout Worker Imagine a consumer picks up a message but then its **server crashes**. That message is now **stuck "In-Flight" forever**. To solve this, I built a background worker that constantly polls the database. If it **finds a message that has been in-flight longer than its timeout**, it automatically **resets the status to `waiting`.** This worker also handles **retries**. If a message fails too many times, the worker doesn't just put it back; it moves it to a **Dead Letter Queue**. This prevents "poison messages" from looping forever and clogging up the system. ## Seeing it in Action: The Analytics Pipeline To show the system's workings, I built a real-time analytics demo. It’s a three-part process: 1. **The Producer (Python)**: A script that simulates product pricing and categories 2. **The Consumer (Python)**: A worker that pulls these events from the queue, calculates aggregates and saves them to a secondary database. 3. **The Dashboard (Streamlit)**: A live-updating frontend that visualizes the flow of data. What’s cool here is the **decoupling**. I can stop the consumer for maintenance, and the producer just keeps happily filling the queue. When the consumer comes back online, it picks up exactly where it left off. No data lost, no pressure. **Which is the exact advantage of a queue!** ### The Infrastructure: EC2 Deployments I deployed it across **two EC2 instances**: 1. **EC2 #1 (SQS Server)**: This instance hosts the Node.js API and the SQLite database. It acts as the central hub. 2. **EC2 #2 (Analytics Suite)**: This instance runs both the **Producer** (FastAPI) and the **Consumer** script. It communicates over the network with EC2 #1. This separation ensures that even if the Analytics instance goes down or needs to scale, the SQS server remains independent and continues to manage the queue state. ## Conclusion **Implementation: [Github](https://github.com/capybara-brain346/sqs-implementation)** Building this taught me the effort and decision making that goes into cloud services like AWS SQS. It’s not just about moving bits from A to B; it’s about making sure those bits survive the journey, no matter what happens in between. --- ### [A Portfolio Website Chatbot with PostgreSQL, Groq & AI SDK](https://piyushc.com/blog/How-I-Used-Postgres-Groq-And-AI-SDK-To-Create-My-Portfolio-Website-Chatbot) (2025-12-25) Summary: I built a chatbot that answers questions about my blogs, projects, and experience, using PostgreSQL, Groq, and Vercel's AI SDK. ## My Data & Reason For This Chatbot My portfolio website contains a decent amount of **text data**. It is my digital real estate where I can host my work afterall. **Components:** - Personal data: Social links, experience, tech skills - Blogs: 10 as of today, 2000 words on average - Project descriptions: 4 as of today I believed if I have so much amount of text data, it could be a great **feature to allow visitors to query it** and help in the process know more about my work. **For example:** - **User**: "Tell me about his recent projects" - **_Assistant_**: "Piyush has 4 recent projects: CapybaraDB, Knowflow, Post Automation Agent, TrackML" - **User**: "Elaborate on CapybaraDB" - **_Assistant_**: "CapybaraDB is a minimalistic vector database implementation designed for educational purposes and prototyping. The major concepts include: Simplicity Provides a minimal API (add_document, search, get_document) for easy integration No complex configuration required to get started Flexibility Supports multiple file formats and precision levels (float32, float16, binary) Offers in-memory or on-disk storage options Includes GPU acceleration capabilities Minimal Dependencies Relies only on essential libraries for core functionality Lightweight footprint ideal for learning and experimentation " - **User**: "What are all the precision types supported?" - **_Assistant_**: "CapybaraDB supports: float32, float16, binary precision" Above is a very simple example, at the end of the day **I want users to be able to query any and every minute detail mentioned on the website.** ## Tech Stack **Here's the tech stack I decided to go with:** 1. **Supabase (PostgresSQL)**: I chose this for my vector database, it is simple to setup, generous free tier and other features like RPC functions 2. **Vercel's AI SDK**: my website already uses typescript (Next.js), integrating AI SDK was a very natural process with great developer experience 3. **Groq & Qwen-32B**: I needed blazing fast inference speeds, hence decided to go with Groq. Plus a LLM which has enough parameters to provide mature reponses and maintain a decent context window but not take ages to respond like Gemini-3-Pro ## Workflow ![chatbot workflow](/images/blog/chatbot/workflow.png) I decided to keep the indexing phase and query phases completely seperate. There should be absolutely no writes to the DB at runtime in prod. **Phases:** 1. **Indexing Phase**: A Python script processes Markdown files from blog and project directories, chunks the content, and stores it in Supabase for vector/full-text search. 2. **Query Phase**: A Next.js API route uses Groq (with Qwen model) to handle user messages, augmented by a dynamic system prompt and a `searchKnowledgeBase` tool that queries Supabase for relevant content chunks. One major issue I thought a lot about was the context management for easy queries vs difficul queries where database querying is actually needed. **The Issue & The Fix:** - For simple queries like "What his name?", "What are his tech skills?", "What is the name of his recent employer?", **searching the database everytime was not work it.** - The fix was **putting simple information + meta data inside the system prompt** itself as the global context and performing database **queries on complex queries only.** To implement the routing for the complex queries, I decided to **use tooling through Vercel's AI SDK**. I provided a `searchKnowledgeBase` tool so the LLM can generate special keywords from user's input and query the database. Then after the context from the db is fetched, the LLM can provide informed responses. ## Database Design I used **Supabase** to store my search vectors. Below is the **schema design.** ```sql CREATE TABLE content_chunks ( id BIGSERIAL PRIMARY KEY, content_type TEXT NOT NULL, title TEXT NOT NULL, file_path TEXT NOT NULL, chunk_text TEXT NOT NULL, chunk_index INTEGER NOT NULL, url TEXT NOT NULL, metadata JSONB DEFAULT '{}', search_vector TSVECTOR GENERATED ALWAYS AS ( setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(chunk_text, '')), 'B') ) STORED, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX content_chunks_search_idx ON content_chunks USING gin(search_vector); CREATE INDEX content_chunks_type_idx ON content_chunks(content_type); CREATE INDEX content_chunks_metadata_idx ON content_chunks USING gin(metadata); ALTER TABLE content_chunks ENABLE ROW LEVEL SECURITY; CREATE POLICY "Public read access" ON content_chunks FOR SELECT USING (true); ``` It stores chunks as search vectors which can **queried by postgres built-in full text search.** ### How PostgreSQL's full text search works It is an **FTS engine**, an alternative to Elastic search. It aims to understand the nuances of linguistics to give relevance based ranking. **Components:** - **Document**: a unit of content you will be searching through - **Lexemes**: normalised word forms will represent the core meaning of the word. Includes, lowercasing, removing punctuation, removing stop words - **Stemming**: reducing words to their root form (running -> ran) **Data types:** 1. **tsvector (Text search vector)**: sorted list of lexemes extracted from a document and also stores positional information 2. **tsquery (Text search query)**: represents search terms and logical operators (&, |, !) Relevance is determined using the ts_rank() function, which calculates a score based on how often the search terms appear and how close they are to each other. You can further refine this by assigning weights to different parts of a document using setweight(). Weight 'A' is typically given to the most important fields, like a title. Weights 'B', 'C', and 'D' are used for less critical data like subtitles or body content. Matches in 'A' weighted fields will result in a higher relevance rank than matches in 'C' weighted fields **Some limitations:** - Lack of Inverse Document Frequency - Expensive scoring - Elasticsearch is better highly complex aggregations, faceted search and geospatial or image based search ## Conclusion **Try the [Chatbot](https://piyushchoudhari.me/chat)** Making a chatbot which has the ability to pull context from my website was a pretty fun implementation as **I see myself using this more often as I forget what I wrote or implemented 6 months down line, lol**. Will try to perform more robust and quantitative tests on the chatbot's responses in the future. --- ### [A Deterministic, Low-Latency Decision Engine in C++](https://piyushc.com/blog/Designing-a-Deterministic-Low-Latency-Decision-Engine-with-CPP) (2025-12-19) Summary: A deterministic decision tree engine in C++ that evaluates rules over gRPC with low latency, hot-reloadable trees, and production-ready observability. ## Decision Tree Engines: What are they? **Let's start with an example** Let's say you have a certain amount of income and a bank wants to assign a score to your account. It's pretty simple: ```python if income>50000: score=100 else: score=50 ``` We can just use a few control statments to assign the score. Now the bank wants to take into account how much loan you have taken into your score: ```python if income>50000: if loan<400_000: score=100 elif loan<1_000_000: score=80 else: score=50 else: score=50 ``` Now the number of control statements increased and pretty as the scoring mechanism gets complex, the instructions will too. Soon, it will be unmaintainable. Another way to implement these decision control flows are **Decision Trees**. Decision tree engines, when viewed purely in terms of rules and workflows, refer to systems that use a tree-like structure of decision rules to model decisions, classifications, or predictions. These are essentially rule-based engines where the knowledge is explicitly represented as a hierarchy of if-then-else conditions. When you run a decision tree engine on new data, the process is always the same: 1. Start at the root node. 2. Evaluate the condition (rule) at the current node. 3. Go left or right based on the answer. 4. Repeat until you reach a leaf. 5. Return the leaf’s value. ## Planning ### Goal I planned to implement a decision tree engine specifically for risk profiling/fraud detection flow. Goal was to create a high performance and scalable engine. **Input: JSON decision trees** **Output: Next node, actions and updated context** ### Things to keep in mind - **Stateless** per request - Deterministic: same input -> same output - Explainable: return the decision path - gRPC API and embeddable C++ library ### Architecture At a high level, a caller sends: - tree_version: which tree to use - current_node: where in the tree evaluation starts - user_input: optional raw input (used for choice nodes) - context: flat key-value map of facts about the transaction, user, device, etc. ### The Engine: 1. Looks up the JSON tree definition for tree_version. 2. Finds the node with id current_node. 3. Evaluates that node according to its type. 4. Returns: - next_node - actions to run (for action nodes) - updated_context - confidence and the decision_path. ## The Implementation: Specifically The Fraud Detection Use Case ### Decision Trees - **Tree definition**: - JSON file - Versioned via `"version"` (e.g. `"fraud_detection_v1"`) - Contains an array of `"nodes"`; each node has an `"id"` and `"type"`. - **Loading**: - Trees are loaded either from disk (`TREE_DIRECTORY`) or via the `LoadTree` gRPC API. - Validation happens on load: - No cycles - All referenced nodes exist - Conditions are syntactically valid - Defaults or terminal ends are present ### Node Types ![decision tree illustration](/images/blog/decision-tree/node-types.png) - **Message Node** - **Purpose**: Display static or templated text. - **Behavior**: Always transitions to `next`. - **Choice Node** - **Purpose**: Branch based on explicit user selection. - **Behavior**: Matches `user_input` against declared `choices`; if none match, uses `default`. - **Condition Node** - **Purpose**: Branch based on evaluating conditions over `context`. - **Behavior**: - Evaluates `conditions` top-to-bottom. - First condition whose `"if"` expression evaluates to true wins. - If none match, uses `default`. - **Action Node** - **Purpose**: Emit a list of actions for the caller to execute (e.g. `BLOCK_CARD`). - **Behavior**: Returns `actions` plus `next`; caller performs side effects. - **Terminal Node** - **Purpose**: End of flow. - **Behavior**: No further traversal; returns a final resolution (e.g. `FRAUD_CONFIRMED`). ### Single-Step Evaluation ![decision tree illustration](/images/blog/decision-tree/evaluation.png) The engine is **step-based**: each `Evaluate` call processes exactly one node. - **Input**: - `tree_version` - `current_node` - `user_input` (optional) - `context` - **Output**: - `next_node` - `actions` - `updated_context` - `confidence` - `decision_path` (includes the evaluated node) The caller is responsible for: - Determining whether to call `Evaluate` again with `current_node = next_node`. - Persisting or propagating `updated_context`. - Executing any actions. ### Traversal Semantics - **Exactly one** node is evaluated per step. - **Exactly one** `next_node` is chosen (or a terminal node ends the flow). - No parallel or branching executions; the flow is linear when viewed step by step. - Maximum traversal depth is enforced to prevent infinite loops. ### gRPC Service - **Service**: `decision_engine.DecisionEngineService` - **Key RPCs**: - **LoadTree**: Load a JSON tree into memory. - **Evaluate**: Evaluate a single step of a tree. - **HealthCheck**: Simple liveness check. The protobuf request for `Evaluate` includes: - `tree_version` - `current_node` - `user_input` - `context` (map of `ContextValue`) The response contains: - `next_node` - `actions` - `updated_context` - `confidence` - `decision_path` ### Embedded Library The same engine can be used directly from C++ by linking against the core library: - Load trees from JSON strings. - Call `Engine::evaluate` with a request struct. - Inspect the `DecisionResult` (next node, actions, context, decision path). This is useful for embedding the engine in other C++ services or for local testing without gRPC. ### Build, Run, and Test - **From repo root**: ```bash cd engine mkdir build && cd build cmake .. make -j"$(nproc)" ``` - **C++ tests**: ```bash cd engine ./build_test.sh ``` Tests cover: - Tree loading and validation - Condition evaluation - Choice matching - Action emission - Tree reloading - **gRPC server** ```bash cd engine mkdir -p build && cd build cmake .. make -j"$(nproc)" export GRPC_SERVER_ADDRESS=0.0.0.0:50051 export TREE_DIRECTORY=../trees ./decision_engine_server ``` You can then call the server using: - `grpcurl` (for ad-hoc tests) - Python client (`test_grpc_client.py`) - Other services via gRPC stubs. ### Fraud Detection Tree (`fraud_detection_v1`): **[The Tree](https://github.com/capybara-brain346/risk-profile-engine/blob/main/engine/trees/fraud_detection_v1.json)** **The Use Case:** - **Tree version**: `fraud_detection_v1` - **Goal**: Model a realistic, enterprise-grade fraud detection and account security workflow. - **Characteristics**: - 70+ nodes - Multiple risk levels and branching paths - Rich set of actions for fraud operations and user security - Terminal Outcomes: - `TRANSACTION_APPROVED` - `TRANSACTION_DENIED` - `FRAUD_CONFIRMED` - `FRAUD_PREVENTED` - `USER_CANCELLED` - `VERIFICATION_FAILED` - `CARD_REPLACED` - `INVESTIGATION_PENDING` - `MONITORING_ENABLED` - `ESCALATED_TO_FRAUD_TEAM` - `CONNECTED_TO_AGENT` - `ACCOUNT_RESTORED` - `PENDING_ACCOUNT_CLOSURE` - `VERIFICATION_PENDING` Each terminal node encodes a clear outcome that a downstream system can act on. ### Fraud Detection Flow: End-to-End Scenarios **1. Scenario: Critical Risk, Large Transaction** - **Context example**: ```json { "transaction_amount": 15000, "velocity_score": 0.9, "risk_score": 0.95 } ``` - **Typical behavior**: - Initial condition node classifies the transaction as **critical risk**. - Engine routes to a branch that: - Immediately blocks the transaction. - Freezes the account. - Creates a fraud case. - Flow terminates with a high-severity resolution, such as `FRAUD_CONFIRMED` or `FRAUD_PREVENTED`. **2. Scenario: Device Mismatch and Location Anomaly** - **Context example**: ```json { "device_fingerprint_mismatch": true, "location_anomaly": true, "risk_score": 0.75 } ``` - **Typical behavior**: - Conditions detect mismatched device and unexpected location. - Engine routes to a branch requiring **strong verification**: - Transaction may be temporarily blocked. - 2FA or OTP is required. - Depending on verification outcome, the tree continues toward approval or a fraud terminal outcome. **3. Scenario: Moderate Risk, Needs Verification** - **Context example**: ```json { "risk_score": 0.5, "behavior_consistent": false } ``` - **Typical behavior**: - Conditions classify the transaction as moderate or elevated risk. - Engine routes to a **user verification path**: - Confirmation prompts or security questions. - Possible temporary monitoring mode. - Terminal resolutions may include `MONITORING_ENABLED` or `VERIFICATION_PENDING`. **4 Scenario: Suspicious Merchant** - **Context example**: ```json { "unusual_merchant_category": true, "merchant_fraud_reports": 10 } ``` - **Typical behavior**: - Merchant-related conditions trigger a risky merchant path. - Engine may: - Block the transaction. - Flag or block the merchant. - Trigger refund flows. - Terminal outcome may be `TRANSACTION_DENIED` or `FRAUD_PREVENTED`, with actions like merchant blocking and refund initiation. **5. Scenario: Card Testing Pattern** - **Context example**: ```json { "multiple_declined_attempts": 5, "velocity_score": 0.8 } ``` - **Typical behavior**: - Tree detects repeated small attempts and high velocity. - Engine routes to a **card testing** branch that: - Blocks or replaces the card. - Alerts the fraud team. - Terminal outcome might be `CARD_REPLACED` or `ESCALATED_TO_FRAUD_TEAM`. ### Running and Testing the Fraud Detection Flow **1. Loading the Fraud Tree via gRPC** With the server running: ```bash cd /home/capybara/code/sde/risk-profile-engine/engine grpcurl -plaintext -import-path src -proto src/decision_engine.proto \ -d '{"tree_version": "fraud_detection_v1", "json_content": "'"$(cat trees/fraud_detection_v1.json | tr -d '\n' | sed 's/\"/\\\"/g')"'"}' \ localhost:50051 decision_engine.DecisionEngineService/LoadTree ``` This loads the full fraud detection tree into the engine under `tree_version = "fraud_detection_v1"`. **2. Evaluating Fraud Scenarios** - **Critical risk path example**: ```bash grpcurl -plaintext -import-path src -proto src/decision_engine.proto \ -d '{ "tree_version": "fraud_detection_v1", "current_node": "start", "context": { "transaction_amount": {"int_value": 15000}, "velocity_score": {"double_value": 0.9}, "risk_score": {"double_value": 0.95} } }' \ localhost:50051 decision_engine.DecisionEngineService/Evaluate ``` Inspect the response to see: - `next_node` (for example, a high-severity fraud path node) - `actions` (block, freeze, create case) - `decision_path` (which fraud rules fired) You can run similar requests for the other scenarios (location anomaly, moderate risk, suspicious merchant, card testing) by adjusting the `context` payload. ## Results ### Integration testing results on a complex fraud detection tree: - Total Nodes: 70+ - Node Types: 5 (message, choice, condition, action, terminal) - Action Types: 35+ different actions - Terminal States: 14 - Max Branching Factor: 4 choices - Average Path Length: 5-8 nodes ```plaintext ========================================== Fraud Detection Workflow - Complex Tree Test ========================================== Loading fraud_detection_v1 tree... { "success": true } ========================================== Scenario Tests ========================================== 1. LOW RISK - Normal Transaction Context: risk_score=0.2 --- { "nextNode": "initial_risk_assessment", "confidence": 1, "decisionPath": [ "start" ] } 2. MODERATE RISK - Needs Behavior Check Context: risk_score=0.55 --- { "nextNode": "initial_risk_assessment", "confidence": 1, "decisionPath": [ "start" ] } 3. ELEVATED RISK - Manual Review Required Context: risk_score=0.75 --- { "nextNode": "initial_risk_assessment", "confidence": 1, "decisionPath": [ "start" ] } 4. HIGH RISK - Device & Location Anomaly Context: device_fingerprint_mismatch=true, location_anomaly=true --- { "nextNode": "initial_risk_assessment", "confidence": 1, "decisionPath": [ "start" ] } 5. CRITICAL RISK - Large Transaction with High Velocity Context: transaction_amount=15000, velocity_score=0.9 --- { "nextNode": "initial_risk_assessment", "confidence": 1, "decisionPath": [ "start" ] } 6. CARD TESTING PATTERN DETECTED Context: multiple_declined_attempts=5 --- { "nextNode": "card_testing_suspected", "confidence": 1, "decisionPath": [ "analyze_transaction_pattern" ] } 7. SUSPICIOUS MERCHANT Context: unusual_merchant_category=true --- { "nextNode": "investigate_merchant", "confidence": 1, "decisionPath": [ "analyze_transaction_pattern" ] } 8. TIME-BASED ANOMALY Context: transaction_time_anomaly=true --- { "nextNode": "time_based_verification", "confidence": 1, "decisionPath": [ "analyze_transaction_pattern" ] } 9. NEW ACCOUNT + CRITICAL RISK Context: transaction_amount=20000, velocity_score=0.95, account_age_days=15 --- { "nextNode": "new_account_protocol", "confidence": 1, "decisionPath": [ "check_account_history" ] } 10. REPEAT OFFENDER Context: previous_fraud_cases=2 --- { "nextNode": "repeat_offender_protocol", "confidence": 1, "decisionPath": [ "check_account_history" ] } ========================================== ✓ All fraud detection scenarios tested! ========================================== ``` ## Conclusion **Implementation: [Github](https://github.com/capybara-brain346/risk-profile-engine.git)** Overall it was a pretty fun implementation, aside from all the build errors lol. It is interesting how complex tree and flows are managed to deliver near instant analysis on data points. --- ### [Simulating vLLM's PagedAttention](https://piyushc.com/blog/Simulating-vLLMs-PagedAttention) (2025-12-08) Summary: I simulated vLLM's PagedAttention in Python to see how paged KV-cache allocation reduces memory fragmentation in LLM inference. ## Why? Anthropic recently released an article, [Code execution with MCP: Building more efficient agents](https://www.anthropic.com/engineering/code-execution-with-mcp) and it focused heavily on **token conservation** and how agents can use **sandboxed environments** to execute code to fetch results. Idea of token/context management stuck with me and then I went down the rabbit hole of token management and optimization where I started studying **vLLM inference runtimes**. vLLM employs a ton of methods to optimize inference but I found PagedAttention very interesting, so **I decided to simulate it.** ## The Problems Nowadays LLM serving is one the most crucial components of applications. But still it faces a lot of challenges related to cost, performance and resource management. **Common challenges:** - **High computational load** - **GPU utilization** - **Latency issues** - **Inefficient memory management:** 1. Internal fragmentation 2. Reservation waste 3. External fragmentation - **Complexity of distributed inference** vLLM inference runtime aims to resolve these challenges and one of the core components it uses is PagedAttention ## PagedAttention In LLMs, the **KV cache** plays a important role during inference. As tokens are generated one by one, because **LLMs are autoregressive**, the model stores the key and value tensors from previous steps instead of recomputing them. This makes future **token prediction faster because the model can reuse past computations**. Early implementations followed a memory allocation strategy borrowed from traditional deep learning workloads. Each inference request **received a large, contiguous block of GPU memory reserved for its KV cache**. The problem was that sequence lengths during inference are unpredictable. Some inputs end quickly, others expand due to long responses or continued user interaction. Since **the system could not know the exact length ahead of time, it had to reserve more memory than necessary**. **This led to several inefficiencies;** - Most of the allocated memory remained unused, contributing to internal fragmentation. - Gaps appeared between allocated memory regions, creating external fragmentation. - Memory was often blocked for potential future tokens but never consumed. Despite reserving large chunks of GPU memory, real usage often hovered between 20 and 40 percent. As a result, throughput suffered because the model could serve fewer simultaneous requests before exhausting memory. The hardware was capable of more, but the memory layout became the bottleneck. PagedAttention redesigns KV cache storage using a paging mechanism inspired by operating systems. Instead of one large allocation, the cache is broken into smaller fixed-size chunks called KV blocks. Key ideas introduced by PagedAttention: - **Non-contiguous storage** ```markdown Logical sequence: [Block 1][Block 2][Block 3][Block 4] Physical GPU layout: [Block 1] [Block 3] [Block 4] [Block 2] ^ mapping handled by page table ^ ``` - **On-demand allocation** ```markdown Initial: [Block 1] As sequence grows: [Block 1][Block 2][Block 3] ... allocated only when needed ``` - **Near-zero waste** Only the final incomplete block may have unused memory. - **Page-table-style lookup** ```markdown +-------------+-------------------------+ | Token Range | Physical Block Address | +-------------+-------------------------+ | 0 - 255 | Block_12 | | 256 - 511 | Block_7 | | 512 - 767 | Block_19 | +-------------+-------------------------+ ``` - **Copy-on-write sharing for generation branches** During beam search or sampling, multiple candidates often share early history: ```markdown Before divergence: Beam A → [B1][B2][B3] Beam B → [B1][B2][B3] (shared memory) After divergence: Beam A → [B1][B2][B3][B4] Beam B → [B1][B2][B3][B4’] (copy only when needed) ``` - **Higher throughput and scaling** Since memory is used efficiently, more requests fit into GPU memory, increasing batch size and token throughput. ## Implementation ### Data Structures #### KVCacheBlock - Represents a physical block in KV cache - Properties: - block_id: Unique identifier for the block - reference_count: Number of requests sharing this block - block_hash: SHA256 hash of block tokens for deduplication ```python class KVCacheBlock(BaseModel): block_id: int reference_count: int = 0 block_hash: Optional[str] = None ``` #### Request - Represents a user request with tokens and allocated blocks - Properties: - tokens: List of token IDs - block_size: Size of each block - block_table: List of physical block IDs allocated to this request ```python class Request(BaseModel): tokens: List[int] block_size: int block_table: List[int] = [] ``` ### PagedAttention Class #### Initialization - total_blocks: Maximum number of blocks available - block_size: Number of tokens per block - Maintains free blocks queue, physical block mappings, and hash table ```python def __init__(self, total_blocks, block_size): self.total_blocks = total_blocks self.free_blocks = deque(range(total_blocks)) self.physical_blocks = {} self.hash_to_block = {} self.cache_hits = 0 self.cache_misses = 0 ``` #### Block Hashing (hash_block_tokens) - Creates SHA256 hash for token sequences - Incorporates parent hash for sequential block identification - Enables block-level deduplication ```python def hash_block_tokens(self, tokens, parent_hash): hasher = hashlib.sha256() if parent_hash: hasher.update(parent_hash.encode()) for token in tokens: hasher.update(str(token).encode()) return hasher.hexdigest()[:16] ``` #### Block Allocation (allocate_block) - Allocates free blocks from the pool - Returns block_id if available, None if out of memory ```python def allocate_block(self): if not self.free_block: return None block_id = self.free_blocks.popleft() return block_id ``` #### Block Deallocation (free_block) - Removes block from physical memory - Cleans up hash mappings - Returns block to free pool ```python def free_block(self, block_id: int): if block_id in self.physical_blocks: block = self.physical_blocks[block_id] if block.block_hash and block.block_hash in self.hash_to_block: del self.hash_to_block[block.block_hash] del self.physical_blocks[block_id] self.free_blocks.append(block_id) ``` #### Token Allocation (allocate) - Divides tokens into blocks (block_size tokens per block) - Implements cache hit logic: reuses existing blocks if hash matches - Implements cache miss logic: allocates new blocks for unique token sequences - Increments reference count for shared blocks ```python def allocate(self, tokens): num_tokens = len(tokens) num_blocks = (num_tokens + self.block_size - 1) // self.block_size request = Request(tokens=tokens, block_size=self.block_size) parent_hash = None for block_idx in range(num_blocks): block_tokens = tokens[start_idx:end_idx] block_hash = self.hash_block_tokens(block_tokens, parent_hash) if block_hash in self.hash_to_block: # Cache hit cached_block = self.hash_to_block[block_hash] cached_block.reference_count += 1 request.block_table.append(cached_block.block_id) self.cache_hits += 1 else: # Cache miss new_block_id = self.allocate_block() new_block = KVCacheBlock(block_id=new_block_id, reference_count=1, block_hash=block_hash) self.physical_blocks[new_block_id] = new_block self.hash_to_block[block_hash] = new_block request.block_table.append(new_block_id) self.cache_misses += 1 parent_hash = block_hash return request ``` #### Token Generation (generate_token) - Appends new token to request - Allocates new block when current block reaches capacity (token overflow) - Implements Copy-on-Write (CoW): creates new block if shared block has reference_count > 1 - Writes in-place to exclusive blocks ```python def generate_token(self, request, new_token): request.tokens.append(new_token) last_block = self.physical_blocks[request.block_table[-1]] if len(request.tokens) % self.block_size == 1 and len(request.tokens) > 1: # Token overflow: allocate new block new_block_id = self.allocate_block() new_block = KVCacheBlock(block_id=new_block_id, reference_count=1) self.physical_blocks[new_block_id] = new_block request.block_table.append(new_block_id) elif last_block.reference_count > 1: # Copy-on-Write: create new block for exclusive modification new_block_id = self.allocate_block() last_block.reference_count -= 1 new_block = KVCacheBlock(block_id=new_block_id, reference_count=1) self.physical_blocks[new_block_id] = new_block request.block_table[-1] = new_block_id ``` #### Request Cleanup (free_request) - Decrements reference count for all blocks in request - Deallocates blocks when reference count reaches 0 ```python def free_request(self, request): for physical_id in request.block_table: if physical_id in self.physical_blocks: block = self.physical_blocks[physical_id] block.reference_count -= 1 if block.reference_count == 0: self.free_block(physical_id) ``` #### Statistics (print_stats) - Cache hit rate calculation - Free and allocated block counts ```python def print_stats(self): total = self.cache_hits + self.cache_misses hit_rate = (self.cache_hits / total * 100) if total > 0 else 0 print(f"Hits: {self.cache_hits}") print(f"Misses: {self.cache_misses}") print(f"Hit Rate: {hit_rate:.1f}%") print(f"Free Blocks: {len(self.free_blocks)}/{self.total_blocks}") print(f"Allocated Blocks: {len(self.physical_blocks)}") ``` --- ## Conclusion #### Implementation: [GitHub](https://github.com/capybara-brain346/PagedAttention-Simulation) Overall it was a fun project to implement and dive deep into PagedAttention. --- ### [Making a Blog Peer Review System with Google ADK & Mem0](https://piyushc.com/blog/Making-A-Peer-Review-System-for-My-Blogs-Using-Google-ADK-And-Mem0) (2025-11-26) Summary: I built a peer review system for my blogs with Google ADK and Mem0. It fact-checks claims against my sources and remembers recurring issues. ## My Process When writing my technical blogs, I have a **very rigid process** I like to follow. 1. Research the topic I am interested in 2. Create a **structured research roadmap** I require to gain knowledge about the particular topic 3. Go through the roadmap and try to **learn/research the concepts** as in-depth as I can 4. **Start coding** whatever the relevant implementation for that topic is 5. Finally, **start writing the blog** But one thing always bugs me, **_"Is my blog factually correct and have I compromised the integrity of my blog anywhere?"_.** That leads me to frantically go through my sources repeatedly and ask tools like Perplexity about the blog. So, I had the idea to **automate this process by creating a peer review system.** --- ## What This System Does ![flowchart](/images/blog/review/flowchart.png) **1. What the System Focuses On** - It behaves like a technical editor, not just a grammar checker. - It evaluates writing for: - Structure - Clarity - Factual accuracy - Tone correctness - Proper use of supporting evidence - The purpose is to help the writer produce content that is accurate, readable, and consistent. **2. How It Reviews Content** - The system doesn’t read content blindly. - It uses uploaded reference files as a knowledge base. - Relevant information from those files is retrieved using semantic search rather than keyword matching. - If a statement appears in the writing: - The system first checks whether it exists in the uploaded sources. - If confirmed, the system becomes more confident in that claim. - If not found, it triggers an external web-based fact check. **3. How Memory Improves Review Quality** - Feedback adapts over time instead of resetting with each review. - The system tracks repeated mistakes or patterns such as: - Missing citations - Style inconsistencies - Formatting issues - If the same issue shows up again, the system highlights it more firmly. - This turns the review into a learning process rather than a one-time correction. --- #### Screenshots: - https://drive.google.com/file/d/1VTvQBkQ4753NbpVFlVPr5v6_kjH3SXjZ/view?usp=sharing - https://drive.google.com/file/d/14sfHrC0Lw0pvU4oX7U18Ydv61a8RNTu0/view?usp=sharing #### A Demo Peer Review Report: - https://drive.google.com/file/d/1HQh5stEAj4tkh3E7Fyf1jOse52ZDw-bb/view?usp=sharing --- ## Workflow ![sequence](/images/blog/review/sequence.png) **Phase 1: Ingestion** - Fetches content from URLs if needed - Loads past review history for the project - Examines uploaded source documents **Phase 2: Verification** - Identifies all factual claims in the content - Searches uploaded sources for supporting evidence - Uses Google search for external fact-checking - Validates technical assertions and statistics **Phase 3: Evaluation** - Assesses clarity, flow, and structure - Checks accuracy against evidence - Evaluates tone for target audience - Compares to past feedback to track improvement - Flags recurring issues with escalated severity **Phase 4: Synthesis** - Generates structured report - Provides evidence for all major issues - References past feedback when relevant - Gives actionable, constructive feedback --- ## Features **1. Model Flexibility** - You aren’t locked into one AI provider. - Switching between models like Gemini, Claude, GPT, or Ollama only requires changing one environment variable. - This gives control over: - Cost - Performance - Privacy - The review logic remains consistent across models. **2. Context-Aware Retrieval** - Uploaded reference files are stored in a vector database. - The system breaks them into chunks, embeds them, and indexes them for efficient search. - During review, it retrieves relevant sections using semantic similarity rather than simple keyword matching. - This helps the system understand meaning, not just match exact text. **3. Automated Fact Verification** - When a claim isn’t supported by uploaded sources, the system escalates verification. - A separate search agent performs a structured web lookup. - The goal is not to rewrite content, but to confirm whether the information is reliable and accurate. **4. Built-In Memory** - The system remembers past reviews and writing patterns. - If a mistake repeats, the system identifies it as a recurring issue. - Instead of pointing it out repeatedly at the same level, the feedback becomes stronger and more specific. - This encourages long-term improvement rather than one-off corrections. --- ## Limitations 1. The verification is only as good as the model plus the search results 2. Source reliability isn’t enforced 3. Web search can surface low-quality or outdated material 4. The model is still the final judge. It can misinterpret sources, over-trust weak evidence, or fabricate justification #### Implementation: [GitHub](https://github.com/capybara-brain346/peer-review-agent) --- ### [Training a Mixture-of-Experts Router](https://piyushc.com/blog/Training-a-Mixture-of-Experts-Router) (2025-11-17) Summary: I built a GPT-style transformer with optional Mixture-of-Experts layers and a trained router, then compared dense and MoE runs. ## Introduction Since Deepseek-MoE introduced the MoE architecture, I was aware of it and saw it's adoption across the open source and proprietary model providers. But I never tried to understand the idea deeper. The idea that you can expand a model’s capacity without sending every token through a huge feed-forward block felt very interesting. I tried to write the whole thing myself, from data loading and tokenization to a GPT-style transformer with optional MoE layers. This included the dataset pipeline, transformer blocks, routing logic, expert modules, and a training loop that tracked timing, throughput, losses, and expert usage. This blog walks through what I learned, how each component fits together, and the results that stood out, with the hope that these insights help anyone curious about MoE models or planning to build one. --- ## Project Plan Before writing any code, I outlined the system I wanted. I needed a modular setup that let me swap dense layers for MoE layers, try different routing strategies, and run controlled comparisons without constant rewrites. That meant keeping data, model, MoE components, and training logic cleanly separated. ![project-plan](/images/blog/moe/project-plan.png) I began with the dataset pipeline. A steady source of tokenized text is essential for any language model experiment, and I wanted the option to fall back to synthetic data. After that, I focused on the model architecture. I planned to build a small GPT-style transformer first, since it provided a stable baseline and a familiar structure to extend with MoE layers. The goal was to keep the dense path intact while making the MoE path a drop-in replacement so both versions could be compared under identical conditions. Next came the MoE module, which required the most iteration. I wanted per-token routing, top k selection, load balancing, and expert statistics without creating a messy forward pass. I mapped out how the router, experts, and auxiliary loss would interact and built an interface that let transformer blocks treat dense and MoE layers the same. The final piece was the training loop. I needed detailed metrics: throughput, timing, auxiliary losses, temperature schedules, and expert usage. The Trainer class would handle epochs, collect metrics, and coordinate evaluation so experiments remained consistent. With the components defined, the plan was straightforward: build the dataset module, implement the transformer, add the MoE layer, wire everything in the Trainer, and run dense and MoE configurations under a shared framework. --- ## Implementation ![implementation](/images/blog/moe/implementation.png) Once the plan was set, the next step was turning each idea into a working module. I wanted the codebase to feel like a compact training stack with clear boundaries. That shaped how the transformer, MoE layer, and Trainer were built. The transformer came first, following a standard GPT-style decoder with token embeddings, positional embeddings, a stack of self-attention blocks, and a final projection. The key feature was a pluggable feed-forward sublayer. If a layer index matched an MoE position, the dense FFN was swapped for an MoE layer through a shared interface. This made it easy to alternate between dense and sparse configurations without altering the architecture. The MoE layer required the most careful engineering. Routing occurs per token, so the implementation flattens batch and sequence dimensions, applies a linear router, then uses a temperature scaled softmax to produce expert probabilities. Tokens pick top experts, pass through identical feed-forward experts, and are recombined with routing weights. The layer also tracks usage, probabilities, and entropy, which was crucial for spotting imbalance and specialization patterns. With the model ready, the Trainer handled timing, throughput, auxiliary losses, and temperature schedules. It recorded detailed metrics, measured forward and backward phases separately, and supported early stopping. Together, these components formed a focused environment for comparing dense and MoE models and revealing their trade-offs. --- ## Dataset For these experiments I needed a dataset that was structured enough to reveal real modeling behavior yet small enough for fast iteration. WikiText-2 fit well. It contains high-quality English text from Wikipedia, offering natural sentence structures, topic shifts, and long-range dependencies that make model behavior easy to inspect. I kept the raw text but used a custom tokenization pipeline instead of the original large vocabulary. I mapped everything into a fixed vocabulary of 10000 tokens. This kept the embedding matrix small and made the model lighter, while also shifting the dataset’s statistics. A smaller vocabulary increases sequence length due to more subword splits and raises the frequency of common tokens. That steeper distribution created clearer patterns early in training and made capacity differences between dense and MoE variants easier to observe. The dataset is stored in Parquet format and loaded with Polars. After tokenization, it produces about 2.1 million training tokens and about 217000 validation tokens. These totals stay similar after remapping, although some lines become longer and the token distribution grows more concentrated. A streaming dataset slices training sequences with sliding windows, keeping memory use low and avoiding preprocessing. I also added a synthetic fallback for development. Overall, WikiText-2 with a 10000-token vocabulary offered a realistic and efficient environment for comparing dense and MoE models. --- ## MoE vs Dense: Experiment Results and Recommendations ### TL;DR ![summary](/images/blog/moe/summary.png) - The dense model achieved the best validation loss and the highest training throughput. It remains the strongest performer for this setup when evaluating generalization versus raw speed. - Mixture-of-experts (MoE) variants increased model capacity (roughly 17.3M parameters vs 9.9M for the dense model) but introduced substantial runtime overhead, primarily in the backward pass. That overhead reduced tokens/sec compared with the dense baseline. - Among MoE variants, `throughput_opt` substantially reduced backward cost compared with the other MoEs and delivered the best throughput among MoEs, but it did not match the dense model in tokens/sec or in best validation loss. - `top2` reached the lowest training loss but the worst validation loss, suggesting overfitting or instability in gating/generalization. - Routing entropy and per-expert usage indicate reasonably balanced expert assignment across experiments, but layer- and experiment-level differences remain and may explain some of the generalization differences. ### Key numbers (single-epoch timing, parameters, best validation loss, avg throughput) | Model | Params | Best validation loss | Avg throughput (tokens/sec) | Forward (s) | Backward (s) | Optimizer (s) | Total per-epoch (s) | | ------------------ | ---------: | -------------------: | --------------------------: | ----------: | -----------: | ------------: | ------------------: | | Dense | 9,924,608 | **9.3698** | **68,825** | 0.40 | 0.20 | 0.03 | 0.63 | | MoE-baseline | 17,286,656 | 9.3809 | 44,976 | 0.75 | 1.17 | 0.05 | 1.97 | | MoE-top2 | 17,286,656 | 9.3921 | 37,387 | 0.90 | 1.47 | 0.05 | 2.42 | | MoE-strong_reg | 17,286,656 | 9.3798 | 44,243 | 0.76 | 1.19 | 0.05 | 2.00 | | MoE-throughput_opt | 17,286,656 | 9.3870 | 54,784 | 0.56 | 0.96 | 0.03 | 1.55 | ### Training and validation dynamics ![training loss](/images/blog/moe/training_loss.png) ![validation loss](/images/blog/moe/validation_loss.png) - **Training loss**: All variants show steadily decreasing training loss. `MoE-top2` reaches the lowest training loss across epochs, indicating higher capacity or faster training fit. - **Validation loss**: Dense achieves the lowest validation loss (9.3698). MoE variants either match or exceed (worse) the dense validation loss: - `MoE-baseline` and `MoE-strong_reg` are close to each other and only marginally worse than dense. - `MoE-top2` exhibits the largest gap and a clear upward trend in validation loss after epoch 4, indicating overfitting or gating instability. - `MoE-throughput_opt` shows stable validation behavior but does not surpass dense. - **Interpretation**: The MoE configurations give higher representational capacity but require careful gating/regularization and optimization to realize generalization benefits. Without such tuning, larger capacity can overfit or destabilize validation performance. ### Throughput and timing breakdown ![throughput](/images/blog/moe/throughput.png) ![timing breakdown](/images/blog/moe/timing_breakdown.png) - The dominant cost for MoE models is the backward pass. Backward times: - `MoE-top2`: 1.47 s - `MoE-baseline`: 1.17 s - `MoE-strong_reg`: 1.19 s - `MoE-throughput_opt`: 0.96 s - Dense: 0.20 s - `throughput_opt` reduced the backward cost significantly compared with other MoEs, producing the best MoE throughput (54,784 tokens/sec), but still below dense. - Total per-epoch wall-clock is smallest for dense (0.63s) and largest for `top2` (2.42s). - Interpretation: MoE overheads are chiefly in expert-specific gradient/communication during backward. Optimizations that reduce communication or reduce expert work in backward propagate directly to throughput gains (as `throughput_opt` demonstrates). ### Expert routing behavior: usage and entropy ![expert usage](/images/blog/moe/expert_usage.png) ![expert entropy](/images/blog/moe/expert_entropy.png) - **Entropy**: Routing entropy per layer is close to the theoretical maximum (max ≈ 2.08 for 8 experts). That indicates routing is using many experts rather than collapsing to a single expert. Specific observations: - `top2` layer 2 entropy reaches very close to max early, which matches its aggressive expert usage behavior. - Layer 4 entropies are slightly lower and more variable across experiments. - **Per-expert usage**: Usage bars across models and layers show modest deviations from perfect uniformity (uniform = 12.5% for 8 experts). Most experiments show usage within roughly 10.6% to 14.7% per expert. A few spots show underused experts (for example `throughput_opt` layer 4 had some experts near 9.8–9.9%). - Interpretation: Routing is generally balanced, but small non-uniformities exist and could cause local specialization or slight load imbalance. Very skewed usage might lead to undertrained experts and affect generalization. ### Trade-offs and interpretation 1. **Dense vs MoE capacity**: MoE increases parameter count substantially but this did not translate into better validation loss in these runs. Denser capacity alone is not sufficient to improve generalization. 2. **Throughput trade-offs**: Dense model is faster and achieves better validation performance. For these experiments, MoE costs (especially backward step) made them slower despite higher capacity. `throughput_opt` shows that MoE overhead can be reduced but not fully eliminated. 3. **MoE-top2 anomaly**: The `top2` variant fits training data best but generalizes worst. This suggests gating choices (top-2 routing) can increase overfitting risk or cause training instability unless balanced with stronger regularization or gating temperature tuning. 4. **Balancing and entropy**: Entropy values close to the max indicate gating is not collapsing, which is good for utilization. However, small routing imbalances can still impact performance. Regularization techniques to encourage balanced loads may help. --- ## Conclusion Implementation: [GitHub](https://github.com/capybara-brain346/moe-router) Working through this project gave me a clearer sense of how MoE models behave in practice. I expected the extra capacity from experts to translate quickly into better validation performance, but the results were more nuanced. The dense baseline stayed the most stable and consistent in both speed and generalization, which reinforced the idea that complexity only helps when training dynamics are tuned to support it. These experiments showed that the dense model remained the strongest, delivering the best validation loss and highest throughput. The MoE variants increased parameter capacity but added meaningful training overhead. The optimized router reduced some of that cost but still lagged behind the dense baseline. The top 2 router trained quickly yet overfit, revealing how sensitive routing is to regularization and tuning. Overall, MoE effectiveness depends on stabilizing routing, maintaining load balance, and improving backward efficiency. Until these factors are refined, the extra capacity offered by experts does not reliably translate into stronger performance. --- ### [Building a Vector Database from Scratch - CapybaraDB](https://piyushc.com/blog/Building-A-Vector-Database-from-Scratch-CapybaraDB) (2025-11-04) Summary: I built CapybaraDB, a lightweight vector database in Python, to learn how embeddings, chunking, and semantic search work internally. ## Introduction Vector databases are one of the most popular and widely used systems in the tech industry. Their market was valued at ≈2.5 billion in 2024 and is projected to >3 billion in 2025. Over 70% of all organizations investing/implementing AI use vector databases for searching and embedding. I have used vector databases in multiple use cases and projects. Be it RAG, searching and filtering documents or even feeding context to agents. After using multiple databases like FAISS, ChromaDB, Pinecone and pgvector, I was fascinated by vector databases and their internal workings. Hence, I decided to implement one myself. Project: [CapybaraDB](https://github.com/capybara-brain346/capybaradb). CapybaraDB, it is a lightweight vector database implementation, built from scratch in Python: - It can perform semantic search using sentence-transformers for embeddings. - It supports built-in token-based chunking. - CUDA acceleration. - Precision control (float32, float16, binary). - .npz file storage for persistance. ## What is a Vector Database? A vector database is a very special type of database which is very efficient in storing and searching dimensional vector embeddings. Embeddings are basically numerical representations of data like text, images, videos, audio, etc. In terms of structure, these embeddings are made up of array of floating point numbers representing the direction and magnitude of the generated vector. A traditional database searches for exact match for the query entered, but vector databases find items by measuring the distance/difference between the query vector and embedded vectors inside the multidimensional space. Metrics like, euclidean distance or cosine similiarity can be used to measure distances between the vectors. They're essential for modern AI applications including semantic search (finding meaning, not just keywords), recommendation systems, RAG (Retrieval Augmented Generation) for chatbots, image similarity search, and anomaly detection. Popular examples include Pinecone, Weaviate, Milvus, Qdrant, and Chroma. They've become crucial infrastructure as AI applications need to search through millions of embeddings in milliseconds while maintaining accuracy. ![vector db illustration](/images/blog/capybaradb/vector-db-illustration.png) ## Design Philosophy 1. Simplicity - A "toy" vector db implementation, aiming for minimal complexity - Straightforward APIs (`add_document`, `search`, `get_document`) - Minimal config to get started 2. Flexibilty - Utility support for multiple file formats - Configurable precision levels (float32, float16 and binary) - Choice to keep in-memory store or on disk - GPU support 3. Minimal dependencies - Core dependencies limited to essential libs - Lightweight footprint for prototyping and learning 4. Educational focus - Demonstrating fundamental vector database concepts ## Metrics & Benchmarks ### Indexing Performance Data source: [benchmark_results/indexing_performance.json](https://github.com/capybara-brain346/capybaradb/blob/main/benchmark_results/indexing_performance.json) ![indexing performane](/images/blog/capybaradb/indexing-performance.png) - Document counts tested: 10, 50, 100, 500, 1000 - Total times (s): 0.138, 1.015, 2.388, 23.126, 76.331 - Average time per doc (s): 0.0138, 0.0203, 0.0239, 0.0463, 0.0763 - Storage times remain small relative to embedding time even at 1k docs (≈0.122 s) - Index size (MB): 0.020, 0.089, 0.174, 0.859, 1.715 - Peak memory (MB): ~2.2–65.4 across scales Key takeaways: - Embedding dominates total indexing time. Storage overhead is negligible in comparison. - Linear growth with dataset size; average time per document rises as batches get larger and memory pressure appears. - Index size scales linearly and remains compact for thousands of chunks. Refer to `benchmark_results/indexing_performance.png` for the trend lines and `indexing_performance_breakdown.png` for stacked time components. --- ### Query Performance Data source: [benchmark_results/query_performance.json](https://github.com/capybara-brain346/capybaradb/blob/main/benchmark_results/query_performance.json) ![query performance](/images/blog/capybaradb/query-performance.png) - Dataset sizes tested: 100, 500, 1000, 2500, 5000 - Average query latency (ms): 7.79, 7.54, 9.10, 8.52, 8.45 - Throughput (qps): 128.3, 132.6, 109.9, 117.4, 118.3 - p50 latency (ms): 7.45–8.79 - p95 latency (ms): 10.09–12.01 - p99 latency (ms): 11.80–16.39 - Breakdown (avg): - Embedding time (ms): ~3.87–4.53 - Retrieval time (ms): ~3.50–4.57 Observations: - Latency remains stable and low (≈7–9 ms on average) from 100 to 5000 vectors for top-k search, reflecting efficient vectorized exact search. - Throughput remains >100 qps at all tested sizes. - The split between query embedding and retrieval remains balanced; both contribute roughly half of total latency. - Note: one anomalous value appears in `min_latency_ms` at 500 (-524.27 ms). This is a measurement artifact and should be ignored; distributional statistics (p50/p95/p99) are consistent and reliable. Charts: `benchmark_results/query_performance.png` and `query_performance_breakdown.png` visualize latency distributions and the embedding vs retrieval split. --- ### Retrieval Quality (Synthetic) Data source: [benchmark_results/retrieval_quality_synthetic.json](https://github.com/capybara-brain346/capybaradb/blob/main/benchmark_results/retrieval_quality_synthetic.json) ![retrieval benchmark](/images/blog/capybaradb/retrieval-benchmark.png) Configuration: - Dataset: Synthetic - Chunk size: 512 Quality metrics: - Precision@k: P@1=1.00, P@3≈0.756, P@5≈0.480, P@10≈0.240 - Recall@k: R@1≈0.433, R@3≈0.956, R@5=1.00, R@10=1.00 - F1@k: F1@1=0.60, F1@3≈0.836, F1@5≈0.643, F1@10≈0.385 - nDCG@k: nDCG@1=1.00, nDCG@3≈0.954, nDCG@5≈0.979, nDCG@10≈0.979 Interpretation: - Very strong early precision (P@1=1.0) and nDCG across cutoffs indicate effective ranking of the most relevant content. - Near-perfect recall by k=5 shows top-5 captures essentially all relevant items. See `benchmark_results/retrieval_quality_synthetic.png` for the quality curves. **Disclaimer** ⚠️: The documents in the dataset used here are relatively short (typically well under 512 tokens). As a result, a chunk size of 512 effectively corresponds to _document-level embeddings_ — each document was indexed as a single vector. While this setup is sufficient for small-scale or toy benchmarks, it may not generalize to longer documents where sub-document (passage-level) chunking becomes necessary for finer-grained retrieval. Future evaluations will include experiments with smaller chunk sizes (e.g., 128–256) and longer document corpora to assess chunk-level retrieval effects. --- ### What These Results Mean from a Perspective of A "Toy Database" - Small to medium collections (≤10k chunks): exact search is fast, simple, and accurate. - Low latency: median ≈7–9 ms per query with >100 qps throughput in benchmarks. - Strong quality: excellent early precision and recall on the synthetic task with coherent chunking. - Scales linearly: indexing and index size grow linearly; storage overhead is minimal compared to embedding time. ## Core Architecture ### 1. BaseIndex The main in-memory (temp) data store of CapybaraDB is the `BaseIndex` class, a data structure that holds: ```python class BaseIndex: documents: Dict[str, str] # doc_id -> full document text chunks: Dict[str, Dict[str, str]] # chunk_id -> {text, doc_id} vectors: Optional[torch.Tensor] # All chunk embeddings chunk_ids: List[str] # Order-preserving chunk IDs total_chunks: int total_documents: int embedding_dim: Optional[int] ``` This design keeps documents and their chunks separate while maintaining relationships through IDs. Why this separation? It allows us to: - Return full documents when retrieving search results - Track which chunk belongs to which document - Maintain metadata without duplicating data ### 2. Index The `Index` class extends `BaseIndex` with persistence: ```python class Index(BaseIndex): def __init__(self, storage_path: Optional[Path] = None): super().__init__() self.storage = Storage(storage_path) ``` This is where of auto-loading happens. When you create an `Index`, it checks if a persisted version exists and loads it automatically. This is of-course optional, if no path is provided, the db is kept in-memory. ### 3. CapybaraDB: The Main Interface The `CapybaraDB` class which exposes the API: ```python class CapybaraDB: def __init__( self, collection: Optional[str] = None, chunking: bool = False, chunk_size: int = 512, precision: Literal["binary", "float16", "float32"] = "float32", device: Literal["cpu", "cuda"] = "cpu", ): ``` You can create multiple collections, control chunking, adjust precision, and choose your compute device. ## Embeddings ### 1. Architecture CapybaraDB uses `sentence-transformers/all-MiniLM-L6-v2`, a lightweight transformer model that converts text into 384-dimensional vectors. ```python class EmbeddingModel: def __init__( self, precision: Literal["binary", "float16", "float32"] = "float32", device: Literal["cpu", "cuda"] = "cpu", ): self.model_name = "sentence-transformers/all-MiniLM-L6-v2" self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.model = AutoModel.from_pretrained(self.model_name).to(device) ``` The model is initialized once and reused for all embeddings, keeping operations fast and memory-efficient. ### 2. The Embedding Process When you call `embed()` on a document, here's what happens: ```python def embed(self, documents: Union[str, List[str]]) -> torch.Tensor: encoded_documents = self.tokenizer( documents, padding=True, truncation=True, return_tensors="pt" ) with torch.no_grad(): model_output = self.model(**encoded_documents) sentence_embeddings = self._mean_pooling( model_output, encoded_documents["attention_mask"] ) sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1) ``` 1. Tokenization: Using `tiktoken` package and cl100kbase token encoding the chunks are tokenized 2. Generation: Production of context-aware representations for each position 3. Normalization: L2 norm to convert all vectors to unit length for accurate retrieval ### 3. Precision Modes CapybaraDB supports three precision modes: **Float32 (default)**: Full precision, highest accuracy **Float16**: Half precision, ~50% memory savings, minimal accuracy loss **Binary**: Each dimension becomes 0 or 1, resulting in memory savings. The embedding process converts values > 0 to 1.0: ```python if self.precision == "binary": sentence_embeddings = (sentence_embeddings > 0).float() ``` Binary embeddings use a scaled dot product during search to compensate for information loss. ## Document Processing Pipeline ### Adding a Document When you add a document, here's the full journey: ```python def add_document(self, text: str, doc_id: Optional[str] = None) -> str: if doc_id is None: doc_id = str(uuid.uuid4()) self.index.documents[doc_id] = text self.index.total_documents += 1 ``` **Step 1: ID Generation** If no ID is provided, we generate a UUID. This ensures every document is uniquely identifiable. **Step 2: Chunking (Optional)** If chunking is enabled, the document is split using token-based chunking: ```python if self.chunking: enc = tiktoken.get_encoding("cl100k_base") token_ids = enc.encode(text) chunks = [] for i in range(0, len(token_ids), self.chunk_size): tok_chunk = token_ids[i : i + self.chunk_size] chunk_text = enc.decode(tok_chunk) chunks.append(chunk_text) ``` Why token-based chunking instead of character-based? - Respects word boundaries - Considers tokenizer structure - Produces more semantically coherent chunks - Works better with the embedding model **Step 3: Create Chunks** Each chunk gets its own UUID and is stored with metadata: ```python for chunk in chunks: chunk_id = str(uuid.uuid4()) self.index.chunks[chunk_id] = {"text": chunk, "doc_id": doc_id} chunk_ids.append(chunk_id) self.index.total_chunks += 1 ``` **Step 4: Generate Embeddings** All chunks are embedded in one batch: ```python chunk_texts = [self.index.chunks[cid]["text"] for cid in chunk_ids] chunk_embeddings = self.model.embed(chunk_texts) ``` Batch processing is key to performance. Embedding 100 chunks together is much faster than 100 individual embeddings. **Step 5: Append to Vector Store** This is where the vectors are added to the index: ```python if self.index.vectors is None: self.index.vectors = chunk_embeddings self.index.chunk_ids = chunk_ids self.index.embedding_dim = chunk_embeddings.size(1) else: self.index.vectors = torch.cat( [self.index.vectors, chunk_embeddings], dim=0 ) self.index.chunk_ids.extend(chunk_ids) ``` The first document creates the tensor. Subsequent documents are concatenated along the batch dimension. **Step 6: Persistence** If not in-memory mode, the index is saved immediately: ```python if not self.index.storage.in_memory: self.index.save() ``` This means you can add documents and they're persisted incrementally—no manual save needed! ## The Search Engine ### The Search Process Here's how search works end-to-end: ```python def search(self, query: str, top_k: int = 5): if self.index.vectors is None: return [] self.index.ensure_vectors_on_device(target_device) indices, scores = self.model.search(query, self.index.vectors, top_k) results = [] for idx, score in zip(indices.tolist(), scores.tolist()): chunk_id = self.index.chunk_ids[idx] chunk_info = self.index.chunks[chunk_id] doc_id = chunk_info["doc_id"] results.append({ "doc_id": doc_id, "chunk_id": chunk_id, "text": chunk_info["text"], "score": score, "document": self.index.documents[doc_id], }) return results ``` **Step 1: Query Embedding** The query text is embedded using the same model: ```python def search(self, query: str, embeddings: torch.Tensor, top_k: int): query_embedding = self.embed(query) ``` **Step 2: Similarity Computation** The similarity between query and all stored vectors is computed: ```python if self.precision == "binary": similarities = torch.matmul( embeddings.float(), query_embedding.t().float() ) / query_embedding.size(1) else: similarities = torch.matmul(embeddings, query_embedding.t()) ``` For each query, the system computes similarity with all stored vectors. In **binary precision**, it performs a dot product between 0/1 vectors, scaled by the embedding dimension—yielding the fraction of matching active bits. In **float precision**, normalized embeddings use standard cosine similarity via matrix multiplication with the query embedding. **Step 3: Top-K Selection** We use `torch.topk` to find the most similar vectors: ```python scores, indices = torch.topk( similarities.squeeze(), min(top_k, embeddings.size(0)) ) ``` **Step 4: Result Assembly** For each result, we reconstruct the full context by: 1. Looking up the chunk text 2. Finding the parent document ID 3. Retrieving the full document This gives you both the specific chunk that matched and the full document context. ## Storage and Persistence ### The Storage Layer The `Storage` class handles persistence with NumPy's compressed NPZ format: ```python def save(self, index) -> None: data = { "vectors": index.vectors.cpu().numpy(), "chunk_ids": np.array(index.chunk_ids), "chunk_texts": np.array([index.chunks[cid]["text"] for cid in index.chunk_ids]), "chunk_doc_ids": np.array([index.chunks[cid]["doc_id"] for cid in index.chunk_ids]), "doc_ids": np.array(list(index.documents.keys())), "doc_texts": np.array(list(index.documents.values())), "total_chunks": index.total_chunks, "total_documents": index.total_documents, "embedding_dim": index.embedding_dim or 0, } np.savez_compressed(self.file_path, **data) ``` Why NPZ? - Compressed by default (saves space) - Efficient binary format - Handles large arrays well - Cross-platform and language-agnostic ### In-Memory vs Persistent CapybaraDB supports two modes: **In-Memory**: No file path specified. Data stays in RAM, lost on exit. **Persistent**: File path specified. Data is saved to disk after each `add_document()` call. This dual-mode design enables both temporary experiments (in-memory) and production use (persistent). ## Putting It All Together ### Example: Simple Document Search ```python from capybaradb.main import CapybaraDB # Initialize db = CapybaraDB( collection="research_papers", chunking=True, chunk_size=512, device="cuda" ) # Add documents doc1_id = db.add_document("Machine learning is transforming NLP...") doc2_id = db.add_document("Deep neural networks excel at image recognition...") # Search results = db.search("artificial intelligence", top_k=2) # Use results for result in results: print(f"Score: {result['score']:.4f}") print(f"Matched text: {result['text'][:100]}...") print(f"Full document: {result['document']}") print("---") ``` ## Conclusion Implementation: [GitHub](https://github.com/capybara-brain346/capybaradb.git) This implementation of CapybaraDB was purely for education purposes and my own learning. I had a great time figuring out the nitty-gritty details behind vector databases and will definitely take on more challenging implementations in the future. --- ### [Be Curious About Your Compute](https://piyushc.com/blog/Be-Curious-About-Your-Compute) (2025-09-24) Summary: A hardware blocker slowed my inference, so I dug into how CPUs, GPUs and TPUs differ and why VRAM matters when serving AI models. ## Hardware Often Takes The Backseat I've been a software guy throughout my journey and **rarely I've tried to lift the curtain up and focus on the hardware**. Those rare times probably happened during my IOT study sessions at my engineering course. Most of the blockers I've ever faced during my AI engineering journey, have been related to software. Broken drivers, unpatched source code, outdated libraries and of course classic python quirks. But one day I faced a blocker, obviously not knowing that it was hardware related. At my internship, I was trying to **draw inference from an Automatic1111 server on AWS**, the server was equipped with two specific diffusion models, one was SDXL (very heavy) another was an SD1.5 (lighter). However **drawing inference from one model caused the next inference from the second model to be very slow**. My first reaction was that it was because of caching. But after debugging this issue, I learned that this was **expected behavior by Automatic1111 module**. It loaded a model into VRAM and "kept it hot" for fast inference then loaded the second model, hence resulting in slow inference. ![my story](/images/blog/compute/my-story.png) That day I learnt that understanding and knowing the relation between the software and hardware interactions goes a long way. **"Not thinking about the hardware"** is something I observe a lot from peers and engineers. So, I had the idea to write this blog. --- ## Types Of Available Hardware ### CPU vs GPU vs TPU | Aspect | CPU | GPU | TPU | | ------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------- | | **Role** | General-purpose processor, brain of the computer | Originally for graphics, now massively parallel compute | Custom ASIC by Google for tensor operations & deep learning | | **Cores** | Few powerful cores (2–64, more in servers) | Thousands of lightweight cores (A100 ~7,000+) | Systolic arrays with Matrix Multiply Units (MXUs) | | **Execution Model** | Low-latency, sequential, strong branch handling | SIMT/SIMD, warp scheduling, high throughput | Data flows across systolic array; highly specialized instructions | | **Memory** | Large cache hierarchy, moderate bandwidth | High-bandwidth VRAM (HBM/GDDR), smaller caches, bulk data optimized | HBM tightly coupled with compute; optimized for DL precision formats | | **Strengths** | Versatile, single-thread performance, task switching | Matrix/vector math, AI/ML training, rendering, high throughput | Extremely efficient at AI training/inference, high perf-per-watt | | **Weaknesses** | Limited parallelism, not efficient for massive matrix ops | Poor at branch-heavy sequential code, higher latency, needs CUDA/OpenCL | Not general-purpose, tied to Google ecosystem, less flexible | AI or any computationally expensive workload, **requires extremely high throughput** as the calculations are extremely straight forward (matmul, gradient averages, dot products, etc...) unlike the calculations the CPU does which includes complex branching logic and minimal latency. Hence GPUs and TPUs are extremely popular choices. ![cpu vs gpu vs tpu](/images/blog/compute/cpu-gpu-tpu.png) GPUs, in particular, have extremely high bandwidths but unlike TPUs, **they interface well using CUDA lib and Pytorch or TensorFlow also include high interoperability with them**. --- ## Bottlenecks ![bottleneck](/images/blog/compute/bottlenecks.png) It is normal to focus on metrics like TFLOPs. But a systems performance and turnaround time is often limited by how quickly data moves and can be accessed, not just how fast can it be processed. 1. **Memory capacity (VRAM) and bandwidth are frequently more important than raw compute power**. A processor is inefficient if it sits idle waiting for data. VRAM capacity is a key constraint, as it determines whether a large model, such as an LLM, can fit onto a single GPU. For instance, a high-TFLOP consumer GPU like an RTX 4090 with 24 GB of VRAM cannot train models that require the 80 GB or more offered by datacenter GPUs. VRAM size also limits the training batch size, affecting efficiency. 2. When scaling to multiple GPUs for larger models, **the interconnect, the communication pathway between GPUs could become the main bottleneck**. Standard interconnects like PCIe have limited bandwidth (around 64 GB/s), which can get saturated when GPUs synchronize data, leading to diminishing returns when scaling beyond a few GPUs. In contrast, proprietary technologies like NVIDIA’s NVLink provide vastly superior bandwidth (up to 900 GB/s), resulting in efficient scaling for training massive foundation models. 3. The entire system can be constrained by **slow data I/O from storage**. If data cannot be loaded from disks to the GPUs quickly enough, even the most powerful hardware will be wasted, creating a foundational bottleneck. --- ## Accelerators Modern AI accelerators are designed around **specific philosophies** and each type of accelerator handle different types of workloads. - **NVIDIA H100** focuses on cutting-edge training with its **Transformer Engine** and **FP8 support**, demanding extreme bandwidth and power efficiency for massive LLMs. - **Google TPU v5p** uses a **systolic array (MXU)** for extreme efficiency in large-scale, matrix-heavy workloads, tightly coupled with Google’s distributed infrastructure. - **AMD MI300** competes by integrating **CPU and GPU components** into one package, offering a **large unified memory pool** — attractive for diverse HPC and AI workloads where flexibility and capacity matter. These differences reflect the **architectural trade-offs** between general-purpose flexibility (GPU) and specialized efficiency (TPU), with AMD carving a hybrid path. ### Accelerator Comparison | Accelerator | Memory | Bandwidth | Key Use Case | | ------------------ | -------------------- | ---------- | ----------------------------------------------------------------------------- | | **NVIDIA H100** | 80 GB HBM3 | ~3.0 TB/s | Cutting-edge LLM training, HPC workloads with extreme throughput needs | | **AMD MI300X** | 192 GB HBM3 | ~5.3 TB/s | Large-scale AI training, HPC, and very large models (fits datasets in memory) | | **Google TPU v5p** | 95 GB HBM2e per chip | ~2.77 TB/s | Large-scale AI training/inference; matrix-heavy workloads in Google ecosystem | --- ## Practical Tips To optimize AI workloads we need to focus on data movement too not just compute speed. - **Profile your system:** The first step is to identify where the bottlenecks are. Is it memory capacity (VRAM), memory bandwidth, interconnect speed between GPUs, or slow data loading from storage? - **Use mixed precision (AMP):** Modern GPUs have specialized Tensor Cores that accelerate FP16/BF16 computations. Using Automatic Mixed Precision (AMP) in frameworks like Pytorch significantly speeds up training by using lower precision for matrix maths while maintaining accuracy with FP32 for sensitive operations like loss calculation. This also reduces VRAM usage. - **Tune batch size and data loaders:** VRAM capacity limits your batch size. A larger batch can improve hardware utilization, but a small one may be forced by memory constraints. Ensure your data loading pipeline from storage to GPU is not the bottleneck, as even the fastest GPU is wasted if it's waiting for data. - **Leverage optimized frameworks:** For multi-GPU training, use libraries like PyTorch's `DistributedDataParallel` with NCCL backends, or advanced frameworks like DeepSpeed, to efficiently manage gradient synchronization, which is often a key bottleneck. These tools are crucial for scaling effectively. --- ## Conclusion You don't need to be a GPU engineer or a chip designer to understand the nuances of hardware and the interaction between hardware and software. Only requirements are to keep the hardware in mind while designing systems and to **_Be Curious About Your Compute_** --- ### [How I Automated My Social Media Workflow with LangGraph](https://piyushc.com/blog/How-I-Automated-My-Social-Media-Workflow-with-LangGraph) (2025-09-14) Summary: Posting on social media is repetitive: draft, edit, get feedback, post. Here is how I automated LinkedIn and X posts with a LangGraph workflow. ## Why an automation? I recently started blogging, more specifically technical blogging. I enjoy going through papers, articles and GitHub repos which spark my interest. This led me to the idea of posting about them. But I realized that technical blogging can be **more than just a medium to share my interests, it can be a powerful way to build up my personal brand.** Speaking of creating a personal brand, a lot goes into it, but in my simple view it **only requires two things:** - High value and high impact content - A great distribution strategy **Social media is the "great distribution strategy".** But writing content optimized for social media, more specifically LinkedIn and X was **not an area I wanted to spend a lot of time on**, and also, **being an engineer, I was attracted to automating it away.** --- ## How it works? ### _Central Idea_ At the heart of this project is a **LangGraph workflow** that automates my content pipeline, which means, right from the idea stage to the draft and publish stage of my social media posts (not my blogs), the workflow takes care of the entire generation. - _What kind of posts I want?_ - _What type of post I need depending on day of the week?_ - _Is the content of the post legitimate and factual?_ - _Does the post make any claims with no basis?_ - _Does the post state any statements without proper citations?_ ### _Why LangGraph?_ After using multiple tools for creating agents like **LCEL, CrewAI and DSPy**, I felt LangGraph was extremely easy to follow in terms of the workflow, as it **maps very well to flowcharts and UML diagrams** we encounter on a daily basis. Also, I am familiar with LangGraph since **I used it extensively at my internship** to build agentic systems. ### _Flowchart_ ### _Here’s a breakdown of the process:_ 1. **Capture & Research** - The workflow starts by capturing a raw idea (`capture_idea`). - It then pulls in notes and references from Obsidian (`obsidian_research`), ensuring the idea is grounded in prior research. 2. **Planning & Teaser Generation** - The `planner_agent` structures the idea into a roadmap. - Depending on the phase, the system may generate an early **teaser post** (`teaser_generator`) to share on Monday as a preview. 3. **Drafting the Blog** - If we’re in the drafting phase, the `blog_drafter` creates a long-form draft. - Once the final blog URL is available, the system scrapes the published content (`scraper`) and builds a concise summary (`summarizer`). 4. **Social Media Post Creation** - Using the blog summary, the workflow generates tailored LinkedIn posts (`final_post_generator`) and X/Twitter posts (`x_generator`). 5. **Validation & Review** - Posts are validated for structure, tone, and platform-fit (`validator`). - If issues are found, they are sent for peer review (`peer_reviewer`) and, if necessary, refined by the `content_improver`. - The workflow limits improvements to 3 iterations to avoid endless loops. 6. **Self-Evaluation & Recovery** - Before finalizing, posts undergo a self-check (`self_evaluator`). - If errors occur (e.g., missing blog URL, broken logic), a `recovery_agent` steps in to fix or gracefully exit. 7. **Completion** - Once validated, the system outputs **ready-to-publish posts** for LinkedIn and X. - If human oversight is required (e.g., controversial phrasing or ambiguous context), the workflow pauses and flags it for manual review. **The workflow code snippet:** ```python def create_workflow(): workflow = StateGraph(AutomationState) workflow.add_node("capture_idea", capture_idea) workflow.add_node("obsidian_research", process_obsidian_content) workflow.add_node("planner_agent", planner_agent) workflow.add_node("teaser_generator", teaser_generator) workflow.add_node("blog_drafter", blog_drafter) workflow.add_node("scraper", scrape_blog_content) workflow.add_node("summarizer", generate_blog_summary) workflow.add_node("final_post_generator", generate_linkedin_posts) workflow.add_node("x_generator", generate_x_posts) workflow.add_node("validator", validate_posts) workflow.add_node("peer_reviewer", peer_review_agent) workflow.add_node("content_improver", content_improver_agent) workflow.add_node("self_evaluator", self_evaluator) workflow.add_node("recovery_agent", recovery_agent) workflow.set_entry_point("capture_idea") workflow.add_edge("capture_idea", "obsidian_research") workflow.add_edge("obsidian_research", "planner_agent") workflow.add_conditional_edges( "planner_agent", should_generate_teaser, { "teaser_generator": "teaser_generator", "planner_agent": "planner_agent", "scraper": "scraper", }, ) workflow.add_conditional_edges( "teaser_generator", should_generate_blog_draft, { "blog_drafter": "blog_drafter", "planner_agent": "planner_agent", "scraper": "scraper", }, ) workflow.add_conditional_edges( "blog_drafter", should_scrape_blog, {"scraper": "scraper", "END": END} ) workflow.add_edge("scraper", "summarizer") workflow.add_edge("summarizer", "final_post_generator") workflow.add_edge("final_post_generator", "x_generator") workflow.add_conditional_edges( "x_generator", should_validate_or_end, {"validator": "validator", "recovery_agent": "recovery_agent", "END": END}, ) workflow.add_conditional_edges( "validator", should_improve_or_evaluate, { "peer_reviewer": "peer_reviewer", "self_evaluator": "self_evaluator", "recovery_agent": "recovery_agent", }, ) workflow.add_conditional_edges( "peer_reviewer", should_improve_or_end, { "content_improver": "content_improver", "self_evaluator": "self_evaluator", "recovery_agent": "recovery_agent", }, ) workflow.add_edge("content_improver", "validator") workflow.add_conditional_edges( "self_evaluator", should_loop_or_end, {"validator": "validator", "recovery_agent": "recovery_agent", "END": END}, ) workflow.add_edge("recovery_agent", END) return workflow.compile() ``` ### _Entire code for my automation:_ [GitHub](https://github.com/capybara-brain346/post-automation.git) --- ## Closing Thoughts It was very fun building out this automation. Obviously it can't be deemed a boon for my productivity in such a short period of time, but I will be keeping a **close eye on gains (or losses) as a result of this automation, which I certainly will be posting about.** ## **Share This Post**

Earlier this week I shared how the real bottleneck wasn’t writing blogs, it was rewriting them into LinkedIn/X posts.
So I built an automation with LangGraph to solve that.
A 🧵: https://t.co/PhvIFatv6H

— Piyush Choudhari (@piyush_yip){' '} September 18, 2025
--- ### [SHAP values for GBTs – intuition + how they work internally](https://piyushc.com/blog/SHAP-values-for-GBTs) (2025-09-01) Summary: How to explain Gradient Boosted Trees with PDP, ICE, and SHAP, and how TreeSHAP makes black-box models transparent and interpretable. While training our ML models, we have access to amazing algorithms to help model our data to highest accuracy. But what happens to **knowing** why our model predicted a certain value or class? Most of the time... Its **_crickets_** This blog takes you through that journey, starting with **tree-based models**, examining how they **trade off bias and variance**, and then pulling back the curtain with explainability techniques like **PDP, ICE, and SHAP**. Along the way, we’ll use a fitness dataset as our playground, highlighting not just performance metrics but also the subtle caveats that come with interpreting models. --- ## **1. From Decision Trees to Boosting** Decision Trees are the most natural starting point. A single tree is like a flowchart of yes/no rules, They are quick to train, easy to explain, but fragile. Sometimes they may remain shallow resulting in an underfit model, if too deep and it memorizes noise. Random Forests improved on this by averaging across many trees grown on bootstrapped samples with randomized splits. The result: variance drops, predictions stabilize, and accuracy improves. In our dataset, Random Forests reached about **76% accuracy**, the best of all. ![model comparison](/images/blog/shap/model_comparison.png) Gradient Boosted Trees take a different path. Instead of many independent trees, they grow trees sequentially, each one correcting the residual errors of the last. This iterative optimization often sharpens decision boundaries and reduces bias. Our boosted model landed at a similar accuracy (**75%**) but achieved a **higher AUC (0.83 vs. 0.81)**, hence it was better at ranking who is likely to be fit. So, the first lesson: bagging (Random Forests) calms variance, boosting attacks bias, and their relative performance depends on whether stability or fine-grained ranking matters more. --- ## **2. Looking Inside with PDP and ICE** Once we have models that predict fitness, the next question is: _why_? Traditional feature importance scores tell us which features are used often but not how they push predictions up or down. That’s where **Partial Dependence Plots (PDP)** and **Individual Conditional Expectation (ICE)** curves come in. ![model comparison](/images/blog/shap/partial_dependence.png) PDPs show the _average effect_ of a feature by sweeping it across values while holding others fixed. In our case, sleep hours had a clear upward slope which can be interpreted as more rest = higher fitness probability. ICE plots take this further, drawing one line per individual. Here, heterogeneity surfaced: smokers of different ages showed very different curves. But these methods have caveats. PDP assumes features are independent, which is shaky if, say, BMI, weight, and height are strongly correlated. ICE can overwhelm with noise in large datasets. And for categoricals, ordinal encoding (like `smokes=0,1,2`) can create misleading artificial orderings. One-hot encoding or SHAP handles these cases better. --- ## **3. Enter SHAP: From Averages to Explanations** While PDP and ICE offer useful intuition, they only sketch the picture. **SHAP (SHapley Additive exPlanations)** gives us the mathematical rigor of game theory. Think of each feature as a player and the model prediction as the payout. SHAP fairly divides credit among features by averaging their contributions across all possible coalitions. ![model comparison](/images/blog/shap/shap_importance_violin.png) This makes SHAP powerful at two levels: - **Locally**, it explains an individual prediction. For one subject in our dataset, SHAP showed that extra sleep added about +0.2 probability of being fit, while smoking subtracted –0.4. - **Globally**, aggregating SHAP values revealed that **Activity Index** was the dominant factor overall, followed by Nutrition and Smoking habits. Yet even SHAP has limits. Standard implementations assume features are independent; with correlated inputs, attributions may drift. Conditional SHAP variants or correlation-aware baselines are designed to address this. --- ## **4. TreeSHAP: Efficient Explanations for Ensembles** The original method for calculating **Shapley values** involves a **combinatorial problem** that quickly becomes intractable. To determine the importance of a single feature, you must consider **all possible coalitions of features**. A coalition is a subset of features used to make a prediction. The number of these subsets grows **exponentially with the number of features**, 2^M, where M is the number of features. For a model with just 20 features, this means considering **over a million subsets**, making the exact calculation computationally impossible for most datasets. **TreeSHAP** overcomes this by leveraging the **tree structure of the model**. Instead of evaluating all possible feature combinations, it **traces all possible paths down a decision tree**. A key insight is that the **order in which features are added to a coalition corresponds to a path through the tree**. TreeSHAP can **efficiently compute the expected marginal contribution of a feature** by traversing the tree and summing up contributions at each split, weighted by the number of samples in that branch. It exploits the fact that for a given path, the **contribution of a feature is determined by the difference in predictions at the nodes above and below the split that uses that feature**. By doing this recursively for all paths and all trees in the ensemble, it **calculates the exact SHAP value in polynomial time**. In practice, this means libraries like **XGBoost** and **LightGBM** let you extract SHAP attributions directly. In our fitness experiment, **TreeSHAP produced global summary plots and local decision plots without prohibitive computation**, turning what once felt like a black box into something **transparent and verifiable**. --- ## **Closing Thoughts** Our fitness dataset experiment highlights a broader truth about machine learning: raw accuracy is only half the story. Random Forests and Gradient Boosted Trees gave us competitive predictive performance, but the real value came when we dug into _why_ the models behaved as they did. PDP offered broad trends, ICE revealed individual variability, and SHAP — especially TreeSHAP — delivered a mathematically grounded explanation at both the local and global scale. --- ## **Share This Post**

Accuracy is only half the story. I just wrapped up an experiment showing how SHAP values, ICE, PDP & TreeSHAP make Gradient Boosted Trees explainable.

Dive in: https://t.co/UXm8vh8FyO

— Piyush Choudhari (@piyush_yip){' '} September 11, 2025
## Projects - [Agent Sandboxing](https://piyushc.com/projects/agent-sandboxing) (2026) Cloud coding agents that change GitHub repos inside isolated Docker sandboxes, with short-lived credentials, live diffs, and pull requests Stack: TypeScript, Node.js, Docker, PostgreSQL, Prisma, Oauth. Outcome: Separates the agent control plane from the Docker execution plane: the agent never enters the sandbox, and sandboxes receive only short-lived, repository-scoped GitHub credentials. - [CapyNodes](https://piyushc.com/projects/capynodes) (2026) System design practice canvas with an AI judge that scores your architecture using rule checks and LLM reasoning Stack: Python, Langchain, Groq, Django, PostgreSQL, LLMs. Outcome: CapyNodes features a unique multi-stage evaluation pipeline combining rule-based heuristics with LLM Chain-of-Thought (CoT) reasoning, backed by a Django + Channels architecture for real-time diagram state sync. - Active users: 50+ - Evaluation sessions: 250+ - Eval pipeline: 3-stage ## Products - [LazyAWS](https://lazyaws.xyz/): TUI for the AWS console. Product Hunt Top 10, 500+ downloads. ## Experience ### Founding AI Engineer @ Webzero.ai (Oct 2026 - Present) ### AI Builder Intern @ Flytbase (Apr 2026 - Aug 2026) - **FB Copilot** Built an AI assistant piloted across 10+ organizations for querying live drone operations and creating mission workflows through natural language, reducing setup time from ~5 minutes to under 30 seconds Designed a 6-stage planning pipeline for intent classification, parameter extraction, entity resolution, validation, planning, and operator confirmation before execution Built an 8-tool ReAct assistant using LangChain and Qdrant to answer grounded questions about fleets, telemetry, docks, missions, and alarms in under 5 seconds Developed a 300-case evaluation suite covering routing, parameter extraction, entity resolution, and rejection of unsupported or fabricated requests - **Thermal Radiometric Inspection Tool** Built a DJI radiometric inspection platform with a backend that converts R-JPEG images into calibrated 640×512 temperature matrices in 150–300 ms, supporting per-pixel, region, line, histogram, isotherm, and image-comparison ### AI Engineer Intern @ Ronin Labs (Jan 2025 - Apr 2026) - **AskRaven** Built an AI system that analyzes live Meta Ads data to answer performance questions, audit creatives, and recommend budget and creative actions. Used across 5 brands, resulting in campaigns with 4% average ROAS improvement Developed a two-layer personalization system combining researched Brand DNA with performance-grounded memory, and consolidated 22 specialized tools into 15 parameterized tools - **Sketchbot** Built an image-to-sketch system deployed at 10 events and used by 1,000+ people, using FastAPI, SDXL Turbo, ControlNet, and OpenCV to cut robot drawing time from 10 minutes to under 3 minutes Deployed GPU inference on AWS g5.2xlarge instances, reducing infrastructure cost by 30% per region, with automated AMI/EBS recovery in under 15 minutes - **OnePlus 13s Quest Quiz** Built backend APIs for a global OnePlus campaign serving 150K+ total users and 250+ active concurrent users, maintaining response times below 120 ms with Node.js, TypeScript, TypeORM, and GCP Cloud SQL - **Cefaly** Built and optimized the pose-estimation system for Cefaly’s mobile app with 1K+ downloads, achieving 0.992 mAP50 for electrode detection and ~60 ms end-to-end mobile inference latency