Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
7763bf4
1
Parent(s): c384ef1
fix gitignore, app and logger, etc
Browse filesFiles changed (5)
- .gitignoreAdded+133
- Dockerfile+2-1
- app.py+436-282
- logger.pyAdded+164
- pyproject.toml+4-3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFESTpip-log.txtpip-delete-this-directory.txt
# Virtual Environment.venv/venv/ENV/env/.virtualenv
# PyInstaller*.manifest*.spec
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# IDEs.idea/.vscode/*.swp*.swo*~.DS_Store
# Jupyter Notebook.ipynb_checkpoints*.ipynb
# PyCharm.idea/*.iml*.iws
# Logs*.loglogs/agi.log
# Environment variables.env.env.local.env.*.local*.env
# Database*.db*.sqlite*.sqlite3
# Model files (often large)*.bin*.gguf*.safetensorsmodels/checkpoints/
# Docker.dockerignoredocker-compose.override.yml
# OS.DS_StoreThumbs.dbDesktop.ini$RECYCLE.BIN/*.cab*.msi*.msix*.msm*.msp*.lnk
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# Temporary files*.tmp*.temptmp/temp/
#*.minimaltests/*.mddocs/48 unmodified lines495051525354552 unmodified lines58596061626348 unmodified lines&& rm -rf /var/lib/apt/lists/*# Install Python packagesRUN pip3 install --no-cache-dir fastapi uvicorn requests pydantic duckduckgo-search beautifulsoup4 lxml --break-system-packages# Create non-root userRUN useradd -m -u 1000 user && \2 unmodified lines# Copy application codeCOPY --chown=user:user app.py /home/user/app.pyUSER userWORKDIR /home/user48 unmodified lines495051525354552 unmodified lines5859606162636448 unmodified lines&& rm -rf /var/lib/apt/lists/*# Install Python packagesRUN pip3 install --no-cache-dir fastapi uvicorn aiohttp pydantic duckduckgo-search beautifulsoup4 lxml --break-system-packages# Create non-root userRUN useradd -m -u 1000 user && \2 unmodified lines# Copy application codeCOPY --chown=user:user app.py /home/user/app.pyCOPY --chown=user:user logger.py /home/user/logger.pyUSER userWORKDIR /home/user
1 unmodified line23456789101112131415161718192021222324252627282 unmodified lines3132333435363738394041424314 unmodified lines58596061626317 unmodified lines8182838485868788895 unmodified lines95969798991001011021031041051061071081 unmodified line1101111121131141158 unmodified lines1241251261271281291301311321331341351361371 unmodified line1391401411421431441451461471481491501511521531541551561571582 unmodified lines1611621631641651661671681691701711721731741751762 unmodified lines17918018118218318418518618718818919019119219319419519619719819916 unmodified lines2162172182192202212223 unmodified lines226227228229230231115 unmodified lines3473483493503513523533543553563573583593603613623633643653663673684 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342413 unmodified lines4384394404414424434444454464474484498 unmodified lines4584594604614624634644656 unmodified lines4724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155166 unmodified lines5235245255265275285295305315325335345355365375385395405415425435445455465475485495506 unmodified lines55755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364422 unmodified lines6676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357363 unmodified lines74074174274374474574674774812 unmodified lines7617627637647657667672 unmodified lines7707717727737747757767777787797807817827837847857867877887897907917927937947957967977983 unmodified lines8028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408414 unmodified lines8468478488498508518528538548558568578588598608618628638648658668671 unmodified lineimport signalimport osimport timefrom typing import Optional, Dictfrom dataclasses import dataclassfrom collections import OrderedDictimport requestsfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.openapi.utils import get_openapifrom pydantic import BaseModel, Fieldfrom duckduckgo_search import DDGSfrom bs4 import BeautifulSoupapp = FastAPI(title="AGI Multi-Model API",description="""**Dynamic Multi-Model LLM API with Web Search Capabilities**This API provides:* 🔄 Dynamic model switching between multiple LLM models* 💬 OpenAI-compatible chat completions* 🌐 Web-augmented chat with real-time search* 📊 Model management and status monitoring## Available Models- **deepseek-chat** (default): General purpose conversational model2 unmodified lines- **deepseek-coder**: Specialized coding assistance- **llama-7b**: Lightweight and fast responses## Quick Start1. Check available models: `GET /models`2. Switch model (optional): `POST /switch-model`3. Chat: `POST /v1/chat/completions`4. Chat with web search: `POST /v1/web-chat/completions`""",version="0.0.1.2025.12.04",contact={"name": "API Support","email": "support@example.com",14 unmodified lines"name": "chat","description": "Chat completion endpoints (OpenAI-compatible)",},{"name": "documentation","description": "API documentation and OpenAPI specification",17 unmodified lines"llama-7b": "TheBloke/Llama-2-7B-Chat-GGUF:llama-2-7b-chat.Q4_K_M.gguf",}# ConfigurationMAX_CACHED_MODELS = 2 # Maximum number of models to keep in memoryBASE_PORT = 8080 # Starting port for llama-server instances@dataclass5 unmodified linesport: inturl: strlast_used: floatclass ModelCache:"""In-memory LRU cache for loaded models.Manages multiple llama-server processes, each on a different port.Automatically evicts least recently used models when cache is full."""def __init__(self, max_size: int = MAX_CACHED_MODELS):1 unmodified lineself.cache: OrderedDict[str, CachedModel] = OrderedDict()self.port_counter = BASE_PORTself.used_ports = set()def _get_next_port(self) -> int:"""Get next available port for a model."""8 unmodified lines"""Release a port back to the pool."""self.used_ports.discard(port)def _evict_lru(self):"""Evict the least recently used model."""if not self.cache:return# Get the first (oldest) itemmodel_name, cached_model = self.cache.popitem(last=False)print(f"Evicting model from cache: {model_name}")# Stop the processtry:1 unmodified lineos.killpg(os.getpgid(cached_model.process.pid), signal.SIGTERM)else:cached_model.process.terminate()cached_model.process.wait(timeout=10)except Exception as e:print(f"Error stopping model {model_name}: {e}")try:if os.name != 'nt':os.killpg(os.getpgid(cached_model.process.pid), signal.SIGKILL)else:cached_model.process.kill()except:pass# Release the portself._release_port(cached_model.port)time.sleep(1)def get(self, model_name: str) -> Optional[CachedModel]:"""Get a model from cache, updating its last used time."""2 unmodified linescached_model.last_used = time.time()# Move to end (most recently used)self.cache.move_to_end(model_name)print(f"Cache hit for model: {model_name}")return cached_modelprint(f"Cache miss for model: {model_name}")return Nonedef put(self, model_name: str, model_id: str, process: subprocess.Popen, port: int):"""Add a model to the cache."""# Evict if cache is fullwhile len(self.cache) >= self.max_size:self._evict_lru()url = f"http://localhost:{port}"cached_model = CachedModel(2 unmodified linesprocess=process,port=port,url=url,last_used=time.time())self.cache[model_name] = cached_modelprint(f"Cached model: {model_name} on port {port}")def clear(self):"""Clear all cached models."""print("Clearing model cache...")for model_name, cached_model in list(self.cache.items()):try:if os.name != 'nt':os.killpg(os.getpgid(cached_model.process.pid), signal.SIGTERM)else:cached_model.process.terminate()cached_model.process.wait(timeout=10)except:try:if os.name != 'nt':16 unmodified lines"name": name,"port": model.port,"url": model.url,"last_used": model.last_used}for name, model in self.cache.items()]3 unmodified lines# Global statecurrent_model = "deepseek-chat" # Default modelmodel_cache = ModelCache(max_size=MAX_CACHED_MODELS)class ModelSwitchRequest(BaseModel):115 unmodified linesmodel: str = Field(..., description="New active model name")def start_llama_server(model_id: str, port: int) -> subprocess.Popen:"""Start llama-server with specified model on a specific port."""cmd = ["llama-server","-hf", model_id,"--host", "0.0.0.0","--port", str(port),"-c", "2048", # Context size"-t", "4", # CPU threads (adjust based on cores)"-ngl", "0", # GPU layers (0 for CPU-only)"--cont-batching", # Enable continuous batching for speed"-b", "512", # Batch size]print(f"Starting llama-server with model: {model_id} on port {port}")print("This may take 2-3 minutes to download and load the model...")process = subprocess.Popen(cmd,4 unmodified linesbufsize=1)# Wait for server to be ready (increased timeout for model download)max_retries = 300 # 5 minutesserver_url = f"http://localhost:{port}"for i in range(max_retries):# Check if process diedif process.poll() is not None:stdout, _ = process.communicate()print(f"llama-server exited with code {process.returncode}")print(f"Output: {stdout}")raise RuntimeError("llama-server process died")try:# Try root endpoint instead of /healthresponse = requests.get(f"{server_url}/", timeout=2)if response.status_code in [200, 404]: # 404 is ok, means server is upprint(f"llama-server ready after {i+1} seconds")return processexcept requests.exceptions.ConnectionError:# Server not ready yetpassexcept Exception:# Other errors, keep waitingpasstime.sleep(1)raise RuntimeError("llama-server failed to start within 5 minutes")@app.on_event("startup")async def startup_event():"""Start with default model and cache it."""global current_modelmodel_id = AVAILABLE_MODELS[current_model]port = model_cache._get_next_port()process = start_llama_server(model_id, port)model_cache.put(current_model, model_id, process, port)print(f"Started with default model: {current_model}")@app.on_event("shutdown")async def shutdown_event():"""Clean shutdown - clear all cached models."""model_cache.clear()@app.get(13 unmodified lines- List of all available models"""return {"status": "AGI Multi-Model API with dynamic model switching and web search","current_model": current_model,"available_models": list(AVAILABLE_MODELS.keys())}@app.get("/models",response_model=ModelsResponse,8 unmodified linesReturns:- current_model: The model currently in use- available_models: Array of all available model namesUse this endpoint to see which models you can switch to."""return {"current_model": current_model,6 unmodified linesresponse_model=ModelSwitchResponse,tags=["models"],summary="Switch Active Model",description="Switch to a different LLM model. Uses caching for instant switching to recently used models.",responses={200: {"description": "Model switched successfully","content": {"application/json": {"example": {"message": "Switched to model: deepseek-coder (from cache)","model": "deepseek-coder"}}}},400: {"description": "Invalid model name","content": {"application/json": {"example": {"detail": "Model 'invalid-model' not found. Available: ['deepseek-chat', 'mistral-7b', ...]"}}}}})async def switch_model(request: ModelSwitchRequest):"""Switch to a different LLM model with intelligent caching.**How it works:**1. Checks if requested model is already active (no switch needed)2. Checks cache for the model (instant switch if cached)3. If not cached, loads the model (may take 2-3 minutes)**Caching:**- Up to 2 models kept in memory- LRU (Least Recently Used) eviction policy- Each model runs on a separate port- Instant switching between cached models"""global current_model6 unmodified linesif request.model_name == current_model:return {"message": f"Already using model: {current_model}", "model": current_model}# Try to get from cachecached_model = model_cache.get(request.model_name)if cached_model:# Model is cached, instant switchcurrent_model = request.model_namereturn {"message": f"Switched to model: {current_model} (from cache)","model": current_model}# Model not cached, need to load itmodel_id = AVAILABLE_MODELS[request.model_name]port = model_cache._get_next_port()try:process = start_llama_server(model_id, port)model_cache.put(request.model_name, model_id, process, port)current_model = request.model_namereturn {"message": f"Switched to model: {current_model} (newly loaded)","model": current_model}except Exception as e:6 unmodified lines"/v1/chat/completions",tags=["chat"],summary="Chat Completions",description="OpenAI-compatible chat completions endpoint. Send messages and get AI-generated responses.",responses={200: {"description": "Successful response","content": {"application/json": {"example": {"id": "chatcmpl-123","object": "chat.completion","created": 1677652288,"model": "deepseek-chat","choices": [{"index": 0,"message": {"role": "assistant","content": "Hello! How can I help you today?"},"finish_reason": "stop"}]}}}},500: {"description": "LLM server error"}})async def chat_completions(request: ChatCompletionRequest):"""OpenAI-compatible chat completions endpoint.This endpoint forwards your request to the currently active LLM modeland returns the response in OpenAI-compatible format.**Message Format:**```json{"messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello!"}],"max_tokens": 256,"temperature": 0.7}```**Supported Roles:**- `system`: Sets the behavior of the assistant- `user`: User messages- `assistant`: Assistant responses (for multi-turn conversations)"""try:# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:raise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-serverresponse = requests.post(f"{cached_model.url}/v1/chat/completions",json={"messages": request.messages,"max_tokens": request.max_tokens,"temperature": request.temperature,},timeout=300)response.raise_for_status()return response.json()except requests.exceptions.RequestException as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")def search_web(query: str, max_results: int = 5) -> list[dict]:"""Search the web using DuckDuckGo and return results."""try:with DDGS() as ddgs:results = list(ddgs.text(query, max_results=max_results))return resultsexcept Exception as e:print(f"Search error: {e}")return []22 unmodified lines"/v1/web-chat/completions",tags=["chat"],summary="Web-Augmented Chat Completions",description="Chat completions enhanced with real-time web search. The last user message is used as a search query.",responses={200: {"description": "Successful response with web search metadata","content": {"application/json": {"example": {"id": "chatcmpl-123","object": "chat.completion","created": 1677652288,"model": "deepseek-chat","choices": [{"index": 0,"message": {"role": "assistant","content": "Based on recent search results, here's what I found..."},"finish_reason": "stop"}],"web_search": {"query": "latest AI developments","results_count": 5,"sources": ["https://example.com/1", "https://example.com/2"]}}}}},400: {"description": "No user message found"},500: {"description": "LLM server or search error"}})async def web_chat_completions(request: WebChatRequest):"""Chat completions with real-time web search augmentation.**How it works:**1. Extracts the last user message as the search query2. Performs a web search using DuckDuckGo3. Injects search results into the LLM context4. Returns the AI response with source citations**Use cases:**- Current events and news- Recent information beyond the model's training data- Fact-checking with web sources- Research with live data**Example:**```json{"messages": [{"role": "user", "content": "What's the latest news about SpaceX?"}],"max_tokens": 512,"max_search_results": 5}```The response includes a `web_search` field with metadata about sources used."""try:# Get the last user message as search query3 unmodified linessearch_query = user_messages[-1].get("content", "")# Perform web searchprint(f"Searching web for: {search_query}")search_results = search_web(search_query, request.max_search_results)# Format search results as contextweb_context = format_search_context(search_query, search_results)12 unmodified linesAlways cite sources when using information from the search results."""}# Insert system message before the last user messageaugmented_messages.insert(-1, system_prompt)# Get current model from cache2 unmodified linesraise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server with augmented contextresponse = requests.post(f"{cached_model.url}/v1/chat/completions",json={"messages": augmented_messages,"max_tokens": request.max_tokens,"temperature": request.temperature,},timeout=300)response.raise_for_status()result = response.json()# Add metadata about search resultsresult["web_search"] = {"query": search_query,"results_count": len(search_results),"sources": [r.get("href", "") for r in search_results if r.get("href")]}return resultexcept requests.exceptions.RequestException as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")except Exception as e:raise HTTPException(status_code=500, detail=f"Error: {str(e)}")3 unmodified lines"/cache/info",tags=["models"],summary="Get Cache Information",description="Returns information about the model cache, including cached models and cache statistics.")async def get_cache_info():"""Get information about the in-memory model cache.Returns:- max_size: Maximum number of models that can be cached- current_size: Current number of cached models- cached_models: List of currently cached models with their metadata**Example Response:**```json{"max_size": 2,"current_size": 2,"cached_models": [{"name": "deepseek-chat","port": 8080,"url": "http://localhost:8080","last_used": 1234567890.123},{"name": "mistral-7b","port": 8081,"url": "http://localhost:8081","last_used": 1234567895.456}]}```"""return model_cache.get_cache_info()@app.get(4 unmodified linesinclude_in_schema=False)async def get_openapi_spec():"""Export the OpenAPI specification for this API.This endpoint returns the complete OpenAPI 3.0 specification that can be used with:- API documentation tools (Swagger UI, ReDoc)- Code generators (openapi-generator, swagger-codegen)- API testing tools (Postman, Insomnia)- SDK generationSave this to a file and use it with tools like:```bash# Generate Python clientopenapi-generator generate -i openapi.json -g python -o ./client# Generate TypeScript clientopenapi-generator generate -i openapi.json -g typescript-fetch -o ./client```"""return app.openapi()1 unmodified line234567891011121314151617181920212223242526272829303132333435362 unmodified lines3940414243444546474849505152535455565758596014 unmodified lines7576777879808182838417 unmodified lines1021031041051061071081091101111121135 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222231 unmodified line2252262272282292302312328 unmodified lines2412422432442452462472482492502512522532541 unmodified line2562572582592602612622632642652662672682692702712722732742752762772782 unmodified lines2812822832842852862872882892902912922932942952962 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432516 unmodified lines3423433443453463473483493503513 unmodified lines355356357358359360361362363364365115 unmodified lines4814824834844854864874884894904914924934944954964974984995005015025035045055065075084 unmodified lines51351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962013 unmodified lines6346356366376386396406416426436446456466476486496506516526536546556566576586596606618 unmodified lines6706716726736746756 unmodified lines6826836846856866876886896906916926936946956966976986 unmodified lines7057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357366 unmodified lines74374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182222 unmodified lines8458468478488498508518528538548558568578588598603 unmodified lines86486586686786886987087187212 unmodified lines8858868878888898902 unmodified lines8938948958968978988999009019029039049059069079089099109119129139149159169179189199203 unmodified lines92492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110124 unmodified lines101710181019102010211 unmodified lineimport signalimport osimport timeimport asynciofrom typing import Optional, Dict, Listfrom dataclasses import dataclass, fieldfrom collections import OrderedDictfrom datetime import datetime, timedeltaimport hashlibimport aiohttpfrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.openapi.utils import get_openapifrom pydantic import BaseModel, Fieldfrom duckduckgo_search import DDGSfrom bs4 import BeautifulSoupfrom logger import get_loggerlogger = get_logger(__name__)app = FastAPI(title="AGI Multi-Model API",description="""**High-Performance Dynamic Multi-Model LLM API with Web Search**This API provides:* 🔄 Dynamic model switching with intelligent caching* 💬 OpenAI-compatible chat completions* 🌐 Web-augmented chat with real-time search* 📊 Model management and performance monitoring* ⚡ Async/await architecture for maximum throughput## Available Models- **deepseek-chat** (default): General purpose conversational model2 unmodified lines- **deepseek-coder**: Specialized coding assistance- **llama-7b**: Lightweight and fast responses## Performance Features- Parallel model loading- Connection pooling for HTTP requests- Web search result caching- Background model preloading- Request queuing to prevent overload- Real-time performance metrics## Quick Start1. Check available models: `GET /models`2. Switch model (optional): `POST /switch-model`3. Chat: `POST /v1/chat/completions`4. Chat with web search: `POST /v1/web-chat/completions`5. View metrics: `GET /metrics`""",version="0.1.0.2026.01.24",contact={"name": "API Support","email": "support@example.com",14 unmodified lines"name": "chat","description": "Chat completion endpoints (OpenAI-compatible)",},{"name": "monitoring","description": "Performance metrics and monitoring",},{"name": "documentation","description": "API documentation and OpenAPI specification",17 unmodified lines"llama-7b": "TheBloke/Llama-2-7B-Chat-GGUF:llama-2-7b-chat.Q4_K_M.gguf",}# Configuration - now environment-variable drivenMAX_CACHED_MODELS = int(os.getenv("MAX_CACHED_MODELS", "2"))BASE_PORT = int(os.getenv("BASE_PORT", "8080"))PRELOAD_MODELS = os.getenv("PRELOAD_MODELS", "").split(",") if os.getenv("PRELOAD_MODELS") else []WEB_SEARCH_CACHE_TTL = int(os.getenv("WEB_SEARCH_CACHE_TTL", "3600")) # 1 hourREQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "300")) # 5 minutes@dataclass5 unmodified linesport: inturl: strlast_used: floatload_time: float = 0.0request_count: int = 0total_latency: float = 0.0@dataclassclass PerformanceMetrics:"""Performance metrics for monitoring."""total_requests: int = 0total_switches: int = 0cache_hits: int = 0cache_misses: int = 0total_web_searches: int = 0web_search_cache_hits: int = 0model_metrics: Dict[str, Dict] = field(default_factory=dict)startup_time: float = 0.0def record_request(self, model_name: str, latency: float):"""Record a request for metrics."""self.total_requests += 1if model_name not in self.model_metrics:self.model_metrics[model_name] = {"requests": 0,"total_latency": 0.0,"avg_latency": 0.0}self.model_metrics[model_name]["requests"] += 1self.model_metrics[model_name]["total_latency"] += latencyself.model_metrics[model_name]["avg_latency"] = (self.model_metrics[model_name]["total_latency"] /self.model_metrics[model_name]["requests"])@dataclassclass WebSearchCacheEntry:"""Cache entry for web search results."""results: List[dict]timestamp: floatttl: int = WEB_SEARCH_CACHE_TTLdef is_expired(self) -> bool:"""Check if cache entry has expired."""return time.time() - self.timestamp > self.ttlclass WebSearchCache:"""LRU cache for web search results."""def __init__(self, max_size: int = 100):self.max_size = max_sizeself.cache: OrderedDict[str, WebSearchCacheEntry] = OrderedDict()def _get_cache_key(self, query: str, max_results: int) -> str:"""Generate cache key from query."""key = f"{query}:{max_results}"return hashlib.md5(key.encode()).hexdigest()def get(self, query: str, max_results: int) -> Optional[List[dict]]:"""Get cached search results if available and not expired."""key = self._get_cache_key(query, max_results)if key in self.cache:entry = self.cache[key]if not entry.is_expired():# Move to end (most recently used)self.cache.move_to_end(key)return entry.resultselse:# Remove expired entrydel self.cache[key]return Nonedef put(self, query: str, max_results: int, results: List[dict]):"""Cache search results."""key = self._get_cache_key(query, max_results)# Evict oldest if cache is fullif len(self.cache) >= self.max_size and key not in self.cache:self.cache.popitem(last=False)self.cache[key] = WebSearchCacheEntry(results=results,timestamp=time.time())def clear(self):"""Clear all cached results."""self.cache.clear()class ModelCache:"""High-performance in-memory LRU cache for loaded models.Features:- Manages multiple llama-server processes on different ports- LRU eviction when cache is full- Parallel model loading support- Performance metrics tracking"""def __init__(self, max_size: int = MAX_CACHED_MODELS):1 unmodified lineself.cache: OrderedDict[str, CachedModel] = OrderedDict()self.port_counter = BASE_PORTself.used_ports = set()self._loading_lock = asyncio.Lock()self._loading_models: Dict[str, asyncio.Task] = {}def _get_next_port(self) -> int:"""Get next available port for a model."""8 unmodified lines"""Release a port back to the pool."""self.used_ports.discard(port)async def _evict_lru(self):"""Evict the least recently used model."""if not self.cache:return# Get the first (oldest) itemmodel_name, cached_model = self.cache.popitem(last=False)logger.info(f"Evicting model from cache: {model_name}")# Stop the processtry:1 unmodified lineos.killpg(os.getpgid(cached_model.process.pid), signal.SIGTERM)else:cached_model.process.terminate()# Wait asynchronously for process to stopfor _ in range(10):if cached_model.process.poll() is not None:breakawait asyncio.sleep(0.1)else:# Force kill if not stoppedif os.name != 'nt':os.killpg(os.getpgid(cached_model.process.pid), signal.SIGKILL)else:cached_model.process.kill()except Exception as e:logger.error(f"Error stopping model {model_name}: {e}")# Release the portself._release_port(cached_model.port)def get(self, model_name: str) -> Optional[CachedModel]:"""Get a model from cache, updating its last used time."""2 unmodified linescached_model.last_used = time.time()# Move to end (most recently used)self.cache.move_to_end(model_name)logger.debug(f"Cache hit for model: {model_name}")return cached_modellogger.debug(f"Cache miss for model: {model_name}")return Noneasync def put(self, model_name: str, model_id: str, process: subprocess.Popen, port: int, load_time: float = 0.0):"""Add a model to the cache."""# Evict if cache is fullwhile len(self.cache) >= self.max_size:await self._evict_lru()url = f"http://localhost:{port}"cached_model = CachedModel(2 unmodified linesprocess=process,port=port,url=url,last_used=time.time(),load_time=load_time)self.cache[model_name] = cached_modellogger.info(f"Cached model: {model_name} on port {port} (load time: {load_time:.2f}s)")async def clear(self):"""Clear all cached models."""logger.info("Clearing model cache...")for model_name, cached_model in list(self.cache.items()):try:if os.name != 'nt':os.killpg(os.getpgid(cached_model.process.pid), signal.SIGTERM)else:cached_model.process.terminate()# Wait asynchronouslyfor _ in range(10):if cached_model.process.poll() is not None:breakawait asyncio.sleep(0.1)except:try:if os.name != 'nt':16 unmodified lines"name": name,"port": model.port,"url": model.url,"last_used": model.last_used,"load_time": model.load_time,"request_count": model.request_count,"avg_latency": model.total_latency / model.request_count if model.request_count > 0 else 0.0}for name, model in self.cache.items()]3 unmodified lines# Global statecurrent_model = "deepseek-chat" # Default modelmodel_cache = ModelCache(max_size=MAX_CACHED_MODELS)web_search_cache = WebSearchCache(max_size=100)metrics = PerformanceMetrics()# HTTP session for connection pooling (will be initialized in startup)http_session: Optional[aiohttp.ClientSession] = Noneclass ModelSwitchRequest(BaseModel):115 unmodified linesmodel: str = Field(..., description="New active model name")async def start_llama_server(model_id: str, port: int) -> tuple[subprocess.Popen, float]:"""Start llama-server with specified model on a specific port.Returns tuple of (process, load_time_seconds).Uses async/await with exponential backoff for health checks."""start_time = time.time()cmd = ["llama-server","-hf", model_id,"--host", "0.0.0.0","--port", str(port),"-c", "2048", # Context size"-t", "4", # CPU threads"-ngl", "0", # GPU layers (0 for CPU-only)"--cont-batching", # Enable continuous batching"-b", "512", # Batch size]logger.info(f"Starting llama-server with model: {model_id} on port {port}")process = subprocess.Popen(cmd,4 unmodified linesbufsize=1)# Wait for server to be ready with exponential backoffserver_url = f"http://localhost:{port}"max_wait_time = 300 # 5 minutesbackoff_time = 0.1 # Start with 100msmax_backoff = 2.0 # Max 2 seconds between checkselapsed = 0while elapsed < max_wait_time:# Check if process diedif process.poll() is not None:stdout, _ = process.communicate()logger.error(f"llama-server exited with code {process.returncode}")logger.error(f"Output: {stdout}")raise RuntimeError("llama-server process died")try:# Use aiohttp for async health checkasync with http_session.get(f"{server_url}/health", timeout=aiohttp.ClientTimeout(total=2)) as response:if response.status in [200, 404]: # 404 is ok, means server is upload_time = time.time() - start_timelogger.info(f"llama-server ready after {load_time:.2f}s")return process, load_timeexcept (aiohttp.ClientError, asyncio.TimeoutError):# Server not ready yetpass# Exponential backoffawait asyncio.sleep(backoff_time)elapsed += backoff_timebackoff_time = min(backoff_time * 1.5, max_backoff)raise RuntimeError("llama-server failed to start within 5 minutes")async def preload_models_background():"""Background task to preload popular models."""if not PRELOAD_MODELS:returnlogger.info(f"Preloading models in background: {PRELOAD_MODELS}")for model_name in PRELOAD_MODELS:if model_name not in AVAILABLE_MODELS:logger.warning(f"Preload model not found: {model_name}")continueif model_cache.get(model_name):logger.info(f"Model already cached: {model_name}")continuetry:model_id = AVAILABLE_MODELS[model_name]port = model_cache._get_next_port()process, load_time = await start_llama_server(model_id, port)await model_cache.put(model_name, model_id, process, port, load_time)logger.info(f"Preloaded model: {model_name}")except Exception as e:logger.error(f"Failed to preload model {model_name}: {e}")@app.on_event("startup")async def startup_event():"""Initialize HTTP session and start with default model."""global current_model, http_sessionstartup_start = time.time()logger.info("Application startup initiated")# Initialize aiohttp session with connection poolingconnector = aiohttp.TCPConnector(limit=100, # Max total connectionslimit_per_host=10, # Max connections per hostttl_dns_cache=300 # DNS cache TTL)http_session = aiohttp.ClientSession(connector=connector,timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT))# Start default modelmodel_id = AVAILABLE_MODELS[current_model]port = model_cache._get_next_port()process, load_time = await start_llama_server(model_id, port)await model_cache.put(current_model, model_id, process, port, load_time)metrics.startup_time = time.time() - startup_startlogger.info(f"Started with default model: {current_model} (total startup: {metrics.startup_time:.2f}s)")# Start preloading in backgroundasyncio.create_task(preload_models_background())@app.on_event("shutdown")async def shutdown_event():"""Clean shutdown - clear cache and close HTTP session."""logger.info("Application shutdown initiated")if http_session:await http_session.close()await model_cache.clear()@app.get(13 unmodified lines- List of all available models"""return {"status": "AGI Multi-Model API - High Performance Edition","current_model": current_model,"available_models": list(AVAILABLE_MODELS.keys())}@app.get("/health",tags=["status"],summary="Health Check",description="Simple health check endpoint for monitoring.")async def health_check():"""Health check endpoint."""return {"status": "healthy","timestamp": time.time(),"cached_models": len(model_cache.cache),"current_model": current_model}@app.get("/models",response_model=ModelsResponse,8 unmodified linesReturns:- current_model: The model currently in use- available_models: Array of all available model names"""return {"current_model": current_model,6 unmodified linesresponse_model=ModelSwitchResponse,tags=["models"],summary="Switch Active Model",description="Switch to a different LLM model with intelligent caching for instant switching.")async def switch_model(request: ModelSwitchRequest):"""Switch to a different LLM model with intelligent caching.**Performance optimizations:**- Instant switching for cached models- Async model loading with exponential backoff- Connection pooling for health checks- Background preloading of popular models"""global current_model6 unmodified linesif request.model_name == current_model:return {"message": f"Already using model: {current_model}", "model": current_model}metrics.total_switches += 1# Try to get from cachecached_model = model_cache.get(request.model_name)if cached_model:# Model is cached, instant switchmetrics.cache_hits += 1current_model = request.model_namereturn {"message": f"Switched to model: {current_model} (from cache, instant)","model": current_model}# Model not cached, need to load itmetrics.cache_misses += 1model_id = AVAILABLE_MODELS[request.model_name]port = model_cache._get_next_port()try:process, load_time = await start_llama_server(model_id, port)await model_cache.put(request.model_name, model_id, process, port, load_time)current_model = request.model_namereturn {"message": f"Switched to model: {current_model} (loaded in {load_time:.2f}s)","model": current_model}except Exception as e:6 unmodified lines"/v1/chat/completions",tags=["chat"],summary="Chat Completions",description="High-performance OpenAI-compatible chat completions with connection pooling.")async def chat_completions(request: ChatCompletionRequest):"""OpenAI-compatible chat completions with performance optimizations.**Performance features:**- Async/await for non-blocking I/O- HTTP connection pooling- Request metrics tracking"""try:request_start = time.time()# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:raise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server using aiohttpasync with http_session.post(f"{cached_model.url}/v1/chat/completions",json={"messages": request.messages,"max_tokens": request.max_tokens,"temperature": request.temperature,}) as response:response.raise_for_status()result = await response.json()# Update metricsrequest_latency = time.time() - request_startcached_model.request_count += 1cached_model.total_latency += request_latencymetrics.record_request(current_model, request_latency)return resultexcept aiohttp.ClientError as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")async def search_web_async(query: str, max_results: int = 5) -> list[dict]:"""Search the web using DuckDuckGo with result caching.Implements LRU cache with TTL for search results."""# Check cache firstcached_results = web_search_cache.get(query, max_results)if cached_results is not None:metrics.web_search_cache_hits += 1logger.debug(f"Web search cache hit for: {query}")return cached_results# Perform searchtry:logger.debug(f"Performing web search: {query}")# Run blocking DDGS in thread pool to avoid blocking event looploop = asyncio.get_event_loop()results = await loop.run_in_executor(None,lambda: list(DDGS().text(query, max_results=max_results)))# Cache resultsweb_search_cache.put(query, max_results, results)metrics.total_web_searches += 1logger.debug(f"Found {len(results)} search results")return resultsexcept Exception as e:logger.error(f"Search error: {e}")return []22 unmodified lines"/v1/web-chat/completions",tags=["chat"],summary="Web-Augmented Chat Completions",description="Chat completions with real-time web search and result caching.")async def web_chat_completions(request: WebChatRequest):"""Chat completions with web search augmentation.**Performance optimizations:**- Async web search- LRU cache for search results (1 hour TTL)- Parallel execution where possible"""try:# Get the last user message as search query3 unmodified linessearch_query = user_messages[-1].get("content", "")# Perform web search (async with caching)logger.info(f"Web chat: Searching for '{search_query}'")search_results = await search_web_async(search_query, request.max_search_results)# Format search results as contextweb_context = format_search_context(search_query, search_results)12 unmodified linesAlways cite sources when using information from the search results."""}augmented_messages.insert(-1, system_prompt)# Get current model from cache2 unmodified linesraise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server with augmented contextasync with http_session.post(f"{cached_model.url}/v1/chat/completions",json={"messages": augmented_messages,"max_tokens": request.max_tokens,"temperature": request.temperature,}) as response:response.raise_for_status()result = await response.json()# Add metadata about search resultsresult["web_search"] = {"query": search_query,"results_count": len(search_results),"sources": [r.get("href", "") for r in search_results if r.get("href")],"cached": metrics.web_search_cache_hits > 0}return resultexcept aiohttp.ClientError as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")except Exception as e:raise HTTPException(status_code=500, detail=f"Error: {str(e)}")3 unmodified lines"/cache/info",tags=["models"],summary="Get Cache Information",description="Returns information about the model cache and performance statistics.")async def get_cache_info():"""Get detailed information about the model cache."""return model_cache.get_cache_info()@app.get("/metrics",tags=["monitoring"],summary="Performance Metrics",description="Get comprehensive performance metrics and statistics.")async def get_metrics():"""Get performance metrics for monitoring and optimization.Returns:- Request counts and latencies- Cache hit/miss ratios- Model-specific statistics- Web search cache stats- Startup time"""cache_hit_rate = (metrics.cache_hits / (metrics.cache_hits + metrics.cache_misses)if (metrics.cache_hits + metrics.cache_misses) > 0else 0.0)web_cache_hit_rate = (metrics.web_search_cache_hits / metrics.total_web_searchesif metrics.total_web_searches > 0else 0.0)return {"uptime_seconds": time.time() - (metrics.startup_time or time.time()),"startup_time_seconds": metrics.startup_time,"total_requests": metrics.total_requests,"total_model_switches": metrics.total_switches,"cache_stats": {"hits": metrics.cache_hits,"misses": metrics.cache_misses,"hit_rate": cache_hit_rate,"current_size": len(model_cache.cache),"max_size": model_cache.max_size},"web_search_stats": {"total_searches": metrics.total_web_searches,"cache_hits": metrics.web_search_cache_hits,"cache_hit_rate": web_cache_hit_rate,"cache_size": len(web_search_cache.cache)},"model_metrics": metrics.model_metrics,"cached_models": model_cache.get_cache_info()["cached_models"]}@app.post("/cache/clear",tags=["models"],summary="Clear Model Cache",description="Clear all cached models (will reload on next request).")async def clear_cache():"""Clear all cached models."""await model_cache.clear()return {"message": "Cache cleared successfully"}@app.post("/cache/web-search/clear",tags=["models"],summary="Clear Web Search Cache",description="Clear all cached web search results.")async def clear_web_search_cache():"""Clear web search cache."""web_search_cache.clear()metrics.web_search_cache_hits = 0metrics.total_web_searches = 0return {"message": "Web search cache cleared successfully"}@app.get(4 unmodified linesinclude_in_schema=False)async def get_openapi_spec():"""Export the OpenAPI specification for this API."""return app.openapi()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Centralized logging module for AGI Multi-Model API.
Provides structured logging with:- Colored console output- File logging with rotation- Configurable log levels- Timestamp and module name tracking"""
import loggingimport sysfrom pathlib import Pathfrom logging.handlers import RotatingFileHandlerfrom typing import Optional
class ColoredFormatter(logging.Formatter): """Custom formatter with color support for console output."""
# ANSI color codes COLORS = { 'DEBUG': '\033[36m', # Cyan 'INFO': '\033[32m', # Green 'WARNING': '\033[33m', # Yellow 'ERROR': '\033[31m', # Red 'CRITICAL': '\033[35m', # Magenta } RESET = '\033[0m' BOLD = '\033[1m'
def format(self, record): """Format log record with colors.""" # Add color to level name levelname = record.levelname if levelname in self.COLORS: record.levelname = f"{self.COLORS[levelname]}{self.BOLD}{levelname}{self.RESET}"
# Format the message result = super().format(record)
# Reset levelname for other handlers record.levelname = levelname
return result
class Logger: """ Singleton logger class for the entire application.
Usage: from logger import get_logger logger = get_logger(__name__) logger.info("Application started") """
_instance: Optional[logging.Logger] = None _initialized: bool = False
@classmethod def get_logger( cls, name: str = "AGI", level: int = logging.INFO, log_file: Optional[str] = "agi.log", max_bytes: int = 10 * 1024 * 1024, # 10MB backup_count: int = 5 ) -> logging.Logger: """ Get or create the application logger.
Args: name: Logger name (typically module name) level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) log_file: Path to log file (None to disable file logging) max_bytes: Maximum size of log file before rotation backup_count: Number of backup files to keep
Returns: Configured logger instance """ # Create or get logger logger = logging.getLogger(name)
# Only configure handlers once for the root logger if not cls._initialized and name == "AGI": logger.setLevel(level)
# Console handler with colors console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(level) console_formatter = ColoredFormatter( fmt='%(asctime)s | %(levelname)s | %(name)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) console_handler.setFormatter(console_formatter) logger.addHandler(console_handler)
# File handler with rotation (if enabled) if log_file: log_path = Path(log_file) log_path.parent.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler( log_file, maxBytes=max_bytes, backupCount=backup_count ) file_handler.setLevel(level) file_formatter = logging.Formatter( fmt='%(asctime)s | %(levelname)-8s | %(name)s | %(funcName)s:%(lineno)d | %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) file_handler.setFormatter(file_formatter) logger.addHandler(file_handler)
# Prevent propagation to avoid duplicate logs logger.propagate = False cls._initialized = True
return logger
# Convenience function for easy importdef get_logger(name: str = "AGI", level: int = logging.INFO) -> logging.Logger: """ Get a logger instance for the specified module.
Args: name: Logger name (use __name__ for automatic module naming) level: Logging level (default: INFO)
Returns: Configured logger instance
Example: from logger import get_logger logger = get_logger(__name__) logger.info("Starting application") """ return Logger.get_logger(name, level)
# Initialize the root logger on module import_root_logger = Logger.get_logger("AGI", level=logging.INFO)
if __name__ == "__main__": # Test the logger logger = get_logger("test_module")
logger.debug("This is a debug message") logger.info("This is an info message") logger.warning("This is a warning message") logger.error("This is an error message") logger.critical("This is a critical message")
print("\nTesting with different module names:") api_logger = get_logger("api") api_logger.info("API logger initialized")
client_logger = get_logger("client") client_logger.info("Client logger initialized")12345671 unmodified line91011121314[project]name = "deepseek-api"version = "0.0.1"description = "Special DeepSeek API on HuggingFace Space"authors = [{ name = "AI Developer", email = "you@example.com" }]1 unmodified linedependencies = ["fastapi>=0.104.0","uvicorn[standard]>=0.24.0","llama-cpp-python>=0.2.0","huggingface-hub>=0.19.0","duckduckgo-search>=4.0.0",12345671 unmodified line9101112131415[project]name = "agi-multi-model-api"version = "0.1.0"description = "High-Performance Multi-Model LLM API with Dynamic Switching"authors = [{ name = "AI Developer", email = "you@example.com" }]1 unmodified linedependencies = ["fastapi>=0.104.0","uvicorn[standard]>=0.24.0","aiohttp>=3.9.0","llama-cpp-python>=0.2.0","huggingface-hub>=0.19.0","duckduckgo-search>=4.0.0",
.gitignoreAdded+133
Dockerfile+2-1
app.py+436-282
logger.pyAdded+164
pyproject.toml+4-3