Skip to content

Implement /chat endpoint#17

Open
leynos wants to merge 4 commits intomainfrom
codex/implement-/chat-endpoint-with-deepseek-model
Open

Implement /chat endpoint#17
leynos wants to merge 4 commits intomainfrom
codex/implement-/chat-endpoint-with-deepseek-model

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 8, 2025

Summary

  • implement simple OpenRouter-backed chat endpoint
  • default to deepseek when model missing
  • test chat endpoint behaviour
  • update integration tests for new logic

Testing

  • ruff check src/bournemouth/resources.py tests/test_resources.py
  • pyright
  • pytest -q

https://chatgpt.com/codex/tasks/task_e_6844d08408f083228c290ec6dace05b7

Summary by Sourcery

Implement full OpenRouter-backed chat functionality and API key storage with proper DB integration, service abstraction, error handling, OpenAPI docs, and updated tests.

New Features:

  • Add POST /chat endpoint to process user messages with optional history and model, call OpenRouter API, and return assistant responses
  • Add POST /auth/openrouter-token endpoint to store and persist users' OpenRouter API keys

Enhancements:

  • Introduce OpenRouterService and chat_with_service wrapper to manage API calls with timeout and error mapping
  • Integrate async database session factory into resources and application setup for DB access
  • Replace placeholder implementations with msgspec-based JSON decoding and structural pattern matching for request validation
  • Add centralized HTTP and unexpected error handlers for consistent JSON error responses

Documentation:

  • Add OpenAPI 3.1 specification for the /chat and /auth/openrouter-token endpoints

Tests:

  • Configure in-memory SQLite async DB fixture and pytest_httpx mocks in integration and unit tests
  • Update login, chat, and token persistence tests to verify successful behaviors against new endpoints

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 8, 2025

Reviewer's Guide

This PR implements a fully functional /chat endpoint backed by the OpenRouterService, including request decoding, history validation, token retrieval from the database, error mapping, and response serialization; it also persists user API keys, refactors the application factory for dependency injection and error handling, defines a reusable OpenRouter service abstraction, adds OpenAPI documentation, and expands both unit and integration tests with in-memory DB fixtures and HTTPX mocks.

Sequence Diagram for /chat Endpoint Processing

sequenceDiagram
    actor User
    participant CR as ChatResource
    participant DB as Database
    participant Helper as "chat_with_service()"
    participant ORS as OpenRouterService
    participant ExtAPI as "OpenRouter External API"

    User->>CR: POST /chat (message, history, model)
    CR->>CR: Decode request & validate history
    CR->>DB: SELECT openrouter_token_enc FROM UserAccount
    DB-->>CR: User's token (or null)
    alt Token Found
        CR->>Helper: chat_with_service(token, history, model)
        Helper->>ORS: chat_completion(token, history, model)
        ORS->>ExtAPI: Request completion
        ExtAPI-->>ORS: Completion response / Error
        alt Successful Completion
            ORS-->>Helper: Completion
            Helper-->>CR: Completion
            CR->>CR: answer = completion.choices[0].message.content
            CR-->>User: HTTP 200 OK {"answer": ...}
        else OpenRouter Timeout from ORS
            ORS-->>Helper: OpenRouterTimeoutError (from OpenRouterAsyncClient)
            Helper-->>CR: OpenRouterServiceTimeoutError
            CR-->>User: HTTP 504 Gateway Timeout
        else OpenRouter Other Error from ORS
            ORS-->>Helper: OpenRouterError (e.g. NetworkError)
            Helper-->>CR: OpenRouterServiceBadGatewayError
            CR-->>User: HTTP 502 Bad Gateway
        end
    else Token Not Found
        CR-->>User: HTTP 400 Bad Request (missing OpenRouter token)
    end
    alt Invalid Request (JSON, message field, history item)
        User->>CR: POST /chat (invalid data)
        CR->>CR: Fail validation
        CR-->>User: HTTP 400 Bad Request
    end
Loading

Sequence Diagram for /auth/openrouter-token Endpoint

sequenceDiagram
    actor User
    participant OTR as OpenRouterTokenResource
    participant DB as Database

    User->>OTR: POST /auth/openrouter-token (api_key)
    OTR->>OTR: Validate api_key
    alt Valid api_key
        OTR->>DB: UPDATE UserAccount SET openrouter_token_enc = api_key.encode()
        DB-->>OTR: Success
        OTR-->>User: HTTP 204 No Content
    else Invalid api_key (not string)
        OTR-->>User: HTTP 400 Bad Request (`api_key` field required)
    end
Loading

Entity Relationship Diagram for UserAccount Changes

erDiagram
    UserAccount {
        string google_sub PK "User's Google Subject ID"
        bytes openrouter_token_enc "Encrypted OpenRouter Token (updated)"
    }
Loading

Class Diagram for API Resource and Request Classes

