Skip to content
bitwizard25Public

About

Low-latency Go voice tutor backend for Indian languages (WebSocket streaming, Bhashini ASR/TTS, Gemini, Clean Architecture, Postgres)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Shiksha AI

Shiksha AI is a voice-first tutor for Indian-language learners: speech in, model reasoning, speech out. The turn structure and latency budget are designed so a session feels like talking to a person. This repository is the Go backend.

  • Design (HLD + LLD + diagrams): docs/design.md. §19 covers architecture and scaling.
  • The build is delivered in five plans; see Status.

How it works

A learner asks a question out loud and hears the tutor answer in the same language, and can interrupt it at any time:

flowchart LR
    mic[Learner speaks] -->|PCM audio over WebSocket| asr[Bhashini ASR]
    asr -->|transcript| llm[Gemini, streaming]
    llm -->|sentences as they arrive| tts[Bhashini TTS, 3 in parallel]
    tts -->|audio frames| spk[Learner hears the reply]
    spk -. barge-in: learner talks over it .-> mic
Loading
  • Latency target: the first audio of the reply goes out at most 1.5 s (p50) and 2.5 s (p95) after the learner stops speaking.
  • How it gets there: audio streams while the learner talks, the model replies in a stream, the first short clause is spoken early, and TTS runs ahead of playback.
  • What exists today: the providers, the benchmark tool, tutoring sessions and the live voice path over a WebSocket (docs/ws-protocol.md). Latency against the real providers has not been measured yet.

Supported languages

Hindi, Marathi, Bengali, Tamil, Telugu, Gujarati, Kannada, Malayalam and English. The tutor replies in the learner's language and script, and each language has its own voice and short spoken phrases, such as fillers and "please say that again".

Architecture

The code follows classic Clean Architecture layers. Source dependencies point inward only, and internal/archtest fails the build if they don't.

