Spaces:
Build error
Build error
File size: 6,811 Bytes
13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 13b9962 053d2b5 | 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 | 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") |