feat: consolida backend RAG e documentação
This commit is contained in:
parent
7c18727f62
commit
d72572ee6f
28 changed files with 2193 additions and 275 deletions
273
rag-api/app.py
273
rag-api/app.py
|
|
@ -1,4 +1,3 @@
|
|||
import os
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
|
@ -8,22 +7,20 @@ from fastapi import FastAPI, Header, HTTPException
|
|||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from config import settings
|
||||
from request_contract import ContractError, extract_user_question, validate_api_key
|
||||
from source_metadata import source_reference
|
||||
|
||||
|
||||
QDRANT_URL = os.getenv("QDRANT_URL", "http://192.168.0.153:6333").rstrip("/")
|
||||
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://192.168.0.106:11434").rstrip("/")
|
||||
|
||||
COLLECTION = os.getenv("QDRANT_COLLECTION", "ativa_knowledge")
|
||||
EMBED_MODEL = os.getenv("EMBED_MODEL", "nomic-embed-text")
|
||||
CHAT_MODEL = os.getenv("CHAT_MODEL", "ativa-assistente")
|
||||
|
||||
API_KEY = os.getenv("ATIVA_RAG_API_KEY", "").strip()
|
||||
|
||||
SCORE_THRESHOLD = float(os.getenv("RAG_SCORE_THRESHOLD", "0.55"))
|
||||
MAX_CONTEXT_CHARS = int(os.getenv("RAG_MAX_CONTEXT_CHARS", "18000"))
|
||||
MAX_QUESTION_CHARS = int(os.getenv("RAG_MAX_QUESTION_CHARS", "2000"))
|
||||
QDRANT_URL = settings.qdrant_url
|
||||
OLLAMA_URL = settings.ollama_url
|
||||
COLLECTION = settings.collection
|
||||
EMBED_MODEL = settings.embed_model
|
||||
CHAT_MODEL = settings.chat_model
|
||||
API_KEY = settings.api_key
|
||||
SCORE_THRESHOLD = settings.score_threshold
|
||||
MAX_CONTEXT_CHARS = settings.max_context_chars
|
||||
MAX_QUESTION_CHARS = settings.max_question_chars
|
||||
|
||||
app = FastAPI(
|
||||
title="ATIVA RAG API",
|
||||
|
|
@ -241,6 +238,9 @@ async def query(
|
|||
|
||||
question = request.question.strip()
|
||||
|
||||
if not question:
|
||||
raise HTTPException(status_code=400, detail="Pergunta vazia.")
|
||||
|
||||
if len(question) > MAX_QUESTION_CHARS:
|
||||
raise HTTPException(status_code=400, detail="Pergunta muito longa.")
|
||||
|
||||
|
|
@ -276,16 +276,21 @@ async def query(
|
|||
"collection": COLLECTION,
|
||||
}
|
||||
|
||||
except httpx.TimeoutException as exc:
|
||||
raise HTTPException(
|
||||
status_code=504,
|
||||
detail="Tempo esgotado ao consultar serviço interno.",
|
||||
) from exc
|
||||
except httpx.HTTPStatusError as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Falha em serviço interno: {exc.response.text[:500]}",
|
||||
)
|
||||
detail="Falha em serviço interno.",
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Erro no RAG: {exc}",
|
||||
)
|
||||
detail="Erro interno no RAG.",
|
||||
) from exc
|
||||
|
||||
|
||||
@app.get("/v1/models")
|
||||
|
|
@ -320,120 +325,140 @@ async def chat_completions(
|
|||
except ContractError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
|
||||
vector = await embed(question)
|
||||
try:
|
||||
vector = await embed(question)
|
||||
|
||||
results = await search_qdrant(
|
||||
vector,
|
||||
top_k=5,
|
||||
score_threshold=SCORE_THRESHOLD,
|
||||
)
|
||||
|
||||
context, sources = build_context(results)
|
||||
|
||||
system_messages = [
|
||||
str(m.get("content", ""))
|
||||
for m in request.messages
|
||||
if m.get("role") == "system"
|
||||
]
|
||||
|
||||
prompt = build_prompt(
|
||||
question=question,
|
||||
context=context,
|
||||
messages=request.messages,
|
||||
)
|
||||
|
||||
if system_messages:
|
||||
prompt = (
|
||||
"INSTRUÇÕES ADICIONAIS DO SISTEMA:\n"
|
||||
+ "\n".join(system_messages)
|
||||
+ "\n\n"
|
||||
+ prompt
|
||||
results = await search_qdrant(
|
||||
vector,
|
||||
top_k=5,
|
||||
score_threshold=SCORE_THRESHOLD,
|
||||
)
|
||||
|
||||
answer = await generate(
|
||||
prompt=prompt,
|
||||
temperature=request.temperature or 0.1,
|
||||
model=request.model or CHAT_MODEL,
|
||||
)
|
||||
context, sources = build_context(results)
|
||||
|
||||
response_id = f"chatcmpl-{uuid.uuid4().hex}"
|
||||
created = int(time.time())
|
||||
system_messages = [
|
||||
str(m.get("content", ""))
|
||||
for m in request.messages
|
||||
if m.get("role") == "system"
|
||||
]
|
||||
|
||||
if not request.stream:
|
||||
return {
|
||||
"id": response_id,
|
||||
"object": "chat.completion",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": answer,
|
||||
prompt = build_prompt(
|
||||
question=question,
|
||||
context=context,
|
||||
messages=request.messages,
|
||||
)
|
||||
|
||||
if system_messages:
|
||||
prompt = (
|
||||
"INSTRUÇÕES ADICIONAIS DO SISTEMA:\n"
|
||||
+ "\n".join(system_messages)
|
||||
+ "\n\n"
|
||||
+ prompt
|
||||
)
|
||||
|
||||
answer = await generate(
|
||||
prompt=prompt,
|
||||
temperature=(
|
||||
request.temperature
|
||||
if request.temperature is not None
|
||||
else 0.1
|
||||
),
|
||||
model=request.model or CHAT_MODEL,
|
||||
)
|
||||
|
||||
response_id = f"chatcmpl-{uuid.uuid4().hex}"
|
||||
created = int(time.time())
|
||||
|
||||
if not request.stream:
|
||||
return {
|
||||
"id": response_id,
|
||||
"object": "chat.completion",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": answer,
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
"x_ativa_sources": sources,
|
||||
}
|
||||
|
||||
async def event_stream():
|
||||
yield (
|
||||
f"data: {{\"id\":\"{response_id}\","
|
||||
f"\"object\":\"chat.completion.chunk\","
|
||||
f"\"created\":{created},"
|
||||
f"\"model\":\"{request.model or CHAT_MODEL}\","
|
||||
f"\"choices\":[{{\"index\":0,\"delta\":{{"
|
||||
f"\"role\":\"assistant\"}},\"finish_reason\":null}}]}}\n\n"
|
||||
)
|
||||
|
||||
import json
|
||||
|
||||
yield (
|
||||
"data: "
|
||||
+ json.dumps(
|
||||
{
|
||||
"id": response_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {"content": answer},
|
||||
"finish_reason": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
"x_ativa_sources": sources,
|
||||
}
|
||||
|
||||
async def event_stream():
|
||||
yield (
|
||||
f"data: {{\"id\":\"{response_id}\","
|
||||
f"\"object\":\"chat.completion.chunk\","
|
||||
f"\"created\":{created},"
|
||||
f"\"model\":\"{request.model or CHAT_MODEL}\","
|
||||
f"\"choices\":[{{\"index\":0,\"delta\":{{"
|
||||
f"\"role\":\"assistant\"}},\"finish_reason\":null}}]}}\n\n"
|
||||
)
|
||||
|
||||
import json
|
||||
|
||||
yield (
|
||||
"data: "
|
||||
+ json.dumps(
|
||||
{
|
||||
"id": response_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {"content": answer},
|
||||
"finish_reason": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ "\n\n"
|
||||
)
|
||||
+ "\n\n"
|
||||
)
|
||||
|
||||
yield (
|
||||
"data: "
|
||||
+ json.dumps(
|
||||
{
|
||||
"id": response_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
}
|
||||
yield (
|
||||
"data: "
|
||||
+ json.dumps(
|
||||
{
|
||||
"id": response_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": request.model or CHAT_MODEL,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
+ "\n\n"
|
||||
)
|
||||
+ "\n\n"
|
||||
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
)
|
||||
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise HTTPException(
|
||||
status_code=504,
|
||||
detail="Tempo esgotado ao consultar serviço interno.",
|
||||
) from exc
|
||||
except httpx.HTTPStatusError as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="Falha em serviço interno.",
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Erro interno no RAG.",
|
||||
) from exc
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue