Semantix-verify
Validieren Sie jede LLM-Ausgabe gegen eine explizite Absicht. Erhalten Sie einen Score, ein Urteil und einen manipulationssicheren Beleg. Lokal. In ca. 15–50 Millisekunden. Ohne API-Schlüssel.
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.Warum existiert dies?
LLM-Anwendungen überspringen stillschweigend den Schritt, in dem Sie nachweisen, dass die Ausgabe zweckmäßig war. Die gängige Lösung – ein größeres LLM als Richter aufzurufen – hat drei Probleme:
Es driftet. Gleiche Eingabe, unterschiedlicher Score bei verschiedenen Durchläufen. Eine Aufsichtsbehörde, die fragt „Führen Sie diese Validierung erneut aus“, erhält eine andere Antwort, die nicht von einem Beweis dafür zu unterscheiden ist, dass das System defekt ist.
Es versendet persönliche Informationen aus Ihrem Netzwerk. Jeder Richter-Aufruf sendet die Ausgabe an eine API eines Drittanbieters. Gemäß POPIA §72 (oder DSGVO Art. 44 oder den Verpflichtungen des EU AI Act für Hochrisikosysteme) ist das ein Problem, das dokumentiert werden muss, kein Standard.
Es erzeugt keinen Beleg. Die Validierung fand statt, ein Score kam zurück, nichts wurde in einer Form aufgezeichnet, die eine Prüfung übersteht.
semantix ersetzt diesen Reflex durch einen lokalen, deterministischen Validator und ein manipulationssicheres Protokoll. Jede Validierung erzeugt ein signiertes JSON-LD-Zertifikat, das per Hash-Kette mit dem vorherigen verknüpft ist. Ändern Sie einen Eintrag und jeder nachfolgende Hash bricht. Die Aufsichtsbehörde muss Ihrer Datenbank nicht vertrauen – die Mathematik beweist, dass die Kette intakt ist.
Related MCP server: agentvet-mcp
Was Sie erhalten
1. Validierung als Dekorator
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)Kombinieren Sie mit & (alle müssen bestehen) und | (eines muss bestehen):
SafeAndPolite = Polite & ~MedicalAdvice & ~LegalAdvice2. Manipulationssicherer Audit-Trail
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 tamperingJedes Zertifikat zeichnet den Hash des validierten Textes, die Absicht, die Identität und Konfiguration des Richters, das Urteil, den Zeitstempel und den Hash des vorherigen Zertifikats auf. Kompatibel mit JSON-LD-Tools und Standard-Audit-Pipelines.
3. Selbstheilende Wiederholungen
Bei einem Fehler fügt semantix strukturiertes Feedback ein, damit das LLM weiß, was schiefgelaufen ist:
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)Erster Aufruf: semantix_feedback ist None. Bei Wiederholung: Es erhält einen Markdown-Bericht mit dem Score, dem Grund und der abgelehnten Ausgabe. Die gemessene Zuverlässigkeit verbessert sich über drei Absichtskategorien hinweg von 21 % auf 70 %.
4. Forensische Attribution auf Token-Ebene
from semantix import ForensicJudge, QuantizedNLIJudge
judge = ForensicJudge(QuantizedNLIJudge())
# Verdict.reason: "Suspect tokens: [indemnify, forfeit, waive]"5. pytest-Integration
from semantix.testing import assert_semantic
def test_chatbot_is_polite():
response = my_chatbot("handle angry customer")
assert_semantic(response, "polite and professional")Bei einem Fehler:
AssertionError: Semantic check failed (score=0.12)
Intent: polite and professional
Output: "You're an idiot for asking that."
Reason: Text contains aggressive languageErstklassiges pytest-Plugin mit Fixtures, Markern und CI-Reporting: pytest-semantix.
Framework-Integrationen
Integrieren Sie es in Ihren bestehenden Stack – Wiederholungen werden von jedem Framework nativ gehandhabt.
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 lassen sich auch in dspy.BestOfN, dspy.Evaluate und MIPROv2 einbinden – lokal, keine API-Aufrufe, ca. 15 ms pro Auswertung. Siehe benchmarks/ für reproduzierbare Vergleiche mit LLM-Richter-Belohnungsfunktionen.
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.pyJeder MCP-fähige Agent (Claude Desktop, Cursor usw.) kann Absichten als Tool validieren.
- uses: labrat-akhona/semantic-test-action@v1
with:
test-path: tests/Postet einen semantischen Testbericht als PR-Kommentar.
Installieren Sie Extras: pip install "semantix-ai[dspy]", "[langchain]", "[pydantic-ai]", "[guardrails]", "[instructor]", "[mcp]", "[all]".
Steckbare Richter
Wählen Sie den Kompromiss zwischen Geschwindigkeit / Genauigkeit / Schlussfolgerung:
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-wrappedQuantisierter Modus (INT8 ONNX, ca. 25 MB, kein PyTorch):
pip install "semantix-ai[turbo]"Wann dies das richtige Werkzeug ist
Sie betreiben ein LLM-gestütztes System, das persönliche Informationen verarbeitet, und benötigen einen prüfbaren Validierungsschritt.
Sie optimieren ein DSPy-Programm und die LLM-Richter-Belohnungsschleife ist zu langsam, zu teuer oder zu nicht-deterministisch.
Sie benötigen semantische Test-Assertions in pytest / CI, die keine kostenpflichtige API aufrufen.
Sie sind in einer regulierten Branche tätig (Finanzdienstleistungen, Versicherungen, Gesundheitswesen) und „das Modell sagte, es sei in Ordnung“ ist keine vertretbare Antwort.
Wann es nicht das richtige Werkzeug ist
Ihre Validierungsabsicht erfordert mehrstufiges Schlussfolgern oder Weltwissen („ist dies konform mit Abschnitt 4(b) des Steuergesetzes von 2026“). NLI kann dies nicht; schlussfolgernde LLMs können es.
Sie benötigen, dass der Richter warum in Prosa erklärt, nicht nur einen Score vergibt.
Sie bewerten weniger als 100 Ausgaben pro Monat und die Latenz / Kosten von LLM-als-Richter spielen keine Rolle.
Siehe Wo semantix passt für einen Vergleich mit TruLens, DeepEval, Vectara HHEM, Guardrails, RAGAS und NeMo.
Schlüsseleigenschaften
Lokale Inferenz — NLI-Modell läuft auf der CPU, keine Daten verlassen Ihre Maschine.
Deterministisch — gleiche Eingabe, gleicher Score, jedes Mal, auf jeder Maschine. Seedbar.
Schnell — ca. 15–50 ms pro Prüfung mit dem quantisierten Richter.
Null API-Kosten — keine Token für die Validierung verbraucht.
Prüfbar — Hash-verkettete JSON-LD-Zertifikate pro Prüfung.
Gut getestet — 249 Tests, MIT-lizenziert.
Installation
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]" # EverythingDer Paketname auf PyPI ist
semantix-ai. Der Import lautetfrom semantix import ....
Mitwirken
Siehe CONTRIBUTING.md für Entwickler-Setup, Tests und Einreichungsrichtlinien.
Lizenz
MIT — siehe 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