from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse, JSONResponse from pydantic import BaseModel import ollama import json import asyncio import subprocess import os from typing import Optional import requests app = FastAPI( title="Ollama AI Server", version="1.0.0", description="AI Chat Server deployed on Hugging Face Spaces" ) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class PromptRequest(BaseModel): prompt: str model: Optional[str] = "tinyllama:1.1b" class AIChatRequest(BaseModel): message: str userId: str model: Optional[str] = "tinyllama:1.1b" # Check if Ollama is available def check_ollama(): try: response = ollama.list() return True except: return False @app.get("/") async def root(): ollama_status = "connected" if check_ollama() else "disconnected" return { "message": "🚀 Ollama FastAPI Server - Hugging Face Spaces", "status": "running", "ollama": ollama_status, "endpoints": { "health": "/health", "generate": "/generate", "chat": "/api/ai/chat", "models": "/models" }, "documentation": "Add /docs to URL for API documentation" } @app.get("/health") async def health_check(): ollama_available = check_ollama() status_info = { "status": "healthy" if ollama_available else "degraded", "fastapi": "running", "ollama": "connected" if ollama_available else "disconnected", "environment": "hugging-face-spaces", "port": 7860 } if ollama_available: try: models = ollama.list() status_info["available_models"] = [model['name'] for model in models['models']] status_info["models_count"] = len(models['models']) except Exception as e: status_info["ollama_error"] = str(e) return status_info @app.post("/generate") async def generate_text(request: PromptRequest): """ Generate text using Ollama """ if not check_ollama(): return JSONResponse( status_code=503, content={ "error": "Ollama service not available", "message": "Ollama is still starting up or failed to start. Please try again in a moment." } ) try: response = ollama.chat( model=request.model, messages=[{"role": "user", "content": request.prompt}] ) if response and 'message' in response and 'content' in response['message']: return { "response": response['message']['content'], "model": request.model, "success": True } else: return {"response": "No content generated", "success": False} except Exception as e: raise HTTPException( status_code=500, detail=f"Generation failed: {str(e)}. Models may still be downloading." ) @app.post("/api/ai/chat") async def ai_chat_stream(request: AIChatRequest): """ Streaming chat endpoint with Ollama """ if not check_ollama(): raise HTTPException( status_code=503, detail="Ollama service not available. Please wait for models to download." ) try: async def generate(): stream = ollama.chat( model=request.model, messages=[{"role": "user", "content": request.message}], stream=True ) for chunk in stream: if 'message' in chunk and 'content' in chunk['message']: content = chunk['message']['content'] data = { "content": content, "finish_reason": None } yield f"data: {json.dumps(data)}\n\n" yield f"data: {json.dumps({'content': '', 'finish_reason': 'stop'})}\n\n" return StreamingResponse( generate(), media_type="text/plain", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" # Important for streaming } ) except Exception as e: raise HTTPException( status_code=500, detail=f"Streaming failed: {str(e)}" ) @app.get("/models") async def list_models(): """ List available Ollama models """ if not check_ollama(): raise HTTPException( status_code=503, detail="Ollama service not available" ) try: models = ollama.list() return { "models": [ { "name": model['name'], "size": model.get('size', 'unknown'), "modified": model.get('modified_at', 'unknown') } for model in models['models'] ], "count": len(models['models']) } except Exception as e: raise HTTPException( status_code=500, detail=f"Failed to list models: {str(e)}" ) @app.post("/pull-model") async def pull_model(model: str = "tinyllama:1.1b"): """ Pull a model (async - starts download in background) """ if not check_ollama(): raise HTTPException( status_code=503, detail="Ollama service not available" ) try: # Start pull in background async def pull_async(): try: result = ollama.pull(model) print(f"Model {model} pulled successfully: {result}") except Exception as e: print(f"Failed to pull model {model}: {e}") asyncio.create_task(pull_async()) return { "status": "started", "message": f"Started pulling model: {model}", "note": "This may take several minutes. Check logs for progress." } except Exception as e: raise HTTPException( status_code=500, detail=f"Failed to start model pull: {str(e)}" ) @app.get("/docs") async def custom_docs(): """Redirect to Swagger docs""" from fastapi.responses import RedirectResponse return RedirectResponse(url="/docs") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")