Download the PHP package stejac/guarded-chat-bundle without Composer
On this page you can find all versions of the php package stejac/guarded-chat-bundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download stejac/guarded-chat-bundle
More information about stejac/guarded-chat-bundle
Files in stejac/guarded-chat-bundle
Package guarded-chat-bundle
Short Description Guardrails for public AI chats in Symfony apps: prompt versioning, injection prefilter, kill switch, budget and rate limits, signed sessions, retention. Built on Symfony AI.
License MIT
Homepage https://github.com/Stefan39/GuardedChatBundle
Informations about the package guarded-chat-bundle
GuardedChatBundle
Guardrails for public AI chats in Symfony apps: signed sessions, prompt versioning, injection prefilter, kill switch, rate limits, budget stop, retention. Built on Symfony AI, with a drop-in chat widget.
Deutsche Version
Why not just use symfony/ai?
Symfony AI talks to the model: platforms, agents, tools, streaming. It deliberately leaves open everything around a public, anonymous chat endpoint, and that is the part that hurts when a site goes live:
| Problem on a public chat | Symfony AI alone | This bundle |
|---|---|---|
| Visitors paste "ignore previous instructions" | up to you | prefilter as an input processor, the model is never called |
| A bot or a bored visitor drains your token budget | up to you | per-client rate limits, session message cap, budget stop |
| Who is allowed to continue a conversation? | up to you | signed session tokens, lifetime and idle timeout |
| Fix the wording of the system prompt without a deploy | code constant | versioned prompts in the database, one active at a time |
| Switch the chat off during an incident | up to you | two-stage kill switch (config flag plus runtime switch) |
| Privacy: how long do you keep transcripts? | up to you | retention with a scheduled prune |
| Telling visitors they talk to an AI (Art. 50 EU AI Act) | up to you | disclosure in the widget and an enforced prompt instruction |
The bundle uses Symfony AI as its foundation, not as a competitor: exactly one internal class touches it (Internal\AiStreamAdapter), so a 0.x change there does not ripple through the rest.
Quick start
That is the whole integration: the widget needs AssetMapper with Symfony UX StimulusBundle (composer require symfony/asset-mapper symfony/stimulus-bundle); Flex registers its controller automatically. The bundle registers its Doctrine mapping but ships no migrations: run bin/console doctrine:migrations:diff and review the result.
If the @stejac/guarded-chat-bundle entry in assets/controllers.json is missing after a Composer update, you came from a version without the symfony-ux keyword (before v1.1.1), and Flex removed the entry. Re-add it by hand, or run composer update stejac/guarded-chat-bundle once the release with the keyword is installed; from then on Flex keeps the entry.
With Symfony Flex the bundle's recipe (in symfony/recipes-contrib, #2093) does the setup for you. Because it comes from the community "contrib" repository, Flex asks once whether to execute it during composer require: answer y (or a/p to be asked less often). The recipe registers the bundle in config/bundles.php, creates config/packages/guarded_chat.yaml and config/routes/guarded_chat.yaml with placeholder values, and adds GUARDED_CHAT_ENABLED=1 to .env (set it to 0 to switch the public chat off with a deploy). Then adjust platform, model and the default prompt in the generated file.
Without the recipe, do these steps yourself: no Flex, an answer of n, or a non-interactive install such as a CI or Docker build without extra.symfony.allow-contrib in composer.json (Flex then skips the recipe and changes nothing, not even config/bundles.php). Register Stejac\GuardedChatBundle\GuardedChatBundle::class => ['all' => true] in config/bundles.php and create the two files from the quick start above.
For the platform itself see the Symfony AI documentation, for example the generic bridge for an OpenAI-compatible gateway such as LiteLLM:
Features
- Signed session tokens and per-session limits (lifetime, idle timeout, message count, history window)
- Versioned system prompts in the database, with a configured fallback and instructions that hold for every version (AI disclosure, form of address, output format)
- Prefilter for obvious prompt-injection phrases, as a Symfony AI input processor
- Two-stage kill switch: a hard
enabledflag plus a runtime switch you can flip without a deploy - Rate limits per client (session start, messages per minute, messages per day) and a budget stop that recognises an exhausted gateway budget
- Human verification hook plus a honeypot field
- Knowledge base with pluggable retrieval (PostgreSQL full text out of the box)
- Retention: sessions and their messages are deleted after a configurable number of days
- Streaming answers as server-sent events, with configurable action markers (e.g.
[[contact]]becomes anactionevent and a button) - Widget: a Stimulus controller plus an overridable Twig template, no CSS framework required
The widget
@GuardedChat/widget.html.twig renders a launcher button and a chat panel. Texts come in English and German from the guarded_chat translation domain, including the AI notice in the panel header and the greeting that discloses the AI to the visitor.
| Variable | Meaning |
|---|---|
locale |
Locale sent with every request, default: request locale |
session_url, message_url |
Endpoints, default: the bundle's routes |
greeting |
First assistant message (also the AI disclosure), '' hides it |
notice |
Text under the panel title |
actions |
{type, label, url} entries; a button is shown under answers that carry that action |
verification_token |
Static token for the human verification hook |
max_message_length |
Input maxlength, default 500 |
root_attributes |
Extra attributes of the root element, merged over {class: 'guarded-chat'}; true renders a bare attribute, false and null leave it out |
user_message_class, assistant_message_class |
Classes of the message bubbles |
Only while the chat is on. chat_enabled() applies the same two-stage check as the session endpoint (the enabled flag and your runtime switch):
Styling. The default look is a small stylesheet driven by CSS custom properties; Flex loads it, otherwise add {{ asset('@stejac/guarded-chat-bundle/dist/widget.css') }}:
Your own markup. Extend the template and override a block (launcher, header, notice, messages, actions, form), or copy it to templates/bundles/GuardedChatBundle/widget.html.twig. The controller relies only on the data-…-target and data-action attributes, so Tailwind classes or any other design work. The variables above can be set in the extending template as well:
Human verification. The widget dispatches a verify event before it starts a session. A listener hands over a token, which is sent as verificationToken to POST /session and checked by your HumanVerifierInterface. Example with Cloudflare Turnstile (the bundle has no dependency on it):
If the promise rejects, the widget shows the reason when it is a string or carries a userMessage, otherwise the translated widget.error_verification text. The message of a plain Error is never shown, it stays in the console.
Configuration
If the service named in platform does not exist, the chat is switched off and a message is logged instead of the container failing to compile.
Endpoints
| Route | Purpose |
|---|---|
POST /chat/session |
Starts a session. Body: {"verificationToken": "", "website": "", "locale": "en"} (website is the honeypot and must stay empty). |
POST /chat/message |
Sends {"message": "...", "locale": "en"} and streams the answer as text/event-stream with text and action events. |
Errors are JSON with a stable error code and a translated message: rate_limited, message_limit_reached, budget_exhausted, gateway_unavailable, verification_failed, invalid_token, session_expired, invalid_request.
Extension points
Each is a service you point the matching configuration key at; the defaults are neutral.
| Key | Interface | Default |
|---|---|---|
runtime_switch |
ChatRuntimeSwitchInterface |
always on |
human_verifier |
HumanVerifierInterface |
lets everyone through |
client_identifier_resolver |
ClientIdentifierResolverInterface |
Request::getClientIp() |
budget_exhaustion_detector |
BudgetExhaustionDetectorInterface |
HTTP 429 means budget exhausted |
knowledge.retriever |
KnowledgeRetrieverInterface |
none (NullRetriever) |
Knowledge base
Answers can draw on hand-curated snippets (chat_knowledge_snippet: title, optional typical question, content, priority, source URL). Snippets created as admin are active at once; snippets suggested as api stay dormant until a person activates them, so a visitor cannot steer what the assistant knows.
postgres_full_text needs PostgreSQL. For any other store, implement KnowledgeRetrieverInterface (retrieve(string $question, int $limit): list<KnowledgeSnippetInterface>) and put its service id into retriever. The ids of the snippets that fed an answer are stored with it in chat_message.context_snippet_ids. The header wording is translatable in the guarded_chat domain (knowledge.*).
Retention
bin/console guarded-chat:prune deletes sessions older than retention.days (default 90). With symfony/scheduler and dragonmantank/cron-expression installed, retention.schedule.enabled: true registers a recurring prune. Every run writes one log entry with the number of deleted sessions; retention.log_level (default info) takes any PSR-3 level, so a production log that keeps only warning and above still records it.
Requirements
PHP 8.3+, Symfony 7.4 or 8, Doctrine ORM 3, symfony/ai-bundle 0.14 (installed with the bundle). The widget additionally needs symfony/twig-bundle, symfony/asset-mapper and symfony/stimulus-bundle.
Development
The PostgreSQL tests need GUARDED_CHAT_TEST_DATABASE_URL, see CONTRIBUTING.md.
License
MIT
All versions of guarded-chat-bundle with dependencies
doctrine/doctrine-bundle Version ^2.13 || ^3.0
doctrine/orm Version ^3.3
psr/clock Version ^1.0
psr/log Version ^3.0
symfony/ai-agent Version ^0.14
symfony/ai-bundle Version ^0.14
symfony/ai-generic-platform Version ^0.14
symfony/ai-platform Version ^0.14
symfony/cache-contracts Version ^3.5
symfony/clock Version ^7.4 || ^8.0
symfony/config Version ^7.4 || ^8.0
symfony/console Version ^7.4 || ^8.0
symfony/dependency-injection Version ^7.4 || ^8.0
symfony/doctrine-bridge Version ^7.4 || ^8.0
symfony/framework-bundle Version ^7.4 || ^8.0
symfony/http-client Version ^7.4 || ^8.0
symfony/http-foundation Version ^7.4 || ^8.0
symfony/http-kernel Version ^7.4 || ^8.0
symfony/messenger Version ^7.4 || ^8.0
symfony/rate-limiter Version ^7.4 || ^8.0
symfony/routing Version ^7.4 || ^8.0
symfony/translation Version ^7.4 || ^8.0
symfony/translation-contracts Version ^3.5
symfony/uid Version ^7.4 || ^8.0
symfony/yaml Version ^7.4 || ^8.0