Edit Selecuon View GO Run O Project
frontend py databasepy 3X nexus apipy 9+ S Appjs .env
database py >..
1 database. py
2
import os
import json
from datetime import datetime
from sqllchemy import creste_engine, Column, Integer, String, Text, DateTime, Foreignkey
7 from sqlelchemy . or import sessionmaker, Session
from sqlelchemy. ext. declarative import declarative base
9 from dotenv import load_dotenv
10
11 # - Load Environment Variables -.
12 load_ dotenv()
13 # DB_USER [Link]("DB_USER_") I
14
DB_PASSWORD [Link]("DB_ PASSWORD")I
15 # DB_HOST [Link]("DB_HOST")
16
#DB_DATABASE os . getenv("DB_DATABASE")
17 # DB_PORT [Link]("DB_PORT", "5432")
18
19 DB_USER "postgres"
20 DB_ HOST "localhost"
21 DB_DATABASE ="chats"
22 DB_PORT 5432
23
24
25 # --- Create PostgresQL Connection URL
26
27
DATABASE_ URL =f"postgresql+psycopg2://(D8_USER}: {DB_PASSHORD)E(DB_HOST}:(D8_PORT)/tD8_ DATABASE"
28 #-- SQLAlchemy Setup
29
engine create_engine(DATABASE_URL)
3e
31
SessionLocal sessionmaker(autocomnite False, utoflusheFalse, bindeengine)
Base = declarative base()
32
33 #-- Define Database Table Models ---
34
35 class ChatSession (Base) :
36 _tablename "chat_sessions"
Ln 14,Col 39 Spaces 4 UTF-8 CRLF () Python 8 3.11.11(conda)
T14
PTOject
frontend,py database,py 3 X nexus_api.py 9+ S Appjs .env
"[Link] > ChatMessage
35 class ChatSession (Base):
36
tablename "chat_sessions"
37 id =Column (String, primary_key=True, indexeTrue)
38 title = Column (String, default="New Chat")
39 created_at Column (DateTime, defaultedetetime . tenew)
40 db_name Column(String, nullablenTrue)
41
42
loaded_tables_json = Column (Text, nullable=True) # Wi11 store a JSON líst of table
names
43
44 class ChatMessage (Base):
45 tablename_ : "chat messages"
46 id = Columr(Integer, primary_key=True, index=True)l
47
session_id = Column (String, Foreignkey ("chat _sessions . id"))
48 role = Column(String) # 'user' or 'assistant!
49 content : Column (Text)
# Store complex data as JSON strings
51 dataframe json= Column (Text, nullable=True)
52 chart json = Column (Text, nullable=True)
53
suggestions json = Column (Text, nullable=True)
54 explanation = olumn (Text, nullable=True)
55
created_at Column (DateTime, default=[Link])
56
57 def create db_and_tables() :
58 n"Creates the database tables if they don't exist. "nn
59
60
[Link].create_al1 (bind=engine)
61
print ("Database tables checked/created. ")
62 def get_db():
63
#**Dependency for getting a DB session. nnm
64 db = SessionLoca1()
65 try:
66 yield db
67 finally:
68 [Link]()
69
79 --- Database Helper Functions
17 A0 Ln46,Col 55 Spaces 4 UTF-8 CRLF 0 Python 3.11.11 (conda)
File Edit Selection View Go Run OProject
[Link] " databasepy 3 X nexus_api.py 9+ S Appjs Oenv
" database,py > ChatMessage
Helper Functions
7e # - - Database
71
72 def get_session (db: Session, session_id: str):
73 wn"Gets a single session object by its ID. ""*
74 return db. query (ChatSession). filter (ChatSession. id session_íd).fírst()
75
76 def save_data_context_to_session(db: Session, session_id : str, db_name: str, tables: 1ist):
77 w*"Saves the data context but does NOT Set a specific title. "u"
78 session_obj get_session (db, session_ id)
79
80 if not session_obj:
81 # Create a new session if it doesn 't exist, using the default title "NevlChat"
82 session_obj = ChatSession(
83 id=session_id,
84 db name=db_name,
85 loaded_tables_json=json . dumps (tables)
86
87 [Link] (session_obj)
88 else:
89 # If the session already exists, just update its data context
90 session_obj.db name = db_name
91 session_obj -loaded tables json json . dumps (tables)
92
93 [Link]()
94
95
96 def geta1l_sessions (db: Session):
97 return db. query (ChatSession) .order_by (ChatSession . created_at. desc()) .all()
98
99
def get_messages by_session (db: Session, session_id: str):
100
return [Link](ChatMessage). filter (ChatMessage.session_id = session_id).order_by (ChatMessage.created_at. asc() ). all ()
101
102 def save_message_to_db(db: Session, session_id : str, message : dict):
103
"Saves a message and updates the chat title on the first user message.'
104
sessionget_session (db,, session_id)
105
17 A0 Ln 46, Col55 Spaces: 4 UTF-8 CRLF (0 Python 3.11.11 (conda)
le Edit Selection View Go Run OProject
frontend. py " databasepy 3 X nexus_api.py 9+ Js Appjs .env
[Link] > ChatMessage
102 def save_message_to_db(db: Session, session_id: str, message: dict) :
103 wnmSaves amessage and updates the chat title on the first user message.
104 session = get_session (db, session_id)
105
106 # Check if a session exists. If not, create it using the first message as the títle.
107 if not session:
108 title = message. get(" content", "New Chat")[:50] if message . get ("role") = "user" else "Chat Session"
109 session ChatSession (id=session_id, title=title)
110 [Link] (session)
111 [Link]()
112 [Link](session)
113 # NEW LOGIC: If the session exists but has a generic title, update it with user's first prompt..
114 elif [Link] "New Chat" and [Link]("role")"user":
115 [Link] message. get ("content", "New Chat") [ :50]
116
117 # Save the actual message content
118 db message = ChatMessage(
119 session_id=session_id,
120 role=[Link] (" role"),
121 content=[Link] ("content"),
122 dataframe_json=message. get ("dataframe"),
-123
chart json=json . dumps (message. get(" chart")) if [Link]("chart" ) else None,
124
suggestions_json=json. dumps ([Link] ("suggestions") ) if message .get("suggestions") else None,
125
explanation=json .dumps ([Link] ("explanation" ) ) if [Link](" explanation") else None,
126 )
127 [Link] (db_message)
128 [Link]()
129 [Link] (db message )