Skip to main content
This guide shows how to integrate Agnost AI analytics with your TypeScript/JavaScript AI applications to track conversations, events, and user interactions.

Step 1: Install the SDK

npm install agnostai

Step 2: Initialize the SDK

Import and initialize the SDK with your organization ID:
import * as agnost from 'agnostai';

// Initialize with your organization ID
agnost.init('your-org-id');
You can find your organization ID in your Agnost AI dashboard.

Step 3: Track AI Interactions

Using begin() and end()

Track AI interactions using begin() to start tracking and end() to complete:
// Start tracking an interaction with input
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'weather-agent',
  input: 'What is the weather?'
});

// ... perform AI processing ...

// Complete the interaction with output
// ✨ Latency is automatically calculated!
interaction.end('The weather is sunny.');
You can also set the input later if needed:
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'weather-agent'
});
interaction.setInput('What is the weather?');
interaction.end('The weather is sunny.');

Track with Conversation Grouping

Group related messages using conversationId:
import { v4 as uuidv4 } from 'uuid';

// Create a conversation ID
const conversationId = `conv_${uuidv4()}`;

// First message
const turn1 = agnost.begin({
  userId: 'user_123',
  agentName: 'support-bot',
  input: 'Hello!',
  conversationId
});
turn1.end('Hi there! How can I help?');

// Follow-up message in the same conversation
const turn2 = agnost.begin({
  userId: 'user_123',
  agentName: 'support-bot',
  input: "What's the weather?",
  conversationId
});
turn2.end('The weather is sunny.');

Step 4: Track User Properties

Associate user characteristics with events:
// Identify user traits
agnost.identify('user_123', {
  name: 'John Doe',
  email: '[email protected]',
  plan: 'premium',
  signupDate: '2024-01-15'
});

// Track events with additional properties
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'analytics-agent',
  input: 'Generate a report',
  properties: {
    model: 'gpt-4',
    temperature: '0.7',
    tokens: '1500'
  }
});

// ... perform AI processing ...

interaction.end("Here's your sales report...");

Advanced Features

Adding Properties with begin() and end()

You can add custom properties to track model parameters, metadata, or any other information:
// Start tracking an interaction with input
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'weather-agent',
  input: 'What is the weather?'
});

// Set properties (chainable)
interaction
  .setProperty('model', 'gpt-4')
  .setProperty('temperature', '0.7');

// Or set multiple properties at once
interaction.setProperties({
  tokens: '150',
  cost: '0.003'
});

// ... perform async work (API calls, processing, etc.) ...

// Complete the interaction
// ✨ Latency is automatically calculated from begin() to end()!
interaction.end('The weather is sunny.');

// Or manually override latency if needed
interaction.end('The weather is sunny.', true, 1500);

Error Tracking

When tracking failed interactions, set success=false and pass the error message as the output:
// Using begin() and end() for errors
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'image-agent',
  input: 'Generate an image'
});

try {
  const result = await generateImage();
  interaction.end(result);
} catch (error) {
  interaction.end(
    error instanceof Error ? error.message : 'Unknown error',
    false  // success = false
  );
}

Custom Configuration

Configure the SDK with custom settings:
import * as agnost from 'agnostai';

// Initialize with custom configuration
agnost.init('your-org-id', {
  endpoint: 'https://api.agnost.ai',
  debug: true  // Enable debug logging
});

API Reference

init()

Initialize the SDK with your organization ID.
agnost.init(writeKey: string, config?: ConversationConfig): boolean
ParameterTypeRequiredDescription
writeKeystringYesYour organization ID
configobjectNoConfiguration options
Configuration Options:
OptionTypeDefaultDescription
endpointstring"https://api.agnost.ai"API endpoint URL
debugbooleanfalseEnable debug logging

identify()

Associate user characteristics with a user ID.
agnost.identify(userId: string, traits: Record<string, any>): boolean

begin()

