Skip to content

Sqlite

SQLiteChatStore #

Bases: BaseChatStore

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
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
class SQLiteChatStore(BaseChatStore):
    table_name: Optional[str] = Field(
        default="chatstore", description="SQLite table name."
    )

    _table_class: TableProtocol = PrivateAttr()  # type: ignore
    _session: sessionmaker = PrivateAttr()  # type: ignore
    _async_session: async_sessionmaker = PrivateAttr()  # type: ignore

    def __init__(
        self,
        session: sessionmaker,
        async_session: async_sessionmaker,
        table_name: str,
    ):
        super().__init__(
            table_name=table_name.lower(),
        )

        # sqlalchemy model
        base = declarative_base()
        self._table_class = get_data_model(
            base,
            table_name,
        )
        self._session = session
        self._async_session = async_session
        self._initialize(base)

    @classmethod
    def from_params(
        cls,
        database: str,
        table_name: str = "chatstore",
        connection_string: Optional[str] = None,
        async_connection_string: Optional[str] = None,
        debug: bool = False,
    ) -> "SQLiteChatStore":
        """Return connection string from database parameters."""
        conn_str = connection_string or f"sqlite:///{database}"
        async_conn_str = async_connection_string or (f"sqlite+aiosqlite:///{database}")
        session, async_session = cls._connect(conn_str, async_conn_str, debug)
        return cls(
            session=session,
            async_session=async_session,
            table_name=table_name,
        )

    @classmethod
    def from_uri(
        cls,
        uri: str,
        table_name: str = "chatstore",
        debug: bool = False,
    ) -> "SQLiteChatStore":
        """Return connection string from database parameters."""
        params = params_from_uri(uri)
        return cls.from_params(
            **params,
            table_name=table_name,
            debug=debug,
        )

    @classmethod
    def _connect(
        cls, connection_string: str, async_connection_string: str, debug: bool
    ) -> tuple[sessionmaker, async_sessionmaker]:
        _engine = create_engine(connection_string, echo=debug)
        session = sessionmaker(_engine)

        _async_engine = create_async_engine(async_connection_string)
        async_session = async_sessionmaker(_async_engine, class_=AsyncSession)
        return session, async_session

    def _create_tables_if_not_exists(self, base) -> None:
        with self._session() as session, session.begin():
            base.metadata.create_all(session.connection())

    def _initialize(self, base) -> None:
        self._create_tables_if_not_exists(base)

    def set_messages(self, key: str, messages: list[ChatMessage]) -> None:
        """Set messages for a key."""
        with self._session() as session:
            session.execute(
                insert(self._table_class),
                [
                    {"key": key, "value": message.model_dump(mode="json")}
                    for message in messages
                ],
            )
            session.commit()

    async def aset_messages(self, key: str, messages: list[ChatMessage]) -> None:
        """Async version of Get messages for a key."""
        async with self._async_session() as session:
            await session.execute(
                insert(self._table_class),
                [
                    {"key": key, "value": message.model_dump(mode="json")}
                    for message in messages
                ],
            )
            await session.commit()

    def get_messages(self, key: str) -> list[ChatMessage]:
        """Get messages for a key."""
        with self._session() as session:
            result = session.execute(
                select(self._table_class)
                .where(self._table_class.key == key)
                .order_by(self._table_class.id)
            )
            result = result.scalars().all()
            if result:
                return [ChatMessage.model_validate(row.value) for row in result]
            return []

    async def aget_messages(self, key: str) -> list[ChatMessage]:
        """Async version of Get messages for a key."""
        async with self._async_session() as session:
            result = await session.execute(
                select(self._table_class)
                .where(self._table_class.key == key)
                .order_by(self._table_class.id)
            )
            result = result.scalars().all()
            if result:
                return [ChatMessage.model_validate(row.value) for row in result]
            return []

    def add_message(self, key: str, message: ChatMessage) -> None:
        """Add a message for a key."""
        with self._session() as session:
            session.execute(
                insert(self._table_class),
                [{"key": key, "value": message.model_dump(mode="json")}],
            )
            session.commit()

    async def async_add_message(self, key: str, message: ChatMessage) -> None:
        """Async version of Add a message for a key."""
        async with self._async_session() as session:
            await session.execute(
                insert(self._table_class),
                [{"key": key, "value": message.model_dump(mode="json")}],
            )
            await session.commit()

    def delete_messages(self, key: str) -> Optional[list[ChatMessage]]:
        """Delete messages for a key."""
        with self._session() as session:
            session.execute(
                delete(self._table_class).where(self._table_class.key == key)
            )
            session.commit()
        return None

    async def adelete_messages(self, key: str) -> Optional[list[ChatMessage]]:
        """Async version of Delete messages for a key."""
        async with self._async_session() as session:
            await session.execute(
                delete(self._table_class).where(self._table_class.key == key)
            )
            await session.commit()
        return None

    def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
        """Delete specific message for a key."""
        with self._session() as session:
            # First, retrieve message
            result = session.execute(
                select(self._table_class.value).where(
                    self._table_class.key == key, self._table_class.id == idx
                )
            ).scalar_one_or_none()

            if result is None:
                return None

            session.execute(
                delete(self._table_class).where(
                    self._table_class.key == key, self._table_class.id == idx
                )
            )
            session.commit()

            return ChatMessage.model_validate(result)

    async def adelete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
        """Async version of Delete specific message for a key."""
        async with self._async_session() as session:
            # First, retrieve message
            result = (
                await session.execute(
                    select(self._table_class.value).where(
                        self._table_class.key == key, self._table_class.id == idx
                    )
                )
            ).scalar_one_or_none()

            if result is None:
                return None

            await session.execute(
                delete(self._table_class).where(
                    self._table_class.key == key, self._table_class.id == idx
                )
            )
            await session.commit()

            return ChatMessage.model_validate(result)

    def delete_last_message(self, key: str) -> Optional[ChatMessage]:
        """Delete last message for a key."""
        with self._session() as session:
            # First, retrieve the current list of messages
            stmt = (
                select(self._table_class.id, self._table_class.value)
                .where(self._table_class.key == key)
                .order_by(self._table_class.id.desc())
                .limit(1)
            )
            result = session.execute(stmt).all()

            if not result:
                # If the key doesn't exist or the array is empty
                return None

            session.execute(
                delete(self._table_class).where(self._table_class.id == result[0][0])
            )
            session.commit()

            return ChatMessage.model_validate(result[0][1])

    async def adelete_last_message(self, key: str) -> Optional[ChatMessage]:
        """Async version of Delete last message for a key."""
        async with self._async_session() as session:
            # First, retrieve the current list of messages
            stmt = (
                select(self._table_class.id, self._table_class.value)
                .where(self._table_class.key == key)
                .order_by(self._table_class.id.desc())
                .limit(1)
            )
            result = (await session.execute(stmt)).all()

            if not result:
                # If the key doesn't exist or the array is empty
                return None

            await session.execute(
                delete(self._table_class).where(self._table_class.id == result[0][0])
            )
            await session.commit()

            return ChatMessage.model_validate(result[0][1])

    def get_keys(self) -> list[str]:
        """Get all keys."""
        with self._session() as session:
            stmt = select(self._table_class.key.distinct())

            return session.execute(stmt).scalars().all()

    async def aget_keys(self) -> list[str]:
        """Async version of Get all keys."""
        async with self._async_session() as session:
            stmt = select(self._table_class.key.distinct())

            return (await session.execute(stmt)).scalars().all()

