Skip to content

Commit

Permalink
feat: introduce Customizable Base URLs for API Providers (#524)
Browse files Browse the repository at this point in the history
* feat(custom-base-url): add support for custom base URL configuration

- Introduced a `custom_base_url` field to the `Account` model in `account_config.py` for providers that allow custom base URLs.
- Updated `EditAccountDialog` in `account_dialog.py` to include a new input field for the custom base URL and adjusted the UI to reflect this change.
- Modified `Provider` class in `provider.py` to include an `allow_custom_base_url` attribute, enabling custom base URL configuration for specific providers.
- Updated provider configurations for `mistralai`, `openai`, and `openrouter` to support custom base URLs.
- Adjusted OpenAIEngine logic to prioritize the custom base URL over the default provider base URL if provided.

* refactor(account_dialog): improve code structure in EditAccountDialog

- Removed `TYPE_CHECKING` imports and directly imported `Provider`.
- Refactored the `EditAccountDialog` class to improve clarity and maintainability:
  - Introduced type hints for method parameters and return types.
  - Improved method names and added docstrings for better readability.
  - Split large methods into smaller, more focused methods.
  - Added error messages for form validation as comments for translators.
  - Reduced code duplication by consolidating similar code blocks.
  - Revised organization and API key fields handling for clarity.

* feat(account_dialog): enhance validation and focus control

- Introduced a regex pattern `CUSTOM_BASE_URL_PATTERN` for validating custom base URLs.
- Changed `get_selected_provider` method into a `provider` property for enhanced code readability.
- Updated `_validate_form` to return a tuple of error message and associated field.
- Added focus control to invalid form fields to enhance user experience by directing attention to the error.
- Refactor form validation to include custom base URL validation.

* Update basilisk/config/account_config.py

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* style(pre-commit.ci): auto fixes from pre-commit hooks

for more information, see https://pre-commit.ci

* Update basilisk/config/account_config.py

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* refactor(config): centralize `CUSTOM_BASE_URL_PATTERN` for unified URL validation

- Move the `CUSTOM_BASE_URL_PATTERN` regex from `account_dialog.py` to `account_config.py`.
- Update the `Account` class definition to use this centralized pattern for `custom_base_url`.
- Adjust imports in `__init__.py` and `account_dialog.py` to utilize the centralized `CUSTOM_BASE_URL_PATTERN`.

* refactor(account_dialog): update type annotations to Python 3.10+ syntax

Replaced 'Optional[T]' with 'T | None' for type hinting in the account_dialog.py file. This change modernizes the code to make use of the Python 3.10+ feature which improves readability.

* feat(account_dialog): show default base URL

Enhanced the account dialog to display the default base URL when available, aiding in customization clarity.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 15, 2025
1 parent 4b3e89c commit 9f87065
Show file tree
Hide file tree
Showing 5 changed files with 289 additions and 102 deletions.
9 changes: 8 additions & 1 deletion basilisk/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
"""Configuration module for Basilisk."""

from .account_config import Account, AccountManager, AccountOrganization
from .account_config import (
CUSTOM_BASE_URL_PATTERN,
Account,
AccountManager,
AccountOrganization,
)
from .account_config import get_account_config as accounts
from .config_enums import (
AccountSource,
Expand All @@ -27,6 +32,8 @@
"conf",
"ConversationProfile",
"conversation_profiles",
"CUSTOM_BASE_URL_PATTERN",
"get_account_source_labels",
"KeyStorageMethodEnum",
"LogLevelEnum",
"ReleaseChannelEnum",
Expand Down
12 changes: 12 additions & 0 deletions basilisk/config/account_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import logging
import re
from functools import cache, cached_property
from os import getenv
from typing import Annotated, Any, Iterable, Optional, Union
Expand Down Expand Up @@ -38,6 +39,10 @@

log = logging.getLogger(__name__)

CUSTOM_BASE_URL_PATTERN = re.compile(
r"^https?://[\w.-]+(?::\d{1,5})?(?:/[\w-]+)*/?$"
)


class AccountOrganization(BaseModel):
"""Manage organization key for an account."""
Expand Down Expand Up @@ -131,6 +136,11 @@ class Account(BaseModel):
organizations: Optional[list[AccountOrganization]] = Field(default=None)
active_organization_id: Optional[UUID4] = Field(default=None)
source: AccountSource = Field(default=AccountSource.CONFIG, exclude=True)
custom_base_url: Optional[str] = Field(
default=None,
pattern=CUSTOM_BASE_URL_PATTERN,
description="Custom base URL for the API provider. Must be a valid HTTP/HTTPS URL.",
)

def __init__(self, **data: Any):
"""Initialize an account instance. If an error occurs, log the error and raise an exception."""
Expand Down Expand Up @@ -186,6 +196,8 @@ def validate_api_key(
if not value:
raise ValueError("API key not found in keyring")
return SecretStr(value)
elif not data["provider"].require_api_key and value is None:
return None
else:
raise ValueError("Invalid API key storage method")

Expand Down
Loading

0 comments on commit 9f87065

Please sign in to comment.