Overview

The Suada Node.js SDK provides a simple and intuitive way to interact with the Suada API. It includes built-in TypeScript support and handles all the complexity of making API requests, managing authentication, and parsing responses.

Prerequisites

  • Node.js version 18.0.0 or higher
  • A Suada API key
  • npm or yarn package manager

Installation

Install the Suada Node.js SDK using npm:

npm install @suada/sdk

Or using yarn:

yarn add @suada/sdk

Quick Start

Here’s a basic example to get you started:

import { Suada } from '@suada/sdk';

// Initialize the client
const suada = new Suada({
  apiKey: 'your-api-key'
});

// Send a chat message
async function chat() {
  try {
    const response = await suada.chat({
      message: 'What insights can you provide about our recent performance?'
    });
    console.log(response.answer);
  } catch (error) {
    console.error('Error:', error);
  }
}

chat();

Authentication

Setting up your API Key

We recommend storing your API key in environment variables:

# .env
SUADA_API_KEY=your-api-key

Then load it in your application:

import dotenv from 'dotenv';
import { Suada } from '@suada/sdk';

dotenv.config();

const suada = new Suada({
  apiKey: process.env.SUADA_API_KEY
});

Core Concepts

Chat Messages

The chat endpoint is the primary way to interact with Suada. Each chat request can include:

  • A message (required)
  • Chat history (optional)
  • Configuration options (optional)
const response = await suada.chat({
  message: "How's our business performing?",
  chatHistory: previousMessages, // Optional
  privacyMode: true            // Optional
});

Response Format

Chat responses include several key components:

interface SuadaResponse {
  // The main response text
  answer: string;
  
  // Internal reasoning process (optional)
  thoughts?: string;
  
  // Actions taken during processing (optional)
  actions?: Array<{
    tool: string;
    toolInput: string;
    log: string;
  }>;
  
  // Suggested follow-up question (optional)
  followUpQuestion?: string;
  
  // Reasoning behind the response (optional)
  reasoning?: string;
  
  // Reference sources (optional)
  sources?: string[];
  
  // Conversation tracking ID (optional)
  conversationId?: string;
  
  // Response timestamp
  timestamp: number;
}

Advanced Features

LangChain Integration

The SDK provides seamless integration with LangChain, allowing you to use Suada’s capabilities within your LangChain applications:

import { Suada } from '@suada/sdk';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { PromptTemplate } from 'langchain/prompts';

// Initialize Suada
const suada = new Suada({
  apiKey: process.env.SUADA_API_KEY
});

// Create a Suada tool for LangChain
const suadaTool = suada.createTool({
  name: 'business_analyst',
  description: 'Use this tool to get business insights and analysis',
  externalUserIdentifier: 'user-123' // Required if using passthrough mode
});

// Create an OpenAI agent with the Suada tool
const model = new ChatOpenAI({ temperature: 0 });
const tools = [suadaTool];

const prompt = PromptTemplate.fromTemplate(`
  You are a helpful assistant that uses Suada's business analyst capabilities.
  
  Current conversation:
  {chat_history}
  
  Human: {input}
  Assistant: Let me help you with that.
`);

const agent = await createOpenAIFunctionsAgent({
  llm: model,
  tools,
  prompt
});

const executor = AgentExecutor.fromAgentAndTools({
  agent,
  tools,
  verbose: true
});

// Use the agent
const result = await executor.invoke({
  input: "What's our revenue trend for the last quarter?",
  chat_history: []
});

LangChain Best Practices

  1. Tool Configuration

    • Provide clear, specific descriptions for your tools
    • Use appropriate temperature settings for your use case
    • Consider implementing tool-specific error handling
  2. Agent Setup

    • Use structured prompts for consistent behavior
    • Implement proper chat history management
    • Consider using memory for maintaining context
  3. Error Handling

    • Implement proper error handling for both Suada and LangChain
    • Consider retry logic for transient failures
    • Log agent actions for debugging
  4. Performance

    • Reuse agent instances when possible
    • Implement appropriate timeouts
    • Consider caching for frequently used data

Passthrough Mode

Passthrough mode allows you to associate Suada conversations with your application’s user system:

const suada = new Suada({
  apiKey: process.env.SUADA_API_KEY,
  passthroughMode: true
});

// When using passthrough mode, include externalUserIdentifier
const response = await suada.chat({
  message: "What's our revenue trend?",
  externalUserIdentifier: 'user-123'  // Required in passthrough mode
});

Privacy Mode

Enable privacy mode to ensure sensitive information is handled with additional security:

const response = await suada.chat({
  message: "Analyze our financial data",
  privacyMode: true
});

Error Handling

The SDK provides typed errors for better error handling:

import { Suada, SuadaError, SuadaAPIError } from '@suada/sdk';

try {
  const response = await suada.chat({
    message: "What's our revenue?"
  });
} catch (error) {
  if (error instanceof SuadaAPIError) {
    // Handle API-specific errors
    console.error('API Error:', error.message, error.status, error.code);
  } else if (error instanceof SuadaError) {
    // Handle general SDK errors
    console.error('SDK Error:', error.message);
  } else {
    // Handle unexpected errors
    console.error('Unexpected error:', error);
  }
}

Best Practices

  1. Environment Variables

    • Store API keys and sensitive configuration in environment variables
    • Use a package like dotenv to manage environment variables
  2. Error Handling

    • Always implement try-catch blocks around API calls
    • Use the provided error types for specific error handling
    • Log errors appropriately for debugging
  3. TypeScript Usage

    • Take advantage of built-in type definitions
    • Enable strict mode in your TypeScript configuration
    • Use type annotations for better code reliability
  4. Response Processing

    • Always check for the presence of optional fields before using them
    • Handle missing data gracefully
    • Consider implementing retry logic for failed requests

Configuration Options

OptionTypeRequiredDescription
apiKeystringYesYour Suada API key
baseUrlstringNoCustom API endpoint (defaults to https://suada.ai/api/public)
passthroughModebooleanNoEnable user-specific resources

FAQ

How do I handle rate limiting?

The SDK automatically handles rate limiting by implementing exponential backoff. You can customize this behavior by implementing your own retry logic.

Can I use the SDK in a browser environment?

No, the SDK is designed for server-side Node.js applications only. For browser applications, use our REST API with appropriate CORS headers.

How do I maintain conversation context?

Use the chatHistory parameter to maintain conversation context:

const messages = [];
const response1 = await suada.chat({ message: "How's our revenue?" });
messages.push({ role: 'user', content: "How's our revenue?" });
messages.push({ role: 'assistant', content: response1.answer });

const response2 = await suada.chat({
  message: "Compare that to last year",
  chatHistory: messages
});

How can I debug API calls?

Enable debug logging by setting the DEBUG environment variable:

DEBUG=suada:* node your-app.js

Support