Update app.py
Browse files
app.py
CHANGED
|
@@ -6,10 +6,6 @@ from fastapi import FastAPI, Request, HTTPException
|
|
| 6 |
from fastapi.responses import StreamingResponse
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
|
| 9 |
-
# --- New imports for LangChain + langchain_ollama ---
|
| 10 |
-
from pydantic import BaseModel
|
| 11 |
-
from langchain_ollama import ChatOllama
|
| 12 |
-
|
| 13 |
# Configure logging
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
| 15 |
logger = logging.getLogger(__name__)
|
|
@@ -33,23 +29,12 @@ app.add_middleware(
|
|
| 33 |
API_KEY = os.environ.get("API_KEY", "change_me")
|
| 34 |
logger.info(f"API key loaded: {API_KEY}")
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
OLLAMA_SERVER_URL = "http://localhost:11434/
|
| 38 |
-
|
| 39 |
-
# --- Initialize a single Ollama instance via langchain_ollama ---
|
| 40 |
-
# This is the "LangChain" style interface to the Ollama server.
|
| 41 |
-
ollama_llm = ChatOllama(
|
| 42 |
-
model="hf.co/abanm/Dubs-Q8_0-GGUF:latest", # same model as before
|
| 43 |
-
base_url="http://localhost:11434", # base URL for Ollama server
|
| 44 |
-
request_timeout=120 # Increase if model loading is slow
|
| 45 |
-
)
|
| 46 |
|
| 47 |
-
# --------------------------------
|
| 48 |
-
# Original endpoint: /api/generate
|
| 49 |
-
# --------------------------------
|
| 50 |
@app.post("/api/generate")
|
| 51 |
async def generate(request: Request):
|
| 52 |
-
"""Endpoint that generates text based on the prompt
|
| 53 |
try:
|
| 54 |
# 1. Parse the incoming request
|
| 55 |
body = await request.json()
|
|
@@ -83,56 +68,36 @@ async def generate(request: Request):
|
|
| 83 |
try:
|
| 84 |
async with httpx.AsyncClient() as client:
|
| 85 |
async with client.stream(
|
| 86 |
-
"POST",
|
|
|
|
|
|
|
|
|
|
| 87 |
) as response:
|
|
|
|
| 88 |
response.raise_for_status()
|
|
|
|
|
|
|
| 89 |
async for chunk in response.aiter_text():
|
| 90 |
yield chunk
|
|
|
|
| 91 |
except httpx.RequestError:
|
| 92 |
logger.exception("Request error while communicating with Ollama")
|
| 93 |
yield json.dumps({"error": "Unable to communicate with Ollama"})
|
|
|
|
| 94 |
except httpx.HTTPStatusError as exc:
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
return StreamingResponse(stream_response(), media_type="application/json")
|
| 99 |
|
| 100 |
-
except Exception
|
| 101 |
logger.exception("Unhandled exception in /api/generate")
|
| 102 |
raise HTTPException(status_code=500, detail="Internal server error")
|
| 103 |
|
| 104 |
-
# ------------------------------
|
| 105 |
-
# New endpoint: /api/langchain-generate
|
| 106 |
-
# ------------------------------
|
| 107 |
-
class LangChainRequest(BaseModel):
|
| 108 |
-
prompt: str
|
| 109 |
-
|
| 110 |
-
@app.post("/api/langchain-generate")
|
| 111 |
-
async def langchain_generate(request: LangChainRequest):
|
| 112 |
-
"""
|
| 113 |
-
Endpoint that uses langchain_ollama to generate text.
|
| 114 |
-
This is an alternative approach that uses the Ollama() class from langchain_ollama.
|
| 115 |
-
"""
|
| 116 |
-
# Check for API key (similar logic as above, or unify the code)
|
| 117 |
-
# ... or just omit it if your environment is already secure
|
| 118 |
-
# If re-using the same approach:
|
| 119 |
-
# (In real code, you'd unify these checks in a shared function)
|
| 120 |
-
#
|
| 121 |
-
# auth_header = ...
|
| 122 |
-
# if token != API_KEY:
|
| 123 |
-
# raise HTTPException(...)
|
| 124 |
-
|
| 125 |
-
prompt = request.prompt
|
| 126 |
-
logger.info(f"LangChain request: {prompt}")
|
| 127 |
-
|
| 128 |
-
# Directly call the Ollama LLM via langchain_ollama
|
| 129 |
-
try:
|
| 130 |
-
response_text = ollama_llm(prompt)
|
| 131 |
-
return {"response": response_text}
|
| 132 |
-
except Exception as e:
|
| 133 |
-
logger.exception("Unhandled exception in /api/langchain-generate")
|
| 134 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 135 |
-
|
| 136 |
@app.get("/health")
|
| 137 |
async def health():
|
| 138 |
"""Health check endpoint."""
|
|
@@ -143,3 +108,4 @@ if __name__ == "__main__":
|
|
| 143 |
import uvicorn
|
| 144 |
logger.info("Starting server on http://0.0.0.0:7860")
|
| 145 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
| 6 |
from fastapi.responses import StreamingResponse
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
# Configure logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger(__name__)
|
|
|
|
| 29 |
API_KEY = os.environ.get("API_KEY", "change_me")
|
| 30 |
logger.info(f"API key loaded: {API_KEY}")
|
| 31 |
|
| 32 |
+
# NOTE: Ollama’s default endpoint is often "/generate", not "/api/generate"
|
| 33 |
+
OLLAMA_SERVER_URL = "http://localhost:11434/generate"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
@app.post("/api/generate")
|
| 36 |
async def generate(request: Request):
|
| 37 |
+
"""Endpoint that generates text based on the prompt."""
|
| 38 |
try:
|
| 39 |
# 1. Parse the incoming request
|
| 40 |
body = await request.json()
|
|
|
|
| 68 |
try:
|
| 69 |
async with httpx.AsyncClient() as client:
|
| 70 |
async with client.stream(
|
| 71 |
+
"POST",
|
| 72 |
+
OLLAMA_SERVER_URL,
|
| 73 |
+
json=payload,
|
| 74 |
+
headers={"Content-Type": "application/json"}
|
| 75 |
) as response:
|
| 76 |
+
# If we get 4xx or 5xx, raise_for_status() triggers HTTPStatusError
|
| 77 |
response.raise_for_status()
|
| 78 |
+
|
| 79 |
+
# Stream out the content as it arrives
|
| 80 |
async for chunk in response.aiter_text():
|
| 81 |
yield chunk
|
| 82 |
+
|
| 83 |
except httpx.RequestError:
|
| 84 |
logger.exception("Request error while communicating with Ollama")
|
| 85 |
yield json.dumps({"error": "Unable to communicate with Ollama"})
|
| 86 |
+
|
| 87 |
except httpx.HTTPStatusError as exc:
|
| 88 |
+
# Read the remaining body so we can log the error text
|
| 89 |
+
error_bytes = await exc.response.aread()
|
| 90 |
+
error_text = error_bytes.decode("utf-8", errors="replace")
|
| 91 |
+
|
| 92 |
+
logger.error(f"HTTP error from Ollama: {exc.response.status_code} - {error_text}")
|
| 93 |
+
yield json.dumps({"error": f"HTTP error: {error_text}"})
|
| 94 |
|
| 95 |
return StreamingResponse(stream_response(), media_type="application/json")
|
| 96 |
|
| 97 |
+
except Exception:
|
| 98 |
logger.exception("Unhandled exception in /api/generate")
|
| 99 |
raise HTTPException(status_code=500, detail="Internal server error")
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
@app.get("/health")
|
| 102 |
async def health():
|
| 103 |
"""Health check endpoint."""
|
|
|
|
| 108 |
import uvicorn
|
| 109 |
logger.info("Starting server on http://0.0.0.0:7860")
|
| 110 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 111 |
+
|