File size: 6,801 Bytes
7e2816d
 
 
 
 
 
 
 
 
 
 
 
 
607c0d3
7e2816d
 
 
 
 
 
607c0d3
 
7e2816d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b95c170
7e2816d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23d2c72
 
7e2816d
 
 
 
 
 
 
 
 
 
 
 
b95c170
 
7e2816d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c0d3
 
 
 
7f9880a
90e9ab6
829f489
607c0d3
 
 
 
 
 
7f9880a
90e9ab6
829f489
 
607c0d3
 
 
 
 
 
7e2816d
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# app.py - VERSÃO COMPLETA COM VOZ (BASE64) E VISÃO
import os
import base64
import io
import asyncio
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel 
from PIL import Image
from jade.core import JadeAgent 
from jade.scholar import ScholarAgent
from jade.heavy_mode import JadeHeavyAgent
from jade.webdev import WebDevAgent

print("Iniciando a J.A.D.E. com FastAPI...")
jade_agent = JadeAgent() 
scholar_agent = ScholarAgent()
# Instantiate Heavy Agent. It uses environment variables.
jade_heavy_agent = JadeHeavyAgent()
# Instantiate WebDev Agent
webdev_agent = WebDevAgent()

print("J.A.D.E. pronta para receber requisições.")

app = FastAPI(title="J.A.D.E. API")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
)

# Mount generated directory for static files (PDFs, Images)
os.makedirs("backend/generated", exist_ok=True)
app.mount("/generated", StaticFiles(directory="backend/generated"), name="generated")

# Dicionário global para armazenar sessões de usuários
# Structure: user_sessions[user_id] = { "jade": [...], "scholar": [...], "heavy": [...] }
user_sessions = {}

class UserRequest(BaseModel):
    user_input: str
    image_base64: str | None = None
    user_id: str | None = None
    agent_type: str = "jade" # "jade", "scholar", "heavy"
    web_search: bool = False  # Toggle para busca web na J.A.D.E.
    thinking_mode: bool = False  # Toggle para modo CoT/Thinking

@app.post("/chat")
async def handle_chat(request: UserRequest):
    try:
        user_id = request.user_id if request.user_id else "default_user"
        agent_type = request.agent_type.lower()
        
        if user_id not in user_sessions:
            print(f"Nova sessão criada para: {user_id}")
            user_sessions[user_id] = {
                "jade": [jade_agent.system_prompt],
                "scholar": [],
                "heavy": []
            }
        
        # Ensure sub-keys exist
        if "jade" not in user_sessions[user_id]: user_sessions[user_id]["jade"] = [jade_agent.system_prompt]
        if "scholar" not in user_sessions[user_id]: user_sessions[user_id]["scholar"] = []
        if "heavy" not in user_sessions[user_id]: user_sessions[user_id]["heavy"] = []

        vision_context = None
        if request.image_base64:
            try:
                header, encoded_data = request.image_base64.split(",", 1)
                image_bytes = base64.b64decode(encoded_data)
                pil_image = Image.open(io.BytesIO(image_bytes))
                # Jade handles vision processing
                vision_context = jade_agent.image_handler.process_pil_image(pil_image)
            except Exception as img_e:
                print(f"Erro ao processar imagem Base64: {img_e}")
                vision_context = "Houve um erro ao analisar a imagem."

        final_user_input = request.user_input if request.user_input else "Descreva a imagem em detalhes."

        bot_response_text = ""
        audio_path = None
        
        if agent_type == "scholar":
            current_history = user_sessions[user_id]["scholar"]
            bot_response_text, audio_path, updated_history = scholar_agent.respond(
                history=current_history,
                user_input=final_user_input,
                user_id=user_id,
                vision_context=vision_context
            )
            user_sessions[user_id]["scholar"] = updated_history
            
        elif agent_type == "heavy":
            current_history = user_sessions[user_id]["heavy"]
            # Heavy agent is async
            bot_response_text, audio_path, updated_history = await jade_heavy_agent.respond(
                history=current_history,
                user_input=final_user_input,
                user_id=user_id,
                vision_context=vision_context,
                web_search=request.web_search  # Passa web search para Heavy Mode
            )
            user_sessions[user_id]["heavy"] = updated_history
            
        else:
            # Default to J.A.D.E.
            current_history = user_sessions[user_id]["jade"]
            # Jade agent is synchronous, run directly
            bot_response_text, audio_path, updated_history = jade_agent.respond(
                history=current_history,
                user_input=final_user_input,
                user_id=user_id,
                vision_context=vision_context,
                web_search=request.web_search,
                thinking_mode=request.thinking_mode  # Passa o toggle de thinking
            )
            user_sessions[user_id]["jade"] = updated_history

        # Audio Logic
        audio_base64 = None
        if audio_path and os.path.exists(audio_path):
            print(f"Codificando arquivo de áudio: {audio_path}")
            with open(audio_path, "rb") as audio_file:
                audio_bytes = audio_file.read()
                audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
            
            # Remove only if temp file
            if "backend/generated" not in audio_path:
                os.remove(audio_path) 
        
        return {
            "success": True,
            "bot_response": bot_response_text,
            "audio_base64": audio_base64 
        }
    except Exception as e:
        print(f"Erro crítico no endpoint /chat: {e}")
        return {"success": False, "error": str(e)}

# WebDev Vibe Coder endpoint
class WebDevRequest(BaseModel):
    prompt: str
    existing_code: str | None = None
    mode: str = "html"  # "html" or "react"
    error_message: str | None = None  # For agentic error fixing
    model: str | None = None  # Model to use (e.g., "kimi-k2", "claude-sonnet")

@app.post("/webdev/generate")
async def handle_webdev(request: WebDevRequest):
    try:
        result = webdev_agent.generate(
            prompt=request.prompt,
            refine_code=request.existing_code,
            mode=request.mode,
            error_message=request.error_message,
            model=request.model
        )
        return result
    except Exception as e:
        print(f"Erro no endpoint /webdev: {e}")
        return {"success": False, "error": str(e)}

@app.get("/")
def root():
    return {"message": "Servidor J.A.D.E. com FastAPI está online."}

if __name__ == "__main__":
    import uvicorn
    port = int(os.environ.get("PORT", 7860))
    print(f"Iniciando o servidor Uvicorn em http://0.0.0.0:{port}")
    uvicorn.run(app, host="0.0.0.0", port=port)