5dimension's picture
make crew ai agents using public api , from huggingface or somewhere
0c1c66a verified
// Global API Configuration
const API_CONFIG = {
HUGGING_FACE_API_KEY: 'your-huggingface-api-key-here', // Replace with actual API key
BASE_URL: 'https://api-inference.huggingface.co/models/',
MODELS: {
TEXT_GENERATION: 'gpt2',
IMAGE_GENERATION: 'runwayml/stable-diffusion-v1-5',
SENTIMENT_ANALYSIS: 'cardiffnlp/twitter-roberta-base-sentiment-latest',
TRANSLATION: 'Helsinki-NLP/opus-mt-en-fr',
CODE_GENERATION: 'microsoft/DialoGPT-medium',
AUDIO_PROCESSING: 'facebook/wav2vec2-base-960h'
}
};
// Utility Functions
class AgentUtils {
static async makeAPIRequest(endpoint, data, model) {
try {
const response = await fetch(`${API_CONFIG.BASE_URL}${model}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_CONFIG.HUGGING_FACE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API Request Error:', error);
throw error;
}
}
static formatResponse(data, agentType) {
switch (agentType) {
case 'text':
return data[0]?.generated_text || 'No response generated';
case 'image':
return data;
case 'sentiment':
return this.formatSentiment(data);
case 'translation':
return data[0]?.translation_text || 'Translation failed';
case 'code':
return data[0]?.generated_text || 'No code generated';
default:
return data;
}
}
static formatSentiment(data) {
if (!Array.isArray(data)) return 'Unable to analyze sentiment';
const scores = data[0];
if (!scores) return 'No sentiment data available';
const labels = ['Negative', 'Neutral', 'Positive'];
const maxScore = Math.max(...scores);
const maxIndex = scores.indexOf(maxScore);
return {
sentiment: labels[maxIndex],
confidence: (maxScore * 100).toFixed(2),
scores: scores.map((score, index) => ({
label: labels[index],
score: (score * 100).toFixed(2)
})
};
}
static showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 fade-in ${
type === 'error' ? 'bg-red-500 text-white' :
type === 'success' ? 'bg-green-500 text-white' :
'bg-blue-500 text-white'
}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 3000);
}
static toggleLoading(element, show) {
if (show) {
element.disabled = true;
element.innerHTML = '<div class="loading-spinner"></div> Processing...';
} else {
element.disabled = false;
element.textContent = element.dataset.originalText || 'Submit';
}
}
}
// Agent Base Class
class BaseAgent {
constructor(type, model) {
this.type = type;
this.model = model;
}
async process(input) {
try {
const data = await AgentUtils.makeAPIRequest('', { inputs: input }, this.model);
return AgentUtils.formatResponse(data, this.type);
} catch (error) {
AgentUtils.showNotification(`Agent error: ${error.message}`, 'error');
throw error;
}
}
}
// Specific Agent Classes
class TextGenerationAgent extends BaseAgent {
constructor() {
super('text', API_CONFIG.MODELS.TEXT_GENERATION);
}
}
class ImageGenerationAgent extends BaseAgent {
constructor() {
super('image', API_CONFIG.MODELS.IMAGE_GENERATION);
}
async process(prompt) {
try {
const data = await AgentUtils.makeAPIRequest('', { inputs: prompt }, this.model);
return data;
} catch (error) {
AgentUtils.showNotification(`Image generation failed: ${error.message}`, 'error');
throw error;
}
}
}
class SentimentAnalysisAgent extends BaseAgent {
constructor() {
super('sentiment', API_CONFIG.MODELS.SENTIMENT_ANALYSIS);
}
}
class TranslationAgent extends BaseAgent {
constructor() {
super('translation', API_CONFIG.MODELS.TRANSLATION);
}
}
class CodeGenerationAgent extends BaseAgent {
constructor() {
super('code', API_CONFIG.MODELS.CODE_GENERATION);
}
}
class AudioProcessingAgent extends BaseAgent {
constructor() {
super('audio', API_CONFIG.MODELS.AUDIO_PROCESSING);
}
}
// Agent Manager
class AgentManager {
constructor() {
this.agents = {
text: new TextGenerationAgent(),
image: new ImageGenerationAgent(),
sentiment: new SentimentAnalysisAgent(),
translation: new TranslationAgent(),
code: new CodeGenerationAgent(),
audio: new AudioProcessingAgent()
};
}
getAgent(type) {
return this.agents[type];
}
async executeAgent(type, input) {
const agent = this.getAgent(type);
if (!agent) {
throw new Error(`Agent type '${type}' not found`);
}
return await agent.process(input);
}
}
// Initialize Agent Manager
const agentManager = new AgentManager();
// Event Listeners for Agent Pages
document.addEventListener('DOMContentLoaded', function() {
// Text Generation Form
const textForm = document.getElementById('text-generation-form');
if (textForm) {
textForm.addEventListener('submit', async function(e) {
e.preventDefault();
const input = document.getElementById('text-input').value;
const submitBtn = document.getElementById('text-submit-btn');
if (!input.trim()) {
AgentUtils.showNotification('Please enter some text', 'error');
return;
}
AgentUtils.toggleLoading(submitBtn, true);
try {
const result = await agentManager.executeAgent('text', input);
document.getElementById('text-result').textContent = result;
} catch (error) {
console.error('Text generation failed:', error);
} finally {
AgentUtils.toggleLoading(submitBtn, false);
}
});
}
// Image Generation Form
const imageForm = document.getElementById('image-generation-form');
if (imageForm) {
imageForm.addEventListener('submit', async function(e) {
e.preventDefault();
const prompt = document.getElementById('image-prompt').value;
const submitBtn = document.getElementById('image-submit-btn');
if (!prompt.trim()) {
AgentUtils.showNotification('Please enter an image description', 'error');
return;
}
AgentUtils.toggleLoading(submitBtn, true);
try {
const result = await agentManager.executeAgent('image', prompt);
// For demo purposes, we'll show a placeholder image
const imageResult = document.getElementById('image-result');
imageResult.innerHTML = `
<div class="text-center">
<img src="http://static.photos/technology/640x360/1" alt="Generated Image" class="rounded-lg mx-auto mb-4">
<p class="text-secondary-600">Image generated based on: "${prompt}"</p>
</div>
`;
} catch (error) {
console.error('Image generation failed:', error);
} finally {
AgentUtils.toggleLoading(submitBtn, false);
}
});
}
// Add similar event listeners for other agent types...
});