File size: 8,488 Bytes
bb3ee41
 
 
 
 
 
bfe0e24
bb3ee41
 
 
 
 
bfe0e24
 
 
 
 
bb3ee41
 
 
 
 
 
bfe0e24
 
bb3ee41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfe0e24
bb3ee41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfe0e24
bb3ee41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfe0e24
bb3ee41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""Working memory for reasoning and scratch space with LRU eviction."""

from __future__ import annotations

import asyncio
from collections import OrderedDict
from datetime import datetime, timezone
from typing import Any

from pydantic import BaseModel, Field


def _utc_now() -> datetime:
    """Return current UTC datetime."""
    return datetime.now(timezone.utc)


class WorkingMemoryItem(BaseModel):
    """A single item in working memory."""

    id: str
    content: Any
    priority: float = 0.0
    created_at: datetime = Field(default_factory=_utc_now)
    last_accessed: datetime = Field(default_factory=_utc_now)
    access_count: int = 0
    metadata: dict[str, Any] = Field(default_factory=dict)

    model_config = {"arbitrary_types_allowed": True}


class WorkingMemory:
    """
    Working memory for reasoning and scratch computations.

    This memory layer provides a limited-capacity buffer with LRU (Least Recently Used)
    eviction policy. It's designed for temporary reasoning steps, intermediate results,
    and scratch space during agent deliberation.

    Attributes:
        capacity: Maximum number of items in working memory.
        _items: Internal LRU-ordered storage.
    """

    def __init__(self, capacity: int = 20) -> None:
        """
        Initialize working memory.

        Args:
            capacity: Maximum number of items to store. Defaults to 20.
        """
        self.capacity = capacity
        self._items: OrderedDict[str, WorkingMemoryItem] = OrderedDict()
        self._counter = 0
        self._lock = asyncio.Lock()

    @property
    def size(self) -> int:
        """Get current number of items in memory."""
        return len(self._items)

    @property
    def is_full(self) -> bool:
        """Check if memory is at capacity."""
        return len(self._items) >= self.capacity

    async def push(
        self,
        content: Any,
        item_id: str | None = None,
        priority: float = 0.0,
        metadata: dict[str, Any] | None = None,
    ) -> WorkingMemoryItem:
        """
        Push a new item into working memory.

        If capacity is reached, the least recently used item is evicted.

        Args:
            content: The content to store.
            item_id: Optional custom ID. Auto-generated if not provided.
            priority: Priority score for potential prioritized eviction.
            metadata: Optional metadata dictionary.

        Returns:
            The created working memory item.
        """
        async with self._lock:
            # Generate ID if not provided
            if item_id is None:
                self._counter += 1
                item_id = f"wm_{self._counter}"

            now = datetime.now(timezone.utc)

            # Check if item already exists (update it)
            if item_id in self._items:
                item = self._items[item_id]
                item.content = content
                item.last_accessed = now
                item.access_count += 1
                if metadata:
                    item.metadata.update(metadata)
                if priority != 0.0:
                    item.priority = priority
                # Move to end (most recent)
                self._items.move_to_end(item_id)
                return item

            # Evict LRU item if at capacity
            if len(self._items) >= self.capacity:
                self._evict_lru()

            # Create new item
            item = WorkingMemoryItem(
                id=item_id,
                content=content,
                priority=priority,
                created_at=now,
                last_accessed=now,
                metadata=metadata or {},
            )
            self._items[item_id] = item
            return item

    def _evict_lru(self) -> WorkingMemoryItem | None:
        """
        Evict the least recently used item.

        Returns:
            The evicted item, or None if memory was empty.
        """
        if not self._items:
            return None
        # Pop first item (least recently used)
        _, item = self._items.popitem(last=False)
        return item

    async def pop(self) -> WorkingMemoryItem | None:
        """
        Remove and return the most recently used item.

        Returns:
            The most recent item, or None if memory is empty.
        """
        async with self._lock:
            if not self._items:
                return None
            _, item = self._items.popitem(last=True)
            return item

    async def pop_by_id(self, item_id: str) -> WorkingMemoryItem | None:
        """
        Remove and return an item by its ID.

        Args:
            item_id: The ID of the item to remove.

        Returns:
            The removed item, or None if not found.
        """
        async with self._lock:
            return self._items.pop(item_id, None)

    async def peek(self) -> WorkingMemoryItem | None:
        """
        Return the most recently used item without removing it.

        Returns:
            The most recent item, or None if memory is empty.
        """
        async with self._lock:
            if not self._items:
                return None
            # Get last item
            item_id = next(reversed(self._items))
            item = self._items[item_id]
            item.last_accessed = datetime.now(timezone.utc)
            item.access_count += 1
            return item

    async def peek_by_id(self, item_id: str) -> WorkingMemoryItem | None:
        """
        Return an item by ID without removing it.

        Args:
            item_id: The ID of the item to peek.

        Returns:
            The item, or None if not found.
        """
        async with self._lock:
            item = self._items.get(item_id)
            if item:
                item.last_accessed = datetime.now(timezone.utc)
                item.access_count += 1
                # Move to end (mark as recently accessed)
                self._items.move_to_end(item_id)
            return item

    async def get_all(self) -> list[WorkingMemoryItem]:
        """
        Get all items in memory, ordered by recency.

        Returns:
            List of items from least to most recent.
        """
        async with self._lock:
            return list(self._items.values())

    async def get_recent(self, n: int = 5) -> list[WorkingMemoryItem]:
        """
        Get the N most recently accessed items.

        Args:
            n: Number of items to return.

        Returns:
            List of most recent items.
        """
        async with self._lock:
            items = list(self._items.values())
            return items[-n:] if n < len(items) else items

    async def clear(self) -> int:
        """
        Clear all items from working memory.

        Returns:
            Number of items that were cleared.
        """
        async with self._lock:
            count = len(self._items)
            self._items.clear()
            self._counter = 0
            return count

    async def search(self, predicate: Any) -> list[WorkingMemoryItem]:
        """
        Search items using a predicate function.

        Args:
            predicate: Callable that takes a WorkingMemoryItem and returns bool.

        Returns:
            List of matching items.
        """
        async with self._lock:
            return [item for item in self._items.values() if predicate(item)]

    async def update_priority(self, item_id: str, priority: float) -> bool:
        """
        Update the priority of an item.

        Args:
            item_id: ID of the item to update.
            priority: New priority value.

        Returns:
            True if item was found and updated, False otherwise.
        """
        async with self._lock:
            if item_id in self._items:
                self._items[item_id].priority = priority
                return True
            return False

    async def get_stats(self) -> dict[str, Any]:
        """
        Get statistics about working memory.

        Returns:
            Dictionary with memory statistics.
        """
        async with self._lock:
            return {
                "size": len(self._items),
                "capacity": self.capacity,
                "is_full": len(self._items) >= self.capacity,
                "utilization": len(self._items) / self.capacity if self.capacity > 0 else 0,
                "item_ids": list(self._items.keys()),
            }