classDiagram
    class ChatRequest {
        <<msgspec.Struct>>
        +message: str
        +history: list~dict~ | None
        +model: str | None
    }
    class ChatResource {
        - _service: OpenRouterService
        - _session_factory: Callable_AsyncSession
        + __init__(service: OpenRouterService, session_factory: Callable_AsyncSession)
        + on_post(req: Request, resp: Response) void
    }
    class OpenRouterTokenResource {
        - _session_factory: Callable_AsyncSession
        + __init__(session_factory: Callable_AsyncSession)
        + on_post(req: Request, resp: Response) void
    }
    ChatResource ..> ChatRequest : decodes
    ChatResource o-- OpenRouterService : uses
    ChatResource o-- Callable_AsyncSession : uses
    OpenRouterTokenResource o-- Callable_AsyncSession : uses

    class OpenRouterService
    class Callable_AsyncSession {
        <<TypeAlias>>
        Callable[[], AsyncSession]
    }
    class Request
    class Response
Loading

File-Level Changes

Change Details Files
Fully implement /chat POST logic
  • Decode raw JSON with msgspec and validate message field
  • Transform and validate history items into ChatMessage objects
  • Fetch and decode the user’s OpenRouter token from DB
  • Invoke chat_with_service and map timeouts and server errors to HTTPGatewayTimeout/BadGateway
  • Extract assistant’s reply and set resp.media with the answer
src/bournemouth/resources.py
Persist user OpenRouter API key
  • Extract and validate api_key from request body
  • Execute SQLAlchemy update on UserAccount.openrouter_token_enc
  • Commit transaction and return HTTP 204 No Content
src/bournemouth/resources.py
Abstract OpenRouter interactions into service wrapper
  • Implement OpenRouterService with default model, base URL, and from_env factory
  • Define chat_with_service helper to convert client errors into service errors
  • Declare OpenRouterServiceTimeoutError and BadGatewayError classes
src/bournemouth/openrouter_service.py
Refine application setup for DI and error handling
  • Require db_session_factory and accept optional openrouter_service
  • Register ChatResource and OpenRouterTokenResource with dependencies
  • Add handlers for falcon.HTTPError and generic exceptions
src/bournemouth/app.py
Expand tests with fixtures and HTTPX mocks
  • Introduce in-memory SQLite session_factory fixture for DB access
  • Inject db_session_factory into create_app in both unit and integration tests
  • Use pytest_httpx to mock OpenRouter API and assert /chat returns answers
  • Assert token persistence in DB after /auth/openrouter-token
tests/integration/test_auth.py
tests/test_resources.py
Extend OpenRouter model definitions
  • Add reusable Role literal type alias
  • Change ChatMessage.role annotation to use Role
src/bournemouth/openrouter.py
Add OpenAPI spec for chat endpoints
  • Define /chat and /auth/openrouter-token paths, request/response schemas
  • Add ProblemDetails, ChatRequest, and Message components
  • Reference common error response in components
docs/chat-endpoint-openapi.yaml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @leynos - I've reviewed your changes - here's some feedback:

  • Consider returning HTTP 500 instead of HTTP 400 when the OpenRouter API key is missing, since that’s a server configuration issue rather than a bad client request.
  • Extract the OpenRouter client and configuration (API key, default model) into a separate service or dependency to improve testability and decouple environment lookups from the request handler.
  • Add validation or a whitelist for the incoming model parameter to ensure only supported model identifiers are used and prevent invalid requests.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 8, 2025

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @leynos - I've reviewed your changes - here's some feedback:

  • You’re manually decoding and validating the request body in ChatResource.on_post; consider using the ChatRequest msgspec.Struct or a shared validator to centralize schema validation and reduce boilerplate.
  • The db_session_factory fixture is duplicated in both integration and unit test files—moving it into a shared conftest.py will DRY up the test setup.
  • Reading the raw body via req.bounded_stream.read() bypasses Falcon’s built-in request parsing and limits—consider integrating a custom media handler or using req.get_media() with msgspec to enforce size and content-type constraints.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

except OpenRouterServiceBadGatewayError as exc:
raise falcon.HTTPBadGateway(description=str(exc)) from None # pyright: ignore[reportUnknownArgumentType]

answer = completion.choices[0].message.content or ""
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Handle case when completion.choices is empty

Add a check to ensure choices is not empty before accessing choices[0] to prevent IndexError.

Comment thread tests/test_resources.py

@pytest.mark.asyncio
async def test_store_token_not_implemented(app: asgi.App) -> None:
async def test_store_token(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Test /auth/openrouter-token with non-string api_key.

Please add a test where api_key is present but not a string (e.g., integer, boolean, or null), and verify that it returns an HTTPBadRequest with the appropriate error message.

@leynos leynos force-pushed the codex/implement-/chat-endpoint-with-deepseek-model branch from d55871f to c0b0926 Compare June 8, 2025 10:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant