File size: 3,022 Bytes
b971141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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()