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をジャッジとして呼び出す」ことには、3つの問題があります。

  1. ドリフトが発生する。 同じ入力でも、実行ごとにスコアが異なります。「この検証を再実行してほしい」という規制当局の要求に対して異なる回答が返されると、システムが壊れている証拠と区別がつきません。

  2. 個人情報がネットワーク外に送信される。 ジャッジを呼び出すたびに、出力がサードパーティのAPIに送信されます。POPIA §72(またはGDPR第44条、あるいはEU AI法の高リスクシステム義務)の下では、これはデフォルトではなく、文書化すべき問題です。

  3. レシートが生成されない。 検証が行われ、スコアが返されても、監査に耐えうる形式で記録されません。

semantixは、その反射的な行動を、ローカルで決定論的なバリデーターと改ざん検知可能なログに置き換えます。すべての検証は、前の検証とハッシュチェーンで結ばれた署名付きJSON-LD証明書を生成します。エントリを1つでも変更すると、それ以降のすべてのハッシュが壊れます。規制当局はあなたのデータベースを信頼する必要はありません。数学がチェーンの完全性を証明します。


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レポートを受け取ります。測定された信頼性は、3つの意図カテゴリ全体で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

フィクスチャ、マーカー、CIレポートを備えたファーストクラスのpytestプラグイン: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呼び出しなし、評価あたり約15ms。LLMジャッジ報酬関数との再現可能な比較については benchmarks/ を参照してください。

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、約25MB、PyTorch不要):

pip install "semantix-ai[turbo]"

これが適切なツールである場合

  • 個人情報を処理するLLMベースのシステムを実行しており、監査可能な検証ステップが必要な場合。

  • DSPyプログラムを最適化しており、LLMジャッジの報酬ループが遅すぎる、コストが高すぎる、または非決定論的すぎる場合。

  • 有料APIを呼び出さないpytest / CIでのセマンティックテストアサーションが必要な場合。

  • 規制産業(金融サービス、保険、ヘルスケア)に属しており、「モデルが大丈夫だと言った」という回答では弁明できない場合。

そうでない場合

  • 検証の意図にマルチホップ推論や世界知識が必要な場合(「これは2026年税法の第4条(b)に準拠しているか」など)。NLIにはこれができませんが、推論LLMには可能です。

  • ジャッジにスコアだけでなく、散文で「理由」を説明させる必要がある場合。

  • 月間100出力未満を評価しており、LLM-as-judgeのレイテンシやコストが問題にならない場合。

TruLens、DeepEval、Vectara HHEM、Guardrails、RAGAS、NeMoとの比較については Where semantix fits を参照してください。


主要な特性

  • ローカル推論 — NLIモデルはCPU上で実行され、データはマシンから離れません。

  • 決定論的 — 同じ入力であれば、どのマシンでも毎回同じスコアになります。シード設定可能。

  • 高速 — 量子化ジャッジを使用してチェックあたり約15~50ms。

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

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