First Commit

This commit is contained in:
2026-04-28 00:09:01 -03:00
parent 69c5060037
commit 8810f2e2e8
37 changed files with 1273 additions and 1 deletions

View File

@@ -0,0 +1,122 @@
from .deterministic_rails import mask_pii, validar_alcada, enforce_compliance_anatel
from .llm_rails import detectar_toxicidade, detectar_out_of_scope, validar_groundedness, verbalizacao_prematura, supervisor_vas_avulso
from .judges import avaliar_qualidade_resposta
import json
def executar_atendimento(user_input: str, context: dict):
steps = []
# INPUT RAILS
r = mask_pii(user_input)
steps.append(r)
text = r.sanitized_text or user_input
for rail in [detectar_toxicidade, detectar_out_of_scope]:
r = rail(text)
steps.append(r)
if not r.allowed:
return {
"allowed": False,
"blocked_by": r.code,
"steps": steps
}
# PYTHON RULE
if "ajuste_valor" in context:
r = validar_alcada(context["ajuste_valor"])
steps.append(r)
if not r.allowed:
return {
"allowed": False,
"blocked_by": r.code,
"steps": steps
}
# LLM RESPONSE (simulada ou real)
resposta = context.get("resposta_llm", "Resposta simulada do agente.")
# OUTPUT + JUDGES + SUPERVISOR
for r in [
verbalizacao_prematura(resposta, context),
enforce_compliance_anatel(resposta, context),
validar_groundedness(resposta, context),
avaliar_qualidade_resposta(user_input, resposta),
supervisor_vas_avulso(context.get("supervisor_payload", {}))
]:
steps.append(r)
return {
"allowed": all(s.allowed for s in steps if s.code != "RQLT"),
"response": resposta,
"steps": steps
}
# =========================
# 🔥 EXECUÇÃO DIRETA
# =========================
def print_result(result):
print("\n" + "=" * 80)
print("📊 RESULTADO FINAL")
print("=" * 80)
print(f"✔ Allowed: {result['allowed']}")
print(f"💬 Response: {result.get('response')}")
if not result["allowed"]:
print(f"🚫 Bloqueado por: {result.get('blocked_by')}")
print("\n🔎 STEPS:")
for s in result["steps"]:
print("-" * 60)
print(f"🧩 Code: {s.code}")
print(f"⚙️ Mechanism: {s.mechanism}")
print(f"✔ Allowed: {s.allowed}")
print(f"📝 Reason: {s.reason}")
if s.sanitized_text:
print(f"🔐 Sanitized: {s.sanitized_text}")
if s.data:
print(f"📦 Data: {s.data}")
print("=" * 80)
# JSON final (para integração)
print("\n📦 JSON OUTPUT:")
print(json.dumps({
"allowed": result["allowed"],
"response": result.get("response"),
"steps": [
{
"code": s.code,
"allowed": s.allowed,
"reason": s.reason,
"mechanism": s.mechanism,
"data": s.data
}
for s in result["steps"]
]
}, indent=2, ensure_ascii=False))
if __name__ == "__main__":
# 🔧 EXEMPLO DE EXECUÇÃO
user_input = "Meu CPF é 123.456.789-00 e quero ajuste de 20 reais"
context = {
"ajuste_valor": 20,
"ajuste_validado": True,
"tipo_fluxo": "ajuste",
"requer_protocolo": True,
"resposta_llm": "Ajuste realizado. Protocolo: 202604270001.",
"chunks_rag": ["serviço fatura cobrança ajuste realizado protocolo"],
"supervisor_payload": {
"cancelamento_correto": True,
"servico_cancelado": "VAS Avulso",
"servico_solicitado": "VAS Avulso"
}
}
result = executar_atendimento(user_input, context)
print_result(result)

View File

