Skip to content

Commit

Permalink
Update autogen_core.memory: adding docs, removing some fields. (#5053)
Browse files Browse the repository at this point in the history
* Update autogen_core.memory: adding docs, removing some fields.

* Remove timestamp

* Remove name from base; fix example code

* fix test

* lint

* fix doc
  • Loading branch information
ekzhu authored Jan 15, 2025
1 parent abbdbb2 commit 6954e51
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 32 deletions.
1 change: 1 addition & 0 deletions python/packages/autogen-core/docs/src/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ python/autogen_core.models
python/autogen_core.model_context
python/autogen_core.tools
python/autogen_core.tool_agent
python/autogen_core.memory
python/autogen_core.exceptions
python/autogen_core.logging
```
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
autogen\_core.memory
====================


.. automodule:: autogen_core.memory
:members:
:undoc-members:
:show-inheritance:
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Protocol, Union, runtime_checkable

Expand All @@ -23,32 +22,47 @@ class MemoryMimeType(Enum):


class MemoryContent(BaseModel):
"""A memory content item."""

content: ContentType
"""The content of the memory item. It can be a string, bytes, dict, or :class:`~autogen_core.Image`."""

mime_type: MemoryMimeType | str
"""The MIME type of the memory content."""

metadata: Dict[str, Any] | None = None
timestamp: datetime | None = None
source: str | None = None
score: float | None = None
"""Metadata associated with the memory item."""

model_config = ConfigDict(arbitrary_types_allowed=True)


class MemoryQueryResult(BaseModel):
"""Result of a memory :meth:`~autogen_core.memory.Memory.query` operation."""

results: List[MemoryContent]


class UpdateContextResult(BaseModel):
"""Result of a memory :meth:`~autogen_core.memory.Memory.update_context` operation."""

memories: MemoryQueryResult


@runtime_checkable
class Memory(Protocol):
"""Protocol defining the interface for memory implementations."""
"""Protocol defining the interface for memory implementations.
@property
def name(self) -> str | None:
"""The name of this memory implementation."""
...
A memory is the storage for data that can be used to enrich or modify the model context.
A memory implementation can use any storage mechanism, such as a list, a database, or a file system.
It can also use any retrieval mechanism, such as vector search or text search.
It is up to the implementation to decide how to store and retrieve data.
It is also a memory implementation's responsibility to update the model context
with relevant memory content based on the current model context and querying the memory store.
See :class:`~autogen_core.memory.ListMemory` for an example implementation.
"""

async def update_context(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,43 @@ class ListMemory(Memory):
allowing external applications to manage memory contents directly.
Example:
.. code-block:: python
# Initialize memory
memory = ListMemory(name="chat_history")
# Add memory content
content = MemoryContent(content="User prefers formal language")
await memory.add(content)
.. code-block:: python
# Directly modify memory contents
memory.content = [MemoryContent(content="New preference")]
import asyncio
from autogen_core.memory import ListMemory, MemoryContent
from autogen_core.model_context import BufferedChatCompletionContext
# Update a model context with memory
memory_contents = await memory.update_context(model_context)
async def main() -> None:
# Initialize memory
memory = ListMemory(name="chat_history")
# Add memory content
content = MemoryContent(content="User prefers formal language", mime_type="text/plain")
await memory.add(content)
# Directly modify memory contents
memory.content = [MemoryContent(content="New preference", mime_type="text/plain")]
# Create a model context
model_context = BufferedChatCompletionContext(buffer_size=10)
# Update a model context with memory
await memory.update_context(model_context)
# See the updated model context
print(await model_context.get_messages())
asyncio.run(main())
Args:
name: Optional identifier for this memory instance
Attributes:
name (str): Identifier for this memory instance
content (List[MemoryContent]): Direct access to memory contents
"""

def __init__(self, name: str | None = None) -> None:
"""Initialize ListMemory.
Args:
name: Optional identifier for this memory instance
"""
self._name = name or "default_list_memory"
self._contents: List[MemoryContent] = []

Expand Down
7 changes: 2 additions & 5 deletions python/packages/autogen-core/tests/test_memory.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from datetime import datetime

import pytest
from autogen_core import CancellationToken
from autogen_core.memory import (
Expand All @@ -16,7 +14,6 @@
def test_memory_protocol_attributes() -> None:
"""Test that Memory protocol has all required attributes."""
# No changes needed here
assert hasattr(Memory, "name")
assert hasattr(Memory, "update_context")
assert hasattr(Memory, "query")
assert hasattr(Memory, "add")
Expand Down Expand Up @@ -76,8 +73,8 @@ async def test_list_memory_add_and_query() -> None:
"""Test adding and querying memory contents."""
memory = ListMemory()

content1 = MemoryContent(content="test1", mime_type=MemoryMimeType.TEXT, timestamp=datetime.now())
content2 = MemoryContent(content={"key": "value"}, mime_type=MemoryMimeType.JSON, timestamp=datetime.now())
content1 = MemoryContent(content="test1", mime_type=MemoryMimeType.TEXT)
content2 = MemoryContent(content={"key": "value"}, mime_type=MemoryMimeType.JSON)

await memory.add(content1)
await memory.add(content2)
Expand Down

0 comments on commit 6954e51

Please sign in to comment.