Skip to main content
Glama

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-ai
from 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:

  1. 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.

  2. 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.

  3. 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 & ~LegalAdvice

2. 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 tampering

Cada 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 language

Plugin 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() | validator
from 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.py

Cualquier 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-wrapped

Modo 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]"             # Everything

El nombre del paquete en PyPI es semantix-ai. La importación es from 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 tool
verify_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

    A3.8/5.0

    Scored across 1 tool

    Disambiguation5/5

    With only one tool, there is no potential for confusion between tools. The single tool has a clearly distinct purpose.

    Naming Consistency5/5

    Only one tool exists, so naming consistency is not an issue. The tool name 'verify_text_intent' follows a clear verb_noun pattern.

    Tool Count3/5

    One tool is borderline appropriate for a focused verification utility. While minimal, it covers the core functionality without being trivial.

    Completeness4/5

    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

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A 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.
      1
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      MCP 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.
      4
      24 PyPI
      1
      MIT