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="intfloat/multilingual-e5-small")
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.0

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.0
File Size Uploaded Provenance Actions
al3x38_intent_guard-1.0.0.tar.gz 11.1 kB Without provenance Details for al3x38_intent_guard-1.0.0.tar.gz

Built distribution (wheel)

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

Total release size: 22.0 kB

Release files / al3x38_intent_guard-1.0.0.tar.gz

Download URL al3x38_intent_guard-1.0.0.tar.gz
Size 11.1 kB
Tags Source
SHA-256 checksum
How to use checksums
927c111d142e699c36cc33c24bd032ed52599b2b82461f26dc1f2f9cfec2cf48
BLAKE2b-256 checksum
How to use checksums
7022bee61280f6580de983ee7dc68b17da18d9de0cb8f7bc65e533e300e5b2db
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.0-py3-none-any.whl

Download URL al3x38_intent_guard-1.0.0-py3-none-any.whl
Size 11.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ce49739e22c0368714878113ac666d0b67a5d062e745ef18cd666649adc3ac80
BLAKE2b-256 checksum
How to use checksums
8c954e0c283a77537232b15dab9859e827bfb46708efed3114116a111d060378
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.0

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