feat: Implement WebSocket support for chat functionality and refactor chat service
- Added WebSocket endpoint for real-time chat interactions. - Refactored ChatPage component to utilize WebSocket for sending and receiving messages. - Updated chat service to handle streaming responses from the LLM agent. - Introduced error handling for WebSocket connections and message processing. - Modified Editor_Test to include AppShellWithMenu for better layout. - Adjusted file path in generar_tree.py for correct directory structure. - Created llm_chat_endpoint_v1.py and llm_chat_srvc.py for handling chat requests and responses. - Established logging for WebSocket interactions and errors.
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
# src/services/agent_service.py
|
||||
|
||||
from src.ApiKeys.openai_apikey_mmr import OpenAICredencialRepo
|
||||
from src.ConexionSql.Postgres_conexion import PostgresConexion
|
||||
from src.ConexionApis.OpenAi_conexion import OpenAICliente
|
||||
from src.Llms.Modelos.Openai_model import ModeloOpenAI
|
||||
from src.Llms.Agente import AgenteAI
|
||||
from src.Llms.Memory.postgres_MemoryConv import MemoryConvPostgres
|
||||
from src.Llms.MCPs.McpClient import MCPClient
|
||||
from src.Llms.MCPs.McpClient_Registry import ClientRegistry
|
||||
from entrypoint.init_db import db_credencial
|
||||
|
||||
from src.Logger.logger_db import LoggerDB, logger
|
||||
LoggerDB(db_credencial, "logger_llm", created_by="sistema")
|
||||
|
||||
from typing import AsyncGenerator
|
||||
|
||||
# 🔧 Inicialización única del agente
|
||||
def construir_agente_llm() -> AgenteAI:
|
||||
logger.info("[INICIO] Inicializando agente LLM...")
|
||||
|
||||
conexion = PostgresConexion(db_credencial)
|
||||
|
||||
# Paso 1: Obtener credencial
|
||||
repo = OpenAICredencialRepo(conexion)
|
||||
credencial = repo.get_by_id("OPAK20250513-61b29978b7604031014")
|
||||
if not credencial:
|
||||
raise ValueError("No se encontró la credencial OpenAI")
|
||||
|
||||
logger.debug(f"[OK] Credencial OpenAI cargada: {credencial.titulo}")
|
||||
|
||||
# Paso 2: Crear cliente
|
||||
cliente = OpenAICliente(credencial)
|
||||
|
||||
# Paso 3: Instanciar modelo
|
||||
modelo = ModeloOpenAI(
|
||||
cliente=cliente,
|
||||
model="gpt-4o",
|
||||
temperature=1
|
||||
)
|
||||
|
||||
# Paso 4: Memoria en PostgreSQL
|
||||
memoria = MemoryConvPostgres(
|
||||
credencial=db_credencial,
|
||||
nombre_tabla="memoria_conversacion_pruebas",
|
||||
k=10
|
||||
)
|
||||
|
||||
# Paso 5: Herramientas MCP (ej. archivos)
|
||||
archivos = MCPClient.from_http(
|
||||
name="files",
|
||||
url="http://127.0.0.1:4201/fs"
|
||||
)
|
||||
registry = ClientRegistry()
|
||||
registry.add("files", archivos)
|
||||
|
||||
# Paso 6: Agente
|
||||
agente = AgenteAI(
|
||||
modelo=modelo,
|
||||
nombre="Asistente Inteligente",
|
||||
descripcion="",
|
||||
system_prompt="",
|
||||
rol="asistente",
|
||||
objetivos=[],
|
||||
max_iterations=0,
|
||||
memoria=memoria,
|
||||
mcp=registry
|
||||
)
|
||||
|
||||
logger.success("[OK] Agente LLM listo.")
|
||||
return agente
|
||||
|
||||
# ⚡ Función simple
|
||||
async def responder(prompt: str, agente: AgenteAI) -> str:
|
||||
logger.info(f"[Petición] Prompt recibido: {prompt[:50]}...")
|
||||
respuesta = await agente.interactuar_en_bucle(prompt=prompt, stream=False)
|
||||
logger.debug(f"[Respuesta] {respuesta[:100]}...")
|
||||
return respuesta
|
||||
|
||||
# 🔁 Función en streaming
|
||||
async def responder_stream(prompt: str, agente: AgenteAI) -> AsyncGenerator[str, None]:
|
||||
logger.info(f"[Streaming] Prompt recibido: {prompt[:50]}...")
|
||||
async for token in agente.interactuar_en_bucle(prompt=prompt, stream=True):
|
||||
yield token
|
||||
Reference in New Issue
Block a user