rimandeep commited on
Commit
e2b5167
·
1 Parent(s): b9570cb

added backend files

Browse files
Files changed (10) hide show
  1. .dockerignore +23 -0
  2. .gitignore +14 -0
  3. Dockerfile +24 -0
  4. agents.py +116 -0
  5. create.sql +33 -0
  6. database.py +36 -0
  7. main.py +274 -0
  8. requirements.txt +16 -0
  9. schemas.py +32 -0
  10. utils.py +9 -0
.dockerignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+ .Python
7
+ *.so
8
+ *.egg
9
+ *.egg-info/
10
+ dist/
11
+ build/
12
+ .env
13
+ .env.*
14
+ *.log
15
+ .DS_Store
16
+ .idea/
17
+ .vscode/
18
+ *.swp
19
+ *.swo
20
+ *~
21
+ .pytest_cache/
22
+ .coverage
23
+ htmlcov/
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ venv/
3
+ ENV/
4
+ env/
5
+
6
+ .env
7
+ .env.*
8
+ *.env
9
+ .envrc
10
+
11
+ .venv_persona
12
+ *__pycache__/
13
+ *.pyc
14
+ .idea
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies
6
+ RUN apt-get update && apt-get install -y \
7
+ build-essential \
8
+ curl \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Copy requirements first for better caching
12
+ COPY requirements.txt .
13
+
14
+ # Install Python dependencies
15
+ RUN pip install --no-cache-dir -r requirements.txt
16
+
17
+ # Copy application code
18
+ COPY . .
19
+
20
+ # Expose port 7860 (Hugging Face default)
21
+ EXPOSE 7860
22
+
23
+ # Run the application
24
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
agents.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ from datetime import datetime
3
+ import os
4
+ from database import get_db_conn
5
+
6
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
7
+
8
+
9
+ # ------------------ Context Agent ------------------
10
+ class ContextManagerAgent:
11
+ def __init__(self, model="gemini-2.0-flash"):
12
+ self.model = genai.GenerativeModel(model)
13
+
14
+ def build_context(self, history):
15
+ text = "\n".join([f"{h['sender']}: {h['message']}" for h in history])
16
+
17
+ prompt = f"""
18
+ Summarize this chat conversation in 3–4 sentences.
19
+ Do NOT invent facts.
20
+
21
+ Conversation:
22
+ {text}
23
+ """
24
+ res = self.model.generate_content(prompt)
25
+ return res.text.strip()
26
+
27
+
28
+ # ------------------ Character Agent ------------------
29
+ class CharacterAgent:
30
+ def __init__(self, character_name, tone="friendly", model="gemini-2.0-flash"):
31
+ self.character_name = character_name
32
+ self.tone = tone
33
+ self.model = genai.GenerativeModel(model)
34
+
35
+ def reply(self, context_summary, user_msg):
36
+ prompt = f"""
37
+ You are {self.character_name}.
38
+ Tone: {self.tone}.
39
+
40
+ Stay completely in character.
41
+ No breaking the fourth wall.
42
+
43
+ Context Summary:
44
+ {context_summary}
45
+
46
+ User: {user_msg}
47
+
48
+ Reply as {self.character_name}.
49
+ """
50
+ res = self.model.generate_content(prompt)
51
+ return res.text.strip()
52
+
53
+
54
+ # ------------------ Moderator Agent ------------------
55
+ class ModeratorAgent:
56
+ def __init__(self, model="gemini-2.0-flash"):
57
+ self.model = genai.GenerativeModel(model)
58
+
59
+ def check(self, reply):
60
+ prompt = f"""
61
+ Clean this reply:
62
+ - No hallucinations
63
+ - Keep same tone & personality
64
+ - Remove unsafe content
65
+
66
+ {reply}
67
+ """
68
+ res = self.model.generate_content(prompt)
69
+ return res.text.strip()
70
+
71
+
72
+ # ------------------ Helpers ------------------
73
+ def fetch_last_messages_api(persona_id, limit=10):
74
+ limit = max(3, min(limit, 30)) # safety
75
+
76
+ conn = get_db_conn()
77
+ cursor = conn.cursor(dictionary=True)
78
+
79
+ cursor.execute("""
80
+ SELECT sender, message FROM persona_messages
81
+ WHERE persona_id=%s ORDER BY id DESC LIMIT %s
82
+ """, (persona_id, limit))
83
+
84
+ rows = cursor.fetchall()
85
+
86
+ cursor.close()
87
+ conn.close()
88
+
89
+ return list(reversed(rows))
90
+
91
+
92
+ def save_message_api(persona_id, sender, message):
93
+ conn = get_db_conn()
94
+ cursor = conn.cursor()
95
+
96
+ cursor.execute("""
97
+ INSERT INTO persona_messages (persona_id, sender, message, created_at)
98
+ VALUES (%s, %s, %s, NOW())
99
+ """, (persona_id, sender, message))
100
+
101
+ conn.commit()
102
+ cursor.close()
103
+ conn.close()
104
+
105
+
106
+ class MultiAgentPipeline:
107
+ def __init__(self, character_name, tone):
108
+ self.ctx = ContextManagerAgent()
109
+ self.char = CharacterAgent(character_name, tone)
110
+ self.mod = ModeratorAgent()
111
+
112
+ def run(self, persona_id, user_msg):
113
+ history = fetch_last_messages_api(persona_id)
114
+ ctx = self.ctx.build_context(history)
115
+ raw = self.char.reply(ctx, user_msg)
116
+ return self.mod.check(raw)
create.sql ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ create database persona_ai;
2
+ show databases;
3
+ use persona_ai;
4
+
5
+ CREATE TABLE users (
6
+ id INT(11) NOT NULL AUTO_INCREMENT,
7
+ username VARCHAR(100) NOT NULL,
8
+ hashed_password VARCHAR(200) NOT NULL,
9
+ created_at DATETIME NOT NULL,
10
+ PRIMARY KEY (id),
11
+ UNIQUE KEY (username) -- Assuming username should be unique
12
+ );
13
+ CREATE TABLE persona_flow (
14
+ id INT(11) NOT NULL AUTO_INCREMENT,
15
+ user_id INT(11) NOT NULL,
16
+ character_name VARCHAR(100) NOT NULL,
17
+ mode ENUM('auto', 'custom') NOT NULL,
18
+ tone VARCHAR(50),
19
+ summary TEXT,
20
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
21
+ PRIMARY KEY (id),
22
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
23
+ );
24
+ CREATE TABLE persona_messages (
25
+ id INT(11) NOT NULL AUTO_INCREMENT,
26
+ persona_id INT(11) NOT NULL,
27
+ sender ENUM('user', 'agent') NOT NULL,
28
+ message TEXT NOT NULL,
29
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
30
+ PRIMARY KEY (id),
31
+ FOREIGN KEY (persona_id) REFERENCES persona_flow(id) ON DELETE CASCADE
32
+ );
33
+ show tables;
database.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mysql.connector
2
+ import os
3
+ from dotenv import load_dotenv
4
+ import certifi
5
+
6
+ load_dotenv()
7
+
8
+ def get_db_conn():
9
+ # Get port with proper handling of empty strings
10
+ db_port = os.getenv("DB_PORT", "4000")
11
+ port = int(db_port) if db_port else 4000
12
+
13
+ config = {
14
+ "host": os.getenv("DB_HOST"),
15
+ "user": os.getenv("DB_USER"),
16
+ "password": os.getenv("DB_PASSWORD"),
17
+ "database": os.getenv("DB_NAME"),
18
+ "port": port,
19
+ "autocommit": True,
20
+ }
21
+
22
+ # TiDB Cloud / SSL Configuration
23
+ # If DB_SSL_CA is set, use it. Otherwise, use certifi's bundle.
24
+ # TiDB Cloud requires SSL.
25
+ ssl_mode = os.getenv("DB_SSL_MODE", "PREFERRED") # DISABLED, PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY
26
+
27
+ if ssl_mode != "DISABLED":
28
+ config["ssl_ca"] = os.getenv("DB_SSL_CA", certifi.where())
29
+ config["ssl_verify_cert"] = True
30
+ config["ssl_verify_identity"] = True
31
+
32
+ try:
33
+ return mysql.connector.connect(**config)
34
+ except mysql.connector.Error as err:
35
+ print(f"❌ Database Connection Error: {err}")
36
+ raise err
main.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Body
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from datetime import datetime
4
+ from database import get_db_conn
5
+ from schemas import UserCreate, UserLogin, PersonaCreate, PersonaOut, MessageCreate
6
+ from utils import hash_password, verify_password
7
+ from agents import MultiAgentPipeline, save_message_api
8
+
9
+ app = FastAPI(title="Persona AI – Final Backend")
10
+
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ @app.get("/")
20
+ def root():
21
+ return {"msg": "Persona AI Backend Running..."}
22
+
23
+ @app.get("/health")
24
+ def health_check():
25
+ """Test database connection"""
26
+ try:
27
+ conn = get_db_conn()
28
+ cursor = conn.cursor()
29
+ cursor.execute("SELECT 1")
30
+ result = cursor.fetchone()
31
+ cursor.close()
32
+ conn.close()
33
+ return {"status": "healthy", "database": "connected", "test_query": result[0]}
34
+ except Exception as e:
35
+ import traceback
36
+ error_details = traceback.format_exc()
37
+ return {
38
+ "status": "unhealthy",
39
+ "database": "disconnected",
40
+ "error": str(e),
41
+ "error_type": type(e).__name__,
42
+ "traceback": error_details
43
+ }
44
+
45
+
46
+ # --------------------------------------------------------
47
+ # REGISTER
48
+ # --------------------------------------------------------
49
+ @app.post("/register")
50
+ def register(user: UserCreate):
51
+ conn = get_db_conn()
52
+ cursor = conn.cursor()
53
+
54
+ hashed = hash_password(user.password)
55
+ now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
56
+
57
+ try:
58
+ cursor.execute("""
59
+ INSERT INTO users (username, hashed_password, created_at)
60
+ VALUES (%s, %s, %s)
61
+ """, (user.username, hashed, now))
62
+
63
+ conn.commit()
64
+ return {"msg": "User created", "username": user.username}
65
+
66
+ except Exception as e:
67
+ conn.rollback()
68
+ print(f"❌ Database error: {type(e).__name__}: {str(e)}")
69
+ import traceback
70
+ traceback.print_exc()
71
+ # Check if it's a duplicate username error
72
+ if "Duplicate entry" in str(e) or "unique" in str(e).lower():
73
+ raise HTTPException(status_code=400, detail="Username already exists")
74
+ # Otherwise raise the actual error
75
+ raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
76
+
77
+ finally:
78
+ cursor.close()
79
+ conn.close()
80
+
81
+
82
+ # --------------------------------------------------------
83
+ # LOGIN → Returns user_id (simple auth)
84
+ # --------------------------------------------------------
85
+ @app.post("/login")
86
+ def login(data: UserLogin):
87
+ conn = get_db_conn()
88
+ cursor = conn.cursor(dictionary=True)
89
+
90
+ cursor.execute("SELECT * FROM users WHERE username=%s", (data.username,))
91
+ user = cursor.fetchone()
92
+
93
+ cursor.close()
94
+ conn.close()
95
+
96
+ if not user or not verify_password(data.password, user["hashed_password"]):
97
+ raise HTTPException(status_code=401, detail="Invalid username/password")
98
+
99
+ return {
100
+ "msg": "Login successful",
101
+ "user_id": user["id"],
102
+ "username": user["username"]
103
+ }
104
+
105
+
106
+ # --------------------------------------------------------
107
+ # CREATE PERSONA
108
+ # --------------------------------------------------------
109
+ @app.post("/personas", response_model=PersonaOut)
110
+ def create_persona(p: PersonaCreate):
111
+
112
+ conn = get_db_conn()
113
+ cursor = conn.cursor()
114
+
115
+ # Fix defaults
116
+ tone = p.tone if p.tone else "neutral"
117
+ summary = p.summary if p.summary else ""
118
+
119
+ if p.mode == "custom" and not summary:
120
+ raise HTTPException(400, "Custom mode needs summary")
121
+
122
+ now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
123
+
124
+ cursor.execute("""
125
+ INSERT INTO persona_flow (user_id, character_name, mode, tone, summary, created_at)
126
+ VALUES (%s, %s, %s, %s, %s, %s)
127
+ """, (p.user_id, p.character_name, p.mode, tone, summary, now))
128
+
129
+ conn.commit()
130
+ persona_id = cursor.lastrowid
131
+
132
+ cursor.execute("SELECT * FROM persona_flow WHERE id=%s", (persona_id,))
133
+ row = cursor.fetchone()
134
+
135
+ cursor.close()
136
+ conn.close()
137
+
138
+ return PersonaOut(
139
+ id=row[0], user_id=row[1], character_name=row[2],
140
+ mode=row[3], tone=row[4], summary=row[5], created_at=row[6]
141
+ )
142
+
143
+
144
+ # --------------------------------------------------------
145
+ # CHAT WITH AGENT
146
+ # --------------------------------------------------------
147
+ @app.post("/agent/respond")
148
+ def agent_respond(
149
+ user_id: int = Body(...),
150
+ persona_id: int = Body(...),
151
+ user_input: str = Body(...)
152
+ ):
153
+
154
+ # Check persona belongs to user
155
+ conn = get_db_conn()
156
+ cursor = conn.cursor(dictionary=True)
157
+
158
+ cursor.execute("SELECT * FROM persona_flow WHERE id=%s AND user_id=%s",
159
+ (persona_id, user_id))
160
+ persona = cursor.fetchone()
161
+
162
+ if not persona:
163
+ raise HTTPException(404, "Persona not found for this user")
164
+
165
+ cursor.close()
166
+ conn.close()
167
+
168
+ pipeline = MultiAgentPipeline(persona["character_name"], persona["tone"] or "neutral")
169
+
170
+ save_message_api(persona_id, "user", user_input)
171
+ reply = pipeline.run(persona_id, user_input)
172
+ save_message_api(persona_id, "agent", reply)
173
+
174
+ return {"reply": reply}
175
+
176
+
177
+ # --------------------------------------------------------
178
+ # GET MESSAGES FOR ONE CHARACTER
179
+ # --------------------------------------------------------
180
+ @app.get("/messages/{persona_id}")
181
+ def get_messages(persona_id: int, user_id: int):
182
+
183
+ conn = get_db_conn()
184
+ cursor = conn.cursor(dictionary=True)
185
+
186
+ cursor.execute("SELECT * FROM persona_flow WHERE id=%s AND user_id=%s",
187
+ (persona_id, user_id))
188
+ owner = cursor.fetchone()
189
+
190
+ if not owner:
191
+ raise HTTPException(403, "Access denied")
192
+
193
+ cursor.execute("""
194
+ SELECT * FROM persona_messages
195
+ WHERE persona_id=%s ORDER BY id ASC
196
+ """, (persona_id,))
197
+
198
+ rows = cursor.fetchall()
199
+
200
+ cursor.close()
201
+ conn.close()
202
+
203
+ return rows
204
+
205
+
206
+ # --------------------------------------------------------
207
+ # GET FULL MESSAGE HISTORY
208
+ # --------------------------------------------------------
209
+ @app.get("/messages/full/{persona_id}")
210
+ def full_history(persona_id: int):
211
+ conn = get_db_conn()
212
+ cursor = conn.cursor(dictionary=True)
213
+
214
+ cursor.execute("""
215
+ SELECT * FROM persona_messages
216
+ WHERE persona_id=%s ORDER BY created_at ASC
217
+ """, (persona_id,))
218
+
219
+ rows = cursor.fetchall()
220
+
221
+ cursor.close()
222
+ conn.close()
223
+
224
+ return rows
225
+
226
+
227
+ # --------------------------------------------------------
228
+ # LIST PERSONAS OF A USER (with message count)
229
+ # --------------------------------------------------------
230
+ @app.get("/personas/list/{user_id}")
231
+ def list_personas(user_id: int):
232
+ conn = get_db_conn()
233
+ cursor = conn.cursor(dictionary=True)
234
+
235
+ cursor.execute("""
236
+ SELECT pf.*,
237
+ (SELECT COUNT(*) FROM persona_messages pm WHERE pm.persona_id = pf.id)
238
+ AS message_count
239
+ FROM persona_flow pf
240
+ WHERE user_id = %s
241
+ ORDER BY created_at DESC
242
+ """, (user_id,))
243
+
244
+ personas = cursor.fetchall()
245
+
246
+ cursor.close()
247
+ conn.close()
248
+
249
+ return personas
250
+
251
+
252
+ # --------------------------------------------------------
253
+ # DELETE PERSONA
254
+ # --------------------------------------------------------
255
+ @app.delete("/personas/{persona_id}")
256
+ def delete_persona(persona_id: int, user_id: int):
257
+ conn = get_db_conn()
258
+ cursor = conn.cursor(dictionary=True)
259
+
260
+ cursor.execute("SELECT * FROM persona_flow WHERE id=%s AND user_id=%s",
261
+ (persona_id, user_id))
262
+ persona = cursor.fetchone()
263
+
264
+ if not persona:
265
+ raise HTTPException(403, "Persona not found or not owned by user")
266
+
267
+ cursor.execute("DELETE FROM persona_messages WHERE persona_id=%s", (persona_id,))
268
+ cursor.execute("DELETE FROM persona_flow WHERE id=%s", (persona_id,))
269
+
270
+ conn.commit()
271
+ cursor.close()
272
+ conn.close()
273
+
274
+ return {"msg": "Persona deleted", "id": persona_id}
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-dotenv
2
+ mysql-connector-python
3
+ SQLAlchemy
4
+ fastapi
5
+ pydantic
6
+ uvicorn
7
+ tenacity
8
+ sqlalchemy
9
+ pymysql
10
+ python-multipart
11
+ PyJWT
12
+ bcrypt==3.2.2
13
+ passlib==1.7.4
14
+ google-generativeai
15
+ certifi
16
+ jose
schemas.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import Optional
3
+ from datetime import datetime
4
+
5
+ class UserCreate(BaseModel):
6
+ username: str
7
+ password: str
8
+
9
+ class UserLogin(BaseModel):
10
+ username: str
11
+ password: str
12
+
13
+ class PersonaCreate(BaseModel):
14
+ user_id: int
15
+ character_name: str
16
+ mode: str
17
+ tone: Optional[str] = None
18
+ summary: Optional[str] = None
19
+
20
+ class PersonaOut(BaseModel):
21
+ id: int
22
+ user_id: int
23
+ character_name: str
24
+ mode: str
25
+ tone: Optional[str]
26
+ summary: Optional[str]
27
+ created_at: datetime
28
+
29
+ class MessageCreate(BaseModel):
30
+ persona_id: int
31
+ sender: str
32
+ message: str
utils.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from passlib.context import CryptContext
2
+
3
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
4
+
5
+ def hash_password(password: str) -> str:
6
+ return pwd_context.hash(password)
7
+
8
+ def verify_password(plain: str, hashed: str) -> bool:
9
+ return pwd_context.verify(plain, hashed)