🌳 Context-Tree Chat Service

A tree-structured conversational system.

Each conversation forms a rooted tree of chat nodesβ€”fork any message, explore tangents without losing context, and replay any branch by climbing back to the root.


✨ Features

  • Session Management – create & list chat sessions (per-user API key).
  • Branching Conversation – fork any node to start a tangent.
  • LLM-Driven Replies – send user history to an LLM and store its reply as a child node.
  • Tree Navigation – fetch the entire session or any branch as nested JSON.
  • API-Key Authentication – protect all endpoints with per-user keys.

πŸš€ Quick-start

Clone & install

git clone <YOUR_FORK_URL>
cd context-tree-service
poetry install

Run locally

poetry run uvicorn branched_backend.main:app --reload

πŸ”‘ Authentication Flow

  1. User onboarding – frontend signs up / logs in via Clerk β†’ receives session JWT.
  2. Generate an API key bash curl -X POST http://localhost:8000/api/v1/keys/generate \ -H "Authorization: Bearer <CLERK_JWT>"
  3. Call the API – include your key on every request:

πŸ“š API Endpoints

All routes clients should call with cURL live under /api/v1/sessions and require Authorization: Bearer <API_KEY>.

Category Method Path Description
Sessions POST /sessions Create a new chat session
Sessions GET /sessions/{sid} Fetch session metadata & nodes
Branching POST /sessions/{sid}/branches Fork a branch under the given parent
Messaging POST /sessions/{sid}/branches/{bid}/msgs Append user message β†’ LLM reply β†’ save
Messaging GET /sessions/{sid}/branches/{bid}/msgs List all replies (children) for a branch

πŸ’‘ cURL Walk-through

# 1. Create a session
curl -X POST http://localhost:8000/api/v1/sessions \
  -H "Authorization: Bearer $API_KEY"

# 2. Fork a branch
curl -X POST http://localhost:8000/api/v1/sessions/$SID/branches \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"parent_id":"<root_branch_id>","user_message":""}'

# 3. Append a message
curl -X POST http://localhost:8000/api/v1/sessions/$SID/branches/$BID/msgs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"parent_id":"<BID>","user_message":"Hello, world!"}'

# 4. List replies
curl http://localhost:8000/api/v1/sessions/$SID/branches/$BID/msgs \
  -H "Authorization: Bearer $API_KEY"

πŸ—οΈ Tech Stack

  • FastAPI – HTTP server & routing
  • SQLAlchemy – ORM for Postgres / SQLite
  • Pydantic – request & response models
  • Clerk – user authentication & onboarding
  • Poetry – dependency management
  • Uvicorn – ASGI server
  • Alembic – database migrations

🎯 Next Steps

  • Add rate-limiting & analytics via Redis
  • Summary / prompt trimming for very long histories
  • Containerize with Docker & set up CI/CD for auto-releases
  • Integrate Stripe for payments

Built With

Share this project:

Updates