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")
# BioGas Mode example
biogas = client.biogas.formulate(
animal_type = "cow",
breed = "HF_crossbred",
body_weight_kg = 500,
milk_yield_kg_day = 12,
fat_pct = 4.0,
production_stage = "mid_lactation",
state = "Punjab",
month = 6
)
print(biogas.effective_mode) # "balanced_biogas" (auto-set)
print(biogas.biogas_analysis.fresh_dung_kg) # 42.4
print(biogas.biogas_analysis.economics.net_benefit_month) # 1320.0
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 |
| farm_mode optional | string | Optimization goal: "dairy" (default), "biogas", or "balanced_biogas". When omitted, uses the account's saved farm mode from profile. Lactating animals in "biogas" mode auto-switch to "balanced_biogas". |
| milk_price_inr optional | number | Milk price per liter in INR (India) or USD (USA). Overrides the saved profile price for this request only. Used in economic analysis. Defaults to state-wise average. |
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..."],
"biogas_analysis": {
"effective_mode": "balanced_biogas",
"mode_override_reason": "Lactating animal \u2014 auto-switched to balanced_biogas",
"fresh_dung_kg": 42.4,
"fecal_dm_kg": 7.2,
"biogas_liters": 1350,
"methane_liters": 810,
"slurry_kg": 22.0,
"economics": {
"biogas_revenue_day": 47.0,
"milk_revenue_change_day": -14.0,
"slurry_revenue_day": 11.0,
"net_benefit_day": 44.0,
"net_benefit_month": 1320.0
}
}
}
],
"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 }
}
}
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.
The biogas_analysis object is returned when farm_mode is biogas or balanced_biogas. Enterprise herd-level biogas endpoints require Enterprise or EnterpriseMax plan.
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"
♻️ BioGas Formulation
Dedicated endpoints for biogas farms to maximize dung and excreta output for biogas digesters, while keeping animals within safe physiological and nutritional limits. Supports India (INR) and USA (USD) ingredient databases.
Generate a biogas-optimized ration for a single animal. Deducts 2 API credits. Uses the same animal parameters as /api/formulate, plus the optional biogas_mode parameter.
| Parameter | Type | Description |
|---|---|---|
| biogas_mode optional | string | "biogas_dung_max" (default) or "balanced_biogas". The system auto-overrides to balanced_biogas for lactating / late-pregnant animals. |
| biogas_price_per_m3 optional | number | CBG or biogas sale price in ₹/m³. Defaults to saved enterprise setting or ₹35/m³. |
| milk_price_inr optional | number | Milk price per liter. Defaults to saved profile setting or state average. |
All other parameters same as /api/formulate (animal_type, body_weight_kg, state, month, etc.) | ||
Side-by-side comparison: runs both dairy mode and biogas mode for the same animal and returns both results plus a comparison block. Deducts 3 API credits.
Enterprise only. Compute total herd-level dung output, daily biogas potential, recommended digester size (m³), and herd-level economics from a list of animal groups. Deducts 6 API credits. Maximum 500 animals per call.
Read or update enterprise-level biogas configuration: plant capacity (m³), CBG price (₹/m³), slurry price (₹/kg), and default farm mode.
/api/biogas/* endpoints are available on all plans. The /api/enterprise/biogas/* endpoints require an Enterprise or EnterpriseMax API plan. Enterprise accounts get higher rate limits: 100 req/min vs 30 req/min for standard accounts.
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"
Custom Ingredients Management
Manage custom feed ingredients unique to your enterprise account. These ingredients will be saved securely to your cloud database and automatically bypass standard formulation checks, dynamically integrating into the LP solver constraints. Requires x-api-key.
Create a new custom ingredient. The server will automatically compute all 15+ derived nutrient values (TDN, NDF, energy fractions) based on the 5 mandatory inputs.
Request Body
| Parameter | Type | Description |
|---|---|---|
| name required | string | Name of your custom feed (e.g. My Special Pellets) |
| price_INR_kg_fresh required | number | Cost per kg fresh (e.g. 24.50) |
| moisture_pct required | number | Moisture percentage (e.g. 10.0) |
| CP_pct_DM required | number | Crude Protein % on Dry Matter basis |
| EE_pct_DM required | number | Ether Extract (Fat) % on Dry Matter basis |
| crude_fibre_pct required | number | Crude Fibre % on Dry Matter basis |
| ash_pct_DM required | number | Total Ash (Minerals) % on Dry Matter basis |
{
"name": "Super Yield Pellet",
"price_INR_kg_fresh": 22.50,
"moisture_pct": 12.0,
"CP_pct_DM": 20.0,
"EE_pct_DM": 4.5,
"crude_fibre_pct": 10.0,
"ash_pct_DM": 8.0
}
List all custom ingredients associated with your enterprise key.
Update an existing custom ingredient. The server will recalculate derived values if you change the primary macro-nutrients.
Permanently delete a custom ingredient.
🌿 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.🐄 Animal Registry API
The Animal Registry API lets your platform register named animals and build personalised nutrition intelligence per animal. Each animal accumulates real milk-slip outcomes that auto-update a learned_profile — running averages for fat%, SNF%, and milk yield. This profile is automatically used by /api/formulate when animal_id is supplied.
dairy_id.POST /api/animals/register — Register Animal
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | REQ | Animal name or label (e.g. "Rani"). |
| animal_type | string | REQ | "cow" | "buffalo" | "heifer" | "bull" | "calf_weaned" |
| breed | string | REQ | Breed string (e.g. "Murrah_buffalo"). See GET /api/breeds. |
| current_stage | string | OPT | Production stage. Default: "mid_lactation". |
| parity | int | OPT | Number of calves born so far. Default: 1. |
| tag_id | string | OPT | Ear tag / farm ID number. |
| dairy_id | string | OPT | Farm/dairy ID for enterprise multi-farm namespacing. |
import pashudhan_ai client = pashudhan_ai.Client(api_key="pd_your_key_here") # Register an animal animal = client.register_animal( name = "Rani", animal_type = "buffalo", breed = "Murrah_buffalo", current_stage = "mid_lactation", parity = 3, tag_id = "MH-042", ) print(animal.animal_id) # e.g. "a3f9c1b2"
GET /api/animals — List All Animals
Returns all registered animals for the authenticated account, newest first. Each animal includes its learned_profile with running averages. Filter by dairy using the optional ?dairy_id= query parameter.
# List all animals animals = client.list_animals() for a in animals: lp = a.learned_profile print(a.name, f"avg_fat={lp.avg_fat_pct}% conf={lp.confidence_level}") # Filter by dairy farm farm_animals = client.list_animals(dairy_id="d4a2b7c8e1")
POST /api/animals/{id}/outcomes — Submit Outcome
Submit a real-world milk-slip result for an animal. Each submission automatically recalculates the animal's learned_profile (running averages for fat%, SNF%, milk yield) and raises the confidence level as more data accumulates.
| Field | Type | Required | Description |
|---|---|---|---|
| actual_milk_yield_kg | float | REQ | Actual milk yield (kg/day) from today's slip. |
| actual_fat_pct | float | REQ | Actual milk fat %. |
| actual_snf_pct | float | OPT | SNF % if available. |
| days_elapsed | int | OPT | Days since the ration was applied. Default: 7. |
| health_events | list | OPT | Observations e.g. ["normal"]. |
| bcs_score | float | OPT | Body condition score (1–5). |
| ration_id | string | OPT | Report ID of the ration that was fed. |
# Submit a milk-slip outcome outcome = client.record_outcome( animal_id = "a3f9c1b2", actual_milk_yield_kg = 19.5, actual_fat_pct = 7.2, actual_snf_pct = 8.9, health_events = ["normal"], ) # After 15+ outcomes, confidence = "high" — formulations # automatically use the animal's learned profile updated = client.get_animal("a3f9c1b2") print(updated.learned_profile.confidence_level) # "medium" / "high" print(updated.learned_profile.avg_fat_pct) # e.g. 7.1
Full Animal SDK Reference
# All animal registry methods client.register_animal(name, animal_type, breed, ...) # → AnimalProfile client.list_animals(dairy_id=None) # → List[AnimalProfile] client.get_animal(animal_id) # → AnimalProfile client.delete_animal(animal_id) # → bool client.record_outcome(animal_id, milk_kg, fat_pct, ...) # → AnimalOutcome # AnimalProfile attributes animal.animal_id # "a3f9c1b2" animal.name # "Rani" animal.breed # "Murrah_buffalo" animal.fat_trend # "above_avg" / "average" / "below_avg" (property) animal.learned_profile # LearnedProfile object .avg_fat_pct # 7.1 .avg_milk_yield_kg # 19.2 .confidence_level # "low" | "medium" | "high" .total_outcomes_recorded # 18
🏭 Multi-Dairy API
Enterprise accounts can manage multiple dairy farms under a single API key. Each dairy has its own animals, custom ingredients, and performance history. Use dairy_id to namespace animals and formulation requests to a specific farm.
ent_pro or ent_promax plan. Individual accounts see a single default farm.POST /api/dairies — Register a Dairy Farm
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | REQ | Farm name (e.g. "Singh Dairy — Ludhiana Unit 2"). |
| location | string | OPT | Farm city/state (e.g. "Ludhiana, Punjab"). |
# Create a dairy farm farm = client.register_dairy( name = "Singh Dairy — Ludhiana Unit 2", location = "Ludhiana, Punjab", ) print(farm.dairy_id) # e.g. "d4a2b7c8e1" # Register animals under this farm animal = client.register_animal( name = "Rani", animal_type = "buffalo", breed = "Murrah_buffalo", dairy_id = farm.dairy_id, # ← namespace to farm )
GET /api/dairies — List All Farms
Returns all dairy farms registered under this enterprise account. Each farm includes its animal_count.
# List all dairy farms farms = client.list_dairies() for farm in farms: print(farm.name, farm.location, farm.animal_count) # Full per-farm workflow farms = client.list_dairies() for farm in farms: animals = client.list_animals(dairy_id=farm.dairy_id) print(f"{farm.name}: {len(animals)} animals") for a in animals: result = client.formulate( animal_type = a.animal_type, breed = a.breed, body_weight_kg = 480, milk_yield_kg_day = a.learned_profile.avg_milk_yield_kg or 15, fat_pct = a.learned_profile.avg_fat_pct or 6.5, production_stage = a.current_stage, state = "Punjab", month = 7, ) print(f"{a.name}: ₹{result.least_cost.total_cost_local_day:.0f}/day")
Full Multi-Dairy SDK Reference
# Multi-dairy methods (enterprise only) client.register_dairy(name, location="") # → DairyFarm client.list_dairies() # → List[DairyFarm] client.delete_dairy(dairy_id) # → bool (deletes all animals) # DairyFarm attributes farm.dairy_id # "d4a2b7c8e1" farm.name # "Singh Dairy — Ludhiana Unit 2" farm.location # "Ludhiana, Punjab" farm.animal_count # 24 farm.created_at # ISO timestamp
pip install --upgrade pashudhan_ai