Skip to content
Draft
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,11 @@ playground/.gitignore
playground/requirements.txt
run.sh
.claude
.cursor
bruno
docs/.astro
docs/node_modules
docs/.cache
docs/package-lock.json
oauth2-proxy.cfg
compose.*.yml
2 changes: 1 addition & 1 deletion api/domain/user/_userrepository.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ async def has_admin_user(self) -> bool:
async def create_user(
self,
email: str,
password: str,
role_id: int,
password: str | None = None,
name: str | None = None,
sub: str | None = None,
iss: str | None = None,
Expand Down
1 change: 1 addition & 0 deletions api/endpoints/admin/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async def create_token(
token_id, token = await global_context.identity_access_manager.create_token(
postgres_session=postgres_session,
user_id=body.user,
email=body.email,
name=body.name,
expires=body.expires,
)
Expand Down
16 changes: 13 additions & 3 deletions api/helpers/_identityaccessmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,14 +546,24 @@ async def get_organizations(

return organizations

async def create_token(self, postgres_session: AsyncSession, user_id: int, name: str, expires: int | None = None) -> tuple[int, str]:
async def create_token(
self, postgres_session: AsyncSession, name: str, expires: int | None = None, user_id: int | None = None, email: str | None = None
) -> tuple[int, str]:
assert user_id is not None or email is not None, "user_id or email is required"
assert user_id is None or email is None, "user_id and email cannot be provided together"

if self.key_max_expiration_days:
if expires is None:
expires = int(dt.datetime.now(tz=dt.UTC).timestamp()) + self.key_max_expiration_days * 86400
elif expires > int(dt.datetime.now(tz=dt.UTC).timestamp()) + self.key_max_expiration_days * 86400:
raise InvalidTokenExpirationException(detail=f"Token expiration timestamp cannot be greater than {self.key_max_expiration_days} days from now.") # fmt: off

result = await postgres_session.execute(statement=select(UserTable).where(UserTable.id == user_id))
statement = select(UserTable)
if user_id is not None:
statement = statement.where(UserTable.id == user_id)
if email is not None:
statement = statement.where(UserTable.email == email)
result = await postgres_session.execute(statement=statement)
try:
user = result.scalar_one()
except NoResultFound:
Expand Down Expand Up @@ -600,7 +610,7 @@ async def refresh_token(self, postgres_session: AsyncSession, user_id: int, name
expires = int((datetime.now() + timedelta(seconds=self.playground_session_duration)).timestamp())

# Create a new token
token_id, token = await self.create_token(postgres_session, user_id, name, expires=expires)
token_id, token = await self.create_token(postgres_session=postgres_session, user_id=user_id, name=name, expires=expires)

return token_id, token

Expand Down
5 changes: 3 additions & 2 deletions api/infrastructure/fastapi/schemas/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
class CreateUserBody(BaseModel):
email: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1), Field(..., description="The user email.")]
name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] | None = Field(default=None, description="The user name.")
password: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] = Field(..., description="The user password.")
role: int = Field(..., description="The role ID.")
password: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] | None = Field(default=None, description="The user password.")
role: int = Field(..., description="The role ID.") # @TODO: replace by role_id
organization: int | None = Field(default=None, description="The organization ID.")
budget: float | None = Field(default=None, description="The budget.")
expires: int | None = Field(default=None, description="The expiration timestamp.")
priority: int = Field(default=0, ge=0, description="The user priority. Higher value means higher priority.")

