Product

SDKs & Client Libraries

Official and community SDKs for integrating Twig AI into your applications

TL;DR

Official and community SDKs for integrating Twig AI into your applications. Installation:

Key Takeaways

  • Official SDKs
  • SDK Features
  • Error Handling
  • Advanced Usage
  • Community SDKs
  • Best Practices

Official and community SDKs for integrating Twig AI into your applications.

Official SDKs

JavaScript/TypeScript SDK

Installation:

npm install @twig-ai/sdk
# or
yarn add @twig-ai/sdk

Basic Usage:

import { TwigAI } from '@twig-ai/sdk';

const twig = new TwigAI({
  apiKey: process.env.TWIG_API_KEY
});

// Chat completion
const response = await twig.chat.create({
  prompt: 'What is your refund policy?',
  agentId: 'agent-123'
});

console.log(response.text);
console.log(response.sources);

Advanced Features:

// Streaming responses
const stream = await twig.chat.create({
  prompt: 'Explain RAG in detail',
  agentId: 'agent-123',
  stream: true
});

for await (const chunk of stream) {
  process.stdout.write(chunk.delta);
}

// Session management
const session = twig.sessions.create();

await twig.chat.create({
  prompt: 'Tell me about pricing',
  agentId: 'agent-123',
  sessionId: session.id
});

await twig.chat.create({
  prompt: 'What about the Pro plan?',
  agentId: 'agent-123',
  sessionId: session.id  // Maintains context
});

Python SDK (Coming Soon)

Installation:

pip install twig-ai

Basic Usage:

from twig_ai import TwigAI

twig = TwigAI(api_key=os.environ['TWIG_API_KEY'])

# Chat completion
response = twig.chat.create(
    prompt='What is your refund policy?',
    agent_id='agent-123'
)

print(response.text)
print(response.sources)

SDK Features

Chat Completion

const response = await twig.chat.create({
  prompt: string,              // User query (required)
  agentId: string,             // Agent ID (required)
  sessionId?: string,          // For context
  stream?: boolean,            // Streaming response
  temperature?: number,        // 0.0-1.0
  maxTokens?: number,          // Response length
  topK?: number,               // Retrieval count
  metadata?: object            // Custom metadata
});

Agent Management

// List agents
const agents = await twig.agents.list();

// Get agent
const agent = await twig.agents.get('agent-123');

// Create agent
const newAgent = await twig.agents.create({
  name: 'Support Agent',
  strategyCode: 'CEDAR',
  dataSourceIds: ['ds-1', 'ds-2']
});

// Update agent
await twig.agents.update('agent-123', {
  temperature: 0.5
});

// Delete agent
await twig.agents.delete('agent-123');

Data Source Management

// List data sources
const dataSources = await twig.dataSources.list();

// Create data source
const ds = await twig.dataSources.create({
  type: 'WEBSITE',
  name: 'Product Docs',
  url: 'https://docs.example.com'
});

// Trigger processing
await twig.dataSources.process('ds-123');

Analytics

// Get dashboard data
const analytics = await twig.analytics.dashboard({
  startDate: '2024-01-01',
  endDate: '2024-01-31',
  agentId: 'agent-123'
});

console.log(analytics.metrics.totalQueries);
console.log(analytics.metrics.avgResponseTime);

Error Handling

Try-Catch Pattern

try {
  const response = await twig.chat.create({
    prompt: 'Hello',
    agentId: 'agent-123'
  });
} catch (error) {
  if (error instanceof TwigAI.RateLimitError) {
    // Handle rate limit
    await sleep(1000);
    // Retry
  } else if (error instanceof TwigAI.AuthenticationError) {
    // Handle auth error
    console.error('Invalid API key');
  } else {
    // Handle other errors
    console.error('Error:', error.message);
  }
}

Error Types

TwigAI.APIError              // Base error
├─ TwigAI.AuthenticationError  // 401 errors
├─ TwigAI.PermissionError      // 403 errors
├─ TwigAI.NotFoundError        // 404 errors
├─ TwigAI.RateLimitError       // 429 errors
└─ TwigAI.ServerError          // 500 errors

