Skip to content

Latest commit

 

History

History

fastapi

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

OpenUI × FastAPI Example

A full-stack example that demonstrates using @openuidev/react-ui with a FastAPI (Python) backend. The LLM streams responses in OpenUI Lang and the React frontend renders them as live components in real time.

This is the first example in the repo using a non-Node.js backend — the same frontend that works with Next.js works here unchanged.

Architecture

┌────────────────────────┐         ┌─────────────────────────┐
│  Vite + React          │  POST   │  FastAPI (Python)       │
│  (port 5173)           │ ──────► │  (port 8000)            │
│                        │         │                         │
│  • AgentInterface UI   │         │  • POST /api/chat       │
│  • openAIReadable-     │  NDJSON │  • OpenUI Cloud         │
│    StreamAdapter()     │ ◄────── │    Chat Completions     │
└────────────────────────┘         └─────────────────────────┘

The Vite dev server proxies /api/* to FastAPI, so CORS is handled transparently.

Project Structure

fastapi-backend/
├── backend/
│   ├── .env.example         # Environment template
│   ├── pyproject.toml       # Python dependencies
│   └── app/
│       └── main.py          # Streaming chat endpoint
└── frontend/
    ├── package.json
    ├── vite.config.js       # Vite + proxy to localhost:8000
    ├── index.html
    └── src/
        ├── library.ts           # openuiLibrary re-export for `openui generate --spec`
        ├── main.jsx
        ├── App.jsx              # AgentInterface + openuiLibrary
        └── index.css

Getting Started

Prerequisites

1. Configure the backend

cd backend
cp .env.example .env

Add your key to backend/.env:

THESYS_API_KEY=sk-th-...

2. Start the backend

cd backend
uv run uvicorn app.main:app --reload

Or with pip:

pip install fastapi openai python-dotenv uvicorn
uvicorn app.main:app --reload

The API will be available at http://localhost:8000.

3. Start the frontend

cd frontend
pnpm install --ignore-workspace
pnpm generate
pnpm dev

Open http://localhost:5173.

What's in This Example

backend/app/main.py

A FastAPI endpoint that:

  1. Receives { messages } as JSON (OpenAI Chat Completions messages)
  2. Calls OpenUI Cloud's Chat Completions API (POST /v1/embed/chat/completions) with a system prompt built from frontend/src/generated/spec.json (openuiLibrary, generated by pnpm generate in the frontend)
  3. Yields each chunk as NDJSON — the same format the JavaScript SDK's toReadableStream() produces

frontend/src/App.jsx

Uses fetchLLM with openAIReadableStreamAdapter() and openAIMessageFormat to parse the NDJSON stream from FastAPI.

Learn More

Verify

From frontend/, the verification script builds the client and syntax-checks the Python backend:

pnpm verify