Upload 3 files (#1)
Browse files- Upload 3 files (9bdf06b946387d892b1fc36cb79f21a88e0c00cd)
Co-authored-by: Gabriel Silva Rodrigues <Restodecoca@users.noreply.huggingface.co>
- chatbot_server.py +140 -133
- mysqlchatstore.py +278 -0
- requirements.txt +13 -11
chatbot_server.py
CHANGED
|
@@ -1,133 +1,140 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import logging
|
| 3 |
-
import sys
|
| 4 |
-
|
| 5 |
-
from flask import Flask, request, jsonify, Response
|
| 6 |
-
# Inicializa o Flask
|
| 7 |
-
app = Flask(__name__)
|
| 8 |
-
|
| 9 |
-
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
| 10 |
-
|
| 11 |
-
from llama_index.llms.openai import OpenAI
|
| 12 |
-
from llama_index.embeddings.openai import OpenAIEmbedding
|
| 13 |
-
from llama_index.core import (
|
| 14 |
-
Settings,
|
| 15 |
-
SimpleDirectoryReader,
|
| 16 |
-
StorageContext,
|
| 17 |
-
Document,
|
| 18 |
-
)
|
| 19 |
-
|
| 20 |
-
Settings.llm = OpenAI(model="gpt-3.5-turbo")
|
| 21 |
-
Settings.embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
|
| 22 |
-
directory_path = "documentos"
|
| 23 |
-
from llama_index.readers.file import PDFReader #concatenar todo o documento já vem nativo no pdfreader
|
| 24 |
-
file_extractor = {".pdf": PDFReader(return_full_document = True)}
|
| 25 |
-
from drive_downloader import GoogleDriveDownloader
|
| 26 |
-
|
| 27 |
-
# ID da pasta no Drive e caminho local
|
| 28 |
-
folder_id = "1n34bmh9rlbOtCvE_WPZRukQilKeabWsN"
|
| 29 |
-
local_path = directory_path
|
| 30 |
-
|
| 31 |
-
GoogleDriveDownloader().download_from_folder(folder_id, local_path)
|
| 32 |
-
|
| 33 |
-
documents = SimpleDirectoryReader(
|
| 34 |
-
input_dir=directory_path,
|
| 35 |
-
file_extractor=file_extractor,
|
| 36 |
-
filename_as_id=True,
|
| 37 |
-
recursive=True
|
| 38 |
-
).load_data()
|
| 39 |
-
|
| 40 |
-
from document_creator import create_single_document_with_filenames
|
| 41 |
-
document = create_single_document_with_filenames(directory_path = directory_path)
|
| 42 |
-
documents.append(document)
|
| 43 |
-
|
| 44 |
-
#from llama_index.core.ingestion import IngestionPipeline
|
| 45 |
-
#ingestion pipeline vai entrar em uso quando adicionar o extrator de metadados
|
| 46 |
-
from llama_index.core.node_parser import SentenceSplitter
|
| 47 |
-
splitter = SentenceSplitter(chunk_size=1024, chunk_overlap=128)
|
| 48 |
-
nodes = splitter.get_nodes_from_documents(documents)
|
| 49 |
-
|
| 50 |
-
from llama_index.core.storage.docstore import SimpleDocumentStore
|
| 51 |
-
docstore = SimpleDocumentStore()
|
| 52 |
-
docstore.add_documents(nodes)
|
| 53 |
-
|
| 54 |
-
from llama_index.core import VectorStoreIndex, StorageContext
|
| 55 |
-
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 56 |
-
import chromadb
|
| 57 |
-
|
| 58 |
-
db = chromadb.PersistentClient(path="chroma_db")
|
| 59 |
-
chroma_collection = db.get_or_create_collection("dense_vectors")
|
| 60 |
-
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
| 61 |
-
storage_context = StorageContext.from_defaults(
|
| 62 |
-
docstore=docstore, vector_store=vector_store
|
| 63 |
-
)
|
| 64 |
-
index = VectorStoreIndex(nodes = nodes, storage_context=storage_context, show_progress = True)
|
| 65 |
-
|
| 66 |
-
storage_context.docstore.persist("./docstore.json")
|
| 67 |
-
|
| 68 |
-
index_retriever = index.as_retriever(similarity_top_k=2)
|
| 69 |
-
import nest_asyncio
|
| 70 |
-
nest_asyncio.apply()
|
| 71 |
-
from llama_index.retrievers.bm25 import BM25Retriever
|
| 72 |
-
bm25_retriever = BM25Retriever.from_defaults(
|
| 73 |
-
docstore=index.docstore,
|
| 74 |
-
similarity_top_k=2,
|
| 75 |
-
language = "portuguese",
|
| 76 |
-
verbose=True,
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
from llama_index.core.retrievers import QueryFusionRetriever
|
| 80 |
-
|
| 81 |
-
retriever = QueryFusionRetriever(
|
| 82 |
-
[index_retriever, bm25_retriever],
|
| 83 |
-
num_queries=1, #desativado = 1
|
| 84 |
-
mode="reciprocal_rerank",
|
| 85 |
-
use_async=True,
|
| 86 |
-
verbose=True,
|
| 87 |
-
)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
from llama_index.core.memory import ChatMemoryBuffer
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from flask import Flask, request, jsonify, Response
|
| 6 |
+
# Inicializa o Flask
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
| 10 |
+
|
| 11 |
+
from llama_index.llms.openai import OpenAI
|
| 12 |
+
from llama_index.embeddings.openai import OpenAIEmbedding
|
| 13 |
+
from llama_index.core import (
|
| 14 |
+
Settings,
|
| 15 |
+
SimpleDirectoryReader,
|
| 16 |
+
StorageContext,
|
| 17 |
+
Document,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
Settings.llm = OpenAI(model="gpt-3.5-turbo")
|
| 21 |
+
Settings.embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
|
| 22 |
+
directory_path = "documentos"
|
| 23 |
+
from llama_index.readers.file import PDFReader #concatenar todo o documento já vem nativo no pdfreader
|
| 24 |
+
file_extractor = {".pdf": PDFReader(return_full_document = True)}
|
| 25 |
+
from drive_downloader import GoogleDriveDownloader
|
| 26 |
+
|
| 27 |
+
# ID da pasta no Drive e caminho local
|
| 28 |
+
folder_id = "1n34bmh9rlbOtCvE_WPZRukQilKeabWsN"
|
| 29 |
+
local_path = directory_path
|
| 30 |
+
|
| 31 |
+
GoogleDriveDownloader().download_from_folder(folder_id, local_path)
|
| 32 |
+
|
| 33 |
+
documents = SimpleDirectoryReader(
|
| 34 |
+
input_dir=directory_path,
|
| 35 |
+
file_extractor=file_extractor,
|
| 36 |
+
filename_as_id=True,
|
| 37 |
+
recursive=True
|
| 38 |
+
).load_data()
|
| 39 |
+
|
| 40 |
+
from document_creator import create_single_document_with_filenames
|
| 41 |
+
document = create_single_document_with_filenames(directory_path = directory_path)
|
| 42 |
+
documents.append(document)
|
| 43 |
+
|
| 44 |
+
#from llama_index.core.ingestion import IngestionPipeline
|
| 45 |
+
#ingestion pipeline vai entrar em uso quando adicionar o extrator de metadados
|
| 46 |
+
from llama_index.core.node_parser import SentenceSplitter
|
| 47 |
+
splitter = SentenceSplitter(chunk_size=1024, chunk_overlap=128)
|
| 48 |
+
nodes = splitter.get_nodes_from_documents(documents)
|
| 49 |
+
|
| 50 |
+
from llama_index.core.storage.docstore import SimpleDocumentStore
|
| 51 |
+
docstore = SimpleDocumentStore()
|
| 52 |
+
docstore.add_documents(nodes)
|
| 53 |
+
|
| 54 |
+
from llama_index.core import VectorStoreIndex, StorageContext
|
| 55 |
+
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 56 |
+
import chromadb
|
| 57 |
+
|
| 58 |
+
db = chromadb.PersistentClient(path="chroma_db")
|
| 59 |
+
chroma_collection = db.get_or_create_collection("dense_vectors")
|
| 60 |
+
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
| 61 |
+
storage_context = StorageContext.from_defaults(
|
| 62 |
+
docstore=docstore, vector_store=vector_store
|
| 63 |
+
)
|
| 64 |
+
index = VectorStoreIndex(nodes = nodes, storage_context=storage_context, show_progress = True)
|
| 65 |
+
|
| 66 |
+
storage_context.docstore.persist("./docstore.json")
|
| 67 |
+
|
| 68 |
+
index_retriever = index.as_retriever(similarity_top_k=2)
|
| 69 |
+
import nest_asyncio
|
| 70 |
+
nest_asyncio.apply()
|
| 71 |
+
from llama_index.retrievers.bm25 import BM25Retriever
|
| 72 |
+
bm25_retriever = BM25Retriever.from_defaults(
|
| 73 |
+
docstore=index.docstore,
|
| 74 |
+
similarity_top_k=2,
|
| 75 |
+
language = "portuguese",
|
| 76 |
+
verbose=True,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
from llama_index.core.retrievers import QueryFusionRetriever
|
| 80 |
+
|
| 81 |
+
retriever = QueryFusionRetriever(
|
| 82 |
+
[index_retriever, bm25_retriever],
|
| 83 |
+
num_queries=1, #desativado = 1
|
| 84 |
+
mode="reciprocal_rerank",
|
| 85 |
+
use_async=True,
|
| 86 |
+
verbose=True,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
from llama_index.core.memory import ChatMemoryBuffer
|
| 91 |
+
from mysqlchatstore import MySQLChatStore
|
| 92 |
+
chat_store = MySQLChatStore.from_params(
|
| 93 |
+
host=os.getenv("MYSQL_HOST"),
|
| 94 |
+
port=os.getenv("MYSQL_PORT"),
|
| 95 |
+
user=os.getenv("MYSQL_USER"),
|
| 96 |
+
password=os.getenv("MYSQL_PASSWORD"),
|
| 97 |
+
database=os.getenv("MYSQL_DATABASE"),
|
| 98 |
+
table_name=os.getenv("MYSQL_TABLE")
|
| 99 |
+
)
|
| 100 |
+
chat_memory = ChatMemoryBuffer.from_defaults(
|
| 101 |
+
token_limit=3000,
|
| 102 |
+
chat_store=chat_store,
|
| 103 |
+
chat_store_key="Sicoob", #Tendo algumas dificuldades ainda pra passar o user
|
| 104 |
+
)
|
| 105 |
+
from llama_index.core.query_engine import RetrieverQueryEngine
|
| 106 |
+
query_engine = RetrieverQueryEngine.from_args(retriever)
|
| 107 |
+
from llama_index.core.chat_engine import CondensePlusContextChatEngine
|
| 108 |
+
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
| 109 |
+
query_engine,
|
| 110 |
+
memory=chat_memory,
|
| 111 |
+
context_prompt=(
|
| 112 |
+
"Você é um assistente virtual capaz de interagir normalmente, além de"
|
| 113 |
+
" fornecer informações sobre organogramas e listar funcionários."
|
| 114 |
+
" Aqui estão os documentos relevantes para o contexto:\n"
|
| 115 |
+
"{context_str}"
|
| 116 |
+
"\nInstrução: Use o histórico da conversa anterior, ou o contexto acima, para responder."
|
| 117 |
+
"No final da resposta, depois de uma quebra de linha escreva o nome do documento que contém a informação entre dois ||, como ||Documento Nome||"
|
| 118 |
+
|
| 119 |
+
),
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@app.route("/chat", methods=["POST"])
|
| 125 |
+
def chat():
|
| 126 |
+
user_input = request.json.get("message", "")
|
| 127 |
+
if not user_input:
|
| 128 |
+
return jsonify({"error": "Mensagem vazia"}), 400
|
| 129 |
+
|
| 130 |
+
def generate_response():
|
| 131 |
+
try:
|
| 132 |
+
response = chat_engine.stream_chat(user_input)
|
| 133 |
+
for token in response.response_gen:
|
| 134 |
+
yield token # Envia cada token
|
| 135 |
+
except Exception as e:
|
| 136 |
+
yield f"Erro: {str(e)}"
|
| 137 |
+
|
| 138 |
+
return Response(generate_response(), content_type="text/plain")
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
app.run(port=5001, debug=False)
|
mysqlchatstore.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Any
|
| 2 |
+
from sqlalchemy import create_engine, text
|
| 3 |
+
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
| 4 |
+
from sqlalchemy.orm import sessionmaker
|
| 5 |
+
from pydantic import Field
|
| 6 |
+
import pymysql
|
| 7 |
+
|
| 8 |
+
from llama_index.core.storage.chat_store import BaseChatStore
|
| 9 |
+
from llama_index.core.llms import ChatMessage
|
| 10 |
+
from llama_index.core.memory import ChatMemoryBuffer
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MySQLChatStore(BaseChatStore):
|
| 15 |
+
"""
|
| 16 |
+
Implementação de um ChatStore que armazena mensagens em uma tabela MySQL,
|
| 17 |
+
unindo a pergunta do usuário e a resposta do assistente na mesma linha.
|
| 18 |
+
"""
|
| 19 |
+
table_name: Optional[str] = Field(default="chatstore", description="Nome da tabela MySQL.")
|
| 20 |
+
|
| 21 |
+
_session: Optional[sessionmaker] = None
|
| 22 |
+
_async_session: Optional[sessionmaker] = None
|
| 23 |
+
|
| 24 |
+
def __init__(self, session: sessionmaker, async_session: sessionmaker, table_name: str):
|
| 25 |
+
super().__init__(table_name=table_name.lower())
|
| 26 |
+
self._session = session
|
| 27 |
+
self._async_session = async_session
|
| 28 |
+
self._initialize()
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def from_params(cls, host: str, port: str, database: str, user: str, password: str, table_name: str = "chatstore") -> "MySQLChatStore":
|
| 32 |
+
"""
|
| 33 |
+
Cria o sessionmaker síncrono e assíncrono, retornando a instância da classe.
|
| 34 |
+
"""
|
| 35 |
+
conn_str = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"
|
| 36 |
+
async_conn_str = f"mysql+aiomysql://{user}:{password}@{host}:{port}/{database}"
|
| 37 |
+
session, async_session = cls._connect(conn_str, async_conn_str)
|
| 38 |
+
return cls(session=session, async_session=async_session, table_name=table_name)
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def _connect(cls, connection_string: str, async_connection_string: str) -> tuple[sessionmaker, sessionmaker]:
|
| 42 |
+
"""
|
| 43 |
+
Cria e retorna um sessionmaker síncrono e um sessionmaker assíncrono.
|
| 44 |
+
"""
|
| 45 |
+
engine = create_engine(connection_string, echo=False)
|
| 46 |
+
session = sessionmaker(bind=engine)
|
| 47 |
+
|
| 48 |
+
async_engine = create_async_engine(async_connection_string)
|
| 49 |
+
async_session = sessionmaker(bind=async_engine, class_=AsyncSession)
|
| 50 |
+
|
| 51 |
+
return session, async_session
|
| 52 |
+
|
| 53 |
+
def _initialize(self):
|
| 54 |
+
"""
|
| 55 |
+
Garante que a tabela exista, com colunas para armazenar user_input e response.
|
| 56 |
+
"""
|
| 57 |
+
with self._session() as session:
|
| 58 |
+
session.execute(text(f"""
|
| 59 |
+
CREATE TABLE IF NOT EXISTS {self.table_name} (
|
| 60 |
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
| 61 |
+
chat_store_key VARCHAR(255) NOT NULL,
|
| 62 |
+
user_input TEXT,
|
| 63 |
+
response TEXT,
|
| 64 |
+
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 65 |
+
)
|
| 66 |
+
"""))
|
| 67 |
+
session.commit()
|
| 68 |
+
|
| 69 |
+
def get_keys(self) -> list[str]:
|
| 70 |
+
"""
|
| 71 |
+
Retorna todas as chaves armazenadas.
|
| 72 |
+
"""
|
| 73 |
+
with self._session() as session:
|
| 74 |
+
result = session.execute(text(f"""
|
| 75 |
+
SELECT DISTINCT chat_store_key FROM {self.table_name}
|
| 76 |
+
"""))
|
| 77 |
+
return [row[0] for row in result.fetchall()]
|
| 78 |
+
|
| 79 |
+
def get_messages(self, key: str) -> list[ChatMessage]:
|
| 80 |
+
"""
|
| 81 |
+
Retorna a conversa inteira (perguntas e respostas), na ordem de inserção (id).
|
| 82 |
+
Cada linha pode conter o user_input, o response ou ambos (caso já respondido).
|
| 83 |
+
"""
|
| 84 |
+
with self._session() as session:
|
| 85 |
+
rows = session.execute(text(f"""
|
| 86 |
+
SELECT user_input, response
|
| 87 |
+
FROM {self.table_name}
|
| 88 |
+
WHERE chat_store_key = :key
|
| 89 |
+
ORDER BY id
|
| 90 |
+
"""), {"key": key}).fetchall()
|
| 91 |
+
|
| 92 |
+
messages = []
|
| 93 |
+
for user_in, resp in rows:
|
| 94 |
+
if user_in is not None:
|
| 95 |
+
messages.append(ChatMessage(role='user', content=user_in))
|
| 96 |
+
if resp is not None:
|
| 97 |
+
messages.append(ChatMessage(role='assistant', content=resp))
|
| 98 |
+
return messages
|
| 99 |
+
|
| 100 |
+
def set_messages(self, key: str, messages: list[ChatMessage]) -> None:
|
| 101 |
+
"""
|
| 102 |
+
Sobrescreve o histórico de mensagens de uma chave (apaga tudo e insere novamente).
|
| 103 |
+
Se quiser somente acrescentar, use add_message.
|
| 104 |
+
|
| 105 |
+
Aqui, cada pergunta do usuário gera uma nova linha.
|
| 106 |
+
Assim que encontrar uma mensagem de assistente, atualiza essa mesma linha.
|
| 107 |
+
Se houver assistentes sem usuários, insere normalmente.
|
| 108 |
+
"""
|
| 109 |
+
with self._session() as session:
|
| 110 |
+
# Limpa histórico anterior
|
| 111 |
+
session.execute(text(f"""
|
| 112 |
+
DELETE FROM {self.table_name} WHERE chat_store_key = :key
|
| 113 |
+
"""), {"key": key})
|
| 114 |
+
|
| 115 |
+
# Reinsere na ordem
|
| 116 |
+
current_id = None
|
| 117 |
+
for msg in messages:
|
| 118 |
+
if msg.role == 'user':
|
| 119 |
+
# Cria nova linha com user_input
|
| 120 |
+
result = session.execute(text(f"""
|
| 121 |
+
INSERT INTO {self.table_name} (chat_store_key, user_input)
|
| 122 |
+
VALUES (:key, :ui)
|
| 123 |
+
"""), {"key": key, "ui": msg.content})
|
| 124 |
+
# Pega o id do insert
|
| 125 |
+
current_id = result.lastrowid
|
| 126 |
+
|
| 127 |
+
else:
|
| 128 |
+
# Tenta atualizar a última linha se existir
|
| 129 |
+
if current_id is not None:
|
| 130 |
+
session.execute(text(f"""
|
| 131 |
+
UPDATE {self.table_name}
|
| 132 |
+
SET response = :resp
|
| 133 |
+
WHERE id = :id
|
| 134 |
+
"""), {"resp": msg.content, "id": current_id})
|
| 135 |
+
# Depois de atualizar a linha, zera o current_id
|
| 136 |
+
current_id = None
|
| 137 |
+
else:
|
| 138 |
+
# Se não houver pergunta pendente, insere como nova linha
|
| 139 |
+
session.execute(text(f"""
|
| 140 |
+
INSERT INTO {self.table_name} (chat_store_key, response)
|
| 141 |
+
VALUES (:key, :resp)
|
| 142 |
+
"""), {"key": key, "resp": msg.content})
|
| 143 |
+
|
| 144 |
+
session.commit()
|
| 145 |
+
|
| 146 |
+
def add_message(self, key: str, message: ChatMessage) -> None:
|
| 147 |
+
"""
|
| 148 |
+
Acrescenta uma nova mensagem no fluxo. Se for do usuário, insere nova linha;
|
| 149 |
+
se for do assistente, tenta preencher a linha pendente que não tenha resposta.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
with self._session() as session:
|
| 153 |
+
if message.role == 'user':
|
| 154 |
+
# Sempre cria uma nova linha para mensagens de usuário
|
| 155 |
+
insert_stmt = text(f"""
|
| 156 |
+
INSERT INTO {self.table_name} (chat_store_key, user_input)
|
| 157 |
+
VALUES (:key, :ui)
|
| 158 |
+
""")
|
| 159 |
+
session.execute(insert_stmt, {
|
| 160 |
+
"key": key,
|
| 161 |
+
"ui": message.content
|
| 162 |
+
})
|
| 163 |
+
else:
|
| 164 |
+
# Tenta encontrar a última linha sem resposta
|
| 165 |
+
|
| 166 |
+
row = session.execute(text(f"""
|
| 167 |
+
SELECT id
|
| 168 |
+
FROM {self.table_name}
|
| 169 |
+
WHERE chat_store_key = :key
|
| 170 |
+
AND user_input IS NOT NULL
|
| 171 |
+
AND response IS NULL
|
| 172 |
+
ORDER BY id DESC
|
| 173 |
+
LIMIT 1
|
| 174 |
+
"""), {"key": key}).fetchone()
|
| 175 |
+
|
| 176 |
+
if row:
|
| 177 |
+
# Atualiza com a resposta
|
| 178 |
+
msg_id = row[0]
|
| 179 |
+
|
| 180 |
+
update_stmt = text(f"""
|
| 181 |
+
UPDATE {self.table_name}
|
| 182 |
+
SET response = :resp
|
| 183 |
+
WHERE id = :id
|
| 184 |
+
""")
|
| 185 |
+
session.execute(update_stmt, {
|
| 186 |
+
"resp": message.content,
|
| 187 |
+
"id": msg_id
|
| 188 |
+
})
|
| 189 |
+
else:
|
| 190 |
+
# Se não achar linha pendente, insere como nova
|
| 191 |
+
|
| 192 |
+
insert_stmt = text(f"""
|
| 193 |
+
INSERT INTO {self.table_name} (chat_store_key, response)
|
| 194 |
+
VALUES (:key, :resp)
|
| 195 |
+
""")
|
| 196 |
+
session.execute(insert_stmt, {
|
| 197 |
+
"key": key,
|
| 198 |
+
"resp": message.content
|
| 199 |
+
})
|
| 200 |
+
|
| 201 |
+
session.commit()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def delete_messages(self, key: str) -> None:
|
| 206 |
+
"""
|
| 207 |
+
Remove todas as linhas associadas a 'key'.
|
| 208 |
+
"""
|
| 209 |
+
with self._session() as session:
|
| 210 |
+
session.execute(text(f"""
|
| 211 |
+
DELETE FROM {self.table_name} WHERE chat_store_key = :key
|
| 212 |
+
"""), {"key": key})
|
| 213 |
+
session.commit()
|
| 214 |
+
|
| 215 |
+
def delete_last_message(self, key: str) -> Optional[ChatMessage]:
|
| 216 |
+
"""
|
| 217 |
+
Apaga a última mensagem da conversa (considerando a ordem de inserção).
|
| 218 |
+
Se a última linha tiver pergunta e resposta, remove primeiro a resposta;
|
| 219 |
+
caso não exista resposta, remove a linha inteira.
|
| 220 |
+
"""
|
| 221 |
+
with self._session() as session:
|
| 222 |
+
# Localiza a última linha
|
| 223 |
+
row = session.execute(text(f"""
|
| 224 |
+
SELECT id, user_input, response
|
| 225 |
+
FROM {self.table_name}
|
| 226 |
+
WHERE chat_store_key = :key
|
| 227 |
+
ORDER BY id DESC
|
| 228 |
+
LIMIT 1
|
| 229 |
+
"""), {"key": key}).fetchone()
|
| 230 |
+
|
| 231 |
+
if not row:
|
| 232 |
+
return None
|
| 233 |
+
|
| 234 |
+
row_id, user_in, resp = row
|
| 235 |
+
|
| 236 |
+
# Se a linha tiver somente pergunta, apagamos a linha inteira.
|
| 237 |
+
# Se tiver também a resposta, apagamos só a parte do assistente.
|
| 238 |
+
if user_in and resp:
|
| 239 |
+
# Remove a resposta
|
| 240 |
+
session.execute(text(f"""
|
| 241 |
+
UPDATE {self.table_name}
|
| 242 |
+
SET response = NULL
|
| 243 |
+
WHERE id = :id
|
| 244 |
+
"""), {"id": row_id})
|
| 245 |
+
session.commit()
|
| 246 |
+
return ChatMessage(role='assistant', content=resp)
|
| 247 |
+
else:
|
| 248 |
+
# Deleta a linha inteira
|
| 249 |
+
session.execute(text(f"""
|
| 250 |
+
DELETE FROM {self.table_name}
|
| 251 |
+
WHERE id = :id
|
| 252 |
+
"""), {"id": row_id})
|
| 253 |
+
session.commit()
|
| 254 |
+
|
| 255 |
+
if user_in:
|
| 256 |
+
return ChatMessage(role='user', content=user_in)
|
| 257 |
+
elif resp:
|
| 258 |
+
return ChatMessage(role='assistant', content=resp)
|
| 259 |
+
else:
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
|
| 263 |
+
"""
|
| 264 |
+
Deleta a mensagem com base na ordem total do histórico. O índice 'idx' é
|
| 265 |
+
calculado após reconstruir a lista de ChatMessages (user e assistant).
|
| 266 |
+
"""
|
| 267 |
+
messages = self.get_messages(key)
|
| 268 |
+
if idx < 0 or idx >= len(messages):
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
removed = messages[idx]
|
| 272 |
+
|
| 273 |
+
# Agora precisamos traduzir 'idx' para saber qual registro no banco será modificado.
|
| 274 |
+
# É mais simples recriar todos os dados com set_messages sem a mensagem em 'idx':
|
| 275 |
+
messages.pop(idx)
|
| 276 |
+
self.set_messages(key, messages)
|
| 277 |
+
|
| 278 |
+
return removed
|
requirements.txt
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
-
llama-index==0.12.12
|
| 2 |
-
llama-index-retrievers-bm25==0.5.2
|
| 3 |
-
llama-index-vector-stores-chroma==0.4.1
|
| 4 |
-
llama-index-readers-google==0.6.0
|
| 5 |
-
openpyxl==3.1.5
|
| 6 |
-
flask==3.1.0
|
| 7 |
-
streamlit==1.41.1
|
| 8 |
-
streamlit-authenticator==0.4.1
|
| 9 |
-
python-levenshtein==0.26.1
|
| 10 |
-
streamlit_feedback
|
| 11 |
-
fuzzywuzzy
|
|
|
|
|
|
|
|
|
| 1 |
+
llama-index==0.12.12
|
| 2 |
+
llama-index-retrievers-bm25==0.5.2
|
| 3 |
+
llama-index-vector-stores-chroma==0.4.1
|
| 4 |
+
llama-index-readers-google==0.6.0
|
| 5 |
+
openpyxl==3.1.5
|
| 6 |
+
flask==3.1.0
|
| 7 |
+
streamlit==1.41.1
|
| 8 |
+
streamlit-authenticator==0.4.1
|
| 9 |
+
python-levenshtein==0.26.1
|
| 10 |
+
streamlit_feedback
|
| 11 |
+
fuzzywuzzy
|
| 12 |
+
pymysql==1.1.1
|
| 13 |
+
aiomysql==0.2.0
|