Real-World Examples
1. Document Summarizer
Takes a long document and returns a structured summary with TL;DR and key points.
src/services/summarizer.service.js
import openai from '../lib/openai.js';
export async function summarizeDocument(text, style = 'concise') {
const styleInstructions = {
concise: 'Provide a 3-5 sentence summary.',
bullets: 'Provide exactly 5 bullet points covering the main ideas.',
executive: 'Write an executive summary: one sentence TL;DR, then 3 key takeaways for a decision-maker.',
};
const response = await openai.chat.completions.create({
model: 'gpt-4o',
response_format: { type: 'json_object' },
temperature: 0.3,
messages: [
{
role: 'system',
content: `You are a document summarization assistant.
${styleInstructions[style] || styleInstructions.concise}
Always respond as JSON: { "tldr": "...", "summary": "...", "keyPoints": ["...", "..."] }`,
},
{ role: 'user', content: `Summarize the following document:\n\n${text}` },
],
max_tokens: 800,
});
return JSON.parse(response.choices[0].message.content);
}
src/routes/summarize.route.js
import { Router } from 'express';
import { summarizeDocument } from '../services/summarizer.service.js';
import { llmRateLimit } from '../middleware/llmRateLimit.js';
const router = Router();
router.post('/', llmRateLimit, async (req, res, next) => {
try {
const { text, style } = req.body;
if (!text || typeof text !== 'string') return res.status(400).json({ error: 'text is required' });
if (text.length > 100000) return res.status(400).json({ error: 'Document too long (max 100,000 characters)' });
res.json(await summarizeDocument(text, style));
} catch (err) { next(err); }
});
export default router;
Streaming version for large documents:
import openai from '../lib/openai.js';
router.post('/stream', llmRateLimit, async (req, res, next) => {
try {
const { text } = req.body;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
stream: true,
messages: [
{ role: 'system', content: 'Summarize the document in clear bullet points.' },
{ role: 'user', content: text },
],
});
for await (const chunk of stream) {
const token = chunk.choices[0]?.delta?.content;
if (token) res.write(`data: ${JSON.stringify({ token })}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
} catch (err) { next(err); }
});
2. Customer Support Chatbot with Tool Use
A full support bot with tool use — looks up orders, cancels them, and checks return policies.
src/services/support.tools.js
import db from '../db.js';
export const supportTools = [
{
type: 'function',
function: {
name: 'get_order',
description: "Look up a specific order or retrieve the user's recent orders",
parameters: {
type: 'object',
properties: {
orderId: { type: 'string' },
userId: { type: 'string' },
},
},
},
},
{
type: 'function',
function: {
name: 'cancel_order',
description: 'Cancel an order. Only call this after the user explicitly confirms.',
parameters: {
type: 'object',
properties: { orderId: { type: 'string' } },
required: ['orderId'],
},
},
},
{
type: 'function',
function: {
name: 'get_return_policy',
description: 'Get the return policy for a product category',
parameters: {
type: 'object',
properties: { category: { type: 'string' } },
required: ['category'],
},
},
},
];
const toolHandlers = {
async get_order({ orderId, userId }) {
if (orderId) return db.orders.findById(orderId);
return db.orders.findMany({ where: { userId }, take: 5, orderBy: { createdAt: 'desc' } });
},
async cancel_order({ orderId }) {
const order = await db.orders.findById(orderId);
if (!order) return { error: 'Order not found' };
if (order.status === 'shipped') return { error: 'Cannot cancel — order already shipped' };
await db.orders.update({ where: { id: orderId }, data: { status: 'cancelled' } });
return { success: true, message: `Order ${orderId} cancelled. Refund in 3-5 business days.` };
},
async get_return_policy({ category }) {
const policies = {
electronics: '30-day return window. Item must be unopened.',
clothing: '60-day return window. Item must have original tags.',
default: '30-day return window. Item must be in original condition.',
};
return { policy: policies[category] || policies.default };
},
};
export async function executeSupportTool(name, args) {
const handler = toolHandlers[name];
if (!handler) throw new Error(`Unknown tool: ${name}`);
return handler(args);
}
src/services/support.service.js
import openai from '../lib/openai.js';
import { supportTools, executeSupportTool } from './support.tools.js';
function buildSystemPrompt(user) {
return `You are a helpful customer support agent for ShopCo.
Customer: ${user.name} (${user.email}) | Plan: ${user.accountStatus}
- Look up order details before discussing them — never guess order status
- Ask for confirmation before cancelling any order
- Never invent policies — use the get_return_policy tool
Today: ${new Date().toDateString()}`.trim();
}
export async function supportChat(user, messages, maxIterations = 6) {
const systemPrompt = buildSystemPrompt(user);
let iteration = 0;
while (iteration < maxIterations) {
iteration++;
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'system', content: systemPrompt }, ...messages],
tools: supportTools,
tool_choice: 'auto',
});
const choice = response.choices[0];
if (choice.finish_reason !== 'tool_calls') {
return { reply: choice.message.content, toolsUsed: iteration - 1 };
}
messages = [...messages, choice.message];
const toolResults = await Promise.all(
choice.message.tool_calls.map(async (tc) => {
const result = await executeSupportTool(tc.function.name, JSON.parse(tc.function.arguments));
return { role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) };
})
);
messages = [...messages, ...toolResults];
}
return { reply: 'I need to escalate this to a human specialist. Please hold.', toolsUsed: maxIterations };
}
src/routes/support.route.js
import { Router } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { supportChat } from '../services/support.service.js';
import { getHistory, saveHistory } from '../services/session.service.js';
import { llmRateLimit } from '../middleware/llmRateLimit.js';
import auth from '../middleware/auth.js';
const router = Router();
router.post('/', auth, llmRateLimit, async (req, res, next) => {
try {
const { sessionId = uuidv4(), message } = req.body;
let history = await getHistory(sessionId);
history.push({ role: 'user', content: message });
const { reply, toolsUsed } = await supportChat(req.user, history);
history.push({ role: 'assistant', content: reply });
await saveHistory(sessionId, history);
res.json({ sessionId, reply, toolsUsed });
} catch (err) { next(err); }
});
export default router;
3. Code Review Assistant
Analyzes code and returns severity-tagged issues with fix suggestions.
src/services/codeReview.service.js
import anthropic from '../lib/anthropic.js';
const SYSTEM_PROMPT = `You are an expert code reviewer. Analyze the provided code and return a JSON report.
Focus on: bugs, security vulnerabilities, performance, code quality.
Respond ONLY with JSON:
{ "score": <1-10>, "summary": "...", "issues": [{ "severity": "critical|high|medium|low", "type": "bug|security|performance|quality", "line": <number|null>, "description": "...", "suggestion": "..." }], "positives": ["..."] }`;
export async function reviewCode(code, language = 'javascript') {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 2048,
system: SYSTEM_PROMPT,
messages: [{ role: 'user', content: `Review this ${language} code:\n\n\`\`\`${language}\n${code}\n\`\`\`` }],
temperature: 0,
});
return JSON.parse(response.content[0].text);
}
src/routes/codeReview.route.js
import { Router } from 'express';
import { reviewCode } from '../services/codeReview.service.js';
import { llmRateLimit } from '../middleware/llmRateLimit.js';
const router = Router();
const SUPPORTED_LANGUAGES = ['javascript', 'typescript', 'python', 'go', 'java', 'rust', 'php'];
router.post('/', llmRateLimit, async (req, res, next) => {
try {
const { code, language = 'javascript' } = req.body;
if (!code) return res.status(400).json({ error: 'code is required' });
if (code.length > 20000) return res.status(400).json({ error: 'Code exceeds 20,000 character limit' });
if (!SUPPORTED_LANGUAGES.includes(language)) return res.status(400).json({ error: `Unsupported language` });
res.json(await reviewCode(code, language));
} catch (err) {
if (err instanceof SyntaxError) return res.status(500).json({ error: 'Review service returned unexpected format' });
next(err);
}
});
export default router;
4. Sentiment Analysis & Content Moderation
Classify user-generated content at scale. Batch multiple texts in one API call.
src/services/sentiment.service.js
import openai from '../lib/openai.js';
export async function analyzeSentiment(texts) {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
response_format: { type: 'json_object' },
temperature: 0,
messages: [
{
role: 'system',
content: `Analyze sentiment and moderation flags for each text.
Return JSON: { "results": [ { "id": <number>, "sentiment": "positive|neutral|negative", "score": <0-1>, "flags": ["spam"|"offensive"|"misinformation"] } ] }
flags array is empty if none apply.`,
},
{ role: 'user', content: JSON.stringify(texts.map((text, i) => ({ id: i, text }))) },
],
});
return JSON.parse(response.choices[0].message.content).results;
}
export async function moderateContent(text) {
const [result] = await analyzeSentiment([text]);
return { allowed: result.flags.length === 0, sentiment: result.sentiment, flags: result.flags };
}
Moderation as middleware
import { moderateContent } from '../services/sentiment.service.js';
export async function moderationGuard(req, res, next) {
const text = req.body.comment || req.body.review || req.body.message;
if (!text) return next();
const result = await moderateContent(text);
if (!result.allowed) {
return res.status(422).json({ error: 'Content flagged', flags: result.flags });
}
req.sentimentScore = result.score;
next();
}
// Usage: router.post('/comments', moderationGuard, saveComment)
5. RAG — Answer Questions from Your Docs
npm install @pinecone-database/pinecone
src/services/rag.service.js
import { Pinecone } from '@pinecone-database/pinecone';
import openai from '../lib/openai.js';
const pinecone = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
const index = pinecone.index('knowledge-base');
export async function indexDocument(id, text, metadata = {}) {
const res = await openai.embeddings.create({ model: 'text-embedding-3-small', input: text });
await index.upsert([{ id, values: res.data[0].embedding, metadata: { text, ...metadata } }]);
}
export async function askQuestion(question) {
const res = await openai.embeddings.create({ model: 'text-embedding-3-small', input: question });
const result = await index.query({ vector: res.data[0].embedding, topK: 5, includeMetadata: true });
const docs = result.matches
.filter(m => m.score > 0.75)
.map(m => m.metadata.text)
.join('\n\n---\n\n');
if (!docs) return { answer: "I don't have information about that.", sources: [] };
const answer = await openai.chat.completions.create({
model: 'gpt-4o',
temperature: 0.2,
messages: [
{
role: 'system',
content: `Answer using ONLY the provided context. If the answer is not in the context, say "I don't have that information."\n\nContext:\n${docs}`,
},
{ role: 'user', content: question },
],
});
return {
answer: answer.choices[0].message.content,
sources: result.matches.filter(m => m.score > 0.75).map(m => ({ id: m.id, score: m.score })),
};
}
6. AI Email Generator
Bullet points → professional email with tone control.
src/services/emailGen.service.js
import openai from '../lib/openai.js';
export async function generateEmail({ subject, bulletPoints, tone = 'professional', recipientName, senderName }) {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
response_format: { type: 'json_object' },
temperature: 0.7,
messages: [
{
role: 'system',
content: `You write professional emails. Respond with JSON: { "subject": "...", "body": "..." }. Body uses \\n\\n for paragraphs.`,
},
{
role: 'user',
content: `Write a ${tone} email.
Subject hint: ${subject}
Recipient: ${recipientName || 'the recipient'}
Sender: ${senderName || 'me'}
Key points:
${bulletPoints.map((p, i) => `${i + 1}. ${p}`).join('\n')}`,
},
],
});
return JSON.parse(response.choices[0].message.content);
}
7. Natural Language to SQL
src/services/nlToSql.service.js
import openai from '../lib/openai.js';
const SCHEMA = `
Tables: users(id, name, email, created_at, plan), orders(id, user_id, status, total_amount, created_at), products(id, name, category, price, stock_quantity), order_items(id, order_id, product_id, quantity, unit_price)
Relationships: orders.user_id→users.id, order_items.order_id→orders.id, order_items.product_id→products.id
`.trim();
export async function generateSQL(query) {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
response_format: { type: 'json_object' },
temperature: 0,
messages: [
{
role: 'system',
content: `SQL generator for PostgreSQL. Schema:\n${SCHEMA}\nRules: SELECT only, always LIMIT ≤100.\nRespond as JSON: { "sql": "...", "explanation": "...", "assumptions": ["..."] }`,
},
{ role: 'user', content: query },
],
});
return JSON.parse(response.choices[0].message.content);
}
src/routes/nlToSql.route.js
import { Router } from 'express';
import { generateSQL } from '../services/nlToSql.service.js';
import db from '../db.js';
import { llmRateLimit } from '../middleware/llmRateLimit.js';
import auth from '../middleware/auth.js';
const router = Router();
const readonlyDb = db.readonlyPool;
router.post('/', auth, llmRateLimit, async (req, res, next) => {
try {
const { query } = req.body;
if (!query) return res.status(400).json({ error: 'query is required' });
const { sql, explanation, assumptions } = await generateSQL(query);
if (!sql.trim().toUpperCase().startsWith('SELECT')) {
return res.status(400).json({ error: 'Only SELECT queries are allowed' });
}
const rows = await readonlyDb.query(sql);
res.json({ query: sql, explanation, assumptions, rowCount: rows.length, data: rows });
} catch (err) { next(err); }
});
export default router;
Always use a read-only database connection
Even with the SELECT guard, connect to a read-only replica or role. Defense in depth — never rely on a single check.