Cognipeer SDK (@cognipeer/sdk)
The official JavaScript/TypeScript SDK for Cognipeer provides a powerful way to build conversational AI applications with client-side tool execution, webchat integration, and flow automation support.
Features
- 🚀 Simple & Intuitive - Easy-to-use API for conversational AI
- 🔧 Client-Side Tools - Define JavaScript functions the AI can automatically execute
- 💬 Webchat Integration - Embed chat UI with iframe, URL, or floating widget
- 📦 Universal Support - Works in Node.js, browsers, and edge runtimes
- 🎯 Type-Safe - Full TypeScript support with complete type definitions
- ⚡ Auto-Execution - Automatic client tool execution with retry logic
- 🌊 Flow Support - Execute complex workflows and automations
- 🔒 Secure - Your sensitive operations stay on your infrastructure
Installation
npm install @cognipeer/sdkOr with Yarn:
yarn add @cognipeer/sdkOr with pnpm:
pnpm add @cognipeer/sdkQuick Start
Prerequisites
Before using the SDK, you need:
- Personal Access Token (PAT): Generate from Settings → Security → Personal Access Tokens
- API Channel Hook ID: Create an API channel for your peer to get a hookId
Basic Conversation
import { CognipeerClient } from '@cognipeer/sdk';
// Initialize the client with PAT and hookId
const client = new CognipeerClient({
token: 'token', // From security settings
hookId: 'your-api-channel-hook-id' // From API channel
});
// The peer is automatically determined from your API channel
// No need to specify peerId!
// Create a conversation
const response = await client.conversations.create({
messages: [
{ role: 'user', content: 'Hello! How can you help me?' }
]
});
console.log(response.content);
// Get peer information
const peer = await client.peers.get();
console.log('Using peer:', peer.name);
// Get authenticated user information
const user = await client.users.get();
console.log('Authenticated as:', user.email);
// Get channel information
const channel = await client.channels.get();
console.log('Channel:', channel.name, 'Active:', channel.isActive);Client-Side Tool Execution
The killer feature - define JavaScript functions that the AI can automatically call:
const response = await client.conversations.create({
messages: [
{ role: 'user', content: 'What is the weather in Tokyo?' }
],
clientTools: [{
type: 'function',
function: {
name: 'getCurrentWeather',
description: 'Get current weather for a city',
parameters: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' }
},
required: ['city']
}
},
implementation: async ({ city }) => {
// Your weather API call here
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.json();
return `Temperature: ${data.temp}°C, Conditions: ${data.conditions}`;
}
}]
});
// The AI automatically executed your function and used the result!
console.log(response.content);Webchat Integration
import { CognipeerWebchat } from '@cognipeer/sdk';
// Floating widget (like Intercom)
const widget = CognipeerWebchat.createWidget({
hookId: 'your-hook-id',
position: 'bottom-right',
theme: {
primary: '#00b5a5',
headerBG: '#ffffff'
}
});
// Or embed in a container
const webchat = new CognipeerWebchat({
hookId: 'your-hook-id',
containerId: 'chat-container'
});
webchat.mount();Configuration
Constructor Options
const client = new CognipeerClient({
// Required
token: 'pat_your-personal-access-token', // PAT from settings
hookId: 'your-api-channel-hook-id', // From API channel
// Optional
apiUrl: 'https://api.cognipeer.com/v1', // Custom API endpoint
baseUrl: 'https://app.cognipeer.com', // Base URL for links
timeout: 60000, // Request timeout in ms (default: 60000)
autoExecuteTools: true, // Auto-execute client tools (default: true)
maxToolExecutions: 10, // Max tool execution loops (default: 10)
// Callbacks
onToolStart: (toolName, args) => {
console.log(`Executing: ${toolName}`, args);
},
onToolEnd: (toolName, result) => {
console.log(`Completed: ${toolName}`, result);
}
});| Parameter | Type | Required | Description |
|---|---|---|---|
token | string | Yes | Personal Access Token (PAT) for authentication |
hookId | string | Yes | API channel hook ID |
apiUrl | string | No | The base URL for the API (default: 'https://api.cognipeer.com/v1') |
baseUrl | string | No | Base URL for the web app (default: 'https://app.cognipeer.com') |
timeout | number | No | Request timeout in milliseconds (default: 60000) |
autoExecuteTools | boolean | No | Automatically execute client tools (default: true) |
maxToolExecutions | number | No | Maximum tool execution loops (default: 10) |
onToolStart | function | No | Callback when tool execution starts |
onToolEnd | function | No | Callback when tool execution completes |
Core API Reference
Conversations
conversations.create(options)
Create a new conversation and get a response.
const response = await client.conversations.create({
messages: [
{ role: 'user', content: 'Hello!' }
],
clientTools: [...], // Optional: Client-side tools
response_format: 'text', // Optional: 'text' | 'json'
response_schema: {...}, // Optional: JSON schema for structured output
userId: 'user-123', // Optional: Associate with user
contactId: 'contact-456' // Optional: Associate with contact
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
messages | Message[] | Yes | Array of messages to send |
clientTools | ClientTool[] | No | Client-side tools the AI can call |
response_format | 'text' | 'json' | No | Response format (default: 'text') |
response_schema | object | No | JSON schema for structured responses |
userId | string | No | User ID to associate with conversation |
contactId | string | No | Contact ID to associate with conversation |
Returns: Promise<CreateConversationResponse>
{
conversationId: string;
messageId: string;
content: string;
tools: ToolExecution[];
status: 'done' | 'client_tool_call' | 'error';
pendingAction?: PendingAction;
}conversations.sendMessage(options)
Send a message to an existing conversation.
const response = await client.conversations.sendMessage({
conversationId: 'conv-123',
content: 'Tell me more about that',
clientTools: [...]
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
conversationId | string | Yes | The conversation ID |
content | string | Yes | Message content |
clientTools | ClientTool[] | No | Client-side tools |
response_format | 'text' | 'json' | No | Response format |
response_schema | object | No | JSON schema |
Returns: Promise<SendMessageResponse>
conversations.list(options)
List conversations with pagination.
const { data, total, page, limit } = await client.conversations.list({
page: 1,
limit: 20,
sort: { createdDate: -1 }
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
page | number | No | Page number (default: 1) |
limit | number | No | Items per page (default: 10) |
sort | object | No | Sort criteria |
filter | object | No | Additional filters |
Returns: Promise<ListConversationsResponse>
{
data: Conversation[];
total: number;
page: number;
limit: number;
}conversations.get(conversationId)
Get a specific conversation by ID.
const conversation = await client.conversations.get('conversation-id');Returns: Promise<Conversation>
conversations.getMessages(options)
Get messages from a conversation.
const messages = await client.conversations.getMessages({
conversationId: 'conv-123',
messagesCount: 50
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
conversationId | string | Yes | The conversation ID |
messagesCount | number | No | Number of messages (default: 10) |
Returns: Promise<ConversationMessage[]>
conversations.resumeMessage(options)
Resume message execution with tool result (manual mode).
const response = await client.conversations.resumeMessage({
conversationId: 'conv-123',
messageId: 'msg-456',
toolResult: {
executionId: 'exec-789',
success: true,
output: 'Tool result data'
}
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
conversationId | string | Yes | The conversation ID |
messageId | string | Yes | The message ID |
toolResult | ToolResult | Yes | Tool execution result |
Returns: Promise<ResumeMessageResponse>
Peers
peers.get()
Get the peer associated with your API channel.
const peer = await client.peers.get();
console.log(peer.name); // Peer name
console.log(peer.modelId); // AI model
console.log(peer.prompt); // System promptReturns: Promise<Peer>
{
_id: string;
name: string;
modelId: string;
prompt: string;
temperature?: number;
messagesCount?: number;
// ... other properties
}Users
users.get()
Get authenticated user information.
const user = await client.users.get();
console.log(user.email); // User email
console.log(user.displayName); // Display name
console.log(user.workspace.name); // Workspace nameReturns: Promise<User>
{
_id: string;
email: string;
displayName: string;
workspace: {
_id: string;
name: string;
slug: string;
plan: string;
};
roles: string[];
// ... other properties
}Channels
channels.get()
Get API channel information.
const channel = await client.channels.get();
console.log(channel.hookId); // Hook ID
console.log(channel.isActive); // Active status
console.log(channel.channelType); // Channel typeReturns: Promise<Channel>
{
_id: string;
name: string;
hookId: string;
peerId: string;
channelType: string;
isActive: boolean;
prompt?: string;
messagesCount?: number;
}Flows (Apps)
flows.execute(options)
Execute a workflow/app.
const result = await client.flows.execute({
flowId: 'invoice-analyzer',
inputs: {
document: 'base64-content',
analysisType: 'detailed'
}
});
console.log(result.outputs);Get available peers.
const peers = await client.peers.list({ limit: 20 });Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options.limit | number | No | Maximum results (default: 10) |
Returns: Promise<Peer[]>
peers.get(peerId)
Get a specific peer by ID.
const peer = await client.peers.get('peer-id');Returns: Promise<Peer>
Flows
flows.execute(flowId, inputs)
Execute a flow with inputs.
const result = await client.flows.execute('flow-id', {
inputs: {
name: 'John Doe',
query: 'How do I reset my password?'
}
});Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
flowId | string | Yes | The flow ID to execute |
inputs | object | Yes | Input values for the flow |
Returns: Promise<FlowExecutionResult>
Client-Side Tools
Client-side tools enable the AI to call JavaScript functions you define. This is perfect for:
- External API integrations
- Database queries
- Custom business logic
- Real-time data access
Tool Definition
{
type: 'function',
function: {
name: 'toolName',
description: 'What the tool does',
parameters: {
type: 'object',
properties: {
paramName: {
type: 'string',
description: 'Parameter description'
}
},
required: ['paramName']
}
},
implementation: async (params) => {
// Your implementation
return result;
}
}Real-World Examples
Weather API Integration
clientTools: [{
type: 'function',
function: {
name: 'getCurrentWeather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name or coordinates'
},
units: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
description: 'Temperature units'
}
},
required: ['location']
}
},
implementation: async ({ location, units = 'celsius' }) => {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${API_KEY}&units=${units}`
);
const data = await response.json();
return {
temperature: data.main.temp,
conditions: data.weather[0].description,
humidity: data.main.humidity
};
}
}]Database Query
clientTools: [{
type: 'function',
function: {
name: 'getUserOrders',
description: 'Get recent orders for a user',
parameters: {
type: 'object',
properties: {
userId: { type: 'string' },
limit: { type: 'number', default: 10 }
},
required: ['userId']
}
},
implementation: async ({ userId, limit }) => {
const orders = await db.orders.find({
userId,
limit
});
return orders;
}
}]Custom Calculation
clientTools: [{
type: 'function',
function: {
name: 'calculateShipping',
description: 'Calculate shipping cost',
parameters: {
type: 'object',
properties: {
weight: { type: 'number', description: 'Weight in kg' },
destination: { type: 'string' },
express: { type: 'boolean', default: false }
},
required: ['weight', 'destination']
}
},
implementation: async ({ weight, destination, express }) => {
const baseRate = weight * 2.5;
const destinationRate = getDestinationRate(destination);
const expressMultiplier = express ? 2 : 1;
return baseRate * destinationRate * expressMultiplier;
}
}]Manual Tool Execution
For fine-grained control, disable auto-execution:
const response = await client.conversations.create({
peerId: 'your-peer-id',
messages: [{ role: 'user', content: 'Check inventory' }],
clientTools: [...],
autoExecuteTools: false // Disable auto-execution
});
if (response.toolCalls) {
for (const toolCall of response.toolCalls) {
// Manually execute and provide result
const result = await executeToolManually(toolCall);
// Continue conversation with tool result
await client.conversations.sendMessage(
response.conversationId,
'',
{ toolResults: [{ toolCallId: toolCall.id, result }] }
);
}
}Webchat Integration
The SDK provides multiple ways to integrate webchat:
Floating Widget
import { CognipeerWebchat } from '@cognipeer/sdk';
const widget = CognipeerWebchat.createWidget({
hookId: 'your-hook-id',
position: 'bottom-right', // or 'bottom-left'
theme: {
primary: '#00b5a5',
headerBG: '#ffffff',
mainBG: '#f5f5f5',
radius: '12px',
fontFamily: 'Inter, sans-serif'
},
logo: {
src: 'https://example.com/logo.png',
width: 120,
height: 40
},
contact: {
email: 'user@example.com',
name: 'John Doe'
},
context: {
userId: '12345',
plan: 'premium'
}
});
// Control the widget
widget.open();
widget.close();
widget.destroy();Iframe Embed
const webchat = new CognipeerWebchat({
hookId: 'your-hook-id',
containerId: 'chat-container',
width: '100%',
height: '600px',
theme: { primary: '#00b5a5' }
});
webchat.mount();HTML:
<div id="chat-container"></div>Event Handling
const webchat = new CognipeerWebchat({
hookId: 'your-hook-id',
containerId: 'chat-container'
});
// Listen for events
webchat.on('ready', (event) => {
console.log('Webchat is ready');
});
webchat.on('message-received', (event) => {
console.log('New message:', event.data.content);
});
webchat.on('conversation-started', (event) => {
console.log('Conversation started:', event.data.conversationId);
});
webchat.mount();Available Events
ready- Webchat iframe loadedmessage-sent- User sent a messagemessage-received- AI response receivedconversation-started- New conversation createdconversation-ended- Conversation closederror- Error occurred
Webchat with Client Tools
You can also provide client tools to webchat for enhanced functionality:
const webchat = new CognipeerWebchat({
hookId: 'your-hook-id',
containerId: 'chat-container',
clientTools: [{
type: 'function',
function: {
name: 'getUserProfile',
description: 'Get user profile data',
parameters: {
type: 'object',
properties: {}
}
},
implementation: async () => {
// Access local data
return {
name: currentUser.name,
email: currentUser.email,
plan: currentUser.plan
};
}
}]
});
webchat.mount();Structured Output
Get AI responses in JSON format with schema validation:
const response = await client.conversations.create({
peerId: 'your-peer-id',
messages: [
{ role: 'user', content: 'Extract contact info from: John Doe, john@example.com, (555) 123-4567' }
],
responseFormat: 'json',
responseSchema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
phone: { type: 'string' }
},
required: ['name', 'email']
}
});
console.log(response.data);
// { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }Multi-Turn Conversations
// Start a conversation
const response1 = await client.conversations.create({
peerId: 'your-peer-id',
messages: [
{ role: 'user', content: 'What products do you offer?' }
]
});
const conversationId = response1.conversationId;
// Continue the conversation
const response2 = await client.conversations.sendMessage(
conversationId,
'Tell me more about the first one'
);
const response3 = await client.conversations.sendMessage(
conversationId,
'What is the price?'
);Error Handling
try {
const response = await client.conversations.create({
peerId: 'your-peer-id',
messages: [{ role: 'user', content: 'Hello' }]
});
console.log(response.content);
} catch (error) {
if (error.response) {
// API error response
console.error('API Error:', error.response.status, error.response.data);
} else if (error.request) {
// Network error
console.error('Network Error:', error.message);
} else {
// Other error
console.error('Error:', error.message);
}
}Browser Usage
Via NPM
import { CognipeerClient, CognipeerWebchat } from '@cognipeer/sdk';
const client = new CognipeerClient({ token: 'your-token' });
// Use as normalVia CDN
<script src="https://unpkg.com/@cognipeer/sdk@latest/dist/webchat-browser.min.js"></script>
<script>
const webchat = new CognipeerWebchat({
hookId: 'your-hook-id',
containerId: 'chat-container'
});
webchat.mount();
</script>TypeScript Support
The SDK is built with TypeScript and includes complete type definitions:
import {
CognipeerClient,
CognipeerWebchat,
ClientTool,
ConversationResponse,
Message,
Peer,
FlowExecutionResult
} from '@cognipeer/sdk';
// Full type safety
const response: ConversationResponse = await client.conversations.create({
peerId: 'your-peer-id',
messages: [{ role: 'user', content: 'Hello' }]
});Promise<Record<string, any>> - The execution results with outputs mapped by name
Error Handling
The client includes built-in error handling that will log API errors to the console. You can also wrap your calls in try/catch blocks for custom error handling:
try {
const peers = await client.peer.list();
} catch (error) {
// Custom error handling
console.error('Failed to list peers:', error);
}Running on-premises
For on-premises deployments, just specify your local API endpoint when initializing the client:
const client = new CognipeerClient({
baseUrl: 'https://your-local-cognipeer-api.com/v1/client',
token: 'your-local-token'
});Complete Examples
E-Commerce Assistant with Client Tools
import { CognipeerClient } from '@cognipeer/sdk';
const client = new CognipeerClient({ token: process.env.COGNIPEER_TOKEN });
const response = await client.conversations.create({
peerId: 'ecommerce-assistant-peer-id',
messages: [
{ role: 'user', content: 'Show me my recent orders and recommend products' }
],
clientTools: [
{
type: 'function',
function: {
name: 'getRecentOrders',
description: 'Get user recent orders',
parameters: {
type: 'object',
properties: {
userId: { type: 'string' },
limit: { type: 'number', default: 5 }
},
required: ['userId']
}
},
implementation: async ({ userId, limit }) => {
const orders = await database.orders.find({ userId, limit });
return orders;
}
},
{
type: 'function',
function: {
name: 'getRecommendations',
description: 'Get product recommendations based on user history',
parameters: {
type: 'object',
properties: {
userId: { type: 'string' },
category: { type: 'string' }
},
required: ['userId']
}
},
implementation: async ({ userId, category }) => {
const recommendations = await recommendationEngine.get(userId, category);
return recommendations;
}
}
],
additionalContext: {
userId: currentUser.id,
preferences: currentUser.preferences
}
});
console.log(response.content);Customer Support with Webchat
<!DOCTYPE html>
<html>
<head>
<title>Customer Support</title>
</head>
<body>
<div id="support-chat"></div>
<script src="https://unpkg.com/@cognipeer/sdk@latest/dist/webchat-browser.min.js"></script>
<script>
const webchat = new CognipeerWebchat({
hookId: 'support-hook-id',
containerId: 'support-chat',
theme: {
primary: '#007bff',
headerBG: '#ffffff',
mainBG: '#f8f9fa'
},
contact: {
email: userEmail,
name: userName
},
context: {
accountType: 'premium',
lastPurchase: '2024-01-15'
},
clientTools: [{
type: 'function',
function: {
name: 'getAccountInfo',
description: 'Get user account information',
parameters: { type: 'object', properties: {} }
},
implementation: async () => {
return {
plan: 'Premium',
billingDate: '2024-02-01',
status: 'active'
};
}
}]
});
webchat.on('conversation-started', (event) => {
console.log('Support chat started:', event.data.conversationId);
analytics.track('support_chat_started');
});
webchat.mount();
</script>
</body>
</html>Migration from @cognipeer/client-js
If you're using the older @cognipeer/client-js package, here's how to migrate:
Package Change
npm uninstall @cognipeer/client-js
npm install @cognipeer/sdkImport Changes
// Old
import CognipeerClient from '@cognipeer/client-js';
// New
import { CognipeerClient } from '@cognipeer/sdk';API Changes
// Old - peer methods (deprecated)
await client.peer.list();
await client.peer.get(peerId);
await client.conversation.create(peerId);
// New - hookId-based API
const peer = await client.peers.get(); // Get peer from channel
const user = await client.users.get(); // Get authenticated user
const channel = await client.channels.get(); // Get channel info
await client.conversations.create({
messages: [{ role: 'user', content: 'Hello' }]
});
messages: [{ role: 'user', content: 'Hello' }]
});New Features Available
- ✅ Client-side tool execution
- ✅ Webchat integration
- ✅ Enhanced TypeScript support
- ✅ Structured JSON output
- ✅ Multi-turn conversation management
Resources
- NPM Package: @cognipeer/sdk
- GitHub Repository: cognipeer/sdk
- API Documentation: Cognipeer API Reference
- Examples: GitHub Examples
Support
- Documentation: https://docs.cognipeer.com
- Discord Community: Join our Discord
- Email Support: support@cognipeer.com
- GitHub Issues: Report issues
License
MIT License - see the LICENSE file for details.

