Wie löste ich Ollama Qwen2.5-Codierer-API-Fehler?JavaScript

Javascript-Forum
Anonymous
 Wie löste ich Ollama Qwen2.5-Codierer-API-Fehler?

Post by Anonymous »

I have installed qwen2.5-coder:3b via ollama, and when I want to use this API to generate Html/css components in my project,t it says

"Error generating content: API error! status: 404, message: Unknown error during generation."

Please Hilf mir bei der Lösung dieses Fehlers. As far as I know, I have correctly routed to the correct functions in ai-service.js, in chat-route.js and chat-controller.js
The sendMessageToLLM() is used to communicate to the LLM in each function: generateComponentHtml() and generateFromTemplateMetadata(). in ai-service.js.const fetch = require('node-fetch');

// This service will handle all interactions with the LLM API

async function sendMessageToLLM(message) {
// Call Ollama API for qwen 2.5-coder:3b
const ollamaUrl = 'http://localhost:11434/api/generate';
const payload = {
model: 'qwen2.5-coder:3b',
prompt: message,
stream: false
};
try {
const response = await fetch(ollamaUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ollama API error! status: ${response.status}, message: ${errorText}`);
}
const data = await response.json();
// Ollama returns { response: "..." } for /generate
return { reply: data.response };
} catch (error) {
console.error('Error calling Ollama:', error);
throw error;
}
}

async function generateComponentHtml(request, templateId) {
// Compose a prompt for the LLM
const prompt = `Generate an HTML component for template ID: ${templateId}. User request: ${request}`;
try {
const llmResult = await sendMessageToLLM(prompt);
return { html: llmResult.reply };
} catch (error) {
return { html: `AI generation failed: ${error.message}` };
}
}

async function generateContentFromTemplateMetadata(templateMetadata) {
// Compose a prompt for the LLM
const prompt = `Generate a full HTML page structure for a website with the following metadata: ${JSON.stringify(templateMetadata)}`;
try {
const llmResult = await sendMessageToLLM(prompt);
return {
message: `Successfully generated content structure for ${templateMetadata.name}.`,
html: llmResult.reply
};
} catch (error) {
return {
message: `AI generation failed: ${error.message}`,
html: `AI generation failed: ${error.message}`
};
}
}

module.exports = {

sendMessageToLLM,

generateComponentHtml,

generateContentFromTemplateMetadata

};
< /code>
Chat-controller.js:
const fs = require('fs');
const path = require('path');
const aiService = require('./ai-service');
const templates = require('../templates.json'); // Assuming templates.json is in the root for simplicity

// Load templates from JSON file
const loadTemplates = () => {
try {
const templatesPath = path.join(__dirname, '..', 'templates.json');
const templatesData = fs.readFileSync(templatesPath, 'utf8');
return JSON.parse(templatesData).templates;
} catch (error) {
console.error('Error loading templates:', error);
return [];
}
};

// Process user message and generate AI response
exports.processMessage = (req, res) => {
try {
const { message, templateId } = req.body;

if (!message) {
return res.status(400).json({ error: 'Message is required' });
}

// Simulate AI processing
setTimeout(() => {
// Generate a response based on the message
let response = {
text: `I've received your message about "${message}". Let me help you build that for your website.`,
suggestions: [
'Add a contact form',
'Change the color scheme',
'Add a product gallery'
]
};

// If template-specific message, customize response
if (templateId) {
const templates = loadTemplates();
const template = templates.find(t => t.id === templateId);

if (template) {
response.text = `I'll help you customize your ${template.name} template based on your request: "${message}"`;
response.suggestions = template.features.map(feature => `Customize the ${feature} section`);
}
}

res.json(response);
}, 1000); // Simulate processing delay
} catch (error) {
console.error('Error processing message:', error);
res.status(500).json({ error: 'Failed to process message' });
}
};

// Generate website component based on user request
exports.generateComponent = async (req, res) => {
try {
const { request, templateId } = req.body; // componentType is not used by ai-service.js for now

if (!request) {
return res.status(400).json({ error: 'Request details are required' });
}

// Call AI service to generate component HTML
const aiResponse = await aiService.generateComponentHtml(request, templateId);

if (aiResponse && aiResponse.html) {
res.json({ html: aiResponse.html });
} else {
console.error('Error: AI service did not return HTML content.');
res.status(500).json({ error: 'Failed to generate component from AI service' });
}

} catch (error) {
console.error('Error in generateComponent controller:', error);
res.status(500).json({ error: 'Failed to generate component' });
}
};

// Get website template suggestions
exports.getSuggestions = (req, res) => {
try {
const templates = loadTemplates();

// Generate suggestions based on templates
const suggestions = [
'Create a landing page with a hero section and contact form',
'Add a product showcase with images and descriptions',
'Design a blog layout with featured posts',
'Build a portfolio page to showcase your work'
];

// Add template-specific suggestions
templates.forEach(template => {
suggestions.push(`Create a ${template.name.toLowerCase()} website with ${template.features.slice(0, 2).join(' and ')}`);
});

res.json({ suggestions });
} catch (error) {
console.error('Error getting suggestions:', error);
res.status(500).json({ error: 'Failed to get suggestions' });
}
};

// Controller function to handle AI content generation from template metadata
exports.generateContentFromTemplate = async (req, res) => {
const { templateMetadata } = req.body;

if (!templateMetadata || !templateMetadata.id) {
return res.status(400).json({ message: 'Template metadata with ID is required.' });
}

// Optionally, re-fetch/validate template data from server-side templates.json
// to ensure integrity, though editor.html already sends it.
// 'templates' is available due to the first search/replace block adding the require.
const serverTemplate = templates.templates.find(t => t.id === templateMetadata.id);
if (!serverTemplate) {
return res.status(404).json({ message: `Template with ID '${templateMetadata.id}' not found on server.` });
}
// Use the metadata sent from the client, which should be the enriched version

try {
console.log(`Chat Controller: Received request to generate content for template: ${templateMetadata.name}`);
const result = await aiService.generateContentFromTemplateMetadata(templateMetadata);
res.json(result);
} catch (error) {
console.error('Error in generateContentFromTemplate controller:', error);
res.status(500).json({ message: 'Error generating content from template.', error: error.message });
}
};
< /code>
Chat-route.js:
const express = require('express');
const router = express.Router();
const chatController = require('./chat-controller');

// Route to handle chat messages
router.post('/message', chatController.processMessage);

// Route to get website component based on user request
router.post('/generate-component', chatController.generateComponent);

// Route to handle AI content generation based on template metadata
router.post('/generate-content', chatController.generateContentFromTemplate);

// Route to get website template suggestions
router.get('/suggestions', chatController.getSuggestions);

module.exports = router;
< /code>
Bitte helfen Sie mir, den Fehler zu beheben! Gibt es weitere Abfragen? Ich möchte helfen. Danke.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post