feat: Add NaliiaBot API
This commit is contained in:
1007
poetry.lock
generated
1007
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -13,7 +13,8 @@ dependencies = [
|
||||
"langgraph[standard] (>=1.0.6,<2.0.0)",
|
||||
"langchain-anthropic (>=1.3.1,<2.0.0)",
|
||||
"langchain-deepseek (>=1.0.1,<2.0.0)",
|
||||
"dotenv (>=0.9.9,<0.10.0)"
|
||||
"dotenv (>=0.9.9,<0.10.0)",
|
||||
"fastapi[standard] (>=0.128.5,<0.129.0)"
|
||||
]
|
||||
|
||||
[tool.poetry]
|
||||
|
||||
0
src/__init__.py
Normal file
0
src/__init__.py
Normal file
0
src/naliiabotapi/__init__.py
Normal file
0
src/naliiabotapi/__init__.py
Normal file
16
src/naliiabotapi/api/dependencies.py
Normal file
16
src/naliiabotapi/api/dependencies.py
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
import os
|
||||
from src.naliiabot.bot.agent.agent import Agent
|
||||
from src.naliiabot.bot.factories.llm_factory import LLMFactory
|
||||
|
||||
MODEL_NAME = os.getenv("LLM_MODEL", "anthropic")
|
||||
|
||||
def get_agent():
|
||||
"""
|
||||
Dependency function to get an instance of the Agent class.
|
||||
|
||||
Returns:
|
||||
Agent: An instance of the Agent class.
|
||||
"""
|
||||
model = LLMFactory(MODEL_NAME).get_model()
|
||||
return Agent(model=model)
|
||||
0
src/naliiabotapi/api/v1/__init__.py
Normal file
0
src/naliiabotapi/api/v1/__init__.py
Normal file
0
src/naliiabotapi/api/v1/endpoints/__init__.py
Normal file
0
src/naliiabotapi/api/v1/endpoints/__init__.py
Normal file
22
src/naliiabotapi/api/v1/endpoints/chat.py
Normal file
22
src/naliiabotapi/api/v1/endpoints/chat.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from ...dependencies import get_agent
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/chat")
|
||||
def chat(messages: dict, agent = Depends(get_agent)):
|
||||
"""
|
||||
Simulate a chat response based on the input message.
|
||||
|
||||
Args:
|
||||
message (str): The input message from the user.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the response message.
|
||||
"""
|
||||
|
||||
messages = [HumanMessage(content=messages["messages"])]
|
||||
response_message = agent.invoke({"messages": messages})
|
||||
|
||||
return {"response": response_message}
|
||||
18
src/naliiabotapi/main.py
Normal file
18
src/naliiabotapi/main.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from fastapi import FastAPI
|
||||
from src.naliiabotapi.api.v1.endpoints.chat import router as chat_router
|
||||
|
||||
app = FastAPI(
|
||||
title="NaliiaBot API",
|
||||
description="API for NaliiaBot, a chatbot that provides customer service and related topics.",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
app.include_router(chat_router)
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
@app.get("/health")
|
||||
def health_check():
|
||||
return {"status": "ok"}
|
||||
27
tests/test_api.py
Normal file
27
tests/test_api.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from src.naliiabotapi.main import app
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
client = TestClient(app)
|
||||
|
||||
return client
|
||||
|
||||
def test_root(client):
|
||||
response = client.get("/")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_health(client):
|
||||
response = client.get("/health")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_chat(client):
|
||||
response = client.post("/chat", json={"messages": "Hello, how are you?"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() is not None
|
||||
@@ -1,176 +0,0 @@
|
||||
import streamlit as st
|
||||
from datetime import datetime
|
||||
|
||||
# Configurar página
|
||||
st.set_page_config(
|
||||
page_title="NaliiaBot Chat",
|
||||
page_icon="💬",
|
||||
layout="wide",
|
||||
initial_sidebar_state="expanded"
|
||||
)
|
||||
|
||||
# Estilos personalizados
|
||||
st.markdown("""
|
||||
<style>
|
||||
.main {
|
||||
padding: 2rem;
|
||||
}
|
||||
.chat-message {
|
||||
padding: 1rem;
|
||||
margin: 0.5rem 0;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
.user-message {
|
||||
background-color: #d1e7dd;
|
||||
text-color: black;
|
||||
text-align: right;
|
||||
}
|
||||
.bot-message {
|
||||
background-color: #f5f5f5;
|
||||
text-color: black;
|
||||
text-align: left;
|
||||
}
|
||||
.timestamp {
|
||||
font-size: 0.8rem;
|
||||
color: #666;
|
||||
}
|
||||
</style>
|
||||
""", unsafe_allow_html=True)
|
||||
|
||||
def initialize_session_state():
|
||||
"""Inicializar estado de sesión"""
|
||||
if "messages" not in st.session_state:
|
||||
st.session_state.messages = []
|
||||
if "chat_history" not in st.session_state:
|
||||
st.session_state.chat_history = []
|
||||
|
||||
def display_messages():
|
||||
"""Mostrar todos los mensajes del chat"""
|
||||
for message in st.session_state.messages:
|
||||
with st.container():
|
||||
if message["role"] == "user":
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="chat-message user-message">
|
||||
<p><strong>Tú:</strong> {message['content']}</p>
|
||||
<p class="timestamp">{message['timestamp']}</p>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True
|
||||
)
|
||||
else:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="chat-message bot-message">
|
||||
<p><strong>NaliiaBot:</strong> {message['content']}</p>
|
||||
<p class="timestamp">{message['timestamp']}</p>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True
|
||||
)
|
||||
|
||||
def get_bot_response(user_message):
|
||||
"""Generar respuesta del bot (placeholder)"""
|
||||
# TODO: Integrar con tu modelo de IA/LLM
|
||||
responses = {
|
||||
"hola": "¡Hola! Bienvenido a NaliiaBot. ¿Cómo puedo ayudarte hoy?",
|
||||
"ayuda": "Puedo ayudarte con: información, responder preguntas, y más. ¿En qué te puedo asistir?",
|
||||
"default": f"Entiendo que dijiste: '{user_message}'. ¿Podrías darme más detalles?"
|
||||
}
|
||||
|
||||
user_lower = user_message.lower().strip()
|
||||
for key, response in responses.items():
|
||||
if key in user_lower:
|
||||
return response
|
||||
return responses["default"]
|
||||
|
||||
def main():
|
||||
# Inicializar estado
|
||||
initialize_session_state()
|
||||
|
||||
# Header
|
||||
st.markdown("# NaliiaBot Chat")
|
||||
st.markdown("---")
|
||||
|
||||
# Sidebar
|
||||
with st.sidebar:
|
||||
st.markdown("### ⚙️ Configuración")
|
||||
|
||||
# Modo de display
|
||||
display_mode = st.radio(
|
||||
"Modo de visualización:",
|
||||
("Completo", "Compacto"),
|
||||
help="Selecciona cómo mostrar el chat"
|
||||
)
|
||||
|
||||
# Opciones
|
||||
st.markdown("### 📋 Opciones")
|
||||
if st.button("🗑️ Limpiar chat", use_container_width=True):
|
||||
st.session_state.messages = []
|
||||
st.session_state.chat_history = []
|
||||
st.rerun()
|
||||
|
||||
if st.button("💾 Guardar conversación", use_container_width=True):
|
||||
st.success("Conversación guardada (función a implementar)")
|
||||
|
||||
# Información
|
||||
st.markdown("---")
|
||||
st.markdown("### ℹ️ Información")
|
||||
st.markdown(f"**Total de mensajes:** {len(st.session_state.messages)}")
|
||||
st.markdown("**Versión:** 1.0.0")
|
||||
st.markdown("**Estado:** En desarrollo")
|
||||
|
||||
# Área principal de chat
|
||||
col1, col2 = st.columns([4, 1])
|
||||
|
||||
with col1:
|
||||
st.markdown("### Conversación")
|
||||
|
||||
# Mostrar mensajes
|
||||
message_container = st.container()
|
||||
with message_container:
|
||||
display_messages()
|
||||
|
||||
# Input del usuario
|
||||
st.markdown("---")
|
||||
|
||||
with st.form(key="message_form", clear_on_submit=True):
|
||||
col1, col2 = st.columns([5, 1])
|
||||
|
||||
with col1:
|
||||
user_input = st.text_input(
|
||||
"Escribe tu mensaje:",
|
||||
placeholder="Escribe aquí y presiona Enter...",
|
||||
label_visibility="collapsed"
|
||||
)
|
||||
|
||||
with col2:
|
||||
send_button = st.form_submit_button("📤 Enviar", use_container_width=True)
|
||||
|
||||
# Procesar entrada del usuario
|
||||
if send_button and user_input.strip():
|
||||
# Agregar mensaje del usuario
|
||||
timestamp = datetime.now().strftime("%H:%M:%S")
|
||||
st.session_state.messages.append({
|
||||
"role": "user",
|
||||
"content": user_input,
|
||||
"timestamp": timestamp
|
||||
})
|
||||
|
||||
# Obtener respuesta del bot
|
||||
bot_response = get_bot_response(user_input)
|
||||
st.session_state.messages.append({
|
||||
"role": "bot",
|
||||
"content": bot_response,
|
||||
"timestamp": datetime.now().strftime("%H:%M:%S")
|
||||
})
|
||||
|
||||
# Guardar en historial
|
||||
st.session_state.chat_history.append({
|
||||
"user": user_input,
|
||||
"bot": bot_response,
|
||||
"timestamp": timestamp
|
||||
})
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user