Skip to content

Commit 988632a

Browse files
committed
Integrates temporary file cleanup into state graph
Adds a new node to the state graph that proactively removes old audio and video files from temporary directories before processing a new agent request. This prevents the accumulation of unused files and helps manage disk space. Also updates the memory update call to pass relevant messages and user ID, ensuring comprehensive context is stored for the conversation.
1 parent ca536f2 commit 988632a

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/chattr/app/builder.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,22 @@ def _setup_graph(cls) -> CompiledStateGraph:
100100
CompiledStateGraph: The compiled state graph is ready for execution.
101101
"""
102102

103+
def _clean_old_files(state: State) -> State:
104+
"""Clean up temporary old audio and video files."""
105+
if any(cls.settings.directory.audio.iterdir()):
106+
for file in cls.settings.directory.audio.iterdir():
107+
try:
108+
file.unlink()
109+
except OSError as e:
110+
logger.error(f"Failed to delete audio file {file}: {e}")
111+
if any(cls.settings.directory.video.iterdir()):
112+
for file in cls.settings.directory.video.iterdir():
113+
try:
114+
file.unlink()
115+
except OSError as e:
116+
logger.error(f"Failed to delete video file {file}: {e}")
117+
return state
118+
103119
async def _call_model(state: State) -> State:
104120
"""
105121
Generate a model response based on the current state and user memory.
@@ -123,17 +139,19 @@ async def _call_model(state: State) -> State:
123139
memory = cls._retrieve_memory(messages, user_id)
124140
system_messages = cls._setup_prompt(memory)
125141
response = await cls._model.ainvoke([*system_messages, *messages])
126-
cls._update_memory()
142+
cls._update_memory(messages, response, user_id)
127143
except Exception as e:
128144
_msg = f"Error in chatbot: {e}"
129145
logger.error(_msg)
130146
raise Error(_msg) from e
131147
return State(messages=[response], mem0_user_id=user_id)
132148

133149
graph_builder: StateGraph = StateGraph(State)
150+
graph_builder.add_node("clean_old_files", _clean_old_files)
134151
graph_builder.add_node("agent", _call_model)
135152
graph_builder.add_node("tools", ToolNode(cls._tools))
136-
graph_builder.add_edge(START, "agent")
153+
graph_builder.add_edge(START, "clean_old_files")
154+
graph_builder.add_edge("clean_old_files", "agent")
137155
graph_builder.add_conditional_edges("agent", tools_condition)
138156
graph_builder.add_edge("tools", "agent")
139157
return graph_builder.compile(debug=True)

0 commit comments

Comments
 (0)