from_params classmethod #

from_params(database: str, table_name: str = 'chatstore', connection_string: Optional[str] = None, async_connection_string: Optional[str] = None, debug: bool = False) -> SQLiteChatStore

Return connection string from database parameters.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@classmethod
def from_params(
    cls,
    database: str,
    table_name: str = "chatstore",
    connection_string: Optional[str] = None,
    async_connection_string: Optional[str] = None,
    debug: bool = False,
) -> "SQLiteChatStore":
    """Return connection string from database parameters."""
    conn_str = connection_string or f"sqlite:///{database}"
    async_conn_str = async_connection_string or (f"sqlite+aiosqlite:///{database}")
    session, async_session = cls._connect(conn_str, async_conn_str, debug)
    return cls(
        session=session,
        async_session=async_session,
        table_name=table_name,
    )

from_uri classmethod #

from_uri(uri: str, table_name: str = 'chatstore', debug: bool = False) -> SQLiteChatStore

Return connection string from database parameters.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@classmethod
def from_uri(
    cls,
    uri: str,
    table_name: str = "chatstore",
    debug: bool = False,
) -> "SQLiteChatStore":
    """Return connection string from database parameters."""
    params = params_from_uri(uri)
    return cls.from_params(
        **params,
        table_name=table_name,
        debug=debug,
    )