@@ -0,0 +1,66 @@
import re
from collections import Counter
from .models import RailResult
from .tracing import span
def mask_pii(text:str)->RailResult:
with span('rail.MSK', mechanism='regex'):
original=text
text=re.sub(r'\b\d{3}\.\d{3}\.\d{3}-\d{2}\b','[CPF_MASCARADO]',text)
text=re.sub(r'\b\d{16}\b','[CARTAO_MASCARADO]',text)
text=re.sub(r'(?i)(senha\s*[:=]?\s*)\S+',r'\1[SENHA_MASCARADA]',text)
return RailResult(True,'PII mascarada' if text!=original else 'Nenhuma PII detectada',text,'MSK','regex')
def enforce_compliance_anatel(text:str, context:dict)->RailResult:
with span('rail.CMP', mechanism='regex'):
requer=context.get('tipo_fluxo')=='ajuste' or context.get('requer_protocolo') is True
if not requer: return RailResult(True,'Compliance Anatel não aplicável',text,'CMP','regex')
has_protocol=bool(re.search(r'(?i)\bprotocolo\b[:\s-]*\d{6,}',text))
if not has_protocol: return RailResult(False,'Resposta de ajuste sem número de protocolo',text,'CMP','regex')
return RailResult(True,'Resposta contém protocolo obrigatório',text,'CMP','regex')
def validar_alcada(valor:float, limite:float=50.0)->RailResult:
with span('rail.ADJ', mechanism='python'):
if valor>limite: return RailResult(False,f'Valor R$ {valor:.2f} excede alçada de R$ {limite:.2f}; escalar para ATH',code='ADJ',mechanism='python')
return RailResult(True,f'Valor R$ {valor:.2f} dentro da alçada',code='ADJ',mechanism='python')
def calcular_tcr(status:str)->RailResult:
status=status.lower(); categoria='Indefinido'
if status in ['concluido','concluído','resolvido']: categoria='Concluído'
elif status in ['abandonado','timeout','desistencia']: categoria='Abandonado'
elif status in ['escalado','ath','humano']: categoria='Escalado'
return RailResult(True,f'TCR classificado como {categoria}',code='TCR',mechanism='python',data={'categoria':categoria})
def detectar_fallback(text:str)->RailResult:
frases=['não entendi','não consegui entender','não tenho informação','não encontrei informação']; detected=any(f in text.lower() for f in frases)
return RailResult(True,'Fallback detectado' if detected else 'Fallback não detectado',text,'FALLBACK','python',{'fallback':detected})
def registrar_violacao(agent_id:str, code:str)->RailResult:
return RailResult(True,'Violação registrada para agregação',code='VIOL',mechanism='python',data={'agent_id':agent_id,'violation_code':code,'count':1})
def validar_consistencia_historica(context:dict)->RailResult:
if context.get('contestacao_anterior')=='procedente_confirmada': return RailResult(False,'Fatura já confirmada como procedente anteriormente',code='HIST',mechanism='python')
return RailResult(True,'Sem conflito histórico',code='HIST',mechanism='python')
def contabilizar_tokens(prompt_tokens:int, completion_tokens:int)->RailResult:
total=prompt_tokens+completion_tokens; return RailResult(True,'Tokens contabilizados',code='PMPTK',mechanism='python',data={'prompt_tokens':prompt_tokens,'completion_tokens':completion_tokens,'total_tokens':total})
def calcular_eficiencia_nlu(chunks_retornados:int, chunks_utilizados:int)->RailResult:
eficiencia=chunks_utilizados/chunks_retornados if chunks_retornados else 0; return RailResult(True,'Eficiência NLU calculada',code='EFIC',mechanism='python',data={'eficiencia':eficiencia})
def detectar_no_match_rag(chunks:list, resposta:str)->RailResult:
no_match=not chunks or 'não encontrei' in resposta.lower(); return RailResult(True,'No-Match RAG detectado' if no_match else 'RAG retornou evidência útil',code='NO-M',mechanism='python',data={'no_match':no_match})
def detectar_loop(mensagens:list[str])->RailResult:
counts=Counter(mensagens); loop=any(v>=2 for v in counts.values()); return RailResult(True,'Loop detectado' if loop else 'Sem loop',code='VLOOP',mechanism='python',data={'loop':loop})
def medir_tamanho_mensagem(text:str)->RailResult:
return RailResult(True,'Tamanho de mensagem medido',text,'MSIZE','python',{'chars':len(text)})
def calcular_precisao_revocacao(y_true:list[str], y_pred:list[str])->RailResult:
total=len(y_true); correct=sum(1 for a,b in zip(y_true,y_pred) if a==b); accuracy=correct/total if total else 0
return RailResult(True,'Acurácia de roteamento calculada',code='REVPREC_METRIC',mechanism='python',data={'accuracy':accuracy})
def avaliar_acuracia_semantica(audio_transcrito:str, referencia_humana:str)->RailResult:
a=set(audio_transcrito.lower().split()); b=set(referencia_humana.lower().split()); score=len(a & b)/len(b) if b else 0
return RailResult(score>=0.85,f'Acurácia semântica STT: {score:.2f}',code='SEMAC',mechanism='python',data={'score':score})

View File

