Download docs/ARCHITECTURE.md from shimen/yapapa: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/spaces/shimen/yapapa/resolve/main/docs/ARCHITECTURE.md
- Command line
-
hf download hf://spaces/shimen/yapapa/docs/ARCHITECTURE.md
-
curl -L -o ARCHITECTURE.md https://huggingface.co/spaces/shimen/yapapa/resolve/main/docs/ARCHITECTURE.md
wiwi β Architecture
wiwi is a self-hosted LLM gateway and proxy. It exposes three native API surfaces β OpenAI Chat Completions, OpenAI Responses (for Codex CLI / Agents SDK), and Anthropic Messages (for Claude Code / Anthropic SDK) β routes every request to the right provider behind the scenes, and adds the operational layer LiteLLM is known for: virtual keys, budgets, rate limits, load balancing, retries, fallbacks, spend tracking, and request logs.
Any inbound surface can reach any provider. A client that calls /v1/messages gets Anthropic-format responses even if the backing deployment is OpenAI, and vice versa. Translation between all wire formats goes through one canonical internal representation (IR), so adding a surface or a provider costs exactly two codecs, never NΓN converters.
The design mirrors LiteLLM's mental model (config-driven model_list, model groups of deployments, a central router, async spend logging) so anyone who knows LiteLLM can operate wiwi.
Trust the code over any doc β this file describes the system as built (see
wiwi/andweb/). Companion docs: CORE.md (module-by-module internals), STREAMING.md (delta contract, failover/journals), API_REFERENCE.md, CONFIG.md, PROVIDERS.md, ADMIN.md, DEVELOPMENT.md.
1. Design principles
- Clients never change. Whatever dialect a client speaks β OpenAI SDK, Codex CLI, Claude Code, LangChain β wiwi answers natively in that dialect.
- One canonical IR. All translation is hub-and-spoke: dialect β IR β provider. No pairwise translators.
- Nothing blocking in the hot path. Auth reads are cache-first. Spend writes, rate-limit accounting, and log writes happen after the response is sent, as background tasks.
- Config file first, database second. A single
wiwi.yamlbootstraps everything; the DB (SQLite/Postgres) backs admin-managed state (providers, keys, deployments, prices, users, logs) so the UI can mutate it at runtime. - Dialects and providers are leaf modules. All branching on dialect/provider lives in
wiwi/wire/andwiwi/providers/;core/,router/,auth/,streaming/are generic. - Failures are first-class. Retries, failover, cooldowns, mid-stream resume, durable journals, and an opt-in healer are built into the request path, not bolted on.
2. High-level view
βββββββββββββββββββββββββ wiwi βββββββββββββββββββββββββ
Clients β β
OpenAI SDK ββΌββΊ /v1/chat/completions ββ β
Codex CLI βββΌββΊ /v1/responses βββββββββ€ wire codecs (decode) β
Claude Code βΌββΊ /v1/messages ββββββββββ β β
β βΌ β
β canonical IR (wiwi/ir/types.py) β
β β β
β auth β ratelimit β router (WRR+health) β
β β β
β gateway pump (streaming guards) β
β β β
β ββββββββββββ¬βββββββββββ¬βββββ΄ββββββ¬ββββββββββ β
Admin UI ββββΌββΊ /admin/* + /auth/* + /public/* β β β
(SPA) β βΌ βΌ βΌ βΌ βΌ β
β 13 provider adapters (openai, anthropic, gemini, β
β openai-compatible, openrouter, gmicloud, bai, β
β nvidia-nim, cline, workbuddy, opencode, hermes, ifm) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
3. Request life cycle (wiwi/server/app.py:run_chat_like)
- Parse JSON body (
app.json_body) β with a body-size guard and request-ID middleware wrapping every route. - Wire decode β IR (
wiwi/wire/<dialect>.py:codec_decode). - Authenticate (
wiwi/auth/service.py:AuthService) β master key for/admin/*; virtual keysk-wiwi-β¦(SHA-256-hashed at rest, constant-time compare) for client traffic; session cookie for/auth/*users. - Resolve group (
wiwi/router/router.py:Router.resolve_group) β alias chain +alias_to_provider. - Enforce rate limit (
wiwi/ratelimit/{memory,redis}.py) β sliding-window rpm/tpm per key. The in-memory limiter is the default;RedisRateLimiteris selected whengeneral_settings.redis_urlorREDIS_URLis set, so caps are shared across workers. - Build
RequestContext(wiwi/core/context.py) β the single mutable object threaded through every stage. - Dispatch:
ir_req.stream ? gateway.stream(ctx) : gateway.complete(ctx)β both wrapped byrouter.execute_with_retriesfor failover over deployments + fallback groups. - Provider call:
wiwi/providers/registry.py:fresh_adapter(type)βadapter.encode_requestβ_callβdecode_stream_event. - Stream pump (
wiwi/streaming/+wiwi/core/gateway.py): SSE parse, coalescing, loop detection, partial-JSON tool args, schema validation, StreamTape failover/resume, journal writes (buffered 64 KiB / 50 ms; terminal record written directly). - Outbound encode:
_encoder_for(surface)βChatStreamEncoder | ResponsesStreamEncoder | AnthropicStreamEncoder(streaming) orcodec_encode_response(non-streaming). - Post (after the response is on the wire): log the request, record TPM, update spend (budget cap β 402), translate
WiwiErrorβ per-surfaceerror_body. Withspend_batching_enabled, the reservation release and charge are aggregated bySpendBufferand settled in oneUPDATEper flush instead of two writes per request.
Hard invariants
- All dialect/provider branching stays inside
wiwi/wire/andwiwi/providers/. wiwi/providers/registry.pyhas an import-timeassertthat fails loudly when aPROVIDER_TYPESentry has no matching branch.RequestContextis the single mutable object threaded through every stage.
4. Component map
| Layer | Location | What it does |
|---|---|---|
| HTTP app | wiwi/server/app.py |
FastAPI factory, pure-ASGI middleware chain (request id, body-size guard, latency headers), lifespan, SPA mount, and the routes that are still inline closures |
| HTTP errors | wiwi/server/errors.py |
APIError (status + error type + dialect) and the per-dialect renderer; the app's exception handlers turn a raised APIError into the caller's dialect body (OpenAI {"error":{β¦}} / Anthropic {"type":"error",β¦}) |
| HTTP deps | wiwi/server/dependencies.py |
The auth guards as importable FastAPI dependencies (require_user, require_admin); they read the app state via request.app.state.wiwi and raise APIError rather than returning a response |
| HTTP routers | wiwi/server/routers/ |
One module per admin surface; a router owns the HTTP shape (path, method, request/response models) and delegates the rules to wiwi/server/services/ |
| HTTP schemas | wiwi/server/schemas/ |
Pydantic v2 request/response models per surface. A validation failure is rendered as 400 (not FastAPI's 422) in the caller's dialect, by the RequestValidationError handler in server/app.py |
| Services | wiwi/server/services/ |
The business rules behind the routes (authorization, invariants), raising APIError; no FastAPI imports, so the rules are testable without an HTTP client |
| Wire codecs | wiwi/wire/{openai_chat,openai_responses,anthropic_messages}.py |
decode_request, encode_response, StreamEncoder, error_body per dialect |
| IR | wiwi/ir/types.py, ir/builtin_tools.py |
Part union (TextPart, ImagePart, ToolUsePart, ToolResultPart, ThinkingPart, AudioPart, DocumentPart), Message, Tool, ToolChoice*, ResponseFormat, GenParams, Request, Usage, AssistantTurn, Response; hosted-tool registry |
| Router | wiwi/router/router.py |
Groups/deployments/keys, WRR picking, alias chains, execute_with_retries, health scoring (EWMA latency + success rate), adaptive cooldowns, session and prompt-prefix affinity |
| Gateway | wiwi/core/gateway.py |
Executes one IR request router β adapter β httpx; pumps deltas; TTFT/TPS timing; partial billing; stream-failure accounting |
| Context | wiwi/core/context.py |
RequestContext (surface, ir_req, auth, group, deployment, provider_key, attempts, usage, cost, est_tokens, stop_reason, status, error, metadata, forward_headers, cancel, β¦) |
| Recovery | wiwi/core/recovery.py |
Shared Backoff, CircuitBreaker, parse_retry_after, build_url; opt-in HealthHealer (1-token probes, graduated probation recovery). Used by router retries, Cline/WorkBuddy refresh services, healer. Imports nothing from router/gateway (cycle safety) |
| Streaming | wiwi/streaming/ |
deltas.py taxonomy, sse.py parse/encode, resume.py StreamTape, tape_store.py JournalStore, partial_json.py, validation.py, coalesce.py, loopdetect.py β see STREAMING.md |
| Cache | wiwi/cache/ |
Opt-in exact-match response cache (CacheSettings, off by default): non-streaming only, keyed on normalized IR + group + surface + key id; bypass via x-wiwi-no-cache; memory or Redis backend; ttl_s <= 0 disables it on both; a hit is rebased onto the serving request's identity (hit_rebase.py). singleflight.py dedupes identical concurrent non-streaming requests when enabled. |
| Rate limit | wiwi/ratelimit/ |
Sliding-window rpm/tpm; sharded in-memory locks by default, RedisRateLimiter when redis_url/REDIS_URL is set so caps are shared across workers |
| Auth | wiwi/auth/ |
service.py AuthService, spend_buffer.py batched spend settlement, keys.py virtual keys (hashed), users.py user accounts + PBKDF2 passwords + signed cookies |
| Cost | wiwi/cost/ |
Token β USD engine; per-model prices from the DB (config_store) with bundled fallback |
| Logging | wiwi/logging_core/ |
Three-stream logger: request (DB + SSE), proxy (stdout + SSE), audit (sync DB); LogEvent ring buffer feeds stats and the windowed metrics, process-lifetime RequestTotals carries the monotonic counters; every drop/failure mode is counted and surfaced on /health |
| Config | wiwi/config.py |
Pydantic v2 models, load_config/load_env, PROVIDER_TYPES, os.environ/NAME interpolation |
| Config store | wiwi/server/config_store.py |
DB-backed providers/keys/deployments/settings/model_prices (runtime-mutable) |
| Stats/Metrics | wiwi/server/stats.py, server/metrics.py |
Admin rollups (ring buffer for short ranges, DB aggregates for 7d/30d/all-time) and Prometheus /metrics |
| Frontend | web/ |
React 19 + Vite 6 + Tailwind 4 SPA; admin console (/console) + public front; built to wiwi/server/static/, mounted at / with history fallback |
5. Router & recovery
- Model groups (
model_name) hold deployments (provider +model_id+ weight/overrides). WRR splits traffic proportionally;resolve_groupfollows alias chains. - Key pools: each provider account holds multiple real keys with weights and health states (
active | cooling | invalid | disabled). Errors trigger cooldowns; TPM accounting credits the key once output actually flows (_defer_key_crediton the streaming path). execute_with_retriescovers connect-phase retries (429/5xx/transient httpx β next attempt), deployment failover, and fallback groups.- Health scoring (opt-in):
router_settings.health_model: scoredadds EWMA latency + success-rate scoring and adaptive cooldowns (health_ewma_alpha,health_window,adaptive_cooldown). Defaultnonekeeps bit-identical legacy behavior. - HealthHealer (opt-in, default off): background service probing sick keys/deployments with 1-token requests, graduated (probation) recovery; wired in lifespan like the Cline/WorkBuddy refresh services.
6. Streaming
The delta taxonomy and ordering contract, the pump, tape-based mid-stream failover, durable journals with Last-Event-ID replay, and the guard subsystems are documented in STREAMING.md. Key properties:
- One
StreamTapeper stream for mid-stream failover (continuation messages synthesized from partial output onto a fallback deployment). JournalStorepersists encoded SSE frames to.wiwi/journals/<request_id>.jsonl(enabled by default, 600 s TTL, 1 MiB cap) so reconnects work across wiwi restarts. Appends are buffered (64 KiB or 50 ms) and the terminal record is written directly; every replay read flushes the active journal first.- Backpressure via
asyncio.Queue(maxsize=4096); coalescer merges text deltas under pressure; loop detector terminates degenerate repetition with a cleanFinish.
6.1 Performance and accounting
The hot path is intentionally write-light and lock-light. Most changes are on by default; the three that change semantics or billing are opt-in.
- SQLite runs in WAL mode with
synchronous=NORMAL,busy_timeout=5000, and foreign keys on every connection. Postgres pool size, overflow, and recycle age are configurable (db_pool_size,db_max_overflow,db_pool_recycle_s). - Spend settlement (
auth/spend_buffer.py,spend_batching_enabled) aggregates the admission reservation release and the real charge into oneUPDATEper key per flush. The reservation stays in the DB until the flush, so a crash fails closed; near-cap keys flush synchronously. Withshared_database: true, startup reclaims only reservations older thanreservation_stale_s, never a live sibling's. - Singleflight (
cache/singleflight.py,singleflight_enabled) lets identical concurrent non-streaming requests share one upstream call. The key includeskey_id, so different virtual keys never share a result; joiners are logged with the shared usage atcost=0. - Stream journals buffer appends in memory (64 KiB / 50 ms) instead of one
to_threadwrite andstatper chunk, and flush before every replay read. - Rate limiting uses 16 sharded locks so unrelated keys do not serialize.
RedisRateLimiteris selected when Redis is configured, which is the multi-worker correctness win. - NIM tool schemas are memoized by a canonical hash of the rendered tools (
tool_schema_cache_entries, default 256); hits are deep-copied so a caller cannot mutate another request's schema. - Outbound HTTP uses configurable
httpxpool limits (http_max_connections,http_max_keepalive_connections,http_keepalive_expiry_s) instead of httpx's 100/20 defaults. - Response cache default capacity is 1024 entries, up from 256.
- Prompt-prefix affinity (
prefix_affinity) pins a stable system+tools prefix to the deployment that served it, keeping the provider's own prompt cache warm. It is a preference among healthy candidates, never a hard binding.
Measured on 2026-11-02 against a mock upstream (5 ms JSON, 40 ms streaming) with SQLite, two clean runs: streaming at concurrency 32 improved from 239β405 RPS to 583β810 RPS (1.4β3.4x) with p95 down 25β35%; JSON at concurrency 32 improved 18% by default and 21β56% with batching; the spend path issued 3x fewer UPDATEs; singleflight collapsed 40 identical concurrent calls to 2β3 upstream calls; the NIM schema memo was 1.9x faster on the sanitize walk. At concurrency 1 the upstream dominates and the change is within noise. These numbers isolate gateway overhead, so real gains depend on database latency, stream chunk count, and duplicate traffic.
7. Two different cache-hit flags β do not conflate
cache_hit= provider prompt-cache hit (feedswiwi_prompt_cache_hits_total).response_cache_hit= served from wiwi's own exact-match response cache (wiwi/cache/).
A response-cache hit must leave cache_hit=False (wiwi/server/app.py response-cache branch) or prompt-cache metrics inflate. The response cache never stores streaming requests or requests with builtin tools.
8. Persistence
- SQLite default (
sqlite+aiosqlite:///wiwi.db) with WAL,synchronous=NORMAL, and a 5 s busy timeout; Postgres auto-normalized topostgresql+asyncpg://with a configurable pool (db_pool_size,db_max_overflow,db_pool_recycle_s);DATABASE_URLenv overrides config. - Schema created via inline
CREATE TABLE IF NOT EXISTSat startup β no Alembic. - Tables: virtual keys (hashed), users/sessions, request logs, provider/key pool state, DB-backed config (providers, deployments, settings,
model_prices), audit log, DB-backed log aggregates for long-range stats. - Runtime scratch:
.wiwi/(stream journals) β gitignored, never committed.
9. Security model
- Master key (
WIWI_MASTER_KEY/ config) guards/admin/*viaAuthorization: Bearer. - Virtual keys
sk-wiwi-β¦: SHA-256-hashed at rest, constant-time compare, plaintext returned once at mint. Carry per-key model allowlists, budgets, rpm/tpm, expiry. - User accounts: stdlib PBKDF2 password hashing, HMAC-signed HttpOnly session cookies, roles (user sees only own keys' data; admin sees all).
- Provider secrets: stored via config-store/admin API (encrypted at rest; the reveal endpoint is audit-logged).
- Error translation:
WiwiErroris the unified internal error type; each wire dialect ownserror_body()so clients always see their own dialect's error shape.
10. Deployment
- Docker: 3-stage Dockerfile (uv builder β npm SPA build β python 3.12-slim runtime), non-root user
wiwi, healthcheckGET /healthevery 30 s;WIWI_STATIC_DIR=/app/wiwi/server/static; data in/app/datavolume.docker-compose.ymlrunspostgres:16-alpine+ wiwi with healthcheck-gateddepends_on. - Process model: single FastAPI/uvicorn process per instance; when
redis_url/REDIS_URLis set, the response cache and the rate limiter use Redis, so several instances share entries and rpm/tpm caps. Singleflight, prefix affinity, and the in-memory limiter remain per process. - Observability: structlog JSON lines,
/metricsPrometheus endpoint,/admin/streamSSE, request/proxy/audit logs.
11. Database tables
Schema is created with inline CREATE TABLE IF NOT EXISTS at startup β there is no Alembic and no migration files to write.
| Table | Owner | Contents |
|---|---|---|
request_logs |
logging_core/db_sink.py |
per-request tokens, TTFT, latency, TPS, cost, cache, retry chain |
request_rollups |
logging_core/db_sink.py |
hourly aggregates (key_id/model_group/provider) kept permanently for pruned rows, incl. a per-metric percentile histogram (p95_hist) |
audit_logs |
logging_core/db_sink.py |
actor / action / target / diff for every admin mutation |
vkeys |
auth/service.py |
hashed virtual keys + budgets + spend + live budget reservations (budget_reserved, reserved_at, reservation_owner) |
users |
auth/users.py |
user accounts and roles |
providers Β· provider_keys Β· deployments Β· settings Β· model_prices |
server/config_store.py |
admin-created config that must survive restart |
Both log limits (log_retention_days, log_max_rows) roll the rows they remove into request_rollups first, so dashboard totals, token counts, cost, and percentiles stay complete β only per-request detail is dropped. log_max_rows is what actually bounds storage on a busy gateway.
Percentiles survive the rollup by keeping a compact log-scale histogram per bucket (the p95_hist column), so a percentile over a window spanning both fresh and rolled-up rows merges correctly instead of averaging two quantiles; an all-fresh window is exact and a mixed one is within ~3%.