core.memory
Memory vector recall: semantic search over PermanentHistory turns.
Tier 1 primitives:
TurnHit— ranked result returned by search.Entry— storage tuple yielded byTurnVectorStore.iter_entries.TurnVectorStore— in-memory append-only vector store with cosine-similarity search.
L2 adds:
Memory— facade combining anEmbeddingsbackend with aTurnVectorStorefor high-levelindex_turn/search/reindexoperations.
L3 adds:
persist_store()/load_store()— Parquet persistence for the in-memory store.
Memory vector recall: semantic search over PermanentHistory turns.
Tier 1 primitives:
TurnHit— ranked result returned by search.Entry— storage tuple yielded byTurnVectorStore.iter_entries.TurnVectorStore— in-memory append-only vector store with cosine-similarity search.
L2 adds:
Memory— facade combining anEmbeddingsbackend with aTurnVectorStorefor high-levelindex_turn/search/reindexoperations.
L3 adds:
persist_store()/load_store()— Parquet persistence for the in-memory store.
- class Entry(text, embedding, turn, metadata)[source]
Bases:
NamedTupleStorage tuple yielded by
TurnVectorStore.iter_entries.Fields mirror what was passed to
add()at index time. Used byMemory.reindex()(L2) andpersist_store()(L3) to read the store’s full contents without reaching into private state.
- class Memory(embeddings, store=None)[source]
Bases:
objectSemantic recall over completed conversation turns.
Wraps an
EmbeddingBackendand aTurnVectorStore. Provides two indexing entry points:index_turn()/aindex_turn()— extract text from a structuredturndict viaturn["content"][0]["text"].index_turn_text()/aindex_turn_text()— embed an arbitrary caller-supplied string while still storing the structuredturndict alongside. Used byHistoryRecorder(L4) to embed the Q+A pair (f"{prompt}\n{response}") rather than just the response.
- Parameters:
embeddings (EmbeddingBackend) – Embedding backend (LiteLLM API model or local
local/...model). Any object implementingEmbeddingBackendis accepted.store (TurnVectorStore | None) – Optional
TurnVectorStore. Defaults to a fresh instance. Public and settable so callers can swap in a store loaded from Parquet (L3).
- index_turn_text(text, turn, metadata=None)[source]
Embed an arbitrary
textand store the structuredturn.Use this when the embedded text differs from
turn["content"][0]["text"]— e.g., when embedding the Q+A pair (f"{prompt}\n{response}") while still storing the response as the canonical turn content.
- async aindex_turn(turn, metadata=None)[source]
Async variant of
index_turn().
- async aindex_turn_text(text, turn, metadata=None)[source]
Async variant of
index_turn_text().
- reindex(new_embeddings)[source]
Re-embed all stored texts with a new embedding model.
Reads all entries via
TurnVectorStore.iter_entries(), clears the store, and re-adds each entry with the new embedding. The turn dicts and metadata are preserved verbatim. After reindexing,self._embeddingsis updated so subsequentsearch()calls embed queries with the new model.- Parameters:
new_embeddings (EmbeddingBackend) – The new embedding backend to use.
- Return type:
None
- class TurnHit(score, turn, turn_index, text, metadata)[source]
Bases:
objectA single ranked result returned by
TurnVectorStore.search.- Parameters:
- score
Cosine similarity in
[-1.0, 1.0]between the query embedding and the stored turn’s embedding. Sorted descending bysearch().- Type:
- turn
The raw turn dict stored at index time. Mirrors the
PermanentHistoryturn shape:{"role": str, "content": [{"type": "text", "text": str}], "timestamp": float, "metadata": dict}.
- turn_index
Position of the entry in
TurnVectorStoreat the time of the search. Stable within a singlesearch()call for a given store; may shift afterclear().- Type:
- text
Pre-extracted plain text (typically the Q+A pair) that was embedded. Equal to the string passed to
add(text=...).- Type:
- metadata
Caller-provided metadata attached at index time. Always present (possibly empty dict). Tier 2 will populate
user_id/session_id/agent_idhere.
- class TurnVectorStore[source]
Bases:
objectAppend-only in-memory store of embedded turns with cosine search.
Entries are stored in four parallel lists keyed by an integer index.
add()returns the index of the appended entry; that index is preserved on the correspondingTurnHitreturned bysearch().Search is O(N) over all stored entries. Adequate for Tier 1 scale; a vector-index backend (Chroma/Qdrant) is a future concern.
- add(text, embedding, turn, metadata=None)[source]
Append an entry and return its integer index.
- Parameters:
- Returns:
The integer index of the newly appended entry.
- Return type:
- search(query_embedding, top_k=5, threshold=None)[source]
Return up to
top_kturns ranked by cosine similarity.- Parameters:
- Returns:
Hits sorted by
scoredescending. Empty list if the store is empty or all hits fall belowthreshold.- Return type:
- cosine_similarity(a, b)[source]
Cosine similarity between two equal-length float vectors.
Thin wrapper around
Embeddings.cosine_similarity()so thatturn_storeconsumers don’t need to import theEmbeddingsclass just to compute similarity. Returns0.0when either vector has zero magnitude.
- load_store(path)[source]
Load a Parquet file written by
persist_store()into a fresh store.- Parameters:
path (str) – Source file path.
- Returns:
A new
TurnVectorStorewhose entries and ordering match what was persisted.- Raises:
FileNotFoundError – If path does not exist.
ValueError – If the file’s
_schema_versionis not1.
- Return type:
- persist_store(store, path)[source]
Write all entries in store to a Parquet file at path.
Overwrites any existing file. Empty stores produce a valid zero-row Parquet file.
- Parameters:
store (TurnVectorStore) – The
TurnVectorStoreto serialize.path (str) – Destination file path. Parent directories are created.
- Return type:
None
Classes
- class Entry(text, embedding, turn, metadata)[source]
Bases:
NamedTupleStorage tuple yielded by
TurnVectorStore.iter_entries.Fields mirror what was passed to
add()at index time. Used byMemory.reindex()(L2) andpersist_store()(L3) to read the store’s full contents without reaching into private state.- count(value, /)
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- class Memory(embeddings, store=None)[source]
Bases:
objectSemantic recall over completed conversation turns.
Wraps an
EmbeddingBackendand aTurnVectorStore. Provides two indexing entry points:index_turn()/aindex_turn()— extract text from a structuredturndict viaturn["content"][0]["text"].index_turn_text()/aindex_turn_text()— embed an arbitrary caller-supplied string while still storing the structuredturndict alongside. Used byHistoryRecorder(L4) to embed the Q+A pair (f"{prompt}\n{response}") rather than just the response.
- Parameters:
embeddings (EmbeddingBackend) – Embedding backend (LiteLLM API model or local
local/...model). Any object implementingEmbeddingBackendis accepted.store (TurnVectorStore | None) – Optional
TurnVectorStore. Defaults to a fresh instance. Public and settable so callers can swap in a store loaded from Parquet (L3).
- index_turn_text(text, turn, metadata=None)[source]
Embed an arbitrary
textand store the structuredturn.Use this when the embedded text differs from
turn["content"][0]["text"]— e.g., when embedding the Q+A pair (f"{prompt}\n{response}") while still storing the response as the canonical turn content.
- async aindex_turn(turn, metadata=None)[source]
Async variant of
index_turn().
- async aindex_turn_text(text, turn, metadata=None)[source]
Async variant of
index_turn_text().
- reindex(new_embeddings)[source]
Re-embed all stored texts with a new embedding model.
Reads all entries via
TurnVectorStore.iter_entries(), clears the store, and re-adds each entry with the new embedding. The turn dicts and metadata are preserved verbatim. After reindexing,self._embeddingsis updated so subsequentsearch()calls embed queries with the new model.- Parameters:
new_embeddings (EmbeddingBackend) – The new embedding backend to use.
- Return type:
None
- class TurnHit(score, turn, turn_index, text, metadata)[source]
Bases:
objectA single ranked result returned by
TurnVectorStore.search.- Parameters:
- score
Cosine similarity in
[-1.0, 1.0]between the query embedding and the stored turn’s embedding. Sorted descending bysearch().- Type:
- turn
The raw turn dict stored at index time. Mirrors the
PermanentHistoryturn shape:{"role": str, "content": [{"type": "text", "text": str}], "timestamp": float, "metadata": dict}.
- turn_index
Position of the entry in
TurnVectorStoreat the time of the search. Stable within a singlesearch()call for a given store; may shift afterclear().- Type:
- text
Pre-extracted plain text (typically the Q+A pair) that was embedded. Equal to the string passed to
add(text=...).- Type:
- metadata
Caller-provided metadata attached at index time. Always present (possibly empty dict). Tier 2 will populate
user_id/session_id/agent_idhere.
- class TurnVectorStore[source]
Bases:
objectAppend-only in-memory store of embedded turns with cosine search.
Entries are stored in four parallel lists keyed by an integer index.
add()returns the index of the appended entry; that index is preserved on the correspondingTurnHitreturned bysearch().Search is O(N) over all stored entries. Adequate for Tier 1 scale; a vector-index backend (Chroma/Qdrant) is a future concern.
- add(text, embedding, turn, metadata=None)[source]
Append an entry and return its integer index.
- Parameters:
- Returns:
The integer index of the newly appended entry.
- Return type:
- search(query_embedding, top_k=5, threshold=None)[source]
Return up to
top_kturns ranked by cosine similarity.- Parameters:
- Returns:
Hits sorted by
scoredescending. Empty list if the store is empty or all hits fall belowthreshold.- Return type:
Functions
- cosine_similarity(a, b)[source]
Cosine similarity between two equal-length float vectors.
Thin wrapper around
Embeddings.cosine_similarity()so thatturn_storeconsumers don’t need to import theEmbeddingsclass just to compute similarity. Returns0.0when either vector has zero magnitude.
- load_store(path)[source]
Load a Parquet file written by
persist_store()into a fresh store.- Parameters:
path (str) – Source file path.
- Returns:
A new
TurnVectorStorewhose entries and ordering match what was persisted.- Raises:
FileNotFoundError – If path does not exist.
ValueError – If the file’s
_schema_versionis not1.
- Return type:
- persist_store(store, path)[source]
Write all entries in store to a Parquet file at path.
Overwrites any existing file. Empty stores produce a valid zero-row Parquet file.
- Parameters:
store (TurnVectorStore) – The
TurnVectorStoreto serialize.path (str) – Destination file path. Parent directories are created.
- Return type:
None