Semantix-verify
Valida cada salida de LLM frente a una intención explícita. Obtén una puntuación, un veredicto y un recibo a prueba de manipulaciones. Localmente. En ~15-50 milisegundos. Sin una clave de API.
pip install semantix-aifrom semantix import Intent, validate_intent
class ResolutionPolite(Intent):
"""The response must acknowledge the customer's issue and propose a concrete next step, in a polite tone."""
@validate_intent(ResolutionPolite, audit=True)
def handle_complaint(message: str) -> str:
return call_my_llm(message)
reply = handle_complaint(incoming)
# Returns the validated reply — or raises SemanticIntentError.
# The audit engine has already written a hash-chained receipt to disk.Por qué existe esto
Las aplicaciones de LLM omiten silenciosamente el paso en el que se demuestra que la salida era adecuada para su propósito. La solución común —llamar a un LLM más grande como juez— tiene tres problemas:
Deriva. La misma entrada, diferente puntuación en diferentes ejecuciones. Un regulador que pide "volver a ejecutar esta validación" obtiene una respuesta diferente, lo cual es indistinguible de una prueba de que el sistema está roto.
Envía información personal fuera de tu red. Cada llamada al juez envía la salida a una API de terceros. Bajo POPIA §72 (o GDPR Art. 44, o las obligaciones de sistemas de alto riesgo de la Ley de IA de la UE), eso es un problema que debe documentarse, no un valor predeterminado.
No produce ningún recibo. La validación ocurrió, se obtuvo una puntuación, nada se registró en una forma que sobreviva a una auditoría.
semantix reemplaza ese reflejo con un validador local y determinista y un registro a prueba de manipulaciones. Cada validación produce un certificado JSON-LD firmado encadenado mediante hash al anterior. Modifica cualquier entrada y cada hash posterior se rompe. El regulador no necesita confiar en tu base de datos: las matemáticas prueban que la cadena está intacta.
Related MCP server: agentvet-mcp
Qué obtienes
1. Validación como decorador
from semantix import Intent, validate_intent
class MedicalAdvice(Intent):
"""The text provides a medical diagnosis or treatment recommendation."""
@validate_intent(~MedicalAdvice) # Must NOT give medical advice
def chatbot(msg: str) -> str:
return call_my_llm(msg)Compón con & (todos deben pasar) y | (al menos uno debe pasar):
SafeAndPolite = Polite & ~MedicalAdvice & ~LegalAdvice2. Pista de auditoría a prueba de manipulaciones
from semantix.audit.engine import AuditEngine
engine = AuditEngine()
# Every @validate_intent call with audit=True writes a hash-chained certificate.
engine.verify_chain() # True if no tamperingCada certificado registra el hash del texto validado, la intención, la identidad y configuración del juez, el veredicto, la marca de tiempo y el hash del certificado anterior. Compatible con herramientas JSON-LD y tuberías de auditoría estándar.
3. Reintentos de autocuración
En caso de fallo, semantix inyecta retroalimentación estructurada para que el LLM sepa qué salió mal:
from typing import Optional
@validate_intent(ResolutionPolite, retries=2)
def reply(msg: str, semantix_feedback: Optional[str] = None) -> str:
prompt = f"Reply to: {msg}"
if semantix_feedback:
prompt += f"\n\n{semantix_feedback}"
return call_llm(prompt)Primera llamada: semantix_feedback es None. En el reintento: recibe un informe en Markdown con la puntuación, la razón y la salida rechazada. La fiabilidad medida mejora del 21% al 70% en tres categorías de intención.
4. Atribución forense a nivel de token
from semantix import ForensicJudge, QuantizedNLIJudge
judge = ForensicJudge(QuantizedNLIJudge())
# Verdict.reason: "Suspect tokens: [indemnify, forfeit, waive]"5. Integración con pytest
from semantix.testing import assert_semantic
def test_chatbot_is_polite():
response = my_chatbot("handle angry customer")
assert_semantic(response, "polite and professional")En caso de fallo:
AssertionError: Semantic check failed (score=0.12)
Intent: polite and professional
Output: "You're an idiot for asking that."
Reason: Text contains aggressive languagePlugin de pytest de primera clase con fixtures, marcadores e informes de CI: pytest-semantix.
Integraciones de frameworks
Incorpora a tu stack existente: los reintentos son manejados de forma nativa por cada framework.
DSPy
import dspy
from semantix.integrations.dspy import semantic_reward
qa = dspy.ChainOfThought("question -> answer")
refined = dspy.Refine(module=qa, N=3, reward_fn=semantic_reward(Polite))semantic_reward / semantic_metric también se conectan a dspy.BestOfN, dspy.Evaluate y MIPROv2: local, sin llamadas a API, ~15 ms por evaluación. Consulta benchmarks/ para comparaciones reproducibles frente a funciones de recompensa de LLM-judge.
from semantix.integrations.langchain import SemanticValidator
validator = SemanticValidator(Polite)
chain = prompt | llm | StrOutputParser() | validatorfrom pydantic_ai import Agent
from semantix.integrations.pydantic_ai import semantix_validator
agent = Agent("openai:gpt-4o", output_type=str)
agent.output_validator(semantix_validator(Polite))from guardrails import Guard
from semantix.integrations.guardrails import SemanticIntent
guard = Guard().use(SemanticIntent("must be polite and professional"))from semantix.integrations.instructor import SemanticStr
from pydantic import BaseModel
class Response(BaseModel):
reply: SemanticStr["must be polite and professional", 0.85]pip install "semantix-ai[mcp,nli]"
mcp run semantix/mcp/server.pyCualquier agente compatible con MCP (Claude Desktop, Cursor, etc.) puede validar intenciones como una herramienta.
- uses: labrat-akhona/semantic-test-action@v1
with:
test-path: tests/Publica un informe de prueba semántica como comentario en un PR.
Instala extras: pip install "semantix-ai[dspy]", "[langchain]", "[pydantic-ai]", "[guardrails]", "[instructor]", "[mcp]", "[all]".
Jueces conectables
Elige el equilibrio entre velocidad / precisión / razonamiento:
from semantix import NLIJudge, EmbeddingJudge, LLMJudge, CachingJudge
@validate_intent(judge=NLIJudge()) # local, ~15 ms, deterministic
@validate_intent(judge=EmbeddingJudge()) # local, ~5 ms, similarity-based
@validate_intent(judge=LLMJudge(model="gpt-4o-mini")) # reasoning, ~500 ms, API
@validate_intent(judge=CachingJudge(NLIJudge(), maxsize=256)) # LRU-wrappedModo cuantizado (INT8 ONNX, ~25 MB, sin PyTorch):
pip install "semantix-ai[turbo]"Cuándo es esta la herramienta adecuada
Estás ejecutando un sistema respaldado por LLM que procesa información personal y necesitas un paso de validación auditable.
Estás optimizando un programa DSPy y el bucle de recompensa de LLM-judge es demasiado lento, demasiado caro o demasiado no determinista.
Necesitas aserciones de prueba semántica en pytest / CI que no llamen a una API de pago.
Estás en una industria regulada (servicios financieros, seguros, atención médica) y "el modelo dijo que estaba bien" no es una respuesta defendible.
Cuándo no lo es
Tu intención de validación requiere razonamiento de múltiples saltos o conocimiento del mundo ("¿es esto conforme con la sección 4(b) del código fiscal de 2026?"). NLI no puede hacer esto; los LLM de razonamiento sí.
Necesitas que el juez explique por qué en prosa, no solo que dé una puntuación.
Estás evaluando menos de 100 salidas por mes y la latencia / costo de LLM-as-judge no importa.
Consulta Dónde encaja semantix para una comparación frente a TruLens, DeepEval, Vectara HHEM, Guardrails, RAGAS y NeMo.
Propiedades clave
Inferencia local — El modelo NLI se ejecuta en la CPU, ningún dato sale de tu máquina.
Determinista — misma entrada, misma puntuación, siempre, en cada máquina. Se puede establecer semilla.
Rápido — ~15-50 ms por verificación con el juez cuantizado.
Costo de API cero — no se queman tokens para la validación.
Auditable — certificados JSON-LD encadenados mediante hash por verificación.
Bien probado — 249 pruebas, con licencia MIT.
Instalación
pip install semantix-ai # Core (default NLI judge)
pip install "semantix-ai[turbo]" # Quantized ONNX (smallest footprint)
pip install "semantix-ai[openai]" # LLM judge (GPT-4o-mini)
pip install "semantix-ai[all]" # EverythingEl nombre del paquete en PyPI es
semantix-ai. La importación esfrom semantix import ....
Contribución
Consulta CONTRIBUTING.md para la configuración de desarrollo, pruebas y pautas de envío.
Licencia
MIT — consulta LICENSE.
Available Tools
1 toolverify_text_intentA
Check whether text satisfies a semantic intent using NLI.
Args:
text: The text to verify.
intent_description: What the text should convey.
threshold: Minimum entailment score to pass (0-1, default 0.5).
Returns:
JSON with score, passed, reason, and correction_suggestion on failure.
Inputs: text (required), intent_description (required), threshold. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 1 tool
With only one tool, there is no potential for confusion between tools. The single tool has a clearly distinct purpose.
Only one tool exists, so naming consistency is not an issue. The tool name 'verify_text_intent' follows a clear verb_noun pattern.
One tool is borderline appropriate for a focused verification utility. While minimal, it covers the core functionality without being trivial.
The tool effectively covers the primary task of text intent verification, including correction suggestions. Minor gaps exist (e.g., no batch verification or intent listing), but the set is complete for the stated purpose.
Maintenance
Related MCP Connectors
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
MCP server providing access to the Scorecard API to evaluate and optimize LLM systems.
Impri MCP server — human-in-the-loop approval inbox for AI agents
MCP server for progressive tool usage at any scale (see https://klavis.ai)
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA lightweight MCP server that enables intelligent tool management and semantic search for APIs using sentence-transformers. It supports both REST and MCP interfaces across dual transport modes, allowing users to upload, manage, and query API tools with natural language.1MIT
- AlicenseAqualityDmaintenanceMCP server that validates LLM-generated tool-call arguments, lints tool definitions, and produces retry messages for AI assistants.346 npm1MIT
- AlicenseAqualityBmaintenanceMCP server for verifying AI agent claims vs reality — single-transcript inline grounding-check that flags when an agent's response states facts not in the input context, when its code silently swallows exceptions and substitutes mock data, or when its multi-turn transcript contains contradictions or unverified completion claims. Sub-second, local, free, no API calls.424 PyPI1MIT
- AlicenseAqualityBmaintenanceA local MCP server that packages LLM evaluation gates as reusable CI/CD primitives, enabling AI agents to run datasets against models, score responses, and enforce quality thresholds.1079 PyPIMIT