Skip to main content
This guide will help you generate your first AI-powered response with brand enrichment using Thred SDK.

Prerequisites

Before you begin, make sure you have:
  • Node.js 16.0.0 or higher installed
  • A Thred API key (get one at https://thred.ai)

Setup Guide

1

Install the Package

Install Thred SDK using your preferred package manager:
npm install @thred-apps/thred-js
2

Configure Your API Key

Create a .env file in your project root and add your API key:
.env
THRED_API_KEY=sk_your_api_key_here
Never commit your .env file to version control. Add it to your .gitignore file.
3

Initialize the Client

Create a new file and import the Thred SDK:
index.ts
import { ThredClient } from '@thred-apps/thred-js';

// Initialize the client with your API key
const client = new ThredClient({
  apiKey: process.env.THRED_API_KEY!,
  defaultModel: 'gpt-4',
  timeout: 30000, // 30 seconds (optional)
});
The defaultModel and timeout parameters are optional. They default to 'gpt-4' and 30000ms respectively.
4

Generate Your First Response

Use the answer() method to generate an AI response:
index.ts
async function generateResponse() {
  try {
    const response = await client.answer({
      message: 'What are the best productivity tools for remote teams?',
    });

    // Display the AI-generated response
    console.log('Response:', response.response);

    // Check if a brand was recommended
    if (response.metadata.brandUsed) {
      console.log('\nRecommended Brand:', response.metadata.brandUsed.name);
      console.log('Domain:', response.metadata.brandUsed.domain);
      console.log('Affiliate Link:', response.metadata.link);
      console.log('Similarity Score:', response.metadata.similarityScore);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

generateResponse();
Run your code:
node index.ts
You should see an AI-generated response about productivity tools, along with brand recommendations and affiliate links!
5

Add Streaming (Optional)

For better user experience with long responses, use streaming to display the response in real-time:
streaming.ts
import { ThredClient } from '@thred-apps/thred-js';

const client = new ThredClient({
  apiKey: process.env.THRED_API_KEY!,
});

async function streamResponse() {
  try {
    const metadata = await client.answerStream(
      {
        message: 'Explain agile project management and recommend tools',
        model: 'gpt-4-turbo',
      },
      (accumulatedText) => {
        // This callback is called as the response streams in
        console.clear();
        console.log('Streaming Response:');
        console.log(accumulatedText);
      }
    );

    // After streaming completes, display metadata
    if (metadata?.metadata.brandUsed) {
      console.log('\n--- Brand Information ---');
      console.log('Brand:', metadata.metadata.brandUsed.name);
      console.log('Link:', metadata.metadata.link);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

streamResponse();
Streaming is ideal for longer responses as it provides immediate feedback to users. The answerStream() method calls your callback with accumulated text as it arrives.

Complete Example

Here’s a complete example that demonstrates both streaming and non-streaming responses:
complete-example.ts
import { ThredClient } from '@thred-apps/thred-js';

const client = new ThredClient({
  apiKey: process.env.THRED_API_KEY!,
  defaultModel: 'gpt-4',
});

async function main() {
  // Example 1: Non-streaming response
  console.log('=== Non-Streaming Example ===\n');
  
  const response = await client.answer({
    message: 'What CRM tool should I use for a small business?',
    model: 'gpt-4-turbo',
    temperature: 0.7,
    instructions: 'Be concise and practical',
  });

  console.log('Response:', response.response);
  
  if (response.metadata.brandUsed) {
    console.log('\nBrand:', response.metadata.brandUsed.name);
    console.log('Link:', response.metadata.link);
  }

  // Example 2: Streaming response
  console.log('\n\n=== Streaming Example ===\n');
  
  const metadata = await client.answerStream(
    {
      message: 'Explain the benefits of project management software',
      model: 'gpt-4',
    },
    (text) => {
      // In a real app, you'd update your UI here
      process.stdout.write('\r' + text.substring(0, 100) + '...');
    }
  );

  console.log('\n\nStreaming complete!');
  
  if (metadata?.metadata.brandUsed) {
    console.log('Brand used:', metadata.metadata.brandUsed.name);
  }
}

main().catch(console.error);

Advanced Features

Conversation Context

Maintain context across multiple messages:
const conversationId = `conv_${Date.now()}`;

// First message
const response1 = await client.answer({
  message: 'What email marketing tool do you recommend?',
  conversationId,
});

// Follow-up question with context
const response2 = await client.answer({
  message: 'Does it integrate with Shopify?',
  conversationId,
});

Previous Messages

Provide explicit conversation history:
const response = await client.answer({
  message: 'What features should I look for?',
  previousMessages: [
    {
      role: 'user',
      content: 'I need a CRM for my small business',
    },
    {
      role: 'assistant',
      content: 'I recommend looking at HubSpot or Salesforce...',
    },
  ],
});

Using Async Generators

For more control over streaming:
for await (const chunk of client.answerStreamGenerator({
  message: 'What are the best cloud storage options?',
})) {
  if (typeof chunk === 'string') {
    // Accumulated text update
    console.log('Text:', chunk);
  } else {
    // Final metadata
    console.log('Brand:', chunk.metadata.metadata.brandUsed?.name);
  }
}

Error Handling

Implement robust error handling for production applications:
import {
  ThredClient,
  AuthenticationError,
  ValidationError,
  TimeoutError,
  NetworkError,
} from '@thred-apps/thred-js';

const client = new ThredClient({
  apiKey: process.env.THRED_API_KEY!,
});

try {
  const response = await client.answer({
    message: 'Your question here',
  });
  console.log(response.response);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof ValidationError) {
    console.error('Invalid request:', error.message);
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (error instanceof NetworkError) {
    console.error('Network connection failed');
  } else {
    console.error('Unexpected error:', error);
  }
}

Next Steps

Congratulations! You’ve successfully generated your first AI-powered response with Thred SDK. Here’s what to explore next:

API Reference

Explore all available methods and configuration options

Streaming Responses

Learn advanced streaming patterns and best practices

Conversation Context

Maintain context across multiple interactions

Error Handling

Implement robust error handling for production apps

Build docs developers (and LLMs) love