Spaces:
Build error
Build error
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,13 +1,20 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from fastapi.responses import StreamingResponse
|
| 4 |
from pydantic import BaseModel
|
| 5 |
import ollama
|
| 6 |
import json
|
| 7 |
-
from typing import Optional
|
| 8 |
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
app = FastAPI(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Add CORS middleware
|
| 13 |
app.add_middleware(
|
|
@@ -20,37 +27,73 @@ app.add_middleware(
|
|
| 20 |
|
| 21 |
class PromptRequest(BaseModel):
|
| 22 |
prompt: str
|
| 23 |
-
model: Optional[str] = "
|
| 24 |
|
| 25 |
class AIChatRequest(BaseModel):
|
| 26 |
message: str
|
| 27 |
userId: str
|
| 28 |
-
model: Optional[str] = "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
@app.get("/")
|
| 31 |
async def root():
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
@app.get("/health")
|
| 35 |
async def health_check():
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
@app.post("/generate")
|
| 50 |
async def generate_text(request: PromptRequest):
|
| 51 |
"""
|
| 52 |
-
Generate text using
|
| 53 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
try:
|
| 55 |
response = ollama.chat(
|
| 56 |
model=request.model,
|
|
@@ -58,19 +101,31 @@ async def generate_text(request: PromptRequest):
|
|
| 58 |
)
|
| 59 |
|
| 60 |
if response and 'message' in response and 'content' in response['message']:
|
| 61 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
else:
|
| 63 |
-
return {"response": "No content generated"}
|
| 64 |
|
| 65 |
except Exception as e:
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
@app.post("/api/ai/chat")
|
| 70 |
async def ai_chat_stream(request: AIChatRequest):
|
| 71 |
"""
|
| 72 |
-
Streaming chat endpoint
|
| 73 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
try:
|
| 75 |
async def generate():
|
| 76 |
stream = ollama.chat(
|
|
@@ -96,30 +151,84 @@ async def ai_chat_stream(request: AIChatRequest):
|
|
| 96 |
headers={
|
| 97 |
"Cache-Control": "no-cache",
|
| 98 |
"Connection": "keep-alive",
|
|
|
|
| 99 |
}
|
| 100 |
)
|
| 101 |
|
| 102 |
except Exception as e:
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
@app.post("/pull-model")
|
| 107 |
-
async def pull_model(model: str = "
|
| 108 |
"""
|
| 109 |
-
Pull a model
|
| 110 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
try:
|
| 112 |
-
#
|
| 113 |
async def pull_async():
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
# Start pull process
|
| 117 |
asyncio.create_task(pull_async())
|
| 118 |
|
| 119 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
if __name__ == "__main__":
|
| 124 |
import uvicorn
|
| 125 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 4 |
from pydantic import BaseModel
|
| 5 |
import ollama
|
| 6 |
import json
|
|
|
|
| 7 |
import asyncio
|
| 8 |
+
import subprocess
|
| 9 |
+
import os
|
| 10 |
+
from typing import Optional
|
| 11 |
+
import requests
|
| 12 |
|
| 13 |
+
app = FastAPI(
|
| 14 |
+
title="Ollama AI Server",
|
| 15 |
+
version="1.0.0",
|
| 16 |
+
description="AI Chat Server deployed on Hugging Face Spaces"
|
| 17 |
+
)
|
| 18 |
|
| 19 |
# Add CORS middleware
|
| 20 |
app.add_middleware(
|
|
|
|
| 27 |
|
| 28 |
class PromptRequest(BaseModel):
|
| 29 |
prompt: str
|
| 30 |
+
model: Optional[str] = "tinyllama:1.1b"
|
| 31 |
|
| 32 |
class AIChatRequest(BaseModel):
|
| 33 |
message: str
|
| 34 |
userId: str
|
| 35 |
+
model: Optional[str] = "tinyllama:1.1b"
|
| 36 |
+
|
| 37 |
+
# Check if Ollama is available
|
| 38 |
+
def check_ollama():
|
| 39 |
+
try:
|
| 40 |
+
response = ollama.list()
|
| 41 |
+
return True
|
| 42 |
+
except:
|
| 43 |
+
return False
|
| 44 |
|
| 45 |
@app.get("/")
|
| 46 |
async def root():
|
| 47 |
+
ollama_status = "connected" if check_ollama() else "disconnected"
|
| 48 |
+
return {
|
| 49 |
+
"message": "🚀 Ollama FastAPI Server - Hugging Face Spaces",
|
| 50 |
+
"status": "running",
|
| 51 |
+
"ollama": ollama_status,
|
| 52 |
+
"endpoints": {
|
| 53 |
+
"health": "/health",
|
| 54 |
+
"generate": "/generate",
|
| 55 |
+
"chat": "/api/ai/chat",
|
| 56 |
+
"models": "/models"
|
| 57 |
+
},
|
| 58 |
+
"documentation": "Add /docs to URL for API documentation"
|
| 59 |
+
}
|
| 60 |
|
| 61 |
@app.get("/health")
|
| 62 |
async def health_check():
|
| 63 |
+
ollama_available = check_ollama()
|
| 64 |
+
|
| 65 |
+
status_info = {
|
| 66 |
+
"status": "healthy" if ollama_available else "degraded",
|
| 67 |
+
"fastapi": "running",
|
| 68 |
+
"ollama": "connected" if ollama_available else "disconnected",
|
| 69 |
+
"environment": "hugging-face-spaces",
|
| 70 |
+
"port": 7860
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
if ollama_available:
|
| 74 |
+
try:
|
| 75 |
+
models = ollama.list()
|
| 76 |
+
status_info["available_models"] = [model['name'] for model in models['models']]
|
| 77 |
+
status_info["models_count"] = len(models['models'])
|
| 78 |
+
except Exception as e:
|
| 79 |
+
status_info["ollama_error"] = str(e)
|
| 80 |
+
|
| 81 |
+
return status_info
|
| 82 |
|
| 83 |
@app.post("/generate")
|
| 84 |
async def generate_text(request: PromptRequest):
|
| 85 |
"""
|
| 86 |
+
Generate text using Ollama
|
| 87 |
"""
|
| 88 |
+
if not check_ollama():
|
| 89 |
+
return JSONResponse(
|
| 90 |
+
status_code=503,
|
| 91 |
+
content={
|
| 92 |
+
"error": "Ollama service not available",
|
| 93 |
+
"message": "Ollama is still starting up or failed to start. Please try again in a moment."
|
| 94 |
+
}
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
try:
|
| 98 |
response = ollama.chat(
|
| 99 |
model=request.model,
|
|
|
|
| 101 |
)
|
| 102 |
|
| 103 |
if response and 'message' in response and 'content' in response['message']:
|
| 104 |
+
return {
|
| 105 |
+
"response": response['message']['content'],
|
| 106 |
+
"model": request.model,
|
| 107 |
+
"success": True
|
| 108 |
+
}
|
| 109 |
else:
|
| 110 |
+
return {"response": "No content generated", "success": False}
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
+
raise HTTPException(
|
| 114 |
+
status_code=500,
|
| 115 |
+
detail=f"Generation failed: {str(e)}. Models may still be downloading."
|
| 116 |
+
)
|
| 117 |
|
| 118 |
@app.post("/api/ai/chat")
|
| 119 |
async def ai_chat_stream(request: AIChatRequest):
|
| 120 |
"""
|
| 121 |
+
Streaming chat endpoint with Ollama
|
| 122 |
"""
|
| 123 |
+
if not check_ollama():
|
| 124 |
+
raise HTTPException(
|
| 125 |
+
status_code=503,
|
| 126 |
+
detail="Ollama service not available. Please wait for models to download."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
try:
|
| 130 |
async def generate():
|
| 131 |
stream = ollama.chat(
|
|
|
|
| 151 |
headers={
|
| 152 |
"Cache-Control": "no-cache",
|
| 153 |
"Connection": "keep-alive",
|
| 154 |
+
"X-Accel-Buffering": "no" # Important for streaming
|
| 155 |
}
|
| 156 |
)
|
| 157 |
|
| 158 |
except Exception as e:
|
| 159 |
+
raise HTTPException(
|
| 160 |
+
status_code=500,
|
| 161 |
+
detail=f"Streaming failed: {str(e)}"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
@app.get("/models")
|
| 165 |
+
async def list_models():
|
| 166 |
+
"""
|
| 167 |
+
List available Ollama models
|
| 168 |
+
"""
|
| 169 |
+
if not check_ollama():
|
| 170 |
+
raise HTTPException(
|
| 171 |
+
status_code=503,
|
| 172 |
+
detail="Ollama service not available"
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
models = ollama.list()
|
| 177 |
+
return {
|
| 178 |
+
"models": [
|
| 179 |
+
{
|
| 180 |
+
"name": model['name'],
|
| 181 |
+
"size": model.get('size', 'unknown'),
|
| 182 |
+
"modified": model.get('modified_at', 'unknown')
|
| 183 |
+
} for model in models['models']
|
| 184 |
+
],
|
| 185 |
+
"count": len(models['models'])
|
| 186 |
+
}
|
| 187 |
+
except Exception as e:
|
| 188 |
+
raise HTTPException(
|
| 189 |
+
status_code=500,
|
| 190 |
+
detail=f"Failed to list models: {str(e)}"
|
| 191 |
+
)
|
| 192 |
|
| 193 |
@app.post("/pull-model")
|
| 194 |
+
async def pull_model(model: str = "tinyllama:1.1b"):
|
| 195 |
"""
|
| 196 |
+
Pull a model (async - starts download in background)
|
| 197 |
"""
|
| 198 |
+
if not check_ollama():
|
| 199 |
+
raise HTTPException(
|
| 200 |
+
status_code=503,
|
| 201 |
+
detail="Ollama service not available"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
try:
|
| 205 |
+
# Start pull in background
|
| 206 |
async def pull_async():
|
| 207 |
+
try:
|
| 208 |
+
result = ollama.pull(model)
|
| 209 |
+
print(f"Model {model} pulled successfully: {result}")
|
| 210 |
+
except Exception as e:
|
| 211 |
+
print(f"Failed to pull model {model}: {e}")
|
| 212 |
|
|
|
|
| 213 |
asyncio.create_task(pull_async())
|
| 214 |
|
| 215 |
+
return {
|
| 216 |
+
"status": "started",
|
| 217 |
+
"message": f"Started pulling model: {model}",
|
| 218 |
+
"note": "This may take several minutes. Check logs for progress."
|
| 219 |
+
}
|
| 220 |
except Exception as e:
|
| 221 |
+
raise HTTPException(
|
| 222 |
+
status_code=500,
|
| 223 |
+
detail=f"Failed to start model pull: {str(e)}"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
@app.get("/docs")
|
| 227 |
+
async def custom_docs():
|
| 228 |
+
"""Redirect to Swagger docs"""
|
| 229 |
+
from fastapi.responses import RedirectResponse
|
| 230 |
+
return RedirectResponse(url="/docs")
|
| 231 |
|
| 232 |
if __name__ == "__main__":
|
| 233 |
import uvicorn
|
| 234 |
+
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
|