set_messages #

set_messages(key: str, messages: list[ChatMessage]) -> None

Set messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
209
210
211
212
213
214
215
216
217
218
219
def set_messages(self, key: str, messages: list[ChatMessage]) -> None:
    """Set messages for a key."""
    with self._session() as session:
        session.execute(
            insert(self._table_class),
            [
                {"key": key, "value": message.model_dump(mode="json")}
                for message in messages
            ],
        )
        session.commit()

aset_messages async #

aset_messages(key: str, messages: list[ChatMessage]) -> None

Async version of Get messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
221
222
223
224
225
226
227
228
229
230
231
async def aset_messages(self, key: str, messages: list[ChatMessage]) -> None:
    """Async version of Get messages for a key."""
    async with self._async_session() as session:
        await session.execute(
            insert(self._table_class),
            [
                {"key": key, "value": message.model_dump(mode="json")}
                for message in messages
            ],
        )
        await session.commit()

get_messages #

get_messages(key: str) -> list[ChatMessage]

Get messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
233
234
235
236
237
238
239
240
241
242
243
244
def get_messages(self, key: str) -> list[ChatMessage]:
    """Get messages for a key."""
    with self._session() as session:
        result = session.execute(
            select(self._table_class)
            .where(self._table_class.key == key)
            .order_by(self._table_class.id)
        )
        result = result.scalars().all()
        if result:
            return [ChatMessage.model_validate(row.value) for row in result]
        return []

aget_messages async #

aget_messages(key: str) -> list[ChatMessage]

Async version of Get messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
246
247
248
249
250
251
252
253
254
255
256
257
async def aget_messages(self, key: str) -> list[ChatMessage]:
    """Async version of Get messages for a key."""
    async with self._async_session() as session:
        result = await session.execute(
            select(self._table_class)
            .where(self._table_class.key == key)
            .order_by(self._table_class.id)
        )
        result = result.scalars().all()
        if result:
            return [ChatMessage.model_validate(row.value) for row in result]
        return []

add_message #

add_message(key: str, message: ChatMessage) -> None

Add a message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
259
260
261
262
263
264
265
266
def add_message(self, key: str, message: ChatMessage) -> None:
    """Add a message for a key."""
    with self._session() as session:
        session.execute(
            insert(self._table_class),
            [{"key": key, "value": message.model_dump(mode="json")}],
        )
        session.commit()

async_add_message async #

async_add_message(key: str, message: ChatMessage) -> None

Async version of Add a message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
268
269
270
271
272
273
274
275
async def async_add_message(self, key: str, message: ChatMessage) -> None:
    """Async version of Add a message for a key."""
    async with self._async_session() as session:
        await session.execute(
            insert(self._table_class),
            [{"key": key, "value": message.model_dump(mode="json")}],
        )
        await session.commit()

delete_messages #

delete_messages(key: str) -> Optional[list[ChatMessage]]

