Spaces:
Running
Running
db api online
Browse files- model_service_api.py +52 -3
- requirements.txt +1 -0
model_service_api.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import aiohttp
|
| 2 |
import logging
|
| 3 |
from typing import List, Dict, Optional
|
| 4 |
-
from fastapi import FastAPI, HTTPException, Query
|
| 5 |
from fastapi.responses import JSONResponse
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from datetime import datetime, timedelta
|
|
@@ -71,6 +71,12 @@ cache = {
|
|
| 71 |
"ttl_minutes": 15 # Cache for 15 minutes
|
| 72 |
}
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
class OpenRouterClient:
|
| 75 |
"""Client for interacting with OpenRouter API"""
|
| 76 |
|
|
@@ -111,7 +117,7 @@ class OpenRouterClient:
|
|
| 111 |
params["category"] = category
|
| 112 |
|
| 113 |
try:
|
| 114 |
-
logger.info("Fetching models from OpenRouter API...")
|
| 115 |
async with self.session.get(url, params=params) as response:
|
| 116 |
if response.status != 200:
|
| 117 |
logger.error(f"OpenRouter API returned status {response.status}")
|
|
@@ -194,11 +200,55 @@ async def root():
|
|
| 194 |
"endpoints": {
|
| 195 |
"free_models": "/api/free-models",
|
| 196 |
"free_models_by_category": "/api/free-models?category=programming",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
"health": "/health"
|
| 198 |
},
|
| 199 |
"description": "This API fetches models from OpenRouter and filters for free models (prompt=0, completion=0)"
|
| 200 |
}
|
| 201 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
@app.get("/api/free-models", response_model=FreeModelsResponse)
|
| 203 |
async def get_free_models(
|
| 204 |
category: Optional[str] = Query(None, description="Filter by category (e.g., 'programming', 'chat')")
|
|
@@ -304,7 +354,6 @@ async def health_check():
|
|
| 304 |
}
|
| 305 |
)
|
| 306 |
|
| 307 |
-
|
| 308 |
@app.get("/ping")
|
| 309 |
async def ping():
|
| 310 |
"""Ping endpoint to check API status"""
|
|
|
|
| 1 |
import aiohttp
|
| 2 |
import logging
|
| 3 |
from typing import List, Dict, Optional
|
| 4 |
+
from fastapi import FastAPI, HTTPException, Query, Path
|
| 5 |
from fastapi.responses import JSONResponse
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from datetime import datetime, timedelta
|
|
|
|
| 71 |
"ttl_minutes": 15 # Cache for 15 minutes
|
| 72 |
}
|
| 73 |
|
| 74 |
+
# Supported categories
|
| 75 |
+
SUPPORTED_CATEGORIES = [
|
| 76 |
+
"chat", "reasoning", "vision", "coding", "lightweight",
|
| 77 |
+
"roleplay", "marketing", "programming", "image", "text"
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
class OpenRouterClient:
|
| 81 |
"""Client for interacting with OpenRouter API"""
|
| 82 |
|
|
|
|
| 117 |
params["category"] = category
|
| 118 |
|
| 119 |
try:
|
| 120 |
+
logger.info(f"Fetching models from OpenRouter API{f' with category: {category}' if category else ''}...")
|
| 121 |
async with self.session.get(url, params=params) as response:
|
| 122 |
if response.status != 200:
|
| 123 |
logger.error(f"OpenRouter API returned status {response.status}")
|
|
|
|
| 200 |
"endpoints": {
|
| 201 |
"free_models": "/api/free-models",
|
| 202 |
"free_models_by_category": "/api/free-models?category=programming",
|
| 203 |
+
"category_route": "/api/category/{category}/free-models",
|
| 204 |
+
"free_model_names": "/api/free-models/names",
|
| 205 |
+
"specific_model": "/api/free-models/{model_id}",
|
| 206 |
+
"supported_categories": "/api/categories",
|
| 207 |
"health": "/health"
|
| 208 |
},
|
| 209 |
"description": "This API fetches models from OpenRouter and filters for free models (prompt=0, completion=0)"
|
| 210 |
}
|
| 211 |
|
| 212 |
+
@app.get("/api/categories")
|
| 213 |
+
async def get_supported_categories():
|
| 214 |
+
"""Get list of supported categories"""
|
| 215 |
+
return {
|
| 216 |
+
"success": True,
|
| 217 |
+
"message": "List of supported categories",
|
| 218 |
+
"categories": SUPPORTED_CATEGORIES,
|
| 219 |
+
"usage": "Use these categories with /api/category/{category}/free-models"
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
@app.get("/api/category/{category}/free-models", response_model=FreeModelsResponse)
|
| 223 |
+
async def get_free_models_by_category(
|
| 224 |
+
category: str = Path(..., description="Category to filter by (e.g., chat, coding, vision)")
|
| 225 |
+
):
|
| 226 |
+
"""Get free models filtered by specific category"""
|
| 227 |
+
|
| 228 |
+
# Validate category
|
| 229 |
+
if category.lower() not in [cat.lower() for cat in SUPPORTED_CATEGORIES]:
|
| 230 |
+
raise HTTPException(
|
| 231 |
+
status_code=400,
|
| 232 |
+
detail=f"Unsupported category '{category}'. Supported categories: {', '.join(SUPPORTED_CATEGORIES)}"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
try:
|
| 236 |
+
free_models = await get_free_models_data(category=category.lower())
|
| 237 |
+
|
| 238 |
+
return FreeModelsResponse(
|
| 239 |
+
success=True,
|
| 240 |
+
message=f"Successfully retrieved {len(free_models)} free models in category '{category}'",
|
| 241 |
+
count=len(free_models),
|
| 242 |
+
models=free_models,
|
| 243 |
+
filtered_at=datetime.now().isoformat()
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
except HTTPException:
|
| 247 |
+
raise
|
| 248 |
+
except Exception as e:
|
| 249 |
+
logger.error(f"Error in get_free_models_by_category: {str(e)}")
|
| 250 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 251 |
+
|
| 252 |
@app.get("/api/free-models", response_model=FreeModelsResponse)
|
| 253 |
async def get_free_models(
|
| 254 |
category: Optional[str] = Query(None, description="Filter by category (e.g., 'programming', 'chat')")
|
|
|
|
| 354 |
}
|
| 355 |
)
|
| 356 |
|
|
|
|
| 357 |
@app.get("/ping")
|
| 358 |
async def ping():
|
| 359 |
"""Ping endpoint to check API status"""
|
requirements.txt
CHANGED
|
@@ -2,3 +2,4 @@ aiohttp==3.11.13
|
|
| 2 |
uvicorn==0.34.0
|
| 3 |
fastapi==0.115.5
|
| 4 |
pydantic==2.10.3
|
|
|
|
|
|
| 2 |
uvicorn==0.34.0
|
| 3 |
fastapi==0.115.5
|
| 4 |
pydantic==2.10.3
|
| 5 |
+
dotenv==0.9.9
|