anymerge 0.1.0 merges dataclasses, TypedDicts and Pydantic models with reducers declared in type annotations
, 5 min read, on python, open-source, 1 star
A Python library for merging dataclasses, TypedDicts, and Pydantic models seamlessly
In late 2024 I was building long-running AI agents at work, as part of a pipeline that parsed legal documents. Each step of a run changed the agent's state a little, and the code that merged those changes ended up spread across the codebase. To see how one field got updated, you had to find every place that touched it. anymerge puts that logic in one place: the model definition. I made the first commit of anymerge on Christmas Day 2024.
Today I released anymerge 0.1.0. It's a small Python library that merges dataclasses, TypedDicts and Pydantic models field by field. You write the merge rule in each field's type annotation, and merge returns a new instance.
A lot of programs keep some state and update it in steps: a job runner, a chat session, an agent loop, a report built from several sources. Each step returns a few changes, and you fold them into the state.
Each field needs its own rule. A status should take the new value. A counter should add up. A log should grow. In a list of records, an update should replace the matching item instead of appending a duplicate.
The usual answer is a function that knows every field:
def apply(state: State, update: dict) -> State:
return State(
status=update.get("status", state.status),
total=state.total + update.get("total", 0),
log=state.log + update.get("log", []),
)This is fine for three fields. As the model grows, every new field needs another line here, and it's easy to forget one.
anymerge moves the rule next to the field, with typing.Annotated:
import dataclasses
import operator
from typing import Annotated
from anymerge import Reducer, merge
@dataclasses.dataclass
class State:
status: str
total: Annotated[int, Reducer(operator.add)] = 0
log: Annotated[list[str], Reducer(operator.add)] = dataclasses.field(default_factory=list)
state = State(status="pending")
state = merge(state, {"status": "running", "total": 3, "log": ["started"]})
state = merge(state, {"total": 2, "log": ["finished"]})
print(state)
#> State(status='running', total=5, log=['started', 'finished'])status has no reducer, so it takes the new value. total and log are combined with operator.add.
A reducer is any function that takes the old value and the new one. operator.add, operator.or_ and max all work, and so does your own function. The update can be a dict or another model. A dict only changes the keys it has. A Pydantic model only changes the fields that were set explicitly, so its defaults don't overwrite your data.
Reducer() with no function on a nested model field merges that model field by field, using its own reducers. Without it, the nested model is replaced whole.merge_by_key("id") handles lists of records. It replaces items with a matching key and appends new ones, and Remove(key) deletes one.Overwrite(value) sets a field and skips its reducer. I use it when a person corrects the state by hand.reduce(state, updates) applies a sequence of updates in order.merge and reduce return the type of the model you pass in, so type checkers follow along.I work on AI agents, and agent state is where I keep reaching for this. An agent run makes many model calls, and each one reports its own token usage. Put the counts in a nested model and add them up:
import operator
from typing import Annotated
from anymerge import Reducer, reduce
from pydantic import BaseModel
class Usage(BaseModel):
requests: Annotated[int, Reducer(operator.add)] = 0
input_tokens: Annotated[int, Reducer(operator.add)] = 0
output_tokens: Annotated[int, Reducer(operator.add)] = 0
class State(BaseModel):
answer: str = ""
usage: Annotated[Usage, Reducer()] = Usage()
calls = [
{"usage": Usage(requests=1, input_tokens=1200, output_tokens=80)},
{"usage": Usage(requests=1, input_tokens=1350, output_tokens=40)},
{"answer": "42", "usage": Usage(requests=1, input_tokens=1400, output_tokens=12)},
]
print(reduce(State(), calls))
#> answer='42' usage=Usage(requests=3, input_tokens=3950, output_tokens=132)The same approach works for sub-agents that run in parallel. Each one returns an update instead of writing to shared state, and you merge the updates once they've all finished. You don't need a lock, and one branch never sees another's half-finished writes.
The AI applications section of the docs has more recipes, including message history, streamed LLM responses and eval results split across shards.
model_copy(update=...) replaces each field you pass. It can't add to the old value, and it replaces a nested model whole.Annotated[list, operator.add] pattern for its graph state, and had it well before 1.0. When I started anymerge, LangGraph was at 0.2. Its reducers run when a LangGraph graph applies a node's update. anymerge works on any dataclass, TypedDict or Pydantic model, with or without a framework.model_copy, which doesn't validate. Call model_validate on the result if you need it checked.merge ignores keys in an update that the model doesn't have, without a warning, so a misspelled key changes nothing. There's no strict mode yet.pip install anymerge
pip install "anymerge[pydantic]" # for Pydantic modelsIt needs Python 3.11 or later, and the only required dependency is typing-extensions. It's MIT licensed.
If you keep typed state and update it in steps, I'd like to hear where the field-level approach doesn't fit and which reducers you'd want built in. Start a discussion and tell me.
A Python library for merging dataclasses, TypedDicts, and Pydantic models seamlessly