Begin a partial interaction for deferred completion. Returns an Interaction object.
agnost.begin(options: BeginOptions): Interaction | null
BeginOptions:
ParameterTypeRequiredDescription
userIdstringYesUser identifier
agentNamestringYesAgent name
inputstringNoInput text/prompt (can also use setInput() later)
conversationIdstringNoConversation ID (auto-generated if not provided)
propertiesobjectNoInitial properties
eventstringNoOptional event name
interactionIdstringNoCustom interaction ID (auto-generated if not provided). Useful for retrieving the interaction later with getInteraction()
Interaction Methods:
MethodDescription
setInput(text)Set input text (optional if already passed to begin())
setProperties(obj)Set multiple properties (chainable)
setProperty(key, value)Set single property (chainable)
end(output, success?, latency?)Complete interaction
end() Parameters:
ParameterTypeDefaultDescription
outputstringRequiredResponse text. When success=false, this is the error message
successbooleantrueWhether successful
latencynumberAutoAutomatically calculated if not provided
// Recommended: Pass input directly
const interaction = agnost.begin({
  userId: 'user_123',
  agentName: 'my-agent',
  input: 'What is the weather?'
});
interaction.setProperty('model', 'gpt-4');

// Success case
interaction.end('Result');  // latency auto-calculated!

// Error case - output contains error message
interaction.end('Error: timeout', false);

getInteraction()

Retrieve an active interaction by its ID. Useful when you need to complete an interaction from a different context (e.g., callback, different function) without passing the Interaction object around.
agnost.getInteraction(interactionId: string): Interaction | null
Example:
// In your request handler
function handleRequest(requestId: string, userMessage: string) {
  agnost.begin({
    userId: 'user_123',
    agentName: 'chat-agent',
    input: userMessage,
    interactionId: requestId  // Use your own ID
  });

  // Pass only the ID to your AI service
  callAIService(requestId, userMessage);
}

// Later, in a callback or different function
function onAIResponse(requestId: string, response: string) {
  const interaction = agnost.getInteraction(requestId);
  if (interaction) {
    interaction
      .setProperty('model', 'gpt-4')
      .setProperty('tokens', 250)
      .end(response);
  }
}
Returns null if the interaction is not found or has already been completed.

flush()

Manually flush all queued events.
await agnost.flush(): Promise<void>

shutdown()

Shutdown the SDK and flush remaining events.
await agnost.shutdown(): Promise<void>

setDebugLogs()

Enable or disable debug logging.
agnost.setDebugLogs(enabled: boolean): void

Complete Example

Here’s a complete example of a chatbot with conversation tracking:
import * as agnost from 'agnostai';
import { v4 as uuidv4 } from 'uuid';

// Initialize the SDK
agnost.init('your-org-id');

// Identify the user
agnost.identify('user_123', {
  name: 'Alice Smith',
  email: '[email protected]',
  plan: 'premium'
});

// Create a conversation
const conversationId = `conv_${uuidv4()}`;

// Simulate a multi-turn conversation
async function chat() {
  // First turn
  const turn1 = agnost.begin({
    userId: 'user_123',
    agentName: 'chatbot',
    input: 'Hello!',
    conversationId,
    properties: { model: 'gpt-4' }
  });

  // Simulate AI processing
  await new Promise(resolve => setTimeout(resolve, 500));

  turn1.end('Hi! How can I help you today?');

  // Second turn
  const turn2 = agnost.begin({
    userId: 'user_123',
    agentName: 'chatbot',
    input: "What's the weather like?",
    conversationId,
    properties: { model: 'gpt-4' }
  });

  await new Promise(resolve => setTimeout(resolve, 800));

  turn2.end('The weather is sunny and 72°F.');

  // Shutdown when done
  await agnost.shutdown();
}

chat();

Using with Custom Client

For multiple clients or advanced use cases:
import { ConversationClient } from 'agnostai';

const client = new ConversationClient();
client.init('your-org-id');

const interaction = client.begin({
  userId: 'user_123',
  agentName: 'greeting-bot',
  input: 'Hello!'
});

interaction.end('Hello! How can I help you today?');

await client.shutdown();

Browser Support

This SDK works in both Node.js and browser environments. It uses the native fetch API which is available in:
  • Node.js 18+
  • All modern browsers
For older Node.js versions, you may need to install a fetch polyfill.

Next Steps