MCPcopy Index your code
hub / github.com/openai/openai-agents-python / FileSession

Class FileSession

examples/memory/file_session.py:20–124  ·  view source on GitHub ↗

Persist session items to a JSON file on disk.

Source from the content-addressed store, hash-verified

18
19
20class FileSession(Session):
21 """Persist session items to a JSON file on disk."""
22
23 session_settings: SessionSettings | None = None
24
25 def __init__(self, *, dir: str | Path | None = None, session_id: str | None = None) -> None:
26 self._dir = Path(dir) if dir is not None else Path.cwd() / ".agents-sessions"
27 self.session_id = session_id or ""
28 # Ensure the directory exists up front so subsequent file operations do not race.
29 self._dir.mkdir(parents=True, exist_ok=True)
30
31 async def _ensure_session_id(self) -> str:
32 if not self.session_id:
33 timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
34 # Prefix with wall-clock time so recent sessions are easy to spot on disk.
35 self.session_id = f"{timestamp}-{uuid4().hex[:12]}"
36 await asyncio.to_thread(self._dir.mkdir, parents=True, exist_ok=True)
37 file_path = self._items_path(self.session_id)
38 if not file_path.exists():
39 await asyncio.to_thread(file_path.write_text, "[]", encoding="utf-8")
40 return self.session_id
41
42 async def get_session_id(self) -> str:
43 """Return the session id, creating one if needed."""
44 return await self._ensure_session_id()
45
46 async def get_items(self, limit: int | None = None) -> list[Any]:
47 session_id = await self._ensure_session_id()
48 items = await self._read_items(session_id)
49 if limit is not None and limit >= 0:
50 return items[-limit:]
51 return items
52
53 async def add_items(self, items: list[Any]) -> None:
54 if not items:
55 return
56 session_id = await self._ensure_session_id()
57 current = await self._read_items(session_id)
58 # Deep-copy via JSON to avoid persisting live references that might mutate later.
59 cloned = json.loads(json.dumps(items))
60 await self._write_items(session_id, current + cloned)
61
62 async def pop_item(self) -> Any | None:
63 session_id = await self._ensure_session_id()
64 items = await self._read_items(session_id)
65 if not items:
66 return None
67 popped = items.pop()
68 await self._write_items(session_id, items)
69 return popped
70
71 async def clear_session(self) -> None:
72 if not self.session_id:
73 return
74 file_path = self._items_path(self.session_id)
75 state_path = self._state_path(self.session_id)
76 try:
77 await asyncio.to_thread(file_path.unlink)

Callers 2

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected