Tutorials
Tutorial 3: AI Chatbot
A chat page whose replies stream in from an AI model as they are written, with each visitor's conversation kept between messages.
- one page (
GET /chat) and one endpoint (POST /chat/send) that streams the reply as Server-Sent Events; - multi-turn history per visitor;
- Anthropic by default; OpenAI or a local Ollama with one line of config;
- a CSRF token on every message and a limit of 30 messages an hour per IP, because each message is a paid call to the provider.
Prerequisites
#- PHP 8.2 or later, with the
curlextension - Composer
- An Anthropic API key (or OpenAI, or Ollama running locally)
Step 1: Create the app
#composer create-project taphra/skeleton my-chat
cd my-chatStep 2: Configure the AI provider
#Create app/Config/ai.yml:
default_provider: anthropic
providers:
anthropic:
api_key: "${ANTHROPIC_API_KEY}"
model: claude-opus-5-5
max_tokens: 4096
# Requests (messages included) are not written to app/tmp/Log/ai.log.
logging:
enabled: false${ANTHROPIC_API_KEY} is read from the environment. app/bootstrap.php
loads .env into the environment on every request, so put the key there
(and never in a file you commit):
echo "ANTHROPIC_API_KEY=sk-ant-your-key" >> .envTo use OpenAI or Ollama instead, add the provider and change
default_provider:
default_provider: ollama
providers:
openai:
api_key: "${OPENAI_API_KEY}"
model: gpt-4o
ollama:
base_url: "http://localhost:11434"
model: llama3Step 3: The system prompt
#Prompt templates live in app/Prompts/. Create
app/Prompts/assistant.prompt.php:
<?php
use Taphra\Ai\Prompt;
return new class extends Prompt {
public function system(): string
{
return 'You are a helpful assistant. Answer clearly and concisely.';
}
public function user(): string
{
return '{message}';
}
};Step 4: The controller
#AppController checks the CSRF token on every request that is not GET,
HEAD or OPTIONS, so a page on another site cannot post messages (and spend
your credits) through a visitor's browser. Create
app/Controllers/ChatController.php:
<?php
namespace App\Controllers;
use Taphra\Ai\AI;
use Taphra\Ai\Prompt;
use Taphra\RateLimiter;
use Taphra\Request;
use Taphra\Session;
class ChatController extends AppController
{
// GET /chat
public function index(): void
{
$this->viewTitle = 'Chat';
$this->autoRender = true;
}
// POST /chat/send message=...&_csrf_token=...
public function send(): string
{
$message = trim((string) ($_POST['message'] ?? ''));
if ($message === '' || mb_strlen($message) > 4000) {
return $this->error(422, 'Write a message of 1 to 4000 characters.');
}
// 30 messages per hour per client IP. attempt() counts and checks
// in one step, so parallel requests cannot all slip through.
$limiter = RateLimiter::make('chat', 30, 3600);
if (!$limiter->attempt(Request::clientIP())) {
return $this->error(429, 'Too many messages. Try again later.');
}
// The visitor's history, kept in the cache under a hash of their
// session id (sse() below closes the session while the reply streams,
// so the reply could not be saved in the session itself).
$conversation = AI::conversation('chat-' . hash('sha256', Session::sessionId()), 'cache');
if ($conversation->count() === 0) {
$conversation->addSystemMessage(Prompt::load('assistant')->toMessages()[0]['content']);
}
$conversation->addUserMessage($message);
// sse() sends each value as "data: <value>", then "data: [DONE]".
$this->sse((function () use ($conversation) {
$reply = '';
try {
foreach (AI::stream($conversation->getMessages()) as $chunk) {
$reply .= $chunk;
yield json_encode(['chunk' => $chunk]);
}
} catch (\Throwable $e) {
$this->log('AI provider: ' . $e->getMessage(), \Taphra\Logger::TYPE_ERROR);
yield json_encode(['error' => 'The AI provider did not answer.']);
}
if ($reply !== '') {
$conversation->addAssistantMessage($reply);
}
})());
}
private function error(int $status, string $message): string
{
http_response_code($status);
header('Content-Type: application/json');
return json_encode(['error' => $message]);
}
}The provider's error goes to the log (app/tmp/Log/), not to the browser.
The cache backend keeps a conversation for an hour after its last
message; the session backend (AI::conversation('chat', 'session')) keeps
it in the session, for code that does not stream.
Step 5: The page
#Create app/Views/chat/index.tpl.php. The form carries the CSRF token
($this->csrf()); the script posts the form's fields and reads the reply as
it streams in:
<div id="messages" style="min-height: 300px; border: 1px solid #ccc; padding: 1rem; white-space: pre-wrap"></div>
<form id="chat-form" style="margin-top: 1rem">
<?= $this->csrf() ?>
<input type="text" name="message" id="message" placeholder="Type a message" autocomplete="off" required style="width: 80%">
<button type="submit">Send</button>
</form>
<script>
const form = document.getElementById('chat-form');
const box = document.getElementById('messages');
function line(who, text) {
const p = document.createElement('p');
p.textContent = who + ': ' + text;
box.appendChild(p);
return p;
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const fields = new URLSearchParams(new FormData(form));
line('You', fields.get('message'));
form.message.value = '';
const reply = line('Assistant', '');
let text = '';
const res = await fetch('/chat/send', { method: 'POST', body: fields });
if (!res.ok) {
reply.textContent = 'Assistant: ' + ((await res.json()).error || res.status);
return;
}
// Each event is a "data: {...}" line; the last one is "data: [DONE]".
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const l of lines) {
if (!l.startsWith('data: ') || l === 'data: [DONE]') continue;
const data = JSON.parse(l.slice(6));
text += data.chunk ?? ('\n' + data.error);
reply.textContent = 'Assistant: ' + text;
}
}
});
</script>The page writes text with textContent, never innerHTML, so a reply that
contains HTML is shown, not run.
Step 6: Routes
#Replace app/Config/routes.yml with:
GET:
/health: health/index
/chat: chat/index
POST:
/chat/send: chat/send/chat/send takes POST only: a link or an image on another site cannot
trigger a paid call with a GET.
Step 7: Run it
#php taphra serveOpen http://127.0.0.1:8000/chat and send a message. To see what the browser does, in a second terminal fetch the page (keeping its session cookie) and read the CSRF token from the form:
export TOKEN=$(curl -s -c cookies.txt http://127.0.0.1:8000/chat | sed -n 's/.*name="_csrf_token" value="\([0-9a-f]*\)".*/\1/p')
curl -s -b cookies.txt -X POST http://127.0.0.1:8000/chat/send \
--data-urlencode "_csrf_token=$TOKEN" \
--data-urlencode "message=Hello!"The reply streams back a few words per event (the words depend on the model):
data: {"chunk":"..."}
...
data: [DONE]Without the token the message is refused, and a GET is not allowed:
curl -s -o /dev/null -w '%{http_code}\n' -b cookies.txt -X POST http://127.0.0.1:8000/chat/send --data-urlencode "message=Hello!"
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/chat/send403
405Before you deploy
#- Put the chat behind a sign-in: anyone who can open the page can spend your
credits.
composer create-project taphra/ai-chat my-chatis this chatbot with a password gate, per-session history, a JSON endpoint and a finished page. - Behind a proxy or load balancer, list it under
trusted_proxiesinapp/Config/app.ymlso the rate limit sees each client's own IP. - An unset
APP_ENVmeans production: no debug pages.
Next steps
#- Let the model call your own functions: Tutorial 5: Agent with tools
- Expose your app to MCP clients such as desktop AI apps and IDEs: Tutorial 4: MCP server