Visão Geral
A biblioteca JavaScript oficial da Muffins AI oferece integração simplificada com todos os recursos da plataforma. Compatível com Node.js e navegadores modernos.
Pré-requisitos
Node.js v19+ ou navegador moderno (Chrome 112+, Firefox 108+, Edge 114+)
- Conta Muffins AI: Crie uma conta
- Chave de API: Obtenha em Painel de API
- Ambiente Node.js (opcional): Guia de instalação
Instalação
Via npm/yarn
npm install muffinscorp
# ou
yarn add muffinscorp
Configuração Inicial
1. Autenticação
// CommonJS
const { MuffinsCorp } = require('muffinscorp');
// ES Modules
import { MuffinsCorp } from 'muffinscorp';
const client = new MuffinsCorp({
apiKey: process.env.MUFFINS_API_KEY, // Recomendado
// baseUrl: <string> Opcional caso tenha dominio personalizado
});
2. Variáveis de Ambiente (Node.js)
Crie um arquivo .env
:
MUFFINS_AI_API_KEY=your_api_key_here
NODE_ENV=production
Uso Básico
Chat Completion
async function getChatResponse() {
const response = await client.chat.create({
model: 'chat-model-small',
messages: [
{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain quantum computing' }
],
temperature: 0.7,
max_tokens: 500
});
console.log(response);
}
getChatResponse().catch(console.error);
Streaming
const stream = await client.chat.create({
model: 'chat-model-small',
messages: [...],
stream: true
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
Recursos Avançados
1. Gerenciamento de Modelos
// Listar modelos disponíveis
const models = await client.models.list();
console.log("Available AI Models:");
console.log(models);
2. Gerenciamento de Assinaturas
// Listar Planos de assinaturas disponíveis
const subscriptions = await client.subscriptions.list();
console.log("Available Subscription Plans:");
console.log(subscriptions);
3. Verificar creditos disponiveis
const balance = await muffinsai.credits.getBalance();
console.log("Current credit balance:");
console.log(balance);
Boas Práticas
- Tratamento de Erros
try {
const response = await client.chat.create(...);
} catch (error) {
if (error instanceof MuffinsAPIError) {
console.error(`API Error [${error.status}]: ${error.message}`);
if (error.status === 429) {
console.log('Retry after:', error.headers['retry-after']);
}
}
}
- Logging
client.on('request', (req) => {
console.log(`Request: ${req.method} ${req.url}`);
});
client.on('response', (res) => {
console.log(`Response: ${res.status}`);
});
Exemplo Completo (Aplicação Web)
import { MuffinsCorp } from 'muffinscorp';
const chatForm = document.getElementById('chat-form');
const chatHistory = document.getElementById('chat-history');
const client = new MuffinsCorp({
apiKey: 'YOUR_API_KEY'
});
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
const userInput = e.target.elements.message.value;
// Adiciona mensagem do usuário ao histórico
chatHistory.innerHTML += `<div class="user-message">${userInput}</div>`;
// Obtém resposta do assistente
const response = await client.chat.create({
model: 'chat-model-small',
messages: [
{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: userInput }
]
});
// Adiciona resposta ao histórico
chatHistory.innerHTML += `<div class="assistant-message">${response}</div>`;
});
Troubleshooting
Erro | Solução |
---|
401 Unauthorized | Verifique sua chave de API e permissões |
429 Rate Limited | Implemente retry com backoff exponencial |
ECONNRESET | Verifique conexão de rede e timeout |
Para mais ajuda, visite nosso Centro de Suporte.