@@ -0,0 +1,16 @@
from .models import RailResult
from .llm_client import LLMClient
from .tracing import span
_client=LLMClient()
def classificar_sentimento(text:str)->RailResult:
with span("judge.CSI", mechanism="llm_judge"):
out=_client.classify("CSI", {"text":text}); return RailResult(True,out.get("reason",""),text,"CSI","llm_judge",{"sentimento":out.get("label"),**out})
def avaliar_alucinacao(resposta:str, dados_reais:str)->RailResult:
with span("judge.ALUC", mechanism="llm_judge"):
out=_client.classify("ALUC", {"resposta":resposta,"dados_reais":dados_reais}); return RailResult(out["allowed"],out.get("reason",""),resposta,"ALUC","llm_judge",{"alucinacao":out.get("label")=="ALUCINACAO",**out})
def avaliar_qualidade_resposta(pergunta:str, resposta:str)->RailResult:
with span("judge.RQLT", mechanism="llm_judge"):
out=_client.classify("RQLT", {"pergunta":pergunta,"resposta":resposta}); return RailResult(True,out.get("reason",""),resposta,"RQLT","llm_judge",out)
def avaliar_tom_de_voz(text:str)->RailResult:
with span("judge.VCTN", mechanism="llm_judge"):
out=_client.classify("VCTN", {"text":text}); return RailResult(out["allowed"],out.get("reason",""),text,"VCTN","llm_judge",{"aderente":out["allowed"],**out})

View File

@@ -0,0 +1,106 @@
import os, json
from openai import OpenAI
from src.prompts.revprec import build_revprec_prompt
from src.prompts.csi import build_csi_prompt
from src.prompts.vctn import build_vctn_prompt
from src.prompts.tox import build_tox_prompt
from src.prompts.oos import build_oos_prompt
from src.prompts.gnd import build_gnd_prompt
from src.prompts.aluc import build_aluc_prompt
from src.prompts.rqlt import build_rqlt_prompt
from src.prompts.supervisor import build_supervisor_prompt
class LLMClient:
def __init__(self):
self.use_mock=os.getenv('USE_MOCK_LLM','true').lower()=='true'
self.model=os.getenv('OPENAI_MODEL','gpt-4.1')
self.client=None if self.use_mock else OpenAI(base_url=os.getenv('OPENAI_BASE_URL','http://localhost:8051/v1'), api_key=os.getenv('OPENAI_API_KEY','dummy'))
def classify(self, task, payload):
if self.use_mock:
return self._mock_classify(task, payload)
# ========================
# ROUTING DE PROMPTS
# ========================
if task == "REVPREC":
prompt = build_revprec_prompt(payload["text"], payload.get("context", {}))
elif task == "CSI":
prompt = build_csi_prompt(payload["text"])
elif task == "VCTN":
prompt = build_vctn_prompt(payload["text"])
elif task == "TOX":
prompt = build_tox_prompt(payload["text"])
elif task == "OOS":
prompt = build_oos_prompt(payload["text"])
elif task == "GND":
prompt = build_gnd_prompt(payload["resposta"], payload.get("context", {}))
# ========================
# 🔥 NOVOS (faltavam)
# ========================
elif task == "ALUC":
prompt = build_aluc_prompt(payload["resposta"], payload["dados_reais"])
elif task == "RQLT":
prompt = build_rqlt_prompt(payload["pergunta"], payload["resposta"])
elif task == "SUPERVISOR_VAS":
prompt = build_supervisor_prompt(payload)
else:
raise ValueError(f"Task não suportada: {task}")
# ========================
# CALL LLM
# ========================
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}],
temperature=0
)
import json
text = response.choices[0].message.content
try:
return json.loads(text)
except:
return {
"allowed": False,
"label": "ERROR",
"reason": text
}
def _mock(self, task, payload):
text=(payload.get('text') or payload.get('resposta') or payload.get('answer') or '').lower()
if task=='TOX':
bad=any(w in text for w in ['idiota','burro','lixo','inútil','ofensivo']); return {'allowed':not bad,'label':'TOXICO' if bad else 'NORMAL','reason':'mock TOX','score':0 if bad else 10}
if task=='OOS':
bad=any(w in text for w in ['política','religião','presidente','concorrente','vivo','claro']); return {'allowed':not bad,'label':'OUT_OF_SCOPE' if bad else 'IN_SCOPE','reason':'mock OOS','score':0 if bad else 10}
if task=='REVPREC':
validated=payload.get('context',{}).get('ajuste_validado',False); premature=any(w in text for w in ['já fiz','já realizei','foi realizado','ajuste aplicado','cancelamento realizado'])
return {'allowed':not(premature and not validated),'label':'PREMATURA' if premature and not validated else 'OK','reason':'mock REVPREC','score':0 if premature and not validated else 10}
if task=='GND':
chunks=' '.join(payload.get('context',{}).get('chunks_rag',[])).lower(); overlap=len(set(text.split()) & set(chunks.split())); ok=overlap>=3
return {'allowed':ok,'label':'GROUNDED' if ok else 'UNGROUNDED','reason':f'mock GND overlap={overlap}','score':min(10,overlap)}
if task=='CSI':
if any(w in text for w in ['insatisfeito','raiva','péssimo','cancelar']): return {'allowed':True,'label':'Negativo','reason':'mock CSI','score':3}
if any(w in text for w in ['obrigado','ótimo','resolvido','satisfeito']): return {'allowed':True,'label':'Positivo','reason':'mock CSI','score':9}
return {'allowed':True,'label':'Neutro','reason':'mock CSI','score':6}
if task=='ALUC':
overlap=len(set(payload.get('resposta','').lower().split()) & set(payload.get('dados_reais','').lower().split())); hallucinated=overlap<2
return {'allowed':not hallucinated,'label':'ALUCINACAO' if hallucinated else 'OK','reason':f'mock ALUC overlap={overlap}','score':0 if hallucinated else 8}
if task=='RQLT':
resposta=payload.get('resposta',''); score=8 if len(resposta)>30 else 3; return {'allowed':True,'label':'QUALIDADE','reason':'mock RQLT','score':score}
if task=='VCTN':
bad=any(w in text for w in ['se vira','problema seu','não posso fazer nada']); return {'allowed':not bad,'label':'TOM_INADEQUADO' if bad else 'TOM_OK','reason':'mock VCTN','score':0 if bad else 9}
if task=='SUPERVISOR_VAS':
ok=payload.get('cancelamento_correto',False) and payload.get('servico_cancelado')==payload.get('servico_solicitado'); return {'allowed':ok,'label':'CONFORME' if ok else 'PROBLEMA','reason':'mock supervisor','score':10 if ok else 0}
return {'allowed':True,'label':'OK','reason':'mock default','score':5}

