86 lines
4.7 KiB
Python
86 lines
4.7 KiB
Python
import asyncio
|
|
from contextlib import closing
|
|
import os
|
|
import sqlite3
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
|
|
class History:
|
|
def __init__(self, path):
|
|
self.path = Path(path)
|
|
self.lock = asyncio.Lock()
|
|
|
|
async def call(self, fn):
|
|
async with self.lock:
|
|
task = asyncio.create_task(asyncio.to_thread(self.transaction, fn))
|
|
try:
|
|
return await asyncio.shield(task)
|
|
except asyncio.CancelledError:
|
|
await task
|
|
raise
|
|
|
|
def transaction(self, fn):
|
|
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
if not self.path.exists():
|
|
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
os.close(fd)
|
|
os.chmod(self.path, 0o600)
|
|
with closing(sqlite3.connect(self.path, timeout=5)) as db:
|
|
db.row_factory = sqlite3.Row
|
|
db.execute('PRAGMA journal_mode=WAL')
|
|
db.execute('PRAGMA foreign_keys=ON')
|
|
with db:
|
|
result = fn(db)
|
|
for suffix in ('-wal', '-shm'):
|
|
p = Path(str(self.path) + suffix)
|
|
if p.exists(): os.chmod(p, 0o600)
|
|
return result
|
|
|
|
async def initialize(self):
|
|
def init(db):
|
|
db.executescript('''CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY, created REAL NOT NULL);
|
|
CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL REFERENCES conversations(id), run_id TEXT NOT NULL, role TEXT NOT NULL, text TEXT NOT NULL, status TEXT NOT NULL, playback TEXT NOT NULL DEFAULT 'not_started', created REAL NOT NULL, updated REAL NOT NULL, UNIQUE(run_id,role));''')
|
|
db.execute("UPDATE messages SET status='interrupted', playback='unconfirmed' WHERE status='generating'")
|
|
await self.call(init)
|
|
|
|
async def conversation(self, requested=None):
|
|
if requested is not None:
|
|
if not isinstance(requested, str) or len(requested) != 36 or str(uuid.UUID(requested)) != requested:
|
|
raise ValueError('invalid conversation UUID')
|
|
value = requested or str(uuid.uuid4())
|
|
await self.call(lambda db: db.execute('INSERT OR IGNORE INTO conversations VALUES (?,?)', (value, time.time())))
|
|
return value
|
|
|
|
async def rows(self, cid):
|
|
return await self.call(lambda db: [dict(r) for r in db.execute('SELECT id,run_id,role,text,status,playback,created,updated FROM (SELECT * FROM messages WHERE conversation_id=? ORDER BY id DESC LIMIT 100) ORDER BY id', (cid,))])
|
|
|
|
async def context(self, cid, current):
|
|
def query(db):
|
|
rows = list(db.execute("SELECT u.text user,a.text assistant FROM messages u JOIN messages a ON u.run_id=a.run_id AND u.conversation_id=a.conversation_id WHERE u.conversation_id=? AND u.run_id<>? AND u.role='user' AND a.role='assistant' AND u.status='completed' AND a.status='completed' AND a.playback='confirmed' ORDER BY u.id DESC LIMIT 10", (cid, current)))
|
|
out = []
|
|
for r in reversed(rows):
|
|
out += [{'role': 'user', 'content': r['user'][:2000]}, {'role': 'assistant', 'content': r['assistant'][:2000]}]
|
|
return out
|
|
return await self.call(query)
|
|
|
|
async def begin(self, cid, rid, text):
|
|
def insert(db):
|
|
now = time.time()
|
|
db.execute('INSERT INTO messages(conversation_id,run_id,role,text,status,created,updated) VALUES (?,?,?,?,?,?,?)', (cid, rid, 'user', text[:2000], 'completed', now, now))
|
|
db.execute('INSERT INTO messages(conversation_id,run_id,role,text,status,created,updated) VALUES (?,?,?,?,?,?,?)', (cid, rid, 'assistant', '', 'generating', now, now))
|
|
await self.call(insert)
|
|
|
|
async def finish(self, rid, text, status):
|
|
await self.call(lambda db: db.execute("UPDATE messages SET text=?, status=?, playback=CASE WHEN ?='completed' THEN 'awaiting_drain' ELSE 'unconfirmed' END,updated=? WHERE run_id=? AND role='assistant' AND (status='generating' OR (status='interrupted' AND ?='interrupted'))", (text[:2000], status, status, time.time(), rid, status)))
|
|
|
|
async def interrupt(self, rid):
|
|
await self.call(lambda db: db.execute("UPDATE messages SET status=CASE WHEN status='completed' THEN status ELSE 'interrupted' END,playback='interrupted',updated=? WHERE run_id=? AND role='assistant' AND playback<>'confirmed'", (time.time(), rid)))
|
|
|
|
async def drained(self, rid):
|
|
await self.call(lambda db: db.execute("UPDATE messages SET playback='confirmed',updated=? WHERE run_id=? AND role='assistant' AND status='completed' AND playback='awaiting_drain'", (time.time(), rid)))
|
|
|
|
async def clear(self, cid):
|
|
await self.call(lambda db: db.execute('DELETE FROM messages WHERE conversation_id=?', (cid,)))
|