import os import gradio as gr from datetime import datetime # Ensure Groq is installed and imported try: from groq import Groq except ImportError: os.system('pip install groq') from groq import Groq # Ensure Notion client is installed and imported try: from notion_client import Client except ImportError: os.system('pip install notion-client') from notion_client import Client # Retrieve API keys and database ID from environment variables groq_api_key = os.getenv("groq_key") notion_api_key = os.getenv("NOTION_API_KEY") notion_db_id = os.getenv("NOTION_DB_ID") if not groq_api_key: raise EnvironmentError("API key for Groq not found in environment variables.") if not notion_api_key: raise EnvironmentError("API key for Notion not found in environment variables.") if not notion_db_id: raise EnvironmentError("Database ID for Notion not found in environment variables.") groq_client = Groq(api_key=groq_api_key) notion_client = Client(auth=notion_api_key) # Function to log to Notion def log_to_notion(name, user_input, bot_response): try: notion_client.pages.create( parent={"database_id": notion_db_id}, properties={ "Name": {"title": [{"text": {"content": name}}]}, "Timestamp": {"date": {"start": datetime.now().isoformat() }}, "User Input": {"rich_text": [{"text": {"content": user_input}}]}, "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]}, } ) except Exception as e: print(f"Failed to log to Notion: {e}") # Function to interact with Groq async def chatbot_response(name, message, history): """Handles user input and retrieves a response from the Groq API.""" try: # Send message to Groq with role: system response = groq_client.chat( messages=[ {"role": "system", "content": "You are a helpful assistant."}, *[{"role": "user", "content": msg[0]} for msg in history], {"role": "user", "content": message} ] ) reply = response["choices"][0]["message"]["content"] history.append((message, reply)) # Log interaction to Notion log_to_notion(name, message, reply) return "", history except Exception as e: return f"Error: {str(e)}", history # Gradio interface def main(): chatbot = gr.Chatbot() name = gr.Textbox(label="Name", placeholder="Enter your name here...") msg = gr.Textbox(placeholder="Enter your message here...") clear = gr.Button("Clear Chat") def reset(): return "", [] with gr.Blocks() as demo: gr.Markdown("# Groq Chatbot with Gradio and Notion Logging") with gr.Row(): name.render() msg.render() msg.submit(chatbot_response, [name, msg, chatbot], [msg, chatbot]) clear.click(reset, None, chatbot) demo.launch() if __name__ == "__main__": main()