Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ A caller submits a **State** (the content to evaluate) and a set of **Questions*
- **Choice** — select one of a defined option set (returns the choice, its distribution, and a confidence)
- **Score** — rate on an ordered rubric of ≥2 levels (returns a probability-weighted value and a confidence)

### Example Curl Request
### Example Curl Requests

```bash
curl -X POST http://localhost:8123/v1/systemone \
curl -X POST http://localhost:8000/v1/systemone \
-H "Content-Type: application/json" \
-d '{
"model": "jev-latest",
Expand All @@ -31,6 +31,40 @@ curl -X POST http://localhost:8123/v1/systemone \
}' | jq
```

```bash
curl -X POST http://localhost:8000/v1/systemone \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "jev-latest",
"state": "Help! I was charged twice for my subscription this month and I need a refund immediately before my account overdrafts.",
"questions": {
"urgency": {
"type": "noul",
"instructions": "Does this message express urgency or request immediate action?"
},
"routing_department": {
"type": "choice",
"instructions": "Which team should handle this?",
"criteria": {
"billing": ["charges", "invoices", "refunds"],
"technical": ["bugs", "outages", "errors"],
"general": null
}
},
"severity": {
"type": "score",
"instructions": "How severe is the issue?",
"criteria": [
"Cosmetic or informational",
"Workaround exists, non-critical",
"Blocking issue, requires immediate intervention"
]
}
}
}' | jq
```


See `CONTEXT.md` for the full domain glossary.

Expand Down
13 changes: 0 additions & 13 deletions SPECIFICATION.md

This file was deleted.

27 changes: 25 additions & 2 deletions docs/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,31 @@ Six custom instruments are exported:

## Logs

Logs are structured JSON. When the logs signal is on and a span is active, each
record is correlated with the current trace via `trace_id` / `span_id`.
Application logs go to the `whatdo` logger, configured by `WHATDO_LOGGING__LEVEL`
(default `INFO`) and `WHATDO_LOGGING__JSON_LOGS` (default `true`). Uvicorn's
`--log-level` only affects uvicorn's own access/server lines, not these.

JSON records carry `timestamp`, `level`, `logger`, `thread` and `message`. When
the OTEL logs signal is on and a span is active, each record is also correlated
with the current trace via `trace_id` / `span_id`. With `JSON_LOGS=false` the
same records are rendered as plain text for local development.

| Level | What is logged |
| ----- | -------------- |
| `INFO` | Startup summary (engine, served model, worker count, queue/timeout, auth and OTEL state), one line per worker describing its engine copy, each engine's load (including Laya's resolved device and dtype), pool readiness, shutdown, and requests rejected for an unserved **Model**. |
| `WARNING` | Requests shed as overload (queue full) or timed out (`529`). |
| `ERROR` | An engine that failed to load, with its traceback. |
| `DEBUG` | Per request: model resolution, queue depth, the questions sent to the engine, answers, token counts and latencies. |

The `thread` field (`laya-worker-N`) shows which engine copy handled a record.
**State** payloads are never logged, since they may carry user data; API keys
are never logged either.

For local development:

```bash
WHATDO_LOGGING__JSON_LOGS=false WHATDO_LOGGING__LEVEL=DEBUG make run
```

## Testing it

Expand Down
19 changes: 18 additions & 1 deletion src/whatdo/api/systemone.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import logging
import time
from typing import Annotated

Expand All @@ -14,6 +15,8 @@
from whatdo.resolution import ModelNotServedError, resolve_model
from whatdo.schemas.jev import SystemOneRequest, SystemOneResponse, Usage

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/v1", tags=["system-one"])

