Rewinds the session to before the specified invocation.
(
self,
*,
user_id: str,
session_id: str,
rewind_before_invocation_id: str,
run_config: Optional[RunConfig] = None,
)
| 1134 | yield event |
| 1135 | |
| 1136 | async def rewind_async( |
| 1137 | self, |
| 1138 | *, |
| 1139 | user_id: str, |
| 1140 | session_id: str, |
| 1141 | rewind_before_invocation_id: str, |
| 1142 | run_config: Optional[RunConfig] = None, |
| 1143 | ) -> None: |
| 1144 | """Rewinds the session to before the specified invocation.""" |
| 1145 | run_config = run_config or RunConfig() |
| 1146 | session = await self._get_or_create_session( |
| 1147 | user_id=user_id, |
| 1148 | session_id=session_id, |
| 1149 | get_session_config=run_config.get_session_config, |
| 1150 | ) |
| 1151 | rewind_event_index = -1 |
| 1152 | for i, event in enumerate(session.events): |
| 1153 | if event.invocation_id == rewind_before_invocation_id: |
| 1154 | rewind_event_index = i |
| 1155 | break |
| 1156 | |
| 1157 | if rewind_event_index == -1: |
| 1158 | raise ValueError( |
| 1159 | f'Invocation ID not found: {rewind_before_invocation_id}' |
| 1160 | ) |
| 1161 | |
| 1162 | # Compute state delta to reverse changes |
| 1163 | state_delta = await self._compute_state_delta_for_rewind( |
| 1164 | session, rewind_event_index |
| 1165 | ) |
| 1166 | |
| 1167 | # Compute artifact delta to reverse changes |
| 1168 | artifact_delta = await self._compute_artifact_delta_for_rewind( |
| 1169 | session, rewind_event_index |
| 1170 | ) |
| 1171 | |
| 1172 | # Create rewind event |
| 1173 | rewind_event = Event( |
| 1174 | invocation_id=new_invocation_context_id(), |
| 1175 | author='user', |
| 1176 | actions=EventActions( |
| 1177 | rewind_before_invocation_id=rewind_before_invocation_id, |
| 1178 | state_delta=state_delta, |
| 1179 | artifact_delta=artifact_delta, |
| 1180 | ), |
| 1181 | ) |
| 1182 | |
| 1183 | logger.info('Rewinding session to invocation: %s', rewind_event) |
| 1184 | |
| 1185 | await self.session_service.append_event(session=session, event=rewind_event) |
| 1186 | |
| 1187 | async def _compute_state_delta_for_rewind( |
| 1188 | self, session: Session, rewind_event_index: int |