Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ricardomb-tech/surqo/llms.txt

Use this file to discover all available pages before exploring further.

The Analysis API is the intelligence layer of Surqo. Each analysis fuses 48 hours of sensor history with a 7-day weather forecast from Open-Meteo and crop-specific agronomic knowledge, then sends the combined context to Groq Llama 3.3 70B to generate actionable irrigation schedules, pest-risk assessments, and prioritised field recommendations. Once an analysis is saved you can continue the conversation with the AI agronomist — the SURQO persona — retaining full context of your farm’s data. The chat endpoint also supports image uploads for on-the-spot plant disease diagnosis.

Trigger a farm analysis

POST /api/v1/analysis/analyze — Auth required — Rate limit: 10 requests / minute
Free-plan quota: Free accounts receive 4 lifetime analyses. Once exhausted the endpoint returns 402 Payment Required. Contact the Surqo team at surqo.co/upgrade to activate unlimited analyses.
When farm_id is provided, the API retrieves up to 500 sensor readings from the last 48 hours and builds trend context for the LLM. When alert_level in the response is "critical" and you supplied alert_email, a critical-alert email is dispatched automatically in the background.

Request body

farm_name
string
required
Display name of the farm. Used in the generated report and any alert emails. Maximum 200 characters.
lat
float
required
Farm latitude in decimal degrees (-90 to 90). Used to fetch the Open-Meteo forecast.
lon
float
required
Farm longitude in decimal degrees (-180 to 180). Used to fetch the Open-Meteo forecast.
crop_type
string
required
Crop type for analysis calibration. Accepted values: maíz, yuca, plátano, café, arroz, algodón.
farm_id
uuid
UUID of the farm. When supplied, the API pulls 48 h of sensor history to enrich the LLM prompt with real field data and verifies the farm is owned by the authenticated user.
alert_email
email
Email address to notify if the analysis produces a critical alert. No email is sent for ok or warning levels.

Response 201

Returns a full AnalysisResponse object.
id
uuid
Unique analysis identifier. Use this to retrieve the analysis later or to start a chat session.
alert_level
string
Overall farm health status. One of "ok", "warning", or "critical".
main_alert
string | null
Short headline describing the primary issue detected (e.g. "Estrés hídrico moderado detectado").
water_stress_index
float | null
Normalised water stress index from 0.0 (no stress) to 1.0 (severe stress).
irrigation_needed
boolean
Whether the model recommends irrigation within the forecast window.
next_irrigation_date
string | null
ISO 8601 date string for the recommended next irrigation event.
avg_temperature_c
float | null
Average air temperature (°C) derived from the 7-day forecast.
total_rain_7d_mm
float | null
Total forecasted precipitation over the next 7 days in millimetres.
avg_vpd_kpa
float | null
Average Vapour Pressure Deficit (kPa) from recent sensor readings.
et0_7d_mm
float | null
Reference evapotranspiration (ET₀) for the next 7 days in millimetres.
summary_for_farmer
string | null
Plain-language summary of the analysis results written for a non-technical audience.
recommendations
array | null
model_used
string
LLM identifier used to generate the analysis (e.g. "groq/llama-3.3-70b-versatile").
input_tokens
integer | null
Number of tokens in the prompt sent to the LLM.
output_tokens
integer | null
Number of tokens in the LLM response.
cost_usd
float | null
Estimated cost in USD for this analysis call.
created_at
datetime
ISO 8601 timestamp of when the analysis was created.

Example

curl -X POST https://surqo-api.fly.dev/api/v1/analysis/analyze \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "farm_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "farm_name": "Finca La Esperanza",
    "lat": 8.7575,
    "lon": -75.8891,
    "crop_type": "maíz",
    "alert_email": "agricultor@ejemplo.com"
  }'
