Skip to content

Commit 8a4b83c

Browse files
committed
feat: filter chat history entries by valid roles and log invalid ones
1 parent 4e511f2 commit 8a4b83c

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

utils/ai.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,19 @@ def use_session(self, id: int, history: list[Content] | None = None) -> AsyncCha
8484
chat = self._chats.get(id)
8585
if not chat:
8686
if history:
87-
history = [
88-
Content(**content) if not isinstance(content, Content) else content
89-
for content in history
90-
] # Sanitize history to ensure correct dumping in dump_history()
87+
# Filter history to only include valid roles (user, model)
88+
valid_history = []
89+
for content in history:
90+
# Get the role from dict or Content object
91+
role = content.get("role") if isinstance(content, dict) else getattr(content, "role", None)
92+
# Only include entries with valid roles
93+
if role in ("user", "model"):
94+
valid_history.append(
95+
Content(**content) if not isinstance(content, Content) else content
96+
)
97+
else:
98+
log.warning(f"Skipping history entry with invalid role: {role}")
99+
history = valid_history
91100
chat = self._client.aio.chats.create(model=self.model_name, history=history) # type: ignore
92101
self._chats[id] = chat
93102
self._current_chat_id = id

0 commit comments

Comments
 (0)