Spaces:
Running
Running
File size: 13,234 Bytes
a57a50a |
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 94 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
"""PostgreSQL Store implementation for ChatKit SDK.
[Task]: T009
[From]: specs/010-chatkit-migration/data-model.md - ChatKit SDK Interface Requirements
[From]: specs/010-chatkit-migration/contracts/backend.md - Store Interface Implementation
This module implements the ChatKit Store interface using SQLModel and PostgreSQL.
The Store interface is required by ChatKit's Python SDK for thread and message persistence.
ChatKit Store Protocol Methods:
- list_threads: List threads for a user with pagination
- get_thread: Get a specific thread by ID
- create_thread: Create a new thread
- update_thread: Update thread metadata
- delete_thread: Delete a thread
- list_messages: List messages in a thread
- get_message: Get a specific message
- create_message: Create a new message
- update_message: Update a message
- delete_message: Delete a message
"""
import uuid
from datetime import datetime
from typing import Any, Optional
from sqlmodel import Session, select, col
from sqlalchemy.ext.asyncio import AsyncSession
from models.thread import Thread
from models.message import Message, MessageRole
class PostgresChatKitStore:
"""PostgreSQL implementation of ChatKit Store interface.
[From]: specs/010-chatkit-migration/data-model.md - Store Interface
This store provides thread and message persistence for ChatKit using
the existing SQLModel models and PostgreSQL database.
Note: The ChatKit SDK uses a Protocol-based interface. The actual
protocol types (ThreadMetadata, MessageItem, etc.) would be imported
from the openai_chatkit package. For this implementation, we use
dictionary-based representations until the SDK is installed.
Usage:
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from services.chatkit_store import PostgresChatKitStore
engine = create_async_engine(database_url)
async with AsyncSession(engine) as session:
store = PostgresChatKitStore(session)
thread = await store.create_thread(
user_id="user-123",
title="My Conversation",
metadata={"tag": "important"}
)
"""
def __init__(self, session: AsyncSession):
"""Initialize the store with a database session.
Args:
session: SQLAlchemy async session for database operations
"""
self.session = session
async def list_threads(
self,
user_id: str,
limit: int = 50,
offset: int = 0
) -> list[dict]:
"""List threads for a user with pagination.
[From]: specs/010-chatkit-migration/data-model.md - Retrieve User's Conversations
Args:
user_id: User ID to filter threads
limit: Maximum number of threads to return (default: 50)
offset: Number of threads to skip (default: 0)
Returns:
List of thread metadata dictionaries
"""
stmt = (
select(Thread)
.where(Thread.user_id == uuid.UUID(user_id))
.order_by(Thread.updated_at.desc())
.limit(limit)
.offset(offset)
)
result = await self.session.execute(stmt)
threads = result.scalars().all()
return [
{
"id": str(thread.id),
"user_id": str(thread.user_id),
"title": thread.title,
"metadata": thread.thread_metadata or {},
"created_at": thread.created_at.isoformat(),
"updated_at": thread.updated_at.isoformat(),
}
for thread in threads
]
async def get_thread(self, thread_id: str) -> Optional[dict]:
"""Get a specific thread by ID.
Args:
thread_id: Thread UUID as string
Returns:
Thread metadata dictionary or None if not found
"""
stmt = select(Thread).where(Thread.id == uuid.UUID(thread_id))
result = await self.session.execute(stmt)
thread = result.scalar_one_or_none()
if thread is None:
return None
return {
"id": str(thread.id),
"user_id": str(thread.user_id),
"title": thread.title,
"metadata": thread.thread_metadata or {},
"created_at": thread.created_at.isoformat(),
"updated_at": thread.updated_at.isoformat(),
}
async def create_thread(
self,
user_id: str,
title: Optional[str] = None,
metadata: Optional[dict] = None
) -> dict:
"""Create a new thread.
Args:
user_id: User ID who owns the thread
title: Optional thread title
metadata: Optional thread metadata
Returns:
Created thread metadata dictionary
"""
thread = Thread(
user_id=uuid.UUID(user_id),
title=title,
thread_metadata=metadata or {},
)
self.session.add(thread)
await self.session.commit()
await self.session.refresh(thread)
return {
"id": str(thread.id),
"user_id": str(thread.user_id),
"title": thread.title,
"metadata": thread.thread_metadata or {},
"created_at": thread.created_at.isoformat(),
"updated_at": thread.updated_at.isoformat(),
}
async def update_thread(
self,
thread_id: str,
title: Optional[str] = None,
metadata: Optional[dict] = None
) -> Optional[dict]:
"""Update a thread.
Args:
thread_id: Thread UUID as string
title: New title (optional)
metadata: New metadata (optional)
Returns:
Updated thread metadata dictionary or None if not found
"""
stmt = select(Thread).where(Thread.id == uuid.UUID(thread_id))
result = await self.session.execute(stmt)
thread = result.scalar_one_or_none()
if thread is None:
return None
if title is not None:
thread.title = title
if metadata is not None:
thread.thread_metadata = metadata
thread.updated_at = datetime.utcnow()
await self.session.commit()
await self.session.refresh(thread)
return {
"id": str(thread.id),
"user_id": str(thread.user_id),
"title": thread.title,
"metadata": thread.thread_metadata or {},
"created_at": thread.created_at.isoformat(),
"updated_at": thread.updated_at.isoformat(),
}
async def delete_thread(self, thread_id: str) -> bool:
"""Delete a thread.
Args:
thread_id: Thread UUID as string
Returns:
True if deleted, False if not found
"""
stmt = select(Thread).where(Thread.id == uuid.UUID(thread_id))
result = await self.session.execute(stmt)
thread = result.scalar_one_or_none()
if thread is None:
return False
await self.session.delete(thread)
await self.session.commit()
return True
async def list_messages(
self,
thread_id: str,
limit: int = 50,
offset: int = 0
) -> list[dict]:
"""List messages in a thread.
[From]: specs/010-chatkit-migration/data-model.md - Retrieve Conversation Messages
Args:
thread_id: Thread UUID as string
limit: Maximum number of messages to return
offset: Number of messages to skip
Returns:
List of message item dictionaries
"""
stmt = (
select(Message)
.where(Message.thread_id == uuid.UUID(thread_id))
.order_by(Message.created_at.asc())
.limit(limit)
.offset(offset)
)
result = await self.session.execute(stmt)
messages = result.scalars().all()
return [
{
"id": str(msg.id),
"type": "message",
"role": msg.role.value,
"content": [{"type": "text", "text": msg.content}],
"tool_calls": msg.tool_calls,
"created_at": msg.created_at.isoformat(),
}
for msg in messages
]
async def get_message(self, message_id: str) -> Optional[dict]:
"""Get a specific message by ID.
Args:
message_id: Message UUID as string
Returns:
Message item dictionary or None if not found
"""
stmt = select(Message).where(Message.id == uuid.UUID(message_id))
result = await self.session.execute(stmt)
message = result.scalar_one_or_none()
if message is None:
return None
return {
"id": str(message.id),
"type": "message",
"role": message.role.value,
"content": [{"type": "text", "text": message.content}],
"tool_calls": message.tool_calls,
"created_at": message.created_at.isoformat(),
}
async def create_message(
self,
thread_id: str,
item: dict
) -> dict:
"""Create a new message in a thread.
Args:
thread_id: Thread UUID as string
item: Message item from ChatKit (UserMessageItem or ClientToolCallOutputItem)
Returns:
Created message item dictionary
Raises:
ValueError: If item format is invalid
"""
# Extract content from ChatKit item format
# ChatKit uses: {"type": "message", "role": "user", "content": [{"type": "text", "text": "..."}]}
item_type = item.get("type", "message")
role = item.get("role", "user")
# Extract text content from content array
content_array = item.get("content", [])
text_content = ""
for content_block in content_array:
if content_block.get("type") == "text":
text_content = content_block.get("text", "")
break
# Handle client tool output items
if item_type == "client_tool_call_output":
text_content = item.get("output", "")
message = Message(
thread_id=uuid.UUID(thread_id),
role=MessageRole(role),
content=text_content,
tool_calls=item.get("tool_calls"),
)
self.session.add(message)
await self.session.commit()
await self.session.refresh(message)
# Update thread's updated_at timestamp
thread_stmt = select(Thread).where(Thread.id == uuid.UUID(thread_id))
thread_result = await self.session.execute(thread_stmt)
thread = thread_result.scalar_one_or_none()
if thread:
thread.updated_at = datetime.utcnow()
await self.session.commit()
return {
"id": str(message.id),
"type": "message",
"role": message.role.value,
"content": [{"type": "text", "text": message.content}],
"tool_calls": message.tool_calls,
"created_at": message.created_at.isoformat(),
}
async def update_message(
self,
message_id: str,
item: dict
) -> Optional[dict]:
"""Update a message.
Args:
message_id: Message UUID as string
item: Updated message item
Returns:
Updated message item dictionary or None if not found
"""
stmt = select(Message).where(Message.id == uuid.UUID(message_id))
result = await self.session.execute(stmt)
message = result.scalar_one_or_none()
if message is None:
return None
# Update content if provided
content_array = item.get("content", [])
if content_array:
for content_block in content_array:
if content_block.get("type") == "text":
message.content = content_block.get("text", message.content)
break
# Update tool_calls if provided
if "tool_calls" in item:
message.tool_calls = item["tool_calls"]
await self.session.commit()
await self.session.refresh(message)
return {
"id": str(message.id),
"type": "message",
"role": message.role.value,
"content": [{"type": "text", "text": message.content}],
"tool_calls": message.tool_calls,
"created_at": message.created_at.isoformat(),
}
async def delete_message(self, message_id: str) -> bool:
"""Delete a message.
Args:
message_id: Message UUID as string
Returns:
True if deleted, False if not found
"""
stmt = select(Message).where(Message.id == uuid.UUID(message_id))
result = await self.session.execute(stmt)
message = result.scalar_one_or_none()
if message is None:
return False
await self.session.delete(message)
await self.session.commit()
return True
|