File size: 2,956 Bytes
bc9904d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from src.models.agent_models import QuestionRequest
from src.agents import AGENT_MANAGER
from langchain_core.messages import HumanMessage, AIMessage
import re

router = APIRouter()

@router.post("/ask-stream")
def ask_stream(req: QuestionRequest):
    agent = AGENT_MANAGER.get_agent(req.agent_id)
    if not agent:
        return {"error": "Agente no encontrado"}
    if "get_context" in agent and "prompt" in agent:
        chat_history = "\n".join([
            f"Usuario: {msg.content}" if isinstance(msg, HumanMessage) else f"Asistente: {msg.content}"
            for msg in agent["history"].messages
        ])
        context_result = agent["get_context"](req.question)
        # Handle both old and new context return formats
        if isinstance(context_result, tuple):
            context, language = context_result
        else:
            context = context_result
            language = "ESPAÑOL"  # Default to Spanish if no language detection
            
        prompt_text = agent["prompt"].format(
            context=context, 
            question=req.question, 
            chat_history=chat_history,
            language=language
        )
        def generate():
            full_response = ""
            for chunk in agent["llm"].stream(prompt_text):
                content = chunk.content
                full_response += content
                yield content
            agent["history"].add_user_message(req.question)
            agent["history"].add_ai_message(full_response)
        return StreamingResponse(generate(), media_type="text/plain")
    elif "agent" in agent and "history" in agent:
        def generate():
            inputs = {
                "input": req.question,
                "chat_history": agent["history"].messages,
                "intermediate_steps": []
            }
            response = agent["agent"].invoke(inputs)
            raw_output = getattr(response, "output", str(response)).strip()
            raw_output = re.sub(r"return_values=\{.*?['\"]output['\"]:\s*['\"]", "", raw_output, flags=re.DOTALL)
            raw_output = re.sub(r"['\"]\}\s*(log=.*)?", "", raw_output, flags=re.DOTALL)
            lines = [line.strip() for line in raw_output.splitlines() if line.strip()]
            lines_with_price = [line for line in lines if re.search(r"\$\d{3,6}", line)]
            final_line = lines_with_price[-1] if lines_with_price else lines[-1] if lines else "⚠️ No se pudo generar respuesta."
            print("💬 Respuesta final mostrada al usuario:")
            print(final_line)
            final_msg = f"\n💵 {final_line}"
            agent["history"].add_user_message(req.question)
            agent["history"].add_ai_message(final_msg)
            yield final_msg
        return StreamingResponse(generate(), media_type="text/plain")
    return {"error": "Estructura de agente no válida"}