@sconedev/ai_toolkit
Version:
Simplify AI integration in web apps with local and offline model support
33 lines (32 loc) • 1.37 kB
JavaScript
export class HuggingFaceProvider {
constructor(apiKey, model) {
this.baseUrl = 'https://api-inference.huggingface.co/models/';
this.apiKey = apiKey;
this.defaultModel = model || 'gpt2';
}
async query(model, inputs) {
const response = await fetch(`${this.baseUrl}${model}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(inputs),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
async chat(messages, options) {
const prompt = messages.map(m => `${m.role}: ${m.content}`).join('\n');
const result = await this.query(this.defaultModel, { inputs: prompt, ...options });
return result[0].generated_text;
}
async generateImage(description, options) {
const model = 'stabilityai/stable-diffusion-2';
const result = await this.query(model, { inputs: description, ...options });
// Note: Hugging Face Stable Diffusion API may return raw data; assuming URL for simplicity
return result.image_url || 'https://example.com/placeholder-image.jpg'; // Adjust based on actual API response
}
}