Update gpt/index.html

This commit is contained in:
2026-05-10 17:51:53 +02:00
parent 2fe636fc90
commit efa7906ea3
+66 -125
View File
@@ -388,7 +388,7 @@
endpoint: '',
model: '',
apiKey: '',
type: 'ollama' // ollama, openai, lmstudio, gpt4all
type: 'openai'
};
// Load saved config
@@ -412,7 +412,7 @@
let isProcessing = false;
/* ============================================
UI FUNCTIONS
UI
============================================ */
function updateStatus() {
if (aiConfig.enabled) {
@@ -469,21 +469,26 @@
addLine('Configuration saved', 'system');
}
/* ============================================
TEST CONNECTION (FIXED)
============================================ */
async function testConnection() {
const endpoint = document.getElementById('endpointInput').value.trim();
const model = document.getElementById('modelInput').value.trim();
if (!endpoint || !model) {
alert('Please enter endpoint and model name');
if (!endpoint) {
alert('Please enter endpoint');
return;
}
try {
// Try a simple request based on detected type
const testEndpoint = endpoint.replace('/chat', '/tags').replace('/completions', '/models');
const response = await fetch(testEndpoint, {
// ONLY OpenAI-style test
const testUrl = endpoint.replace('/chat/completions', '/models');
const response = await fetch(testUrl, {
method: 'GET',
headers: aiConfig.apiKey ? { 'Authorization': 'Bearer ' + aiConfig.apiKey } : {}
headers: aiConfig.apiKey
? { 'Authorization': 'Bearer ' + aiConfig.apiKey }
: {}
});
if (response.ok) {
@@ -496,14 +501,26 @@
}
}
// Preset handling
/* ============================================
PRESETS (CLEAN)
============================================ */
document.getElementById('presetSelect').addEventListener('change', function () {
const presets = {
ollama: { endpoint: 'http://localhost:11434/api/chat', model: 'llama2', type: 'ollama' },
lmstudio: { endpoint: 'http://localhost:1234/v1/chat/completions', model: 'local-model', type: 'openai' },
gpt4all: { endpoint: 'http://localhost:4891/v1/chat/completions', model: 'gpt4all-model', type: 'openai' },
openai: { endpoint: 'https://api.openai.com/v1/chat/completions', model: 'gpt-4o-mini', type: 'openai' },
claude: { endpoint: 'https://api.anthropic.com/v1/messages', model: 'claude-sonnet-4-20250514', type: 'claude' }
local: {
endpoint: 'http://localhost:4891/v1/chat/completions',
model: 'local-model',
type: 'openai'
},
openai: {
endpoint: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-4o-mini',
type: 'openai'
},
claude: {
endpoint: 'https://api.anthropic.com/v1/messages',
model: 'claude-sonnet-4-20250514',
type: 'claude'
}
};
const preset = presets[this.value];
@@ -515,17 +532,15 @@
});
/* ============================================
HELPER FUNCTIONS
HELPERS
============================================ */
function getFormattedDate() {
const now = new Date();
const dd = String(now.getDate()).padStart(2, '0');
const mm = String(now.getMonth() + 1).padStart(2, '0');
const yyyy = now.getFullYear();
const HH = String(now.getHours()).padStart(2, '0');
const MM = String(now.getMinutes()).padStart(2, '0');
const SS = String(now.getSeconds()).padStart(2, '0');
return `${dd}/${mm}/${yyyy}:${HH}/${MM}/${SS}`;
return `${String(now.getDate()).padStart(2, '0')}/${
String(now.getMonth() + 1).padStart(2, '0')
}/${now.getFullYear()}:${String(now.getHours()).padStart(2, '0')}/${
String(now.getMinutes()).padStart(2, '0')
}/${String(now.getSeconds()).padStart(2, '0')}`;
}
function getStatusInfo() {
@@ -533,88 +548,34 @@
}
function preprocessMessage(message) {
// Replace "date" keyword with actual date (case insensitive, whole word)
let processed = message.replace(/\bdate\b/gi, `date (${getFormattedDate()})`);
// Replace "status" keyword with actual status info (case insensitive, whole word)
processed = processed.replace(/\bstatus\b/gi, `status ${getStatusInfo()}`);
return processed;
return message
.replace(/\bdate\b/gi, `date (${getFormattedDate()})`)
.replace(/\bstatus\b/gi, `status ${getStatusInfo()}`);
}
/* ============================================
AI COMMUNICATION
AI CALL (OPENAI ONLY)
============================================ */
async function queryAI(message) {
if (!aiConfig.enabled) {
addLine('', '');
addLine('The AI you are trying to reach is not online at the moment.', 'error');
addLine('', '');
addLine('To connect an AI backend:', 'system');
addLine(' 1. Type "config" to open settings', 'system');
addLine(' 2. Choose a preset or enter custom endpoint', 'system');
addLine(' 3. Supported: Ollama, LM Studio, GPT4All, OpenAI, Claude', 'system');
addLine('AI is offline. Use config to connect.', 'error');
return;
}
isProcessing = true;
// Preprocess message to replace date/status keywords
const processedMessage = preprocessMessage(message);
try {
let response;
if (aiConfig.type === 'ollama') {
response = await fetch(aiConfig.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: aiConfig.model,
messages: [{ role: 'user', content: processedMessage }],
stream: false
})
});
const data = await response.json();
if (data.message && data.message.content) {
addLine(data.message.content, 'ai');
} else if (data.error) {
addLine('Error: ' + data.error, 'error');
}
} else if (aiConfig.type === 'claude') {
// Claude/Anthropic API
response = await fetch(aiConfig.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': aiConfig.apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model: aiConfig.model,
max_tokens: 1024,
messages: [{ role: 'user', content: processedMessage }]
})
});
const data = await response.json();
if (data.content && data.content[0]) {
addLine(data.content[0].text, 'ai');
} else if (data.error) {
addLine('Error: ' + (data.error.message || data.error), 'error');
}
} else {
// OpenAI-compatible API (LM Studio, GPT4All, OpenAI, etc.)
const headers = { 'Content-Type': 'application/json' };
if (aiConfig.apiKey) {
headers['Authorization'] = 'Bearer ' + aiConfig.apiKey;
}
response = await fetch(aiConfig.endpoint, {
const response = await fetch(aiConfig.endpoint, {
method: 'POST',
headers: headers,
headers,
body: JSON.stringify({
model: aiConfig.model,
messages: [{ role: 'user', content: processedMessage }],
@@ -623,23 +584,23 @@
});
const data = await response.json();
if (data.choices && data.choices[0]) {
addLine(data.choices[0].message.content, 'ai');
} else if (data.error) {
addLine('Error: ' + (data.error.message || data.error), 'error');
} else {
addLine('Invalid response from server', 'error');
}
}
} catch (e) {
addLine('Connection error: ' + e.message, 'error');
addLine('Make sure your AI backend is running', 'system');
}
isProcessing = false;
}
/* ============================================
COMMAND PROCESSING
COMMANDS
============================================ */
function processCommand(input) {
const trimmed = input.trim();
@@ -649,21 +610,9 @@
commandHistory.unshift(trimmed);
historyIndex = -1;
const cmd = trimmed.toLowerCase();
switch (cmd) {
switch (trimmed.toLowerCase()) {
case 'help':
addLine('', '');
addLine('Available commands:', 'system');
addLine(' help - Show this help', 'system');
addLine(' config - Configure AI backend', 'system');
addLine(' clear - Clear screen', 'system');
addLine('', '');
addLine('Keywords (replaced in messages to AI):', 'system');
addLine(' date - Replaced with current date/time', 'system');
addLine(' status - Replaced with connection info', 'system');
addLine('', '');
addLine('Any other input is sent to the AI', 'system');
addLine('help | config | clear | date | status', 'system');
break;
case 'config':
@@ -674,46 +623,38 @@
clearOutput();
break;
case 'date':
addLine(getFormattedDate(), 'system');
break;
case 'status':
addLine(getStatusInfo(), 'system');
break;
default:
queryAI(trimmed);
}
}
/* ============================================
INPUT HANDLING
INPUT
============================================ */
inputField.addEventListener('keydown', function(e) {
inputField.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !isProcessing) {
processCommand(this.value);
this.value = '';
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (historyIndex < commandHistory.length - 1) {
historyIndex++;
this.value = commandHistory[historyIndex];
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex > 0) {
historyIndex--;
this.value = commandHistory[historyIndex];
} else {
historyIndex = -1;
this.value = '';
}
processCommand(inputField.value);
inputField.value = '';
}
});
/* ============================================
INITIALIZATION
INIT
============================================ */
updateStatus();
updateTime();
setInterval(updateTime, 1000);
inputField.focus();
// Click anywhere to focus input
document.addEventListener('click', function(e) {
document.addEventListener('click', (e) => {
if (!configPanel.contains(e.target)) {
inputField.focus();
}