drrobot9 commited on
Commit
3dd2c24
·
verified ·
1 Parent(s): 9c38b67

Update app/text_to_text/farm_agent.py

Browse files
Files changed (1) hide show
  1. app/text_to_text/farm_agent.py +6 -14
app/text_to_text/farm_agent.py CHANGED
@@ -16,7 +16,6 @@ from app.config import config
16
  log = logging.getLogger("farmlingua")
17
 
18
  SYSTEM_PROMPT = """You are FarmLingua AI, an expert agricultural assistant for Nigerian farmers built by Kawafarm LTD.
19
-
20
  RULES:
21
  - Answer ONLY farming-related questions — crops, livestock, soil, irrigation, fertilizer, pest control, harvest, and agribusiness.
22
  - If a question mentions a food item (e.g. "how to cook rice"), extract the crop name (rice) and answer how to PLANT and FARM it instead.
@@ -25,7 +24,6 @@ RULES:
25
  - Give complete, structured answers covering: land preparation, planting, inputs, care, harvest, and business or budget where relevant.
26
  - Never repeat the user's question. No preamble. Answer directly.
27
  - End every response by informing the user that Kawafarm LTD built you to help Nigerian farmers.
28
-
29
  FORMATTING RULES — CRITICAL:
30
  - Do NOT use markdown of any kind.
31
  - Do NOT use asterisks, hashtags, bold, italic, or any special characters for formatting.
@@ -66,7 +64,6 @@ class FarmAgent:
66
  )
67
  self._trans_model.eval()
68
 
69
-
70
  self._validate_language_codes()
71
 
72
 
@@ -77,7 +74,7 @@ class FarmAgent:
77
  )
78
  self._llm_model = AutoModelForCausalLM.from_pretrained(
79
  config.LLM_MODEL,
80
- torch_dtype=torch.float16 if device == "cuda" else torch.float32,
81
  device_map="auto",
82
  token=token,
83
  )
@@ -85,7 +82,6 @@ class FarmAgent:
85
  log.info("FarmAgent ready.")
86
 
87
  def _validate_language_codes(self):
88
- """Validate FLORES-200 codes resolve to real token IDs at startup."""
89
  log.info("[VALIDATE] Checking NLLB FLORES-200 token IDs...")
90
  for lang, code in config.NLLB_CODES.items():
91
  try:
@@ -96,7 +92,7 @@ class FarmAgent:
96
  except Exception as e:
97
  log.error(f" {lang} ({code}) failed — {e}")
98
 
99
- # Language detection
100
 
101
  def detect_language(self, text: str) -> tuple:
102
  clean = text.strip().replace("\n", " ")
@@ -187,7 +183,7 @@ class FarmAgent:
187
  text = re.sub(r'\n{3,}', '\n\n', text)
188
  return text.strip()
189
 
190
- # LLM streaming
191
 
192
  def stream_response(self, history: list, english_message: str):
193
  log.info(f"[LLM] Sending to Qwen: {english_message[:120]}")
@@ -218,17 +214,13 @@ class FarmAgent:
218
  kwargs=dict(
219
  **model_inputs,
220
  streamer=streamer,
221
- max_new_tokens=config.LLM_MAX_TOKENS,
222
- temperature=config.LLM_TEMPERATURE,
223
- do_sample=True,
224
- repetition_penalty=1.5,
225
- no_repeat_ngram_size=4,
226
  ),
227
  ).start()
228
 
229
  return streamer
230
 
231
- # Full pipeline
232
 
233
  def process(self, user_text: str, history: list) -> dict:
234
  detected_lang, confidence = self.detect_language(user_text)
@@ -252,5 +244,5 @@ class FarmAgent:
252
  }
253
 
254
 
255
- # Singleton
256
  farm_agent = FarmAgent()
 
16
  log = logging.getLogger("farmlingua")
17
 
18
  SYSTEM_PROMPT = """You are FarmLingua AI, an expert agricultural assistant for Nigerian farmers built by Kawafarm LTD.
 
19
  RULES:
20
  - Answer ONLY farming-related questions — crops, livestock, soil, irrigation, fertilizer, pest control, harvest, and agribusiness.
21
  - If a question mentions a food item (e.g. "how to cook rice"), extract the crop name (rice) and answer how to PLANT and FARM it instead.
 
24
  - Give complete, structured answers covering: land preparation, planting, inputs, care, harvest, and business or budget where relevant.
25
  - Never repeat the user's question. No preamble. Answer directly.
26
  - End every response by informing the user that Kawafarm LTD built you to help Nigerian farmers.
 
27
  FORMATTING RULES — CRITICAL:
28
  - Do NOT use markdown of any kind.
29
  - Do NOT use asterisks, hashtags, bold, italic, or any special characters for formatting.
 
64
  )
65
  self._trans_model.eval()
66
 
 
67
  self._validate_language_codes()
68
 
69
 
 
74
  )
75
  self._llm_model = AutoModelForCausalLM.from_pretrained(
76
  config.LLM_MODEL,
77
+ torch_dtype="auto",
78
  device_map="auto",
79
  token=token,
80
  )
 
82
  log.info("FarmAgent ready.")
83
 
84
  def _validate_language_codes(self):
 
85
  log.info("[VALIDATE] Checking NLLB FLORES-200 token IDs...")
86
  for lang, code in config.NLLB_CODES.items():
87
  try:
 
92
  except Exception as e:
93
  log.error(f" {lang} ({code}) failed — {e}")
94
 
95
+
96
 
97
  def detect_language(self, text: str) -> tuple:
98
  clean = text.strip().replace("\n", " ")
 
183
  text = re.sub(r'\n{3,}', '\n\n', text)
184
  return text.strip()
185
 
186
+ # LLM streaming
187
 
188
  def stream_response(self, history: list, english_message: str):
189
  log.info(f"[LLM] Sending to Qwen: {english_message[:120]}")
 
214
  kwargs=dict(
215
  **model_inputs,
216
  streamer=streamer,
217
+ max_new_tokens=512,
 
 
 
 
218
  ),
219
  ).start()
220
 
221
  return streamer
222
 
223
+ # Full pipeline
224
 
225
  def process(self, user_text: str, history: list) -> dict:
226
  detected_lang, confidence = self.detect_language(user_text)
 
244
  }
245
 
246
 
247
+
248
  farm_agent = FarmAgent()