Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,88 +1,130 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import anthropic
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# Initialize the Anthropic client with your API key
|
| 6 |
client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
|
| 7 |
MODEL = "claude-3-5-sonnet-20241022"
|
| 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 |
-
Extract Key Information (Logical Propositions):
|
| 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 |
-
def chat_with_claude(message, history):
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
response_content = ""
|
| 67 |
|
| 68 |
-
#
|
| 69 |
-
for user_msg, assistant_msg in history:
|
| 70 |
-
messages.append({
|
| 71 |
-
"role": "user",
|
| 72 |
-
"content": user_msg
|
| 73 |
-
})
|
| 74 |
-
messages.append({
|
| 75 |
-
"role": "assistant",
|
| 76 |
-
"content": assistant_msg
|
| 77 |
-
})
|
| 78 |
-
|
| 79 |
-
# Add the new user message
|
| 80 |
-
messages.append({
|
| 81 |
-
"role": "user",
|
| 82 |
-
"content": str(message)
|
| 83 |
-
})
|
| 84 |
-
|
| 85 |
-
# Stream response from Claude with system prompt at top level
|
| 86 |
with client.messages.stream(
|
| 87 |
max_tokens=5000,
|
| 88 |
system=SYSTEM_PROMPT,
|
|
@@ -92,56 +134,146 @@ def chat_with_claude(message, history):
|
|
| 92 |
for text in stream.text_stream:
|
| 93 |
response_content += text
|
| 94 |
yield response_content
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
.user-message {
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# Launch the interface
|
| 146 |
if __name__ == "__main__":
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import anthropic
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import uuid
|
| 6 |
+
from typing import List, Dict
|
| 7 |
+
import asyncio
|
| 8 |
+
import asyncpg
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
# Load environment variables
|
| 12 |
+
load_dotenv()
|
| 13 |
|
| 14 |
# Initialize the Anthropic client with your API key
|
| 15 |
client = anthropic.Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
|
| 16 |
MODEL = "claude-3-5-sonnet-20241022"
|
| 17 |
|
| 18 |
+
class DatabaseManager:
|
| 19 |
+
def __init__(self):
|
| 20 |
+
self.pool = None
|
| 21 |
+
|
| 22 |
+
async def initialize(self):
|
| 23 |
+
# Connect to Neon.tech PostgreSQL database
|
| 24 |
+
self.pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
|
| 25 |
+
|
| 26 |
+
# Create necessary tables if they don't exist
|
| 27 |
+
async with self.pool.acquire() as conn:
|
| 28 |
+
await conn.execute('''
|
| 29 |
+
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 30 |
+
session_id UUID PRIMARY KEY,
|
| 31 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
| 32 |
+
)
|
| 33 |
+
''')
|
| 34 |
+
|
| 35 |
+
await conn.execute('''
|
| 36 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 37 |
+
message_id UUID PRIMARY KEY,
|
| 38 |
+
session_id UUID REFERENCES chat_sessions(session_id),
|
| 39 |
+
role TEXT NOT NULL,
|
| 40 |
+
content TEXT NOT NULL,
|
| 41 |
+
timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
| 42 |
+
)
|
| 43 |
+
''')
|
|
|
|
| 44 |
|
| 45 |
+
class ChatManager:
|
| 46 |
+
def __init__(self, db_manager: DatabaseManager):
|
| 47 |
+
self.db = db_manager
|
| 48 |
+
self.current_session_id = None
|
| 49 |
+
|
| 50 |
+
async def new_session(self) -> str:
|
| 51 |
+
"""Create a new chat session and return its ID"""
|
| 52 |
+
session_id = uuid.uuid4()
|
| 53 |
+
async with self.db.pool.acquire() as conn:
|
| 54 |
+
await conn.execute(
|
| 55 |
+
'INSERT INTO chat_sessions (session_id) VALUES ($1)',
|
| 56 |
+
session_id
|
| 57 |
+
)
|
| 58 |
+
self.current_session_id = session_id
|
| 59 |
+
return str(session_id)
|
| 60 |
+
|
| 61 |
+
async def add_message(self, session_id: str, role: str, content: str):
|
| 62 |
+
"""Add a message to a chat session"""
|
| 63 |
+
async with self.db.pool.acquire() as conn:
|
| 64 |
+
await conn.execute(
|
| 65 |
+
'INSERT INTO messages (message_id, session_id, role, content) VALUES ($1, $2, $3, $4)',
|
| 66 |
+
uuid.uuid4(), uuid.UUID(session_id), role, content
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
async def get_session_history(self, session_id: str) -> List[Dict]:
|
| 70 |
+
"""Get all messages for a chat session"""
|
| 71 |
+
async with self.db.pool.acquire() as conn:
|
| 72 |
+
rows = await conn.fetch('''
|
| 73 |
+
SELECT role, content, timestamp
|
| 74 |
+
FROM messages
|
| 75 |
+
WHERE session_id = $1
|
| 76 |
+
ORDER BY timestamp ASC
|
| 77 |
+
''', uuid.UUID(session_id))
|
| 78 |
+
return [dict(row) for row in rows]
|
| 79 |
+
|
| 80 |
+
async def list_sessions(self) -> List[Dict]:
|
| 81 |
+
"""Get all chat sessions with their message counts"""
|
| 82 |
+
async with self.db.pool.acquire() as conn:
|
| 83 |
+
sessions = await conn.fetch('''
|
| 84 |
+
SELECT
|
| 85 |
+
cs.session_id,
|
| 86 |
+
cs.created_at,
|
| 87 |
+
COUNT(m.message_id) as message_count
|
| 88 |
+
FROM chat_sessions cs
|
| 89 |
+
LEFT JOIN messages m ON cs.session_id = m.session_id
|
| 90 |
+
GROUP BY cs.session_id, cs.created_at
|
| 91 |
+
ORDER BY cs.created_at DESC
|
| 92 |
+
''')
|
| 93 |
+
return [dict(session) for session in sessions]
|
| 94 |
|
| 95 |
+
# Initialize database and chat managers
|
| 96 |
+
db_manager = DatabaseManager()
|
| 97 |
+
chat_manager = None
|
| 98 |
|
| 99 |
+
async def initialize_managers():
|
| 100 |
+
global chat_manager
|
| 101 |
+
await db_manager.initialize()
|
| 102 |
+
chat_manager = ChatManager(db_manager)
|
| 103 |
|
| 104 |
+
def format_message(msg):
|
| 105 |
+
"""Format message for Claude API"""
|
| 106 |
+
return {
|
| 107 |
+
"role": msg["role"],
|
| 108 |
+
"content": msg["content"]
|
| 109 |
+
}
|
| 110 |
|
| 111 |
+
async def chat_with_claude(message, history, session_id: str = None):
|
| 112 |
+
"""Main chat function with persistence"""
|
| 113 |
+
|
| 114 |
+
# Create new session if none exists
|
| 115 |
+
if not session_id:
|
| 116 |
+
session_id = await chat_manager.new_session()
|
| 117 |
+
|
| 118 |
+
# Add user message to database
|
| 119 |
+
await chat_manager.add_message(session_id, "user", message)
|
| 120 |
+
|
| 121 |
+
# Get session history and prepare messages for Claude
|
| 122 |
+
session_history = await chat_manager.get_session_history(session_id)
|
| 123 |
+
messages = [format_message(msg) for msg in session_history[:-1]] # Exclude latest user message
|
| 124 |
+
|
| 125 |
response_content = ""
|
| 126 |
|
| 127 |
+
# Stream response from Claude
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
with client.messages.stream(
|
| 129 |
max_tokens=5000,
|
| 130 |
system=SYSTEM_PROMPT,
|
|
|
|
| 134 |
for text in stream.text_stream:
|
| 135 |
response_content += text
|
| 136 |
yield response_content
|
| 137 |
+
|
| 138 |
+
# Add assistant response to database
|
| 139 |
+
await chat_manager.add_message(session_id, "assistant", response_content)
|
| 140 |
|
| 141 |
+
def create_chat_interface():
|
| 142 |
+
"""Create the Gradio interface with ChatGPT-like styling"""
|
| 143 |
+
|
| 144 |
+
css = """
|
| 145 |
+
.gradio-container {
|
| 146 |
+
max-width: 1200px !important;
|
| 147 |
+
margin: auto !important;
|
| 148 |
+
padding-top: 20px !important;
|
| 149 |
+
height: 100vh !important;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
.chat-history {
|
| 153 |
+
height: calc(100vh - 200px) !important;
|
| 154 |
+
overflow-y: auto !important;
|
| 155 |
+
padding: 20px !important;
|
| 156 |
+
border-radius: 10px !important;
|
| 157 |
+
background: #ffffff !important;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
.message {
|
| 161 |
+
padding: 15px !important;
|
| 162 |
+
margin: 10px 0 !important;
|
| 163 |
+
border-radius: 8px !important;
|
| 164 |
+
max-width: 85% !important;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
.user-message {
|
| 168 |
+
background: #f7f7f8 !important;
|
| 169 |
+
margin-left: auto !important;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
.assistant-message {
|
| 173 |
+
background: #ffffff !important;
|
| 174 |
+
border: 1px solid #e5e5e5 !important;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
.input-area {
|
| 178 |
+
position: fixed !important;
|
| 179 |
+
bottom: 20px !important;
|
| 180 |
+
width: calc(100% - 40px) !important;
|
| 181 |
+
max-width: 1160px !important;
|
| 182 |
+
background: white !important;
|
| 183 |
+
padding: 15px !important;
|
| 184 |
+
border-radius: 10px !important;
|
| 185 |
+
box-shadow: 0 0 10px rgba(0,0,0,0.1) !important;
|
| 186 |
+
}
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
with gr.Blocks(css=css) as demo:
|
| 190 |
+
session_id = gr.State(value=None)
|
| 191 |
+
|
| 192 |
+
with gr.Row():
|
| 193 |
+
with gr.Column(scale=3):
|
| 194 |
+
chatbot = gr.Chatbot(
|
| 195 |
+
elem_id="chatbot",
|
| 196 |
+
height=700,
|
| 197 |
+
show_label=False,
|
| 198 |
+
layout="bubble"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
with gr.Column(scale=1):
|
| 202 |
+
session_list = gr.Dropdown(
|
| 203 |
+
choices=lambda: [(str(s["session_id"]), f"Chat {i+1}")
|
| 204 |
+
for i, s in enumerate(asyncio.run(chat_manager.list_sessions()))],
|
| 205 |
+
label="Previous Chats",
|
| 206 |
+
interactive=True
|
| 207 |
+
)
|
| 208 |
+
new_chat_btn = gr.Button("New Chat")
|
| 209 |
+
|
| 210 |
+
with gr.Row(elem_classes="input-area"):
|
| 211 |
+
msg = gr.Textbox(
|
| 212 |
+
show_label=False,
|
| 213 |
+
placeholder="Type your message here...",
|
| 214 |
+
lines=2
|
| 215 |
+
)
|
| 216 |
+
submit_btn = gr.Button("Send", variant="primary")
|
| 217 |
+
|
| 218 |
+
async def load_chat(selected_id):
|
| 219 |
+
if selected_id:
|
| 220 |
+
history = await chat_manager.get_session_history(selected_id)
|
| 221 |
+
chat_history = [(msg["content"], msg["content"])
|
| 222 |
+
for msg in history
|
| 223 |
+
if msg["role"] in ["user", "assistant"]]
|
| 224 |
+
return chat_history, selected_id
|
| 225 |
+
return [], None
|
| 226 |
+
|
| 227 |
+
async def new_chat():
|
| 228 |
+
session_id = await chat_manager.new_session()
|
| 229 |
+
sessions = await chat_manager.list_sessions()
|
| 230 |
+
return [], session_id, gr.Dropdown.update(
|
| 231 |
+
choices=[(str(s["session_id"]), f"Chat {i+1}") for i, s in enumerate(sessions)]
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Connect event handlers
|
| 235 |
+
session_list.change(
|
| 236 |
+
lambda x: asyncio.run(load_chat(x)),
|
| 237 |
+
inputs=[session_list],
|
| 238 |
+
outputs=[chatbot, session_id]
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
new_chat_btn.click(
|
| 242 |
+
lambda: asyncio.run(new_chat()),
|
| 243 |
+
outputs=[chatbot, session_id, session_list]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Chat submission
|
| 247 |
+
submit_btn.click(
|
| 248 |
+
chat_with_claude,
|
| 249 |
+
inputs=[msg, chatbot, session_id],
|
| 250 |
+
outputs=[chatbot],
|
| 251 |
+
queue=False
|
| 252 |
+
).then(
|
| 253 |
+
lambda: "",
|
| 254 |
+
None,
|
| 255 |
+
[msg]
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
msg.submit(
|
| 259 |
+
chat_with_claude,
|
| 260 |
+
inputs=[msg, chatbot, session_id],
|
| 261 |
+
outputs=[chatbot],
|
| 262 |
+
queue=False
|
| 263 |
+
).then(
|
| 264 |
+
lambda: "",
|
| 265 |
+
None,
|
| 266 |
+
[msg]
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
return demo
|
| 270 |
|
| 271 |
# Launch the interface
|
| 272 |
if __name__ == "__main__":
|
| 273 |
+
# Initialize database connection
|
| 274 |
+
asyncio.run(initialize_managers())
|
| 275 |
+
|
| 276 |
+
# Create and launch the interface
|
| 277 |
+
demo = create_chat_interface()
|
| 278 |
+
demo.queue()
|
| 279 |
+
demo.launch(share=True)
|