Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option for the ollama server to not be online all the time #153

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ module.exports = {
},
ollama: {
apiUrl: process.env.OLLAMA_API_URL || 'http://localhost:11434',
model: process.env.OLLAMA_MODEL || 'llama2'
model: process.env.OLLAMA_MODEL || 'llama2',
skipValidation: process.env.OLLAMA_SKIP_VALIDATION || "false"
},
aiProvider: process.env.AI_PROVIDER || 'openai',
scanInterval: process.env.SCAN_INTERVAL || '*/30 * * * *',
Expand Down
17 changes: 15 additions & 2 deletions routes/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const { authenticateJWT, isAuthenticated } = require('./auth.js');
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

const config = require("../config/config.js");

// API endpoints that should not redirect
const API_ENDPOINTS = ['/health'];
Expand Down Expand Up @@ -415,7 +415,8 @@ router.get('/setup', async (req, res) => {
PROMPT_TAGS: normalizeArray(process.env.PROMPT_TAGS),
PAPERLESS_AI_VERSION: configFile.PAPERLESS_AI_VERSION || ' ',
PROCESS_ONLY_NEW_DOCUMENTS: process.env.PROCESS_ONLY_NEW_DOCUMENTS || 'yes',
USE_EXISTING_DATA: process.env.USE_EXISTING_DATA || 'no'
USE_EXISTING_DATA: process.env.USE_EXISTING_DATA || 'no',
OLLAMA_SKIP_VALIDATION: process.env.OLLAMA_SKIP_VALIDATION || "false"
};

// Check both configuration and users
Expand Down Expand Up @@ -696,6 +697,18 @@ router.post('/manual/playground', express.json(), async (req, res) => {
)
return res.json(analyzeDocument);
} else if (process.env.AI_PROVIDER === 'ollama') {

if(config.OLLAMA_SKIP_VALIDATION !== 'true') {
const ollamaValid = await setupService.validateOllamaConfig(
config.ollama.apiUrl,
config.ollama.model
);
if (!ollamaValid) {
console.error('Ollama server is not running or the configuration is invalid. Skipping document scan.');
return;
}
}

const analyzeDocument = await ollamaService.analyzePlayground(content, prompt);
return res.json(analyzeDocument);
} else {
Expand Down
38 changes: 30 additions & 8 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async function processDocument(doc, existingTags, existingCorrespondentList, own

const aiService = AIServiceFactory.getService();
const analysis = await aiService.analyzeDocument(content, existingTags, existingCorrespondentList, doc.id);

if (analysis.error) {
throw new Error(`[ERROR] Document analysis failed: ${analysis.error}`);
}
Expand Down Expand Up @@ -132,13 +132,13 @@ async function buildUpdateData(analysis, doc) {

async function saveDocumentChanges(docId, updateData, analysis, originalData) {
const { tags: originalTags, correspondent: originalCorrespondent, title: originalTitle } = originalData;

await Promise.all([
documentModel.saveOriginalData(docId, originalTags, originalCorrespondent, originalTitle),
paperlessService.updateDocument(docId, updateData),
documentModel.addProcessedDocument(docId, updateData.title),
documentModel.addOpenAIMetrics(
docId,
docId,
analysis.metrics.promptTokens,
analysis.metrics.completionTokens,
analysis.metrics.totalTokens
Expand All @@ -150,6 +150,18 @@ async function saveDocumentChanges(docId, updateData, analysis, originalData) {
// Main scanning functions
async function scanInitial() {
try {

if (config.aiProvider === 'ollama' && config.ollama.skipValidation === 'true') {
const ollamaValid = await setupService.validateOllamaConfig(
config.ollama.apiUrl,
config.ollama.model
);
if (!ollamaValid) {
console.error('Ollama server is not running or the configuration is invalid. Skipping document scan.');
return;
}
}

const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
console.log('[ERROR] Setup not completed. Skipping document scan.');
Expand Down Expand Up @@ -187,6 +199,16 @@ async function scanDocuments() {
console.log('[DEBUG] Task already running');
return;
}
if (config.aiProvider === 'ollama' && config.OLLAMA_SKIP_VALIDATION !== 'true') {
const ollamaValid = await setupService.validateOllamaConfig(
config.ollama.apiUrl,
config.ollama.model
);
if (!ollamaValid) {
console.error('Ollama server is not running or the configuration is invalid. Skipping document scan.');
return;
}
}

runningTask = true;
try {
Expand Down Expand Up @@ -236,7 +258,7 @@ app.get('/health', async (req, res) => {
try {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
return res.status(503).json({
return res.status(503).json({
status: 'not_configured',
message: 'Application setup not completed'
});
Expand All @@ -246,9 +268,9 @@ app.get('/health', async (req, res) => {
res.json({ status: 'healthy' });
} catch (error) {
console.error('Health check failed:', error);
res.status(503).json({
status: 'error',
message: error.message
res.status(503).json({
status: 'error',
message: error.message
});
}
});
Expand Down Expand Up @@ -281,7 +303,7 @@ async function startScanning() {
cron.schedule(config.scanInterval, async () => {
console.log(`Starting scheduled scan at ${new Date().toISOString()}`);
await scanDocuments();
});
}, { runOnInit: false });
} catch (error) {
console.error('[ERROR] in startScanning:', error);
}
Expand Down
Loading