Layer Package Holds
Entities internal/entity Enterprise rules: users, emails, languages (with each one's TTS voice and spoken phrases), subjects, tutoring sessions and messages, refresh-token replay rule
Use cases internal/usecase Interactors (auth, accounts, language catalog, sessions and tickets, prompt builder, history, summaries, sweeper) and the ports they need; usecase/conversation holds the speech and language ports (ASR, LLM, TTS) and the realtime core (session actor, turn pipeline, segmenter, TTS pool, persister, hub)
Interface adapters internal/adapter REST controllers (httpapi), the voice WebSocket (ws: codec, outbox, handler), Postgres repositories (repository), provider gateways (gateway: Bhashini, Gemini, simulated providers, and a guard with a concurrency cap, circuit breaker and metrics)
Frameworks & drivers internal/infrastructure Config, database (pool, TxManager, migrations), crypto, mail, rate limiter, audio (WAV/PCM), embedded audio clips, realtime metrics
Composition root internal/bootstrap, cmd/shiksha Wiring and roles
Tools cmd/voicecli, cmd/devdb Provider CLI and latency benchmark; local Postgres for development

The same binary runs as different roles, so each part scales on its own. Coordination goes only through Postgres; no Redis is needed.

shiksha serve --roles=api      # stateless REST API
shiksha serve --roles=realtime # WebSocket voice sessions on the configured providers (PROVIDERS=fake or real)
shiksha serve --roles=worker   # sweeper: ends abandoned sessions, purges expired tokens and tickets
shiksha serve                  # every role in this build: api,realtime,worker (local dev)
shiksha migrate                # apply migrations and exit (release step)

api and realtime share one listener (HTTP_ADDR) when they run in the same process; in production a load balancer sends /v1/ws to the realtime pods.

Status

Plan Scope State
1 Clean skeleton, Postgres, accounts API, admin endpoints, api role ✅ done
2 Bhashini ASR/TTS + Gemini gateways, provider guard, voicecli, latency benchmark gate ✅ code done; the real-provider latency benchmark is pending API keys
3 Tutoring sessions and tickets, prompt builder, history, summaries, sweeper in a worker role ✅ done (see note)
4 realtime role: WebSocket voice core (turn pipeline, barge-in, continuation merge, outbox, hub) ✅ done; tested end to end on simulated providers (see note)
5 Latency polish, hardening, protocol docs planned

Works today:

  • Accounts: sign-up, sign-in, rotating refresh tokens, password reset, profile, account deletion.
  • The language catalog, which shows each language's availability, and the subject list.
  • Tutoring sessions: create, list, read back with their messages, reconnect tickets and ending; session summaries feed the tutor's memory of earlier sessions.
  • The live voice (or typed) conversation over a WebSocket: streamed replies, barge-in, fillers, reconnects. The protocol is in docs/ws-protocol.md.
  • The worker role's sweeper, which ends abandoned sessions and purges expired tokens and tickets.
  • The speech and language provider layer (Bhashini and Gemini, or simulated providers), used by the realtime role and summaries and exercised directly through voicecli.

Plan 4 note. The realtime core is tested end to end over a real WebSocket and Postgres on the simulated providers (PROVIDERS=fake: a tone for speech, a canned tutor reply). With PROVIDERS=real it runs on the same guarded Bhashini and Gemini gateways as voicecli; a reply that fails before its first token is retried once on GEMINI_FALLBACK_MODEL. Latency against the real providers has not been measured yet, and the embedded clips (fillers, "please say that again") are empty until voicecli assets generates them.

Plan 3 note. No River job queue or LISTEN/NOTIFY bus was needed: the sweeper is a plain loop in the worker role, safe across instances because every step is one conditional SQL statement. A connection on another instance is fenced by the database epoch, and POST /v1/sessions/{id}/end only reaches a live session hosted by the same process (otherwise it ends the row, and the live connection is fenced on its next write or stopped by the sweeper). They stay on the list for when sessions are spread over many realtime pods. Summaries are written with the providers' LLM on GEMINI_SUMMARY_MODEL.

Tech stack

  • Language and HTTP: Go 1.27; standard-library net/http routing.
  • Realtime: WebSockets through coder/websocket; one actor goroutine per live session.
  • Database: Postgres through pgx v5, with goose migrations embedded in the binary.
  • Auth: argon2id password hashing and HS256 JWTs (golang-jwt); x/time/rate limiters.
  • Speech and language: Bhashini ULCA (ASR/TTS) over REST; Gemini through Google's genai SDK.
  • Observability: Prometheus metrics and structured slog JSON logs.
  • Tests: a real embedded Postgres, so no Docker is needed, and the race detector on every run.

Run locally (Windows, no Docker)

You need Go 1.27. In the first terminal, start a local Postgres (the first run downloads it):

go run ./cmd/devdb

In a second terminal:

Copy-Item .env.example .env
# .env.example ships with no JWT_SECRET (there is no safe default). Generate one and set it in .env:
[Convert]::ToBase64String((1..48 | % { Get-Random -Max 256 }))
go run ./cmd/shiksha serve

Try it:

$body = @{ email="[email protected]"; password="correct horse"; display_name="Asha"; terms_accepted=$true } | ConvertTo-Json
$r = Invoke-RestMethod -Method Post -Uri http://localhost:8080/v1/auth/register -ContentType 'application/json' -Body $body
Invoke-RestMethod -Uri http://localhost:8080/v1/me -Headers @{ Authorization = "Bearer $($r.access_token)" }
Invoke-RestMethod -Uri http://localhost:9090/readyz

Run with Docker

cp .env.example .env
# .env.example ships with no JWT_SECRET (there is no safe default). Generate one and set it in .env:
openssl rand -base64 48
docker compose up --build

docker-compose.yml runs serve (all roles: api,realtime,worker) with migrations on (--migrate defaults to true), which is convenient for local dev. The production image's default CMD is serve --migrate=false: a service instance should never race another replica to apply migrations at startup. Run shiksha migrate once as its own release step instead, using a direct (non-PgBouncer) DATABASE_URL — migrations need a real session, not a pooled transaction-mode connection.

Tests

go test -race ./...
  • Use-case tests run on in-memory fakes, with no database.
  • Adapter and infrastructure tests start a real embedded Postgres, with no Docker. The first run downloads the binaries; run go test ./internal/infrastructure/database/... once on its own before the full suite, so the download doesn't race across packages.
  • Existing server: set TEST_DATABASE_URL to a role with CREATEDB to test against it instead.

Speech and language providers

PROVIDERS=fake (the default) simulates speech recognition, the tutor model and speech synthesis, so everything runs without keys. PROVIDERS=real uses Bhashini (ASR + TTS) and Gemini and needs BHASHINI_USER_ID, BHASHINI_ULCA_API_KEY and GEMINI_API_KEY in .env. Use a paid-tier Gemini key: the learners are minors, and paid-tier data is not used for training. GET /v1/languages reports available: false for a language until Bhashini has resolved both its ASR and TTS models; failed attempts are logged and retried in the background.

The realtime role (live replies) and the session summarizer use these same providers. Every provider call goes through a guard with three parts:

  • A concurrency cap: PROVIDER_MAX_CONCURRENCY, default 64.
  • A circuit breaker: after 5 consecutive failures it fails fast for 15 s, then lets one probe call through.
  • Prometheus metrics on :9090/metrics.

API keys never appear in logs or error messages.

voicecli calls the providers directly:

go run ./cmd/voicecli tts --lang hi --text "नमस्ते" --out hello.wav
go run ./cmd/voicecli asr --lang hi --wav testdata/hi_question.wav       # 16 kHz mono WAV
go run ./cmd/voicecli llm --lang hi --text "भिन्न क्या होता है?"
go run ./cmd/voicecli assets                                              # regenerate the spoken clips
go run ./cmd/voicecli latency --lang hi --wav testdata/hi_question.wav --runs 20

The benchmark's p50/p95 results against the latency budget (p50 ≤ 1.5 s, p95 ≤ 2.5 s) will be recorded in docs/design.md §20 once it has run with real keys.

API (current)

Method Path Auth
POST /v1/auth/register –
POST /v1/auth/login –
POST /v1/auth/refresh –
POST /v1/auth/logout –
POST /v1/auth/password/forgot –
POST /v1/auth/password/reset –
GET / PATCH / DELETE /v1/me Bearer
GET /v1/languages (with available), /v1/subjects –
POST / GET /v1/sessions (create, list with limit and cursor) Bearer
GET /v1/sessions/{id} (session and messages) Bearer
POST /v1/sessions/{id}/ticket (reconnect ticket; 409 if ended) Bearer
POST /v1/sessions/{id}/end (202; idempotent) Bearer
GET /v1/ws?ticket=… (WebSocket, subprotocol shiksha.v1; see docs/ws-protocol.md) ticket
GET :9090/healthz, :9090/readyz, :9090/metrics –

Errors use {"error":{"code","message","field?","request_id"}}.

Security

  • Passwords: hashed with argon2id, after Unicode normalization so that different encodings of the same Indic-script text match.
  • Tokens:
    • Access tokens last 15 minutes. Refresh tokens are opaque and rotate on every use, and only their hashes are stored.
    • Reusing a rotated refresh token after a 20-second grace window revokes the whole token family.
  • No account enumeration:
    • Login costs the same time for unknown emails.
    • Forgot-password always answers 202, even when something fails internally.
  • Rate limits and input checks:
    • Rate limits on register, login, refresh, password reset and account deletion.
    • Strict JSON bodies (1 MB cap, unknown fields rejected), and display names that reject control and bidi-override characters.
  • Secrets: provider API keys are redacted from logs and error messages, and HTTP redirects are refused so keys are never forwarded to another host.
  • WebSocket tickets: single-use and short-lived (WS_TICKET_TTL, default 60 s), stored only as hashes, and issued only to the session's owner; browser origins must be in ALLOWED_ORIGINS.

Upcoming features

  • Structured lessons: topic catalogue, lesson plans, tutor-driven steps, quizzes, progress tracking.
  • Language-learning mode: pronunciation feedback and conversation practice.
  • Streaming ASR through Bhashini's socket.io API, so the learner is transcribed while they speak.
  • Gemini Live native-audio engine as an alternative pipeline.
  • Opus audio downlink, or resampling, to cut mobile bandwidth.
  • Phone OTP and Google sign-in.
  • Verifiable parental consent (DPDP Act 2023).
  • Parent and teacher dashboards with learning analytics.
  • Opt-in audio retention for quality review.
  • Usage quotas and plans.
  • Redis adapters for globally exact rate limits, plus OpenTelemetry tracing.
  • Web and mobile clients.

About

Low-latency Go voice tutor backend for Indian languages (WebSocket streaming, Bhashini ASR/TTS, Gemini, Clean Architecture, Postgres)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages