Spaces:
Running
Running
| """ | |
| Stage 4: Farmer Translator - Natural Language Output | |
| """ | |
| import json | |
| from typing import Dict, Any | |
| from openai import OpenAI | |
| class FarmerTranslator: | |
| """Stage 4: Convert technical data to farmer-friendly advice""" | |
| def __init__(self, client: OpenAI): | |
| self.client = client | |
| def translate(self, query: str, compiled_data: Dict[str, Any], location: Dict[str, Any]) -> str: | |
| """ | |
| Generate farmer-friendly response from technical data | |
| Returns: | |
| str: Natural language advice for farmers | |
| """ | |
| data_summary = json.dumps(compiled_data.get("data", {}), indent=2) | |
| system_prompt = f"""You are an agricultural advisor for farmers in {location['name']}. | |
| Task: Convert technical data into clear, actionable advice. | |
| Guidelines: | |
| 1. Use simple language (avoid jargon) | |
| 2. Provide specific, actionable recommendations | |
| 3. Include risk levels (LOW/MODERATE/HIGH) when relevant | |
| 4. Explain WHY you're making recommendations | |
| 5. If data is missing, acknowledge it but provide useful advice | |
| Structure: | |
| - Clear summary | |
| - Current conditions | |
| - Risk assessment (if applicable) | |
| - Specific recommendations | |
| - Action items | |
| Data from {len(compiled_data.get('successful_servers', []))} sources: | |
| {data_summary} | |
| """ | |
| if compiled_data.get("failed_servers"): | |
| system_prompt += f"\n\nNote: Some sources failed: {compiled_data['failed_servers']}" | |
| system_prompt += "\nWork with available data, note limitations." | |
| try: | |
| response = self.client.chat.completions.create( | |
| model="gpt-4o", | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": f"Farmer query: {query}\n\nProvide advice based on the data."} | |
| ], | |
| temperature=0.7 | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| return f"⚠️ Unable to generate advice: {str(e)}" |