Response 201
{
  "id": "c0ffee00-1234-5678-abcd-000000000001",
  "alert_level": "warning",
  "main_alert": "Estrés hídrico moderado detectado",
  "water_stress_index": 0.67,
  "irrigation_needed": true,
  "next_irrigation_date": "2026-06-29",
  "avg_temperature_c": 29.5,
  "total_rain_7d_mm": 12.3,
  "avg_vpd_kpa": 1.42,
  "et0_7d_mm": 31.5,
  "summary_for_farmer": "Tu cultivo de maíz muestra estrés hídrico moderado. El VPD de 1.42 kPa supera el umbral óptimo y la lluvia prevista (12.3 mm) no compensará la evapotranspiración (31.5 mm) en los próximos 7 días.",
  "recommendations": [
    {
      "priority": 1,
      "category": "irrigation",
      "action": "Aplicar riego por goteo — 25 mm en las próximas 6 horas",
      "time_window": "0-6h",
      "justification": "VPD de 1.42 kPa y suelo al 38% de capacidad"
    }
  ],
  "model_used": "groq/llama-3.3-70b-versatile",
  "input_tokens": 624,
  "output_tokens": 318,
  "cost_usd": 0.0,
  "created_at": "2026-06-28T14:35:00Z"
}

Alert levels

LevelMeaning
okAll monitored parameters are within healthy thresholds. No immediate action needed.
warningOne or more parameters are approaching critical thresholds. Preventive action recommended.
criticalImmediate intervention required. If alert_email was provided, a notification is dispatched.

Error: quota exhausted

Response 402
{
  "code": "analysis_quota_exceeded",
  "message": "Usaste tus 4 análisis IA gratuitos. Contacta a nuestro equipo para activar el plan premium y tener análisis ilimitados.",
  "analyses_used": 4,
  "analyses_limit": 4,
  "contact_url": "https://surqo.co/upgrade"
}

Get analysis history

GET /api/v1/analysis/history/{farm_id} — Auth required Returns the 10 most recent analyses for a farm, sorted newest first. The farm must belong to the authenticated user.
farm_id
uuid
required
UUID of the farm whose analysis history to retrieve.
Returns 403 if the farm does not belong to the authenticated user.
curl https://surqo-api.fly.dev/api/v1/analysis/history/a1b2c3d4-e5f6-7890-abcd-ef1234567890 \
  -H "Authorization: Bearer <token>"

Get a single analysis

GET /api/v1/analysis/{analysis_id} — Auth required Returns the full AnalysisResponse for a specific analysis. Access is resolved by direct ownership (user_id); legacy analyses without a user_id are resolved through their linked farm.
analysis_id
uuid
required
UUID of the analysis to retrieve.
Returns 404 if the analysis does not exist or is not accessible by the authenticated user (the API intentionally returns 404 rather than 403 to avoid leaking record existence).
curl https://surqo-api.fly.dev/api/v1/analysis/c0ffee00-1234-5678-abcd-000000000001 \
  -H "Authorization: Bearer <token>"

Chat with the AI agronomist

POST /api/v1/analysis/chat — Auth required — Rate limit: 20 requests / minute
Free-plan token quota: Chat token usage is tracked cumulatively. When the free token budget is exhausted the endpoint returns 402. Contact the Surqo team to unlock unlimited chat.
Send a message to the SURQO AI agronomist. When analysis_id is provided, the full analysis context (crop type, alert level, stress indices, recommendations) is automatically injected into the LLM prompt. The chat also supports image uploads for plant disease diagnosis — the backend routes vision requests to Groq Llama 4 Scout or Anthropic Claude depending on configuration. Messages are persisted per session_id. Omit session_id to start a new session; include it to continue an existing conversation.

Request body

message
string
required
The user’s message to the agronomist. Maximum 2000 characters.
analysis_id
uuid
UUID of a previously generated analysis. Injects that analysis’s farm data and recommendations as context for the LLM.
session_id
uuid
UUID of an existing chat session to continue. When omitted a new session_id is generated and returned in the response.
history
array
The last few turns of conversation to include as context. Each element is a {role, content} object where role is "user" or "assistant". Recommended maximum: 10 messages.
image_base64
string
Base64-encoded image for visual plant disease diagnosis. When present the request is routed to a vision-capable model.
image_mime
string
MIME type of the uploaded image. Defaults to "image/jpeg". Common values: "image/jpeg", "image/png", "image/webp".

Response 200

response
string
The agronomist’s reply text.
session_id
uuid
Session UUID. Pass this back in subsequent requests to maintain conversation continuity.
input_tokens
integer
Number of prompt tokens consumed.
output_tokens
integer
Number of completion tokens generated.