View File

@@ -0,0 +1,20 @@
from .models import RailResult
from .llm_client import LLMClient
from .tracing import span
_client=LLMClient()
def detectar_toxicidade(text:str)->RailResult:
with span("rail.TOX", mechanism="llm_rail"):
out=_client.classify("TOX", {"text":text}); return RailResult(out["allowed"],out.get("reason",""),text,"TOX","llm_rail",out)
def detectar_out_of_scope(text:str)->RailResult:
with span("rail.OOS", mechanism="llm_rail"):
out=_client.classify("OOS", {"text":text}); return RailResult(out["allowed"],out.get("reason",""),text,"OOS","llm_rail",out)
def verbalizacao_prematura(text:str, context:dict)->RailResult:
with span("rail.REVPREC", mechanism="llm_rail"):
out=_client.classify("REVPREC", {"text":text,"context":context}); return RailResult(out["allowed"],out.get("reason",""),text,"REVPREC","llm_rail",out)
def validar_groundedness(resposta:str, context:dict)->RailResult:
with span("rail.GND", mechanism="llm_rail"):
out=_client.classify("GND", {"resposta":resposta,"context":context}); return RailResult(out["allowed"],out.get("reason",""),resposta,"GND","llm_rail",out)
def supervisor_vas_avulso(payload:dict)->RailResult:
with span("supervisor.REVPREC_SUP", mechanism="llm_supervisor"):
out=_client.classify("SUPERVISOR_VAS", payload); return RailResult(out["allowed"],out.get("reason",""),code="REVPREC_SUP",mechanism="llm_supervisor",data=out)

View File

@@ -0,0 +1,10 @@
from dataclasses import dataclass
from typing import Any
@dataclass
class RailResult:
allowed: bool
reason: str
sanitized_text: str | None = None
code: str | None = None
mechanism: str | None = None
data: dict[str, Any] | None = None

View File

@@ -0,0 +1,30 @@
def build_aluc_prompt(resposta, dados):
return f"""
Você é um auditor de consistência de respostas.
Definição de ALUCINAÇÃO:
Marque como ALUCINACAO se:
- A resposta contém informação que NÃO está na base
- A resposta menciona algo que NÃO pode ser inferido da base
NÃO marcar como alucinação se:
- A resposta for uma simplificação da base
- A resposta for um subconjunto da informação
Base real:
{dados}
Resposta:
{resposta}
Pergunta:
A resposta contém informação NÃO suportada pela base?
Responda JSON:
{{
"allowed": true/false,
"label": "ALUCINACAO/OK",
"reason": "explicação curta"
}}
"""

