@embedapi/core
v1.0.11
Published
π₯ ONE API KEY TO RULE THEM ALL! Access ANY AI model instantly through our game-changing unified API. Build AI apps in minutes, not months! The ultimate all-in-one AI agent solution you've been waiting for! π
Downloads
41
Maintainers
Readme
EmbedAPI Client
π The ULTIMATE Node.js client that gives you SUPERPOWERS! Connect to 100+ AI models with ONE line of code! Build the next unicorn startup in minutes, not months! π¦β¨
Transform your boring apps into AI-powered MONSTERS that users can't stop talking about! π₯πͺ
π₯ ONE API KEY TO RULE THEM ALL! Access ANY AI model instantly through our game-changing unified API. Build AI apps in minutes, not months! The ultimate all-in-one AI agent solution you've been waiting for! π
Visit embedapi.com to get your API key and start building!
Installation
npm install @embedapi/coreUsing yarn:
yarn add @embedapi/coreUsing pnpm:
pnpm add @embedapi/coreInitialization
const EmbedAPIClient = require('@embedapi/core');
# Regular API client
const client = new EmbedAPIClient('your-api-key');
# Agent mode client
const agentClient = new EmbedAPIClient('your-agent-id', { isAgent: true });
# Debug mode client
const debugClient = new EmbedAPIClient('your-api-key', { debug: true });
# Agent and debug mode client
const debugAgentClient = new EmbedAPIClient('your-agent-id', {
isAgent: true,
debug: true
});Constructor Parameters
apiKey(string): Your API key for regular mode, or agent ID for agent modeoptions(object, optional): Configuration optionsisAgent(boolean, optional): Set to true to use agent mode. Defaults to falsedebug(boolean, optional): Set to true to enable debug logging. Defaults to false
Methods
1. generate(options)
Generates text using AI models.
Parameters
service(string): AI service provider (openai, anthropic, vertexai, etc.)model(string): Model namemessages(array): Array of message objectsmaxTokens(number, optional): Maximum tokens to generatetemperature(number, optional): Temperature (0-1)topP(number, optional): Top P samplingfrequencyPenalty(number, optional): Frequency penaltypresencePenalty(number, optional): Presence penaltystopSequences(array, optional): Stop sequencestools(array, optional): Tools to usetoolChoice(string, optional): Tool choiceenabledTools(array, optional): Enabled toolsuserId(string, optional): User ID (for agent mode)
Usage Example
// Regular mode
const response = await client.generate({
service: 'openai',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});
// Agent mode
const agentResponse = await agentClient.generate({
service: 'openai',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});2. stream({ service, model, messages, ...options })
Streams text generation using the specified AI service and model.
Parameters
Same as generate(), plus:
streamOptions(object, optional): Stream-specific configuration options
Response Format
The stream emits Server-Sent Events (SSE) with two types of messages:
- Content Chunks:
{
"content": "Generated text chunk",
"role": "assistant"
}- Final Statistics:
{
"type": "done",
"tokenUsage": 17,
"cost": 0.000612
}Usage Example
// Regular mode
const streamResponse = await client.stream({
service: 'openai',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});
// Agent mode
const agentStreamResponse = await agentClient.stream({
service: 'openai',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});
// Process the stream
const reader = streamResponse.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
if (data.type === 'done') {
console.log('Stream stats:', {
tokenUsage: data.tokenUsage,
cost: data.cost
});
} else {
console.log('Content:', data.content);
}
}
}
}3. listModels()
Lists all available models.
const models = await client.listModels();4. testAPIConnection()
Tests the connection to the API.
const isConnected = await client.testAPIConnection();5. genImage(options)
Generates images using AI models.
Parameters
prompt(string): Image descriptionwidth(number, optional): Image widthheight(number, optional): Image heightmaxTokens(number, optional): Maximum tokenstemperature(number, optional): Temperature (0-1)steps(number, optional): Generation stepsguidance(number, optional): Guidance scaleseed(number, optional): Random seedimage_count(number, optional): Number of images to generateimage_quality(string, optional): Image qualityimage_format(string, optional): Image formatmodel(string, optional): Model name ('stability.stable-image-ultra-v1:1' or 'imagen')
Usage Example
// Stability AI example
const stabilityResponse = await client.genImage({
prompt: 'A beautiful sunset over mountains',
width: 512,
height: 512,
model: 'stability.stable-image-ultra-v1:1',
steps: 30,
guidance: 7.5
});
// Imagen example
const imagenResponse = await client.genImage({
prompt: 'A futuristic cityscape at night',
width: 1024,
height: 1024,
model: 'imagen',
steps: 50,
guidance: 8.5,
image_quality: 'high',
image_format: 'png'
});6. isNSFW(image)
Checks if an image is NSFW (Not Safe For Work).
Parameters
image(object): Image data objectdata(string): Base64 encoded image datamimeType(string): MIME type of the image (e.g., 'image/png', 'image/jpeg')
Usage Example
const nsfwResult = await client.isNSFW({
data: base64ImageData,
mimeType: 'image/png'
});7. textToSpeech(text)
Converts text to speech.
Parameters
text(string): Text to convert to speech
Usage Example
const audioBlob = await client.textToSpeech('Hello, world!');8. speechToText(audioBase64)
Converts speech to text.
Parameters
audioBase64(string): Base64 encoded audio file
Usage Example
const transcription = await client.speechToText(base64AudioData);9. processImages(options)
Processes images using Vision AI.
Parameters
prompt(string): Description of what to analyzeimages(string[]): Array of base64 encoded images
Usage Example
const analysis = await client.processImages({
prompt: 'Describe what you see in this image',
images: [base64ImageData]
});Agent Management
The EmbedAPI client provides comprehensive agent management capabilities for creating, listing, updating, and deleting AI agents.
10. createAgent(agentData)
Creates a new AI agent.
Parameters
agentData(object): Agent configuration dataname(string): Agent namedescription(string): Agent descriptionservice(string): AI service provider (openai, anthropic, vertexai, etc.)model(string): Specific model to useinstructions(string): System instructions for the agenttheme(object, optional): Theme configurationcustomTheme(boolean, optional): Whether to use custom themecustomColors(object, optional): Custom color configurationfeatures(string[], optional): Agent featuressecurity(object, optional): Security configurationisPublic(boolean, optional): Whether the agent is public
Usage Example
const agentData = {
name: 'Customer Service Bot',
description: 'A helpful customer service assistant',
service: 'openai',
model: 'gpt-4o',
instructions: 'You are a helpful customer service representative. Be polite and professional.',
theme: {
name: 'Classic Light',
colors: {
primary: '#1976d2',
background: '#ffffff',
text: '#1A1A1A'
}
},
customTheme: false,
customColors: {
primary: '#1976d2',
background: '#ffffff',
text: '#1A1A1A'
},
features: ['Knowledge Base', 'Function Calling'],
security: {
embedEnabled: false,
allowedDomains: [],
rateLimit: 60,
maxTokensPerDay: 10000
},
isPublic: false
};
const response = await client.createAgent(agentData);
console.log('Created agent:', response.agent);11. listAgents(options)
Lists agents owned by the authenticated user.
Parameters
options(object, optional): Query optionslimit(number, optional): Number of agents to return (default: 50, max: 100)offset(number, optional): Number of agents to skip (default: 0)status(string, optional): Filter by status (active, inactive)isPublic(boolean, optional): Filter by public status
Usage Example
// List all agents
const allAgents = await client.listAgents();
// List with pagination and filters
const filteredAgents = await client.listAgents({
limit: 10,
offset: 0,
status: 'active',
isPublic: false
});
console.log('Total agents:', allAgents.total);
console.log('Agents:', allAgents.agents);12. getAgent(agentId)
Retrieves a specific agent by ID.
Parameters
agentId(string): The agent ID
Usage Example
const agent = await client.getAgent('agent-id-123');
console.log('Agent details:', agent.agent);13. updateAgent(agentId, updateData)
Updates an existing agent. Only fields provided in the request body will be updated.
Parameters
agentId(string): The agent IDupdateData(object): Fields to update
Usage Example
const updateData = {
name: 'Updated Customer Service Bot',
description: 'An improved customer service assistant',
instructions: 'You are an improved customer service representative.',
isPublic: true
};
const response = await client.updateAgent('agent-id-123', updateData);
console.log('Updated agent:', response.agent);14. deleteAgent(agentId)
Deletes an agent.
Parameters
agentId(string): The agent ID
Usage Example
const response = await client.deleteAgent('agent-id-123');
console.log('Deletion result:', response.message);Complete Agent Management Example
const EmbedAPIClient = require('@embedapi/core');
const client = new EmbedAPIClient('your-api-key');
async function manageAgents() {
try {
// Create a new agent
const newAgent = await client.createAgent({
name: 'Sales Assistant',
description: 'AI sales assistant for product recommendations',
service: 'anthropic',
model: 'claude-3-opus',
instructions: 'You are a knowledgeable sales assistant...',
features: ['Knowledge Base', 'Function Calling'],
isPublic: false
});
console.log('Created agent:', newAgent.agentId);
// List all agents
const agents = await client.listAgents({ limit: 10 });
console.log('Found', agents.total, 'agents');
// Get specific agent
const agent = await client.getAgent(newAgent.agentId);
console.log('Agent details:', agent.agent.name);
// Update agent
const updated = await client.updateAgent(newAgent.agentId, {
name: 'Enhanced Sales Assistant',
isPublic: true
});
console.log('Updated agent:', updated.agent.name);
// Delete agent
const deleted = await client.deleteAgent(newAgent.agentId);
console.log('Agent deleted:', deleted.message);
} catch (error) {
console.error('Error managing agents:', error.message);
}
}
manageAgents();Important Notes
Image Storage
Generated images are temporarily stored on the server and will be automatically deleted after a period of time. It is recommended to:
- Download and store generated images in your own storage system
- For Stability AI images, save the URLs immediately after generation
- For Imagen images, save the base64 data to your storage
Audio Storage
Generated audio files from Text-to-Speech are also temporarily stored. Make sure to:
- Save the audio blob to your storage system
- Handle the audio data immediately after generation
Error Handling
All methods throw errors if the API request fails:
try {
const response = await client.generate({
service: 'openai',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }]
});
} catch (error) {
console.error('Error:', error.message);
}Authentication
The client supports two authentication modes:
Regular Mode (default)
- Uses API key in request headers
- Initialize with:
new EmbedAPIClient('your-api-key')
Agent Mode
- Uses agent ID in request body
- Initialize with:
new EmbedAPIClient('your-agent-id', { isAgent: true }) - Optional
userIdparameter available for request tracking
Need inspiration or ideas?
Looking for creative ways to use EmbedAPI? From AI story visualizers and comic creators to intelligent business solutions and interactive art galleries, the possibilities are endless! Check out INFINITE_POSSIBILITIES.md for innovative use cases and complete code examples that will spark your imagination. πβ¨
π Share Your Creation
Built something amazing? Share it with the community!
- Tag us on Twitter: @embed_api
- Join our Discord: discord.gg/UTZbYsR
- Submit your project: embedapi.com/showcase
Remember: The only limit is your imagination! π
License
MIT
