Work Log
Keep a log of every tool call the agent makes, with its full result, and of the model’s replies, so the model can find and read earlier work again after compaction cleared it from the conversation or ToolOutputLimits cut it down. The model searches the log with search_work_log and reads an entry with read_work_log, as tools or from Code Mode code. ResetCompaction builds on it: it clears the history in one step and points the model at the log.
from pydantic_ai import Agent
from pydantic_ai_harness import WorkLog
from pydantic_ai_harness.work_log import FileWorkLogStore
agent = Agent('openai:gpt-6.1-sol', capabilities=[WorkLog(FileWorkLogStore('work-logs'))])
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
flowchart TB
accTitle: Work Log: keep every tool result where the model can read it again
accDescr: A tool's full result goes to WorkLog, which appends it to the conversation's log in its store before ToolOutputLimits reduces the copy the conversation keeps. After compaction has cleared that result from the conversation, the model searches the log with search_work_log and reads an entry with read_work_log, as tools or from code.
tool["tool call"]
log["WorkLog(store)<br/>search_work_log<br/>read_work_log"]:::capability
store[("work log store<br/>one log per conversation")]:::external
limits["ToolOutputLimits"]
model(["model"])
tool -->|"full result"| log
log <-->|"appends, reads"| store
log -->|"result"| limits
limits -->|"reduced result"| model
model <-->|"query or seq,<br/>entries"| log
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
A long run outgrows its context window, and compaction makes room by clearing old tool results or dropping old messages. The model then runs the same tool again to get back a result it already had. WorkLog writes each result to a store as the tool returns it, so the model can search for the entry it needs and read it in pages instead.
The log is written beside the conversation, not derived from it. It holds what the conversation never did: the full result before ToolOutputLimits reduced it, and the tool calls a Code Mode script made inside one run_code call.
Each entry is one tool call, one model reply, or one piece of model thinking:
- Tool calls that ran. The tool’s name and arguments (as JSON), the outcome, and the result as the model would see it: the return value, followed by a
ToolReturn’scontentwhen it has one. Text is stored as it is. Structured results are stored as indented JSON, one field per line, soread_work_logpages them by line andpatternmatches a field; a value holding something with no JSON form, such as a type, is stored as compact JSON with that part as itsrepr. Files are not logged: each becomes a[<media type> content not logged]line. - Failures. A
ModelRetryis logged with the outcomeretriedand the retry message. Any other exception is logged asfailed, with its type only, and is still raised; a tool wrapped byReportToolErrorsis logged asfailedwith the message it reports. A failure that an outer capability recovers from is logged once, assuccess, with the recovered result. A result that an outer capability’safter_tool_executerejects is logged twice: assuccess, then asretriedorfailedwith the rejection. - Native tool calls. A tool the provider ran, such as web search, with its arguments and the result its response holds, recorded when the response arrives. The outcome is
failedwhen the provider reported the call failed, elsesuccess. - Output tool calls. A call to an output tool, such as
final_result, with the output the model wrote as its content, once that output is final rather than a partial one from a stream. An output function’s return value goes to your application, not to the model, so it is not logged. - Model replies. Each text part of a response, with
record_text=True(the default). Thinking is logged only withrecord_thinking=True.search_work_log’s description tells the model which of the two the log holds, so it doesn’t read a reply missing from the log as one it never gave.
Not logged:
- a call that needs approval: it is logged when it runs after approval, and a denied call never runs;
- the result of an external call, which your application runs and passes back in
DeferredToolResults: no tool runs in the agent, so no entry is written; - a call whose arguments failed validation, since nothing ran and the model already got the retry prompt;
- calls to
search_work_logandread_work_logthemselves; - user prompts;
- anything in the history a run is given that this log didn’t record: history from another store or another process’s in-memory store, history built by hand, and calls made before
WorkLogwas added to the conversation.
Capabilities that run innermost, such as ToolGuardrail and PromptInjectionDefender, see a result before WorkLog does, so the log holds the result after they blocked or redacted it.
Every entry carries seq (its 1-based position in the log), kind (tool, text or thinking), tool_name, tool_call_id, parent_tool_call_id, args, outcome, content, chars (the content’s length), run_id, step, a UTC timestamp, and context: how many times ResetCompaction had cleared the conversation when it was recorded, 0 before the first. Each entry also has an idempotency key, so a hook that runs again, or a retried durable operation, writes it once.
A tool that dispatches others records them under its own call: a Code Mode script’s calls have run_code’s id as their parent_tool_call_id. ToolBridge’s tool_call runs the tool it names under its own id, so the two entries share a tool_call_id, and the named tool’s parent_tool_call_id is that same id.
WorkLog adds no instructions. The tool descriptions say what the log holds, and ResetCompaction’s notice points the model at it when the history was cleared.
search_work_log(query=None, tool_name=None, limit=10) finds entries:
- With a
query, only entries containing a query word are returned, ranked with BM25 over the tool name, arguments and content, the same ranking as Conversation Search: rare terms and exact words score higher. - Without one, it returns the most recent entries, newest first.
tool_namekeeps only entries for calls to that tool.
Entries hold full results, so ranking and excerpting run in a worker thread, off the event loop. A query over 1,000 characters or 32 unique terms goes back to the model to retry, and a search with a query scores only the newest max_scanned_entries entries that pass the filters (2,000 by default). The result’s unsearched_entries says how many older ones it skipped. A tool_name filter narrows the entries first, so it still reaches an older one. Raise max_scanned_entries to search further back; each search then takes longer.
Each match has the entry’s seq, context, kind and tool_name, its arguments clipped to about 200 characters, an excerpt of about 300 characters around the first query term the content contains, and chars, so the model can tell whether reading the entry takes more than one page. The result also has total_entries, the size of the whole log, unsearched_entries, and capped, set when matches were left out to keep the result under 50,000 characters.
read_work_log(seq, offset=0, limit=200, from_end=False, pattern=None, unit='lines') reads one entry: the call with its arguments in full and its outcome, plus a window of the content. It follows ToolOutputLimits’ read_tool_result:
patternis a literal substring, not a regex, and keeps only the lines that contain it;totalcounts those lines, or all lines without apattern.limitis clamped to 1,000 lines, and the returned text to 50,000 characters.cappedsays the character cap cut the text, keeping its start, or its end withfrom_end=True;next_offsetthen points at the first line not returned in full, passing over a line the cap cut.cut_atis the byte offset where the cut line’s missing part starts.unit='bytes'reads the content’s UTF-8 bytes instead, for output without useful line breaks such as minified JSON:offset,limit,next_offsetandtotalthen count bytes,limitis clamped to 50,000, andpatterncan’t be used.read_work_log(seq, unit='bytes', offset=cut_at, limit=50_000)returns the rest of a cut line.next_offsetis theoffsetthat reads on, orNonewhen the window reached the end (the start, withfrom_end=True).- An unknown
seq, a negativeoffsetor alimitbelow 1 asks the model to retry. For an unknownseq, the message points it atsearch_work_log, which lists each entry’sseq, rather than reading the whole log to count it.
Both tools return TypedDicts, so Code Mode shows their return types to the model, and a script can search and read the log in one run_code call. Both are exempt from ToolOutputLimits, as its own read_tool_result and grep_tool_result are: each result is already bounded, and a spilled one would need a second tool to read.
Both tools are 'redacted' for UI adapters: a client sees each call with its arguments, and a placeholder instead of its result. The log holds every tool’s result, including ones the adapter keeps from the client, such as a 'private' tool’s, and an entry does not carry the visibility of the tool it recorded. To show the results, set the tools’ visibility with PrepareTools.
The log is keyed by the run’s conversation_id, so a run continued from earlier history appends to the same log, and the model can find the work earlier runs of the conversation recorded in it. A run’s conversation_id is the explicit conversation_id= argument, else the most recent one on message_history, else a fresh one.
The log holds only what WorkLog recorded in this store. Continuing a conversation doesn’t copy its history into the log, so a call in message_history that the log never recorded (see “Not logged” above) has no entry. Before ResetCompaction clears calls, it checks the log for each of them, and its notice says when some are missing.
The value is trusted as given. UI adapters set it from client input, so in a multi-tenant application derive it on the server from the authenticated user, as for Conversation Search; see the threat model.
WorkLog takes its store as its first argument, with no default: the choice decides how long the log lasts and who can open it.
| Store | Where the log is | Handle a reset notice shows |
|---|---|---|
InMemoryWorkLogStore() | This process, until discard(conversation_id) or process exit | None: the agent reaches the log only through the tools |
FileWorkLogStore(directory) | One JSONL file per conversation, <directory>/<log>.jsonl, on the machine running the agent | The file’s absolute path |
WorkspaceWorkLogStore(workspace=None) | One file per entry under .pydantic-ai-harness/work-log/<log>/ in the run’s workspace | That directory, relative to the working directory; none with workspace= |
<log> is the conversation ID’s SHA-256 hex digest, never the ID itself, so no ID can name a path outside the store’s directory, and no two IDs share a log, even on a file system that ignores case.
- In memory. The log grows for as long as the process runs, so a long-lived server should call
discardwhen a conversation ends. TwoWorkLog(InMemoryWorkLogStore())s are one log stated twice (see Two of them). A reset notice names no handle for it: the agent reaches the log only through the tools. - File. The directory is created on the first write, readable by its owner only (
0700), and each file0600; an existing directory is made owner-only, and one that is a symlink or that another user owns is refused. The process reads a log’s file once, the first time it touches that log, to learn which entries it already holds, then keeps those keys in memory: a long-lived server should callforget(conversation_id)when a conversation ends, which drops them and leaves the file. A reset notice names the file’s absolute path. - Workspace. The working directory’s
.pydantic-ai-harness/holds a.gitignore, so the entries stay out of version control, and the agent’s own file and shell tools can open them. TheWorkspaceprotocol has no append, so each entry is its own file, named by itsseqand its key’s digest. A search tool that ignores.gitignorealso finds the copies of files the agent read that the entries hold, as they were when read. The store keeps only file names and keys in memory, untilforget(conversation_id)drops them: each search reads every entry file, which in a remote sandbox is one round trip per entry. A symlinked log directory or entry file raisesWorkspaceError. A run with no workspace fails at its start; passworkspace=a backend, such asLocalWorkspaceBackend('/var/work-logs'), to keep logs in a workspace of their own instead. The agent’s file and shell tools can’t reach a workspace passed asworkspace=, so a reset notice then names no handle, as for the in-memory store.FileSystem’s default read-only patterns cover.pydantic-ai-harness/, but the agent’s shell can still write there, so an entry read back from this store can hold what the agent wrote rather than what the tool returned.
Each store numbers entries in memory, one append at a time per log, so it supports one writer process per log. Nothing prunes the file and workspace logs; delete them when you no longer need them.
To keep the log elsewhere, implement WorkLogStore: append(log_id, record) returns the entry’s seq and writes nothing when the log already holds record['key']; read(log_id, start=1, stop=None) returns entries with start <= seq < stop, in order; locate(log_id) returns the handle a reset notice names, or None when the agent can’t open the log itself, synchronously and without I/O.
run_code is logged like any other tool: its args hold the code and its content the script’s output. Each tool call the script makes is logged as an entry of its own, with run_code’s call ID as its parent_tool_call_id. A nested call finishes before the script does, so it gets a lower seq than its run_code: seq follows the order calls finished, not the order they started.
With CodeMode(speculate=...), a call launched while the model is still writing the script runs its hooks when it launches, so it is logged under its provisional ID (<call id>__spec_<n>), which it keeps when the script adopts it. A launch the script never claims is cancelled: one still running is not logged, while one that had already finished stays in the log although the script never used its result.
WorkLog orders itself inside ToolOutputLimits, so it records a result before ToolOutputLimits reduces it: the conversation can hold a spill marker while the log keeps the whole result. Without ToolOutputLimits on the agent, this ordering has no effect.
The log’s writes and both tools run as durable operations of the capability’s id, 'work_log': append for each recorded entry, search and read for the tools, and count_unlogged for ResetCompaction’s check of the calls it clears. A replay reuses what was recorded. That records one operation per entry, so under Temporal each recorded tool call, reply or thought outside another durable unit runs as an activity of its own in the workflow history. An append made inside another durable unit runs inline in it, and the entry’s key keeps a retried unit from writing twice.
Keep the id fixed once a workflow is live. Each store numbers entries in the memory of the process that writes them, so two processes appending to one log give two entries the same seq. With one worker at a time, FileWorkLogStore and WorkspaceWorkLogStore keep the log across a worker restart, which the in-memory store loses. When a log’s operations can run on several workers at once, implement WorkLogStore over storage that assigns seq atomically, such as a database.
WorkLog declares the default id 'work_log'. Two WorkLogs on one agent that share it are one log stated twice: they become one when they agree, and the agent raises a UserError when it’s built if they differ.
WorkLog emits no spans of its own. Each search and read is a tool call, and the calls it records are tool calls and model requests, so core’s spans already cover them, with their content behind the usual instrumentation settings.
- Conversation Search searches the message history
StepPersistencesaved: user turns, replies, and tool results as the conversation held them.WorkLogkeeps its own record of tool calls with their full results, including the ones made inside Code Mode, and the model’s replies, but no user prompts. Use Conversation Search to recall what was said, andWorkLogto recall what tools returned. ResetCompactionclears the history down to the task and the latest step, and leaves a notice naming this log and its tools.- Tool Output Limits keeps one large result from filling the context; the log keeps that result whole.
- A search reads the conversation’s whole log on every call, so it gets slower as the log grows.
- The log holds files as they were when the tool read them. A later write is not reflected in an earlier entry. The log is for results that are expensive to get again and for what the model already did, not for a file’s current contents.
- Speculative calls keep their provisional IDs; the log does not map them to the IDs the script would have given them.
- It can’t be loaded from an agent spec: its store is an object. Build it in Python.
- Pydantic AI capabilities
- Compaction — the strategies that clear what this log keeps
- Tool Output Limits — reduce large tool results at the source
Bases: AbstractCapability[AgentDepsT]
Record every tool call with its full result, and model replies, in a log the model can search.
Each conversation has one log, keyed by its conversation_id, so a run continued from earlier
history appends to the same log. Tool results are recorded before ToolOutputLimits reduces
them. Calls made from CodeMode’s run_code are recorded too, each with run_code’s call id as
its parent_tool_call_id. The model reads the log with search_work_log and read_work_log,
as tools or from code:
from pydantic_ai import Agent
from pydantic_ai_harness.work_log import FileWorkLogStore, WorkLog
agent = Agent('openai:gpt-5', capabilities=[WorkLog(FileWorkLogStore('work-logs'))])
WorkLog adds no instructions: the tool descriptions say what the log holds.
Where the log is kept: an InMemoryWorkLogStore, which lasts as long as the process, a
FileWorkLogStore, a WorkspaceWorkLogStore, or your own WorkLogStore.
Type: WorkLogStore | WorkspaceWorkLogStore
Record the model’s text replies.
Type: bool Default: True
Record the model’s thinking.
Type: bool Default: False
How many of the newest matching entries one search with a query scores. Must be positive.
This bounds how long one search takes. When more entries match the filters, older ones are not
searched and the result’s unsearched_entries says how many. Raise it to search further back at
the cost of slower searches.
Type: int Default: DEFAULT_MAX_SCANNED_ENTRIES
Stable capability ID: durable execution names the log’s operations by it, and it is the id of the toolset
holding search_work_log and read_work_log.
Two WorkLogs sharing this id are one log stated twice when they agree, and an error when
they differ.
Type: str | None Default: 'work_log'
@classmethod
def combine(
cls,
capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]
Two under one id are one log stated twice; two that disagree raise rather than merge.
AbstractCapability[AgentDepsT]
@classmethod
def get_serialization_name(cls) -> str | None
Not spec-serializable: store is a live object, and a store’s spec form is not designed yet.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Fail the run at its start when the log belongs in the run’s workspace and none is attached.
def get_toolset() -> AgentToolset[AgentDepsT] | None
Provide search_work_log and read_work_log, each running through a durable operation.
AgentToolset[AgentDepsT] | None
@async
def after_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
result: Any,
) -> Any
Record a tool’s result as the model sees it, before an outer capability reduces it.
@async
def wrap_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
handler: WrapToolExecuteHandler,
) -> Any
Record a tool call that failed or asked for a retry, then re-raise.
Failures skip after_tool_execute, so they are recorded here. A deferral or a skipped call
has no result yet; its later execution is recorded.
@async
def after_model_request(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
response: ModelResponse,
) -> ModelResponse
Record the response’s native tool calls with their results, its text, and its thinking when record_thinking is set.
@async
def after_output_process(
ctx: RunContext[AgentDepsT],
*,
output_context: OutputContext,
output: Any,
) -> Any
Record an output tool’s call with the output the model wrote, once it is final rather than partial.
Not output: an output function’s return value goes to the application, never to the model, so it stays out
of a log the model can read.