Skip to content

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

bash
npm install @cognipeer/sdk

Or with Yarn:

bash
yarn add @cognipeer/sdk

Or with pnpm:

bash
pnpm add @cognipeer/sdk

Quick Start

Prerequisites

Before using the SDK, you need:

  1. Personal Access Token (PAT): Generate from SettingsSecurityPersonal Access Tokens
  2. API Channel Hook ID: Create an API channel for your peer to get a hookId

Basic Conversation

typescript
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:

typescript
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

typescript
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

typescript
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);
  }
});
ParameterTypeRequiredDescription
tokenstringYesPersonal Access Token (PAT) for authentication
hookIdstringYesAPI channel hook ID
apiUrlstringNoThe base URL for the API (default: 'https://api.cognipeer.com/v1')
baseUrlstringNoBase URL for the web app (default: 'https://app.cognipeer.com')
timeoutnumberNoRequest timeout in milliseconds (default: 60000)
autoExecuteToolsbooleanNoAutomatically execute client tools (default: true)
maxToolExecutionsnumberNoMaximum tool execution loops (default: 10)
onToolStartfunctionNoCallback when tool execution starts
onToolEndfunctionNoCallback when tool execution completes

Core API Reference

Conversations

conversations.create(options)

Create a new conversation and get a response.

typescript
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:

ParameterTypeRequiredDescription
messagesMessage[]YesArray of messages to send
clientToolsClientTool[]NoClient-side tools the AI can call
response_format'text' | 'json'NoResponse format (default: 'text')
response_schemaobjectNoJSON schema for structured responses
userIdstringNoUser ID to associate with conversation
contactIdstringNoContact ID to associate with conversation

Returns: Promise<CreateConversationResponse>

typescript
{
  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.

typescript
const response = await client.conversations.sendMessage({
  conversationId: 'conv-123',
  content: 'Tell me more about that',
  clientTools: [...]
});

Parameters:

ParameterTypeRequiredDescription
conversationIdstringYesThe conversation ID
contentstringYesMessage content
clientToolsClientTool[]NoClient-side tools
response_format'text' | 'json'NoResponse format
response_schemaobjectNoJSON schema

Returns: Promise<SendMessageResponse>

conversations.list(options)

List conversations with pagination.

typescript
const { data, total, page, limit } = await client.conversations.list({ 
  page: 1,
  limit: 20,
  sort: { createdDate: -1 }
});

Parameters:

ParameterTypeRequiredDescription
pagenumberNoPage number (default: 1)
limitnumberNoItems per page (default: 10)
sortobjectNoSort criteria
filterobjectNoAdditional filters

Returns: Promise<ListConversationsResponse>

typescript
{
  data: Conversation[];
  total: number;
  page: number;
  limit: number;
}

conversations.get(conversationId)

Get a specific conversation by ID.

typescript
const conversation = await client.conversations.get('conversation-id');

Returns: Promise<Conversation>

conversations.getMessages(options)

Get messages from a conversation.

typescript
const messages = await client.conversations.getMessages({
  conversationId: 'conv-123',
  messagesCount: 50
});

Parameters:

ParameterTypeRequiredDescription
conversationIdstringYesThe conversation ID
messagesCountnumberNoNumber of messages (default: 10)

Returns: Promise<ConversationMessage[]>

conversations.resumeMessage(options)

Resume message execution with tool result (manual mode).

typescript
const response = await client.conversations.resumeMessage({
  conversationId: 'conv-123',
  messageId: 'msg-456',
  toolResult: {
    executionId: 'exec-789',
    success: true,
    output: 'Tool result data'
  }
});

Parameters:

ParameterTypeRequiredDescription
conversationIdstringYesThe conversation ID
messageIdstringYesThe message ID
toolResultToolResultYesTool execution result

Returns: Promise<ResumeMessageResponse>

Peers

peers.get()

Get the peer associated with your API channel.

typescript
const peer = await client.peers.get();

console.log(peer.name);        // Peer name
console.log(peer.modelId);     // AI model
console.log(peer.prompt);      // System prompt

Returns: Promise<Peer>

typescript
{
  _id: string;
  name: string;
  modelId: string;
  prompt: string;
  temperature?: number;
  messagesCount?: number;
  // ... other properties
}

Users

users.get()

Get authenticated user information.

typescript
const user = await client.users.get();

console.log(user.email);           // User email
console.log(user.displayName);     // Display name
console.log(user.workspace.name);  // Workspace name

Returns: Promise<User>

typescript
{
  _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.

typescript
const channel = await client.channels.get();

console.log(channel.hookId);       // Hook ID
console.log(channel.isActive);     // Active status
console.log(channel.channelType);  // Channel type

Returns: Promise<Channel>

typescript
{
  _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.

typescript
const result = await client.flows.execute({
  flowId: 'invoice-analyzer',
  inputs: {
    document: 'base64-content',
    analysisType: 'detailed'
  }
});

console.log(result.outputs);

Get available peers.

typescript
const peers = await client.peers.list({ limit: 20 });

Parameters:

ParameterTypeRequiredDescription
options.limitnumberNoMaximum results (default: 10)

Returns: Promise<Peer[]>

peers.get(peerId)

Get a specific peer by ID.

typescript
const peer = await client.peers.get('peer-id');

Returns: Promise<Peer>

Flows

flows.execute(flowId, inputs)

Execute a flow with inputs.

typescript
const result = await client.flows.execute('flow-id', {
  inputs: {
    name: 'John Doe',
    query: 'How do I reset my password?'
  }
});

Parameters:

ParameterTypeRequiredDescription
flowIdstringYesThe flow ID to execute
inputsobjectYesInput 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

typescript
{
  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

typescript
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

typescript
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

typescript
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:

typescript
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

typescript
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

typescript
const webchat = new CognipeerWebchat({
  hookId: 'your-hook-id',
  containerId: 'chat-container',
  width: '100%',
  height: '600px',
  theme: { primary: '#00b5a5' }
});

webchat.mount();

HTML:

html
<div id="chat-container"></div>

Event Handling

typescript
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 loaded
  • message-sent - User sent a message
  • message-received - AI response received
  • conversation-started - New conversation created
  • conversation-ended - Conversation closed
  • error - Error occurred

Webchat with Client Tools

You can also provide client tools to webchat for enhanced functionality:

typescript
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:

typescript
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

typescript
// 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

typescript
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

typescript
import { CognipeerClient, CognipeerWebchat } from '@cognipeer/sdk';

const client = new CognipeerClient({ token: 'your-token' });
// Use as normal

Via CDN

html
<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:

typescript
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:

javascript
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:

javascript
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

typescript
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

html
<!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

bash
npm uninstall @cognipeer/client-js
npm install @cognipeer/sdk

Import Changes

typescript
// Old
import CognipeerClient from '@cognipeer/client-js';

// New
import { CognipeerClient } from '@cognipeer/sdk';

API Changes

typescript
// 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

Support

License

MIT License - see the LICENSE file for details.

Built with VitePress