Créer un bot de support IA pour votre boutique en ligne
Bot de support en Python : code source
Python
1"""Short per-chat conversation history, kept in memory."""23from __future__ import annotations45import threading6from collections import deque7from typing import Literal, TypedDict8910class ChatTurn(TypedDict):11 role: Literal["user", "assistant"]12 content: str131415class ConversationMemory:16 """Keeps the last `max_messages` user/assistant messages of each chat.1718 Tool calls and tool results are not stored: the next turn starts from plain text,19 which keeps prompts small and avoids replaying stale order or stock data.20 """2122 def __init__(self, max_messages: int, max_chats: int = 10_000) -> None:23 if max_messages < 2:24 raise ValueError("max_messages must be at least 2")25 self._max_messages = max_messages26 self._max_chats = max_chats27 self._chats: dict[int, deque[ChatTurn]] = {}28 self._lock = threading.Lock()2930 def history(self, chat_id: int) -> list[ChatTurn]:31 with self._lock:32 return list(self._chats.get(chat_id, ()))3334 def add_exchange(self, chat_id: int, user_text: str, assistant_text: str) -> None:35 with self._lock:36 turns = self._chats.pop(chat_id, None) or deque(maxlen=self._max_messages)37 turns.append({"role": "user", "content": user_text})38 turns.append({"role": "assistant", "content": assistant_text})39 # Re-insert so the dict stays ordered from least to most recently used.40 self._chats[chat_id] = turns41 while len(self._chats) > self._max_chats:42 self._chats.pop(next(iter(self._chats)))4344 def clear(self, chat_id: int) -> None:45 with self._lock:46 self._chats.pop(chat_id, None)