Skip to content
This repository was archived by the owner on Oct 26, 2026. It is now read-only.
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
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,13 @@ In `pl.read_excel()` “calamine” engine can be used for reading all major typ
<p align="right">(<a href="#readme-top">back to top</a>)</p>

### Worker aware async scheduler
The project uses the APScheduler library to schedule tasks in the background.
The APScheduler library is a powerful and flexible in-process task scheduler with Cron-like capabilities.
It allows you to schedule jobs to run at specific times or intervals, and it supports multiple job stores, triggers, and executors.
The library is designed to be easy to use and highly configurable, making it suitable for a wide range of use cases.
It was added to project in version 4.0.0a5 with Redis as event broker and SQLAlchemy as data store.
The app starts an `AsyncScheduler` as part of FastAPI's lifespan. Each worker shares
the persistent SQLAlchemy data store in the `scheduler` schema and uses Redis as the
event broker, allowing APScheduler to coordinate scheduling across workers. The
`tick-sql-25` schedule runs `app.services.scheduler.tick` every 25 seconds and is
replaced on startup so its definition stays current. The project uses APScheduler
4.0.0a6, a pre-release; see the
[ASGI/FastAPI integration example](https://github.com/agronholm/apscheduler/blob/4.0.0a6/examples/web/asgi_fastapi.py).

<p align="right">(<a href="#readme-top">back to top</a>)</p>

Expand Down Expand Up @@ -183,7 +185,7 @@ ollama run llama3.2
<p align="right">(<a href="#readme-top">back to top</a>)</p>

### Websocket AI chat service
A general-purpose, websocket-based chat service lives at `/v1/chat/ws`, built with FastAPI 0.139.0
A general-purpose, websocket-based chat service lives at `/v1/chat/ws`, built with FastAPI 0.159.1
and Pydantic models for every message shape exchanged over the wire. It follows the
[Pydantic AI chat-app](https://github.com/pydantic/pydantic-ai/blob/main/docs/web.md) interaction
pattern - a session id, role-labeled messages, and streamed assistant chunks - so a UI can be wired
Expand All @@ -201,10 +203,15 @@ up later without changing the backend contract.
chat flow.

**Lifespan wiring**: `app/main.py`'s `lifespan` builds the configured `ChatAgent` via
`build_chat_agent(settings.chat)` and a fresh `ChatSessionManager` on startup (`app.chat_agent`
/ `app.state.chat_sessions`), and calls `chat_agent.aclose()` on shutdown to release any held
`build_chat_agent(settings.chat)` and a fresh `ChatSessionManager` on startup. The agent is stored
on `app.chat_agent`, and the session manager on `app.state.chat_sessions`; the websocket route
uses that manager to track active sessions. On shutdown, `chat_agent.aclose()` releases any held
connections.

The WebSocket integration tests use HTTPX2's async `ASGIWebSocketTransport`
(`httpx2[ws]`) to exercise the application without starting a server. They manage
the app lifespan explicitly because the transport does not start it.

**Configuration** (`ChatConfig` in `app/config.py`, all overridable via environment variables):

| Env var | Default | Description |
Expand Down
2 changes: 1 addition & 1 deletion app/api/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ async def chat_websocket(websocket: WebSocket) -> None:
await websocket.accept()

agent: ChatAgent = websocket.app.chat_agent
session_manager: ChatSessionManager = ChatSessionManager()
session_manager: ChatSessionManager = websocket.app.state.chat_sessions
session = await session_manager.create()

await websocket.send_json(Connected(session_id=session.id).model_dump(mode="json"))
Expand Down
23 changes: 6 additions & 17 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from app.redis import get_redis
from app.services.auth import AuthBearer
from app.services.chat_agent import build_chat_agent
from app.services.chat_session import ChatSessionManager
from app.services.scheduler import scheduler_lifespan

templates = Jinja2Templates(directory=Path(__file__).parent.parent / "templates")

Expand All @@ -31,11 +33,9 @@ async def lifespan(app: FastAPI):
app.logger = get_logger()
app.redis = await get_redis()
global_settings.postgres_url.unicode_string()
# Chat service: initialize the pluggable model-client adapter. The session
# manager is now a singleton and will be auto-instantiated on first access.
# See app/services/chat_agent.py to swap the local stub for a real model
# client (OpenAI, Ollama, etc.).
# Initialize the chat agent and per-application session registry.
app.chat_agent = build_chat_agent(global_settings.chat)
app.state.chat_sessions = ChatSessionManager()
try:
# app.postgres_pool = await asyncpg.create_pool(
# dsn=postgres_dsn,
Expand All @@ -45,7 +45,8 @@ async def lifespan(app: FastAPI):
# await app.logger.ainfo(
# "Postgres pool created", idle_size=app.postgres_pool.get_idle_size()
# )
yield
async with scheduler_lifespan():
yield
except Exception as e:
await app.logger.aerror("Error during app startup", error=repr(e))
raise
Expand Down Expand Up @@ -96,16 +97,4 @@ def get_index(request: Request) -> _TemplateResponse:

app = create_app()

# --- Unused/experimental code and TODOs ---
# from apscheduler import AsyncScheduler
# from apscheduler.datastores.sqlalchemy import SQLAlchemyDataStore
# from apscheduler.eventbrokers.redis import RedisEventBroker
# from app.database import engine
# from app.services.scheduler import SchedulerMiddleware
# _scheduler_data_store = SQLAlchemyDataStore(engine, schema="scheduler")
# _scheduler_event_broker = RedisEventBroker(client_or_url=global_settings.redis_url.unicode_string())
# _scheduler_himself = AsyncScheduler(_scheduler_data_store, _scheduler_event_broker)
# app.add_middleware(SchedulerMiddleware, scheduler=_scheduler_himself)
# TODO: every non-GET method should reset cache
# TODO: scheduler tasks needing DB should access connection pool via request
# TODO: https://stackoverflow.com/questions/16053364/make-sure-only-one-worker-launches-the-apscheduler-event-in-a-pyramid-web-app-ru
1 change: 1 addition & 0 deletions app/services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Application service implementations."""
23 changes: 14 additions & 9 deletions app/services/auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Bearer-token authentication and Redis-backed token storage."""

import time

import jwt
Expand All @@ -11,24 +13,27 @@
logger = get_logger()


async def get_from_redis(request: Request, key: str):
async def get_from_redis(request: Request, key: str) -> str | None:
"""Return the Redis value stored under ``key``."""
return await request.app.redis.get(key)


async def set_to_redis(request: Request, key: str, value: str, ex: int):
async def set_to_redis(request: Request, key: str, value: str, ex: int) -> bool:
"""Store ``value`` in Redis for ``ex`` seconds."""
return await request.app.redis.set(key, value, ex=ex)


async def verify_jwt(request: Request, token: str) -> bool:
"""Check whether Redis recognizes the bearer token."""
payload = await get_from_redis(request, token)
return bool(payload)


class AuthBearer(HTTPBearer):
def __init__(self, auto_error: bool = True) -> None:
super().__init__(auto_error=auto_error)
"""Validate bearer credentials against the active Redis token store."""

async def __call__(self, request: Request):
async def __call__(self, request: Request) -> str:
"""Return a valid token or raise an authorization error."""
credentials: HTTPAuthorizationCredentials = await super().__call__(request)
if not credentials:
raise HTTPException(status_code=403, detail="Invalid authorization code.")
Expand All @@ -44,8 +49,8 @@ async def __call__(self, request: Request):
return credentials.credentials


async def create_access_token(user: User, request: Request):
# sourcery skip: avoid-builtin-shadow
async def create_access_token(user: User, request: Request) -> str | None:
"""Sign a user token and store it in Redis until its configured expiry."""
payload = {
"email": user.email,
"expiry": time.time() + global_settings.jwt_expire,
Expand All @@ -55,8 +60,8 @@ async def create_access_token(user: User, request: Request):
payload, str(user.password), algorithm=global_settings.jwt_algorithm
)

_bool = await set_to_redis(
stored = await set_to_redis(
request, token, str(payload), ex=global_settings.jwt_expire
)
if _bool:
if stored:
return token
78 changes: 21 additions & 57 deletions app/services/chat_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from urllib.parse import urlparse

import attrs
import httpx
import httpx2
import orjson

from app.config import ChatConfig
Expand Down Expand Up @@ -49,9 +49,11 @@ class LocalEchoAgent:
"""

def __init__(self, stream_delay_seconds: float = 0.02) -> None:
"""Initialize the delay between streamed words."""
self.stream_delay_seconds = stream_delay_seconds

def _compose_reply(self, messages: list[ChatMessage]) -> str:
"""Compose a canned response to the latest user message."""
last_user = next(
(m.content for m in reversed(messages) if m.role == "user"), ""
)
Expand All @@ -63,26 +65,20 @@ def _compose_reply(self, messages: list[ChatMessage]) -> str:
return f"You said: {last_user!r}. This is a local echo response (stub agent)."

async def stream_reply(self, messages: list[ChatMessage]) -> AsyncIterator[str]:
"""Yield the canned reply one word at a time."""
reply = self._compose_reply(messages)
for word in reply.split(" "):
await asyncio.sleep(self.stream_delay_seconds + random.uniform(0, 0.01))
yield word + " "

async def aclose(self) -> None:
return None
"""Close resources; the local agent holds none."""


def _validate_base_url(_instance: OllamaChatAgent, _attribute: attrs.Attribute, value: str) -> None:
"""Validate that base_url is a valid HTTP(S) URL.

Args:
instance: The OllamaChatAgent instance being initialized.
attribute: The attrs attribute descriptor for base_url.
value: The URL string to validate.

Raises:
ValueError: If base_url is not a valid HTTP(S) URL.
"""
def _validate_base_url(
_instance: OllamaChatAgent, _attribute: attrs.Attribute, value: str
) -> None:
"""Require an absolute HTTP(S) endpoint URL."""
parsed = urlparse(value)
if parsed.scheme not in ("http", "https"):
msg = f"base_url must be HTTP(S), got scheme '{parsed.scheme}' from '{value}'"
Expand All @@ -92,37 +88,15 @@ def _validate_base_url(_instance: OllamaChatAgent, _attribute: attrs.Attribute,
raise ValueError(msg)


def _validate_timeout(_instance: OllamaChatAgent, _attribute: attrs.Attribute, value: float) -> None:
"""Validate that timeout is positive.

Args:
instance: The OllamaChatAgent instance being initialized.
attribute: The attrs attribute descriptor for timeout.
value: The timeout value in seconds.

Raises:
ValueError: If timeout is not positive.
"""
def _validate_timeout(
_instance: OllamaChatAgent, _attribute: attrs.Attribute, value: float
) -> None:
"""Require a positive request timeout."""
if value <= 0:
msg = f"timeout must be positive, got {value}"
raise ValueError(msg)


def _create_httpx_client(instance: OllamaChatAgent) -> httpx.AsyncClient:
"""Factory function to create the httpx.AsyncClient with validated config.

This function is called from __attrs_post_init__ after all field validators
have run, ensuring the client is created with validated configuration.

Args:
instance: The OllamaChatAgent instance being initialized.

Returns:
An initialized httpx.AsyncClient configured with base_url and timeout.
"""
return httpx.AsyncClient(base_url=instance.base_url, timeout=instance.timeout)


@attrs.define(slots=True, eq=False, hash=False)
class OllamaChatAgent:
"""Streams chat completions from an OpenAI-compatible endpoint.
Expand All @@ -132,9 +106,6 @@ class OllamaChatAgent:
a ready-to-swap-in replacement for :class:`LocalEchoAgent` once a real
model should be used.

Attrs Configuration:
- slots=True: Memory-efficient attribute storage (~40-50% reduction)
- eq=False, hash=False: Instances are not comparable (contain async resources)
"""

model: str = attrs.field(
Expand All @@ -160,20 +131,15 @@ class OllamaChatAgent:
"constraints": "Must be positive",
},
)
_client: httpx.AsyncClient = attrs.field(
_client: httpx2.AsyncClient = attrs.field(
init=False,
repr=False,
metadata={"description": "Internal HTTP client for API communication"},
)

def __attrs_post_init__(self) -> None:
"""Initialize the HTTP client after field validation.

This hook is called by attrs after __init__ completes and all field
validators have run. It's used to initialize the internal _client
field which depends on validated configuration.
"""
self._client = _create_httpx_client(self)
"""Create the HTTPX2 client after attrs validates the fields."""
self._client = httpx2.AsyncClient(base_url=self.base_url, timeout=self.timeout)

async def stream_reply(self, messages: list[ChatMessage]) -> AsyncIterator[str]:
"""Stream chat completion responses from the configured model.
Expand All @@ -195,13 +161,11 @@ async def stream_reply(self, messages: list[ChatMessage]) -> AsyncIterator[str]:
async for line in response.aiter_lines():
if not line.startswith("data: ") or line == "data: [DONE]":
continue
try:
data = orjson.loads(line[6:])
content = (
data.get("choices", [{}])[0].get("delta", {}).get("content", "")
)
except Exception:
content = ""
data = orjson.loads(line.removeprefix("data: "))
choices = data.get("choices", [])
if not choices:
continue
content = choices[0].get("delta", {}).get("content", "")
if content:
yield content

Expand Down
16 changes: 12 additions & 4 deletions app/services/chat_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,46 +13,54 @@
import attrs

from app.schemas.chat import ChatMessage
from app.utils.singleton import SingletonMetaNoArgs


@attrs.define(slots=True)
class ChatSession:
"""Conversation history associated with one websocket connection."""

id: UUID = attrs.field(factory=uuid4)
messages: list[ChatMessage] = attrs.field(factory=list)

def add(self, message: ChatMessage) -> None:
"""Append a message to this conversation."""
self.messages.append(message)

def history(self) -> list[ChatMessage]:
"""Return a copy of the conversation history."""
return list(self.messages)


class ChatSessionManager(metaclass=SingletonMetaNoArgs):
class ChatSessionManager:
"""Tracks active chat sessions keyed by their opaque session id.

Implemented as a singleton to ensure exactly one instance per application,
maintaining a consistent registry of all active websocket chat sessions.
Each application lifespan owns its own manager, maintaining a consistent
registry of active websocket chat sessions for that application.
"""

def __init__(self) -> None:
"""Create an empty, lock-protected session registry."""
self._sessions: dict[UUID, ChatSession] = {}
self._lock = asyncio.Lock()

async def create(self) -> ChatSession:
"""Create and register a new conversation."""
session = ChatSession()
async with self._lock:
self._sessions[session.id] = session
return session

async def get(self, session_id: UUID) -> ChatSession | None:
"""Return the matching session, if it is active."""
async with self._lock:
return self._sessions.get(session_id)

async def remove(self, session_id: UUID) -> None:
"""Remove a session from the active registry."""
async with self._lock:
self._sessions.pop(session_id, None)

async def count(self) -> int:
"""Return the number of active sessions."""
async with self._lock:
return len(self._sessions)
Loading
Loading