Spaces:
Paused
Paused
File size: 17,560 Bytes
f3bcb28 | 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 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | """PostgreSQL Model Registry Adapter.
Architecture Hexagonale: Implémentation persistante du ModelRegistryPort
utilisant PostgreSQL pour le stockage du catalogue de modèles.
Ce module fournit:
- Stockage persistant des modèles
- Synchronisation avec providers externes
- Cache local pour performance
- Versioning des modèles
"""
from datetime import datetime
from typing import Any
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from backend.ports.model_registry import (
ModelRegistryPort,
ModelInfo,
ModelPricing,
ModelLimits,
ModelValidation,
ProviderType,
ModelStatus,
ModelCapability,
)
class PostgresModelRegistryAdapter(ModelRegistryPort):
"""
PostgreSQL-backed model registry implementation.
Stores model catalog in database with caching layer.
Supports dynamic model discovery and versioning.
"""
def __init__(
self,
session_factory: Any,
table_name: str = "model_registry",
cache_ttl_seconds: int = 300,
):
"""
Initialize PostgreSQL adapter.
Args:
session_factory: SQLAlchemy async session factory
table_name: Name of the model registry table
cache_ttl_seconds: Cache TTL in seconds
"""
self._session_factory = session_factory
self._table_name = table_name
self._cache_ttl = cache_ttl_seconds
# Local cache
self._cache: dict[str, ModelInfo] = {}
self._cache_time: datetime | None = None
self._aliases: dict[str, str] = {}
async def _get_session(self) -> AsyncSession:
"""Get a database session."""
return self._session_factory()
async def _ensure_table(self, session: AsyncSession) -> None:
"""Ensure the model registry table exists."""
await session.execute(
text(
f"""
CREATE TABLE IF NOT EXISTS {self._table_name} (
model_id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
provider VARCHAR(50) NOT NULL,
provider_model_id VARCHAR(255) NOT NULL,
description TEXT,
capabilities JSONB DEFAULT '[]',
input_per_million DECIMAL(10, 6) DEFAULT 0,
output_per_million DECIMAL(10, 6) DEFAULT 0,
max_context_tokens INTEGER DEFAULT 0,
max_output_tokens INTEGER DEFAULT 0,
max_images INTEGER,
status VARCHAR(50) DEFAULT 'available',
tags JSONB DEFAULT '[]',
metadata JSONB DEFAULT '{{}}',
base_url VARCHAR(500),
added_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
deprecated_at TIMESTAMP
)
"""
)
)
await session.commit()
async def _refresh_cache(self) -> None:
"""Refresh the local cache from database."""
now = datetime.now()
if (
self._cache_time
and (now - self._cache_time).total_seconds() < self._cache_ttl
):
return
async with await self._get_session() as session:
await self._ensure_table(session)
result = await session.execute(
text(
f"""
SELECT model_id, name, provider, provider_model_id, description,
capabilities, input_per_million, output_per_million,
max_context_tokens, max_output_tokens, max_images,
status, tags, metadata, base_url, added_at, updated_at, deprecated_at
FROM {self._table_name}
"""
)
)
self._cache.clear()
for row in result.fetchall():
model = self._row_to_model(row)
self._cache[model.model_id] = model
self._cache_time = now
def _row_to_model(self, row: Any) -> ModelInfo:
"""Convert a database row to ModelInfo."""
capabilities = [
ModelCapability(c)
for c in (row[5] or [])
if c in [cap.value for cap in ModelCapability]
]
return ModelInfo(
model_id=row[0],
name=row[1],
provider=ProviderType(row[2]),
provider_model_id=row[3],
description=row[4] or "",
capabilities=capabilities,
pricing=ModelPricing(
input_per_million=float(row[6] or 0),
output_per_million=float(row[7] or 0),
),
limits=ModelLimits(
max_context_tokens=row[8] or 0,
max_output_tokens=row[9] or 0,
max_images=row[10],
),
status=ModelStatus(row[11]) if row[11] else ModelStatus.AVAILABLE,
tags=row[12] or [],
metadata=row[13] or {},
base_url=row[14],
added_at=row[15],
updated_at=row[16],
deprecated_at=row[17],
)
async def list_models(
self,
provider: ProviderType | None = None,
capability: ModelCapability | None = None,
status: ModelStatus | None = None,
tags: list[str] | None = None,
) -> list[ModelInfo]:
"""List models with optional filters."""
await self._refresh_cache()
results = list(self._cache.values())
if provider:
results = [m for m in results if m.provider == provider]
if capability:
results = [m for m in results if capability in m.capabilities]
if status:
results = [m for m in results if m.status == status]
if tags:
results = [m for m in results if any(t in m.tags for t in tags)]
return sorted(results, key=lambda m: m.name)
async def get_model(
self,
model_id: str,
) -> ModelInfo | None:
"""Get a model by ID."""
await self._refresh_cache()
if model_id in self._cache:
return self._cache[model_id]
# Try alias
resolved = await self.resolve_model_alias(model_id)
if resolved and resolved in self._cache:
return self._cache[resolved]
return None
async def get_model_by_provider_id(
self,
provider: ProviderType,
provider_model_id: str,
) -> ModelInfo | None:
"""Get a model by provider ID."""
await self._refresh_cache()
for model in self._cache.values():
if (
model.provider == provider
and model.provider_model_id == provider_model_id
):
return model
return None
async def validate_model(
self,
model_id: str,
capability: ModelCapability | None = None,
) -> ModelValidation:
"""Validate a model."""
model = await self.get_model(model_id)
if not model:
suggested = None
for m in self._cache.values():
if model_id.lower() in m.model_id.lower():
suggested = m.model_id
break
return ModelValidation(
valid=False,
model_id=model_id,
reason=f"Model '{model_id}' not found",
suggested_model=suggested,
)
if model.status == ModelStatus.UNAVAILABLE:
return ModelValidation(
valid=False,
model_id=model_id,
provider=model.provider,
reason="Model is currently unavailable",
)
if model.status == ModelStatus.DEPRECATED:
suggested = model.metadata.get("replacement")
return ModelValidation(
valid=True,
model_id=model_id,
provider=model.provider,
reason="Model is deprecated",
suggested_model=suggested,
)
if capability and capability not in model.capabilities:
return ModelValidation(
valid=False,
model_id=model_id,
provider=model.provider,
reason=f"Model does not support capability: {capability.value}",
)
return ModelValidation(
valid=True,
model_id=model_id,
provider=model.provider,
)
async def resolve_model_alias(
self,
alias: str,
) -> str | None:
"""Resolve a model alias."""
if alias in self._cache:
return alias
return self._aliases.get(alias)
async def register_model(
self,
model: ModelInfo,
) -> ModelInfo:
"""Register a new model."""
async with await self._get_session() as session:
await self._ensure_table(session)
capabilities = [c.value for c in model.capabilities]
now = datetime.now()
await session.execute(
text(
f"""
INSERT INTO {self._table_name} (
model_id, name, provider, provider_model_id, description,
capabilities, input_per_million, output_per_million,
max_context_tokens, max_output_tokens, max_images,
status, tags, metadata, base_url, added_at, updated_at
) VALUES (
:model_id, :name, :provider, :provider_model_id, :description,
:capabilities, :input_per_million, :output_per_million,
:max_context_tokens, :max_output_tokens, :max_images,
:status, :tags, :metadata, :base_url, :added_at, :updated_at
)
ON CONFLICT (model_id) DO UPDATE SET
name = EXCLUDED.name,
provider = EXCLUDED.provider,
provider_model_id = EXCLUDED.provider_model_id,
description = EXCLUDED.description,
capabilities = EXCLUDED.capabilities,
input_per_million = EXCLUDED.input_per_million,
output_per_million = EXCLUDED.output_per_million,
max_context_tokens = EXCLUDED.max_context_tokens,
max_output_tokens = EXCLUDED.max_output_tokens,
max_images = EXCLUDED.max_images,
status = EXCLUDED.status,
tags = EXCLUDED.tags,
metadata = EXCLUDED.metadata,
base_url = EXCLUDED.base_url,
updated_at = EXCLUDED.updated_at
"""
),
{
"model_id": model.model_id,
"name": model.name,
"provider": model.provider.value,
"provider_model_id": model.provider_model_id,
"description": model.description,
"capabilities": capabilities,
"input_per_million": model.pricing.input_per_million,
"output_per_million": model.pricing.output_per_million,
"max_context_tokens": model.limits.max_context_tokens,
"max_output_tokens": model.limits.max_output_tokens,
"max_images": model.limits.max_images,
"status": model.status.value,
"tags": model.tags,
"metadata": model.metadata,
"base_url": model.base_url,
"added_at": now,
"updated_at": now,
},
)
await session.commit()
# Update cache
model.added_at = now
model.updated_at = now
self._cache[model.model_id] = model
return model
async def update_model(
self,
model_id: str,
status: ModelStatus | None = None,
pricing: ModelPricing | None = None,
limits: ModelLimits | None = None,
tags: list[str] | None = None,
) -> ModelInfo:
"""Update a model."""
model = await self.get_model(model_id)
if not model:
raise ValueError(f"Model {model_id} not found")
async with await self._get_session() as session:
updates = ["updated_at = NOW()"]
params: dict[str, Any] = {"model_id": model_id}
if status:
updates.append("status = :status")
params["status"] = status.value
model.status = status
if pricing:
updates.append("input_per_million = :input_per_million")
updates.append("output_per_million = :output_per_million")
params["input_per_million"] = pricing.input_per_million
params["output_per_million"] = pricing.output_per_million
model.pricing = pricing
if limits:
updates.append("max_context_tokens = :max_context_tokens")
updates.append("max_output_tokens = :max_output_tokens")
updates.append("max_images = :max_images")
params["max_context_tokens"] = limits.max_context_tokens
params["max_output_tokens"] = limits.max_output_tokens
params["max_images"] = limits.max_images
model.limits = limits
if tags:
updates.append("tags = :tags")
params["tags"] = tags
model.tags = tags
await session.execute(
text(
f"""
UPDATE {self._table_name}
SET {", ".join(updates)}
WHERE model_id = :model_id
"""
),
params,
)
await session.commit()
model.updated_at = datetime.now()
self._cache[model_id] = model
return model
async def deprecate_model(
self,
model_id: str,
suggested_replacement: str | None = None,
) -> ModelInfo:
"""Deprecate a model."""
model = await self.get_model(model_id)
if not model:
raise ValueError(f"Model {model_id} not found")
now = datetime.now()
metadata = model.metadata.copy()
if suggested_replacement:
metadata["replacement"] = suggested_replacement
async with await self._get_session() as session:
await session.execute(
text(
f"""
UPDATE {self._table_name}
SET status = 'deprecated',
deprecated_at = :deprecated_at,
updated_at = :updated_at,
metadata = :metadata
WHERE model_id = :model_id
"""
),
{
"model_id": model_id,
"deprecated_at": now,
"updated_at": now,
"metadata": metadata,
},
)
await session.commit()
model.status = ModelStatus.DEPRECATED
model.deprecated_at = now
model.updated_at = now
model.metadata = metadata
self._cache[model_id] = model
return model
async def remove_model(
self,
model_id: str,
) -> bool:
"""Remove a model."""
async with await self._get_session() as session:
result = await session.execute(
text(
f"""
DELETE FROM {self._table_name}
WHERE model_id = :model_id
"""
),
{"model_id": model_id},
)
await session.commit()
if result.rowcount > 0:
self._cache.pop(model_id, None)
return True
return False
async def discover_local_models(
self,
provider: ProviderType,
base_url: str | None = None,
) -> list[ModelInfo]:
"""Discover local models (not supported in PostgreSQL adapter)."""
# Local discovery is not applicable for database storage
return []
async def sync_provider_models(
self,
provider: ProviderType,
) -> int:
"""Sync models from a provider (no-op for PostgreSQL)."""
return 0
async def estimate_cost(
self,
model_id: str,
input_tokens: int,
output_tokens: int,
) -> float:
"""Estimate cost for a request."""
model = await self.get_model(model_id)
if not model:
return 0.0
input_cost = (input_tokens / 1_000_000) * model.pricing.input_per_million
output_cost = (output_tokens / 1_000_000) * model.pricing.output_per_million
return input_cost + output_cost
async def get_pricing(
self,
model_id: str,
) -> ModelPricing | None:
"""Get pricing for a model."""
model = await self.get_model(model_id)
return model.pricing if model else None
def add_alias(self, alias: str, model_id: str) -> None:
"""Add a model alias."""
self._aliases[alias] = model_id
def invalidate_cache(self) -> None:
"""Invalidate the local cache."""
self._cache.clear()
self._cache_time = None
|