pavan234Reddy commited on
Commit
053d2b5
·
verified ·
1 Parent(s): 00056d8

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +143 -34
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(title="Ollama AI Server", version="1.0.0")
 
 
 
 
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] = "gemma2:2b" # Using smaller model for faster deployment
24
 
25
  class AIChatRequest(BaseModel):
26
  message: str
27
  userId: str
28
- model: Optional[str] = "gemma2:2b"
 
 
 
 
 
 
 
 
29
 
30
  @app.get("/")
31
  async def root():
32
- return {"message": "Ollama API Server is running"}
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  @app.get("/health")
35
  async def health_check():
36
- try:
37
- models = ollama.list()
38
- model_available = any('gemma2:2b' in model['name'] for model in models['models'])
39
-
40
- return {
41
- "status": "healthy",
42
- "ollama_running": True,
43
- "model_available": model_available,
44
- "available_models": [model['name'] for model in models['models']]
45
- }
46
- except Exception as e:
47
- raise HTTPException(status_code=503, detail=f"Ollama not available: {str(e)}")
 
 
 
 
 
 
 
48
 
49
  @app.post("/generate")
50
  async def generate_text(request: PromptRequest):
51
  """
52
- Generate text using specified model
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 {"response": response['message']['content']}
 
 
 
 
62
  else:
63
- return {"response": "No content generated"}
64
 
65
  except Exception as e:
66
- print("Ollama Error:", str(e))
67
- raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
 
 
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
- print("Ollama Streaming Error:", str(e))
104
- raise HTTPException(status_code=500, detail=f"Streaming failed: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  @app.post("/pull-model")
107
- async def pull_model(model: str = "gemma2:2b"):
108
  """
109
- Pull a model if it's not available
110
  """
 
 
 
 
 
 
111
  try:
112
- # Run pull in background
113
  async def pull_async():
114
- return ollama.pull(model)
 
 
 
 
115
 
116
- # Start pull process
117
  asyncio.create_task(pull_async())
118
 
119
- return {"status": "started", "message": f"Started pulling model {model}"}
 
 
 
 
120
  except Exception as e:
121
- raise HTTPException(status_code=500, detail=f"Failed to pull model: {str(e)}")
 
 
 
 
 
 
 
 
 
122
 
123
  if __name__ == "__main__":
124
  import uvicorn
125
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
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")