Record chat history into the database using async SQL.
| 10 | |
| 11 | |
| 12 | class HistoryRecorder: |
| 13 | """Record chat history into the database using async SQL.""" |
| 14 | |
| 15 | def __init__(self, db_url: str, table_name: str): |
| 16 | self.logger = get_logger() |
| 17 | self._db_url = db_url |
| 18 | self._table_name = table_name |
| 19 | self._initialized = False |
| 20 | |
| 21 | async def prepare(self) -> None: |
| 22 | if self._initialized: |
| 23 | return |
| 24 | engine, self.meta_cls, self.blob_cls = await init_async_engine( |
| 25 | db_url=self._db_url, |
| 26 | table_name=self._table_name, |
| 27 | schema_type="experience", |
| 28 | ) |
| 29 | self.session = async_sessionmaker(engine, expire_on_commit=False) |
| 30 | self._initialized = True |
| 31 | self.logger.info(f"Init async SQL storage at {self._db_url}") |
| 32 | |
| 33 | async def record_history(self, experiences: List[Experience]) -> None: |
| 34 | """Save experiences to the database.""" |
| 35 | await self.prepare() |
| 36 | |
| 37 | async def operation(session: AsyncSession): |
| 38 | for exp in experiences: |
| 39 | meta_row = self.meta_cls.from_experience(exp) |
| 40 | session.add(meta_row) |
| 41 | await session.flush() |
| 42 | blob_row = self.blob_cls(id=meta_row.id, experience_bytes=exp.serialize()) |
| 43 | session.add(blob_row) |
| 44 | |
| 45 | await async_run_with_retry_session(self.session, operation) |
| 46 | |
| 47 | async def update_reward( |
| 48 | self, reward: float, msg_ids: list, run_id: int, task_id: str |
| 49 | ) -> List[Experience]: |
| 50 | """Update reward for given response IDs and return the updated experiences. |
| 51 | |
| 52 | Only experiences that have not been consumed (consumed == 0) will be returned. |
| 53 | """ |
| 54 | await self.prepare() |
| 55 | |
| 56 | meta_cls = self.meta_cls |
| 57 | blob_cls = self.blob_cls |
| 58 | |
| 59 | async def operation(session: AsyncSession): |
| 60 | stmt = ( |
| 61 | select(meta_cls) |
| 62 | .where(meta_cls.msg_id.in_(msg_ids), meta_cls.consumed == 0) |
| 63 | .with_for_update() |
| 64 | ) |
| 65 | result = await session.execute(stmt) |
| 66 | records = result.scalars().all() |
| 67 | |
| 68 | if not records: |
| 69 | return [] |
no outgoing calls