-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessing_api.py
More file actions
220 lines (196 loc) · 7.71 KB
/
Copy pathprocessing_api.py
File metadata and controls
220 lines (196 loc) · 7.71 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
import time
import json
import sqlite3
import threading
import requests
from fastapi import FastAPI, BackgroundTasks, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(title="API de Processamento - Hackathon", version="1.0.0")
BOT_API_URL = os.getenv("BOT_API_URL", "http://localhost:5000")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "deepseek-r1")
MAX_ITERACOES = int(os.getenv("MAX_ITERACOES_POR_TURNO", 5))
# Setup DB
db_conn = sqlite3.connect("conversas.db", check_same_thread=False)
cursor = db_conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS conversas (
uuid TEXT PRIMARY KEY,
status TEXT,
turno_atual INTEGER,
iteracao_atual INTEGER,
pergunta_pendente TEXT,
resposta_final TEXT,
erro TEXT,
historico TEXT,
atualizado_em REAL
)
''')
db_conn.commit()
db_lock = threading.Lock()
def get_conversa(c_uuid):
with db_lock:
cursor.execute("SELECT * FROM conversas WHERE uuid = ?", (c_uuid,))
row = cursor.fetchone()
if not row: return None
return {
"uuid": row[0], "status": row[1], "turno_atual": row[2],
"iteracao_atual": row[3], "pergunta_pendente": row[4],
"resposta_final": row[5], "erro": row[6],
"historico": json.loads(row[7]), "atualizado_em": row[8]
}
def save_conversa(c):
with db_lock:
cursor.execute('''
INSERT OR REPLACE INTO conversas
(uuid, status, turno_atual, iteracao_atual, pergunta_pendente, resposta_final, erro, historico, atualizado_em)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (c["uuid"], c["status"], c["turno_atual"], c["iteracao_atual"],
c["pergunta_pendente"], c["resposta_final"], c["erro"],
json.dumps(c["historico"]), time.time()))
db_conn.commit()
class ConversaCreate(BaseModel):
uuid: str
enunciado: str
respostas: List[str]
class RespostasUpdate(BaseModel):
respostas: List[str]
class MensagemNova(BaseModel):
enunciado: str
respostas: Optional[List[str]] = []
def processar_llm_background(c_uuid):
c = get_conversa(c_uuid)
if not c: return
# Monta contexto do historico
contexto = "Histórico:\n"
for item in c["historico"]:
contexto += f"Turno {item['turno']} - Iteração {item['iteracao']}:\n"
contexto += f"P: {item['pergunta']}\n"
contexto += f"R: {item['respostas']}\n"
prompt = f"""Você é um analista sintetizando opiniões de um grupo.
{contexto}
Com base nessas opiniões, você tem informações suficientes para uma resposta final?
Responda APENAS em JSON no formato exato: {{"decisao": "final" ou "esclarecimento", "texto": "sua resposta final ou a pergunta adicional"}}"""
# Chamada Ollama
try:
res = requests.post(f"{OLLAMA_URL}/api/generate", json={
"model": OLLAMA_MODEL,
"prompt": prompt,
"stream": False,
"format": "json"
}, timeout=15)
if res.status_code == 200:
data = json.loads(res.json()["response"])
decisao = data.get("decisao")
texto = data.get("texto")
if decisao == "esclarecimento" and c["iteracao_atual"] < MAX_ITERACOES:
c["status"] = "awaiting_answers"
c["pergunta_pendente"] = texto
c["iteracao_atual"] += 1
save_conversa(c)
# Chama Bot API para pedir mais dados pro grupo
requests.post(f"{BOT_API_URL}/v1/perguntas", json={
"uuid": c["uuid"],
"pergunta": texto,
"callback_url": f"/v1/conversas/{c_uuid}/respostas"
})
return
else:
c["status"] = "completed"
c["resposta_final"] = texto
c["pergunta_pendente"] = None
save_conversa(c)
return
except Exception as e:
print(f"Erro na LLM: {e}. Usando Fallback mockado para Hackathon.")
# Fallback para o Hackathon se o Ollama não rodar/falhar
if c["iteracao_atual"] == 0:
c["status"] = "awaiting_answers"
c["pergunta_pendente"] = "🤔 IA: As respostas foram confusas. Vocês poderiam ser mais específicos sobre a viabilidade?"
c["iteracao_atual"] += 1
save_conversa(c)
try:
requests.post(f"{BOT_API_URL}/v1/perguntas", json={
"uuid": c["uuid"],
"pergunta": c["pergunta_pendente"],
"callback_url": f"/v1/conversas/{c_uuid}/respostas"
})
except Exception as bot_e:
print(f"A API do Bot não respondeu no Fallback: {bot_e}")
else:
c["status"] = "completed"
c["resposta_final"] = "✅ Conclusão da IA (Fallback): Baseado nos esclarecimentos, a solução proposta pelo grupo é viável para o projeto."
c["pergunta_pendente"] = None
save_conversa(c)
return
@app.post("/v1/conversas", status_code=202)
def criar_conversa(dados: ConversaCreate, background_tasks: BackgroundTasks):
if get_conversa(dados.uuid):
raise HTTPException(status_code=409, detail="UUID já existe")
c = {
"uuid": dados.uuid,
"status": "processing",
"turno_atual": 0,
"iteracao_atual": 0,
"pergunta_pendente": None,
"resposta_final": None,
"erro": None,
"historico": [{
"turno": 0,
"iteracao": 0,
"pergunta": dados.enunciado,
"respostas": dados.respostas
}],
"atualizado_em": time.time()
}
save_conversa(c)
background_tasks.add_task(processar_llm_background, dados.uuid)
return {"uuid": dados.uuid, "status": "processing"}
@app.get("/v1/conversas/{uuid}")
def consultar_conversa(uuid: str):
c = get_conversa(uuid)
if not c:
raise HTTPException(status_code=404, detail="Não encontrado")
return c
@app.post("/v1/conversas/{uuid}/respostas", status_code=202)
def enviar_respostas(uuid: str, dados: RespostasUpdate, background_tasks: BackgroundTasks):
c = get_conversa(uuid)
if not c:
raise HTTPException(status_code=404, detail="Não encontrado")
if c["status"] != "awaiting_answers":
raise HTTPException(status_code=409, detail="Não está aguardando")
c["historico"].append({
"turno": c["turno_atual"],
"iteracao": c["iteracao_atual"],
"pergunta": c["pergunta_pendente"],
"respostas": dados.respostas
})
c["status"] = "processing"
save_conversa(c)
background_tasks.add_task(processar_llm_background, uuid)
return {"uuid": uuid, "status": "processing"}
@app.post("/v1/conversas/{uuid}/mensagens", status_code=202)
def nova_mensagem(uuid: str, dados: MensagemNova, background_tasks: BackgroundTasks):
c = get_conversa(uuid)
if not c:
raise HTTPException(status_code=404, detail="Não encontrado")
if c["status"] == "processing":
raise HTTPException(status_code=409, detail="Ainda processando")
c["turno_atual"] += 1
c["iteracao_atual"] = 0
c["status"] = "processing"
c["resposta_final"] = None
c["historico"].append({
"turno": c["turno_atual"],
"iteracao": 0,
"pergunta": dados.enunciado,
"respostas": dados.respostas
})
save_conversa(c)
background_tasks.add_task(processar_llm_background, uuid)
return {"uuid": uuid, "status": "processing"}
@app.get("/health")
def health():
return {"status": "ok"}