View File

@@ -0,0 +1,18 @@
def build_csi_prompt(text):
return f"""
Classifique o sentimento do cliente.
Texto:
{text}
Opções:
- Positivo
- Neutro
- Negativo
Responda JSON:
{{
"sentimento": "Positivo/Neutro/Negativo",
"score": 0-10
}}
"""

View File

@@ -0,0 +1,16 @@
def build_gnd_prompt(resposta, context):
return f"""
Verifique se a resposta está fundamentada.
Resposta:
{resposta}
Base:
{context.get("chunks_rag", [])}
Responda:
{{
"allowed": true/false,
"label": "GROUNDED/UNGROUNDED"
}}
"""

View File

@@ -0,0 +1,18 @@
def build_oos_prompt(text):
return f"""
Verifique se o texto está fora do escopo de Telecom.
Texto:
{text}
Fora de escopo:
- política
- religião
- concorrentes
Responda JSON:
{{
"allowed": true/false,
"label": "IN_SCOPE/OUT_OF_SCOPE"
}}
"""

View File

@@ -0,0 +1,24 @@
def build_revprec_prompt(text, context):
return f"""
Você é um auditor de atendimento ao cliente.
Regra:
- O agente NÃO pode afirmar que executou uma ação
- SE essa ação NÃO foi validada previamente
Contexto:
ajuste_validado = {context.get("ajuste_validado")}
Texto do agente:
{text}
Pergunta:
O agente cometeu verbalização prematura?
Responda JSON:
{{
"allowed": true/false,
"label": "OK" ou "PREMATURA",
"reason": "explicação curta"
}}
"""

View File

@@ -0,0 +1,31 @@
def build_rqlt_prompt(pergunta, resposta):
return f"""
Você é um avaliador de qualidade de respostas de atendimento.
Pergunta:
{pergunta}
Resposta:
{resposta}
Critérios:
1. Clareza (0-3)
2. Completude (0-3)
3. Utilidade (0-4)
Regras IMPORTANTES:
- Se a resposta explica corretamente o motivo → score mínimo 6
- Se a resposta é clara e útil → score entre 7 e 9
- Se a resposta é vaga ("não sei", "verifique") → score < 5
- NÃO penalizar respostas curtas se estiverem corretas
Agora avalie.
Responda APENAS JSON:
{{
"score": 0-10,
"reason": "explicação curta"
}}
"""

View File

@@ -0,0 +1,21 @@
def build_supervisor_prompt(payload):
return f"""
Você é um auditor de atendimento.
Verifique se o cancelamento foi correto.
Solicitado:
{payload.get("servico_solicitado")}
Cancelado:
{payload.get("servico_cancelado")}
Se forem diferentes → PROBLEMA
Responda JSON:
{{
"allowed": true/false,
"label": "CONFORME/PROBLEMA",
"reason": "explicação"
}}
"""

View File

@@ -0,0 +1,17 @@
def build_tox_prompt(text):
return f"""
Classifique o texto abaixo:
Texto:
{text}
Classifique como:
- TOXICO
- NORMAL
Responda JSON:
{{
"allowed": true/false,
"label": "TOXICO/NORMAL"
}}
"""

View File

@@ -0,0 +1,22 @@
def build_vctn_prompt(text):
return f"""
Avalie o tom de voz do agente.
Regra:
- Deve ser educado
- Não pode ser rude ou agressivo
Texto:
{text}
Classifique:
- Adequado
- Inadequado
Responda JSON:
{{
"allowed": true/false,
"label": "Adequado/Inadequado",
"reason": "explicação"
}}
"""

View File

@@ -0,0 +1,5 @@
from pathlib import Path
import yaml
def load_guardrail_registry(path=None):
if path is None: path=Path(__file__).resolve().parent.parent/'config'/'guardrails.yaml'
with open(path,'r',encoding='utf-8') as f: return yaml.safe_load(f)['guardrails']

View File

@@ -0,0 +1,21 @@
import os
from contextlib import contextmanager
_TRACING_ENABLED=os.getenv("ENABLE_TRACING","false").lower()=="true"
try:
if _TRACING_ENABLED:
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
provider=TracerProvider(); endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT","http://localhost:6006/v1/traces")
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint)))
trace.set_tracer_provider(provider); tracer=trace.get_tracer("nemo_guardrails_governed_project")
else: tracer=None
except Exception: tracer=None
@contextmanager
def span(name:str, **attrs):
if tracer is None:
yield None; return
with tracer.start_as_current_span(name) as sp:
for k,v in attrs.items(): sp.set_attribute(k,str(v))
yield sp