File size: 7,008 Bytes
b269c5d f2adbf5 b269c5d f2adbf5 b269c5d f2adbf5 b269c5d f2adbf5 b269c5d f2adbf5 b269c5d |
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 |
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Dict, Any
import json
import base64
from PIL import Image
from io import BytesIO
import uvicorn
from app import llm_client
# Create FastAPI application
api_app = FastAPI(
title="LLM Structured Output API",
description="API for generating structured responses from local GGUF models via llama-cpp-python",
version="1.0.0"
)
# Setup CORS
api_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Data models for API
class StructuredOutputRequest(BaseModel):
prompt: str
json_schema: Dict[str, Any]
image_base64: Optional[str] = None
use_grammar: bool = True
class StructuredOutputResponse(BaseModel):
success: bool
data: Optional[Dict[str, Any]] = None
error: Optional[str] = None
raw_response: Optional[str] = None
def decode_base64_image(base64_string: str) -> Image.Image:
"""Decode base64 string to PIL Image"""
try:
image_data = base64.b64decode(base64_string)
image = Image.open(BytesIO(image_data))
return image
except Exception as e:
raise HTTPException(status_code=400, detail=f"Image decoding error: {str(e)}")
@api_app.post("/generate", response_model=StructuredOutputResponse)
async def generate_structured_output(request: StructuredOutputRequest):
"""
Main endpoint for generating structured response
Args:
request: Request containing prompt, JSON schema and optionally base64 image
Returns:
StructuredOutputResponse: Structured response or error
"""
# Check model initialization
if llm_client is None:
raise HTTPException(
status_code=503,
detail="LLM model not initialized. Check server configuration."
)
try:
# Validate input data
if not request.prompt.strip():
raise HTTPException(status_code=400, detail="Prompt cannot be empty")
if not request.json_schema:
raise HTTPException(status_code=400, detail="JSON schema cannot be empty")
# Decode image if provided
image = None
if request.image_base64:
image = decode_base64_image(request.image_base64)
# Generate response
result = llm_client.generate_structured_response(
prompt=request.prompt,
json_schema=request.json_schema,
image=image,
use_grammar=request.use_grammar
)
# Format response
if "error" in result:
return StructuredOutputResponse(
success=False,
error=result["error"],
raw_response=result.get("raw_response")
)
else:
return StructuredOutputResponse(
success=True,
data=result.get("data"),
raw_response=result.get("raw_response")
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@api_app.post("/generate_with_file", response_model=StructuredOutputResponse)
async def generate_with_file(
prompt: str = Form(...),
json_schema: str = Form(...),
image: Optional[UploadFile] = File(None),
use_grammar: bool = Form(True)
):
"""
Alternative endpoint for uploading image as file
Args:
prompt: Text prompt
json_schema: JSON schema as string
image: Uploaded image file
use_grammar: Whether to use grammar-based structured output
Returns:
StructuredOutputResponse: Structured response or error
"""
# Check model initialization
if llm_client is None:
raise HTTPException(
status_code=503,
detail="LLM model not initialized. Check server configuration."
)
try:
# Validate input data
if not prompt.strip():
raise HTTPException(status_code=400, detail="Prompt cannot be empty")
if not json_schema.strip():
raise HTTPException(status_code=400, detail="JSON schema cannot be empty")
# Parse JSON schema
try:
parsed_schema = json.loads(json_schema)
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail=f"Invalid JSON schema: {str(e)}")
# Process image if provided
pil_image = None
if image:
# Check file type
if not image.content_type.startswith('image/'):
raise HTTPException(status_code=400, detail="Uploaded file must be an image")
# Read and convert image
image_data = await image.read()
pil_image = Image.open(BytesIO(image_data))
# Generate response
result = llm_client.generate_structured_response(
prompt=prompt,
json_schema=parsed_schema,
image=pil_image,
use_grammar=use_grammar
)
# Format response
if "error" in result:
return StructuredOutputResponse(
success=False,
error=result["error"],
raw_response=result.get("raw_response")
)
else:
return StructuredOutputResponse(
success=True,
data=result.get("data"),
raw_response=result.get("raw_response")
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@api_app.get("/health")
async def health_check():
"""API health check"""
model_status = "loaded" if llm_client is not None else "not_loaded"
return {
"status": "healthy" if llm_client is not None else "degraded",
"model_status": model_status,
"message": "API is working correctly" if llm_client is not None else "API is working, but model is not loaded"
}
@api_app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "LLM Structured Output API",
"version": "1.0.0",
"model_loaded": llm_client is not None,
"endpoints": {
"/generate": "POST - main endpoint for generating structured response",
"/generate_with_file": "POST - endpoint with image file upload",
"/health": "GET - health check",
"/docs": "GET - automatic Swagger documentation"
}
}
if __name__ == "__main__":
from config import Config
uvicorn.run(
"api:api_app",
host=Config.HOST,
port=Config.API_PORT,
reload=True
)
|