@agentai/agentai
v0.2.0
Published
A JavaScript client for the Agent.ai API
Maintainers
Readme
Agent.ai JavaScript SDK
A modern JavaScript SDK for interacting with the Agent.ai Actions API.
For LLMs: See
llm.txtfor a complete machine-readable specification of this SDK.
Installation
# Using npm
npm install @agentai/agentai
# Using yarn
yarn add @agentai/agentai
# Using pnpm
pnpm add @agentai/agentaiQuick Start
Before using the SDK, obtain a Bearer token from https://agent.ai/user/integrations#api.
const { AgentAiClient } = require('@agentai/agentai');
// Initialize the client
const client = new AgentAiClient('YOUR_BEARER_TOKEN');
// Chat with an LLM
const response = await client.chat('What is an AI agent?');
console.log(response.results);Usage Examples
Chat with LLM
const { AgentAiClient } = require('@agentai/agentai');
const client = new AgentAiClient(process.env.AGENT_API_KEY);
// Basic chat
const response = await client.chat('Explain quantum computing in simple terms');
if (response.status === 200) {
console.log(response.results);
} else {
console.error('Error:', response.error);
}
// Chat with different models
const claudeResponse = await client.chat('Write a haiku about AI', {
model: 'claude_sonnet_35'
});Available LLM Models
gpt4o(default)gpt-4o-minigpt-5,gpt-5-mini,gpt-5-nanoo1,o1-mini,o1-pro,o3-miniclaude_sonnet_35,claude_sonnet_4,claude_opus_4gemini_15_pro,gemini_15_flash,gemini-2.0-flash-expperplexity- And many more...
Grab Web Page Content
// Scrape a single page
const webContent = await client.grabWebText('https://example.com');
if (webContent.status === 200) {
console.log('Content:', webContent.results);
console.log('Page title:', webContent.metadata?.title);
}
// Crawl multiple pages (up to 100)
const crawlResult = await client.grabWebText('https://example.com', {
mode: 'crawl'
});Get Google News
const news = await client.getGoogleNews('artificial intelligence', {
dateRange: '7d' // Options: '24h', '7d', '30d'
});
if (news.status === 200) {
const articles = news.results.organic_results || [];
articles.forEach(article => {
console.log(`${article.title}`);
console.log(` Source: ${article.source}`);
console.log(` Date: ${article.date}`);
console.log(` Link: ${article.link}`);
});
}Web Search
const searchResults = await client.search('best AI frameworks 2024');
if (searchResults.status === 200) {
console.log(searchResults.results);
}YouTube Transcript
const transcript = await client.getYoutubeTranscript(
'https://www.youtube.com/watch?v=VIDEO_ID'
);
if (transcript.status === 200) {
console.log(transcript.results);
}LinkedIn Profile
const profile = await client.getLinkedinProfile(
'https://www.linkedin.com/in/username'
);
if (profile.status === 200) {
console.log(profile.results);
}Generate Images
const image = await client.generateImage('A futuristic city with AI robots');
if (image.status === 200) {
console.log(image.results); // Image URL or data
}Using the Generic Action Method
For any action not covered by convenience methods:
// Get available actions
const actions = client.getAvailableActions();
console.log(actions);
// Call any action directly
const result = await client.action('getTwitterUsers', {
usernames: ['openai', 'anthropic']
});
// Store a variable
await client.action('storeVariableToDatabase', {
key: 'myData',
value: { hello: 'world' }
});
// Retrieve a variable
const stored = await client.action('getVariableFromDatabase', {
key: 'myData'
});API Reference
Creating a Client
const { AgentAiClient } = require('@agentai/agentai');
// Basic initialization
const client = new AgentAiClient('YOUR_API_KEY');
// With custom configuration
const client = new AgentAiClient('YOUR_API_KEY', {
timeout: 60000, // Custom timeout in ms (default: 30000)
baseUrl: 'https://...', // Custom base URL (optional)
headers: { // Additional headers (optional)
'X-Custom-Header': 'value'
}
});Convenience Methods
| Method | Description |
|--------|-------------|
| chat(prompt, options) | Chat with an LLM model |
| grabWebText(url, options) | Extract text from a web page |
| getGoogleNews(query, options) | Get news articles |
| search(query, options) | Web search |
| getYoutubeTranscript(videoUrl) | Get YouTube video transcript |
| getLinkedinProfile(linkedinUrl) | Get LinkedIn profile data |
| generateImage(prompt, options) | Generate an image with AI |
| invokeAgent(agentId, input) | Invoke another Agent.ai agent |
| getAvailableActions() | List all available action IDs |
Generic Action Method
client.action(actionId, params)Available Action IDs:
Data Retrieval:
grabWebText- Extract text from web pagesgrabWebScreenshot- Take web page screenshotsgetSearchResults- Google searchgetGoogleNews- News articlesgetDomainInformation- Domain/company infogetYoutubeTranscript- Video transcriptsgetYoutubeChannel- Channel datarunYoutubeSearch- Search YouTube
Social Media:
getTwitterUsers- Twitter profile datagetRecentTweets- Recent tweetsgetLinkedinProfile- LinkedIn profilesfindLinkedinProfile- Find LinkedIn by namegetLinkedinActivity- LinkedIn activitygetInstagramProfile- Instagram profilesgetInstagramFollowers- Instagram followersgetBlueskyPosts- Bluesky postssearchBlueskyPosts- Search Bluesky
AI:
invokeLlm- Chat with LLMgenerateImage- Generate imagesoutputAudio- Text to speech
Advanced:
invokeAgent- Call other agentsrestCall- Make REST API callsconvertFile- Convert file formatsstoreVariableToDatabase- Store datagetVariableFromDatabase- Retrieve datasaveToFile- Save content to file
Response Structure
All methods return a Promise that resolves to:
{
status: 200, // HTTP status code
error: null, // Error message (null on success)
results: {...}, // API response data
metadata: {...} // Additional metadata (when available)
}Error Handling
const response = await client.chat('Hello');
if (response.status === 200) {
// Success
console.log(response.results);
} else {
// API error
console.error(`Error ${response.status}: ${response.error}`);
}
// For network errors, wrap in try/catch
try {
const response = await client.chat('Hello');
// handle response
} catch (error) {
console.error('Network error:', error.message);
}Examples
See the examples/ directory for complete working examples:
basic-usage.js- Simple examples for common use casesadvanced-usage.js- Advanced patterns like parallel requests and pipelines
Run examples:
# Set your API key
export AGENT_API_KEY=your_token_here
# Run basic examples
node examples/basic-usage.js
# Run advanced examples
node examples/advanced-usage.jsTypeScript Support
While this package is written in JavaScript, it works with TypeScript projects. Type definitions can be added by creating a .d.ts file:
declare module '@agentai/agentai' {
export interface AgentResponse {
status: number;
error: string | null;
results: any;
metadata: any;
}
export interface ClientConfig {
baseUrl?: string;
timeout?: number;
headers?: Record<string, string>;
}
export class AgentAiClient {
constructor(apiKey: string, config?: ClientConfig);
action(actionId: string, params: object): Promise<AgentResponse>;
chat(prompt: string, options?: { model?: string }): Promise<AgentResponse>;
grabWebText(url: string, options?: { mode?: 'scrape' | 'crawl' }): Promise<AgentResponse>;
getGoogleNews(query: string, options?: { dateRange?: '24h' | '7d' | '30d' }): Promise<AgentResponse>;
search(query: string, options?: object): Promise<AgentResponse>;
getYoutubeTranscript(videoUrl: string, options?: object): Promise<AgentResponse>;
getLinkedinProfile(linkedinUrl: string, options?: object): Promise<AgentResponse>;
generateImage(prompt: string, options?: object): Promise<AgentResponse>;
invokeAgent(agentId: string, input: string, options?: object): Promise<AgentResponse>;
getAvailableActions(): string[];
}
}Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for feature requests or bug reports.
License
This project is licensed under the MIT License.
