llama3RAG / api_server.py
githubAdmin
Add FastAPI microservice and Docker support
51b0d05
Raw History Blame Contribute Delete
23.7 kB
"""
Omiver LLM REST API Service.
Replaces Streamlit UI with a high-performance FastAPI microservice exposing
biomarker RAG search, clinical precision nutrition plans, meal reprompting, and conversational AI.
"""
import os
import re
import json
import logging
from typing import Dict, Any, List, Optional, Union
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from dotenv import load_dotenv
load_dotenv()
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("omiver-llm-service")
from db_agent import (
get_llm_client,
get_vector_store,
_complete,
query_rag,
qa,
generate_report,
MODEL,
)
from calculator import (
calculate_bmr_and_tdee,
calculate_target_calories,
calculate_macronutrients,
)
# ─── Lifespan ────────────────────────────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Initializing Omiver LLM Microservice...")
# Warm up client / vector store lazily if env is available
try:
get_llm_client()
logger.info(f"Chat client initialized with model: {MODEL}")
except Exception as e:
logger.warning(f"Chat client warm-up skipped: {e}")
try:
vs = get_vector_store()
if vs:
logger.info("Pinecone vector store connected successfully.")
except Exception as e:
logger.warning(f"Vector store warm-up skipped: {e}")
yield
logger.info("Shutting down Omiver LLM Microservice.")
app = FastAPI(
title="Omiver LLM & Metabolomics API",
description="Precision clinical nutrition, metabolomics vector search, and AI plan generation for Omiver.",
version="1.0.0",
lifespan=lifespan,
)
# CORS setup
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ─── Helper Functions ────────────────────────────────────────────────────────
def extract_json_from_text(text: str) -> Optional[Dict[str, Any]]:
"""Robustly extracts JSON object or array from LLM response text."""
if not text:
return None
cleaned = text.strip()
# Strip markdown code fences if present
if cleaned.startswith("```"):
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)
cleaned = re.sub(r"\s*```$", "", cleaned)
try:
return json.loads(cleaned)
except json.JSONDecodeError:
# Match outermost curly braces
match = re.search(r"(\{.*\})", cleaned, re.DOTALL)
if match:
try:
return json.loads(match.group(1))
except json.JSONDecodeError:
pass
return None
def call_llm(messages: List[Dict[str, str]], max_tokens: int = 4096) -> str:
"""Invokes LLM with error handling."""
try:
return _complete(messages, max_tokens=max_tokens)
except Exception as e:
logger.error(f"LLM completion error: {e}")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Inference error: {str(e)}",
)
# ─── Request / Response Schemas ──────────────────────────────────────────────
class HealthResponse(BaseModel):
status: str
service: str
model: str
pinecone_connected: bool
class ChatRequest(BaseModel):
query: str = Field(..., description="User question or inquiry")
client_profile: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Client biological/fitness profile")
abnormal_markers: Optional[List[Dict[str, Any]]] = Field(default_factory=list, description="Abnormal biomarkers")
role: Optional[str] = Field("regular", description="'regular' or 'dietician'")
history: Optional[List[str]] = Field(default_factory=list, description="Previous conversation turns")
class ChatResponse(BaseModel):
answer: str
key_takeaways: List[str]
clinical_notes: Optional[str] = None
sources: Optional[List[str]] = Field(default_factory=list)
class PlanRequest(BaseModel):
client_profile: Dict[str, Any] = Field(..., description="Client demographic and fitness profile")
abnormal_markers: Optional[List[Dict[str, Any]]] = Field(default_factory=list, description="Abnormal biomarker test results")
all_markers: Optional[List[Dict[str, Any]]] = Field(default_factory=list, description="All biomarker test results")
role: Optional[str] = Field("regular", description="'regular' or 'dietician'")
doctor_feedback: Optional[str] = Field(None, description="Doctor direct notes or feedback")
class RepromptMealRequest(BaseModel):
meal_type: str = Field(..., description="e.g. Breakfast, Lunch, Dinner, Snack")
instruction: str = Field(..., description="Customization instruction from patient or provider")
current_meals: Optional[List[Dict[str, Any]]] = Field(default_factory=list, description="Existing meal plan items")
class RagQueryRequest(BaseModel):
query: Union[str, List[str]] = Field(..., description="Search query or list of messages")
person_info: Optional[Union[str, Dict[str, Any]]] = Field("", description="Client context or profile")
class RagReportRequest(BaseModel):
person_info: Union[str, Dict[str, Any]] = Field(..., description="Client context or profile")
query: Optional[List[str]] = Field(default_factory=list, description="Conversation context")
class LlmJsonRequest(BaseModel):
prompt: str = Field(..., description="Prompt instructing model to produce JSON")
system_message: Optional[str] = Field("", description="System instructions")
# ─── API Endpoints ────────────────────────────────────────────────────────────
@app.get("/", tags=["Health"])
@app.get("/health", tags=["Health"], response_model=HealthResponse)
def health_check():
"""Healthcheck endpoint for Docker, Caddy, and orchestration."""
vs = get_vector_store()
return HealthResponse(
status="healthy",
service="omiver-llm",
model=MODEL,
pinecone_connected=(vs is not None),
)
@app.post("/api/chat", tags=["AI Chat"], response_model=ChatResponse)
def chat_endpoint(payload: ChatRequest):
"""
Precision metabolomics and nutrition Q&A endpoint.
Retrieves vector context from Pinecone and synthesizes answers with clinical guidelines.
"""
is_dietician = payload.role.lower() in ["dietician", "provider", "doctor", "admin"]
# 1. Retrieve RAG context if vector store available
rag_context = ""
sources = []
vs = get_vector_store()
if vs is not None:
try:
results = vs.similarity_search_with_score(payload.query, k=4)
rag_context = "\n".join([doc.page_content for doc, _score in results])
sources = [str(doc.metadata.get("id", "")) for doc, _score in results if doc.metadata.get("id")]
except Exception as e:
logger.warning(f"Vector search failed: {e}")
# 2. Construct Prompt
system_message = (
"You are Omiver, an elite clinical metabolomics and precision nutrition AI. "
"Provide factual, evidence-informed guidance tailored to the user's role. "
"Strictly refrain from providing diagnositic medical advice. Output strict JSON."
)
prompt = f"""
CLIENT CONTEXT:
- Profile: {json.dumps(payload.client_profile)}
- Abnormal Biomarkers: {json.dumps(payload.abnormal_markers)}
- Retrieved Scientific Knowledge: {rag_context}
- Viewer Role: {'Dietician / Clinical Provider' if is_dietician else 'Regular Account (Client)'}
Question: "{payload.query}"
Respond strictly with a JSON object matching this schema:
{{
"answer": "Clear, informative explanation tailored to user's role.",
"key_takeaways": ["Point 1", "Point 2", "Point 3"],
"clinical_notes": "{'Detailed biochemical mechanism and metabolic pathway rationale' if is_dietician else ''}"
}}
"""
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt}
]
raw_response = call_llm(messages, max_tokens=1500)
parsed = extract_json_from_text(raw_response)
if parsed and isinstance(parsed, dict) and "answer" in parsed:
return ChatResponse(
answer=parsed.get("answer", ""),
key_takeaways=parsed.get("key_takeaways", []),
clinical_notes=parsed.get("clinical_notes") if is_dietician else None,
sources=sources,
)
# Fallback response
return ChatResponse(
answer=raw_response or "Based on your metabolic profile, we recommend focusing on balanced macronutrient intake and targeted micronutrients.",
key_takeaways=["Maintain consistent protein intake", "Prioritize whole-food micronutrients"],
clinical_notes="Metabolic pathway stability supported by consistent glycemic and lipid management." if is_dietician else None,
sources=sources,
)
@app.post("/api/generate-plan", tags=["Plan Generation"])
@app.post("/api/plan", tags=["Plan Generation"])
def generate_plan_endpoint(payload: PlanRequest):
"""
Generates a full precision nutrition and exercise plan:
1. Standardized Energy Targets (BMR, TDEE, Calorie Delta, Target Macros)
2. Biomarker-specific Dietary Recommendations (dos, donts, sample meal plan with estimated calories and macros)
3. Exercise Programming
4. Conditional Output Reasoning (Dietician clinical rationale vs Regular summary)
"""
profile = payload.client_profile
abnormal_markers = payload.abnormal_markers or []
is_dietician = payload.role.lower() in ["dietician", "provider", "doctor", "admin"]
# 1. Standardized Energy Calculation
bmr, tdee = calculate_bmr_and_tdee(
weight_kg=profile.get("weight"),
height_cm=profile.get("height"),
age=profile.get("age") if isinstance(profile.get("age"), int) else None,
gender=profile.get("gender"),
exercise_days_per_week=profile.get("exercise_days_per_week"),
activity_level=profile.get("weekly_exercise_routine"),
)
target_calories, delta = calculate_target_calories(
tdee=tdee,
fitness_goal=profile.get("fitness_goal"),
nutritional_goal=profile.get("nutritional_goal"),
)
macros = calculate_macronutrients(
target_calories=target_calories,
weight_kg=profile.get("weight"),
fitness_goal=profile.get("fitness_goal"),
nutritional_goal=profile.get("nutritional_goal"),
)
dashboard_goals = {
"bmr": bmr,
"tdee": tdee,
"target_calories": target_calories,
"calorie_deficit_surplus": delta,
"macros": macros,
}
# 2. Vector search context on abnormal biomarkers
rag_context = ""
vs = get_vector_store()
if vs is not None and abnormal_markers:
marker_names = [m.get("name", "") for m in abnormal_markers if m.get("name")]
if marker_names:
try:
results = vs.similarity_search_with_score(" ".join(marker_names[:5]), k=3)
rag_context = "\n".join([doc.page_content for doc, _score in results])
except Exception as e:
logger.warning(f"Vector search for markers failed: {e}")
# 3. Prompt Construction
system_message = (
"You are Omiver, an elite clinical precision metabolomics AI. "
"Generate a structured, evidence-based nutrition and exercise protocol. "
"Return ONLY a valid JSON object matching the requested schema."
)
feedback_section = ""
if payload.doctor_feedback:
feedback_section = f"\nDOCTOR DIRECT FEEDBACK TO INCORPORATE:\n\"{payload.doctor_feedback}\"\n"
prompt = f"""
CLIENT PROFILE:
- Age: {profile.get('age')}, Gender: {profile.get('gender')}
- Height: {profile.get('height')} cm, Weight: {profile.get('weight')} kg
- Primary Fitness Goal: {profile.get('fitness_goal')}
- Nutritional Goal: {profile.get('nutritional_goal')}
- Health Conditions: {profile.get('health_conditions')}
- Dietary Preferences: {profile.get('dietary_preferences')}
- Current Exercise: {profile.get('weekly_exercise_routine')} ({profile.get('exercise_days_per_week')} days/week)
STANDARDIZED ENERGY TARGETS (ONE SOURCE OF TRUTH):
- BMR: {bmr} kcal/day | TDEE: {tdee} kcal/day
- Target Calories: {target_calories} kcal/day (Delta: {delta} kcal)
- Target Macros: Protein {macros['protein_g']}g, Carbs {macros['carb_g']}g, Fat {macros['fat_g']}g
ABNORMAL BIOMARKERS:
{json.dumps(abnormal_markers, indent=2)}
{feedback_section}
SCIENTIFIC REFERENCE KNOWLEDGE:
{rag_context}
TARGET AUDIENCE: {'Dietician / Clinical Provider' if is_dietician else 'Regular Account (Client)'}
Generate a JSON object strictly matching this schema:
{{
"dashboard_goals": {{
"bmr": {bmr},
"tdee": {tdee},
"target_calories": {target_calories},
"calorie_deficit_surplus": {delta},
"macros": {json.dumps(macros)}
}},
"dietary_recommendations": {{
"summary": "Concise summary of dietary strategy addressing biomarker status.",
"dos": ["Item 1", "Item 2", "Item 3"],
"donts": ["Avoided item 1", "Avoided item 2"],
"sample_meal_plan": [
{{
"meal": "Breakfast",
"suggestion": "Detailed meal description",
"estimated_calories": {int(round(target_calories * 0.25))},
"macros": {{"protein_g": {int(round(macros['protein_g'] * 0.25))}, "carb_g": {int(round(macros['carb_g'] * 0.25))}, "fat_g": {int(round(macros['fat_g'] * 0.25))}}}
}},
{{
"meal": "Lunch",
"suggestion": "Detailed meal description",
"estimated_calories": {int(round(target_calories * 0.35))},
"macros": {{"protein_g": {int(round(macros['protein_g'] * 0.35))}, "carb_g": {int(round(macros['carb_g'] * 0.35))}, "fat_g": {int(round(macros['fat_g'] * 0.35))}}}
}},
{{
"meal": "Dinner",
"suggestion": "Detailed meal description",
"estimated_calories": {int(round(target_calories * 0.30))},
"macros": {{"protein_g": {int(round(macros['protein_g'] * 0.30))}, "carb_g": {int(round(macros['carb_g'] * 0.30))}, "fat_g": {int(round(macros['fat_g'] * 0.30))}}}
}},
{{
"meal": "Snack",
"suggestion": "Healthy snack description",
"estimated_calories": {max(100, target_calories - int(round(target_calories * 0.90)))},
"macros": {{"protein_g": {max(5, macros['protein_g'] - int(round(macros['protein_g'] * 0.90)))}, "carb_g": {max(10, macros['carb_g'] - int(round(macros['carb_g'] * 0.90)))}, "fat_g": {max(5, macros['fat_g'] - int(round(macros['fat_g'] * 0.90)))}}}
}}
]
}},
"exercise_recommendations": {{
"summary": "Exercise programming guidance.",
"frequency": "{profile.get('exercise_days_per_week') or 3} to 4 sessions per week",
"activities": ["Activity 1", "Activity 2", "Activity 3"],
"precautions": ["Precaution 1"]
}},
"output_reasoning": {{
"regular_summary": "Actionable, clear explanation for the patient.",
"clinical_rationale": "Comprehensive biochemical, metabolic pathway, and macro calculation reasoning for the Dietician."
}}
}}
"""
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt}
]
raw_response = call_llm(messages, max_tokens=3000)
parsed = extract_json_from_text(raw_response)
if parsed and isinstance(parsed, dict) and "dietary_recommendations" in parsed:
if not is_dietician and "output_reasoning" in parsed:
if isinstance(parsed["output_reasoning"], dict):
parsed["output_reasoning"]["clinical_rationale"] = None
parsed["dashboard_goals"] = dashboard_goals
return parsed
# Fallback dynamic plan
return {
"dashboard_goals": dashboard_goals,
"dietary_recommendations": {
"summary": f"Targeted metabolic protocol addressing biomarker profile with a caloric target of {target_calories} kcal/day.",
"dos": ["High-fiber leafy greens", "Lean biological proteins", "Adequate structured hydration"],
"donts": ["Refined carbohydrates and trans-fats", "Added sucrose and corn syrups"],
"sample_meal_plan": [
{
"meal": "Breakfast",
"suggestion": "Steel-cut oats with chia seeds, Ceylon cinnamon, and berries",
"estimated_calories": int(round(target_calories * 0.25)),
"macros": {
"protein_g": int(round(macros["protein_g"] * 0.25)),
"carb_g": int(round(macros["carb_g"] * 0.25)),
"fat_g": int(round(macros["fat_g"] * 0.25)),
},
},
{
"meal": "Lunch",
"suggestion": "Char-grilled free-range chicken breast over quinoa and Mediterranean vegetables",
"estimated_calories": int(round(target_calories * 0.35)),
"macros": {
"protein_g": int(round(macros["protein_g"] * 0.35)),
"carb_g": int(round(macros["carb_g"] * 0.35)),
"fat_g": int(round(macros["fat_g"] * 0.35)),
},
},
{
"meal": "Dinner",
"suggestion": "Wild salmon fillet with steamed greens and sweet potato mash",
"estimated_calories": int(round(target_calories * 0.30)),
"macros": {
"protein_g": int(round(macros["protein_g"] * 0.30)),
"carb_g": int(round(macros["carb_g"] * 0.30)),
"fat_g": int(round(macros["fat_g"] * 0.30)),
},
},
{
"meal": "Snack",
"suggestion": "Raw walnuts with unsweetened Greek yogurt",
"estimated_calories": max(100, target_calories - int(round(target_calories * 0.90))),
"macros": {
"protein_g": max(5, macros["protein_g"] - int(round(macros["protein_g"] * 0.90))),
"carb_g": max(10, macros["carb_g"] - int(round(macros["carb_g"] * 0.90))),
"fat_g": max(5, macros["fat_g"] - int(round(macros["fat_g"] * 0.90))),
},
},
],
},
"exercise_recommendations": {
"summary": "Multi-modal aerobic and resistance training supporting metabolic clearance.",
"frequency": f"{profile.get('exercise_days_per_week') or 3} to 4 sessions per week",
"activities": ["Zone 2 steady-state cardiovascular training", "Compound resistance movements", "Post-meal walks"],
"precautions": ["Adequate hydration and dynamic warm-up"],
},
"output_reasoning": {
"regular_summary": f"Your plan is calibrated to {target_calories} kcal/day with {macros['protein_g']}g protein to support your goals.",
"clinical_rationale": (
f"BMR {bmr} kcal via Mifflin-St Jeor, TDEE {tdee} kcal with {delta} kcal energy delta. "
f"Macronutrient distribution: P {macros['protein_g']}g, C {macros['carb_g']}g, F {macros['fat_g']}g."
) if is_dietician else None,
},
}
@app.post("/api/reprompt-meal", tags=["Meal Plans"])
def reprompt_meal_endpoint(payload: RepromptMealRequest):
"""
Re-generates a single meal item (Breakfast, Lunch, Dinner, Snack) or substitutes ingredients.
"""
system_prompt = (
"You are Omiver precision nutrition assistant. Adjust the specific meal according to the "
"client instruction while maintaining healthy macros. Output strict JSON."
)
prompt = f"""
Current Meals Context: {json.dumps(payload.current_meals)}
Target Meal Type to Replace: "{payload.meal_type}"
User Reprompt Instruction: "{payload.instruction}"
Return a JSON object with:
{{
"meal": "{payload.meal_type}",
"suggestion": "New adjusted meal description",
"estimated_calories": 500,
"macros": {{"protein_g": 35, "carb_g": 45, "fat_g": 15}}
}}
"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
raw_response = call_llm(messages, max_tokens=600)
parsed = extract_json_from_text(raw_response)
if parsed and isinstance(parsed, dict) and "suggestion" in parsed:
return parsed
return {
"meal": payload.meal_type,
"suggestion": f"Adjusted {payload.meal_type}: {payload.instruction}",
"estimated_calories": 450,
"macros": {"protein_g": 30, "carb_g": 40, "fat_g": 12},
}
@app.post("/api/rag/query", tags=["RAG"])
def rag_query_endpoint(payload: RagQueryRequest):
"""
Exposes raw Pinecone vector similarity search + conversational RAG pipeline.
"""
query_list = payload.query if isinstance(payload.query, list) else [payload.query]
person_info_str = json.dumps(payload.person_info) if isinstance(payload.person_info, dict) else str(payload.person_info or "")
try:
ans = query_rag(query_list, person_info_str)
# Also obtain sources if available
sources = []
vs = get_vector_store()
if vs is not None:
results = vs.similarity_search_with_score(query_list[-1], k=4)
sources = [str(doc.metadata.get("id", "")) for doc, _score in results if doc.metadata.get("id")]
return {"response": ans, "sources": sources}
except Exception as e:
logger.error(f"query_rag failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/rag/report", tags=["RAG"])
def rag_report_endpoint(payload: RagReportRequest):
"""
Generates an in-depth clinical metabolomics delta analysis report.
"""
person_info_str = json.dumps(payload.person_info) if isinstance(payload.person_info, dict) else str(payload.person_info)
query_list = payload.query or ["Give an analysis for this client."]
try:
report = generate_report(query_list, person_info_str)
return {"report": report}
except Exception as e:
logger.error(f"generate_report failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/llm/json", tags=["LLM"])
def llm_json_endpoint(payload: LlmJsonRequest):
"""
Generic structured JSON generation endpoint.
"""
messages = []
if payload.system_message:
messages.append({"role": "system", "content": payload.system_message})
messages.append({"role": "user", "content": payload.prompt})
raw_response = call_llm(messages, max_tokens=3000)
parsed = extract_json_from_text(raw_response)
if parsed is not None:
return {"result": parsed}
return {"raw": raw_response, "result": None}
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", "8501"))
host = os.getenv("HOST", "0.0.0.0")
uvicorn.run("api_server:app", host=host, port=port, reload=False)