agent memory and replay
What this workflow does
Agent run steps are recorded in AgentMemory, converted back to messages, and replayed through logging and code reconstruction.
Purpose
preserve and inspect an agent’s task, planning, action, and final-answer history
What it produces
AgentMemory steps and code actions
Who relies on it
agent developer / operator
Why this workflow matters
- supports debugging and auditability of agent runs
- enables reconstruction of executable code from prior actions
- preserves step history for summaries and replays
View supporting code
228 | def __init__(self, system_prompt: str):
229 | self.system_prompt: SystemPromptStep = SystemPromptStep(system_prompt=system_prompt)
230 | self.steps: list[TaskStep | ActionStep | PlanningStep] = []
231 |
232 | def reset(self):
233 | """Reset the agent's memory, clearing all steps and keeping the system prompt."""
234 | self.steps = []
235 |
236 | def get_succinct_steps(self) -> list[dict]:
237 | """Return a succinct representation of the agent's steps, excluding model input messages."""
238 | return [
239 | {key: value for key, value in step.dict().items() if key != "model_input_messages"} for step in self.steps
240 | ]
241 |
242 | def get_full_steps(self) -> list[dict]:
243 | """Return a full representation of the agent's steps, including model input messages."""
244 | if len(self.steps) == 0:
245 | return []
246 | return [step.dict() for step in self.steps] 248 | def replay(self, logger: AgentLogger, detailed: bool = False):
249 | """Prints a pretty replay of the agent's steps.
250 |
251 | Args:
252 | logger (`AgentLogger`): The logger to print replay logs to.
253 | detailed (`bool`, default `False`): If True, also displays the memory at each step. Defaults to False.
254 | Careful: will increase log length exponentially. Use only for debugging.
255 | """
256 | logger.console.log("Replaying the agent's steps:")
257 | logger.log_markdown(title="System prompt", content=self.system_prompt.system_prompt, level=LogLevel.ERROR)
258 | for step in self.steps:
259 | if isinstance(step, TaskStep):
260 | logger.log_task(step.task, "", level=LogLevel.ERROR)
261 | elif isinstance(step, ActionStep):
262 | logger.log_rule(f"Step {step.step_number}", level=LogLevel.ERROR)
263 | if detailed and step.model_input_messages is not None:
264 | logger.log_messages(step.model_input_messages, level=LogLevel.ERROR)
265 | if step.model_output is not None:
266 | logger.log_markdown(title="Agent output:", content=step.model_output, level=LogLevel.ERROR)
267 | elif isinstance(step, PlanningStep):
268 | logger.log_rule("Planning step", level=LogLevel.ERROR)
269 | if detailed and step.model_input_messages is not None:
270 | logger.log_messages(step.model_input_messages, level=LogLevel.ERROR)
271 | logger.log_markdown(title="Agent output:", content=step.plan, level=LogLevel.ERROR)
272 |
273 | def return_full_code(self) -> str:
274 | """Returns all code actions from the agent's steps, concatenated as a single script."""
275 | return "\n\n".join(
276 | [step.code_action for step in self.steps if isinstance(step, ActionStep) and step.code_action is not None]
277 | ) 214 | class AgentMemory:
215 | """Memory for the agent, containing the system prompt and all steps taken by the agent.
216 |
217 | This class is used to store the agent's steps, including tasks, actions, and planning steps.
218 | It allows for resetting the memory, retrieving succinct or full step information, and replaying the agent's steps.
219 |
220 | Args:
221 | system_prompt (`str`): System prompt for the agent, which sets the context and instructions for the agent's behavior.
222 |
223 | **Attributes**:
224 | - **system_prompt** (`SystemPromptStep`) -- System prompt step for the agent.
225 | - **steps** (`list[TaskStep | ActionStep | PlanningStep]`) -- List of steps taken by the agent, which can include tasks, actions, and planning steps.
226 | """
227 |
228 | def __init__(self, system_prompt: str):
229 | self.system_prompt: SystemPromptStep = SystemPromptStep(system_prompt=system_prompt)
230 | self.steps: list[TaskStep | ActionStep | PlanningStep] = [] 224 | - **system_prompt** (`SystemPromptStep`) -- System prompt step for the agent.
225 | - **steps** (`list[TaskStep | ActionStep | PlanningStep]`) -- List of steps taken by the agent, which can include tasks, actions, and planning steps.
226 | """
227 |
228 | def __init__(self, system_prompt: str):
229 | self.system_prompt: SystemPromptStep = SystemPromptStep(system_prompt=system_prompt)
230 | self.steps: list[TaskStep | ActionStep | PlanningStep] = [] 51 | class ActionStep(MemoryStep):
52 | step_number: int
53 | timing: Timing
54 | model_input_messages: list[ChatMessage] | None = None
55 | tool_calls: list[ToolCall] | None = None
56 | error: AgentError | None = None
57 | model_output_message: ChatMessage | None = None
58 | model_output: str | list[dict[str, Any]] | None = None
59 | code_action: str | None = None
60 | observations: str | None = None
61 | observations_images: list["PIL.Image.Image"] | None = None
62 | action_output: Any = None
63 | token_usage: TokenUsage | None = None
64 | is_final_answer: bool = False 273 | def return_full_code(self) -> str:
274 | """Returns all code actions from the agent's steps, concatenated as a single script."""
275 | return "\n\n".join(
276 | [step.code_action for step in self.steps if isinstance(step, ActionStep) and step.code_action is not None]
277 | )