Spaces:
Paused
Paused
File size: 16,991 Bytes
9792ea7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | # -*- coding: utf-8 -*-
"""The embedding model base class."""
from __future__ import annotations
import asyncio
import inspect
from abc import abstractmethod
from pathlib import Path
from typing import Any, Generic, TypeVar, Type, Union
from pydantic import BaseModel, ConfigDict
from ._embedding_model_card import EmbeddingModelCard
from ._embedding_response import EmbeddingResponse
from ._embedding_usage import EmbeddingUsage
from .._logging import logger
from ..credential import CredentialBase
from ..message import DataBlock, TextBlock
#: Type variable for embedding input elements.
#:
#: Bound to the union of all element shapes the framework supports;
#: each concrete subclass narrows it to its accepted input via
#: ``class Foo(EmbeddingModelBase[str | TextBlock]): ...`` so callers
#: get accurate IDE completion and type-checking on ``__call__``.
#:
#: ``__call__`` accepts ``TextBlock`` and unpacks it to ``.text``
#: before invoking :meth:`_call_api`; therefore ``_call_api``'s input
#: type is intentionally decoupled from :data:`InputT` (it is typed
#: ``list[Any]`` on the base and narrowed by each subclass).
InputT = TypeVar("InputT", bound=Union[str, TextBlock, DataBlock])
class EmbeddingModelBase(Generic[InputT]):
"""Base class for embedding models.
Generic over :data:`InputT` so that text-only subclasses
(``EmbeddingModelBase[str]``) and multimodal subclasses
(``EmbeddingModelBase[str | TextBlock | DataBlock]``) expose the
correct ``inputs`` type to the IDE.
Follows the same pattern as :class:`~agentscope.model.ChatModelBase`:
- ``__call__`` splits inputs into batches of size
:attr:`batch_size`, calls :meth:`_call_api` for each batch
**concurrently** via :func:`asyncio.gather`, and merges the
results. Each batch call is wrapped with retry logic.
- Subclasses only implement :meth:`_call_api` for a **single
batch** β no batching or retry code needed.
- Each subclass may override :meth:`_get_retryable_exceptions` to
declare provider-specific retriable errors.
"""
class Parameters(BaseModel):
"""Provider-specific tunables for embedding models.
Intentionally empty in the base β ``dimensions`` is a contract
property of an embedding model (its output vector size), not a
tunable knob, so it lives directly on the instance via the
required :paramref:`__init__.dimensions` argument. Subclasses
extend this class to expose **non-dimensional** knobs (e.g.
Gemini's ``task_type``, Dashscope's ``text_type``).
``extra="allow"`` is set so old persisted configs (where
``dimensions`` lived in ``parameters``) keep deserialising
without raising; :meth:`EmbeddingModelBase.__init__` extracts
it back out for backward compatibility.
"""
model_config = ConfigDict(extra="allow")
credential: CredentialBase
"""The API credential."""
model: str
"""The embedding model name."""
dimensions: int
"""The output embedding vector dimensions.
Set directly from the :paramref:`__init__.dimensions` argument β
a required, first-class field rather than something derived from
:attr:`parameters`.
"""
context_size: int
"""Maximum input length (in tokens) per single input item."""
batch_size: int
"""Maximum number of input items per API call."""
max_retries: int
"""The maximum number of retries for the underlying API."""
retry_delay: float
"""Seconds to sleep between retry attempts."""
supports_multimodal: bool = False
"""Whether this model instance accepts :class:`DataBlock` inputs in
addition to text. Text-only models keep the default ``False``;
multimodal subclasses must set it to ``True`` (per instance when
routing depends on the model name)."""
def __init__(
self,
credential: CredentialBase,
model: str,
dimensions: int | None,
parameters: BaseModel | None,
context_size: int,
batch_size: int,
max_retries: int,
retry_delay: float,
) -> None:
"""Initialize the embedding model base class.
Args:
credential (`CredentialBase`):
The API credential used for authentication.
model (`str`):
The name of the embedding model.
dimensions (`int | None`):
The output embedding vector dimensions for this
instance. Required and first-class β see the class
docstring for the rationale of keeping ``dimensions``
outside :class:`Parameters`. For backward compatibility
with older configs that stored ``dimensions`` inside
:class:`Parameters`, ``None`` is accepted at the
signature level and is back-filled from
``parameters.dimensions`` when present.
parameters (`BaseModel | None`):
Provider-specific non-dimensional parameters. When
``None``, the default ``Parameters()`` is used.
context_size (`int`):
Maximum input length (in tokens) per single input item.
batch_size (`int`):
Maximum number of input items per API call. When
``__call__`` receives more items, it splits them into
batches and calls :meth:`_call_api` concurrently.
max_retries (`int`):
The maximum number of retries for each batch API call.
Only exceptions listed in
:meth:`_get_retryable_exceptions` count against this
budget.
retry_delay (`float`):
Seconds to sleep between retry attempts.
"""
resolved_parameters = parameters or self.Parameters()
# Backward-compat: older session/KB configs persisted
# ``dimensions`` inside ``parameters``. Promote it to the
# constructor argument when the caller did not pass one
# explicitly, then strip it from the parameters object so it
# never reaches provider-specific request payloads.
param_dump = resolved_parameters.model_dump()
legacy_dimensions = param_dump.pop("dimensions", None)
if dimensions is None:
if legacy_dimensions is None:
raise ValueError(
"dimensions is required: pass it explicitly to "
"EmbeddingModelBase.__init__ or include it in the "
"legacy `parameters` mapping.",
)
dimensions = int(legacy_dimensions)
resolved_parameters = type(resolved_parameters)(**param_dump)
elif legacy_dimensions is not None:
# Both routes set it β explicit constructor wins, strip the
# legacy mirror so it can't drift.
resolved_parameters = type(resolved_parameters)(**param_dump)
if dimensions <= 0:
raise ValueError(
f"dimensions must be a positive integer, got {dimensions}.",
)
self.credential = credential
self.model = model
self.dimensions = dimensions
self.parameters = resolved_parameters
self.context_size = context_size
self.batch_size = batch_size
self.max_retries = max_retries
self.retry_delay = retry_delay
@classmethod
def _get_retryable_exceptions(cls) -> tuple[Type[Exception], ...]:
"""Return exception types that should trigger a retry.
Defaults to an empty tuple (no retries). Subclasses can
override to declare provider-specific retryable exceptions.
"""
return ()
# ------------------------------------------------------------------
# Public API β batching + concurrent retry
# ------------------------------------------------------------------
async def __call__(
self,
inputs: list[InputT],
**kwargs: Any,
) -> EmbeddingResponse:
"""Embed a list of inputs with automatic batching and retry.
The inputs are split into chunks of :attr:`batch_size`. All
chunks are dispatched **concurrently** via
:func:`asyncio.gather`. Each chunk is individually retried up
to ``max_retries`` times on retryable errors. Results are
merged into a single :class:`EmbeddingResponse` preserving the
original input order.
Args:
inputs (`list[InputT]`):
The input data to embed. For text-only models this is
``list[str]``; for multimodal models it is
``list[str | TextBlock | DataBlock]``. Any
:class:`TextBlock` items are transparently unpacked to
their ``.text`` field on entry, so subclasses' batching
and ``_call_api`` only have to handle ``str`` (and
``DataBlock`` for multimodal variants).
**kwargs:
Additional keyword arguments forwarded to
:meth:`_call_api`.
Returns:
`EmbeddingResponse`:
A merged response containing embeddings for all inputs.
"""
if not inputs:
return EmbeddingResponse(
embeddings=[],
usage=EmbeddingUsage(tokens=0, time=0),
)
normalized: list[Any] = [
item.text if isinstance(item, TextBlock) else item
for item in inputs
]
# Split into batches.
batches = [
normalized[i : i + self.batch_size]
for i in range(0, len(normalized), self.batch_size)
]
if len(batches) > 1:
logger.info(
"Embedding %d inputs in %d batches (batch_size=%d) "
"for model %s.",
len(normalized),
len(batches),
self.batch_size,
self.model,
)
# Dispatch all batches concurrently, each with retry.
results: list[EmbeddingResponse] = await asyncio.gather(
*(self._call_with_retry(batch, **kwargs) for batch in batches),
)
return self._merge_responses(results)
# ------------------------------------------------------------------
# Internal β merge multiple batch responses
# ------------------------------------------------------------------
@staticmethod
def _merge_responses(
responses: list[EmbeddingResponse],
) -> EmbeddingResponse:
"""Merge multiple batch :class:`EmbeddingResponse` objects into
one, preserving input order.
Args:
responses (`list[EmbeddingResponse]`):
Batch responses to merge.
Returns:
`EmbeddingResponse`: The merged response.
"""
if len(responses) == 1:
return responses[0]
all_embeddings: list = []
total_tokens = 0
total_time = 0.0
for resp in responses:
all_embeddings.extend(resp.embeddings)
if resp.usage:
total_time += resp.usage.time
if resp.usage.tokens:
total_tokens += resp.usage.tokens
return EmbeddingResponse(
embeddings=all_embeddings,
usage=EmbeddingUsage(
tokens=total_tokens,
time=total_time,
),
source="api",
)
# ------------------------------------------------------------------
# Internal β retry wrapper for a single batch
# ------------------------------------------------------------------
async def _call_with_retry(
self,
inputs: list[Any],
**kwargs: Any,
) -> EmbeddingResponse:
"""Call :meth:`_call_api` with retry logic for a single batch.
Args:
inputs (`list[Any]`):
A single batch of inputs (size β€ ``batch_size``), already
normalised by :meth:`__call__` (any :class:`TextBlock`
items unpacked to their ``.text``). Typed as
``list[Any]`` because the concrete element shape depends
on the subclass β see :meth:`_call_api`.
**kwargs:
Forwarded to :meth:`_call_api`.
"""
retryable = tuple(self._get_retryable_exceptions())
last_error: Exception | None = None
for attempt in range(self.max_retries + 1):
try:
return await self._call_api(inputs, **kwargs)
except Exception as e:
if not isinstance(e, retryable):
raise
last_error = e
if attempt < self.max_retries:
logger.warning(
"Batch attempt %d failed for embedding model "
"%s: %s. Retrying in %.1fs...",
attempt + 1,
self.model,
str(e),
self.retry_delay,
)
await asyncio.sleep(self.retry_delay)
else:
logger.warning(
"All %d attempt(s) failed for a batch of "
"embedding model %s.",
self.max_retries + 1,
self.model,
)
if last_error is not None:
raise last_error
raise RuntimeError(
f"Failed to call embedding model {self.model} after "
f"{self.max_retries + 1} retries.",
)
# ------------------------------------------------------------------
# Abstract β subclasses implement this for a single batch
# ------------------------------------------------------------------
@abstractmethod
async def _call_api(
self,
inputs: list[Any],
**kwargs: Any,
) -> EmbeddingResponse:
"""Call the underlying embedding API for a **single batch**.
Subclasses must implement this method. The batch splitting,
concurrency, and retry logic are handled by :meth:`__call__`
β this method only needs to handle one API call.
.. note::
The parameter is typed ``list[Any]`` rather than
``list[InputT]`` because :meth:`__call__` unpacks
:class:`TextBlock` items to their ``.text`` field *before*
dispatching to this method. The element shape this method
actually receives is therefore subclass-specific
(:data:`InputT` minus :class:`TextBlock`). Subclasses
should override with their concrete narrower type, e.g.
``list[str]`` for text-only models or
``list[str | DataBlock]`` for multimodal ones.
Args:
inputs (`list[Any]`):
A batch of inputs (guaranteed ``len(inputs) <=
self.batch_size``).
**kwargs:
Additional keyword arguments.
Returns:
`EmbeddingResponse`:
The embedding response for this batch.
"""
# ------------------------------------------------------------------
# Model card discovery
# ------------------------------------------------------------------
@classmethod
def list_models(
cls,
custom_yaml_dir: str | None = None,
) -> list[EmbeddingModelCard]:
"""List candidate embedding models from YAML files.
Each concrete subclass should live in its own provider
subdirectory (e.g. ``embedding/_openai/_model.py``) with a
sibling ``_models/`` directory containing YAML files β identical
to the layout used by :class:`~agentscope.model.ChatModelBase`.
Args:
custom_yaml_dir (`str | None`):
Override the YAML directory.
Returns:
`list[EmbeddingModelCard]`:
A list of embedding model cards.
"""
if custom_yaml_dir is None:
subclass_file = Path(inspect.getfile(cls))
yaml_dir = subclass_file.parent / "_models"
else:
yaml_dir = Path(custom_yaml_dir)
if not yaml_dir.is_dir():
return []
yaml_files = list(yaml_dir.glob("*.yaml"))
model_cards = []
for yaml_file in yaml_files:
try:
card = EmbeddingModelCard.from_yaml(
yaml_path=str(yaml_file),
parameter_class=cls.Parameters,
)
model_cards.append(card)
except Exception as e:
logger.warning(
"Failed to load embedding model card %s: %s",
yaml_file,
str(e),
)
continue
return model_cards
|