CoAI LogoCoAI.Dev
Reference

API Reference

Complete API documentation for CoAI.Dev platform integration

API Reference

Complete reference for CoAI.Dev's REST API, including authentication, endpoints, request/response formats, and integration examples.

Base URL and Versioning

Production: https://api.chatnio.com/v1
Staging: https://staging-api.chatnio.com/v1

All API requests must include the version in the URL path. The current stable version is v1.

Authentication

CoAI.Dev API uses API keys for authentication. Include your API key in the Authorization header:

Authorization: Bearer YOUR_API_KEY

Obtaining API Keys

  1. Admin Panel: Navigate to Settings → API Keys
  2. User Dashboard: Go to Profile → API Access
  3. Programmatic: Use the API Key Management endpoints

Security Best Practices

  • Store API keys securely (environment variables, secret managers)
  • Use different keys for different environments
  • Rotate keys regularly (recommended: every 90 days)
  • Monitor API key usage for anomalies

Rate Limiting

API requests are subject to rate limiting:

TierRequests/MinuteRequests/HourRequests/Day
Free601,00010,000
Pro30010,000100,000
Enterprise1,00050,0001,000,000

Rate limit headers are included in all responses:

  • X-RateLimit-Limit: Total requests allowed in time window
  • X-RateLimit-Remaining: Requests remaining in current window
  • X-RateLimit-Reset: Unix timestamp when rate limit resets

Chat Completions API

Create Chat Completion

The primary endpoint for AI conversations, compatible with OpenAI's chat completions format.

POST /v1/chat/completions

Request Body:

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user", 
      "content": "Hello, how are you?"
    }
  ],
  "max_tokens": 150,
  "temperature": 0.7,
  "stream": false
}

Response:

{
  "id": "chatcmpl-8x9Xz2B3QmR5nF7k",
  "object": "chat.completion",
  "created": 1704067200,
  "model": "gpt-4",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! I'm doing well, thank you for asking. How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 21,
    "completion_tokens": 16,
    "total_tokens": 37
  }
}

Streaming Completions

For real-time streaming responses, set stream: true:

const response = await fetch('/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    model: 'gpt-4',
    messages: [{role: 'user', content: 'Tell me a story'}],
    stream: true
  })
});
 
const reader = response.body.getReader();
const decoder = new TextDecoder();
 
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  const lines = chunk.split('\n').filter(line => line.trim());
  
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = line.slice(6);
      if (data === '[DONE]') return;
      
      try {
        const parsed = JSON.parse(data);
        const content = parsed.choices[0]?.delta?.content;
        if (content) {
          console.log(content); // Stream content
        }
      } catch (e) {
        console.error('Parse error:', e);
      }
    }
  }
}

Message Roles

RoleDescriptionRequired
systemInstructions for the AI assistantOptional
userMessage from the userRequired
assistantPrevious AI response (for conversation context)Optional
functionFunction call result (for function calling)Optional

Function Calling

Enable the AI to call predefined functions:

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "What's the weather in San Francisco?"
    }
  ],
  "functions": [
    {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "City name"
          },
          "units": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"],
            "description": "Temperature units"
          }
        },
        "required": ["location"]
      }
    }
  ],
  "function_call": "auto"
}

Models API

List Available Models

GET /v1/models

Response:

{
  "object": "list",
  "data": [
    {
      "id": "gpt-4",
      "object": "model",
      "created": 1704067200,
      "owned_by": "openai",
      "permission": [],
      "root": "gpt-4",
      "parent": null,
      "context_length": 8192,
      "max_tokens": 4096,
      "pricing": {
        "input_tokens": 0.03,
        "output_tokens": 0.06
      }
    }
  ]
}

Get Model Details

GET /v1/models/{model_id}

Response:

{
  "id": "gpt-4",
  "object": "model",
  "created": 1704067200,
  "owned_by": "openai",
  "context_length": 8192,
  "max_tokens": 4096,
  "description": "GPT-4 is a large multimodal model",
  "capabilities": ["text", "function_calling"],
  "pricing": {
    "input_tokens": 0.03,
    "output_tokens": 0.06,
    "currency": "USD"
  },
  "rate_limits": {
    "requests_per_minute": 500,
    "tokens_per_minute": 10000
  }
}

File Upload API

Upload File

POST /v1/files
Content-Type: multipart/form-data

Request:

curl -X POST https://api.chatnio.com/v1/files \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@document.pdf" \
  -F "purpose=chat"

Response:

{
  "id": "file-BK7bzQj3VfWGq5xg",
  "object": "file",
  "bytes": 175542,
  "created_at": 1704067200,
  "filename": "document.pdf",
  "purpose": "chat",
  "status": "uploaded",
  "processing_status": "completed",
  "extracted_text": "Document content...",
  "metadata": {
    "pages": 5,
    "file_type": "application/pdf"
  }
}

List Files

GET /v1/files

Query Parameters:

  • purpose (string): Filter by file purpose
  • limit (integer): Number of files to return (default: 20)
  • offset (integer): Pagination offset

Delete File

DELETE /v1/files/{file_id}

Users API

Get Current User

GET /v1/users/me

Response:

