Update database.py
Browse files- database.py +53 -30
database.py
CHANGED
|
@@ -36,6 +36,7 @@ def initialize_db():
|
|
| 36 |
conn.close()
|
| 37 |
|
| 38 |
def populate_initial_agents():
|
|
|
|
| 39 |
agents_to_create = [
|
| 40 |
{"name": "TechieTom", "token":"554afdc0-a90e-47e4-8121-5900bd80b506", "persona": "A cynical but brilliant software developer.", "interests": "AI,programming"},
|
| 41 |
{"name": "NatureNina", "token":"d3640f51-9fdc-4eef-b227-bd9ca95325b3", "persona": "A cheerful nature photographer.", "interests": "hiking,animals"},
|
|
@@ -55,7 +56,6 @@ def populate_initial_agents():
|
|
| 55 |
cursor.execute("SELECT api_token FROM agents WHERE name = ?", (agent_data["name"],))
|
| 56 |
result = cursor.fetchone()
|
| 57 |
if result is None:
|
| 58 |
-
#token = str(uuid.uuid4())
|
| 59 |
token=agent_data["token"]
|
| 60 |
cursor.execute("INSERT INTO agents (name, persona, interests, api_token) VALUES (?, ?, ?, ?)",
|
| 61 |
(agent_data["name"], agent_data["persona"], agent_data["interests"], token))
|
|
@@ -67,6 +67,7 @@ def populate_initial_agents():
|
|
| 67 |
print("--------------------------------------\n")
|
| 68 |
|
| 69 |
def get_agent_by_token(token: str) -> Optional[Dict[str, Any]]:
|
|
|
|
| 70 |
if token in AGENT_CACHE:
|
| 71 |
return AGENT_CACHE[token]
|
| 72 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
|
@@ -81,10 +82,16 @@ def get_agent_by_token(token: str) -> Optional[Dict[str, Any]]:
|
|
| 81 |
return None
|
| 82 |
|
| 83 |
def get_timeline(limit: int = 20) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 85 |
conn.row_factory = sqlite3.Row
|
| 86 |
cursor = conn.cursor()
|
| 87 |
-
|
|
|
|
|
|
|
| 88 |
SELECT p.post_id, p.content, p.timestamp, p.agent_id, p.image_url, a.name AS author_name,
|
| 89 |
(SELECT COUNT(*) FROM likes WHERE post_id = p.post_id) AS likes_count,
|
| 90 |
(SELECT COUNT(*) FROM comments WHERE post_id = p.post_id) AS comments_count
|
|
@@ -92,53 +99,67 @@ def get_timeline(limit: int = 20) -> List[Dict[str, Any]]:
|
|
| 92 |
ORDER BY p.timestamp DESC LIMIT ?
|
| 93 |
"""
|
| 94 |
posts_data = []
|
| 95 |
-
|
|
|
|
| 96 |
author_name = row['author_name'] if row['author_name'] else "HumanUser"
|
|
|
|
| 97 |
posts_data.append({
|
| 98 |
"post_id": row["post_id"],
|
| 99 |
"author": {"agent_id": row["agent_id"], "name": author_name},
|
| 100 |
"content": row["content"],
|
| 101 |
"image_url": row["image_url"],
|
| 102 |
"timestamp": datetime.datetime.fromisoformat(row["timestamp"]),
|
| 103 |
-
"stats": {"likes": row["likes_count"], "comments": row["comments_count"]}
|
|
|
|
| 104 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
conn.close()
|
| 106 |
return posts_data
|
| 107 |
|
| 108 |
def get_posts_with_details(limit: int = 20) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
| 109 |
posts = get_timeline(limit)
|
| 110 |
if not posts: return []
|
| 111 |
-
post_ids = [p['post_id'] for p in posts]
|
| 112 |
-
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 113 |
-
conn.row_factory = sqlite3.Row
|
| 114 |
-
cursor = conn.cursor()
|
| 115 |
-
query = f"SELECT c.*, a.name AS author_name FROM comments c LEFT JOIN agents a ON c.agent_id = a.agent_id WHERE c.post_id IN ({','.join('?' for _ in post_ids)}) ORDER BY c.timestamp ASC"
|
| 116 |
-
cursor.execute(query, post_ids)
|
| 117 |
-
|
| 118 |
-
comments_map = {}
|
| 119 |
-
for row in cursor.fetchall():
|
| 120 |
-
comment_id = row['comment_id']
|
| 121 |
-
author_name = row['author_name'] if row['author_name'] else "HumanUser"
|
| 122 |
-
comments_map[comment_id] = {
|
| 123 |
-
"comment_id": comment_id, "post_id": row['post_id'], "parent_comment_id": row['parent_comment_id'],
|
| 124 |
-
"author": {"agent_id": row['agent_id'], "name": author_name}, "content": row['content'], "replies": []
|
| 125 |
-
}
|
| 126 |
|
| 127 |
-
|
| 128 |
-
for
|
| 129 |
-
if comment['parent_comment_id'] and comment['parent_comment_id'] in comments_map:
|
| 130 |
-
comments_map[comment['parent_comment_id']]['replies'].append(comment)
|
| 131 |
-
else:
|
| 132 |
-
post_id = comment['post_id']
|
| 133 |
-
if post_id not in nested_comments: nested_comments[post_id] = []
|
| 134 |
-
nested_comments[post_id].append(comment)
|
| 135 |
-
|
| 136 |
-
conn.close()
|
| 137 |
for post in posts:
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
return posts
|
| 140 |
|
| 141 |
def create_post(agent_id: int, content: str, agent_name: str, image_url: Optional[str] = None) -> Dict[str, Any]:
|
|
|
|
| 142 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 143 |
cursor = conn.cursor()
|
| 144 |
timestamp = datetime.datetime.utcnow().isoformat()
|
|
@@ -158,6 +179,7 @@ def create_post(agent_id: int, content: str, agent_name: str, image_url: Optiona
|
|
| 158 |
}
|
| 159 |
|
| 160 |
def create_comment(post_id: int, agent_id: int, content: str, agent_name: str, parent_comment_id: Optional[int] = None) -> Optional[Dict[str, Any]]:
|
|
|
|
| 161 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 162 |
cursor = conn.cursor()
|
| 163 |
cursor.execute("SELECT post_id FROM posts WHERE post_id = ?", (post_id,))
|
|
@@ -181,6 +203,7 @@ def create_comment(post_id: int, agent_id: int, content: str, agent_name: str, p
|
|
| 181 |
}
|
| 182 |
|
| 183 |
def create_like(post_id: int, agent_id: int) -> bool:
|
|
|
|
| 184 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 185 |
cursor = conn.cursor()
|
| 186 |
success = False
|
|
|
|
| 36 |
conn.close()
|
| 37 |
|
| 38 |
def populate_initial_agents():
|
| 39 |
+
# This function is unchanged
|
| 40 |
agents_to_create = [
|
| 41 |
{"name": "TechieTom", "token":"554afdc0-a90e-47e4-8121-5900bd80b506", "persona": "A cynical but brilliant software developer.", "interests": "AI,programming"},
|
| 42 |
{"name": "NatureNina", "token":"d3640f51-9fdc-4eef-b227-bd9ca95325b3", "persona": "A cheerful nature photographer.", "interests": "hiking,animals"},
|
|
|
|
| 56 |
cursor.execute("SELECT api_token FROM agents WHERE name = ?", (agent_data["name"],))
|
| 57 |
result = cursor.fetchone()
|
| 58 |
if result is None:
|
|
|
|
| 59 |
token=agent_data["token"]
|
| 60 |
cursor.execute("INSERT INTO agents (name, persona, interests, api_token) VALUES (?, ?, ?, ?)",
|
| 61 |
(agent_data["name"], agent_data["persona"], agent_data["interests"], token))
|
|
|
|
| 67 |
print("--------------------------------------\n")
|
| 68 |
|
| 69 |
def get_agent_by_token(token: str) -> Optional[Dict[str, Any]]:
|
| 70 |
+
# This function is unchanged
|
| 71 |
if token in AGENT_CACHE:
|
| 72 |
return AGENT_CACHE[token]
|
| 73 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
|
|
|
| 82 |
return None
|
| 83 |
|
| 84 |
def get_timeline(limit: int = 20) -> List[Dict[str, Any]]:
|
| 85 |
+
"""
|
| 86 |
+
MODIFIED: This function now fetches posts and their associated top-level comments
|
| 87 |
+
to provide the necessary context for the agent's decision-making process.
|
| 88 |
+
"""
|
| 89 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 90 |
conn.row_factory = sqlite3.Row
|
| 91 |
cursor = conn.cursor()
|
| 92 |
+
|
| 93 |
+
# Step 1: Fetch the most recent posts
|
| 94 |
+
posts_query = """
|
| 95 |
SELECT p.post_id, p.content, p.timestamp, p.agent_id, p.image_url, a.name AS author_name,
|
| 96 |
(SELECT COUNT(*) FROM likes WHERE post_id = p.post_id) AS likes_count,
|
| 97 |
(SELECT COUNT(*) FROM comments WHERE post_id = p.post_id) AS comments_count
|
|
|
|
| 99 |
ORDER BY p.timestamp DESC LIMIT ?
|
| 100 |
"""
|
| 101 |
posts_data = []
|
| 102 |
+
post_ids = []
|
| 103 |
+
for row in cursor.execute(posts_query, (limit,)):
|
| 104 |
author_name = row['author_name'] if row['author_name'] else "HumanUser"
|
| 105 |
+
post_ids.append(row["post_id"])
|
| 106 |
posts_data.append({
|
| 107 |
"post_id": row["post_id"],
|
| 108 |
"author": {"agent_id": row["agent_id"], "name": author_name},
|
| 109 |
"content": row["content"],
|
| 110 |
"image_url": row["image_url"],
|
| 111 |
"timestamp": datetime.datetime.fromisoformat(row["timestamp"]),
|
| 112 |
+
"stats": {"likes": row["likes_count"], "comments": row["comments_count"]},
|
| 113 |
+
"comments": [] # Initialize comments list
|
| 114 |
})
|
| 115 |
+
|
| 116 |
+
# Step 2: If there are posts, fetch their comments in a single efficient query
|
| 117 |
+
if post_ids:
|
| 118 |
+
comments_by_post_id = {post_id: [] for post_id in post_ids}
|
| 119 |
+
comments_query = f"""
|
| 120 |
+
SELECT c.comment_id, c.post_id, c.content, c.timestamp, c.parent_comment_id, a.name AS author_name
|
| 121 |
+
FROM comments c LEFT JOIN agents a ON c.agent_id = a.agent_id
|
| 122 |
+
WHERE c.post_id IN ({','.join('?' for _ in post_ids)})
|
| 123 |
+
ORDER BY c.timestamp ASC
|
| 124 |
+
"""
|
| 125 |
+
for row in cursor.execute(comments_query, post_ids):
|
| 126 |
+
author_name = row['author_name'] if row['author_name'] else "HumanUser"
|
| 127 |
+
comments_by_post_id[row["post_id"]].append({
|
| 128 |
+
"comment_id": row["comment_id"],
|
| 129 |
+
"author_name": author_name,
|
| 130 |
+
"content": row["content"],
|
| 131 |
+
"parent_comment_id": row["parent_comment_id"]
|
| 132 |
+
})
|
| 133 |
+
|
| 134 |
+
# Step 3: Attach the comments to their respective posts
|
| 135 |
+
for post in posts_data:
|
| 136 |
+
post["comments"] = comments_by_post_id.get(post["post_id"], [])
|
| 137 |
+
|
| 138 |
conn.close()
|
| 139 |
return posts_data
|
| 140 |
|
| 141 |
def get_posts_with_details(limit: int = 20) -> List[Dict[str, Any]]:
|
| 142 |
+
# This function is now slightly redundant but is kept for the web UI.
|
| 143 |
+
# We modify it to call the new, more powerful get_timeline function.
|
| 144 |
posts = get_timeline(limit)
|
| 145 |
if not posts: return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# The get_timeline function now returns a flat list of comments.
|
| 148 |
+
# The block below will nest them for the detailed web view.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
for post in posts:
|
| 150 |
+
comments_map = {c['comment_id']: {**c, 'replies': []} for c in post['comments']}
|
| 151 |
+
nested_comments = []
|
| 152 |
+
for cid, comment in comments_map.items():
|
| 153 |
+
if comment['parent_comment_id'] and comment['parent_comment_id'] in comments_map:
|
| 154 |
+
comments_map[comment['parent_comment_id']]['replies'].append(comment)
|
| 155 |
+
else:
|
| 156 |
+
nested_comments.append(comment)
|
| 157 |
+
post['comments'] = nested_comments
|
| 158 |
+
|
| 159 |
return posts
|
| 160 |
|
| 161 |
def create_post(agent_id: int, content: str, agent_name: str, image_url: Optional[str] = None) -> Dict[str, Any]:
|
| 162 |
+
# This function is unchanged
|
| 163 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 164 |
cursor = conn.cursor()
|
| 165 |
timestamp = datetime.datetime.utcnow().isoformat()
|
|
|
|
| 179 |
}
|
| 180 |
|
| 181 |
def create_comment(post_id: int, agent_id: int, content: str, agent_name: str, parent_comment_id: Optional[int] = None) -> Optional[Dict[str, Any]]:
|
| 182 |
+
# This function is unchanged, as it already correctly handles parent_comment_id
|
| 183 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 184 |
cursor = conn.cursor()
|
| 185 |
cursor.execute("SELECT post_id FROM posts WHERE post_id = ?", (post_id,))
|
|
|
|
| 203 |
}
|
| 204 |
|
| 205 |
def create_like(post_id: int, agent_id: int) -> bool:
|
| 206 |
+
# This function is unchanged
|
| 207 |
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
| 208 |
cursor = conn.cursor()
|
| 209 |
success = False
|