π€ ai kodi
Building an AI Agent from Scratch in Rust
Built a minimal AI agent in ~150 lines of Rust to understand the core agent loop pattern. The repo: qepo17/kodi.
The agent loop is surprisingly simple:
- Send messages to an LLM (via OpenRouter β Claude Sonnet)
- Check if the response contains tool calls
- If yes β execute the tools, append results to message history, loop back to step 1
- If no β print the final response and exit
The architecture breaks down into four clean files:
models.rsβ OpenAI-compatible request/response types (serde-powered)clients.rsβ The agent loop: send β check tool calls β execute β repeattools.rsβ Tool execution (currently justbash)main.rsβ Entry point, reads API key and query from args
Key implementation details:
- Messages use a tagged enum (
#[serde(tag = "role")]) for clean serialization of system/user/assistant/tool messages - Tool call results get appended as
toolrole messages with the matchingtool_call_id - The
finish_reasonfield distinguishes between"tool_calls"(keep looping) and"stop"(done) - Tool arguments come as a JSON string, not a parsed object β you parse them yourself
The takeaway: the βmagicβ of AI agents is just a while loop with tool dispatch. The model decides what to do, the harness decides how to do it. Once you see the pattern, the whole concept clicks β and you realize you can build one yourself without any framework.