Elffuss BraidHub

kikocis/llama-stack public

3fc339af16ee · 2.8 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import json
8from datetime import datetime
9from typing import Any, List, Optional
10
11import aiosqlite
12
13from llama_stack.apis.control_plane import * # noqa: F403
14
15
16from .config import SqliteControlPlaneConfig
17
18
19class SqliteControlPlane(ControlPlane):
20 def __init__(self, config: SqliteControlPlaneConfig):
21 self.db_path = config.db_path
22 self.table_name = config.table_name
23
24 async def initialize(self):
25 async with aiosqlite.connect(self.db_path) as db:
26 await db.execute(
27 f"""
28 CREATE TABLE IF NOT EXISTS {self.table_name} (
29 key TEXT PRIMARY KEY,
30 value TEXT,
31 expiration TIMESTAMP
32 )
33 """
34 )
35 await db.commit()
36
37 async def set(
38 self, key: str, value: Any, expiration: Optional[datetime] = None
39 ) -> None:
40 async with aiosqlite.connect(self.db_path) as db:
41 await db.execute(
42 f"INSERT OR REPLACE INTO {self.table_name} (key, value, expiration) VALUES (?, ?, ?)",
43 (key, json.dumps(value), expiration),
44 )
45 await db.commit()
46
47 async def get(self, key: str) -> Optional[ControlPlaneValue]:
48 async with aiosqlite.connect(self.db_path) as db:
49 async with db.execute(
50 f"SELECT value, expiration FROM {self.table_name} WHERE key = ?", (key,)
51 ) as cursor:
52 row = await cursor.fetchone()
53 if row is None:
54 return None
55 value, expiration = row
56 return ControlPlaneValue(
57 key=key, value=json.loads(value), expiration=expiration
58 )
59
60 async def delete(self, key: str) -> None:
61 async with aiosqlite.connect(self.db_path) as db:
62 await db.execute(f"DELETE FROM {self.table_name} WHERE key = ?", (key,))
63 await db.commit()
64
65 async def range(self, start_key: str, end_key: str) -> List[ControlPlaneValue]:
66 async with aiosqlite.connect(self.db_path) as db:
67 async with db.execute(
68 f"SELECT key, value, expiration FROM {self.table_name} WHERE key >= ? AND key <= ?",
69 (start_key, end_key),
70 ) as cursor:
71 result = []
72 async for row in cursor:
73 key, value, expiration = row
74 result.append(
75 ControlPlaneValue(
76 key=key, value=json.loads(value), expiration=expiration
77 )
78 )
79 return result