Spaces:
Sleeping
Sleeping
Kennedy Johnson Cursor commited on
Commit ·
96378bc
1
Parent(s): 838be72
Add deterministic nutrition calculator for MuscleGrowthAI advisors.
Browse filesPre-compute protein targets from body weight and inject exact values into persona context so advisors use factual math instead of LLM arithmetic.
Co-authored-by: Cursor <cursoragent@cursor.com>
- docs/nutrition_tools.md +35 -0
- multi_llm_chatbot_backend/app/core/improved_orchestrator.py +12 -0
- multi_llm_chatbot_backend/app/tests/unit/test_nutrition_calculator.py +92 -0
- multi_llm_chatbot_backend/app/tests/unit/test_nutrition_calculator_tool.py +24 -0
- multi_llm_chatbot_backend/app/tests/unit/test_tool_registry.py +7 -2
- multi_llm_chatbot_backend/app/tools/__init__.py +4 -1
- multi_llm_chatbot_backend/app/tools/nutrition_calculator.py +230 -0
- muscle_growth_config.yaml +5 -0
docs/nutrition_tools.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Nutrition calculation tools (MuscleGrowthAI)
|
| 2 |
+
|
| 3 |
+
Deterministic fitness/nutrition math for advisor responses. LLM personas receive pre-computed values instead of doing arithmetic themselves.
|
| 4 |
+
|
| 5 |
+
## Tools in use
|
| 6 |
+
|
| 7 |
+
| Source | Cost | Status | Purpose |
|
| 8 |
+
|--------|------|--------|---------|
|
| 9 |
+
| **Local Python formulas** | Free | **Active** | lbs↔kg, protein g/kg (1.6–2.2), meal splits |
|
| 10 |
+
| **USDA FoodData Central** | Free (API key) | Planned | Food nutrient lookup by name/barcode |
|
| 11 |
+
| **Open Food Facts** | Free (no key) | Planned | Product/barcode nutrient data |
|
| 12 |
+
|
| 13 |
+
## Core formulas (local)
|
| 14 |
+
|
| 15 |
+
- **Weight:** `kg = lbs × 0.45359237`
|
| 16 |
+
- **Protein (hypertrophy):** `protein_g_min = round(weight_kg × 1.6)`, `protein_g_max = round(weight_kg × 2.2)`
|
| 17 |
+
- **Meal split:** even distribution with remainder assigned to first meals
|
| 18 |
+
|
| 19 |
+
Example: **230 lb** → **104.33 kg** → **167–230 g protein/day** (4 meals ≈ 42/42/42/41 g at the low end).
|
| 20 |
+
|
| 21 |
+
## How calculations reach advisors
|
| 22 |
+
|
| 23 |
+
1. **Context injection (primary):** When chat history mentions protein and a body weight is present, `compute_protein_advisory_context()` runs in `_build_enhanced_context_for_persona()` and adds a `PRE-COMPUTED NUTRITION VALUES` JSON block to each persona system prompt.
|
| 24 |
+
2. **LLM tool calling (optional):** `calculate_protein_target` is registered in `app/tools/nutrition_calculator.py` and enabled via `muscle_growth_config.yaml` → `tools.nutrition_calculator.enabled: true`. The orchestrator may call it for direct tool responses when appropriate.
|
| 25 |
+
|
| 26 |
+
## Files
|
| 27 |
+
|
| 28 |
+
- `multi_llm_chatbot_backend/app/tools/nutrition_calculator.py` — formulas + tool definition
|
| 29 |
+
- `multi_llm_chatbot_backend/app/core/improved_orchestrator.py` — injects computed context into persona prompts
|
| 30 |
+
- `muscle_growth_config.yaml` — enables `nutrition_calculator` tool
|
| 31 |
+
|
| 32 |
+
## USDA / Open Food Facts (later)
|
| 33 |
+
|
| 34 |
+
- USDA: register at [https://fdc.nal.usda.gov/api-key-signup](https://fdc.nal.usda.gov/api-key-signup), set `USDA_API_KEY` env var.
|
| 35 |
+
- Open Food Facts: `https://world.openfoodfacts.org/api/v2/product/{barcode}` — no key required.
|
multi_llm_chatbot_backend/app/core/improved_orchestrator.py
CHANGED
|
@@ -6,6 +6,10 @@ from app.core.rag_manager import get_rag_manager
|
|
| 6 |
from app.config import get_settings
|
| 7 |
from app.llm.llm_client import LLMClient, ToolCallResult
|
| 8 |
from app.tools import get_tool_definitions, get_tool_executor
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from app.utils.chat_summary import generate_conversation_context_summary
|
| 10 |
|
| 11 |
import json
|
|
@@ -88,6 +92,8 @@ class ImprovedChatOrchestrator:
|
|
| 88 |
"Call get_current_datetime when the user asks about today, deadlines, timelines, "
|
| 89 |
"schedules, or when accurate date/time context would improve "
|
| 90 |
"your guidance — then weave the result into your answer. "
|
|
|
|
|
|
|
| 91 |
"If no tool is relevant, respond with a brief text answer. "
|
| 92 |
"Format your responses using markdown."
|
| 93 |
)
|
|
@@ -830,6 +836,12 @@ When analyzing the document context:
|
|
| 830 |
"Use this background to calibrate technical depth, examples, and priorities."
|
| 831 |
)
|
| 832 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 833 |
enhanced_context.append({
|
| 834 |
"role": "system",
|
| 835 |
"content": system_message,
|
|
|
|
| 6 |
from app.config import get_settings
|
| 7 |
from app.llm.llm_client import LLMClient, ToolCallResult
|
| 8 |
from app.tools import get_tool_definitions, get_tool_executor
|
| 9 |
+
from app.tools.nutrition_calculator import (
|
| 10 |
+
compute_protein_advisory_context,
|
| 11 |
+
format_computed_context_block,
|
| 12 |
+
)
|
| 13 |
from app.utils.chat_summary import generate_conversation_context_summary
|
| 14 |
|
| 15 |
import json
|
|
|
|
| 92 |
"Call get_current_datetime when the user asks about today, deadlines, timelines, "
|
| 93 |
"schedules, or when accurate date/time context would improve "
|
| 94 |
"your guidance — then weave the result into your answer. "
|
| 95 |
+
"Call calculate_protein_target when the user asks about protein intake and "
|
| 96 |
+
"provides body weight — use the returned grams, do not guess arithmetic. "
|
| 97 |
"If no tool is relevant, respond with a brief text answer. "
|
| 98 |
"Format your responses using markdown."
|
| 99 |
)
|
|
|
|
| 836 |
"Use this background to calibrate technical depth, examples, and priorities."
|
| 837 |
)
|
| 838 |
|
| 839 |
+
computed_nutrition = compute_protein_advisory_context(conversation_messages)
|
| 840 |
+
if computed_nutrition:
|
| 841 |
+
system_message += (
|
| 842 |
+
f"\n\n{format_computed_context_block(computed_nutrition)}"
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
enhanced_context.append({
|
| 846 |
"role": "system",
|
| 847 |
"content": system_message,
|
multi_llm_chatbot_backend/app/tests/unit/test_nutrition_calculator.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from app.tools.nutrition_calculator import (
|
| 4 |
+
bodyweight_to_kg,
|
| 5 |
+
compute_protein_advisory_context,
|
| 6 |
+
conversation_mentions_protein,
|
| 7 |
+
extract_weight_from_text,
|
| 8 |
+
meal_split,
|
| 9 |
+
protein_target_g,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestBodyweightConversion(unittest.TestCase):
|
| 14 |
+
def test_230_lbs_to_kg(self):
|
| 15 |
+
self.assertEqual(bodyweight_to_kg(230, "lb"), 104.33)
|
| 16 |
+
|
| 17 |
+
def test_kg_passthrough(self):
|
| 18 |
+
self.assertEqual(bodyweight_to_kg(104.33, "kg"), 104.33)
|
| 19 |
+
|
| 20 |
+
def test_unsupported_unit_raises(self):
|
| 21 |
+
with self.assertRaises(ValueError):
|
| 22 |
+
bodyweight_to_kg(100, "stone")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestProteinTarget(unittest.TestCase):
|
| 26 |
+
def test_230_lbs_protein_range(self):
|
| 27 |
+
weight_kg = bodyweight_to_kg(230, "lb")
|
| 28 |
+
protein = protein_target_g(weight_kg)
|
| 29 |
+
self.assertEqual(weight_kg, 104.33)
|
| 30 |
+
self.assertEqual(protein["protein_g_min"], 167)
|
| 31 |
+
self.assertEqual(protein["protein_g_max"], 230)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestMealSplit(unittest.TestCase):
|
| 35 |
+
def test_splits_evenly_with_remainder(self):
|
| 36 |
+
result = meal_split(167, meals=4)
|
| 37 |
+
self.assertEqual(result["per_meal_g"], [42, 42, 42, 41])
|
| 38 |
+
self.assertEqual(sum(result["per_meal_g"]), 167)
|
| 39 |
+
|
| 40 |
+
def test_requires_positive_meals(self):
|
| 41 |
+
with self.assertRaises(ValueError):
|
| 42 |
+
meal_split(100, meals=0)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TestWeightExtraction(unittest.TestCase):
|
| 46 |
+
def test_extracts_lbs(self):
|
| 47 |
+
info = extract_weight_from_text("I weigh 230 lbs")
|
| 48 |
+
self.assertIsNotNone(info)
|
| 49 |
+
self.assertEqual(info["value"], 230)
|
| 50 |
+
self.assertEqual(info["unit"], "lb")
|
| 51 |
+
self.assertEqual(info["weight_kg"], 104.33)
|
| 52 |
+
|
| 53 |
+
def test_extracts_kg(self):
|
| 54 |
+
info = extract_weight_from_text("about 104.33 kg")
|
| 55 |
+
self.assertIsNotNone(info)
|
| 56 |
+
self.assertEqual(info["weight_kg"], 104.33)
|
| 57 |
+
|
| 58 |
+
def test_standalone_number_defaults_to_lb(self):
|
| 59 |
+
info = extract_weight_from_text("230")
|
| 60 |
+
self.assertIsNotNone(info)
|
| 61 |
+
self.assertEqual(info["unit"], "lb")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class TestProteinAdvisoryContext(unittest.TestCase):
|
| 65 |
+
def test_computes_from_conversation(self):
|
| 66 |
+
messages = [
|
| 67 |
+
{"role": "user", "content": "how much protein should I consume?"},
|
| 68 |
+
{"role": "nutrition_strategist", "content": "What is your body weight?"},
|
| 69 |
+
{"role": "user", "content": "230 lbs"},
|
| 70 |
+
]
|
| 71 |
+
computed = compute_protein_advisory_context(messages)
|
| 72 |
+
self.assertIsNotNone(computed)
|
| 73 |
+
self.assertEqual(computed["weight_kg"], 104.33)
|
| 74 |
+
self.assertEqual(computed["protein_g_min"], 167)
|
| 75 |
+
self.assertEqual(computed["protein_g_max"], 230)
|
| 76 |
+
self.assertEqual(len(computed["meal_split_min_g"]), 4)
|
| 77 |
+
|
| 78 |
+
def test_returns_none_without_protein_topic(self):
|
| 79 |
+
messages = [{"role": "user", "content": "230 lbs"}]
|
| 80 |
+
self.assertIsNone(compute_protein_advisory_context(messages))
|
| 81 |
+
|
| 82 |
+
def test_returns_none_without_weight(self):
|
| 83 |
+
messages = [{"role": "user", "content": "how much protein per day?"}]
|
| 84 |
+
self.assertIsNone(compute_protein_advisory_context(messages))
|
| 85 |
+
|
| 86 |
+
def test_conversation_mentions_protein(self):
|
| 87 |
+
self.assertTrue(conversation_mentions_protein("How much protein should I eat?"))
|
| 88 |
+
self.assertFalse(conversation_mentions_protein("best chest exercises"))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
unittest.main()
|
multi_llm_chatbot_backend/app/tests/unit/test_nutrition_calculator_tool.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
from app.tools.nutrition_calculator import TOOL_DEFINITION, execute
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestNutritionCalculatorTool(unittest.TestCase):
|
| 8 |
+
def test_tool_definition_shape(self):
|
| 9 |
+
self.assertEqual(TOOL_DEFINITION["type"], "function")
|
| 10 |
+
self.assertEqual(
|
| 11 |
+
TOOL_DEFINITION["function"]["name"],
|
| 12 |
+
"calculate_protein_target",
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def test_execute_230_lbs(self):
|
| 16 |
+
result = asyncio.run(execute(weight=230, unit="lb", meals=4))
|
| 17 |
+
self.assertEqual(result["weight_kg"], 104.33)
|
| 18 |
+
self.assertEqual(result["protein_g_min"], 167)
|
| 19 |
+
self.assertEqual(result["protein_g_max"], 230)
|
| 20 |
+
self.assertEqual(sum(result["meal_split_min_g"]), 167)
|
| 21 |
+
|
| 22 |
+
def test_execute_missing_args(self):
|
| 23 |
+
result = asyncio.run(execute())
|
| 24 |
+
self.assertIn("error", result)
|
multi_llm_chatbot_backend/app/tests/unit/test_tool_registry.py
CHANGED
|
@@ -10,7 +10,7 @@ from app.tools import (
|
|
| 10 |
)
|
| 11 |
|
| 12 |
|
| 13 |
-
KNOWN_TOOLS = {"get_current_datetime"}
|
| 14 |
|
| 15 |
|
| 16 |
class TestToolDiscovery(unittest.TestCase):
|
|
@@ -32,10 +32,15 @@ class TestGetToolDefinitions(unittest.TestCase):
|
|
| 32 |
self.assertTrue(KNOWN_TOOLS.issubset(names))
|
| 33 |
|
| 34 |
def test_filter_to_single_tool(self):
|
| 35 |
-
defs = get_tool_definitions(enabled=["
|
| 36 |
self.assertEqual(len(defs), 1)
|
| 37 |
self.assertEqual(defs[0]["function"]["name"], "get_current_datetime")
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
class TestGetToolExecutor(unittest.TestCase):
|
| 41 |
def test_dispatch_unknown_tool_returns_error(self):
|
|
|
|
| 10 |
)
|
| 11 |
|
| 12 |
|
| 13 |
+
KNOWN_TOOLS = {"get_current_datetime", "calculate_protein_target"}
|
| 14 |
|
| 15 |
|
| 16 |
class TestToolDiscovery(unittest.TestCase):
|
|
|
|
| 32 |
self.assertTrue(KNOWN_TOOLS.issubset(names))
|
| 33 |
|
| 34 |
def test_filter_to_single_tool(self):
|
| 35 |
+
defs = get_tool_definitions(enabled=["current_datetime"])
|
| 36 |
self.assertEqual(len(defs), 1)
|
| 37 |
self.assertEqual(defs[0]["function"]["name"], "get_current_datetime")
|
| 38 |
|
| 39 |
+
def test_module_alias_enables_nutrition_tool(self):
|
| 40 |
+
defs = get_tool_definitions(enabled=["nutrition_calculator"])
|
| 41 |
+
self.assertEqual(len(defs), 1)
|
| 42 |
+
self.assertEqual(defs[0]["function"]["name"], "calculate_protein_target")
|
| 43 |
+
|
| 44 |
|
| 45 |
class TestGetToolExecutor(unittest.TestCase):
|
| 46 |
def test_dispatch_unknown_tool_returns_error(self):
|
multi_llm_chatbot_backend/app/tools/__init__.py
CHANGED
|
@@ -70,7 +70,10 @@ def _discover_tools() -> None:
|
|
| 70 |
)
|
| 71 |
continue
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
| 74 |
logger.info("Registered tool: %s (from %s)", tool_name, qualified)
|
| 75 |
|
| 76 |
|
|
|
|
| 70 |
)
|
| 71 |
continue
|
| 72 |
|
| 73 |
+
entry = {"definition": defn, "executor": executor}
|
| 74 |
+
_REGISTRY[tool_name] = entry
|
| 75 |
+
if module_name != tool_name:
|
| 76 |
+
_REGISTRY[module_name] = entry
|
| 77 |
logger.info("Registered tool: %s (from %s)", tool_name, qualified)
|
| 78 |
|
| 79 |
|
multi_llm_chatbot_backend/app/tools/nutrition_calculator.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic fitness/nutrition calculations for MuscleGrowthAI advisors.
|
| 2 |
+
|
| 3 |
+
Core math is local (no API). Optional future integrations:
|
| 4 |
+
- USDA FoodData Central (free, API key) — food nutrient lookup
|
| 5 |
+
- Open Food Facts (free, no key) — barcode / product lookup
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 13 |
+
|
| 14 |
+
_LB_TO_KG = 0.45359237
|
| 15 |
+
_KG_TO_LB = 1 / _LB_TO_KG
|
| 16 |
+
|
| 17 |
+
_PROTEIN_TOPIC_KEYWORDS = (
|
| 18 |
+
"protein",
|
| 19 |
+
"macro",
|
| 20 |
+
"macros",
|
| 21 |
+
"g/kg",
|
| 22 |
+
"grams of protein",
|
| 23 |
+
"how much protein",
|
| 24 |
+
"protein intake",
|
| 25 |
+
"protein target",
|
| 26 |
+
"protein goal",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
_WEIGHT_PATTERNS: List[Tuple[str, str]] = [
|
| 30 |
+
(r"(\d+(?:\.\d+)?)\s*(?:lbs?|pounds?)\b", "lb"),
|
| 31 |
+
(r"(\d+(?:\.\d+)?)\s*(?:kgs?|kilos?)\b", "kg"),
|
| 32 |
+
(r"(\d+(?:\.\d+)?)\s*kg\b", "kg"),
|
| 33 |
+
(r"(?:weigh(?:s)?|weight(?:\s+is)?|at)\s+(\d+(?:\.\d+)?)\b", "lb"),
|
| 34 |
+
(r"^\s*(\d{2,3}(?:\.\d+)?)\s*$", "lb"),
|
| 35 |
+
(r"i['']?m\s+(\d+(?:\.\d+)?)\b", "lb"),
|
| 36 |
+
(r"i am\s+(\d+(?:\.\d+)?)\b", "lb"),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def bodyweight_to_kg(value: float, unit: str) -> float:
|
| 41 |
+
"""Convert body weight to kilograms."""
|
| 42 |
+
unit_norm = unit.strip().lower()
|
| 43 |
+
if unit_norm in {"lb", "lbs", "pound", "pounds"}:
|
| 44 |
+
return round(value * _LB_TO_KG, 2)
|
| 45 |
+
if unit_norm in {"kg", "kgs", "kilo", "kilos", "kilogram", "kilograms"}:
|
| 46 |
+
return round(value, 2)
|
| 47 |
+
raise ValueError(f"Unsupported weight unit: {unit!r}")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def protein_target_g(
|
| 51 |
+
weight_kg: float,
|
| 52 |
+
g_per_kg_low: float = 1.6,
|
| 53 |
+
g_per_kg_high: float = 2.2,
|
| 54 |
+
) -> Dict[str, int]:
|
| 55 |
+
"""Return rounded daily protein range in grams for hypertrophy."""
|
| 56 |
+
return {
|
| 57 |
+
"protein_g_min": round(weight_kg * g_per_kg_low),
|
| 58 |
+
"protein_g_max": round(weight_kg * g_per_kg_high),
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def meal_split(total_g: int, meals: int = 4) -> Dict[str, Any]:
|
| 63 |
+
"""Split a daily protein target across meals (integer grams per meal)."""
|
| 64 |
+
if meals < 1:
|
| 65 |
+
raise ValueError("meals must be at least 1")
|
| 66 |
+
base = total_g // meals
|
| 67 |
+
remainder = total_g % meals
|
| 68 |
+
per_meal = [base + (1 if i < remainder else 0) for i in range(meals)]
|
| 69 |
+
return {
|
| 70 |
+
"meals": meals,
|
| 71 |
+
"total_g": total_g,
|
| 72 |
+
"per_meal_g": per_meal,
|
| 73 |
+
"per_meal_avg": round(total_g / meals, 1),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _plausible_body_weight(value: float, unit: str) -> bool:
|
| 78 |
+
"""Reject obvious non-body-weight numbers (age, reps, etc.)."""
|
| 79 |
+
if unit == "kg":
|
| 80 |
+
return 35 <= value <= 250
|
| 81 |
+
return 80 <= value <= 550
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def extract_weight_from_text(text: str, default_unit: str = "lb") -> Optional[Dict[str, Any]]:
|
| 85 |
+
"""Parse the first plausible body-weight mention from *text*."""
|
| 86 |
+
for pattern, unit in _WEIGHT_PATTERNS:
|
| 87 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 88 |
+
if not match:
|
| 89 |
+
continue
|
| 90 |
+
value = float(match.group(1))
|
| 91 |
+
resolved_unit = unit or default_unit
|
| 92 |
+
if not _plausible_body_weight(value, resolved_unit):
|
| 93 |
+
continue
|
| 94 |
+
weight_kg = bodyweight_to_kg(value, resolved_unit)
|
| 95 |
+
return {
|
| 96 |
+
"value": value,
|
| 97 |
+
"unit": resolved_unit,
|
| 98 |
+
"weight_kg": weight_kg,
|
| 99 |
+
"source_text": match.group(0).strip(),
|
| 100 |
+
}
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def conversation_mentions_protein(text: str) -> bool:
|
| 105 |
+
lowered = text.lower()
|
| 106 |
+
return any(keyword in lowered for keyword in _PROTEIN_TOPIC_KEYWORDS)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def compute_protein_advisory_context(
|
| 110 |
+
messages: List[Dict[str, str]],
|
| 111 |
+
*,
|
| 112 |
+
g_per_kg_low: float = 1.6,
|
| 113 |
+
g_per_kg_high: float = 2.2,
|
| 114 |
+
meals: int = 4,
|
| 115 |
+
) -> Optional[Dict[str, Any]]:
|
| 116 |
+
"""When protein is discussed and weight is known, return structured facts."""
|
| 117 |
+
combined_text = "\n".join(
|
| 118 |
+
msg.get("content", "")
|
| 119 |
+
for msg in messages
|
| 120 |
+
if msg.get("role") != "system"
|
| 121 |
+
)
|
| 122 |
+
if not conversation_mentions_protein(combined_text):
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
weight_info: Optional[Dict[str, Any]] = None
|
| 126 |
+
for msg in reversed(messages):
|
| 127 |
+
if msg.get("role") == "system":
|
| 128 |
+
continue
|
| 129 |
+
weight_info = extract_weight_from_text(msg.get("content", ""))
|
| 130 |
+
if weight_info:
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
if not weight_info:
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
weight_kg = weight_info["weight_kg"]
|
| 137 |
+
protein = protein_target_g(weight_kg, g_per_kg_low, g_per_kg_high)
|
| 138 |
+
split_min = meal_split(protein["protein_g_min"], meals=meals)
|
| 139 |
+
split_max = meal_split(protein["protein_g_max"], meals=meals)
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"topic": "protein",
|
| 143 |
+
"weight_input": {
|
| 144 |
+
"value": weight_info["value"],
|
| 145 |
+
"unit": weight_info["unit"],
|
| 146 |
+
"source_text": weight_info["source_text"],
|
| 147 |
+
},
|
| 148 |
+
"weight_kg": weight_kg,
|
| 149 |
+
"protein_g_min": protein["protein_g_min"],
|
| 150 |
+
"protein_g_max": protein["protein_g_max"],
|
| 151 |
+
"g_per_kg_range": [g_per_kg_low, g_per_kg_high],
|
| 152 |
+
"meal_split_min_g": split_min["per_meal_g"],
|
| 153 |
+
"meal_split_max_g": split_max["per_meal_g"],
|
| 154 |
+
"meals": meals,
|
| 155 |
+
"formula": "protein_g = weight_kg × g_per_kg (Mifflin-independent; hypertrophy range 1.6–2.2 g/kg)",
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def format_computed_context_block(computed: Dict[str, Any]) -> str:
|
| 160 |
+
"""Serialize computed values for injection into persona system prompts."""
|
| 161 |
+
return (
|
| 162 |
+
"PRE-COMPUTED NUTRITION VALUES (deterministic Python; use these exact "
|
| 163 |
+
"numbers — do not recalculate or guess):\n"
|
| 164 |
+
f"{json.dumps(computed, indent=2)}"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ---------------------------------------------------------------------------
|
| 169 |
+
# LLM tool surface (optional direct orchestrator path)
|
| 170 |
+
# ---------------------------------------------------------------------------
|
| 171 |
+
|
| 172 |
+
TOOL_DEFINITION = {
|
| 173 |
+
"type": "function",
|
| 174 |
+
"function": {
|
| 175 |
+
"name": "calculate_protein_target",
|
| 176 |
+
"description": (
|
| 177 |
+
"Compute daily protein targets in grams from body weight using the "
|
| 178 |
+
"hypertrophy range 1.6–2.2 g/kg. Use when the user asks about protein "
|
| 179 |
+
"intake and provides or implies body weight."
|
| 180 |
+
),
|
| 181 |
+
"parameters": {
|
| 182 |
+
"type": "object",
|
| 183 |
+
"properties": {
|
| 184 |
+
"weight": {
|
| 185 |
+
"type": "number",
|
| 186 |
+
"description": "Body weight numeric value.",
|
| 187 |
+
},
|
| 188 |
+
"unit": {
|
| 189 |
+
"type": "string",
|
| 190 |
+
"enum": ["lb", "kg"],
|
| 191 |
+
"description": "Unit for weight (lb or kg).",
|
| 192 |
+
},
|
| 193 |
+
"meals": {
|
| 194 |
+
"type": "integer",
|
| 195 |
+
"description": "Number of meals to split protein across (default 4).",
|
| 196 |
+
},
|
| 197 |
+
},
|
| 198 |
+
"required": ["weight", "unit"],
|
| 199 |
+
},
|
| 200 |
+
},
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
async def execute(
|
| 205 |
+
name: str = "",
|
| 206 |
+
weight: float | None = None,
|
| 207 |
+
unit: str | None = None,
|
| 208 |
+
meals: int = 4,
|
| 209 |
+
**_: Any,
|
| 210 |
+
) -> Dict[str, Any]:
|
| 211 |
+
if weight is None or unit is None:
|
| 212 |
+
return {"error": "weight and unit are required"}
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
weight_kg = bodyweight_to_kg(float(weight), unit)
|
| 216 |
+
protein = protein_target_g(weight_kg)
|
| 217 |
+
split_min = meal_split(protein["protein_g_min"], meals=max(1, int(meals)))
|
| 218 |
+
split_max = meal_split(protein["protein_g_max"], meals=max(1, int(meals)))
|
| 219 |
+
except (TypeError, ValueError) as exc:
|
| 220 |
+
return {"error": str(exc)}
|
| 221 |
+
|
| 222 |
+
return {
|
| 223 |
+
"weight_kg": weight_kg,
|
| 224 |
+
"protein_g_min": protein["protein_g_min"],
|
| 225 |
+
"protein_g_max": protein["protein_g_max"],
|
| 226 |
+
"g_per_kg_range": [1.6, 2.2],
|
| 227 |
+
"meal_split_min_g": split_min["per_meal_g"],
|
| 228 |
+
"meal_split_max_g": split_max["per_meal_g"],
|
| 229 |
+
"meals": max(1, int(meals)),
|
| 230 |
+
}
|
muscle_growth_config.yaml
CHANGED
|
@@ -211,6 +211,11 @@ tools:
|
|
| 211 |
current_datetime:
|
| 212 |
enabled: true
|
| 213 |
default_timezone: "America/Denver"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
voice:
|
| 216 |
stt_endpoint: "https://whisper.neonaiservices.com"
|
|
|
|
| 211 |
current_datetime:
|
| 212 |
enabled: true
|
| 213 |
default_timezone: "America/Denver"
|
| 214 |
+
nutrition_calculator:
|
| 215 |
+
enabled: true
|
| 216 |
+
# Core protein math is local (1.6–2.2 g/kg). Optional future APIs:
|
| 217 |
+
# usda_fooddata_central — free, requires USDA_API_KEY env var
|
| 218 |
+
# open_food_facts — free, no key (https://world.openfoodfacts.org)
|
| 219 |
|
| 220 |
voice:
|
| 221 |
stt_endpoint: "https://whisper.neonaiservices.com"
|