Appearance
Express.js Integration
Complete guide for integrating the SDK with Express.js.
Basic Setup
The simplest way to use the SDK with Express.js:
typescript
import express from "express";
import { AiFlowAssistant } from "@sipgate/ai-flow-sdk";
const app = express();
app.use(express.json());
const assistant = AiFlowAssistant.create({
onSessionStart: async (event) => {
return "Welcome! How can I help you today?";
},
onUserSpeak: async (event) => {
return processUserInput(event.text);
},
onSessionEnd: async (event) => {
await cleanupSession(event.session.id);
},
});
// Webhook endpoint
app.post("/webhook", assistant.express());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`AI Flow assistant running on port ${PORT}`);
});Complete Example
Here's a complete example with error handling and logging:
typescript
import express from "express";
import { AiFlowAssistant } from "@sipgate/ai-flow-sdk";
const app = express();
app.use(express.json());
const assistant = AiFlowAssistant.create({
debug: process.env.NODE_ENV !== "production",
onSessionStart: async (event) => {
console.log(`Session started: ${event.session.id}`);
return "Welcome! How can I help you today?";
},
onUserSpeak: async (event) => {
try {
return await processUserInput(event.text);
} catch (error) {
console.error("Error processing input:", error);
return "I'm sorry, I encountered an error. Please try again.";
}
},
onSessionEnd: async (event) => {
await cleanupSession(event.session.id);
},
});
// Webhook endpoint
app.post("/webhook", assistant.express());
// Health check
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`AI Flow assistant running on port ${PORT}`);
});Error Handling
The express() middleware automatically handles errors, but you can add custom error handling:
typescript
app.post("/webhook", (req, res, next) => {
assistant.express()(req, res).catch(next);
});
app.use((err, req, res, next) => {
console.error("Error:", err);
res.status(500).json({ error: "Internal server error" });
});Authentication
Add authentication middleware before the webhook:
typescript
app.post("/webhook", authenticate, assistant.express());
function authenticate(req, res, next) {
const apiKey = req.headers["x-api-key"];
if (apiKey !== process.env.API_KEY) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
}Multiple Endpoints
You can use multiple assistants for different endpoints:
typescript
const salesAssistant = AiFlowAssistant.create({
onUserSpeak: async (event) => {
return "Welcome to sales!";
},
});
const supportAssistant = AiFlowAssistant.create({
onUserSpeak: async (event) => {
return "Welcome to support!";
},
});
app.post("/webhook/sales", salesAssistant.express());
app.post("/webhook/support", supportAssistant.express());Next Steps
- WebSocket Integration - WebSocket integration guide
- Examples - More integration examples