Delete messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
277
278
279
280
281
282
283
284
def delete_messages(self, key: str) -> Optional[list[ChatMessage]]:
    """Delete messages for a key."""
    with self._session() as session:
        session.execute(
            delete(self._table_class).where(self._table_class.key == key)
        )
        session.commit()
    return None

adelete_messages async #

adelete_messages(key: str) -> Optional[list[ChatMessage]]

Async version of Delete messages for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
286
287
288
289
290
291
292
293
async def adelete_messages(self, key: str) -> Optional[list[ChatMessage]]:
    """Async version of Delete messages for a key."""
    async with self._async_session() as session:
        await session.execute(
            delete(self._table_class).where(self._table_class.key == key)
        )
        await session.commit()
    return None

delete_message #

delete_message(key: str, idx: int) -> Optional[ChatMessage]

Delete specific message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
    """Delete specific message for a key."""
    with self._session() as session:
        # First, retrieve message
        result = session.execute(
            select(self._table_class.value).where(
                self._table_class.key == key, self._table_class.id == idx
            )
        ).scalar_one_or_none()

        if result is None:
            return None

        session.execute(
            delete(self._table_class).where(
                self._table_class.key == key, self._table_class.id == idx
            )
        )
        session.commit()

        return ChatMessage.model_validate(result)

adelete_message async #

adelete_message(key: str, idx: int) -> Optional[ChatMessage]

Async version of Delete specific message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
async def adelete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
    """Async version of Delete specific message for a key."""
    async with self._async_session() as session:
        # First, retrieve message
        result = (
            await session.execute(
                select(self._table_class.value).where(
                    self._table_class.key == key, self._table_class.id == idx
                )
            )
        ).scalar_one_or_none()

        if result is None:
            return None

        await session.execute(
            delete(self._table_class).where(
                self._table_class.key == key, self._table_class.id == idx
            )
        )
        await session.commit()

        return ChatMessage.model_validate(result)

delete_last_message #

delete_last_message(key: str) -> Optional[ChatMessage]

Delete last message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def delete_last_message(self, key: str) -> Optional[ChatMessage]:
    """Delete last message for a key."""
    with self._session() as session:
        # First, retrieve the current list of messages
        stmt = (
            select(self._table_class.id, self._table_class.value)
            .where(self._table_class.key == key)
            .order_by(self._table_class.id.desc())
            .limit(1)
        )
        result = session.execute(stmt).all()

        if not result:
            # If the key doesn't exist or the array is empty
            return None

        session.execute(
            delete(self._table_class).where(self._table_class.id == result[0][0])
        )
        session.commit()

        return ChatMessage.model_validate(result[0][1])

adelete_last_message async #

adelete_last_message(key: str) -> Optional[ChatMessage]

Async version of Delete last message for a key.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
async def adelete_last_message(self, key: str) -> Optional[ChatMessage]:
    """Async version of Delete last message for a key."""
    async with self._async_session() as session:
        # First, retrieve the current list of messages
        stmt = (
            select(self._table_class.id, self._table_class.value)
            .where(self._table_class.key == key)
            .order_by(self._table_class.id.desc())
            .limit(1)
        )
        result = (await session.execute(stmt)).all()

        if not result:
            # If the key doesn't exist or the array is empty
            return None

        await session.execute(
            delete(self._table_class).where(self._table_class.id == result[0][0])
        )
        await session.commit()

        return ChatMessage.model_validate(result[0][1])

get_keys #

get_keys() -> list[str]

Get all keys.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
387
388
389
390
391
392
def get_keys(self) -> list[str]:
    """Get all keys."""
    with self._session() as session:
        stmt = select(self._table_class.key.distinct())

        return session.execute(stmt).scalars().all()

aget_keys async #

aget_keys() -> list[str]

Async version of Get all keys.

Source code in llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py
394
395
396
397
398
399
async def aget_keys(self) -> list[str]:
    """Async version of Get all keys."""
    async with self._async_session() as session:
        stmt = select(self._table_class.key.distinct())

        return (await session.execute(stmt)).scalars().all()