An AI chat widget can be much more useful than just another box connected to a language model.
Instead of simply answering questions, it can act as a virtual assistant: understand what a potential client needs, ask a few useful follow-up questions, collect contact details, and pass a structured request to the website owner.
In this article, we will build exactly that kind of assistant for a MODX 2/3 website.
We will create an animated Vanilla JavaScript chat widget, connect it to an AI model through Groq, use Google Cloud Run as a secure API gateway, and teach the assistant to send qualified leads by both email and Telegram.
Along the way, we will also look at real-world problems that usually do not appear in simple AI demos: API regional restrictions, rate limits, secret management, conversation context, invalid email addresses, retries after failed requests, and the differences between MODX 2 and MODX 3 mail APIs.
Source code:
web86/modx-ai-lead-assistant
What we will build:
A visitor opens the chat, enters an email address, describes a task, and answers a few AI-generated questions. When enough information has been collected, the assistant creates a short summary and passes the lead to the website owner by email and Telegram.
What We Are Building
The final architecture looks like this:
Browser
│
▼
Animated Chat Widget
│
▼
MODX / PHP
│
├── conversation history
├── email validation
├── lead handling
├── email notification
│
▼
Cloud Run Gateway
│
├── Groq API
│ ↓
│ GPT-OSS 120B
│
└── Telegram Bot API
Later we will see why Cloud Run became an important part of this architecture.
1. Building the Chat Interface
We start with the frontend.
A small animated button is displayed in the lower-left corner of the website.
When clicked, it expands into a full chat window.
For a small widget like this, React, Vue, or another frontend framework is not necessary. Everything can be built with:
HTML
CSS
Vanilla JavaScript
This has several advantages:
-
minimal bundle size;
-
no additional dependencies;
-
full control over animation;
-
easy integration with almost any CMS.
A simplified structure may look like this:
<div class="fw-assistant">
<div class="fw-assistant-window">
<div class="fw-assistant-header">
AI Assistant
</div>
<div class="fw-assistant-body">
...
</div>
<div class="fw-assistant-footer">
...
</div>
</div>
<button class="fw-assistant-trigger">
...
</button>
</div>
The widget itself can be positioned using:
.fw-assistant {
position: fixed;
left: 24px;
bottom: 24px;
z-index: 99999;
}
For opening and closing the window, a combination of:
opacity
visibility
transform
works very well.
For example:
.fw-assistant-window {
opacity: 0;
visibility: hidden;
transform:
translateY(18px)
scale(0.92);
transition:
opacity .3s ease,
transform .4s cubic-bezier(.16, 1, .3, 1);
}
.fw-assistant.is-open .fw-assistant-window {
opacity: 1;
visibility: visible;
transform:
translateY(0)
scale(1);
}
This gives us a modern, smooth opening animation without requiring a JavaScript animation library.
2. Collect the Email Address First
Before starting the conversation, the visitor is asked to provide an email address.
This is useful for two reasons.
First, if the user closes the website after the conversation, we already have a contact method.
Second, the AI does not need to repeatedly ask:
How can we contact you?
The email address can temporarily be stored in:
sessionStorage
For example:
sessionStorage.setItem(
'fwAssistantEmail',
email
);
Unlike localStorage, session data disappears when the browser session ends.
3. Validate the Email on the Frontend
The backend must always validate the email again, but an obviously invalid address should never be allowed to enter the chat in the first place.
A simple frontend validator:
function isValidEmail(email) {
email = email.trim();
if (
email.length < 5 ||
email.length > 254
) {
return false;
}
return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(email);
}
If the address is invalid:
if (!isValidEmail(email)) {
input.classList.add('is-invalid');
return;
}
The server should still validate it again:
if (
!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)
) {
// reject request
}
Frontend validation improves user experience.
Backend validation protects the application.
4. Why You Should Never Call the AI API Directly from the Browser
A bad architecture would be:
Browser
↓
Groq API
That would require putting the API key inside JavaScript.
Any visitor could open DevTools and see it.
A better architecture is:
Browser
↓
your-site.com/api/chat.php
↓
AI API
The API key must remain on the server.
5. Creating a PHP Endpoint in MODX
On the website, we can create an endpoint such as:
/assets/components/assistant/api/chat.php
In this project we use MODX 2, so first we bootstrap MODX:
define(
'MODX_API_MODE',
true
);
$rootPath = dirname(__DIR__, 4);
require_once $rootPath . '/index.php';
After that, the endpoint can read MODX System Settings:
$model = trim(
(string)$modx->getOption(
'portfolio_assistant.model',
null,
'openai/gpt-oss-120b'
)
);
It is convenient to create a dedicated group of settings:
portfolio_assistant.enabled
portfolio_assistant.model
portfolio_assistant.email_to
portfolio_assistant.max_messages
portfolio_assistant.gateway_url
portfolio_assistant.gateway_secret
portfolio_assistant.telegram_enabled
portfolio_assistant.telegram_gateway_url
This allows the assistant configuration to be changed from MODX Manager without editing PHP files.
6. Storing Conversation History
The AI needs to remember previous messages.
For an MVP, there is no need to create database tables immediately.
A PHP session is enough:
$_SESSION[
'portfolio_assistant_conversation'
];
For example:
$conversation = [
'email' => $email,
'page_url' => $pageUrl,
'started_at' => time(),
'history' => [],
];
Each message uses a very simple structure:
[
'role' => 'user',
'content' => $message,
]
or:
[
'role' => 'assistant',
'content' => $reply,
]
7. Do Not Send Unlimited Conversation History
If the entire conversation is sent to the model every time, token usage will keep growing.
That increases both cost and the risk of reaching API limits.
So the history should be limited:
$history = array_slice(
$history,
-10
);
For a small lead assistant, several recent message pairs are usually enough.
8. The System Prompt Matters More Than the Model
The goal is not to create a general-purpose ChatGPT clone.
Quite the opposite.
The assistant should be tightly constrained.
For example:
You are the virtual AI assistant of Konstantin,
a freelance frontend and backend developer.
Your job is to help visitors understand
Konstantin's services and collect useful
information about their project.
Never pretend to be Konstantin.
Answer in the visitor's language.
Keep replies concise.
Never invent:
- prices
- deadlines
- availability
- portfolio projects
If information is insufficient,
ask one useful next question.
Do not ask all questions at once.
It is also useful to explicitly list the developer's areas of expertise:
PHP
JavaScript
HTML
CSS
WordPress
MODX
Node.js
API integrations
automation
website maintenance
performance optimization
This makes the assistant behave like a real website helper rather than a general chatbot.
9. Tell the AI That the Email Has Already Been Collected
During testing, one interesting bug appeared.
The visitor entered an email before starting the chat, but that email was not included in the AI context.
As a result, the model asked:
Please provide your email address.
even though the user had already entered it.
The solution was to add server-controlled context:
$instructions .= "\n\nVISITOR CONTACT\n\n";
$instructions .=
"The visitor already provided this email address:\n";
$instructions .=
$email . "\n\n";
$instructions .=
"Never ask the visitor for their email again.\n";
An important detail is that this context is generated by the server, not by the browser.
10. Why Google Cloud Run Became Necessary
Initially, the PHP server called the AI provider directly:
MODX
↓
AI provider
However, the website was hosted in an environment where some external APIs were either unstable or inaccessible because of network or regional restrictions.
Instead of moving the entire website to another hosting provider, we introduced a small gateway:
MODX
↓
Google Cloud Run
↓
AI API
This turned out to be a very useful architectural decision.
The website remains on its existing hosting.
Cloud Run only handles external API calls.
11. Building the Cloud Run Gateway
The gateway is a small Node.js service.
For example:
import express from 'express';
const app = express();
app.use(
express.json({
limit: '64kb'
})
);
MODX sends requests to:
POST /chat
Cloud Run then calls the AI provider and returns the response to PHP.
12. Protect the Gateway with a Secret
If the Cloud Run endpoint is publicly accessible without protection, anyone could use it as a free AI proxy.
So MODX sends:
X-Gateway-Secret: ...
On Cloud Run:
const suppliedSecret =
req.get('x-gateway-secret') || '';
Then we verify it:
if (
!secureEqual(
suppliedSecret,
GATEWAY_SECRET
)
) {
return res.status(401).json({
error: 'Invalid gateway credentials'
});
}
The result:
Internet
↓
Cloud Run
without secret → ❌
MODX
↓
X-Gateway-Secret
↓
Cloud Run → ✅
13. Store Secrets Properly
AI API keys and Telegram bot tokens should never be stored in:
JavaScript
Git
HTML
MODX templates
public files
For Cloud Run, Google Secret Manager is a convenient solution.
For example:
GROQ_API_KEY
GATEWAY_SECRET
TELEGRAM_BOT_TOKEN
Cloud Run receives them as environment secrets.
14. Using Groq with GPT-OSS
For this MVP, Groq provides a convenient way to run:
openai/gpt-oss-120b
MODX sends a payload similar to:
$payload = [
'model' => $model,
'store' => false,
'reasoning' => [
'effort' => 'low',
],
'instructions' =>
$instructions,
'input' =>
$history,
'max_output_tokens' =>
400,
];
Cloud Run forwards the request to Groq and returns the result to PHP.
15. Be Aware of Rate Limits
Even free API plans have limits.
And the important limit is not always the number of requests.
Tokens per minute can matter even more.
A large system prompt plus conversation history can consume a surprising number of tokens.
It is therefore useful to:
-
limit conversation history;
-
keep responses short;
-
avoid unnecessarily large output limits;
-
avoid repeating the same information in the prompt;
-
use prompt caching when supported by the provider.
16. When Should a Lead Be Considered Ready?
This is one of the most interesting parts of the project.
The assistant should understand when it no longer makes sense to continue asking questions.
For example:
User:
I need a WordPress blog.
Assistant:
Do you already have a design?
User:
No, I need everything done from scratch.
I already have a specification and can send it.
At this point there may already be enough information to hand the request to a human.
So the model receives an additional instruction:
For every response determine whether
the visitor's request is sufficiently clear
to hand off to Konstantin.
It then returns something like:
{
"reply": "...",
"ready_to_handoff": true,
"handoff_message": "...",
"lead": {
"name": "John",
"website": null,
"request": "WordPress blog",
"summary": "..."
}
}
17. Use Structured Output Instead of Parsing Text
A bad approach would be searching for text markers such as:
HANDOFF_READY
or:
[send_email=true]
A much more reliable approach is to require JSON that follows a schema.
For example:
'text' => [
'format' => [
'type' => 'json_schema',
'name' =>
'portfolio_assistant_turn',
'schema' => [
...
],
],
],
PHP then receives structured data instead of trying to parse natural language.
18. The AI Must Not Claim That a Message Was Sent
This is an important architectural detail.
The model may decide:
"ready_to_handoff": true
But this does not mean an email was actually delivered.
The correct flow is:
AI:
ready_to_handoff = true
↓
PHP sends email
↓
success?
↓
YES
↓
show:
"Your request has been forwarded"
If SMTP fails:
AI:
ready_to_handoff = true
↓
email failed
↓
DO NOT claim
that the message was sent
This prevents the AI from accidentally lying to the user.
19. Do Not Save the User Message Too Early
Another interesting bug appeared during development.
Initially, the user message was immediately written into the persistent session history:
$conversation['history'][] = [
'role' => 'user',
'content' => $message,
];
Then the AI request was executed.
If the AI or email request failed, the visitor clicked Retry.
The history then contained:
User:
the same message
User:
the same message
A better approach is to first create temporary history:
$history =
$conversation['history'];
$history[] = [
'role' => 'user',
'content' => $message,
];
Only after the request completes successfully:
$conversation['history'] =
$history;
This is essentially a small transaction-like pattern.
20. Sending Email with MODX 2
It is important not to confuse MODX 2 with MODX 3 here (see in Github repo folder /modx3).
In MODX 2, the mail service is loaded using:
$mail = $modx->getService(
'mail',
'mail.modPHPMailer'
);
Then:
$mail->set(
modMail::MAIL_BODY,
$html
);
$mail->set(
modMail::MAIL_FROM,
$sender
);
$mail->set(
modMail::MAIL_SUBJECT,
'[Portfolio Lead] ' . $subject
);
$mail->address(
'to',
$emailTo
);
$mail->address(
'reply-to',
$visitorEmail
);
$mail->setHTML(true);
$sent =
$mail->send();
$mail->reset();
The email can include:
Visitor email
Name
Website
Source page
Request
AI summary
Full conversation transcript
21. Telegram as a Second Notification Channel
Email is good for details.
Telegram is good for speed.
So when a handoff happens, we can send:
Email
+
Telegram
A Telegram notification may look like this:
? New Portfolio Lead
? Name: John
? Email: john@example.com
? Website: example.com
? Request
Build a WordPress website.
? AI Summary
The client needs a small corporate website...
The full transcript can remain in the email.
22. Why Telegram Also Goes Through Cloud Run
During testing, we discovered that the website hosting server could not reliably connect to:
api.telegram.org
The request simply timed out.
Cloud Run, however, could reach Telegram without problems.
So the architecture became:
MODX
↓
Cloud Run /telegram
↓
Telegram Bot API
Another benefit is that the Telegram bot token can remain in Secret Manager.
MODX does not need to know it at all.
23. Creating a Telegram Endpoint in Cloud Run
We add another endpoint:
app.post(
'/telegram',
async (req, res) => {
...
}
);
Cloud Run receives only the lead data:
{
"name": "John",
"email": "john@example.com",
"website": "example.com",
"request": "Build a website",
"summary": "...",
"page_url": "https://example.com/"
}
Then it calls:
https://api.telegram.org/bot.../sendMessage
The Telegram token never leaves Cloud Run.
24. Email and Telegram Should Be Independent
A bad design would be:
Telegram failed
↓
entire handoff failed
Telegram is only an additional notification channel.
A better approach:
$handoffSent =
$emailSent ||
$telegramSent;
If at least one channel succeeds, the lead is considered delivered.
For debugging, the API can also return:
{
"handoff_sent": true,
"handoff_channels": {
"email": true,
"telegram": true
}
}
This is very useful during development.
25. What the Frontend Receives
A normal response may look like:
{
"ok": true,
"message": "Could you tell me..."
}
After a successful handoff:
{
"ok": true,
"message": "Thank you! I have forwarded your request to Konstantin.",
"handoff_sent": true
}
The JavaScript can then disable the composer:
if (result.handoffSent) {
chatInput.disabled = true;
chatInput.placeholder =
'Request sent ✓';
sendButton.disabled = true;
}
The conversation ends naturally.
26. Final Architecture
The final stack looks like this:
┌─────────────────────────┐
│ Website Visitor │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ Animated Vanilla JS Chat│
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ MODX 2 / PHP │
│ │
│ • session │
│ • email validation │
│ • history │
│ • system prompt │
│ • lead logic │
│ • email │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ Google Cloud Run │
│ │
│ /chat │
│ /telegram │
└────────┬─────────┬──────┘
│ │
▼ ▼
┌─────────────┐ ┌───────────────┐
│ Groq │ │ Telegram API │
│ GPT-OSS │ └───────────────┘
│ 120B │
└─────────────┘
What We Ended Up With
The assistant is no longer just a chatbot.
It performs a concrete business task:
Visitor
↓
Conversation
↓
Requirements clarification
↓
Lead qualification
↓
AI summary
↓
Email + Telegram
↓
Human follow-up
In other words, AI does not replace the developer.
It acts as the first point of contact and passes a structured request to a human.
Possible Improvements
The current MVP is already fully functional, but there are many ways it could be extended.
For example:
-
store leads in a dedicated MODX database table;
-
add a lead history section to MODX Manager;
-
add a “Start new conversation” button;
-
connect the assistant to a knowledge base built from website articles;
-
provide AI with structured portfolio information;
-
add analytics events;
-
implement stronger IP-based abuse protection;
-
add Cloudflare Turnstile for suspicious traffic;
-
configure a fallback AI provider;
-
allow visitors to upload a project specification;
-
send attachments together with the lead.
But for a first production-ready version, the current implementation already covers the most important parts.
The Main Lesson
When building an AI assistant for a real website, the interesting part is not just:
call AI API
The real work happens around it.
You need to think about:
UX
security
API keys
conversation state
rate limits
failures
email
Telegram
handoff
validation
network restrictions
These details are what turn a small AI demo into a useful production tool.
In this project, we ended up with a virtual assistant that can understand a visitor's request, ask useful follow-up questions, avoid inventing prices or deadlines, determine when the task is clear enough for a human, and notify the website owner through two independent channels.
And the frontend still remains a lightweight Vanilla JavaScript widget with no additional framework dependencies.
Source Code
The full source code is available on GitHub:
The repository includes:
frontend/
assistant.html
assistant.css
assistant.js
modx/
chat.php
cloud-run/
index.js
package.json
.env.example
README.md
LICENSE
No production API keys, Telegram tokens, or gateway secrets are included in the repository.
