File size: 1,050 Bytes
f440f03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Aģenta atmiņa — saglabā pieredzi."""

from __future__ import annotations

import json
import logging
from collections import deque
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)


class AgentMemory:
    """Vienkārša aģenta atmiņa ar ierakstu vēsturi."""

    def __init__(self, max_size: int = 100) -> None:
        self._buffer: deque[dict[str, Any]] = deque(maxlen=max_size)

    def add(self, entry: dict[str, Any]) -> None:
        self._buffer.append(entry)

    def get_recent(self, n: int = 10) -> list[dict[str, Any]]:
        return list(self._buffer)[-n:]

    def save(self, path: str | Path) -> None:
        with open(path, "w") as f:
            json.dump(list(self._buffer), f, indent=2)

    def load(self, path: str | Path) -> None:
        try:
            with open(path) as f:
                data = json.load(f)
            self._buffer = deque(data, maxlen=self._buffer.maxlen)
        except FileNotFoundError:
            logger.info("Atmiņas fails nav atrasts: %s", path)