Appearance
Validation with Zod
The SDK exports Zod schemas for runtime validation of events and actions.
Event Validation
Validate incoming events to ensure they match the expected format:
typescript
import { AiFlowEventSchema } from "@sipgate/ai-flow-sdk";
import { z } from "zod";
app.post("/webhook", async (req, res) => {
try {
// Validate incoming event
const event = AiFlowEventSchema.parse(req.body);
// event is now type-safe and validated
const action = await assistant.onEvent(event);
if (action) {
res.json(action);
} else {
res.status(204).send();
}
} catch (error) {
if (error instanceof z.ZodError) {
console.error("Invalid event:", error.errors);
res.status(400).json({
error: "Invalid event format",
details: error.errors
});
} else {
console.error("Error:", error);
res.status(500).json({ error: "Internal server error" });
}
}
});Action Validation
Validate outgoing actions before sending:
typescript
import { AiFlowActionSchema } from "@sipgate/ai-flow-sdk";
import { z } from "zod";
onUserSpeak: async (event) => {
const action = {
type: "speak",
session_id: event.session.id,
text: "Hello!",
};
try {
// Validate action before returning
const validatedAction = AiFlowActionSchema.parse(action);
return validatedAction;
} catch (error) {
if (error instanceof z.ZodError) {
console.error("Invalid action:", error.errors);
// Return a safe fallback
return "I encountered an error. Please try again.";
}
throw error;
}
}Custom Validation
You can extend the schemas for custom validation:
typescript
import { AiFlowEventSchema } from "@sipgate/ai-flow-sdk";
import { z } from "zod";
// Extend the schema with custom validation
const CustomEventSchema = AiFlowEventSchema.extend({
session: z.object({
id: z.string().uuid(),
account_id: z.string().min(1),
// Add custom validation
}),
});
app.post("/webhook", async (req, res) => {
try {
const event = CustomEventSchema.parse(req.body);
// Process validated event
} catch (error) {
// Handle validation errors
}
});Benefits
- Type Safety - Catch errors at runtime
- Better Error Messages - Zod provides detailed error information
- Data Integrity - Ensure events and actions match expected format
- Debugging - Easier to identify malformed data
Next Steps
- Direct Integration - Working without the wrapper
- API Reference - Complete API documentation