Spaces:
Sleeping
Sleeping
Update app.py
Browse files123424 unmodified lines2930313233345 unmodified lines4041424344454620 unmodified lines676869707172734 unmodified lines7879808182838485868788899091929394959697989910010110210310452 unmodified lines15715815916016116216316416513 unmodified lines17918018118218318418530 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652666 unmodified lines2732742752762772782792805 unmodified lines2862872882892902912924 unmodified lines29729829930030130230351 unmodified lines35535635735835936036110 unmodified lines37237337437537637721 unmodified lines3994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524532 unmodified lines456457458459460461462463464465# app.pyimport jsonimport openai24 unmodified linesmodel_name: strmax_retries: int = 3temperature: float = 0.5@classmethoddef from_env(cls):5 unmodified lines)class EasyFarmsAssistant:"""Enhanced EasyFarms AI Assistant with weather integration and persistent sessions"""def __init__(self, config: Optional[Config] = None, manager: Optional[ConversationManager] = None):"""20 unmodified lines# Use the provided conversation manager or create a new oneself.manager = manager or ConversationManager()# System promptsself.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.Core Capabilities:4 unmodified lines- Market data and commodity prices- General agricultural guidanceRules:1. Check if any relevant function_tools or datasets are available for this query.2. If available, use the functions to fetch information and generate the final user-facing response.3. If the functions or data are unavailable, do **not stop**; instead, generate a general, well-reasoned response based on your own knowledge.4. Keep the response **simple, smooth, well-pointed, and concise**.5. Structure the response with bullet points or numbered steps where helpful.6. Provide practical, actionable advice a user can implement immediately.7. Use English or Hindi based on user preference.8. If any information is uncertain, mention it clearly and suggest alternatives.9. For weather-related queries, prioritize safety and timely alerts."""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.Rules:1. Combine the function outputs and your own reasoning to answer the query.2. Keep responses simple, smooth, well-pointed, and concise.3. Structure response with headings or bullet points if helpful.4. Provide practical advice that a farmer or user can implement immediately.5. If some data is missing, clearly state it and offer alternatives.6. Use English or Hindi based on the user preference.7. For weather alerts, emphasize urgency and protective measures."""def _initialize_tools(self) -> List[Dict]:"""Initialize and convert all function schemas to the new tools format"""52 unmodified linesfrom alert import execute_functionreturn execute_function(function_name, kwargs)def process_query(self, user_message: str, user_id: str, chat_id: Optional[str] = None, image_url: Optional[str] = None) -> Dict[str, Any]:"""Process user query with user authentication and improved conversation managementArgs:user_message: The user's message13 unmodified lines"is_new_chat": True,"user_message_id": None,"assistant_message_id": None,"total_messages": 0}# Handle chat ID30 unmodified linesllm_message_content += f" [image_url: {image_url}]"messages.append({"role": "user", "content": llm_message_content})# Make API callresponse = self.client.chat.completions.create(model=self.config.model_name,messages=messages,tools=self.tools,tool_choice="auto",temperature=self.config.temperature)message = response.choices[0].messageif hasattr(message, 'tool_calls') and message.tool_calls:# Add the assistant's message with tool callsmessages.append({"role": "assistant","tool_calls": [{"id": tool_call.id,"type": "function","function": {"name": tool_call.function.name,"arguments": tool_call.function.arguments}} for tool_call in message.tool_calls]})# Execute all tool callsfor tool_call in message.tool_calls:function_name = tool_call.function.namefunction_args = json.loads(tool_call.function.arguments)logger.info(f"Calling function: {function_name} with args: {function_args}")# Call the functionfunction_result = self.call_function(function_name, function_args)# Add function result to messagesmessages.append({"role": "tool","tool_call_id": tool_call.id,"content": json.dumps(function_result)})# Add final system prompt for generating responsemessages.append({"role": "system","content": self.final_system6 unmodified linestemperature=self.config.temperature)response_content = final_response.choices[0].message.contentelse:response_content = message.content# Add messages to conversation history with unique IDsuser_msg = self.manager.add_message(chat_id, user_id, "user", user_message, image_url)5 unmodified lines"is_new_chat": is_new_chat,"user_message_id": user_msg.get("message_id"),"assistant_message_id": assistant_msg.get("message_id"),"total_messages": len(self.manager.get_history(chat_id, user_id))}except Exception as e:4 unmodified lines"is_new_chat": True,"user_message_id": None,"assistant_message_id": None,"total_messages": 0}def get_chat_info(self, chat_id: str, user_id: str) -> Dict[str, Any]:51 unmodified lines# Utility class for generating example queries (can be used for testing)class QuickQueries:"""Pre-defined query templates for common farming questions"""@staticmethoddef crop_recommendation(N: int, P: int, K: int, temp: float, humidity: float, ph: float = 6.5) -> str:10 unmodified lines"""Generate weather alert query"""location_str = f" for {location}" if location else ""return f"What are the current weather alerts and conditions{location_str}? How will this affect farming?"# Test function to validate configuration21 unmodified linesreturn False# Test the new conversation managementdef test_conversation_management():"""Test the enhanced conversation management"""try:assistant = EasyFarmsAssistant()# Test 1: New conversationprint("\n=== Test 1: New Conversation ===")result1 = assistant.process_query("Hello, I need help with farming", "test_user_123")print(f"Chat ID: {result1['chat_id']}")print(f"Is new chat: {result1['is_new_chat']}")print(f"User message ID: {result1['user_message_id']}")print(f"Assistant message ID: {result1['assistant_message_id']}")print(f"Total messages: {result1['total_messages']}")# Test 2: Continue conversationprint("\n=== Test 2: Continue Conversation ===")chat_id = result1['chat_id']result2 = assistant.process_query("What crops grow well in sandy soil?", "test_user_123", chat_id=chat_id)print(f"Chat ID: {result2['chat_id']}")print(f"Is new chat: {result2['is_new_chat']}")print(f"User message ID: {result2['user_message_id']}")print(f"Assistant message ID: {result2['assistant_message_id']}")print(f"Total messages: {result2['total_messages']}")# Test 3: Get messagesprint(f"\n=== Test 3: Messages in chat {chat_id} ===")messages = assistant.get_messages(chat_id, "test_user_123")for msg in messages:print(f" Message {msg.get('message_id')}: {msg.get('role')} - {msg.get('content')[:50]}...")# Test 4: User-defined chat IDprint("\n=== Test 4: User-defined Chat ID ===")custom_chat_id = "my_farming_chat_2024"result3 = assistant.process_query("Tell me about wheat farming", "test_user_123", chat_id=custom_chat_id)print(f"Custom chat ID: {result3['chat_id']}")print(f"Is new chat: {result3['is_new_chat']}")# Test 5: Get all chatsprint("\n=== Test 5: All Chats ===")all_chats = assistant.get_all_chats("test_user_123")for chat in all_chats[:3]: # Show first 3print(f" {chat.get('session_id')}: {chat.get('title')} ({chat.get('message_count')} messages)")print("\n✅ Conversation management tests completed!")return Trueexcept Exception as e:print(f"❌ Conversation management test failed: {e}")return False2 unmodified linesif test_configuration():print("✅ Basic configuration ready!")print("\n=== Testing Enhanced Conversation Management ===")if test_conversation_management():print("✅ All systems ready!")else:print("⚠️ Basic functions work, but conversation management needs attention")else:print("❌ Please fix configuration issues before running the assistant.")123424 unmodified lines293031323334355 unmodified lines4142434445464720 unmodified lines686970717273744 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113252 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024113 unmodified lines25525625725825926026126230 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333346 unmodified lines3413423433443453463473483493503513523533543553563573583593605 unmodified lines3663673683693703713723734 unmodified lines37837938038138238338438551 unmodified lines43743843944044144244310 unmodified lines45445545645745845946046146246346446546646746846947047147247347447547647747847948048148248321 unmodified lines5055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495502 unmodified lines553554555556557558559560561562# app.py - Enhanced with unlimited multi-function executionimport jsonimport openai24 unmodified linesmodel_name: strmax_retries: int = 3temperature: float = 0.5max_function_rounds: int = 5 # Maximum rounds of function calling to prevent infinite loops@classmethoddef from_env(cls):5 unmodified lines)class EasyFarmsAssistant:"""Enhanced EasyFarms AI Assistant with unlimited multi-function execution"""def __init__(self, config: Optional[Config] = None, manager: Optional[ConversationManager] = None):"""20 unmodified lines# Use the provided conversation manager or create a new oneself.manager = manager or ConversationManager()# Enhanced system prompt for multi-function executionself.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.Core Capabilities:4 unmodified lines- Market data and commodity prices- General agricultural guidanceIMPORTANT - Multi-Function Execution Guidelines:1. **You can and SHOULD use multiple functions in a single response** when it provides better value to the user.2. **You can call the same function multiple times** with different parameters to compare or analyze different scenarios.3. **Think comprehensively** - if a user asks about crops AND market prices, use both functions.4. **Make comparisons** - if asked to compare, call the function multiple times with different parameters.5. **Provide complete solutions** - gather all necessary data before responding.Example Multi-Function Scenarios:- "Compare wheat and rice prices" → Call get_market_prices twice (once for wheat, once for rice)- "What crop should I grow and what's its market price?" → Call get_crop_recommendation AND get_market_prices- "Check prices in Gujarat and Maharashtra" → Call get_market_prices multiple times for different states- "Recommend crops for sandy and loamy soil" → Call get_crop_recommendation multiple times- "Give fertilizer advice and check market prices for wheat" → Call both functionsResponse Rules:1. Use all available function_tools when they can help answer the query comprehensively.2. If comparing multiple items, execute the function for each item separately.3. If data is unavailable from functions, supplement with your own agricultural knowledge.4. Present results clearly - use tables, comparisons, or bullet points as appropriate.5. Keep responses concise but comprehensive.6. Provide practical, actionable advice.7. Use English or Hindi based on user preference.8. For weather-related queries, prioritize safety and timely alerts.Remember: Don't hesitate to use multiple functions - it's better to provide complete information than partial data."""self.final_system = """You are the final response assistant for EasyForms Agritech Solutions. You have received outputs from multiple function calls. Your job is to synthesize all this information into a **clear, comprehensive, and actionable response** for the user.Response Synthesis Guidelines:1. **Analyze all function outputs** - Look at every function result provided.2. **Create comparisons** - If multiple similar functions were called, create comparison tables or clear comparisons.3. **Highlight insights** - Point out interesting patterns, best options, or important differences.4. **Structure intelligently**:- Use tables for price comparisons- Use bullet points for multiple recommendations- Use numbered steps for sequential advice- Use paragraphs for explanations5. **Be comprehensive but concise** - Include all important information without being verbose.6. **Provide actionable recommendations** - End with clear next steps or advice.7. **Handle missing data gracefully** - If some functions returned errors, work with available data.8. **Use appropriate formatting** - Make the response easy to scan and understand.Example Response Structures:- For price comparisons: Create a comparison table showing commodity, location, and prices- For crop recommendations: List recommended crops with reasoning- For multi-aspect queries: Use sections with clear headingsRemember: The user asked one question but you have data from multiple sources - combine them intelligently."""def _initialize_tools(self) -> List[Dict]:"""Initialize and convert all function schemas to the new tools format"""52 unmodified linesfrom alert import execute_functionreturn execute_function(function_name, kwargs)def _execute_tool_calls_round(self, messages: List[Dict], tool_calls) -> tuple[List[Dict], int]:"""Execute a round of tool calls and return updated messages with function countArgs:messages: Current message historytool_calls: Tool calls to executeReturns:Tuple of (updated messages, number of functions executed)"""function_count = 0# Add the assistant's message with tool callsmessages.append({"role": "assistant","tool_calls": [{"id": tool_call.id,"type": "function","function": {"name": tool_call.function.name,"arguments": tool_call.function.arguments}} for tool_call in tool_calls]})# Execute all tool callsfor tool_call in tool_calls:function_name = tool_call.function.namefunction_args = json.loads(tool_call.function.arguments)logger.info(f"Calling function: {function_name} with args: {function_args}")# Call the functionfunction_result = self.call_function(function_name, function_args)function_count += 1# Add function result to messagesmessages.append({"role": "tool","tool_call_id": tool_call.id,"content": json.dumps(function_result)})return messages, function_countdef process_query(self, user_message: str, user_id: str, chat_id: Optional[str] = None, image_url: Optional[str] = None) -> Dict[str, Any]:"""Process user query with unlimited multi-function execution capabilityArgs:user_message: The user's message13 unmodified lines"is_new_chat": True,"user_message_id": None,"assistant_message_id": None,"total_messages": 0,"functions_executed": 0}# Handle chat ID30 unmodified linesllm_message_content += f" [image_url: {image_url}]"messages.append({"role": "user", "content": llm_message_content})# Track total functions executedtotal_functions_executed = 0# Iterative function calling - allow multiple roundsfor round_num in range(self.config.max_function_rounds):logger.info(f"Function calling round {round_num + 1}/{self.config.max_function_rounds}")# Make API callresponse = self.client.chat.completions.create(model=self.config.model_name,messages=messages,tools=self.tools,tool_choice="auto",temperature=self.config.temperature)message = response.choices[0].message# Check if there are tool callsif hasattr(message, 'tool_calls') and message.tool_calls:logger.info(f"Round {round_num + 1}: Executing {len(message.tool_calls)} function(s)")# Execute this round of tool callsmessages, functions_executed = self._execute_tool_calls_round(messages, message.tool_calls)total_functions_executed += functions_executed# Continue to next round to see if AI wants to call more functionscontinueelse:# No more tool calls, we have the final responseresponse_content = message.contentlogger.info(f"Function calling completed after {round_num + 1} round(s). Total functions executed: {total_functions_executed}")breakelse:# Max rounds reached, add final system prompt and get responselogger.warning(f"Max function rounds ({self.config.max_function_rounds}) reached")messages.append({"role": "system","content": self.final_system6 unmodified linestemperature=self.config.temperature)response_content = final_response.choices[0].message.content# If functions were executed, add final synthesis promptif total_functions_executed > 0 and not response_content:messages.append({"role": "system","content": self.final_system})final_response = self.client.chat.completions.create(model=self.config.model_name,messages=messages,temperature=self.config.temperature)response_content = final_response.choices[0].message.content# Add messages to conversation history with unique IDsuser_msg = self.manager.add_message(chat_id, user_id, "user", user_message, image_url)5 unmodified lines"is_new_chat": is_new_chat,"user_message_id": user_msg.get("message_id"),"assistant_message_id": assistant_msg.get("message_id"),"total_messages": len(self.manager.get_history(chat_id, user_id)),"functions_executed": total_functions_executed}except Exception as e:4 unmodified lines"is_new_chat": True,"user_message_id": None,"assistant_message_id": None,"total_messages": 0,"functions_executed": 0}def get_chat_info(self, chat_id: str, user_id: str) -> Dict[str, Any]:51 unmodified lines# Utility class for generating example queries (can be used for testing)class QuickQueries:"""Pre-defined query templates for common farming questions with multi-function examples"""@staticmethoddef crop_recommendation(N: int, P: int, K: int, temp: float, humidity: float, ph: float = 6.5) -> str:10 unmodified lines"""Generate weather alert query"""location_str = f" for {location}" if location else ""return f"What are the current weather alerts and conditions{location_str}? How will this affect farming?"@staticmethoddef multi_function_queries() -> List[str]:"""Generate example multi-function queries"""return [# Multiple function calls - same function multiple times"Compare wheat and rice market prices in Gujarat","What are the market prices for tomato in Gujarat, Maharashtra, and Punjab?","Recommend crops for sandy soil and loamy soil, which one is better?",# Multiple function calls - different functions"What crop should I grow with N=90, P=42, K=43, temperature 25°C, humidity 80% and what's the market price for that crop?","Give me crop recommendations and current weather alerts for my region","I want to grow wheat, tell me fertilizer recommendations and current market prices",# Complex multi-function queries"Compare tomato and potato prices across different states and tell me which crop has better market potential","What are the best crops for my soil (N=80, P=40, K=50, temp=22°C, humidity=75%) and their current market prices?","Give me weather alerts, crop recommendations for my conditions, and market prices for the recommended crops",# Sequential same function calls"Get market prices for wheat, rice, maize, and sugarcane in Gujarat","Compare fertilizer requirements for wheat in black soil, red soil, and sandy soil",]# Test function to validate configuration21 unmodified linesreturn False# Test the multi-function executiondef test_multi_function_execution():"""Test the enhanced multi-function execution"""try:assistant = EasyFarmsAssistant()print("\n=== Testing Multi-Function Execution ===\n")# Test 1: Single function callprint("Test 1: Single Function Call")result1 = assistant.process_query("What crop should I grow with N=90, P=42, K=43, temperature 25°C, humidity 80%?","test_user_multi")print(f"Functions executed: {result1.get('functions_executed', 0)}")print(f"Response preview: {result1['response'][:200]}...\n")# Test 2: Multiple different functionsprint("Test 2: Multiple Different Functions")result2 = assistant.process_query("What crop should I grow with N=90, P=42, K=43, temperature 25°C, humidity 80% and what's the current market price for wheat?","test_user_multi")print(f"Functions executed: {result2.get('functions_executed', 0)}")print(f"Response preview: {result2['response'][:200]}...\n")# Test 3: Same function multiple timesprint("Test 3: Same Function Multiple Times")result3 = assistant.process_query("Compare wheat and rice market prices in Gujarat","test_user_multi")print(f"Functions executed: {result3.get('functions_executed', 0)}")print(f"Response preview: {result3['response'][:200]}...\n")print("✅ Multi-function execution tests completed!")return Trueexcept Exception as e:print(f"❌ Multi-function test failed: {e}")return False2 unmodified linesif test_configuration():print("✅ Basic configuration ready!")print("\n=== Testing Multi-Function Execution ===")if test_multi_function_execution():print("✅ All systems ready!")else:print("⚠️ Basic functions work, but multi-function execution needs attention")else:print("❌ Please fix configuration issues before running the assistant.")
app.py+208-111