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. 결과가 달라집니다(Drift). 동일한 입력이라도 실행할 때마다 점수가 다릅니다. 규제 기관이 "이 검증을 다시 실행하라"고 요청할 때 다른 답변이 나오면, 이는 시스템이 고장 났다는 증거와 다를 바 없습니다.

  2. 개인정보가 네트워크 외부로 유출됩니다. 모든 판사 호출은 출력을 타사 API로 전송합니다. POPIA §72(또는 GDPR 제44조, EU AI 법의 고위험 시스템 의무)에 따라 이는 기본값이 아니라 문서화해야 할 문제입니다.

  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입니다. 재시도 시: 점수, 이유, 거부된 출력이 포함된 마크다운 보고서를 받습니다. 세 가지 의도 범주에 걸쳐 측정된 신뢰도가 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와의 비교는 semantix가 적합한 곳을 참조하세요.


주요 속성

  • 로컬 추론 — 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

    ActivityStale
    ResponsivenessNo recent community 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
      24 PyPI
      1
      MIT