subodh / smart-ai-assistant
A reusable Laravel package providing a smart AI assistant for AEPS error handling.
Requires
- php: >=8.1
- illuminate/support: ^10.0|^11.0
- phpoffice/phpspreadsheet: ^1.29
Requires (Dev)
- anthropic-ai/sdk: ^0.57
- orchestra/testbench: ^9.0
- phpunit/phpunit: ^11.0
- smalot/pdfparser: ^2.12
Suggests
- anthropic-ai/sdk: Needed for document answers with ai.driver = anthropic (^0.57)
- smalot/pdfparser: Needed to ingest PDF documents with smart-ai:ingest (^2.12)
Provides
None
Conflicts
None
Replaces
None
README
A modern, intelligent chat assistant for Laravel applications with automatic error detection, file attachments, and bilingual support.
๐ Features
- โ Auto Error Detection - Automatically scans pages for errors
- โ Clickable Error Tags - Interactive chips for found errors
- โ Modern Chat UI - WhatsApp/ChatGPT-inspired design
- โ File Attachments - Upload images, PDFs, and documents
- โ Fullscreen Preview - View attachments in fullscreen modal
- โ Bilingual Support - English and Hindi responses
- โ Typing Indicators - Animated dots while waiting
- โ Smart Context - Includes error context in queries
- โ Responsive Design - Works on mobile and desktop
- โ Smooth Animations - Professional transitions and effects
๐ธ Screenshots
See the visual mockups showing the modern, premium design!
๐ Quick Start
Installation
This package is already installed in your Laravel application.
Deployment
# Clear caches php artisan cache:clear php artisan view:clear # Publish assets php artisan vendor:publish --tag=smart-ai-assistant-assets --force php artisan vendor:publish --tag=smart-ai-assistant-views --force # Hard refresh browser # Ctrl + Shift + R
Usage
Add the widget to any Blade template:
<x-smart-assistant-widget />
That's it! The assistant will appear as a floating button in the bottom-right corner.
๐ Documentation
| Document | Description |
|---|---|
| UPGRADE_SUMMARY.md | Complete upgrade overview |
| DEPLOYMENT_GUIDE.md | Step-by-step deployment |
| README_UPGRADE.md | Feature documentation |
| ARCHITECTURE.md | System architecture |
| QUICK_REFERENCE.md | Developer quick reference |
| CHANGELOG.md | Version history |
๐ฏ How It Works
1. Panel Opens
- Shows welcome message: "Hello! I'm Soniya"
- Automatically scans page for errors
- Displays status: "Scanning your page..."
2. Error Detection
- Scans for:
.alert-danger,.invalid-feedback,.text-danger,.smart-error - Displays errors as clickable tags
- Shows warning icon (โ ๏ธ)
3. User Interaction
- Click error tag โ Sends to API โ Shows AI response
- Or type manual message โ Send to support
- Attach files for context
4. AI Response
- Replies in one language: the one picked in the header menu, or the language
the user wrote in (
localesconfig; e.g. English, Hindi, Hinglish) - Displays in chat bubble format, with "Raise ticket" under replies it could not answer
- Auto-scrolls to bottom
๐จ Customization
Branding, page scan and widget features
Everything is set in config/smart-ai-assistant.php under widget; do not
publish or edit the view. Each section replaces only the keys you list:
'widget' => [ 'branding' => [ 'title' => 'Help desk', 'welcome_title' => "Hello! I'm Asha", 'welcome_subtitle' => 'How may I assist you today?', 'footer' => 'Powered by Example', // null hides it 'primary_color' => '#0a7d5a', // hex only 'secondary_color' => '#095c45', ], 'features' => [ 'page_scan' => true, 'attachments' => true, 'screenshot' => true, 'bootstrap_modal_compat' => false, // Bootstrap modals steal the chat input's focus ], 'suggestions' => ['Money deducted but transaction failed'], // needs resolve_typed_messages 'page_scan' => [ 'ids' => ['payment-error'], // always errors 'selectors' => ['.alert-danger'], // always errors 'soft_selectors' => ['.text-danger'], // errors unless an ignore rule applies 'ignore_classes' => ['invalid-feedback'], 'ignore_ids' => ['status'], 'ignore_patterns' => ['^(loading\.*|please\s+wait)$'], // JS regex, case-insensitive ], ],
Pages can also mark an element the scan must skip with data-sa-ignore.
Host configuration checklist
The package defaults are generic (English replies, no categories, knowledge
domain general). Publish the config once
(php artisan vendor:publish --tag=smart-ai-assistant-config) and set:
middleware: keepweband add your auth middleware.user_resolver: only if you don't use Laravel's auth guard (e.g. Sentinel).default_service: the knowledge domain your KB rows use (smart-ai:seed-kb file.xlsx --domain=...).understanding.patterns/understanding.categories: your language and product vocabulary. A pattern type you list replaces its defaults.localesandresponses: your reply languages (label, Unicodescript, wordpatternsfor romanised text,fallback), and the reply texts to change, per key, with one text per language code. With more than one language, the widget shows a language menu (Auto + each language).resolution.strategies: add your ownResolutionStrategyclasses; keepFallbackStrategylast.escalation.channel: yourEscalationChannelclass that turns a support request into a ticket in your system (the default rejects every request). Setescalation.attachmentsandescalation.max_message_lengthwithin your system's limits.features.server_escalation(orSMART_AI_SERVER_ESCALATION=true): send typed messages through the package endpoint and your channel. While it is off, the widget posts to/customer-support/raise/ticketwith identity fields rendered into the page.conversations.retention_days(orSMART_AI_RETENTION_DAYS): how long to keep stored conversations, then schedulephp artisan smart-ai:prunedaily.nullkeeps everything.features.resolve_typed_messages(orSMART_AI_RESOLVE_TYPED_MESSAGES=true): typed messages go to the assistant first, and a ticket is created only after the user presses "Raise ticket" and confirms. While it is off, every typed message that passes the widget's own checks becomes a ticket.widget: branding, page scan rules and widget features (see above).data_tools,understanding.entitiesandcapabilities.data_tools(orSMART_AI_DATA_TOOLS=true): answers from your own data, e.g. a transaction's status when the message contains its reference. ImplementSubodh\SmartAiAssistant\Core\Contracts\DataTool;authorize()must check that the user may see the record, andexecute()must return masked, display-safe values only. List the wholecapabilitiesarray, since top-level keys replace the package default.knowledge.synonymsand keyword entries: for free-text complaints that never contain an exact error text. Seed rows withphp artisan smart-ai:seed-kb keywords.csv --keywords, where column A lists words that must all appear (in any order), e.g.pan refund, and map your users' spellings to those words, e.g.'not' => ['nahi', 'nhi', 'เคจเคนเฅเค']. Longer words also match with a small spelling mistake ("incompleate"); setknowledge.typo_toleranceto false to require exact words. Measure the effect withsmart-ai:eval; its "answerable by a data tool" line counts queries a tool would answer for a logged-in user.documents: guides, policies and FAQs stored as passages withsmart-ai:ingest(see "Documents" below). Set the defaultaudience(users= logged-in only,public= guests too). For PDFs runcomposer require smalot/pdfparserin your app.aiandcapabilities.document_answers(orSMART_AI_DOCUMENT_ANSWERS=true): answers written by an LLM from your documents. SetSMART_AI_DRIVER=anthropicandSMART_AI_API_KEY, and runcomposer require anthropic-ai/sdk. Replace the oldaistub in your published config with the package'saiblock. Tunedocuments.retrieval.min_score,documents.answers(guests, sources line, daily caps) andresponses.document_sourcesper language.
The config is merged one level deep: a top-level key in your file replaces the
package's value for that key entirely. The exception is widget, whose
sections keep their defaults for keys you leave out.
๐ง API Endpoints
Message (features.resolve_typed_messages on)
POST /smart-assistant/message
Request: {"text": "...", "source": "typed", "page_url": "...", "conversation_id": 12}.
source is typed (default), page_error or suggestion. The response is
the same as for the error query below. It never creates a ticket.
Error Query
POST /smart-assistant/help
Request:
{
"error_text": "Error message",
"page_url": "https://example.com",
"conversation_id": 12
}
conversation_id is the one from the previous response; it is only honoured
for the same user (or guest session) and while the conversation is active.
Response (protocol 1, with the legacy fields kept for one release):
{
"protocol": 1,
"conversation_id": 12,
"blocks": [
{ "type": "text", "format": "basic", "locale": "en", "text": "English solution" }
],
"actions": [],
"meta": { "source": "kb", "input_type": "valid", "category": "AEPS", "locale": "en" },
"source": "kb",
"answer_en": "English solution",
"answer_hi": "Hindi solution",
"input_type": "valid",
"category": "AEPS"
}
After an unresolved reply or a request for a human, actions holds
{"type": "action", "id": "escalate", "label": "Raise ticket", "confirm": true}.
Support Request (features.server_escalation on)
POST /smart-assistant/escalate
Multipart form: message (required unless files are attached),
error_context (page error the user picked, optional), page_url (optional),
attachments[] (files, limited by escalation.attachments). The user comes
from the session; identity fields in the form are ignored.
Response (201 created, 422 rejected, 429 throttled by the host,
503 failed; 401 for guests):
{
"conversation_id": 12,
"status": "created",
"message": "Your query has been registered successfully.",
"reference": "MDXCID123456789",
"view_url": "/customer-support/ticket/MDXCID123456789"
}
Chat Message (features.server_escalation off)
POST /customer-support/raise/ticket
FormData:
maddox_id: User IDdescription: Message textattachment: File (optional)
๐ File Structure
packages/smart-ai-assistant/
โโโ public/
โ โโโ css/
โ โ โโโ assistant.css
โ โโโ js/
โ โโโ ui-manager.js
โ โโโ api-manager.js
โ โโโ file-preview.js
โ โโโ assistant.js
โโโ resources/
โ โโโ views/
โ โโโ components/
โ โโโ widget.blade.php
โโโ src/
โ โโโ Http/
โ โ โโโ Controllers/
โ โโโ Models/
โ โโโ SmartAiAssistantServiceProvider.php
โโโ config/
โ โโโ smart-ai-assistant.php
โโโ database/
โ โโโ migrations/
โโโ routes/
โโโ web.php
๐ Documents (smart-ai:ingest)
Store your own documents as searchable passages. With document answers on (see "Document answers" below), questions that the knowledge base can't answer get an answer written from them.
php artisan smart-ai:ingest docs/refund-policy.pdf [--title="Refund policy"] [--domain=PAN] [--audience=public] php artisan smart-ai:ingest docs/ # every supported file, subfolders included php artisan smart-ai:documents [--all] # list (active versions; --all adds archived) php artisan smart-ai:documents archive "Refund policy"
Supported: PDF with a text layer (needs smalot/pdfparser; scanned PDFs need
OCR, which is not supported), DOCX, XLSX/XLS/CSV (row 1 is the header; each
row becomes "Header: value" lines), TXT/MD and HTML. Text is split into
passages of up to documents.chunk_size characters that never cross a
heading; each passage records its heading path.
The title defaults to the file name without extension. Ingesting the same
title again with a changed file adds a new version and archives the previous
one (old versions stay in the database). The same file again changes nothing,
except the audience when --audience differs. Add a file type by mapping its
extension to your own TextExtractor class in documents.extractors.
Document answers
When the knowledge base has no answer, the assistant searches the active
documents. It sends the question, with personal data masked, and up to
documents.answers.passages passages to the LLM, which answers only from
them. The answer ends with "Source: ". In each of these cases
the user gets the usual "no answer yet" reply with "Raise ticket", as before:
- no passage contains at least
documents.retrieval.min_scoreof the question's words (no LLM call is made then); - a daily cap is reached;
- the model says the passages don't answer the question;
- the model declines, fails or times out (
ai.timeout).
Guests get document answers only with documents.answers.guests, and only
from public documents.
Rollout:
php artisan migrate, thencomposer require anthropic-ai/sdk(andsmalot/pdfparserfor PDFs).- Ingest the documents, then measure:
php artisan smart-ai:eval queries.csv --baseline=before.json. The "matching document passage" lines show how many queries would reach document answers. Raise or lowermin_scoreuntil the matches look right. - Set
SMART_AI_DRIVER=anthropic,SMART_AI_API_KEY=...andSMART_AI_DOCUMENT_ANSWERS=true. Ask a few real questions and check the stored conversations (smart_ai_messages.data.documentsnames the document versions used).
๐ Measuring coverage (smart-ai:eval)
Before adding rules, knowledge or AI, measure what the assistant answers today:
php artisan smart-ai:eval queries.csv --json=before.json
# ... add KB rows, patterns, a data tool ...
php artisan smart-ai:eval queries.csv --baseline=before.json
The file (CSV or Excel, row 1 a header) holds real user queries in column A,
optionally the expected outcome or source in B (answered, unresolved,
clarify, escalate, kb, unknown, ...) and the expected category in C.
Support tickets work well as a source. Each query is resolved like a typed
message from a new guest conversation; nothing is stored. The report shows
outcome and category shares, how many queries contain a data-tool entity, label
accuracy, and the most frequent unanswered queries (--list=clarify for
another outcome), with personal data masked. The query file itself holds real
customer text: keep it out of the repository and delete it after use.
๐งช Testing
Manual Testing Checklist
- Panel opens with welcome message
- Error scanning detects errors
- Error tags are clickable
- Chat messages display correctly
- File attachment works
- Fullscreen preview opens
- Send button works
- API responses display
- With
server_escalationon: a typed message creates a ticket and shows its reference; a second one within the host's limit shows the host's "please wait" message; a.docxor a file over the size limit is refused with a message; the page source has nosa-user-*inputs - Replies have no "Solution" / "เคนเคฟเคเคฆเฅ เคฎเฅเค" headings and show one language: English for an English question, Hindi for a Devanagari one, Hinglish for "mATM par device kaise register karen"; "hello" after a Hindi message stays Hindi; the header menu (Auto / English / เคนเคฟเคเคฆเฅ / Hinglish) overrides this and is remembered after a reload. The same greeting twice, or the same error twice, gets the exit message, also after navigating to another page in the same tab
- "Raise ticket" appears inside the reply bubble (labelled in the reply language), not in a separate "Still need help?" bubble; clicking it adds the "This will be sent to our support team" confirmation below
- With
resolve_typed_messageson: a typed greeting gets a reply and no ticket; an unknown problem gets the reply plus a "Raise ticket" button; the button shows what will be sent; "Cancel" sends nothing; "Send to support" creates one ticket and shows its reference; typing "talk to an agent" offers the button; a screenshot sent without text offers the button; an older "Raise ticket" button is disabled after a new message - Branding from
widget.branding(title, welcome texts, footer, colours) with no customised view inresources/views/vendor/smart-ai-assistant - Error tags appear for the same page errors as before (AEPS modal
errors,
.alert-danger), not for "Loading...", form validation or labels - With a Bootstrap modal open, the chat input can be clicked and typed in
(
bootstrap_modal_compat) - With
data_toolson: "status of " shows a Transaction card (reference, service, type, amount, status, date); a reference of a user outside your downline, and a made-up reference, both get "I couldn't find that reference in your account" with a "Raise ticket" button; the log has one "Smart assistant data tool" line per lookup - Mobile responsive works
- No console errors
Browser Testing
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
- Mobile browsers
๐ Troubleshooting
Changes not appearing?
- Clear all Laravel caches
- Republish assets with
--force - Hard refresh browser
JavaScript errors?
- Check all 4 JS files are loaded
- Verify load order in widget.blade.php
- Check browser console
Styles not applying?
- Verify CSS file is loaded
- Check for CSS conflicts
- Inspect elements in DevTools
See DEPLOYMENT_GUIDE.md for more troubleshooting tips.
๐ Version History
v2.0.0 (2025-12-04)
- Complete UI/UX overhaul
- Modular JavaScript architecture
- File attachment system
- Fullscreen preview modal
- Modern chat interface
- Comprehensive documentation
v1.0.0 (2025-11-29)
- Initial release
- Basic error detection
- Simple chat interface
See CHANGELOG.md for detailed history.
๐๏ธ Architecture
Modular Design
- ui-manager.js - UI interactions and state
- api-manager.js - Backend communications
- file-preview.js - File handling and preview
- assistant.js - Main controller
Data Flow
User Action โ UI Manager โ API Manager โ Backend
โ โ
Update UI โ Parse Response
See ARCHITECTURE.md for detailed diagrams.
๐ Learning Resources
For Developers
- Start with QUICK_REFERENCE.md
- Study ARCHITECTURE.md
- Review code comments in JS files
For Designers
- Review assistant.css
- Check color palette in docs
- Inspect animations
For Testers
- Follow testing checklist above
- Test on multiple browsers
- Test error scenarios
๐ค Contributing
This is a proprietary package for Maddox Pay. Internal contributions welcome.
Development Workflow
- Make changes in
packages/smart-ai-assistant/ - Test locally
- Publish assets
- Test in browser
- Document changes
๐ License
Proprietary - Maddox Pay
๐ฅ Credits
Developed for: Maddox Pay
Version: 2.0.0
Last Updated: December 4, 2025
๐ Support
For issues or questions:
- Check documentation files
- Review troubleshooting section
- Check browser console
- Contact development team
๐ฏ Roadmap
Future Enhancements
- Voice input support
- Multi-language support (beyond EN/HI)
- Advanced analytics
- Custom themes
- Keyboard shortcuts
- Search history
- Export chat history
๐ Why Choose Smart AI Assistant?
Before
- Basic error detection
- Simple UI
- Limited functionality
- No file support
- Minimal documentation
After (v2.0)
- โ Advanced error detection with tags
- โ Modern, premium UI
- โ Full file attachment system
- โ Fullscreen previews
- โ Comprehensive documentation
- โ Mobile responsive
- โ Smooth animations
- โ Bilingual support
Ready to get started? Check out DEPLOYMENT_GUIDE.md!
Built with โค๏ธ for Maddox Pay
Powered by Maddox AI