The Chatbot Engineer builds conversational AI experiences that feel natural and stay grounded in facts. The biggest failure mode of LLM chatbots is hallucination - the model confidently states false information. The solution is RAG: retrieve relevant context from a trusted knowledge base and inject it into every prompt. Never let an LLM answer from parametric knowledge alone when you can ground it in current facts.
Streaming Chat API (Next.js)
// app/api/chat/route.ts
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await client.messages.stream({
model: 'claude-opus-5',
max_tokens: 1024,
system: 'You are a helpful assistant for Acme Corp. Answer questions about our product. If you don\'t know, say so.',
messages,
});
// Return a ReadableStream compatible with the Fetch API
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {
controller.enqueue(new TextEncoder().encode(chunk.delta.text));
}
}
controller.close();
},
});
return new Response(readable, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
Streaming Chat UI (React)
import { useState, useRef } from 'react';
interface Message { role: 'user' | 'assistant'; content: string }
export function ChatInterface() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [streaming, setStreaming] = useState(false);
async function sendMessage() {
if (!input.trim() || streaming) return;
const userMessage: Message = { role: 'user', content: input };
const updatedMessages = [...messages, userMessage];
setMessages(updatedMessages);
setInput('');
setStreaming(true);
// Add empty assistant message that will be streamed into
setMessages(prev => [...prev, { role: 'assistant', content: '' }]);
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: updatedMessages }),
});
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const text = decoder.decode(value);
setMessages(prev =>
prev.map((m, i) =>
i === prev.length - 1 ? { ...m, content: m.content + text } : m
)
);
}
setStreaming(false);
}
return (
<div className="chat">
{messages.map((m, i) => <div key={i} className={m.role}>{m.content}</div>)}
<input value={input} onChange={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && sendMessage()} />
</div>
);
}
Conversation Memory Management
- Keep conversation history in the
messagesarray and send full history with each request - Claude is stateless - Limit history to last N messages or last N tokens to avoid context window overflow; summarize older turns with a separate LLM call
- Inject RAG context as a system message or as a leading
userturn before the conversation - never concatenate retrieved text directly into a user message mid-conversation - Log every conversation turn with timestamps, model version, token counts, and latency - you will need this data for fine-tuning and evaluation
- Implement chat session IDs so users can return to previous conversations; store sessions in Redis (TTL) or Postgres (persistent)