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.

B2B Only. This API is exclusively for Enterprises and Dairy Cooperatives. Individual farmers should use the Web Formulator.
REST
HTTP / JSON
ICAR+NASEM
2013+2021 Standards
~45-60s
Avg Response Time

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.

Key Format: All keys start with 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

  1. Go to your API Dashboard and generate an Enterprise API Key.
  2. Click the Download MCP Config button next to your key.
  3. This downloads a pashudhan_mcp_config.json file.
  4. 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
  5. Restart Claude Desktop. The AI will now have access to the Pashudhan Formulation Tools!
Security Note: The MCP Server runs 100% locally on your machine and uses your existing Enterprise API key as a secure bridge. The AI model itself never sees your raw API key.

Python SDK — Install

📦 Official SDK: The pashudhan_ai package wraps the REST API with a clean, Pythonic interface. No need to handle HTTP headers or JSON manually.

Install via pip

pip install pashudhan_ai

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

POST /api/formulate

The core endpoint. Returns up to 4 optimized ration strategies in JSON.

Request Body

ParameterTypeDescription
animal_type requiredstringcow, buffalo, heifer, bull
breed requiredstringe.g. HF_crossbred, Sahiwal, Murrah
body_weight_kg requirednumberBody weight in kg (e.g. 450)
milk_yield_kg_day requirednumberDaily milk yield in kg
fat_pct requirednumberMilk fat % (e.g. 3.5). Only used if lactating.
protein_pct optionalnumberMilk protein % (e.g. 3.2). Default: breed avg. Only used if lactating.
production_stage requiredstringlactating, dry, growing, pre_calving
dim optionalnumberDays in Milk. Affects intake & ketosis risk scoring.
parity optionalnumberLactation number. Default 1. Used for lactating/dry.
days_pregnant optionalnumberDays of pregnancy. Triggers fetal energy demands if > 60.
bcs optionalnumberBody Condition Score (1-5). Default 3.0.
health_flags optionalarrayStrings e.g. ["ketosis_history", "steaming_up"]
state requiredstringState or region (e.g. Punjab, Gujarat)
month requirednumberMonth 1–12 for seasonal ingredient filter
use_ai optionalbooleanEnable AI Nutritionist critique (Pro/ProMax only)
location optionalstringCity 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 }
  }
}
Feature Availability: The 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.
POST /api/herd-formulate

Formulates for an entire herd. Deducts 4 API credits per call.

Request Body

ParameterTypeDescription
groups requiredarrayList of animal group dictionaries (each containing entries)
state requiredstringState or region (e.g. Punjab, Gujarat)
month requirednumberMonth 1–12 for seasonal ingredient filter
farmer_ingredients optionalarrayList 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."
      }
    }
  ]
}
GET /api/plans

Returns all available subscription plans. No authentication required.

curl https://pashudhan-nutri-ai.web.app/api/plans
GET /api/enterprise/status

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
}
GET /api/ingredients-list

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"
GET /api/countries

Returns a list of supported countries and their configurations (currency, regions). No authentication required.

curl https://pashudhan-nutri-ai.web.app/api/countries
GET /api/breeds

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.

💡 API Tip: If the 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.
💡 API Tip: The API uses 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.
💡 API Tip: Pass the 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:

GroupAnimalsKey Nutritional Priority
High-yield LactatingFresh cows + cows giving >20 L/day (DIM 5–100)Max NEL density, bypass protein
Mid-yield LactatingCows giving 10–20 L/day (DIM 100–200)Balanced cost/performance
Late Lactation / Dry OffCows giving <10 L/day (DIM >200)Reduce energy, prevent over-conditioning
Close-Up Dry21 days before calvingAnionic diet, low Ca, monitor BCS
Far-Off Dry60–22 days before calvingMaintenance only, high roughage
Heifers0–24 monthsGrowth, 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:

StageTarget BCSAction if BelowAction if Above
Calving3.0 – 3.25Increase concentrate pre-calvingReduce energy in dry period
Early Lactation (DIM 0–60)2.5 – 3.0Add bypass fat, limit milk goalMonitor for fatty liver
Peak / Mid Lactation2.75 – 3.25Increase energy densityNormal range
Drying Off3.0 – 3.5Supplement energy, check parasitesRestrict concentrate
📢 SDK Tip: Pass 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.

SeasonMonthsKey Available FeedsWatch Out For
Summer (Garmi)March – JuneMaize silage (if stored), dry straw, cotton seedHeat stress (THI > 72), water scarcity, low green fodder — supplement bypass fat
Monsoon (Barsaat)July – SeptemberFresh green fodder (napier, bajra, maize), cheap pricesMycotoxin contamination in wet silage, low DM content in fresh fodder
Post-Monsoon (Kharif Harvest)October – NovemberMaize grain, groundnut cake, soyabean meal — peak availability and lowest pricesAflatoxin in groundnut products post-rains — insist on tested batches
Winter (Sardi)December – FebruaryWheat bran, mustard cake, berseem/lucerne (premium green fodder)Optimal DMI season — highest milk yields expected; maximise production
Spring (Rabi Harvest)MarchWheat straw (new crop), cheap branTransition 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.

Strict Validations: If you submit values outside these ranges, the API will reject the request with an HTTP 400 Bad Request and a detailed ValidationError explaining the biological mismatch.
ParameterConstraintDescription
body_weight_kg10 to 1500Captures from small newborn calves up to mature heavy bulls.
milk_yield_kg_day≤ 100Maximum plausible physiological limit for daily yield.
fat_pct0.5 to 15.0Ensures valid energy correction mathematics.
protein_pct1.5 to 7.0Ensures valid milk protein limits.
days_pregnant≤ 320Accommodates standard cow gestation (~285) and buffalo (~315).
dim (Days in Milk)≤ 1000Prevents infinite lactation curves.
parity1 to 20Biological limits on the number of lactations.
bcs1.0 to 5.0Body condition scoring limits.
age_months≤ 360 (30 years)Absolute biological maximum age.
Stage MismatchCalf max 18 mo.
Heifer max 48 mo.
The API will aggressively reject a 48-month-old calf, enforcing standard maturity timelines.
Health Flags LogicConditionalprotein_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.

CodeMeaningResolution
200SuccessProcess the response normally.
400Bad Request — invalid payloadCheck required fields, animal count limits (<=15 for herd), valid month (1–12).
401Unauthorised — missing or invalid API keyVerify the x-api-key header is included and the key is active.
403Forbidden — plan limit exceeded or wrong roleCheck your credit balance via GET /api/enterprise/status. Upgrade plan if needed.
429Rate Limited — monthly quota exhaustedMonthly limit reset on the 1st. Upgrade to Pro API or Enterprise Max plan.
500Server Error — formulation engine issueRetry once. If persistent, contact support with the request body and timestamp.
💡 SDK Behaviour: The Python SDK maps these to typed exceptions — AuthError (401/403), ValidationError (400), RateLimitError (429), and APIError (5xx) — so you can handle them cleanly in application code.