Semantix-verify
Проверяйте каждый вывод LLM на соответствие явному намерению. Получайте оценку, вердикт и защищенную от несанкционированного доступа квитанцию. Локально. За ~15-50 миллисекунд. Без 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.Почему это существует
Приложения на базе LLM часто пропускают этап проверки того, что результат пригоден для использования. Распространенное решение — вызов более мощной LLM в качестве судьи — имеет три проблемы:
Нестабильность. Один и тот же ввод, разные оценки при разных запусках. Регулятор, запрашивающий «повторить эту проверку», получает другой ответ, который невозможно отличить от доказательства неисправности системы.
Передача личных данных за пределы вашей сети. Каждый вызов судьи отправляет выходные данные во внешний API. Согласно POPIA §72 (или GDPR ст. 44, или обязательствам по системам высокого риска в Законе ЕС об ИИ), это проблема, которую нужно документировать, а не стандартное поведение.
Отсутствие квитанции. Проверка прошла, оценка получена, но ничего не было записано в форме, которая выдержит аудит.
semantix заменяет этот рефлекс локальным детерминированным валидатором и защищенным от несанкционированного доступа журналом. Каждая проверка создает подписанный JSON-LD сертификат, связанный хешем с предыдущим. Измените любую запись, и каждый последующий хеш будет нарушен. Регулятору не нужно доверять вашей базе данных — математика доказывает, что цепочка целостна.
Related MCP server: agentvet-mcp
Что вы получаете
1. Валидация как декоратор
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)Комбинируйте с помощью & (все должны пройти) и | (любое должно пройти):
SafeAndPolite = Polite & ~MedicalAdvice & ~LegalAdvice2. Защищенный от несанкционированного доступа аудиторский след
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Каждый сертификат записывает хеш проверенного текста, намерение, идентификатор и конфигурацию судьи, вердикт, временную метку и хеш предыдущего сертификата. Совместимо с инструментами JSON-LD и стандартными конвейерами аудита.
3. Самовосстанавливающиеся повторные попытки
В случае сбоя semantix внедряет структурированную обратную связь, чтобы LLM знала, что пошло не так:
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)Первый вызов: semantix_feedback равен None. При повторной попытке: он получает Markdown-отчет с оценкой, причиной и отклоненным выводом. Измеренная надежность повышается с 21% до 70% по трем категориям намерений.
4. Криминалистическая атрибуция на уровне токенов
from semantix import ForensicJudge, QuantizedNLIJudge
judge = ForensicJudge(QuantizedNLIJudge())
# Verdict.reason: "Suspect tokens: [indemnify, forfeit, waive]"5. Интеграция с pytest
from semantix.testing import assert_semantic
def test_chatbot_is_polite():
response = my_chatbot("handle angry customer")
assert_semantic(response, "polite and professional")В случае сбоя:
AssertionError: Semantic check failed (score=0.12)
Intent: polite and professional
Output: "You're an idiot for asking that."
Reason: Text contains aggressive languageПервоклассный плагин pytest с фикстурами, маркерами и отчетностью для CI: pytest-semantix.
Интеграции с фреймворками
Внедряйте в существующий стек — повторные попытки обрабатываются нативно каждым фреймворком.
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 также подключаются к dspy.BestOfN, dspy.Evaluate и MIPROv2 — локально, без вызовов API, ~15 мс на оценку. См. benchmarks/ для воспроизводимых сравнений с функциями вознаграждения на базе LLM-судьи.
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.pyЛюбой агент с поддержкой MCP (Claude Desktop, Cursor и т.д.) может проверять намерения как инструмент.
- uses: labrat-akhona/semantic-test-action@v1
with:
test-path: tests/Публикует отчет о семантическом тестировании в виде комментария к PR.
Установите дополнительные компоненты: pip install "semantix-ai[dspy]", "[langchain]", "[pydantic-ai]", "[guardrails]", "[instructor]", "[mcp]", "[all]".
Подключаемые судьи
Выберите баланс между скоростью / точностью / рассуждением:
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Квантованный режим (INT8 ONNX, ~25 МБ, без PyTorch):
pip install "semantix-ai[turbo]"Когда это подходящий инструмент
Вы запускаете систему на базе LLM, которая обрабатывает личную информацию, и вам нужен проверяемый этап валидации.
Вы оптимизируете программу DSPy, и цикл вознаграждения LLM-судьи слишком медленный, дорогой или недетерминированный.
Вам нужны семантические утверждения в тестах pytest / CI, которые не вызывают платный API.
Вы работаете в регулируемой отрасли (финансовые услуги, страхование, здравоохранение), и ответ «модель сказала, что все в порядке» не является защитимым аргументом.
Когда это не подходит
Ваше намерение проверки требует многошагового рассуждения или знаний о мире («соответствует ли это разделу 4(b) налогового кодекса 2026 года»). NLI не может этого сделать; рассуждающие LLM могут.
Вам нужно, чтобы судья объяснил почему в прозе, а не просто дал оценку.
Вы оцениваете менее 100 выводов в месяц, и задержка / стоимость LLM-судьи не имеют значения.
См. Где подходит semantix для сравнения с TruLens, DeepEval, Vectara HHEM, Guardrails, RAGAS и NeMo.
Ключевые свойства
Локальный вывод — модель NLI работает на CPU, данные не покидают вашу машину.
Детерминированность — один и тот же ввод, одна и та же оценка, каждый раз, на каждой машине. Поддерживает сиды.
Скорость — ~15-50 мс на проверку с квантованным судьей.
Нулевая стоимость API — токены не расходуются на проверку.
Проверяемость — JSON-LD сертификаты, связанные хешами, для каждой проверки.
Хорошо протестировано — 249 тестов, лицензия MIT.
Установка
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Имя пакета в PyPI —
semantix-ai. Импорт —from semantix import ....
Участие в разработке
См. CONTRIBUTING.md для настройки среды разработки, тестирования и правил подачи заявок.
Лицензия
MIT — см. 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.352 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.433 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.10187 PyPIMIT