File size: 23,691 Bytes
51b0d05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
"""
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)