Delete utils
Browse files- utils/config.py +0 -180
- utils/database.py +0 -93
- utils/object_manager.py +0 -147
utils/config.py
DELETED
|
@@ -1,180 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Configurações e constantes do projeto AgentGraph
|
| 3 |
-
"""
|
| 4 |
-
import os
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
import logging
|
| 7 |
-
|
| 8 |
-
# Carrega variáveis de ambiente
|
| 9 |
-
load_dotenv()
|
| 10 |
-
|
| 11 |
-
# Configurações de API
|
| 12 |
-
HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
|
| 13 |
-
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 14 |
-
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
| 15 |
-
|
| 16 |
-
# Configurações do LangSmith (observabilidade)
|
| 17 |
-
LANGSMITH_API_KEY = os.getenv("LANGSMITH_API_KEY")
|
| 18 |
-
LANGSMITH_TRACING = os.getenv("LANGSMITH_TRACING", "false").lower() == "true"
|
| 19 |
-
LANGSMITH_ENDPOINT = os.getenv("LANGSMITH_ENDPOINT", "https://api.smith.langchain.com")
|
| 20 |
-
LANGSMITH_PROJECT = os.getenv("LANGSMITH_PROJECT", "agentgraph-project")
|
| 21 |
-
|
| 22 |
-
# Configurações de arquivos e diretórios
|
| 23 |
-
UPLOAD_DIR = os.getenv("UPLOAD_DIR", "uploaded_data")
|
| 24 |
-
DEFAULT_CSV_PATH = os.getenv("DEFAULT_CSV_PATH", "tabela.csv")
|
| 25 |
-
SQL_DB_PATH = os.getenv("SQL_DB_PATH", "data.db")
|
| 26 |
-
UPLOADED_CSV_PATH = os.path.join(UPLOAD_DIR, "tabela.csv")
|
| 27 |
-
|
| 28 |
-
# Modelos disponíveis para seleção (usados no agentSQL)
|
| 29 |
-
AVAILABLE_MODELS = {
|
| 30 |
-
"GPT-o3-mini": "o3-mini",
|
| 31 |
-
"GPT-4o-mini": "gpt-4o-mini",
|
| 32 |
-
"GPT-4o": "gpt-4o",
|
| 33 |
-
"Claude-3.5-Sonnet": "claude-3-5-sonnet-20241022"
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
# Modelos para refinamento (apenas uso interno)
|
| 37 |
-
REFINEMENT_MODELS = {
|
| 38 |
-
"LLaMA 70B": "meta-llama/Llama-3.3-70B-Instruct",
|
| 39 |
-
"LlaMA 8B": "meta-llama/Llama-3.1-8B-Instruct",
|
| 40 |
-
"DeepSeek-R1": "deepseek-ai/DeepSeek-R1-0528"
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
# Mapeamento completo de modelos (para compatibilidade)
|
| 44 |
-
LLAMA_MODELS = {**AVAILABLE_MODELS, **REFINEMENT_MODELS}
|
| 45 |
-
|
| 46 |
-
MAX_TOKENS_MAP = {
|
| 47 |
-
# Modelos de refinamento
|
| 48 |
-
"meta-llama/Llama-3.3-70B-Instruct": 900,
|
| 49 |
-
"meta-llama/Llama-3.1-8B-Instruct": 700,
|
| 50 |
-
"deepseek-ai/DeepSeek-R1-0528": 8192,
|
| 51 |
-
# Modelos do agentSQL
|
| 52 |
-
"o3-mini": 4096,
|
| 53 |
-
"gpt-4o-mini": 4096,
|
| 54 |
-
"gpt-4o": 4096,
|
| 55 |
-
"claude-3-5-sonnet-20241022": 1024
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
# Modelos que usam OpenAI (GPT)
|
| 59 |
-
OPENAI_MODELS = {
|
| 60 |
-
"o3-mini",
|
| 61 |
-
"gpt-4o-mini"
|
| 62 |
-
"gpt-4o",
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
# Modelos que usam Anthropic (Claude)
|
| 66 |
-
ANTHROPIC_MODELS = {
|
| 67 |
-
"claude-3-5-sonnet-20241022"
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
# Modelos que usam HuggingFace (para refinamento)
|
| 71 |
-
HUGGINGFACE_MODELS = {
|
| 72 |
-
"meta-llama/Llama-3.3-70B-Instruct",
|
| 73 |
-
"meta-llama/Llama-3.1-8B-Instruct",
|
| 74 |
-
"deepseek-ai/DeepSeek-R1-0528"
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
# Configurações do agente
|
| 78 |
-
DEFAULT_MODEL = os.getenv("DEFAULT_MODEL", "GPT-4o-mini")
|
| 79 |
-
MAX_ITERATIONS = int(os.getenv("MAX_ITERATIONS", "40"))
|
| 80 |
-
TEMPERATURE = float(os.getenv("TEMPERATURE", "0"))
|
| 81 |
-
|
| 82 |
-
# Configurações do Gradio
|
| 83 |
-
GRADIO_SHARE = os.getenv("GRADIO_SHARE", "False").lower() == "true"
|
| 84 |
-
GRADIO_PORT = int(os.getenv("GRADIO_PORT", "7860"))
|
| 85 |
-
|
| 86 |
-
# Configurações de logging
|
| 87 |
-
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
|
| 88 |
-
|
| 89 |
-
# Configuração do logging
|
| 90 |
-
logging.basicConfig(
|
| 91 |
-
level=getattr(logging, LOG_LEVEL.upper()),
|
| 92 |
-
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
# Cria diretório de upload se não existir
|
| 96 |
-
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 97 |
-
|
| 98 |
-
# Configuração das variáveis de ambiente para OpenAI
|
| 99 |
-
if OPENAI_API_KEY:
|
| 100 |
-
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
| 101 |
-
|
| 102 |
-
# Configuração das variáveis de ambiente para Anthropic
|
| 103 |
-
if ANTHROPIC_API_KEY:
|
| 104 |
-
os.environ["ANTHROPIC_API_KEY"] = ANTHROPIC_API_KEY
|
| 105 |
-
|
| 106 |
-
# Configuração das variáveis de ambiente para LangSmith
|
| 107 |
-
if LANGSMITH_API_KEY:
|
| 108 |
-
os.environ["LANGSMITH_API_KEY"] = LANGSMITH_API_KEY
|
| 109 |
-
os.environ["LANGSMITH_TRACING"] = str(LANGSMITH_TRACING).lower()
|
| 110 |
-
os.environ["LANGSMITH_ENDPOINT"] = LANGSMITH_ENDPOINT
|
| 111 |
-
os.environ["LANGSMITH_PROJECT"] = LANGSMITH_PROJECT
|
| 112 |
-
logging.info(f"LangSmith configurado: projeto='{LANGSMITH_PROJECT}', tracing={LANGSMITH_TRACING}")
|
| 113 |
-
else:
|
| 114 |
-
logging.info("LangSmith não configurado (LANGSMITH_API_KEY não encontrada)")
|
| 115 |
-
|
| 116 |
-
def get_active_csv_path():
|
| 117 |
-
"""Retorna o CSV ativo: o carregado ou o padrão."""
|
| 118 |
-
if os.path.exists(UPLOADED_CSV_PATH):
|
| 119 |
-
logging.info(f"[CSV] Usando arquivo CSV carregado: {UPLOADED_CSV_PATH}")
|
| 120 |
-
return UPLOADED_CSV_PATH
|
| 121 |
-
else:
|
| 122 |
-
logging.info(f"[CSV] Usando arquivo CSV padrão: {DEFAULT_CSV_PATH}")
|
| 123 |
-
return DEFAULT_CSV_PATH
|
| 124 |
-
|
| 125 |
-
def validate_config():
|
| 126 |
-
"""Valida se as configurações necessárias estão presentes."""
|
| 127 |
-
errors = []
|
| 128 |
-
warnings = []
|
| 129 |
-
|
| 130 |
-
if not HUGGINGFACE_API_KEY:
|
| 131 |
-
errors.append("HUGGINGFACE_API_KEY não configurada")
|
| 132 |
-
|
| 133 |
-
if not OPENAI_API_KEY:
|
| 134 |
-
errors.append("OPENAI_API_KEY não configurada")
|
| 135 |
-
|
| 136 |
-
if not ANTHROPIC_API_KEY:
|
| 137 |
-
errors.append("ANTHROPIC_API_KEY não configurada")
|
| 138 |
-
|
| 139 |
-
if not os.path.exists(DEFAULT_CSV_PATH):
|
| 140 |
-
errors.append(f"Arquivo CSV padrão não encontrado: {DEFAULT_CSV_PATH}")
|
| 141 |
-
|
| 142 |
-
# LangSmith é opcional - apenas aviso se não configurado
|
| 143 |
-
if not LANGSMITH_API_KEY:
|
| 144 |
-
warnings.append("LANGSMITH_API_KEY não configurada - observabilidade desabilitada")
|
| 145 |
-
|
| 146 |
-
if errors:
|
| 147 |
-
raise ValueError(f"Erros de configuração: {', '.join(errors)}")
|
| 148 |
-
|
| 149 |
-
if warnings:
|
| 150 |
-
for warning in warnings:
|
| 151 |
-
logging.warning(warning)
|
| 152 |
-
|
| 153 |
-
logging.info("Configurações validadas com sucesso")
|
| 154 |
-
return True
|
| 155 |
-
|
| 156 |
-
def is_langsmith_enabled() -> bool:
|
| 157 |
-
"""
|
| 158 |
-
Verifica se o LangSmith está habilitado e configurado
|
| 159 |
-
|
| 160 |
-
Returns:
|
| 161 |
-
True se LangSmith estiver habilitado, False caso contrário
|
| 162 |
-
"""
|
| 163 |
-
return bool(LANGSMITH_API_KEY and LANGSMITH_TRACING)
|
| 164 |
-
|
| 165 |
-
def get_langsmith_metadata() -> dict:
|
| 166 |
-
"""
|
| 167 |
-
Retorna metadados padrão para traces do LangSmith
|
| 168 |
-
|
| 169 |
-
Returns:
|
| 170 |
-
Dicionário com metadados do projeto
|
| 171 |
-
"""
|
| 172 |
-
if not is_langsmith_enabled():
|
| 173 |
-
return {}
|
| 174 |
-
|
| 175 |
-
return {
|
| 176 |
-
"project": LANGSMITH_PROJECT,
|
| 177 |
-
"application": "AgentGraph",
|
| 178 |
-
"version": "1.0.0",
|
| 179 |
-
"environment": "production"
|
| 180 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/database.py
DELETED
|
@@ -1,93 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Funções para gerenciamento de banco de dados e processamento de CSV
|
| 3 |
-
"""
|
| 4 |
-
import os
|
| 5 |
-
import pandas as pd
|
| 6 |
-
from sqlalchemy import create_engine
|
| 7 |
-
from sqlalchemy.types import DateTime, Integer, Float
|
| 8 |
-
from langchain_community.utilities import SQLDatabase
|
| 9 |
-
import logging
|
| 10 |
-
from typing import Optional
|
| 11 |
-
|
| 12 |
-
from utils.config import SQL_DB_PATH
|
| 13 |
-
|
| 14 |
-
# FUNÇÃO REMOVIDA: create_engine_and_load_db
|
| 15 |
-
# Esta função foi substituída pela nova arquitetura de nós
|
| 16 |
-
# Use: csv_processing_node.py + database_node.py
|
| 17 |
-
|
| 18 |
-
def create_engine_from_processed_dataframe(processed_df: pd.DataFrame, sql_types: dict, sql_db_path: str = SQL_DB_PATH):
|
| 19 |
-
"""
|
| 20 |
-
Cria engine SQLAlchemy a partir de DataFrame já processado
|
| 21 |
-
NOVA VERSÃO - usa processamento genérico
|
| 22 |
-
|
| 23 |
-
Args:
|
| 24 |
-
processed_df: DataFrame já processado
|
| 25 |
-
sql_types: Dicionário com tipos SQL para as colunas
|
| 26 |
-
sql_db_path: Caminho para o banco SQLite
|
| 27 |
-
|
| 28 |
-
Returns:
|
| 29 |
-
SQLAlchemy Engine
|
| 30 |
-
"""
|
| 31 |
-
logging.info("Criando banco de dados a partir de DataFrame processado...")
|
| 32 |
-
engine = create_engine(f"sqlite:///{sql_db_path}")
|
| 33 |
-
|
| 34 |
-
logging.info("[DEBUG] Tipos das colunas processadas:")
|
| 35 |
-
logging.info(processed_df.dtypes)
|
| 36 |
-
|
| 37 |
-
# Salva no banco SQLite
|
| 38 |
-
processed_df.to_sql("tabela", engine, index=False, if_exists="replace", dtype=sql_types)
|
| 39 |
-
logging.info(f"Banco de dados SQL criado com sucesso! {len(processed_df)} registros salvos")
|
| 40 |
-
return engine
|
| 41 |
-
|
| 42 |
-
def create_sql_database(engine) -> SQLDatabase:
|
| 43 |
-
"""
|
| 44 |
-
Cria objeto SQLDatabase do LangChain a partir de uma engine
|
| 45 |
-
|
| 46 |
-
Args:
|
| 47 |
-
engine: SQLAlchemy Engine
|
| 48 |
-
|
| 49 |
-
Returns:
|
| 50 |
-
SQLDatabase do LangChain
|
| 51 |
-
"""
|
| 52 |
-
return SQLDatabase(engine=engine)
|
| 53 |
-
|
| 54 |
-
def get_sample_data(engine, limit: int = 10) -> pd.DataFrame:
|
| 55 |
-
"""
|
| 56 |
-
Obtém dados de amostra do banco para contexto
|
| 57 |
-
|
| 58 |
-
Args:
|
| 59 |
-
engine: SQLAlchemy Engine
|
| 60 |
-
limit: Número de linhas para retornar
|
| 61 |
-
|
| 62 |
-
Returns:
|
| 63 |
-
DataFrame com dados de amostra
|
| 64 |
-
"""
|
| 65 |
-
try:
|
| 66 |
-
return pd.read_sql_query(f"SELECT * FROM tabela LIMIT {limit}", engine)
|
| 67 |
-
except Exception as e:
|
| 68 |
-
logging.error(f"Erro ao obter dados de amostra: {e}")
|
| 69 |
-
return pd.DataFrame()
|
| 70 |
-
|
| 71 |
-
def validate_database(engine) -> bool:
|
| 72 |
-
"""
|
| 73 |
-
Valida se o banco de dados está funcionando corretamente
|
| 74 |
-
|
| 75 |
-
Args:
|
| 76 |
-
engine: SQLAlchemy Engine
|
| 77 |
-
|
| 78 |
-
Returns:
|
| 79 |
-
True se válido, False caso contrário
|
| 80 |
-
"""
|
| 81 |
-
try:
|
| 82 |
-
# Testa uma query simples
|
| 83 |
-
result = pd.read_sql_query("SELECT COUNT(*) as count FROM tabela", engine)
|
| 84 |
-
count = result.iloc[0]['count']
|
| 85 |
-
logging.info(f"Banco validado: {count} registros encontrados")
|
| 86 |
-
return count > 0
|
| 87 |
-
except Exception as e:
|
| 88 |
-
logging.error(f"Erro na validação do banco: {e}")
|
| 89 |
-
return False
|
| 90 |
-
|
| 91 |
-
# FUNÇÃO REMOVIDA: async_create_engine_and_load_db
|
| 92 |
-
# Esta função foi removida junto com create_engine_and_load_db
|
| 93 |
-
# Use a nova arquitetura de nós: csv_processing_node.py + database_node.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/object_manager.py
DELETED
|
@@ -1,147 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Gerenciador de objetos não-serializáveis para LangGraph
|
| 3 |
-
"""
|
| 4 |
-
import uuid
|
| 5 |
-
from typing import Dict, Any, Optional
|
| 6 |
-
import logging
|
| 7 |
-
|
| 8 |
-
class ObjectManager:
|
| 9 |
-
"""
|
| 10 |
-
Gerencia objetos não-serializáveis que não podem ser incluídos no estado do LangGraph
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
def __init__(self):
|
| 14 |
-
self._objects: Dict[str, Any] = {}
|
| 15 |
-
self._sql_agents: Dict[str, Any] = {}
|
| 16 |
-
self._engines: Dict[str, Any] = {}
|
| 17 |
-
self._databases: Dict[str, Any] = {}
|
| 18 |
-
self._cache_managers: Dict[str, Any] = {}
|
| 19 |
-
# Mapeamento para relacionar agentes com seus bancos
|
| 20 |
-
self._agent_db_mapping: Dict[str, str] = {}
|
| 21 |
-
|
| 22 |
-
def store_sql_agent(self, agent: Any, db_id: str = None) -> str:
|
| 23 |
-
"""Armazena agente SQL e retorna ID"""
|
| 24 |
-
agent_id = str(uuid.uuid4())
|
| 25 |
-
self._sql_agents[agent_id] = agent
|
| 26 |
-
|
| 27 |
-
# Mapeia agente com seu banco se fornecido
|
| 28 |
-
if db_id:
|
| 29 |
-
self._agent_db_mapping[agent_id] = db_id
|
| 30 |
-
|
| 31 |
-
logging.info(f"Agente SQL armazenado com ID: {agent_id}")
|
| 32 |
-
return agent_id
|
| 33 |
-
|
| 34 |
-
def get_sql_agent(self, agent_id: str) -> Optional[Any]:
|
| 35 |
-
"""Recupera agente SQL pelo ID"""
|
| 36 |
-
return self._sql_agents.get(agent_id)
|
| 37 |
-
|
| 38 |
-
def store_engine(self, engine: Any) -> str:
|
| 39 |
-
"""Armazena engine e retorna ID"""
|
| 40 |
-
engine_id = str(uuid.uuid4())
|
| 41 |
-
self._engines[engine_id] = engine
|
| 42 |
-
logging.info(f"Engine armazenada com ID: {engine_id}")
|
| 43 |
-
return engine_id
|
| 44 |
-
|
| 45 |
-
def get_engine(self, engine_id: str) -> Optional[Any]:
|
| 46 |
-
"""Recupera engine pelo ID"""
|
| 47 |
-
return self._engines.get(engine_id)
|
| 48 |
-
|
| 49 |
-
def store_database(self, database: Any) -> str:
|
| 50 |
-
"""Armazena banco de dados e retorna ID"""
|
| 51 |
-
db_id = str(uuid.uuid4())
|
| 52 |
-
self._databases[db_id] = database
|
| 53 |
-
logging.info(f"Banco de dados armazenado com ID: {db_id}")
|
| 54 |
-
return db_id
|
| 55 |
-
|
| 56 |
-
def get_database(self, db_id: str) -> Optional[Any]:
|
| 57 |
-
"""Recupera banco de dados pelo ID"""
|
| 58 |
-
return self._databases.get(db_id)
|
| 59 |
-
|
| 60 |
-
def get_db_id_for_agent(self, agent_id: str) -> Optional[str]:
|
| 61 |
-
"""Recupera ID do banco associado ao agente"""
|
| 62 |
-
return self._agent_db_mapping.get(agent_id)
|
| 63 |
-
|
| 64 |
-
def store_cache_manager(self, cache_manager: Any) -> str:
|
| 65 |
-
"""Armazena cache manager e retorna ID"""
|
| 66 |
-
cache_id = str(uuid.uuid4())
|
| 67 |
-
self._cache_managers[cache_id] = cache_manager
|
| 68 |
-
logging.info(f"Cache manager armazenado com ID: {cache_id}")
|
| 69 |
-
return cache_id
|
| 70 |
-
|
| 71 |
-
def get_cache_manager(self, cache_id: str) -> Optional[Any]:
|
| 72 |
-
"""Recupera cache manager pelo ID"""
|
| 73 |
-
return self._cache_managers.get(cache_id)
|
| 74 |
-
|
| 75 |
-
def store_object(self, obj: Any, category: str = "general") -> str:
|
| 76 |
-
"""Armazena objeto genérico e retorna ID"""
|
| 77 |
-
obj_id = str(uuid.uuid4())
|
| 78 |
-
self._objects[obj_id] = {"object": obj, "category": category}
|
| 79 |
-
logging.info(f"Objeto {category} armazenado com ID: {obj_id}")
|
| 80 |
-
return obj_id
|
| 81 |
-
|
| 82 |
-
def get_object(self, obj_id: str) -> Optional[Any]:
|
| 83 |
-
"""Recupera objeto pelo ID"""
|
| 84 |
-
obj_data = self._objects.get(obj_id)
|
| 85 |
-
return obj_data["object"] if obj_data else None
|
| 86 |
-
|
| 87 |
-
def update_sql_agent(self, agent_id: str, new_agent: Any) -> bool:
|
| 88 |
-
"""Atualiza agente SQL existente"""
|
| 89 |
-
if agent_id in self._sql_agents:
|
| 90 |
-
self._sql_agents[agent_id] = new_agent
|
| 91 |
-
logging.info(f"Agente SQL atualizado: {agent_id}")
|
| 92 |
-
return True
|
| 93 |
-
return False
|
| 94 |
-
|
| 95 |
-
def update_engine(self, engine_id: str, new_engine: Any) -> bool:
|
| 96 |
-
"""Atualiza engine existente"""
|
| 97 |
-
if engine_id in self._engines:
|
| 98 |
-
self._engines[engine_id] = new_engine
|
| 99 |
-
logging.info(f"Engine atualizada: {engine_id}")
|
| 100 |
-
return True
|
| 101 |
-
return False
|
| 102 |
-
|
| 103 |
-
def update_cache_manager(self, cache_id: str, new_cache_manager: Any) -> bool:
|
| 104 |
-
"""Atualiza cache manager existente"""
|
| 105 |
-
if cache_id in self._cache_managers:
|
| 106 |
-
self._cache_managers[cache_id] = new_cache_manager
|
| 107 |
-
logging.info(f"Cache manager atualizado: {cache_id}")
|
| 108 |
-
return True
|
| 109 |
-
return False
|
| 110 |
-
|
| 111 |
-
def clear_all(self):
|
| 112 |
-
"""Limpa todos os objetos armazenados"""
|
| 113 |
-
self._objects.clear()
|
| 114 |
-
self._sql_agents.clear()
|
| 115 |
-
self._engines.clear()
|
| 116 |
-
self._databases.clear()
|
| 117 |
-
self._cache_managers.clear()
|
| 118 |
-
self._agent_db_mapping.clear()
|
| 119 |
-
logging.info("Todos os objetos foram limpos do gerenciador")
|
| 120 |
-
|
| 121 |
-
def get_stats(self) -> Dict[str, int]:
|
| 122 |
-
"""Retorna estatísticas dos objetos armazenados"""
|
| 123 |
-
return {
|
| 124 |
-
"sql_agents": len(self._sql_agents),
|
| 125 |
-
"engines": len(self._engines),
|
| 126 |
-
"databases": len(self._databases),
|
| 127 |
-
"cache_managers": len(self._cache_managers),
|
| 128 |
-
"general_objects": len(self._objects),
|
| 129 |
-
"agent_db_mappings": len(self._agent_db_mapping)
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
# Instância global do gerenciador
|
| 133 |
-
_object_manager: Optional[ObjectManager] = None
|
| 134 |
-
|
| 135 |
-
def get_object_manager() -> ObjectManager:
|
| 136 |
-
"""Retorna instância singleton do gerenciador de objetos"""
|
| 137 |
-
global _object_manager
|
| 138 |
-
if _object_manager is None:
|
| 139 |
-
_object_manager = ObjectManager()
|
| 140 |
-
return _object_manager
|
| 141 |
-
|
| 142 |
-
def reset_object_manager():
|
| 143 |
-
"""Reseta o gerenciador de objetos"""
|
| 144 |
-
global _object_manager
|
| 145 |
-
if _object_manager:
|
| 146 |
-
_object_manager.clear_all()
|
| 147 |
-
_object_manager = ObjectManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|