A LoRA fine-tuned version of
Meta-Llama-3.1-8B-Instruct specialized for Pakistani crop farming advisory. The model answers general crop questions and interprets field sensor data (NDVI, EVI, NDWI, temperature, humidity) to provide concise, actionable farm advisories.
1from unsloth import FastLanguageModel
2import torch
3
4model, tokenizer = FastLanguageModel.from_pretrained(
5 model_name = "your-hf-username/finetuned-Llama-3.1-8B-Instruct",
6 max_seq_length= 2048,
7 dtype = None,
8 load_in_4bit = True,
9)
10FastLanguageModel.for_inference(model)
11
12SYSTEM_PROMPT = (
13 "You are an expert agricultural advisor specializing in Pakistani crop farming. "
14 "You can answer general crop questions and also interpret field sensor data "
15 "(NDVI, EVI, NDWI, temperature, humidity, etc.) to provide precise farm advisories. "
16 "Answer accurately and concisely based on official recommendations and best practices. "
17 "Keep answers under 3 sentences. Do not include citations, URLs, or markdown headers. "
18 "Answer directly and stop."
19)
20
21def ask(crop, question, topic="General"):
22 messages = [
23 {"role": "system", "content": SYSTEM_PROMPT},
24 {"role": "user", "content": f"[Crop: {crop} | Topic: {topic}]\n{question}"},
25 ]
26 inputs = tokenizer.apply_chat_template(
27 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"
28 ).to("cuda")
29
30 with torch.no_grad():
31 out = model.generate(
32 input_ids=inputs, max_new_tokens=150,
33 use_cache=True, temperature=0.7, top_p=0.9,
34 repetition_penalty=1.1,
35 pad_token_id=tokenizer.eos_token_id,
36 )
37 return tokenizer.decode(out[0][inputs.shape[1]:], skip_special_tokens=True).strip()
38
39print(ask("Maize", "How much seed is required per acre?"))
40# → 50-60 kg per acre for good stand at 40-45 thousand plants per acre.
1def ask_farm(crop, stage, sensors: dict):
2 sensor_str = "\n".join(f"{k}: {v}" for k, v in sensors.items())
3 messages = [
4 {"role": "system", "content": SYSTEM_PROMPT},
5 {"role": "user", "content": (
6 f"[Crop: {crop} | Stage: {stage}]\n"
7 f"Field sensor readings:\n{sensor_str}\n\n"
8 f"Provide a detailed farm advisory based on these readings."
9 )},
10 ]
11 inputs = tokenizer.apply_chat_template(
12 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"
13 ).to("cuda")
14
15 with torch.no_grad():
16 out = model.generate(
17 input_ids=inputs, max_new_tokens=200,
18 use_cache=True, temperature=0.7, top_p=0.9,
19 repetition_penalty=1.1,
20 pad_token_id=tokenizer.eos_token_id,
21 )
22 return tokenizer.decode(out[0][inputs.shape[1]:], skip_special_tokens=True).strip()
23
24print(ask_farm("Cotton", "Boll Formation", {"NDVI": 0.38, "temperature_c": 34, "relative_humidity": 55}))
Developed for the AgroBot-Research project.