Skip to main content
Glama

Проверяйте каждый вывод LLM на соответствие явному намерению. Получайте оценку, вердикт и защищенную от несанкционированного доступа квитанцию. Локально. За ~15-50 миллисекунд. Без 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.

Почему это существует

Приложения на базе LLM часто пропускают этап проверки того, что результат пригоден для использования. Распространенное решение — вызов более мощной LLM в качестве судьи — имеет три проблемы:

  1. Нестабильность. Один и тот же ввод, разные оценки при разных запусках. Регулятор, запрашивающий «повторить эту проверку», получает другой ответ, который невозможно отличить от доказательства неисправности системы.

  2. Передача личных данных за пределы вашей сети. Каждый вызов судьи отправляет выходные данные во внешний API. Согласно POPIA §72 (или GDPR ст. 44, или обязательствам по системам высокого риска в Законе ЕС об ИИ), это проблема, которую нужно документировать, а не стандартное поведение.

  3. Отсутствие квитанции. Проверка прошла, оценка получена, но ничего не было записано в форме, которая выдержит аудит.

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

2. Защищенный от несанкционированного доступа аудиторский след

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() | 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

Любой агент с поддержкой 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 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.
ParametersJSON Schema
NameRequiredDescriptionDefault
textYes
thresholdNo
intent_descriptionYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

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.

Conciseness4/5

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.

Completeness3/5

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.

Parameters4/5

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.

Purpose5/5

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.

Usage Guidelines2/5

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. 1 tool update
    • First observedverify_text_intent

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

ActivityMaintained
ResponsivenessNo issues

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