Skip to main content

al3x38-intent-guard

al3x38-intent-guard — это асинхронный поведенческий фаервол (Guardrail) для ИИ-агентов на Python. Библиотека проверяет согласованность между исходным запросом пользователя, текстовым ответом нейросети и вызываемыми системными инструментами (Function Calling).

Зачем это нужно

Современные LLM-агенты уязвимы к скрытым промпт-инъекциям (Indirect Prompt Injection) и несогласованному поведению: модель может сгенерировать вежливый, релевантный ответ для пользователя, но в фоновом режиме попытаться вызвать привилегированную функцию (rm_dir, db_write, send_funds) с аргументами, не связанными с исходной задачей.

al3x38-intent-guard решает эту проблему через трехуровневый контроль:

  1. Семантическая кросс-валидация: вычисляет косинусное расстояние между эмбеддингами запроса, ответа и аргументов вызываемого инструмента.
  2. Анализ энтропии логитов (White-Box): при наличии logprobs оценивает внутреннюю неуверенность модели по формуле Шеннона.
  3. Динамический скоринг доверия (Trust Score): ведет накопительную репутацию по каждой сессии (session_id) с поддержкой режима ручного подтверждения (NEED_APPROVAL) и полной заморозки (SUSPENDED).

Установка

Базовая установка (требуется только numpy):

pip install al3x38-intent-guard

Установка с автономным офлайн-движком эмбеддингов (без необходимости поднимать Ollama или использовать внешние API):

pip install al3x38-intent-guard[offline]

Быстрый старт

1. Работа с локальной Ollama

import asyncio
from al3x38_intent_guard import (
    ActionVerdict,
    IntentGuardCore,
    OllamaLocalEmbedder,
    parse_ollama_payload,
)

async def main():
    embedder = OllamaLocalEmbedder(host="http://localhost:11434", model="bge-m3")
    guard = IntentGuardCore(embedder)

    # Сырой ответ от Ollama (/api/chat)
    raw_response = {
        "message": {
            "content": "Конечно, сейчас проверю статус вашего заказа.",
            "tool_calls": [
                {"function": {"name": "rm_dir", "arguments": {"path": "/var/www"}}}
            ]
        }
    }

    telemetry = parse_ollama_payload(
        session_id="user_42",
        prompt="Где мой заказ №105?",
        payload=raw_response
    )

    verdict, reason = await guard.check(telemetry)
    if verdict != ActionVerdict.ALLOW:
        print(f"Выполнение остановлено [{verdict.value}]: {reason}")

if __name__ == "__main__":
    asyncio.run(main())

2. Полностью автономный режим (на CPU)

from al3x38_intent_guard import IntentGuardCore, OfflineFastEmbedder

embedder = OfflineFastEmbedder(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
guard = IntentGuardCore(embedder)

3. Подключение к OpenAI / LM Studio / vLLM

from al3x38_intent_guard import IntentGuardCore, OpenAICompatEmbedder

embedder = OpenAICompatEmbedder(
    base_url="http://localhost:1234/v1",
    api_key="lm-studio",
    model="nomic-embed-text"
)
guard = IntentGuardCore(embedder)

Ссылки

Лицензия

MIT License. Автор концепции и архитектуры: al3x38.

Metadata

Release files for al3x38-intent-guard 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for al3x38-intent-guard 1.0.1
File Size Uploaded Provenance Actions
al3x38_intent_guard-1.0.1.tar.gz 11.0 kB Without provenance Details for al3x38_intent_guard-1.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for al3x38-intent-guard 1.0.1
File Interpreter ABI Platform Actions
al3x38_intent_guard-1.0.1-py3-none-any.whl Python 3 none any Details for al3x38_intent_guard-1.0.1-py3-none-any.whl

Total release size: 22.1 kB

Release files / al3x38_intent_guard-1.0.1.tar.gz

Download URL al3x38_intent_guard-1.0.1.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e0f2ba686b54221048fca761caebbe5d0e696e73d3a6e5e1c5e4735230361db5
BLAKE2b-256 checksum
How to use checksums
d7e9cec518e2bbb8028a509fdd6fcb737601f32af44e4ee733d9557fdecf81e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.13

Release files / al3x38_intent_guard-1.0.1-py3-none-any.whl

Download URL al3x38_intent_guard-1.0.1-py3-none-any.whl
Size 11.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7ec4b7cfd27a08c4259445c3f3b009acf511ed0c0f13c63f408747fbf630a740
BLAKE2b-256 checksum
How to use checksums
7830247f3a372105a6ed67c3e35041819d2d419e099c5efee7cf13d65b4ffdca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.13

Security for al3x38-intent-guard 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page