Product

REST API Overview

Programmatic access to agents, data sources, and analytics

TL;DR

Programmatic access to agents, data sources, and analytics. Protocol: HTTPS only (HTTP redirects to HTTPS with 301)

Key Takeaways

  • Base URL
  • Authentication
  • Rate Limits
  • Response Format
  • Common Error Codes
  • Core Endpoints

Programmatic access to agents, data sources, and analytics.

Base URL

https://api.twig.so

Protocol: HTTPS only (HTTP redirects to HTTPS with 301)

API versioning: Path-based (/api/v1/... for new endpoints, /api/... for legacy)

Authentication

All API requests require authentication using an API key:

curl -X GET https://api.twig.so/api/agents \
  -H "Authorization: Bearer YOUR_API_KEY"

See Authentication for details on generating API keys.

Rate Limits

API requests are rate-limited per organization:

PlanRequests per MinuteRequests per Day
Free201,000
Pro10010,000
Enterprise1,000+Custom

Rate limit headers are included in every response:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

When exceeded, you'll receive a 429 Too Many Requests response.

Response Format

Success Response

{
  "data": {
    "id": "agent-123",
    "name": "Customer Support Agent",
    ...
  },
  "status": "success"
}

Error Response

{
  "error": {
    "code": "invalid_request",
    "message": "Agent not found",
    "details": {
      "agentId": "agent-123"
    }
  },
  "status": "error"
}

Common Error Codes

CodeStatusDescription
invalid_request400Malformed request
unauthorized401Invalid or missing API key
forbidden403Insufficient permissions
not_found404Resource not found
rate_limit_exceeded429Too many requests
internal_error500Server error

Core Endpoints

Chat & Completion

POST /api/chat

Generate an AI response for a given prompt.

curl -X POST https://api.twig.so/api/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "What is your refund policy?",
    "agentId": "agent-123",
    "sessionId": "session-456",
    "stream": false
  }'

Response:

{
  "response": "Our refund policy allows returns within 30 days...",
  "sources": [
    {
      "title": "Refund Policy",
      "url": "https://example.com/refund-policy",
      "content": "...",
      "relevance": 0.95
    }
  ],
  "metadata": {
    "latency": 1.2,
    "tokensUsed": 1523,
    "strategy": "CEDAR",
    "confidence": 0.92
  }
}

Agents

GET /api/ai-agent-managers

List all AI agents in your organization.

curl -X GET https://api.twig.so/api/ai-agent-managers \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /api/ai-agent-managers

Create a new AI agent.

curl -X POST https://api.twig.so/api/ai-agent-managers \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support Agent",
    "description": "Customer support assistant",
    "strategyCode": "CEDAR",
    "dataSourceIds": ["ds-1", "ds-2"]
  }'

GET /api/ai-agent-managers/:id

Get details of a specific agent.

PUT /api/ai-agent-managers/:id

Update an agent's configuration.

DELETE /api/ai-agent-managers/:id

Delete an agent.

Data Sources

GET /api/data-specs

List all data sources.

curl -X GET https://api.twig.so/api/data-specs \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /api/data-specs

Create a new data source.

curl -X POST https://api.twig.so/api/data-specs \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "WEBSITE",
    "name": "Product Documentation",
    "url": "https://docs.example.com",
    "refreshFrequency": "DAILY"
  }'

POST /api/data-specs/:id/process

Trigger processing/sync for a data source.

curl -X POST https://api.twig.so/api/data-specs/ds-123/process \
  -H "Authorization: Bearer YOUR_API_KEY"

Interactions

GET /api/interactions

List recent interactions.

curl -X GET https://api.twig.so/api/interactions?limit=50 \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /api/interactions/feedback

Submit feedback on an interaction.

curl -X POST https://api.twig.so/api/interactions/feedback \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "interactionId": "int-123",
    "rating": 5,
    "comment": "Very helpful!"
  }'

Analytics

GET /api/analytics/charts/dashboard

Get analytics dashboard data.

curl -X GET https://api.twig.so/api/analytics/charts/dashboard?startDate=2024-01-01&endDate=2024-01-31 \
  -H "Authorization: Bearer YOUR_API_KEY"

Advanced Features

Streaming Responses

Enable streaming for real-time response delivery:

curl -X POST https://api.twig.so/api/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Explain RAG in detail",
    "agentId": "agent-123",
    "stream": true
  }'

Responses are sent as Server-Sent Events (SSE):

data: {"delta": "RAG stands for", "done": false}
data: {"delta": " Retrieval-Augmented", "done": false}
data: {"delta": " Generation...", "done": false}
data: {"delta": "", "done": true, "sources": [...]}

Semantic Search Only

Retrieve relevant documents without generating a response:

curl -X POST https://api.twig.so/api/semantic-search \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "pricing information",
    "orgId": "org-123",
    "topK": 10
  }'

Webhooks

Register webhooks to receive events:

curl -X POST https://api.twig.so/api/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhook",
    "events": ["interaction.created", "agent.updated"],
    "secret": "your-webhook-secret"
  }'

SDKs & Client Libraries

JavaScript/TypeScript

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

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

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

console.log(response.text);

Python (Coming Soon)

pip install twig-ai
from twig_ai import TwigAI

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

response = twig.chat(
    prompt="What is your refund policy?",
    agent_id="agent-123"
)

print(response.text)

Best Practices

1. Error Handling

Always handle errors gracefully:

try {
  const response = await twig.chat({ prompt, agentId });
  return response;
} catch (error) {
  if (error.code === 'rate_limit_exceeded') {
    // Wait and retry
    await sleep(1000);
    return retry();
  }
  // Log error and handle appropriately
  logger.error(error);
  throw error;
}

2. Rate Limit Management

Implement exponential backoff:

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.code === 'rate_limit_exceeded' && i < maxRetries - 1) {
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }
      throw error;
    }
  }
}

3. Caching

Cache responses for frequently asked questions:

const cache = new Map();

async function getCachedResponse(prompt, agentId) {
  const cacheKey = `${agentId}:${prompt}`;
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  
  const response = await twig.chat({ prompt, agentId });
  cache.set(cacheKey, response);
  
  return response;
}

4. Session Management

Maintain conversation context with session IDs:

const sessionId = generateSessionId();

// First message
await twig.chat({
  prompt: "What are your pricing plans?",
  agentId: "agent-123",
  sessionId
});

// Follow-up maintains context
await twig.chat({
  prompt: "What's included in the Enterprise plan?",
  agentId: "agent-123",
  sessionId // Same session
});

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/overview.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 26, 2026