Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,327 +1,447 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import openai
|
| 5 |
-
from typing import Dict, Any, Optional, List
|
| 6 |
-
from dataclasses import dataclass
|
| 7 |
-
import logging
|
| 8 |
-
from openai import OpenAI
|
| 9 |
-
from dotenv import load_dotenv
|
| 10 |
-
import os
|
| 11 |
-
|
| 12 |
-
# Import your modules
|
| 13 |
-
from easy_agents import EASYFARMS_FUNCTION_SCHEMAS, execute_easyfarms_function
|
| 14 |
-
from alert import WEATHER_TOOLS , execute_function
|
| 15 |
-
from conversation_manager import ConversationManager
|
| 16 |
-
|
| 17 |
-
# Configure logging
|
| 18 |
-
logging.basicConfig(level=logging.INFO)
|
| 19 |
-
logger = logging.getLogger(__name__)
|
| 20 |
-
|
| 21 |
-
# Load environment variables
|
| 22 |
-
load_dotenv()
|
| 23 |
-
|
| 24 |
-
@dataclass
|
| 25 |
-
class Config:
|
| 26 |
-
"""Configuration settings"""
|
| 27 |
-
api_key: str
|
| 28 |
-
api_url: str
|
| 29 |
-
model_name: str
|
| 30 |
-
max_retries: int = 3
|
| 31 |
-
temperature: float = 0.5
|
| 32 |
-
|
| 33 |
-
@classmethod
|
| 34 |
-
def from_env(cls):
|
| 35 |
-
"""Load configuration from environment variables"""
|
| 36 |
-
return cls(
|
| 37 |
-
api_key=os.getenv("API_KEY"),
|
| 38 |
-
api_url=os.getenv("API_URL"),
|
| 39 |
-
model_name=os.getenv("MODEL_NAME")
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
class EasyFarmsAssistant:
|
| 43 |
-
"""Enhanced EasyFarms AI Assistant with weather integration and persistent sessions"""
|
| 44 |
-
|
| 45 |
-
def __init__(self, config: Optional[Config] = None, manager: Optional[ConversationManager] = None):
|
| 46 |
-
"""
|
| 47 |
-
Initialize the assistant with configuration and a conversation manager.
|
| 48 |
-
|
| 49 |
-
Args:
|
| 50 |
-
config (Optional[Config]): Configuration object. If None, loads from environment.
|
| 51 |
-
manager (Optional[ConversationManager]): Manager for handling conversation persistence.
|
| 52 |
-
"""
|
| 53 |
-
self.config = config or Config.from_env()
|
| 54 |
-
|
| 55 |
-
# Validate configuration
|
| 56 |
-
if not all([self.config.api_key, self.config.api_url, self.config.model_name]):
|
| 57 |
-
raise ValueError("Missing required configuration: API_KEY, API_URL, and MODEL_NAME must be set")
|
| 58 |
-
|
| 59 |
-
self.client = OpenAI(
|
| 60 |
-
api_key=self.config.api_key,
|
| 61 |
-
base_url=self.config.api_url
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
# All available functions from both modules are combined into the tools list
|
| 65 |
-
self.tools = self._initialize_tools()
|
| 66 |
-
|
| 67 |
-
# Use the provided conversation manager or create a new one
|
| 68 |
-
self.manager = manager or ConversationManager()
|
| 69 |
-
|
| 70 |
-
# System prompts
|
| 71 |
-
self.system_prompt = """You are the AI assistant for EasyForms Agritech Solutions. Your task is to provide users with clear, concise, and actionable responses regarding agriculture, crop management, production, treatment, weather alerts, and related queries.
|
| 72 |
-
|
| 73 |
-
Core Capabilities:
|
| 74 |
-
- Crop recommendations based on soil and weather conditions
|
| 75 |
-
- Fertilizer recommendations for specific crops
|
| 76 |
-
- Plant disease detection and treatment advice
|
| 77 |
-
- Weather alerts and forecasts for farming decisions
|
| 78 |
-
- Market data and commodity prices
|
| 79 |
-
- General agricultural guidance
|
| 80 |
-
|
| 81 |
-
Rules:
|
| 82 |
-
1. Check if any relevant function_tools or datasets are available for this query.
|
| 83 |
-
2. If available, use the functions to fetch information and generate the final user-facing response.
|
| 84 |
-
3. If the functions or data are unavailable, do **not stop**; instead, generate a general, well-reasoned response based on your own knowledge.
|
| 85 |
-
4. Keep the response **simple, smooth, well-pointed, and concise**.
|
| 86 |
-
5. Structure the response with bullet points or numbered steps where helpful.
|
| 87 |
-
6. Provide practical, actionable advice a user can implement immediately.
|
| 88 |
-
7. Use English or Hindi based on user preference.
|
| 89 |
-
8. If any information is uncertain, mention it clearly and suggest alternatives.
|
| 90 |
-
9. For weather-related queries, prioritize safety and timely alerts."""
|
| 91 |
-
|
| 92 |
-
self.final_system = """You are the final response assistant for EasyForms Agritech Solutions. Use the outputs from previous function calls to generate a **clear, concise, actionable response** for the user.
|
| 93 |
-
|
| 94 |
-
Rules:
|
| 95 |
-
1. Combine the function outputs and your own reasoning to answer the query.
|
| 96 |
-
2. Keep responses simple, smooth, well-pointed, and concise.
|
| 97 |
-
3. Structure response with headings or bullet points if helpful.
|
| 98 |
-
4. Provide practical advice that a farmer or user can implement immediately.
|
| 99 |
-
5. If some data is missing, clearly state it and offer alternatives.
|
| 100 |
-
6. Use English or Hindi based on the user preference.
|
| 101 |
-
7. For weather alerts, emphasize urgency and protective measures."""
|
| 102 |
-
|
| 103 |
-
def _initialize_tools(self) -> List[Dict]:
|
| 104 |
-
"""Initialize and convert all function schemas to the new tools format"""
|
| 105 |
-
tools = []
|
| 106 |
-
|
| 107 |
-
# Convert EasyFarms schemas to the new format
|
| 108 |
-
for schema in EASYFARMS_FUNCTION_SCHEMAS:
|
| 109 |
-
tool = {
|
| 110 |
-
"type": "function",
|
| 111 |
-
"function": {
|
| 112 |
-
"name": schema["name"],
|
| 113 |
-
"description": schema["description"],
|
| 114 |
-
"parameters": schema["parameters"]
|
| 115 |
-
}
|
| 116 |
-
}
|
| 117 |
-
tools.append(tool)
|
| 118 |
-
|
| 119 |
-
# Add weather tools (which are already in the correct format)
|
| 120 |
-
tools.extend(WEATHER_TOOLS)
|
| 121 |
-
|
| 122 |
-
return tools
|
| 123 |
-
|
| 124 |
-
def call_function(self, function_name: str, arguments: Dict) -> Any:
|
| 125 |
-
"""Route function calls to appropriate handlers with error handling"""
|
| 126 |
-
try:
|
| 127 |
-
# Map all available function names to their handlers
|
| 128 |
-
function_map = {
|
| 129 |
-
# EasyFarms functions
|
| 130 |
-
"get_crop_recommendation": lambda args: execute_easyfarms_function("get_crop_recommendation", **args),
|
| 131 |
-
"get_fertilizer_recommendation": lambda args: execute_easyfarms_function("get_fertilizer_recommendation", **args),
|
| 132 |
-
"detect_plant_disease": lambda args: execute_easyfarms_function("detect_plant_disease", **args),
|
| 133 |
-
"get_supported_options": lambda args: execute_easyfarms_function("get_supported_options", **args),
|
| 134 |
-
"get_market_prices": lambda args: execute_easyfarms_function("get_market_prices", **args),
|
| 135 |
-
"compare_commodity_prices": lambda args: execute_easyfarms_function("compare_commodity_prices", **args),
|
| 136 |
-
"get_market_locations": lambda args: execute_easyfarms_function("get_market_locations", **args),
|
| 137 |
-
"get_commodity_list": lambda args: execute_easyfarms_function("get_commodity_list", **args),
|
| 138 |
-
|
| 139 |
-
# Weather alert functions
|
| 140 |
-
"get_weather_alerts": lambda args: self._execute_weather_function("get_weather_alerts", **args),
|
| 141 |
-
"get_weather": lambda args: self._execute_weather_function("get_weather", **args),
|
| 142 |
-
"get_alert_summary": lambda args: self._execute_weather_function("get_alert_summary", **args),
|
| 143 |
-
"get_available_locations": lambda args: self._execute_weather_function("get_available_locations", **args)
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
if function_name in function_map:
|
| 147 |
-
return function_map[function_name](arguments)
|
| 148 |
-
else:
|
| 149 |
-
return {"error": f"Unknown function: {function_name}"}
|
| 150 |
-
|
| 151 |
-
except Exception as e:
|
| 152 |
-
logger.error(f"Error executing function {function_name}: {e}")
|
| 153 |
-
return {"error": str(e)}
|
| 154 |
-
|
| 155 |
-
def _execute_weather_function(self, function_name: str, **kwargs):
|
| 156 |
-
"""Helper to execute weather functions from the alert.py module"""
|
| 157 |
-
from alert import execute_function
|
| 158 |
-
return execute_function(function_name, kwargs)
|
| 159 |
-
|
| 160 |
-
def process_query(self, user_message: str,
|
| 161 |
-
"""
|
| 162 |
-
Process user query
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
#
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
print("❌ Please fix configuration issues before running the assistant.")
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import openai
|
| 5 |
+
from typing import Dict, Any, Optional, List
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import logging
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Import your modules
|
| 13 |
+
from easy_agents import EASYFARMS_FUNCTION_SCHEMAS, execute_easyfarms_function
|
| 14 |
+
from alert import WEATHER_TOOLS , execute_function
|
| 15 |
+
from conversation_manager import ConversationManager
|
| 16 |
+
|
| 17 |
+
# Configure logging
|
| 18 |
+
logging.basicConfig(level=logging.INFO)
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
# Load environment variables
|
| 22 |
+
load_dotenv()
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class Config:
|
| 26 |
+
"""Configuration settings"""
|
| 27 |
+
api_key: str
|
| 28 |
+
api_url: str
|
| 29 |
+
model_name: str
|
| 30 |
+
max_retries: int = 3
|
| 31 |
+
temperature: float = 0.5
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_env(cls):
|
| 35 |
+
"""Load configuration from environment variables"""
|
| 36 |
+
return cls(
|
| 37 |
+
api_key=os.getenv("API_KEY"),
|
| 38 |
+
api_url=os.getenv("API_URL"),
|
| 39 |
+
model_name=os.getenv("MODEL_NAME")
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
class EasyFarmsAssistant:
|
| 43 |
+
"""Enhanced EasyFarms AI Assistant with weather integration and persistent sessions"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, config: Optional[Config] = None, manager: Optional[ConversationManager] = None):
|
| 46 |
+
"""
|
| 47 |
+
Initialize the assistant with configuration and a conversation manager.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
config (Optional[Config]): Configuration object. If None, loads from environment.
|
| 51 |
+
manager (Optional[ConversationManager]): Manager for handling conversation persistence.
|
| 52 |
+
"""
|
| 53 |
+
self.config = config or Config.from_env()
|
| 54 |
+
|
| 55 |
+
# Validate configuration
|
| 56 |
+
if not all([self.config.api_key, self.config.api_url, self.config.model_name]):
|
| 57 |
+
raise ValueError("Missing required configuration: API_KEY, API_URL, and MODEL_NAME must be set")
|
| 58 |
+
|
| 59 |
+
self.client = OpenAI(
|
| 60 |
+
api_key=self.config.api_key,
|
| 61 |
+
base_url=self.config.api_url
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# All available functions from both modules are combined into the tools list
|
| 65 |
+
self.tools = self._initialize_tools()
|
| 66 |
+
|
| 67 |
+
# Use the provided conversation manager or create a new one
|
| 68 |
+
self.manager = manager or ConversationManager()
|
| 69 |
+
|
| 70 |
+
# System prompts
|
| 71 |
+
self.system_prompt = """You are the AI assistant for EasyForms Agritech Solutions. Your task is to provide users with clear, concise, and actionable responses regarding agriculture, crop management, production, treatment, weather alerts, and related queries.
|
| 72 |
+
|
| 73 |
+
Core Capabilities:
|
| 74 |
+
- Crop recommendations based on soil and weather conditions
|
| 75 |
+
- Fertilizer recommendations for specific crops
|
| 76 |
+
- Plant disease detection and treatment advice
|
| 77 |
+
- Weather alerts and forecasts for farming decisions
|
| 78 |
+
- Market data and commodity prices
|
| 79 |
+
- General agricultural guidance
|
| 80 |
+
|
| 81 |
+
Rules:
|
| 82 |
+
1. Check if any relevant function_tools or datasets are available for this query.
|
| 83 |
+
2. If available, use the functions to fetch information and generate the final user-facing response.
|
| 84 |
+
3. If the functions or data are unavailable, do **not stop**; instead, generate a general, well-reasoned response based on your own knowledge.
|
| 85 |
+
4. Keep the response **simple, smooth, well-pointed, and concise**.
|
| 86 |
+
5. Structure the response with bullet points or numbered steps where helpful.
|
| 87 |
+
6. Provide practical, actionable advice a user can implement immediately.
|
| 88 |
+
7. Use English or Hindi based on user preference.
|
| 89 |
+
8. If any information is uncertain, mention it clearly and suggest alternatives.
|
| 90 |
+
9. For weather-related queries, prioritize safety and timely alerts."""
|
| 91 |
+
|
| 92 |
+
self.final_system = """You are the final response assistant for EasyForms Agritech Solutions. Use the outputs from previous function calls to generate a **clear, concise, actionable response** for the user.
|
| 93 |
+
|
| 94 |
+
Rules:
|
| 95 |
+
1. Combine the function outputs and your own reasoning to answer the query.
|
| 96 |
+
2. Keep responses simple, smooth, well-pointed, and concise.
|
| 97 |
+
3. Structure response with headings or bullet points if helpful.
|
| 98 |
+
4. Provide practical advice that a farmer or user can implement immediately.
|
| 99 |
+
5. If some data is missing, clearly state it and offer alternatives.
|
| 100 |
+
6. Use English or Hindi based on the user preference.
|
| 101 |
+
7. For weather alerts, emphasize urgency and protective measures."""
|
| 102 |
+
|
| 103 |
+
def _initialize_tools(self) -> List[Dict]:
|
| 104 |
+
"""Initialize and convert all function schemas to the new tools format"""
|
| 105 |
+
tools = []
|
| 106 |
+
|
| 107 |
+
# Convert EasyFarms schemas to the new format
|
| 108 |
+
for schema in EASYFARMS_FUNCTION_SCHEMAS:
|
| 109 |
+
tool = {
|
| 110 |
+
"type": "function",
|
| 111 |
+
"function": {
|
| 112 |
+
"name": schema["name"],
|
| 113 |
+
"description": schema["description"],
|
| 114 |
+
"parameters": schema["parameters"]
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
tools.append(tool)
|
| 118 |
+
|
| 119 |
+
# Add weather tools (which are already in the correct format)
|
| 120 |
+
tools.extend(WEATHER_TOOLS)
|
| 121 |
+
|
| 122 |
+
return tools
|
| 123 |
+
|
| 124 |
+
def call_function(self, function_name: str, arguments: Dict) -> Any:
|
| 125 |
+
"""Route function calls to appropriate handlers with error handling"""
|
| 126 |
+
try:
|
| 127 |
+
# Map all available function names to their handlers
|
| 128 |
+
function_map = {
|
| 129 |
+
# EasyFarms functions
|
| 130 |
+
"get_crop_recommendation": lambda args: execute_easyfarms_function("get_crop_recommendation", **args),
|
| 131 |
+
"get_fertilizer_recommendation": lambda args: execute_easyfarms_function("get_fertilizer_recommendation", **args),
|
| 132 |
+
"detect_plant_disease": lambda args: execute_easyfarms_function("detect_plant_disease", **args),
|
| 133 |
+
"get_supported_options": lambda args: execute_easyfarms_function("get_supported_options", **args),
|
| 134 |
+
"get_market_prices": lambda args: execute_easyfarms_function("get_market_prices", **args),
|
| 135 |
+
"compare_commodity_prices": lambda args: execute_easyfarms_function("compare_commodity_prices", **args),
|
| 136 |
+
"get_market_locations": lambda args: execute_easyfarms_function("get_market_locations", **args),
|
| 137 |
+
"get_commodity_list": lambda args: execute_easyfarms_function("get_commodity_list", **args),
|
| 138 |
+
|
| 139 |
+
# Weather alert functions
|
| 140 |
+
"get_weather_alerts": lambda args: self._execute_weather_function("get_weather_alerts", **args),
|
| 141 |
+
"get_weather": lambda args: self._execute_weather_function("get_weather", **args),
|
| 142 |
+
"get_alert_summary": lambda args: self._execute_weather_function("get_alert_summary", **args),
|
| 143 |
+
"get_available_locations": lambda args: self._execute_weather_function("get_available_locations", **args)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
if function_name in function_map:
|
| 147 |
+
return function_map[function_name](arguments)
|
| 148 |
+
else:
|
| 149 |
+
return {"error": f"Unknown function: {function_name}"}
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logger.error(f"Error executing function {function_name}: {e}")
|
| 153 |
+
return {"error": str(e)}
|
| 154 |
+
|
| 155 |
+
def _execute_weather_function(self, function_name: str, **kwargs):
|
| 156 |
+
"""Helper to execute weather functions from the alert.py module"""
|
| 157 |
+
from alert import execute_function
|
| 158 |
+
return execute_function(function_name, kwargs)
|
| 159 |
+
|
| 160 |
+
def process_query(self, user_message: str, chat_id: Optional[str] = None, image_url: Optional[str] = None) -> Dict[str, Any]:
|
| 161 |
+
"""
|
| 162 |
+
Process user query with improved conversation management
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
user_message: The user's message
|
| 166 |
+
chat_id: Optional chat ID. If None, generates a new one
|
| 167 |
+
image_url: Optional image URL
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
Dictionary containing response, chat_id, and message IDs
|
| 171 |
+
"""
|
| 172 |
+
try:
|
| 173 |
+
# Handle chat ID
|
| 174 |
+
if not chat_id:
|
| 175 |
+
chat_id = self.manager.generate_chat_id()
|
| 176 |
+
is_new_chat = True
|
| 177 |
+
logger.info(f"Generated new chat ID: {chat_id}")
|
| 178 |
+
else:
|
| 179 |
+
is_new_chat = not self.manager.chat_exists(chat_id)
|
| 180 |
+
if is_new_chat:
|
| 181 |
+
logger.info(f"Creating new chat with provided ID: {chat_id}")
|
| 182 |
+
else:
|
| 183 |
+
logger.info(f"Continuing existing chat: {chat_id}")
|
| 184 |
+
|
| 185 |
+
# Get conversation history
|
| 186 |
+
conversation_history = self.manager.get_history(chat_id)
|
| 187 |
+
|
| 188 |
+
# Prepare messages for AI
|
| 189 |
+
messages = [{"role": "system", "content": self.system_prompt}]
|
| 190 |
+
|
| 191 |
+
# Add conversation history
|
| 192 |
+
for message in conversation_history:
|
| 193 |
+
if message.get("role") == "user":
|
| 194 |
+
llm_user_content = message.get("content", "")
|
| 195 |
+
if message.get("imageUrl"):
|
| 196 |
+
llm_user_content += f" [image_url: {message.get('imageUrl')}]"
|
| 197 |
+
messages.append({"role": "user", "content": llm_user_content})
|
| 198 |
+
elif message.get("role") == "assistant":
|
| 199 |
+
messages.append({"role": "assistant", "content": message.get("content", "")})
|
| 200 |
+
|
| 201 |
+
# Add current user message
|
| 202 |
+
llm_message_content = user_message
|
| 203 |
+
if image_url:
|
| 204 |
+
llm_message_content += f" [image_url: {image_url}]"
|
| 205 |
+
messages.append({"role": "user", "content": llm_message_content})
|
| 206 |
+
|
| 207 |
+
# Make API call
|
| 208 |
+
response = self.client.chat.completions.create(
|
| 209 |
+
model=self.config.model_name,
|
| 210 |
+
messages=messages,
|
| 211 |
+
tools=self.tools,
|
| 212 |
+
tool_choice="auto",
|
| 213 |
+
temperature=self.config.temperature
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
message = response.choices[0].message
|
| 217 |
+
|
| 218 |
+
if hasattr(message, 'tool_calls') and message.tool_calls:
|
| 219 |
+
# Add the assistant's message with tool calls
|
| 220 |
+
messages.append({
|
| 221 |
+
"role": "assistant",
|
| 222 |
+
"tool_calls": [
|
| 223 |
+
{
|
| 224 |
+
"id": tool_call.id,
|
| 225 |
+
"type": "function",
|
| 226 |
+
"function": {
|
| 227 |
+
"name": tool_call.function.name,
|
| 228 |
+
"arguments": tool_call.function.arguments
|
| 229 |
+
}
|
| 230 |
+
} for tool_call in message.tool_calls
|
| 231 |
+
]
|
| 232 |
+
})
|
| 233 |
+
|
| 234 |
+
# Execute all tool calls
|
| 235 |
+
for tool_call in message.tool_calls:
|
| 236 |
+
function_name = tool_call.function.name
|
| 237 |
+
function_args = json.loads(tool_call.function.arguments)
|
| 238 |
+
|
| 239 |
+
logger.info(f"Calling function: {function_name} with args: {function_args}")
|
| 240 |
+
|
| 241 |
+
# Call the function
|
| 242 |
+
function_result = self.call_function(function_name, function_args)
|
| 243 |
+
|
| 244 |
+
# Add function result to messages
|
| 245 |
+
messages.append({
|
| 246 |
+
"role": "tool",
|
| 247 |
+
"tool_call_id": tool_call.id,
|
| 248 |
+
"content": json.dumps(function_result)
|
| 249 |
+
})
|
| 250 |
+
|
| 251 |
+
# Add final system prompt for generating response
|
| 252 |
+
messages.append({
|
| 253 |
+
"role": "system",
|
| 254 |
+
"content": self.final_system
|
| 255 |
+
})
|
| 256 |
+
|
| 257 |
+
# Get final response
|
| 258 |
+
final_response = self.client.chat.completions.create(
|
| 259 |
+
model=self.config.model_name,
|
| 260 |
+
messages=messages,
|
| 261 |
+
temperature=self.config.temperature
|
| 262 |
+
)
|
| 263 |
+
response_content = final_response.choices[0].message.content
|
| 264 |
+
else:
|
| 265 |
+
response_content = message.content
|
| 266 |
+
|
| 267 |
+
# Add messages to conversation history with unique IDs
|
| 268 |
+
user_msg = self.manager.add_message(chat_id, "user", user_message, image_url)
|
| 269 |
+
assistant_msg = self.manager.add_message(chat_id, "assistant", response_content)
|
| 270 |
+
|
| 271 |
+
return {
|
| 272 |
+
"response": response_content,
|
| 273 |
+
"chat_id": chat_id,
|
| 274 |
+
"is_new_chat": is_new_chat,
|
| 275 |
+
"user_message_id": user_msg.get("message_id"),
|
| 276 |
+
"assistant_message_id": assistant_msg.get("message_id"),
|
| 277 |
+
"total_messages": len(self.manager.get_history(chat_id))
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
except Exception as e:
|
| 281 |
+
logger.error(f"Error processing query for chat {chat_id}: {e}")
|
| 282 |
+
return {
|
| 283 |
+
"error": f"I apologize, but I encountered an error: {str(e)}. Please try again or rephrase your question.",
|
| 284 |
+
"chat_id": chat_id or self.manager.generate_chat_id(),
|
| 285 |
+
"is_new_chat": True,
|
| 286 |
+
"user_message_id": None,
|
| 287 |
+
"assistant_message_id": None,
|
| 288 |
+
"total_messages": 0
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
| 292 |
+
"""
|
| 293 |
+
Get information about a specific chat
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
chat_id: The chat ID to get information for
|
| 297 |
+
|
| 298 |
+
Returns:
|
| 299 |
+
Dictionary with chat information
|
| 300 |
+
"""
|
| 301 |
+
return self.manager.get_chat_info(chat_id)
|
| 302 |
+
|
| 303 |
+
def get_all_chats(self) -> List[Dict[str, Any]]:
|
| 304 |
+
"""
|
| 305 |
+
Get all chat sessions
|
| 306 |
+
|
| 307 |
+
Returns:
|
| 308 |
+
List of chat session information
|
| 309 |
+
"""
|
| 310 |
+
return self.manager.get_all_chat_sessions()
|
| 311 |
+
|
| 312 |
+
def clear_history(self, chat_id: str) -> bool:
|
| 313 |
+
"""
|
| 314 |
+
Clear conversation history for a specific chat
|
| 315 |
+
|
| 316 |
+
Args:
|
| 317 |
+
chat_id: The ID of the chat to clear
|
| 318 |
+
|
| 319 |
+
Returns:
|
| 320 |
+
True if deletion was successful, False otherwise
|
| 321 |
+
"""
|
| 322 |
+
logger.info(f"Clearing history for chat: {chat_id}")
|
| 323 |
+
return self.manager.delete_history(chat_id)
|
| 324 |
+
|
| 325 |
+
def get_messages(self, chat_id: str) -> List[Dict[str, Any]]:
|
| 326 |
+
"""
|
| 327 |
+
Get all messages for a specific chat
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
chat_id: The chat ID to get messages for
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
List of messages with their IDs
|
| 334 |
+
"""
|
| 335 |
+
return self.manager.get_history(chat_id)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# Utility class for generating example queries (can be used for testing)
|
| 339 |
+
class QuickQueries:
|
| 340 |
+
"""Pre-defined query templates for common farming questions"""
|
| 341 |
+
|
| 342 |
+
@staticmethod
|
| 343 |
+
def crop_recommendation(N: int, P: int, K: int, temp: float, humidity: float, ph: float = 6.5) -> str:
|
| 344 |
+
"""Generate crop recommendation query"""
|
| 345 |
+
return f"What crop should I grow with N={N}, P={P}, K={K}, temperature {temp}°C, humidity {humidity}%, pH {ph}?"
|
| 346 |
+
|
| 347 |
+
@staticmethod
|
| 348 |
+
def fertilizer_query(crop: str, soil: str, N: int, P: int, K: int) -> str:
|
| 349 |
+
"""Generate fertilizer recommendation query"""
|
| 350 |
+
return f"I need fertilizer recommendation for {crop} in {soil} soil with N={N}, P={P}, K={K}"
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def weather_alert(location: str = "") -> str:
|
| 354 |
+
"""Generate weather alert query"""
|
| 355 |
+
location_str = f" for {location}" if location else ""
|
| 356 |
+
return f"What are the current weather alerts and conditions{location_str}? How will this affect farming?"
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# Test function to validate configuration
|
| 360 |
+
def test_configuration():
|
| 361 |
+
"""Test if all configuration is properly set up"""
|
| 362 |
+
try:
|
| 363 |
+
# Check environment variables
|
| 364 |
+
required_env_vars = ["API_KEY", "API_URL", "MODEL_NAME"]
|
| 365 |
+
missing_vars = [var for var in required_env_vars if not os.getenv(var)]
|
| 366 |
+
|
| 367 |
+
if missing_vars:
|
| 368 |
+
print(f"Missing environment variables: {missing_vars}")
|
| 369 |
+
return False
|
| 370 |
+
|
| 371 |
+
# Test assistant initialization
|
| 372 |
+
assistant = EasyFarmsAssistant()
|
| 373 |
+
print("Assistant initialized successfully")
|
| 374 |
+
|
| 375 |
+
# Test function schemas
|
| 376 |
+
print(f"Loaded {len(assistant.tools)} function tools")
|
| 377 |
+
|
| 378 |
+
return True
|
| 379 |
+
except Exception as e:
|
| 380 |
+
print(f"Configuration test failed: {e}")
|
| 381 |
+
return False
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# Test the new conversation management
|
| 385 |
+
def test_conversation_management():
|
| 386 |
+
"""Test the enhanced conversation management"""
|
| 387 |
+
try:
|
| 388 |
+
assistant = EasyFarmsAssistant()
|
| 389 |
+
|
| 390 |
+
# Test 1: New conversation
|
| 391 |
+
print("\n=== Test 1: New Conversation ===")
|
| 392 |
+
result1 = assistant.process_query("Hello, I need help with farming")
|
| 393 |
+
print(f"Chat ID: {result1['chat_id']}")
|
| 394 |
+
print(f"Is new chat: {result1['is_new_chat']}")
|
| 395 |
+
print(f"User message ID: {result1['user_message_id']}")
|
| 396 |
+
print(f"Assistant message ID: {result1['assistant_message_id']}")
|
| 397 |
+
print(f"Total messages: {result1['total_messages']}")
|
| 398 |
+
|
| 399 |
+
# Test 2: Continue conversation
|
| 400 |
+
print("\n=== Test 2: Continue Conversation ===")
|
| 401 |
+
chat_id = result1['chat_id']
|
| 402 |
+
result2 = assistant.process_query("What crops grow well in sandy soil?", chat_id=chat_id)
|
| 403 |
+
print(f"Chat ID: {result2['chat_id']}")
|
| 404 |
+
print(f"Is new chat: {result2['is_new_chat']}")
|
| 405 |
+
print(f"User message ID: {result2['user_message_id']}")
|
| 406 |
+
print(f"Assistant message ID: {result2['assistant_message_id']}")
|
| 407 |
+
print(f"Total messages: {result2['total_messages']}")
|
| 408 |
+
|
| 409 |
+
# Test 3: Get messages
|
| 410 |
+
print(f"\n=== Test 3: Messages in chat {chat_id} ===")
|
| 411 |
+
messages = assistant.get_messages(chat_id)
|
| 412 |
+
for msg in messages:
|
| 413 |
+
print(f" Message {msg.get('message_id')}: {msg.get('role')} - {msg.get('content')[:50]}...")
|
| 414 |
+
|
| 415 |
+
# Test 4: User-defined chat ID
|
| 416 |
+
print("\n=== Test 4: User-defined Chat ID ===")
|
| 417 |
+
custom_chat_id = "my_farming_chat_2024"
|
| 418 |
+
result3 = assistant.process_query("Tell me about wheat farming", chat_id=custom_chat_id)
|
| 419 |
+
print(f"Custom chat ID: {result3['chat_id']}")
|
| 420 |
+
print(f"Is new chat: {result3['is_new_chat']}")
|
| 421 |
+
|
| 422 |
+
# Test 5: Get all chats
|
| 423 |
+
print("\n=== Test 5: All Chats ===")
|
| 424 |
+
all_chats = assistant.get_all_chats()
|
| 425 |
+
for chat in all_chats[:3]: # Show first 3
|
| 426 |
+
print(f" {chat.get('session_id')}: {chat.get('title')} ({chat.get('message_count')} messages)")
|
| 427 |
+
|
| 428 |
+
print("\n✅ Conversation management tests completed!")
|
| 429 |
+
return True
|
| 430 |
+
|
| 431 |
+
except Exception as e:
|
| 432 |
+
print(f"❌ Conversation management test failed: {e}")
|
| 433 |
+
return False
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
if __name__ == "__main__":
|
| 437 |
+
print("=== EasyFarms Assistant Configuration Test ===")
|
| 438 |
+
if test_configuration():
|
| 439 |
+
print("✅ Basic configuration ready!")
|
| 440 |
+
|
| 441 |
+
print("\n=== Testing Enhanced Conversation Management ===")
|
| 442 |
+
if test_conversation_management():
|
| 443 |
+
print("✅ All systems ready!")
|
| 444 |
+
else:
|
| 445 |
+
print("⚠️ Basic functions work, but conversation management needs attention")
|
| 446 |
+
else:
|
| 447 |
print("❌ Please fix configuration issues before running the assistant.")
|