alchemist-js-sdk
v0.0.1
Published
Official JavaScript SDK for Alchemist AI agents
Maintainers
Readme
Alchemist JavaScript SDK
Official JavaScript SDK for interacting with Alchemist AI agents.
Installation
npm install alchemist-js-sdkQuick Start
const { AgentClient } = require('alchemist-js-sdk');
// Initialize the client
const client = new AgentClient(
'your-agent-id',
'ak_your_api_key_here'
);
// Create a session
const sessionId = await client.createSession('user123');
// Send a message
const response = await client.sendMessage(sessionId, 'Hello!');
console.log(response.text);TypeScript Support
import { AgentClient, ChatResponse, SessionMetadata } from 'alchemist-js-sdk';
const client = new AgentClient('your-agent-id', 'ak_your_api_key_here');
const sessionId: string = await client.createSession('user123', {
source: 'web-app',
version: '1.0.0'
});
const response: ChatResponse = await client.sendMessage(sessionId, 'Hello!');
console.log(response.text);Features
- 🚀 Simple API - Just agent ID and API key needed
- 🔄 Session Management - Persistent conversation sessions
- 📡 Streaming Support - Real-time response streaming
- 🛡️ Type Safe - Full TypeScript support
- 🌐 Universal - Works in Node.js and browsers
- ⚡ Automatic Retries - Built-in error handling
- 🎯 Session-Based - All messages require explicit session IDs
- 🔍 Rich Metadata - Attach custom metadata to sessions and messages
API Reference
AgentClient
Constructor
const client = new AgentClient(agentId, apiKey, options);agentId(string): Your agent's unique identifierapiKey(string): Your agent-specific API key (starts with 'ak_')options(optional): Configuration optionstimeout(number): Request timeout in milliseconds (default: 120000)maxRetries(number): Maximum retry attempts (default: 3)headers(object): Additional HTTP headers
Methods
createSession(userId?, metadata?)
Create a new conversation session.
const sessionId = await client.createSession('user123', {
source: 'web',
userAgent: 'MyApp/1.0.0'
});Returns: Promise<string> - The session ID
sendMessage(sessionId, message, userId?, metadata?)
Send a message to the agent and get a complete response.
const response = await client.sendMessage(sessionId, 'Hello!', 'user123', {
messageType: 'greeting'
});
console.log(response.text);
console.log(response.tokenUsage);Returns: Promise<ChatResponse>
streamMessage(sessionId, message, userId?, metadata?)
Send a message and receive a streaming response.
for await (const chunk of client.streamMessage(sessionId, 'Tell me a story')) {
process.stdout.write(chunk);
}Returns: AsyncIterableIterator<string>
getSessionHistory(sessionId, limit?, includeMetadata?)
Get the conversation history for a session.
const history = await client.getSessionHistory(sessionId, 50, true);
history.forEach(msg => {
console.log(`[${msg.role}]: ${msg.content}`);
});Returns: Promise<Message[]>
getSessionInfo(sessionId)
Get session information.
const info = await client.getSessionInfo(sessionId);
console.log(`Session created: ${info.createdAt}`);Returns: Promise<SessionInfo>
getSessionStats(sessionId)
Get session statistics.
const stats = await client.getSessionStats(sessionId);
console.log(`Total messages: ${stats.totalMessages}`);Returns: Promise<SessionStats>
deleteSession(sessionId)
Delete a session and its history.
await client.deleteSession(sessionId);Returns: Promise<void>
Streaming Example
const { AgentClient } = require('alchemist-js-sdk');
async function streamingExample() {
const client = new AgentClient('your-agent-id', 'ak_your_api_key_here');
const sessionId = await client.createSession('streaming-user');
console.log('AI: ');
for await (const chunk of client.streamMessage(sessionId, 'Tell me a joke')) {
process.stdout.write(chunk);
}
console.log('\n');
}Error Handling
The SDK provides specific error types for different scenarios:
import {
AlchemistError,
AuthenticationError,
ValidationError,
NetworkError,
RateLimitError
} from 'alchemist-js-sdk';
try {
const response = await client.sendMessage(sessionId, message);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof ValidationError) {
console.error('Invalid input:', error.field, error.value);
} else if (error instanceof RateLimitError) {
console.error('Rate limited. Retry after:', error.retryAfter);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.statusCode);
} else if (error instanceof AlchemistError) {
console.error('SDK error:', error.errorCode, error.details);
}
}Session Management
All interactions require a session. Sessions maintain conversation context:
// Create a session
const sessionId = await client.createSession('user123');
// Send multiple messages in the same session
const msg1 = await client.sendMessage(sessionId, 'What is AI?');
const msg2 = await client.sendMessage(sessionId, 'Can you explain more?');
// Get the full conversation
const history = await client.getSessionHistory(sessionId);Advanced Configuration
const client = new AgentClient('agent-id', 'api-key', {
timeout: 180000, // 3 minutes
maxRetries: 5, // Retry up to 5 times
headers: {
'User-Agent': 'MyApp/1.0.0',
'X-Custom-Header': 'value'
}
});Environment Support
- Node.js: 16+ (ESM and CommonJS)
- Browsers: Modern browsers with fetch API
- TypeScript: Full type definitions included
Examples
Check the examples/ directory for more detailed usage examples:
basic-usage.js- Basic API usagestreaming-example.js- Streaming responsestypescript-example.ts- TypeScript usage with types
License
MIT
