pavan234Reddy commited on
Commit
13b9962
·
verified ·
1 Parent(s): b28e624

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +125 -0
main.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
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,
57
+ messages=[{"role": "user", "content": request.prompt}]
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(
77
+ model=request.model,
78
+ messages=[{"role": "user", "content": request.message}],
79
+ stream=True
80
+ )
81
+
82
+ for chunk in stream:
83
+ if 'message' in chunk and 'content' in chunk['message']:
84
+ content = chunk['message']['content']
85
+ data = {
86
+ "content": content,
87
+ "finish_reason": None
88
+ }
89
+ yield f"data: {json.dumps(data)}\n\n"
90
+
91
+ yield f"data: {json.dumps({'content': '', 'finish_reason': 'stop'})}\n\n"
92
+
93
+ return StreamingResponse(
94
+ generate(),
95
+ media_type="text/plain",
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)