Text message example

curl -X POST https://surqo-api.fly.dev/api/v1/analysis/chat \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "analysis_id": "c0ffee00-1234-5678-abcd-000000000001",
    "message": "¿Cada cuántos días debo regar el maíz en estas condiciones?",
    "history": []
  }'
Response 200
{
  "response": "Con un VPD de 1.42 kPa y ET₀ de 31.5 mm en 7 días, recomiendo riegos cada 2-3 días aplicando entre 20-25 mm por evento...",
  "session_id": "d1e2f3a4-b5c6-7890-1234-567890abcdef",
  "input_tokens": 412,
  "output_tokens": 185
}

Image upload example (plant disease diagnosis)

Request body
{
  "analysis_id": "c0ffee00-1234-5678-abcd-000000000001",
  "session_id": "d1e2f3a4-b5c6-7890-1234-567890abcdef",
  "message": "¿Qué enfermedad tiene esta planta?",
  "image_base64": "/9j/4AAQSkZJRgAB...",
  "image_mime": "image/jpeg",
  "history": [
    { "role": "user",      "content": "¿Cada cuántos días debo regar el maíz?" },
    { "role": "assistant", "content": "Con un VPD de 1.42 kPa..." }
  ]
}
Keep history to the last 10 messages to balance context quality against token cost. The API does not automatically truncate history — sending very long histories will increase latency and consume more of your free quota.

List chat sessions for an analysis

GET /api/v1/analysis/{analysis_id}/chat-sessions — Auth required Returns a summary list of all chat sessions initiated for a given analysis. Useful for building a sessions sidebar or continuing a previous conversation.
analysis_id
uuid
required
UUID of the analysis whose sessions to list.

Response 200

Returns an array of ChatSession objects.
session_id
uuid
Unique session identifier. Pass this as session_id in POST /api/v1/analysis/chat to resume.
started_at
datetime
Timestamp of the first message in the session.
message_count
integer
Total number of user messages in the session.
first_message
string
The first 80 characters of the session’s opening user message.
curl https://surqo-api.fly.dev/api/v1/analysis/c0ffee00-1234-5678-abcd-000000000001/chat-sessions \
  -H "Authorization: Bearer <token>"
Response 200
[
  {
    "session_id": "d1e2f3a4-b5c6-7890-1234-567890abcdef",
    "started_at": "2026-06-28T15:00:00Z",
    "message_count": 3,
    "first_message": "¿Cada cuántos días debo regar el maíz en estas condiciones?"
  }
]

Get chat history for an analysis

GET /api/v1/analysis/{analysis_id}/chat-history — Auth required Returns all persisted chat messages for an analysis in ascending chronological order, interleaving user and assistant turns. Optionally filter to a single session.
analysis_id
uuid
required
UUID of the analysis.
session_id
uuid
When provided, only messages belonging to that session are returned.

Response 200

Returns an array of ChatHistoryItem objects.
id
uuid
Unique message identifier.
session_id
uuid
Session this message belongs to.
role
string
Message author: "user" or "assistant".
content
string
Full message text.
created_at
datetime
ISO 8601 timestamp of when the message was persisted.
curl "https://surqo-api.fly.dev/api/v1/analysis/c0ffee00-1234-5678-abcd-000000000001/chat-history?session_id=d1e2f3a4-b5c6-7890-1234-567890abcdef" \
  -H "Authorization: Bearer <token>"
Response 200
[
  {
    "id": "aaaaaaaa-0000-0000-0000-000000000001",
    "session_id": "d1e2f3a4-b5c6-7890-1234-567890abcdef",
    "role": "user",
    "content": "¿Cada cuántos días debo regar el maíz en estas condiciones?",
    "created_at": "2026-06-28T15:00:00Z"
  },
  {
    "id": "aaaaaaaa-0000-0000-0000-000000000002",
    "session_id": "d1e2f3a4-b5c6-7890-1234-567890abcdef",
    "role": "assistant",
    "content": "Con un VPD de 1.42 kPa y ET₀ de 31.5 mm en 7 días...",
    "created_at": "2026-06-28T15:00:02Z"
  }
]

Build docs developers (and LLMs) love