Pashudhan Nutri AI API
Version 2.1 · ICAR-2013+NASEM Compliant · REST & Python SDK
The Pashudhan Nutri AI API gives your cooperative or agri-tech platform plug-and-play access to India's most accurate dairy ration engine. Send a single HTTP request and receive a complete, science-backed ration in JSON — or use the official pashudhan_ai Python SDK for a one-liner workflow.
Authentication
All API requests require an x-api-key header. Get your key from the API Dashboard. Treat it like a password — never expose it in client-side code.
pd_ followed by 32 hex characters. Invalid keys return 401 Unauthorized.curl -X POST https://pashudhan-nutri-ai.web.app/api/formulate \
-H "x-api-key: pd_your_key_here" \
-H "Content-Type: application/json" \
-d '{ ... }'
Quickstart
Get a complete ration in under 60 seconds. Choose your language:
import pashudhan_ai
client = pashudhan_ai.Client(api_key="pd_your_key_here")
result = client.formulate(
animal_type = "cow",
breed = "HF_crossbred",
body_weight_kg = 450,
milk_yield_kg_day = 18,
fat_pct = 3.5,
production_stage = "mid_lactation",
state = "Punjab",
month = 5,
location = "30.90,75.85" # Optional: For live THI tracking
)
# Access all 4 optimisation strategies
for opt in result.formulations:
print(opt.mode, opt.total_cost_local_day) # e.g. least_cost 248.5
# Or use convenience properties
print(result.least_cost.total_cost_local_day)
for ing in result.least_cost.ingredients:
print(f"{ing.name}: {ing.kg_fresh_day} kg")
AI Agents & MCP Integration
Model Context Protocol (MCP)
Empower Claude, Cursor, and other AI agents to formulate rations on your behalf.
The Pashudhan Nutri AI platform natively supports the open-source Model Context Protocol (MCP). This means you can instantly give AI assistants the ability to formulate rations, check live heat stress (THI), and query the ICAR-NDRI ingredient database directly within their chat interfaces.
How to connect Claude Desktop
- Go to your API Dashboard and generate an Enterprise API Key.
- Click the Download MCP Config button next to your key.
- This downloads a
pashudhan_mcp_config.jsonfile. - Copy the contents of this file into your Claude Desktop configuration file.
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
- Windows:
- Restart Claude Desktop. The AI will now have access to the Pashudhan Formulation Tools!
Python SDK — Install
pashudhan_ai package wraps the REST API with a clean, Pythonic interface. No need to handle HTTP headers or JSON manually.
Install via pip
Requirements
Python >= 3.8 requests >= 2.28
Python SDK — Usage
Initialize the client
import pashudhan_ai # Option 1: Pass key directly client = pashudhan_ai.Client(api_key="pd_your_key_here") # Option 2: Set environment variable PASHUDHAN_API_KEY client = pashudhan_ai.Client() # reads from env automatically
Formulate a ration
result = client.formulate(
animal_type = "cow",
breed = "Sahiwal",
body_weight_kg = 380,
milk_yield_kg_day = 10,
fat_pct = 4.2,
production_stage = "mid_lactation",
state = "Rajasthan",
month = 11,
use_ai = True, # enable AI Nutritionist critique
location = "Jaipur" # fetch live weather data
)
# Access all 4 strategies
for opt in result.formulations:
print(f"[{opt.mode}] Cost: {opt.total_cost_local_day}/day NEL={opt.nutrients.nel_mcal_kg_dm} Mcal/kg")
# Access AI Explanation
if result.ai_explanation:
print("AI says:", result.ai_explanation)
# Access Live THI data
if result.thi_report:
print(f"Live THI: {result.thi_report.thi} ({result.thi_report.category})")
# Access Metabolic Report (Requires Pro/Enterprise Plan)
if result.metabolic_report:
print(f"Methane: {result.metabolic_report.methane.enteric_ch4_g_day} g/day")
print(f"RUP/RDP Status: {result.metabolic_report.rup_rdp.ratio_status}")
Check your usage
status = client.status() print(status.plan) # "starter" / "pro" / "pro_max" print(status.calls_used) # API calls used this month print(status.calls_limit) # monthly limit
API Reference
The core endpoint. Returns up to 4 optimized ration strategies in JSON.
Request Body
| Parameter | Type | Description |
|---|---|---|
| animal_type required | string | cow, buffalo, heifer, bull |
| breed required | string | e.g. HF_crossbred, Sahiwal, Murrah |
| body_weight_kg required | number | Body weight in kg (e.g. 450) |
| milk_yield_kg_day required | number | Daily milk yield in kg |
| fat_pct required | number | Milk fat % (e.g. 3.5). Only used if lactating. |
| protein_pct optional | number | Milk protein % (e.g. 3.2). Default: breed avg. Only used if lactating. |
| production_stage required | string | lactating, dry, growing, pre_calving |
| dim optional | number | Days in Milk. Affects intake & ketosis risk scoring. |
| parity optional | number | Lactation number. Default 1. Used for lactating/dry. |
| days_pregnant optional | number | Days of pregnancy. Triggers fetal energy demands if > 60. |
| bcs optional | number | Body Condition Score (1-5). Default 3.0. |
| health_flags optional | array | Strings e.g. ["ketosis_history", "steaming_up"] |
| state required | string | State or region (e.g. Punjab, Gujarat) |
| month required | number | Month 1–12 for seasonal ingredient filter |
| use_ai optional | boolean | Enable AI Nutritionist critique (Pro/ProMax only) |
| location optional | string | City or lat,lon for live THI heat stress adjustment |
Response
{
"request_id": "req_abc123",
"formulations": [
{
"mode": "least_cost",
"total_cost_local_day": 248.50,
"feed_cost_local_day": 220.0,
"formulation": {
"ingredients": [
{ "name": "Wheat Straw", "kg_fresh_day": 5.0, "cost_local_day": 22.5 },
{ "name": "Maize Grain", "kg_fresh_day": 3.5, "cost_local_day": 87.5 }
],
"nutrient_summary": { "NEL_Mcal_day": 22.1, "CP_g_day": 1680, "NDF_pct_DM": 32.4 },
"ai_explanation": "Option 1 is the cheapest but has severe nutrient gaps. A calcium supplement MUST be added.",
"ai_warnings": [
"DANGEROUS Ca:P RATIO: The calcium-to-phosphorus ratio is 0.51 — far below the safe minimum of 1.5:1."
]
},
"palatability": { "score": 88, "refusal_probability_pct": 8 },
"adaptive_reasoning": ["Ration is nutritionally balanced. Consider adding bypass fat..."]
}
],
"thi_report": { "thi": 78, "category": "mild_stress", "adjusted_water_L_day": 82 },
"metabolic_report": {
"methane": { "enteric_CH4_g_day": 345, "CO2e_kg_year": 3524, "vs_benchmark_pct": -4, "mitigation_tips": ["Increase fat"], "applicable": true },
"rup_rdp": { "ratio_status": "Optimal", "actual_rdp_rup_ratio": "65:35", "applicable": true },
"amino_acids": { "lys_pct_mp": 6.9, "met_pct_mp": 2.2, "applicable": true }
}
}
metabolic_report object requires a Pro, ProMax, Enterprise, or EnterpriseMax API plan.
Specifically, Methane estimations are only available for functional ruminants (e.g. not pre-ruminant calves) on supported plans.
Formulates for an entire herd. Deducts 4 API credits per call.
Request Body
| Parameter | Type | Description |
|---|---|---|
| groups required | array | List of animal group dictionaries (each containing entries) |
| state required | string | State or region (e.g. Punjab, Gujarat) |
| month required | number | Month 1–12 for seasonal ingredient filter |
| farmer_ingredients optional | array | List of ingredient IDs to restrict formulation to |
Example Request Body
{
"state": "Punjab",
"month": 5,
"farmer_ingredients": ["Wheat Straw", "Maize Grain"],
"groups": [
{
"category": "Lactating",
"entries": [
{
"animal_type": "cow",
"breed": "HF_crossbred",
"count": 10,
"body_weight_kg": 500,
"milk_yield_kg_day": 20,
"milk_fat_pct": 3.5,
"production_stage": "mid_lactation"
}
]
}
]
}
Example Response
{
"herd_summary": {
"total_animals": 10,
"total_feed_cost_inr": 2485.00,
"avg_cost_per_animal_inr": 248.50,
"thi": 78
},
"groups": [
{
"category": "Lactating",
"animal_count": 10,
"total_group_cost_inr": 2485.00,
"formulation": {
"strategy": "least_cost",
"ingredients": [
{ "name": "Wheat Straw", "kg_fresh_day": 50.0, "cost_inr": 225.0 },
{ "name": "Maize Grain", "kg_fresh_day": 35.0, "cost_inr": 875.0 }
],
"nutrients": { "NEL_Mcal_day": 221.0, "CP_g_day": 16800 },
"ai_explanation": "Group is well-balanced. Monitor heat stress impact on DMI."
}
}
]
}
Returns all available subscription plans. No authentication required.
curl https://pashudhan-nutri-ai.web.app/api/plans
Returns your current plan and monthly API usage. Requires x-api-key header or Authorization: Bearer <firebase-token>.
curl https://pashudhan-nutri-ai.web.app/api/enterprise/status \
-H "x-api-key: pd_your_key_here"
# Response:
{
"plan": "starter",
"monthly_limit": 1000,
"requests_used": 142
}
Returns all available ingredients with their composition for a given country. This allows you to build custom ingredient picker UIs. Requires x-api-key. By default, it returns Indian ingredients with INR prices. Passing ?country=USA will return USA ingredients with USD prices.
# India (Default) curl "https://pashudhan-nutri-ai.web.app/api/ingredients-list?country=India" \ -H "x-api-key: pd_your_key_here" # USA curl "https://pashudhan-nutri-ai.web.app/api/ingredients-list?country=USA" \ -H "x-api-key: pd_your_key_here"
Returns a list of supported countries and their configurations (currency, regions). No authentication required.
curl https://pashudhan-nutri-ai.web.app/api/countries
Returns the dairy breeds available for a specific country, along with their default body weights and milk fat metrics. No authentication required.
# India (Default) curl "https://pashudhan-nutri-ai.web.app/api/breeds?country=India" # USA curl "https://pashudhan-nutri-ai.web.app/api/breeds?country=USA"
🌿 Feeding Best Practices
The Pashudhan Nutri AI API returns scientifically optimised rations. To help your users get the best real-world outcomes, consider surfacing the following guidance alongside the formulation results.
Total Mixed Ration (TMR) — Prevent Sorting
When feeding a TMR, mix dry roughage with concentrates and wet ingredients (silage, green fodder) thoroughly in the manger or a chaff cutter. Add a small amount of water or molasses to bind fine particles. This prevents dominant animals from sorting out concentrates and consuming excess starch, which causes acidosis and laminitis in high-yielding cows.
vet_rules response contains a sorting or dominance warning, display a prominent banner to your user advising them to use TMR mixing.Transition Cow Management (21 Days Before Calving)
The transition period is the most critical phase in a dairy cow's production cycle. Follow these rules for close-up dry cows:
- Feed anionic salts (e.g., calcium chloride, ammonium sulphate) to keep DCAD negative (-10 to -15 mEq/100g DM), which prevents milk fever (hypocalcaemia).
- Limit dietary calcium to < 0.5% DM to prime the parathyroid hormone response before calving.
- Avoid over-conditioning — target BCS 3.0–3.25 at calving to reduce risk of fatty liver and ketosis.
- Provide propylene glycol (300 mL/day) as a gluconeogenic precursor for cows with BCS > 3.5 going into the dry period.
production_stage: "close_up_dry" to trigger DCAD-targeted formulation automatically. Always pass this stage for animals within 3 weeks of expected calving.Heat Stress Mitigation (THI > 72)
When the Temperature-Humidity Index (THI) exceeds 72, dairy cows can lose 2–4 kg of milk per day. The API's THI response field signals when heat stress is active. Advise your users to:
- Shift feeding times to early morning (5–7 AM) and late evening (7–10 PM) when ambient temperature is lower and DMI is higher.
- Increase bypass fat (e.g., Calcium Soap of Fatty Acids, 200–300 g/day) to compensate for reduced DMI without increasing rumen heat load.
- Ensure continuous access to clean, cool water — heat-stressed cows drink 50% more. Install shade nets over water troughs.
- Add sodium bicarbonate (100–150 g/day) as a rumen buffer — heat stress reduces salivation and ruminal buffering capacity.
location field (city or "lat,lon") in individual formulation requests. The API automatically fetches live THI and adjusts NDF and energy constraints.🐄 Herd Management Tips
Grouping Strategy
For herd formulation to be most effective, group animals with similar nutritional needs. The following grouping strategy is recommended for semi-intensive farms:
| Group | Animals | Key Nutritional Priority |
|---|---|---|
| High-yield Lactating | Fresh cows + cows giving >20 L/day (DIM 5–100) | Max NEL density, bypass protein |
| Mid-yield Lactating | Cows giving 10–20 L/day (DIM 100–200) | Balanced cost/performance |
| Late Lactation / Dry Off | Cows giving <10 L/day (DIM >200) | Reduce energy, prevent over-conditioning |
| Close-Up Dry | 21 days before calving | Anionic diet, low Ca, monitor BCS |
| Far-Off Dry | 60–22 days before calving | Maintenance only, high roughage |
| Heifers | 0–24 months | Growth, mineral balance, no urea |
Manger Space & Feeding Frequency
- Provide minimum 60 cm of manger space per cow. Inadequate space is the single biggest cause of low DMI and feed sorting in most farm conditions.
- Feed at least twice daily (morning + evening). For high-yielding cows (>25 L), three feedings significantly improve DMI and milk fat.
- Push up feed every 2–3 hours to encourage eating. Cows eat most actively in the 2 hours after milking.
- Weigh feed refusals daily. Target 3–5% refusal — if refusals are zero, the cow is underfed; if >10%, the ration palatability is low.
Monitoring & Body Condition Score (BCS)
BCS is the most practical on-farm indicator of energy balance. Train your users to score their herd monthly:
| Stage | Target BCS | Action if Below | Action if Above |
|---|---|---|---|
| Calving | 3.0 – 3.25 | Increase concentrate pre-calving | Reduce energy in dry period |
| Early Lactation (DIM 0–60) | 2.5 – 3.0 | Add bypass fat, limit milk goal | Monitor for fatty liver |
| Peak / Mid Lactation | 2.75 – 3.25 | Increase energy density | Normal range |
| Drying Off | 3.0 – 3.5 | Supplement energy, check parasites | Restrict concentrate |
avg_bcs in each herd entry. The API uses this to detect negative energy balance risk and may return a NEB warning in warnings[].🌞 Seasonal Feeding Calendar
Ingredient availability and nutritional value varies significantly by season in India. Use the month field in all API calls — the engine automatically adjusts ingredient prices and availability based on the season for the given state.
| Season | Months | Key Available Feeds | Watch Out For |
|---|---|---|---|
| Summer (Garmi) | March – June | Maize silage (if stored), dry straw, cotton seed | Heat stress (THI > 72), water scarcity, low green fodder — supplement bypass fat |
| Monsoon (Barsaat) | July – September | Fresh green fodder (napier, bajra, maize), cheap prices | Mycotoxin contamination in wet silage, low DM content in fresh fodder |
| Post-Monsoon (Kharif Harvest) | October – November | Maize grain, groundnut cake, soyabean meal — peak availability and lowest prices | Aflatoxin in groundnut products post-rains — insist on tested batches |
| Winter (Sardi) | December – February | Wheat bran, mustard cake, berseem/lucerne (premium green fodder) | Optimal DMI season — highest milk yields expected; maximise production |
| Spring (Rabi Harvest) | March | Wheat straw (new crop), cheap bran | Transition from good winter to summer heat — start heat stress protocols early |
🧬 Biological Constraints & Validations
The Pashudhan Nutri API actively guards against biologically impossible inputs to ensure generated formulations remain safe and adhere to ICAR & NASEM standards. All limits are widened appropriately to accommodate the longer gestation and slower maturity of Buffalo breeds.
400 Bad Request and a detailed ValidationError explaining the biological mismatch.
| Parameter | Constraint | Description |
|---|---|---|
body_weight_kg | 10 to 1500 | Captures from small newborn calves up to mature heavy bulls. |
milk_yield_kg_day | ≤ 100 | Maximum plausible physiological limit for daily yield. |
fat_pct | 0.5 to 15.0 | Ensures valid energy correction mathematics. |
protein_pct | 1.5 to 7.0 | Ensures valid milk protein limits. |
days_pregnant | ≤ 320 | Accommodates standard cow gestation (~285) and buffalo (~315). |
dim (Days in Milk) | ≤ 1000 | Prevents infinite lactation curves. |
parity | 1 to 20 | Biological limits on the number of lactations. |
bcs | 1.0 to 5.0 | Body condition scoring limits. |
age_months | ≤ 360 (30 years) | Absolute biological maximum age. |
| Stage Mismatch | Calf max 18 mo. Heifer max 48 mo. | The API will aggressively reject a 48-month-old calf, enforcing standard maturity timelines. |
| Health Flags Logic | Conditional | protein_pct only used if lactating. steaming_up only used if pregnant/dry. |
⚠ Error Codes Reference
The API returns standard HTTP status codes. Always check the detail field in error responses for a human-readable message.
| Code | Meaning | Resolution |
|---|---|---|
| 200 | Success | Process the response normally. |
| 400 | Bad Request — invalid payload | Check required fields, animal count limits (<=15 for herd), valid month (1–12). |
| 401 | Unauthorised — missing or invalid API key | Verify the x-api-key header is included and the key is active. |
| 403 | Forbidden — plan limit exceeded or wrong role | Check your credit balance via GET /api/enterprise/status. Upgrade plan if needed. |
| 429 | Rate Limited — monthly quota exhausted | Monthly limit reset on the 1st. Upgrade to Pro API or Enterprise Max plan. |
| 500 | Server Error — formulation engine issue | Retry once. If persistent, contact support with the request body and timestamp. |
AuthError (401/403), ValidationError (400), RateLimitError (429), and APIError (5xx) — so you can handle them cleanly in application code.