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
69 changes: 69 additions & 0 deletions packages/gen/gen_ai_hub/_base_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""
Shared base model and response-validation helpers for all `gen_ai_hub models.

The `SdkBaseModel` sets `extra="forbid"`, which rejects unknown parameters during validation.
The `validate_response` and `validate_response_as` helpers overwrite this setting to `extra="allow"`
for response validation.
"""

from typing import Any, Type, TypeVar

from pydantic import BaseModel, ConfigDict, TypeAdapter

T = TypeVar("T", bound=BaseModel)


class SdkBaseModel(BaseModel):
"""
Abstract base model that extends Pydantic's BaseModel.

- `extra="forbid"` prevents unexpected fields from being accepted or sent,
since the external API is strict about allowed parameters.
- `exclude_none=True` ensures optional fields that were not provided are
omitted from the payload instead of being serialized as None.
- `by_alias=True` guarantees aliases are used during serialization, which is
required because some API field names conflict with Pydantic's built-ins.

This enforces consistent and safe serialization behavior across all
derived models.
"""
model_config = ConfigDict(
extra="forbid",
frozen=False,
)

def model_dump(self, **kwargs):
"""Dumps the model to a dictionary with default settings."""
kwargs.setdefault("by_alias", True)
kwargs.setdefault("exclude_none", True)
return super().model_dump(**kwargs)


def validate_response(model: Type[T], data: Any) -> T:
"""Validate a response payload into `model`.

Sets the `extra=allow` flag, which includes unknown fields into the model.

Args:
model: A :class:`pydantic.BaseModel` subclass to validate into.
data: The response payload to validate.

Returns:
An instance of ``model``.
"""
return model.model_validate(data, extra="allow")


def validate_response_as(type_: Any, data: Any) -> Any:
"""Validate a response payload into an arbitrary type.

Only use this for types that cannot be validated via `validate_response`.

Args:
type_: Any type accepted by :class:`pydantic.TypeAdapter`.
data: The response payload to validate.

Returns:
The validated value.
"""
return TypeAdapter(type_).validate_python(data, extra="allow")
4 changes: 0 additions & 4 deletions packages/gen/gen_ai_hub/batch_service/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from .base import ABCBaseModel, ResponseBaseModel
from .request import BatchCreateRequest, BatchInput, BatchOutput, BatchSpec
from .response import (
BatchStatus,
Expand All @@ -16,9 +15,6 @@
)

__all__ = [
# base
"ABCBaseModel",
"ResponseBaseModel",
# request
"BatchCreateRequest",
"BatchInput",
Expand Down
31 changes: 0 additions & 31 deletions packages/gen/gen_ai_hub/batch_service/models/base.py

This file was deleted.

10 changes: 5 additions & 5 deletions packages/gen/gen_ai_hub/batch_service/models/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

from pydantic import Field

from gen_ai_hub.batch_service.models.base import ABCBaseModel
from gen_ai_hub._base_model import SdkBaseModel


class BatchInput(ABCBaseModel):
class BatchInput(SdkBaseModel):
"""Input configuration for a batch job.

Points to the ``.jsonl`` file in an object store that contains the
Expand All @@ -23,7 +23,7 @@ class BatchInput(ABCBaseModel):
uri: str = Field(..., description="Input file URI (must be a .jsonl file)")


class BatchOutput(ABCBaseModel):
class BatchOutput(SdkBaseModel):
"""Output configuration for a batch job.

Points to the directory in an object store where results will be written
Expand All @@ -37,7 +37,7 @@ class BatchOutput(ABCBaseModel):
uri: str = Field(..., description="Output directory URI")


class BatchSpec(ABCBaseModel):
class BatchSpec(SdkBaseModel):
"""Specification of the LLM to use for a batch job.

:param provider: LLM provider name as registered in SAP AI Core
Expand All @@ -52,7 +52,7 @@ class BatchSpec(ABCBaseModel):
model: str = Field(..., description="Model name")


class BatchCreateRequest(ABCBaseModel):
class BatchCreateRequest(SdkBaseModel):
"""Request body sent to ``POST /llm-batch-service/v1/batches``.

Describes a new batch processing job: where to read input from, where to
Expand Down
24 changes: 12 additions & 12 deletions packages/gen/gen_ai_hub/batch_service/models/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from pydantic import Field

from gen_ai_hub.batch_service.models.base import ResponseBaseModel
from gen_ai_hub._base_model import SdkBaseModel


class BatchStatus(str, Enum):
Expand All @@ -29,7 +29,7 @@ class BatchStatus(str, Enum):
CANCELLING = "CANCELLING"


class BatchCreateResponse(ResponseBaseModel):
class BatchCreateResponse(SdkBaseModel):
"""Response returned by ``POST /llm-batch-service/v1/batches``.

Confirms that the batch job has been accepted and provides the assigned
Expand All @@ -51,7 +51,7 @@ class BatchCreateResponse(ResponseBaseModel):
message: Optional[str] = Field(None, description="Human-readable status message")


class BatchSummary(ResponseBaseModel):
class BatchSummary(SdkBaseModel):
"""Summary entry for a single batch job as returned in a list response.

:param id: Unique identifier (UUID) of the batch job.
Expand All @@ -73,7 +73,7 @@ class BatchSummary(ResponseBaseModel):
status: Optional[str] = Field(None, description="Current job status")


class BatchListResponse(ResponseBaseModel):
class BatchListResponse(SdkBaseModel):
"""Response returned by ``GET /llm-batch-service/v1/batches``.

Contains a count and a list of batch job summaries for the current
Expand All @@ -89,7 +89,7 @@ class BatchListResponse(ResponseBaseModel):
resources: Optional[list[BatchSummary]] = Field(None, description="List of batch job summaries")


class BatchStatusDetail(ResponseBaseModel):
class BatchStatusDetail(SdkBaseModel):
"""Status block embedded inside :class:`BatchDetailResponse`.

:param current_status: The job's current lifecycle status.
Expand All @@ -108,7 +108,7 @@ class BatchStatusDetail(ResponseBaseModel):
message: Optional[str] = Field(None, description="Optional human-readable status message")


class BatchInputDetail(ResponseBaseModel):
class BatchInputDetail(SdkBaseModel):
"""Input configuration as returned in a batch detail response.

:param uri: Object-store URI of the input ``.jsonl`` file.
Expand All @@ -118,7 +118,7 @@ class BatchInputDetail(ResponseBaseModel):
uri: Optional[str] = Field(None, description="Input file URI")


class BatchOutputDetail(ResponseBaseModel):
class BatchOutputDetail(SdkBaseModel):
"""Output configuration as returned in a batch detail response.

:param uri: Object-store URI of the output directory.
Expand All @@ -128,7 +128,7 @@ class BatchOutputDetail(ResponseBaseModel):
uri: Optional[str] = Field(None, description="Output directory URI")


class BatchDetailResponse(ResponseBaseModel):
class BatchDetailResponse(SdkBaseModel):
"""Response returned by ``GET /llm-batch-service/v1/batches/{batch_id}``.

Provides the full configuration and current status of a specific batch job.
Expand Down Expand Up @@ -161,7 +161,7 @@ class BatchDetailResponse(ResponseBaseModel):
status: Optional[BatchStatusDetail] = Field(None, description="Current status details")


class BatchStatusResponse(ResponseBaseModel):
class BatchStatusResponse(SdkBaseModel):
"""Response returned by ``GET /llm-batch-service/v1/batches/{batch_id}/status``.

:param current_status: The job's current lifecycle status.
Expand All @@ -180,7 +180,7 @@ class BatchStatusResponse(ResponseBaseModel):
message: Optional[str] = Field(None, description="Optional human-readable status message")


class BatchCancelResponse(ResponseBaseModel):
class BatchCancelResponse(SdkBaseModel):
"""Response returned by ``PATCH /llm-batch-service/v1/batches/{batch_id}/cancel``.

Confirms that the cancellation request has been accepted. The job will
Expand All @@ -199,7 +199,7 @@ class BatchCancelResponse(ResponseBaseModel):
message: Optional[str] = Field(None, description="Human-readable confirmation message")


class BatchDeleteResponse(ResponseBaseModel):
class BatchDeleteResponse(SdkBaseModel):
"""Response returned by ``DELETE /llm-batch-service/v1/batches/{batch_id}``.

Confirms that the batch job record has been deleted. Only jobs in a
Expand All @@ -218,7 +218,7 @@ class BatchDeleteResponse(ResponseBaseModel):
message: Optional[str] = Field(None, description="Human-readable confirmation message")


class ErrorResponse(ResponseBaseModel):
class ErrorResponse(SdkBaseModel):
"""Error response body returned by the batch service on 4xx/5xx responses.

:param request_id: Unique request identifier, useful for tracing the
Expand Down
25 changes: 13 additions & 12 deletions packages/gen/gen_ai_hub/batch_service/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from gen_ai_hub.proxy import get_proxy_client
from gen_ai_hub.batch_service.exceptions import BatchServiceError
from gen_ai_hub.batch_service.models.request import BatchCreateRequest, BatchInput, BatchOutput, BatchSpec
from gen_ai_hub._base_model import validate_response
from gen_ai_hub.batch_service.models.response import (
BatchCreateResponse,
BatchListResponse,
Expand Down Expand Up @@ -154,7 +155,7 @@ def create(
)
if not response.is_success:
_handle_http_error(response)
return BatchCreateResponse(**response.json())
return validate_response(BatchCreateResponse, response.json())

def list(
self,
Expand All @@ -173,7 +174,7 @@ def list(
)
if not response.is_success:
_handle_http_error(response)
return BatchListResponse(**response.json())
return validate_response(BatchListResponse, response.json())

def get(
self,
Expand All @@ -195,7 +196,7 @@ def get(
)
if not response.is_success:
_handle_http_error(response)
return BatchDetailResponse(**response.json())
return validate_response(BatchDetailResponse, response.json())

def get_status(
self,
Expand All @@ -217,7 +218,7 @@ def get_status(
)
if not response.is_success:
_handle_http_error(response)
return BatchStatusResponse(**response.json())
return validate_response(BatchStatusResponse, response.json())

def cancel(
self,
Expand All @@ -239,7 +240,7 @@ def cancel(
)
if not response.is_success:
_handle_http_error(response)
return BatchCancelResponse(**response.json())
return validate_response(BatchCancelResponse, response.json())

def delete(
self,
Expand All @@ -261,7 +262,7 @@ def delete(
)
if not response.is_success:
_handle_http_error(response)
return BatchDeleteResponse(**response.json())
return validate_response(BatchDeleteResponse, response.json())

# ------------------------------------------------------------------
# Async API
Expand Down Expand Up @@ -307,7 +308,7 @@ async def acreate(
)
if not response.is_success:
_handle_http_error(response)
return BatchCreateResponse(**response.json())
return validate_response(BatchCreateResponse, response.json())

async def alist(
self,
Expand All @@ -326,7 +327,7 @@ async def alist(
)
if not response.is_success:
_handle_http_error(response)
return BatchListResponse(**response.json())
return validate_response(BatchListResponse, response.json())

async def aget(
self,
Expand All @@ -348,7 +349,7 @@ async def aget(
)
if not response.is_success:
_handle_http_error(response)
return BatchDetailResponse(**response.json())
return validate_response(BatchDetailResponse, response.json())

async def aget_status(
self,
Expand All @@ -370,7 +371,7 @@ async def aget_status(
)
if not response.is_success:
_handle_http_error(response)
return BatchStatusResponse(**response.json())
return validate_response(BatchStatusResponse, response.json())

async def acancel(
self,
Expand All @@ -392,7 +393,7 @@ async def acancel(
)
if not response.is_success:
_handle_http_error(response)
return BatchCancelResponse(**response.json())
return validate_response(BatchCancelResponse, response.json())

async def adelete(
self,
Expand All @@ -414,7 +415,7 @@ async def adelete(
)
if not response.is_success:
_handle_http_error(response)
return BatchDeleteResponse(**response.json())
return validate_response(BatchDeleteResponse, response.json())

# ------------------------------------------------------------------
# Resource management
Expand Down
Loading
Loading