{
  "id": "user-123",
  "email": "user@example.com",
  "name": "John Doe",
  "created_at": "2024-01-01T00:00:00Z",
  "subscription": {
    "plan": "pro",
    "status": "active",
    "credits_remaining": 1000,
    "reset_date": "2024-02-01T00:00:00Z"
  },
  "usage": {
    "tokens_used_today": 1250,
    "requests_made_today": 45
  }
}

Update User Profile

PATCH /v1/users/me

Request Body:

{
  "name": "John Smith",
  "preferences": {
    "default_model": "gpt-4",
    "temperature": 0.7
  }
}

Conversations API

List Conversations

GET /v1/conversations

Query Parameters:

  • limit (integer): Number of conversations (default: 20, max: 100)
  • offset (integer): Pagination offset
  • order (string): Sort order (asc or desc, default: desc)

Response:

{
  "object": "list",
  "data": [
    {
      "id": "conv-123",
      "title": "AI Assistant Conversation",
      "created_at": "2024-01-15T10:00:00Z",
      "updated_at": "2024-01-15T10:30:00Z",
      "message_count": 6,
      "model": "gpt-4",
      "shared": false
    }
  ],
  "has_more": false,
  "total_count": 15
}

Get Conversation

GET /v1/conversations/{conversation_id}

Create Conversation

POST /v1/conversations

Request Body:

{
  "title": "New Conversation",
  "model": "gpt-4",
  "system_message": "You are a helpful assistant."
}

Update Conversation

PATCH /v1/conversations/{conversation_id}

Delete Conversation

DELETE /v1/conversations/{conversation_id}

Channels API (Admin)

List Channels

GET /v1/admin/channels

Response:

{
  "data": [
    {
      "id": "channel-123",
      "name": "OpenAI GPT-4",
      "type": "openai",
      "status": "active",
      "models": ["gpt-4", "gpt-3.5-turbo"],
      "priority": 1,
      "weight": 100,
      "health_status": "healthy",
      "last_check": "2024-01-15T10:00:00Z"
    }
  ]
}

Create Channel

POST /v1/admin/channels

Request Body:

{
  "name": "My OpenAI Channel",
  "type": "openai",
  "config": {
    "api_key": "sk-...",
    "base_url": "https://api.openai.com/v1",
    "models": ["gpt-4", "gpt-3.5-turbo"]
  },
  "priority": 1,
  "weight": 100
}

Test Channel

POST /v1/admin/channels/{channel_id}/test

Analytics API

Get Usage Statistics

GET /v1/analytics/usage

Query Parameters:

  • start_date (string): Start date (ISO 8601)
  • end_date (string): End date (ISO 8601)
  • granularity (string): hour, day, week, month
  • model (string): Filter by model
  • user_id (string): Filter by user

Response:

{
  "period": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  },
  "total_requests": 1250,
  "total_tokens": 450000,
  "unique_users": 45,
  "revenue": 125.50,
  "breakdown": [
    {
      "date": "2024-01-15",
      "requests": 85,
      "tokens": 32500,
      "users": 12,
      "revenue": 8.75
    }
  ]
}

Error Handling

All API endpoints return standard HTTP status codes and error responses:

Error Response Format

{
  "error": {
    "type": "invalid_request_error",
    "code": "missing_required_parameter",
    "message": "Missing required parameter: 'model'",
    "param": "model",
    "request_id": "req-123456"
  }
}

Common Error Codes

HTTP StatusError TypeDescription
400invalid_request_errorBad request format or missing parameters
401authentication_errorInvalid or missing API key
403permission_errorInsufficient permissions
404not_found_errorResource not found
429rate_limit_errorRate limit exceeded
500internal_server_errorServer error
503service_unavailable_errorService temporarily unavailable

Rate Limit Error

{
  "error": {
    "type": "rate_limit_error",
    "code": "requests_per_minute_exceeded",
    "message": "Rate limit exceeded. Try again in 60 seconds.",
    "retry_after": 60
  }
}

Webhooks

Configure webhooks to receive real-time notifications about events in your CoAI.Dev account.

Webhook Events

EventDescription
conversation.createdNew conversation started
conversation.completedConversation ended
user.registeredNew user registration
usage.threshold_reachedUsage limit threshold reached
channel.health_changedChannel health status changed
payment.succeededPayment processed successfully
payment.failedPayment processing failed

Webhook Payload Example

{
  "id": "evt_123456",
  "object": "event",
  "type": "conversation.created",
  "created": 1704067200,
  "data": {
    "object": {
      "id": "conv-123",
      "title": "New Conversation",
      "user_id": "user-456",
      "model": "gpt-4",
      "created_at": "2024-01-15T10:00:00Z"
    }
  }
}

Webhook Security

Verify webhook signatures using the provided signing secret:

const crypto = require('crypto');
 
function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

SDK Examples

// Install: npm install chatnio-sdk
import { ChatNio } from 'chatnio-sdk';
 
const chatnio = new ChatNio({
  apiKey: process.env.CHATNIO_API_KEY,
  baseURL: 'https://api.chatnio.com/v1'
});
 
// Chat completion
const response = await chatnio.chat.completions.create({
  model: 'gpt-4',
  messages: [
    { role: 'user', content: 'Hello, world!' }
  ]
});
 
console.log(response.choices[0].message.content);
 
// Streaming
const stream = await chatnio.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Tell me a story' }],
  stream: true
});
 
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

This API reference provides comprehensive documentation for integrating with CoAI.Dev. For additional examples and use cases, see our GitHub repository or community examples.