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.
| Name | Required | Description | Default |
|---|---|---|---|
| text | Yes | ||
| threshold | No | ||
| intent_description | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided. Description reveals it returns JSON with score, passed, reason, and correction_suggestion, which implies inference without side effects. However, it does not explicitly state whether it's read-only or if it has any side effects, leaving some ambiguity.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Description is relatively concise, with parameter list and return format. Could be slightly more compact, but no wasted sentences.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Has output schema (though not shown), and description covers return fields adequately. Missing usage guidelines reduces completeness. For a simple 3-parameter tool, it's sufficient but not thorough.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema documentation coverage is 0%, so description must explain parameters. It does so: text is 'the text to verify', intent_description is 'what the text should convey', threshold is 'minimum entailment score' with default. This adds meaningful context beyond schema structure.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Description clearly states 'Check whether text satisfies a semantic intent using NLI.' Specifies verb, resource, and method (NLI). No sibling tools, so differentiation is not needed.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use this tool versus alternatives. No mention of prerequisites, limitations, or when not to use it. The description solely explains what it does without usage context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
- First observed
verify_text_intent
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 providing access to the Scorecard API to evaluate and optimize LLM systems.
MCP server for progressive tool usage at any scale (see https://klavis.ai)
MCP server for AI agents to plan, verify, and deploy Cloudflare-native apps.
Deterministic validation for AI-generated artifacts: JSON Schema, OpenAPI response, SQL syntax.
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.325 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.41MIT
- AlicenseAqualityCmaintenanceA 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.10MIT