# Non-standard overload status the official SDK retries with backoff (ADR-0003).
Expand All @@ -30,6 +33,11 @@ async def system_one(
try:
resolved_model = resolve_model(body.model, settings.model)
except ModelNotServedError as error:
logger.info(
"Rejected request for model %r (this deployment serves %r)",
error.requested,
error.served,
)
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error)
) from error
Expand Down Expand Up @@ -58,7 +66,16 @@ async def system_one(

# Count only served requests, matching the metric's "accepted" meaning; a
# shed request is signalled solely by the overload counter above.
telemetry.record_inference_latency(time.perf_counter() - started)
elapsed = time.perf_counter() - started
logger.debug(
"System One: model %r -> %r, %d questions, %d input tokens, %.1fms",
body.model,
resolved_model,
question_count,
result.input_tokens,
elapsed * 1000,
)
telemetry.record_inference_latency(elapsed)
telemetry.record_request(model=resolved_model, question_count=question_count)

return SystemOneResponse(
Expand Down
43 changes: 43 additions & 0 deletions src/whatdo/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from __future__ import annotations

import logging
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

Expand All @@ -21,6 +23,8 @@
from whatdo.inference.pool import WorkerPool
from whatdo.observability import configure_observability, shutdown_observability

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
Expand All @@ -31,21 +35,60 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
blocking model load does not block the loop. The pool is drained on exit.
"""
pool: WorkerPool = app.state.pool
_log_startup(app.state.settings, pool)
started = time.perf_counter()
pool.start()
try:
await run_in_threadpool(pool.wait_ready)
except BaseException:
# The worker already logged the load error; uvicorn prints the chain.
logger.error("Startup failed: worker pool did not become ready")
# A failed load leaves sibling workers blocked on the queue; drain them
# (and stop OTEL export threads) rather than leak before propagating.
await run_in_threadpool(pool.shutdown)
await run_in_threadpool(shutdown_observability, app)
raise
logger.info(
"Worker pool ready: %d engines loaded in %.1fs",
len(pool.engines),
time.perf_counter() - started,
)
try:
yield
finally:
logger.info("Shutting down worker pool")
await run_in_threadpool(pool.shutdown)
# Flush and stop OTEL providers (no-op when observability is off).
await run_in_threadpool(shutdown_observability, app)
logger.info("Shutdown complete")


def _log_startup(settings: Settings, pool: WorkerPool) -> None:
"""Report what this process is about to serve (never logs API keys)."""
model = settings.model
otel = settings.otel
logger.info(
"Starting whatdo: engine=%s served_model=%s workers=%d queue_max=%d "
"request_timeout=%.1fs auth=%s otel=%s log_level=%s",
model.engine,
model.served_model,
len(pool.engines),
settings.server.queue_max,
settings.server.request_timeout,
(
f"enabled ({len(settings.auth.api_keys)} keys)"
if settings.auth.enabled
else "disabled"
),
f"enabled ({otel.endpoint or 'default endpoint'})"
if otel.enabled
else "disabled",
settings.logging.level.upper(),
)
# One line per copy: each engine's repr carries its own model/device, so
# this stays accurate for injected engines and future engine types.
for index, engine in enumerate(pool.engines):
logger.info("Worker %d: %r", index, engine)


def create_app(
Expand Down
15 changes: 13 additions & 2 deletions src/whatdo/inference/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import hashlib
import json
import logging
import random
from collections.abc import Sequence

Expand All @@ -25,6 +26,8 @@
ScoreQuestion,
)

logger = logging.getLogger(__name__)


def _rng(*parts: str) -> random.Random:
"""A Random seeded stably from the given parts (stable across processes)."""
Expand All @@ -49,8 +52,12 @@ def _argmax(probabilities: dict[str, float]) -> str:
class FakeEngine:
"""Deterministic engine implementing the ``DecisionEngine`` protocol."""

def __repr__(self) -> str:
return "FakeEngine()"

def load(self) -> None:
"""Nothing to load; the fake engine is ready on construction."""
logger.debug("FakeEngine has nothing to load")

def is_ready(self) -> bool:
return True
Expand All @@ -67,9 +74,13 @@ def predict(
answers[name] = self._choice(rng, question)
elif isinstance(question, ScoreQuestion):
answers[name] = self._score(rng, question)
return PredictResult(
answers=answers, input_tokens=self._estimate_tokens(state, questions)
input_tokens = self._estimate_tokens(state, questions)
logger.debug(
"Fake predict: questions=%s input_tokens=%d",
{name: question.type for name, question in questions.items()},
input_tokens,
)
return PredictResult(answers=answers, input_tokens=input_tokens)

def _noul(self, rng: random.Random) -> NoulAnswer:
return NoulAnswer(noul=round(rng.random(), 4))
Expand Down
38 changes: 38 additions & 0 deletions src/whatdo/inference/laya_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@

from __future__ import annotations

import logging
import time
from typing import Any

from whatdo.inference.base import PredictResult
from whatdo.inference.translate import to_jev_answer, to_laya_question
from whatdo.schemas.jev import Answer, JSONContent, Question

logger = logging.getLogger(__name__)

# Default Laya checkpoint (the English root of the bundled repo).
DEFAULT_CHECKPOINT = "convaiinnovations/laya"

Expand All @@ -33,9 +37,16 @@ def __init__(
# An injected agent (used by tests) is treated as already loaded.
self._agent = agent

def __repr__(self) -> str:
return (
f"LayaEngine(checkpoint={self._checkpoint!r}, device={self._device!r}, "
f"subfolder={self._subfolder!r})"
)

def load(self) -> None:
"""Load the Laya checkpoint. Device auto-detects CUDA/MPS/CPU when unset."""
if self._agent is not None:
logger.debug("Laya agent injected; skipping checkpoint load")
return
try:
import laya
Expand All @@ -46,9 +57,25 @@ def load(self) -> None:
"The 'laya' package is required for the Laya engine. "
"Install it with: pip install 'whatdo[laya]'."
) from error
logger.info(
"Loading Laya checkpoint=%r device=%s subfolder=%r",
self._checkpoint,
self._device or "auto",
self._subfolder,
)
started = time.perf_counter()
self._agent = laya.load(
self._checkpoint, device=self._device, subfolder=self._subfolder
)
# Laya auto-detects the device and may silently fall back to CPU, so
# report what it actually resolved to.
logger.info(
"Loaded Laya checkpoint=%r on device=%s dtype=%s in %.1fs",
self._checkpoint,
getattr(self._agent, "device", "unknown"),
getattr(self._agent, "dtype", "unknown"),
time.perf_counter() - started,
)

def is_ready(self) -> bool:
return self._agent is not None
Expand All @@ -61,10 +88,21 @@ def predict(
laya_questions = {
name: to_laya_question(question) for name, question in questions.items()
}
# The state may carry user data, so only the questions are logged.
logger.debug("Laya predict: questions=%s", laya_questions)
started = time.perf_counter()
result = self._agent.predict(state, laya_questions)
elapsed = time.perf_counter() - started
answers: dict[str, Answer] = {
name: to_jev_answer(answer) for name, answer in result["answers"].items()
}
# Laya always reports tokenizer-derived usage; fail loud if it doesn't.
input_tokens = int(result["usage"]["input_tokens"])
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"Laya predict done in %.1fms: input_tokens=%d answers=%s",
elapsed * 1000,
input_tokens,
{name: answer.model_dump() for name, answer in answers.items()},
)
return PredictResult(answers=answers, input_tokens=input_tokens)
Loading
Loading