schema-sheets-ollama
v1.2.0
Published
A conversational form filler using Ollama
Readme
Interactive Form Filler
An AI-powered interactive form filling assistant that uses Ollama to help users complete forms through natural conversation. The system takes JSON schemas and guides users through filling out forms conversationally, validating input and asking follow-up questions as needed.
Features
- 🤖 AI-powered conversational form filling
- 📋 JSON Schema validation using AJV
- 🔄 Interactive chat interface with conversation history
- 📄 Support for custom form schemas
- ✅ Real-time form validation and error handling
- 🎯 Smart field completion detection
See real world usage in keet, here: https://github.com/holepunchto/keet-bot-server-examples/blob/ollama-forms/examples/ollama-forms/src/index.mjs
Prerequisites
Install Ollama
Install Ollama on your system:
- macOS: Download from ollama.ai or use Homebrew:
brew install ollama - Linux:
curl -fsSL https://ollama.ai/install.sh | sh
- macOS: Download from ollama.ai or use Homebrew:
Start the Ollama service:
ollama serveDownload the required model:
ollama pull qwen3-coder:latestNote: The project is configured to use
qwen3-coder:latest. This model provides good performance for structured data generation and following JSON schemas.
Install Node.js Dependencies
npm installUsage
Interactive Form Filling
Run the interactive form filler with the default sailing registration schema:
node interactive-test.mjsUsing Custom Schemas
You can use any of the provided example schemas or create your own:
# Use the pet adoption form
node interactive-test.mjs examples/pet-adoption.json
# Use the restaurant order form
node interactive-test.mjs examples/restaurant-order.json
# Use the space mission form
node interactive-test.mjs examples/space-mission.json
# Use the adventure quest form
node interactive-test.mjs examples/adventure-quest.jsonExample Session
📄 Loaded schema from: examples/pet-adoption.json
🤖 Preparing your form experience...
AI: Welcome to our Pet Adoption Application! I'm here to help you through the adoption process. We'll need to gather some information about you and your preferences to find the perfect furry companion.
AI: Let's start with the basics - could you please tell me your full name and how I can contact you?
You: Hi, I'm John Smith and my email is [email protected]
🤖 Processing your response...
📋 Current form data:
{
"name": "John Smith",
"email": "[email protected]"
}
AI: Great to meet you, John! I have your name and email. Now, could you tell me a bit about your living situation? Do you live in a house or apartment, and do you have a yard?
You: I live in a house with a large backyard
...Project Structure
index.mjs- Main FormFiller class and core logicinteractive-test.mjs- Interactive CLI interfacetest.mjs- Automated testing scriptexamples/- Sample JSON schemas for different form typespet-adoption.json- Pet adoption applicationrestaurant-order.json- Restaurant ordering systemspace-mission.json- Space mission applicationadventure-quest.json- Adventure quest character creation
Creating Custom Schemas
You can create your own JSON schemas following the JSON Schema specification. Here's a simple example:
{
"type": "object",
"title": "Contact Form",
"description": "Basic contact information form",
"properties": {
"name": {
"type": "string",
"description": "Full name",
"minLength": 1
},
"email": {
"type": "string",
"format": "email",
"description": "Email address"
},
"message": {
"type": "string",
"description": "Your message",
"minLength": 10
}
},
"required": ["name", "email", "message"]
}Configuration
The system uses the following default configuration:
- Ollama Host:
http://localhost:11434 - Model:
qwen3-coder:latest
You can modify these settings in the FormFiller constructor in index.mjs.
Troubleshooting
Common Issues
- "Connection refused" error: Make sure Ollama is running (
ollama serve) - Model not found: Ensure you've pulled the required model (
ollama pull qwen3-coder:latest) - Validation errors: Check that your JSON schema is valid and follows JSON Schema specification
Testing
Run the automated test suite:
node test.mjsAPI Usage
You can also use the form filler programmatically:
import { fill, generateOpeningMessage } from './index.mjs';
const schema = { /* your JSON schema */ };
const result = await fill("Hello, I'm John", schema);
console.log(result.responseText);Chat Application Integration
The StateManager provides a complete solution for integrating form filling into chat applications. Here's how to set it up:
Basic Setup
import { StateManager, JsonSchemaManager, MemoryStorage } from './state-manager.mjs';
import { readFileSync } from 'fs';
import { resolve } from 'path';
// 1. Load your form schemas
const schemas = [
{
id: 'pet-adoption',
schema: JSON.parse(readFileSync(resolve('examples/pet-adoption.json'), 'utf8')),
metadata: {
title: 'Pet Adoption Application',
description: 'Apply to adopt a pet from our shelter',
keywords: ['pet', 'adoption', 'animal', 'dog', 'cat'],
category: 'applications',
estimatedTime: '5-7 minutes'
}
},
{
id: 'restaurant-order',
schema: JSON.parse(readFileSync(resolve('examples/restaurant-order.json'), 'utf8')),
metadata: {
title: 'Restaurant Order',
description: 'Place an order for food delivery',
keywords: ['food', 'order', 'restaurant', 'delivery'],
category: 'orders',
estimatedTime: '3-5 minutes'
}
}
];
// 2. Initialize the components
const schemaManager = new JsonSchemaManager(schemas);
const storage = new MemoryStorage(); // Use your own storage implementation
const stateManager = new StateManager(storage, schemaManager);Chat Handler Function
async function handleChatMessage(userId, message) {
try {
const response = await stateManager.handleMessage(userId, message);
return {
text: response.responseText,
sessionActive: response.sessionActive,
formData: response.formData || null,
schemaId: response.schemaId || null,
formTitle: response.formTitle || null
};
} catch (error) {
console.error('Chat handler error:', error);
return {
text: "Sorry, I encountered an error. Please try again.",
sessionActive: false
};
}
}
// Usage in your chat application
const userId = "user123";
const userMessage = "I want to adopt a pet";
const response = await handleChatMessage(userId, userMessage);
console.log(response.text); // AI response to send back to userExpress.js Integration Example
import express from 'express';
const app = express();
app.use(express.json());
app.post('/chat', async (req, res) => {
const { userId, message } = req.body;
if (!userId || !message) {
return res.status(400).json({ error: 'userId and message are required' });
}
try {
const response = await stateManager.handleMessage(userId, message);
res.json({
response: response.responseText,
sessionActive: response.sessionActive,
formData: response.formData,
schemaId: response.schemaId,
formTitle: response.formTitle
});
} catch (error) {
console.error('Chat API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(3000, () => {
console.log('Chat API running on port 3000');
});WebSocket Integration Example
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', async (data) => {
try {
const { userId, message } = JSON.parse(data);
const response = await stateManager.handleMessage(userId, message);
ws.send(JSON.stringify({
type: 'chat_response',
response: response.responseText,
sessionActive: response.sessionActive,
formData: response.formData,
schemaId: response.schemaId
}));
} catch (error) {
ws.send(JSON.stringify({
type: 'error',
message: 'Failed to process message'
}));
}
});
});Custom Storage Implementation
For production use, implement your own storage interface:
class DatabaseStorage {
constructor(dbConnection) {
this.db = dbConnection;
}
async load(userId) {
const result = await this.db.query(
'SELECT state FROM user_sessions WHERE user_id = ?',
[userId]
);
return result.length > 0 ? JSON.parse(result[0].state) : null;
}
async save(userId, state) {
await this.db.query(
'INSERT INTO user_sessions (user_id, state, updated_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE state = ?, updated_at = NOW()',
[userId, JSON.stringify(state), JSON.stringify(state)]
);
}
async delete(userId) {
await this.db.query('DELETE FROM user_sessions WHERE user_id = ?', [userId]);
}
}
// Use it with StateManager
const storage = new DatabaseStorage(yourDbConnection);
const stateManager = new StateManager(storage, schemaManager);Session Management
// Check if user has an active session
const sessionStatus = await stateManager.getSessionStatus(userId);
if (sessionStatus.hasActiveSession) {
console.log(`User has active session for: ${sessionStatus.formTitle}`);
}
// End a user's session programmatically
await stateManager.endSession(userId);Response Object Structure
The handleMessage method returns an object with these properties:
responseText(string): The AI's response message to send to the usersessionActive(boolean): Whether the user has an active form sessionformData(object, optional): Completed form data when a form is finishedschemaId(string, optional): ID of the active form schemaformTitle(string, optional): Human-readable title of the active formcurrentFormData(object, optional): Current partial form data during active session
User Commands
Users can control their sessions with these commands:
- End session: "cancel", "stop", "quit", "exit", "end", "abort"
- List forms: "list", "show", "available", "forms", "options", "help"
The StateManager automatically handles these commands and provides appropriate responses.
License
This project is open source. Feel free to modify and distribute as needed.
