Skip to content

About

Tool-calling AI agent for campus questions: picks tools, cites sources, and streams its reasoning trace live.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CampusBrain Agent

CI Python 3.12 FastAPI React

An AI agent for students and staff that takes a question in plain language, decides which tools it needs (college knowledge base, web search, web pages, calculator), runs them, and returns a cited answer with its full reasoning trace visible.

Live demo: https://campus-agent-six.vercel.app

Overview

A chatbot answers from one prompt; a RAG system answers from one retrieval. This project is the layer above both: a tool-calling loop (think, call a tool, observe, repeat) that chooses its own steps under a hard budget and records every step. Retrieval over college documents is just one of its tools. It is served by CampusBrain (live), a separate RAG service that this repo only calls over HTTP. Users can try it on a small hosted trial allowance or bring their own LLM API key.

Features

  • Agent loop: one readable, synchronous loop (backend/app/agent/loop.py) that never raises. Provider outages, bad tool calls and exhausted budgets all end as a recorded run with whatever the agent found.
  • Six tools: knowledge_search, knowledge_list_documents and knowledge_read_document (via CampusBrain), web_search (Tavily), web_read (built-in HTML fetcher, or Firecrawl when configured), and a safe AST-based calculator.
  • Run budget: limits on steps, tokens, wall-clock time and calls per tool, with a warning to the model before it runs out.
  • Bring your own key: 9 provider entries defined as data in catalogue.json. Gemini, Anthropic and OpenAI-compatible adapters cover Gemini, Groq, OpenRouter, GitHub Models, OpenAI, Anthropic, AgentRouter, Ollama and any custom endpoint. Custom URLs pass through an SSRF guard.
  • Hosted trial mode: anonymous identities with per-identity, per-IP and global daily limits. A failing user key never falls back to the hosted key.
  • Live trace UI: the run's steps stream to the browser over Server-Sent Events, with a sources rail, run history and provider settings.
  • Evaluation harness: a golden set of goals plus metrics computed from the stored trace (success, tool-selection accuracy, answer accuracy, step efficiency, degraded runs).
  • Production basics: rate limiting, request IDs, security headers, credentials redacted before steps are stored, and a startup reaper for abandoned runs.
  • CI: ruff, mypy, Alembic migration and pytest against Postgres; ESLint, Vitest, a type-checked build and a Playwright smoke test; Docker image build. Dependency audits (pip-audit, npm audit) run but don't block the build.

Tech stack

  • Backend: Python 3.12, FastAPI, SQLAlchemy 2 + Alembic, Postgres (psycopg3), Pydantic Settings, httpx (no vendor LLM SDKs), slowapi, structlog
  • Frontend: React 18, TypeScript, Vite, Tailwind CSS 4, Radix UI, react-markdown
  • Testing: pytest, Vitest + Testing Library, Playwright
  • Deployment: Docker on Render (backend), Vercel (frontend), Neon Postgres; see DEPLOYMENT.md

How it works

flowchart LR
    UI[React frontend] -- "POST /api/v1/runs<br/>SSE /runs/{id}/events" --> API[FastAPI]
    CLI[cli.py] --> Loop
    API --> Loop[Agent loop]
    Loop --> PM[Provider manager<br/>trial or BYOK]
    PM --> LLM[(LLM provider)]
    Loop --> Tools[Tool executor]
    Tools --> KB[CampusBrain RAG<br/>HTTP + X-API-Key]
    Tools --> Web[Tavily / web pages]
    Tools --> Calc[Calculator]
    Loop --> DB[(Postgres<br/>runs + steps)]
Loading
  1. POST /api/v1/runs creates a run and runs the agent as a FastAPI background task in the same process. There is no queue or worker.
  2. Each turn, the provider manager's LLM chooses a tool or gives an answer. The tool executor validates arguments against the tool's Pydantic model, enforces timeouts and per-tool call limits, and returns an observation.
  3. Every thought, tool call, observation and answer is written to the steps table. The next prompt is built from these rows, and the SSE endpoint and the evaluation metrics both read from them too.
  4. backend/app/tools/knowledge.py is the only module that knows about CampusBrain. It maps CampusBrain's responses to this repo's own types, so the retrieval backend can be swapped by changing that one file.

Design docs: VISION, PRD, ARCHITECTURE, PROVIDER_ARCHITECTURE, INTEGRATION_CONTRACT, FRONTEND_DESIGN, DEPLOYMENT, and spike/PROVIDER_EVALUATION.md (an early experiment on which free-tier models handle tool calling reliably).

Getting started

Prerequisites

  • Python 3.12 (pinned in backend/.python-version and used by the Dockerfile)
  • Node.js and npm (CI uses Node 20)
  • A Postgres database (the app uses Postgres-only features such as JSONB)
  • A running CampusBrain instance for the knowledge tools, plus an API key for at least one LLM provider