@field_validator("expires", mode="before")
def must_be_future(cls, expires):
# @TODO: replace by Pydantic FutureDatetime
if isinstance(expires, int):
if expires <= int(dt.datetime.now(tz=dt.UTC).timestamp()):
raise ValueError("Wrong timestamp, must be in the future.")
Expand Down
2 changes: 1 addition & 1 deletion api/infrastructure/postgres/_postgresusersrepository.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ async def has_admin_user(self) -> bool:
async def create_user(
self,
email: str,
password: str,
role_id: int,
password: str | None = None,
name: str | None = None,
sub: str | None = None,
iss: str | None = None,
Expand Down
17 changes: 13 additions & 4 deletions api/schemas/admin/tokens.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import datetime as dt
from typing import Literal

from pydantic import Field, constr, field_validator
from pydantic import Field, constr, field_validator, model_validator

from api.schemas import BaseModel

Expand All @@ -12,18 +12,27 @@ class TokensResponse(BaseModel):


class CreateToken(BaseModel):
name: constr(strip_whitespace=True, min_length=1)
user: int = Field(description="User ID to create the token for another user (by default, the current user). Required CREATE_USER permission.") # fmt: off
expires: int | None = Field(None, description="Timestamp in seconds")
name: constr(strip_whitespace=True, min_length=1) = Field(..., description="The name of the token.")
user: int | None = Field(None, description="User ID of the user to create the token for. Optional if email is provided.")
email: str | None = Field(None, description="Email of the user to create the token for. Optional if user is provided.")
expires: int | None = Field(None, description="Timestamp in seconds for the token expiration.")

@field_validator("expires", mode="before")
def must_be_future(cls, expires):
# @TODO: replace by Pydantic FutureDatetime
if isinstance(expires, int):
if expires <= int(dt.datetime.now(tz=dt.UTC).timestamp()):
raise ValueError("Wrong timestamp, must be in the future.")

return expires

@model_validator(mode="after")
def validate_user_or_email(self):
if self.user is None and self.email is None:
raise ValueError("Either user or email must be provided.")

return self


class Token(BaseModel):
object: Literal["token"] = "token"
Expand Down
24 changes: 11 additions & 13 deletions api/schemas/core/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
# utils ----------------------------------------------------------------------------------------------------------------------------------------------


def custom_validation_error(url: str | None = None):
def custom_validation_error(suffix: str = ""):
"""
Decorator to override Pydantic ValidationError to change error message.

Expand Down Expand Up @@ -63,7 +63,7 @@ def resolve_model_for_error(model: type[BaseModel], loc: tuple[Any, ...]):
break

current_model = next_model
documentation_url = f"{base_url}#{current_model.__name__.lower()}"
documentation_url = f"{base_url}#{current_model.__name__.lower()}{suffix}"

return documentation_url

Expand Down Expand Up @@ -145,8 +145,6 @@ class Model(ConfigBaseModel):
serve the same type of model (text-generation or text-embeddings-inference, etc.). We recommend that all providers of a model serve exactly the same
model, otherwise users may receive responses of varying quality. For embedding models, the API verifies that all providers output vectors of the
same dimension. You can define the load balancing strategy between the model's providers. By default, it is random.

For more information to configure model providers, see the [ModelProvider section](#modelprovider).
"""

name: constr(strip_whitespace=True, min_length=1, max_length=64) = Field(..., description="Unique name exposed to clients when selecting the model.", examples=["gpt-4o"]) # fmt: off
Expand Down Expand Up @@ -269,13 +267,13 @@ class EmptyDependency(ConfigBaseModel):

@custom_validation_error()
class Dependencies(ConfigBaseModel):
albert: AlbertDependency | None = Field(default=None, description="**[DEPRECATED]** See the [AlbertDependency section](#albertdependency) for more information.") # fmt: off
celery: CeleryDependency | None = Field(default=None, description="**[DEPRECATED]** See the [CeleryDependency section](#celerydependency) for more information.") # fmt: off
elasticsearch: ElasticsearchDependency | None = Field(default=None, description="See the [ElasticsearchDependency section](#elasticsearchdependency) for more information.") # fmt: off
marker: MarkerDependency | None = Field(default=None, description="**[DEPRECATED]** See the [MarkerDependency section](#markerdependency) for more information.") # fmt: off
postgres: PostgresDependency = Field(..., description="See the [PostgresDependency section](#postgresdependency) for more information.") # fmt: off
redis: RedisDependency = Field(..., description="See the [RedisDependency section](#redisdependency) for more information.") # fmt: off
sentry: SentryDependency | None = Field(default=None, description="See the [SentryDependency section](#sentrydependency) for more information.") # fmt: off
albert: AlbertDependency | None = Field(default=None, json_schema_extra={"deprecated": True}) # fmt: off
celery: CeleryDependency | None = Field(default=None, json_schema_extra={"deprecated": True}) # fmt: off
elasticsearch: ElasticsearchDependency | None = Field(default=None, description="Elasticsearch is an optional dependency of OpenGateLLM. Elasticsearch is used as a vector store. If this dependency is provided, all documents endpoint are enabled.") # fmt: off
marker: MarkerDependency | None = Field(default=None, json_schema_extra={"deprecated": True}) # fmt: off
postgres: PostgresDependency = Field(..., description="Postgres is a required dependency of OpenGateLLM to store API data.") # fmt: off
redis: RedisDependency = Field(..., description="Redis is a required dependency of OpenGateLLM to store rate limiting counters and performance metrics.") # fmt: off
sentry: SentryDependency | None = Field(default=None, description="Sentry is an optional dependency of OpenGateLLM. Sentry helps you identify, diagnose, and fix errors in real-time.") # fmt: off

@model_validator(mode="after")
def complete_celery(self):
Expand Down Expand Up @@ -345,7 +343,7 @@ class Tokenizer(StrEnum):
TIKTOKEN_O200K_BASE = "tiktoken_o200k_base"


@custom_validation_error(url="https://docs.opengatellm.org/configuration/configuration_file#settings")
@custom_validation_error()
class Settings(ConfigBaseModel):
"""
General settings configuration fields.
Expand Down Expand Up @@ -381,7 +379,7 @@ class Settings(ConfigBaseModel):
swagger_redoc_url: str = Field(default="/redoc", pattern=r"^/", description="Redoc URL of swagger UI, see https://fastapi.tiangolo.com/tutorial/metadata for more information.") # fmt: off

# auth
auth_master_key: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] = Field(default="changeme", description="[DEPRECATED] Master key for the API. It should be a random string with at least 32 characters. This key has all permissions and cannot be modified or deleted. This key is used to create the first role and the first user.") # fmt: off
auth_master_key: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] = Field(default="changeme", description="[DEPRECATED] Master key for the API. It should be a random string with at least 32 characters. This key has all permissions and cannot be modified or deleted. This key is used to create the first role and the first user.", json_schema_extra={"deprecated": True}) # fmt: off
auth_secret_key: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] | None = Field(default=None, description="Secret key for the API. It should be a random string with at least 32 characters. This key is used to encrypt user tokens, watch out if you modify the secret key, you'll need to update all user API keys. If not provided, the master key will be used.") # fmt: off
auth_default_username: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] = Field(default="admin", description="Username of the admin user created at startup.") # fmt: off
auth_default_password: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] = Field(default="changeme", description="Password of the admin user created at startup.") # fmt: off
Expand Down
2 changes: 1 addition & 1 deletion api/use_cases/admin/users/_createuserusecase.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
class CreateUserCommand:
user_id: int
email: str
password: str
role_id: int
password: str | None = None
name: str | None = None
organization_id: int | None = None
budget: float | None = None
Expand Down
8 changes: 7 additions & 1 deletion compose.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ services:
ports:
- "${API_PORT:-8000}:8000"
volumes:
- "${CONFIG_FILE:-./config.yml}:/config.yml:ro" # outside the container, do not change this line
- "${CONFIG_FILE:-./config.yml}:/config.yml:ro"
depends_on:
redis:
condition: service_healthy
Expand All @@ -27,6 +27,12 @@ services:
- "${PLAYGROUND_PORT:-8501}:8501"
volumes:
- "./${CONFIG_FILE:-config.yml}:/config.yml:ro"
healthcheck:
test: [ "CMD-SHELL", "curl -sf http://localhost:8501/ping || exit 1" ]
interval: 5s
timeout: 5s
retries: 10
start_period: 30s
depends_on:
redis:
condition: service_healthy
Expand Down
4 changes: 3 additions & 1 deletion config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ dependencies:
index_name: opengatellm
index_language: english
number_of_shards: 1
index_name: "opengatellm"
number_of_replicas: 0
hosts: "http://${ELASTICSEARCH_HOST:-localhost}:${ELASTICSEARCH_PORT:-9200}"
basic_auth:
Expand Down Expand Up @@ -85,6 +84,9 @@ settings:
# search_multi_agents_reranker_model: my-model

playground_opengatellm_url: ${OPENGATELLM_URL}
# playground_sso_enabled: False
# playground_sso_opengatellm_admin_api_key: ${SSO_OPENGATELLM_ADMIN_API_KEY}
# playground_sso_opengatellm_default_role_id: 1
# playground_default_model: my-model
# playground_theme_has_background: True
# playground_theme_accent_color: purple
Expand Down
Loading