Advanced Usage

Retry with Backoff

import { TwigAI, retry } from '@twig-ai/sdk';

const twig = new TwigAI({
  apiKey: process.env.TWIG_API_KEY,
  maxRetries: 3,
  retryDelay: (attempt) => Math.pow(2, attempt) * 1000
});

const response = await twig.chat.create({...});

Custom Configuration

const twig = new TwigAI({
  apiKey: process.env.TWIG_API_KEY,
  baseURL: 'https://api.twig.so',
  timeout: 30000,              // 30 seconds
  maxRetries: 3,
  httpAgent: customAgent,      // Custom HTTP agent
  headers: {
    'X-Custom-Header': 'value'
  }
});

Webhook Helpers

import { TwigAI } from '@twig-ai/sdk';

// Verify webhook signature
const isValid = TwigAI.webhooks.verify(
  payload,
  signature,
  secret
);

// Parse webhook event
const event = TwigAI.webhooks.parse(payload);

if (event.type === 'interaction.completed') {
  handleInteraction(event.data);
}

Community SDKs

Ruby (Community)

# Gemfile
gem 'twig-ai'

# Usage
require 'twig_ai'

client = TwigAI::Client.new(api_key: ENV['TWIG_API_KEY'])

response = client.chat.create(
  prompt: 'What is your refund policy?',
  agent_id: 'agent-123'
)

puts response.text

Go (Community)

import "github.com/twig-ai/twig-go"

client := twig.NewClient(os.Getenv("TWIG_API_KEY"))

response, err := client.Chat.Create(context.Background(), &twig.ChatRequest{
    Prompt:  "What is your refund policy?",
    AgentID: "agent-123",
})

if err != nil {
    log.Fatal(err)
}

fmt.Println(response.Text)

Best Practices

1. API Key Management

✅ Use environment variables ✅ Different keys per environment ✅ Rotate keys regularly ❌ Don't hardcode keys

2. Error Handling

✅ Catch specific error types ✅ Implement retry logic ✅ Log errors properly ❌ Don't ignore errors

3. Performance

✅ Reuse client instances ✅ Enable connection pooling ✅ Use streaming for long responses ❌ Don't create new client per request

4. Testing

✅ Mock SDK calls in tests ✅ Use test API keys ✅ Test error scenarios ❌ Don't test against production

Examples

Next.js API Route

// pages/api/chat.ts
import { TwigAI } from '@twig-ai/sdk';

const twig = new TwigAI({
  apiKey: process.env.TWIG_API_KEY
});

export default async function handler(req, res) {
  try {
    const { prompt } = req.body;
    
    const response = await twig.chat.create({
      prompt,
      agentId: process.env.AGENT_ID
    });
    
    res.json(response);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

Express.js Server

import express from 'express';
import { TwigAI } from '@twig-ai/sdk';

const app = express();
const twig = new TwigAI({
  apiKey: process.env.TWIG_API_KEY
});

app.post('/api/chat', async (req, res) => {
  const { prompt, agentId } = req.body;
  
  try {
    const response = await twig.chat.create({
      prompt,
      agentId
    });
    
    res.json(response);
  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);

React Component

import { useState } from 'react';
import { TwigAI } from '@twig-ai/sdk';

const twig = new TwigAI({
  apiKey: process.env.NEXT_PUBLIC_TWIG_API_KEY
});

function ChatComponent() {
  const [response, setResponse] = useState('');
  
  async function handleSubmit(prompt: string) {
    const result = await twig.chat.create({
      prompt,
      agentId: 'agent-123'
    });
    
    setResponse(result.text);
  }
  
  return (
    <div>
      <input onSubmit={handleSubmit} />
      <div>{response}</div>
    </div>
  );
}

Contributing

Want to create an SDK for another language?

  1. Fork our SDK template
  2. Implement required methods
  3. Add tests
  4. Submit for review
  5. Listed as community SDK

Next Steps


Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the ask query parameter:

GET /dev/product/developer-api/sdks.md?ask=<question>

The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Related Pages

Last updated January 25, 2026