Backend

cd backend
python3.12 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt
cp .env.example .env               # then fill it in (see below)
alembic upgrade head
uvicorn app.main:app --reload      # http://localhost:8000, docs at /docs

The existing setup uses uv as well: uv venv --python 3.12 .venv then uv pip install -r requirements.txt.

Environment variables

Configuration lives in backend/app/core/config.py. The app checks it at startup and won't boot if a required value is missing. See backend/.env.example for comments on each value.

Variable Required Purpose
DATABASE_URL yes Postgres URL. Must use postgresql+psycopg:// (psycopg3)
KNOWLEDGE_BASE_URL yes Base URL of the CampusBrain API
KNOWLEDGE_BASE_API_KEY Must match CampusBrain's SERVICE_API_KEY
KNOWLEDGE_TIMEOUT Seconds; default 30
APP_SECRET yes Signs trial-identity tokens and salts IP hashes
LLM_PRIMARY_PROVIDER, LLM_FALLBACK_PROVIDER gemini or openrouter. The key for each one listed is required at startup
GEMINI_API_KEY, GEMINI_MODEL see above Gemini credentials and model
OPENROUTER_API_KEY, OPENROUTER_MODEL, OPENROUTER_ALLOW_FALLBACKS see above OpenRouter credentials, model and upstream pinning
HOSTED_PROVIDER, HOSTED_MODEL, HOSTED_API_KEY for trial mode The key behind hosted trial runs (not in .env.example)
TAVILY_API_KEY for web_search Tavily search
FIRECRAWL_API_KEY Optional. web_read uses Firecrawl instead of the built-in fetcher
MAX_STEPS, MAX_TOKENS_PER_RUN, MAX_WALL_CLOCK_SECONDS, MAX_CALLS_PER_TOOL Run budget
TRIAL_RUNS_PER_IDENTITY, TRIAL_RUNS_PER_IP, TRIAL_GLOBAL_DAILY_RUNS, TRIAL_MAX_STEPS, TRIAL_MAX_TOKENS, TRIAL_TOOLS Trial limits
BYOK_SESSION_TTL_MINUTES, BYOK_ALLOW_CUSTOM_BASE_URL, BYOK_ALLOW_LOOPBACK Bring-your-own-key options. Keep loopback off in production
CORS_ALLOWED_ORIGINS, CORS_ALLOWED_ORIGIN_REGEX Allowed frontend origins. Set http://localhost:5173 for local dev
DEFAULT_TENANT_ID, LOG_LEVEL Tenancy and logging

The frontend reads one variable, VITE_API_BASE_URL (see frontend/.env.example). Vite bakes it in at build time.

Frontend

cd frontend
npm install
echo "VITE_API_BASE_URL=http://localhost:8000" > .env.local
npm run dev                        # http://localhost:5173

Other scripts: npm run build, npm run lint, npm test (Vitest), npm run test:e2e (Playwright).

CLI

From backend/ with the venv active:

python cli.py run "What is the minimum CGPA to keep my scholarship?"   # trial mode (needs HOSTED_API_KEY)
python cli.py run "..." --provider gemini --max-steps 5 -q             # BYOK; key read from GEMINI_API_KEY
python cli.py tools          # tool descriptions, exactly as the model sees them
python cli.py runs           # recent runs
python cli.py trace 13       # replay a run's full trace
python cli.py eval           # run the golden set and print metrics
python verify.py             # end-to-end checks, including live model calls

Tests

cd backend && pytest -q            # needs the Postgres in DATABASE_URL; LLM and tool calls are mocked
cd frontend && npm test

Project structure

backend/
  app/
    agent/        agent loop, prompts, next-action selector
    api/v1/       runs (+ SSE), providers, identity, health
    core/         config, database, budget, rate limit, identity, redaction
    eval/         golden set and trace-based metrics
    llm/          provider adapters, provider manager, catalogue.json
    tools/        tool registry, executor and the six tools
    models/, repositories/
  alembic/        database migrations
  cli.py          command-line interface
  Dockerfile
frontend/
  src/            pages (Home, RunView, Settings), run timeline components, API client
  e2e/            Playwright smoke test
spike/            early provider-evaluation scripts and results
*.md              design documents (vision, PRD, architecture, roadmap, deployment)

Roadmap

ROADMAP.md and DEVELOPMENT_STRATEGY.md describe the planned phases. Treat them as the design record, not a live progress tracker. Not built yet:

  • automatic failover between LLM providers (LLM_FALLBACK_PROVIDER is validated at startup but no router uses it yet)
  • plan/replan/reflect phases, long-term memory and human-in-the-loop approvals
  • async runs with a queue and workers (runs are in-process background tasks today)
  • a LangGraph port for comparison

About

Tool-calling AI agent for campus questions: picks tools, cites sources, and streams its reasoning trace live.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages