import os from groq import Groq import gradio as gr from dotenv import load_dotenv from gtts import gTTS import tempfile load_dotenv() API_KEY = os.getenv("GROQ_API_KEY") if not API_KEY: raise ValueError("Missing GROQ_API_KEY environment variable.") client = Groq(api_key=API_KEY) VALIDATION_PROMPT = "You are an intelligent assistant. Analyze the input question carefully. Respond with 'Yes' if the input is agriculture-related, and 'No' otherwise." RESPONSE_PROMPT = "You are an agriculture expert. Provide a concise and accurate answer to the following agriculture-related question:" def validate_input(input_text): try: validation_response = client.chat.completions.create( model="llama-3.1-8b-instant", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": VALIDATION_PROMPT}, {"role": "user", "content": input_text}, ], temperature=0, max_completion_tokens=1, ) return validation_response.choices[0].message.content.strip() except Exception as e: return f"Error: {e}" def get_agriculture_response(input_text): try: detailed_response = client.chat.completions.create( model="llama-3.1-8b-instant", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": RESPONSE_PROMPT}, {"role": "user", "content": input_text}, ], temperature=0.5, max_completion_tokens=700, ) return detailed_response.choices[0].message.content.strip() except Exception as e: return f"Error: {e}" def text_to_speech(text): if not text.strip(): return None try: tts = gTTS(text=text, lang='en') temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") tts.save(temp_file.name) return temp_file.name except Exception as e: print(f"TTS error: {e}") return None def groq_chatbot(input_text, chat_history): validation_result = validate_input(input_text) if validation_result.lower() == "yes": response = get_agriculture_response(input_text) elif validation_result.lower() == "no": response = "❌ This is not an agriculture-related question." else: response = f"⚠️ Unexpected response: {validation_result}" chat_history.append((input_text, response)) # Return chat history, clear input, reset audio output return chat_history, "", None def on_tts_click(chat_history): if chat_history and chat_history[-1][1]: last_response = chat_history[-1][1] audio_path = text_to_speech(last_response) return audio_path return None