# chatapi.ai-now.space API Documentation

This document provides a comprehensive overview of the chatapi.ai-now.space API, detailing its functionalities, endpoints, and usage instructions.

## Overview

chatapi.ai-now.space is a proxy API that provides access to various large language models (LLMs) for chat completions and other AI-related tasks. It offers a unified interface for interacting with different models, simplifying the development process for users.

## Authentication

All API requests require an API key for authentication. To obtain an API key, please contact [email protected].

The API key should be included in the `Authorization` header of each request using the `Bearer` scheme:

```
Authorization: Bearer YOUR_API_KEY
```

## Endpoints

### `/models`

**GET** - Retrieves a list of available models.

**Response:**

```json
{
  "data": [
    {
      "id": 1,
      "name": "Model A",
      "contextWindow": 2048,
      "inputCostPer1kTokens": 0.001,
      "outputCostPer1kTokens": 0.002,
      "quality": "high",
      "medianPrice": 0.05,
      "outputTokensPerSecond": 10,
      "latencyToFirstChunk": 500,
      "average": 85,
      "multiChoiceQs": 90,
      "reasoning": 80,
      "pythonCoding": 75,
      "futureCapabilities": 70,
      "gradeSchoolMath": 95,
      "mathProblems": 80,
      "arenaScore": 75,
      "confidenceInterval": 90,
      "votes": 100,
      "organization": "Organization A",
      "license": "MIT",
      "knowledgeCutoff": "2023-01-01",
      "working": true
    },
    // ... other models
  ]
}
```
### [Full list of models is available here](https://chatapi.ai-now.space/listmodels)

**Example:**

```bash
curl -H "Authorization: Bearer YOUR_API_KEY" https://chatapi.ai-now.space/models
```

### `/chat/completions`

**POST** - Generates chat completions using the specified model.

**Request Body:**

```json
{
  "model": "Model A",
  "messages": [
    { "role": "user", "content": "What is the capital of France?" }
  ],
  "stream": false, // Optional, defaults to false
  // ... other parameters (see OpenAI's Chat Completion API documentation)
}
```

**Response (Non-Streaming):**

```json
{
  "id": "chatcmpl-XXXXXXXXXXXXXXXXX",
  "object": "chat.completion",
  "created": 1678886384,
  "model": "Model A",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop"
    }
  ],
  "input_tokens": 7,
  "output_tokens": 6,
  "input_tokens_cost": 0.000007,
  "output_tokens_cost": 0.000012,
  "total_tokens_cost": 0.000019,
  "total_time_taken": 123,
  "tokens_per_second": 0.1057
}
```

**Response (Streaming):**

```text
data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": "The"}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": " capital"}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": " of"}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": " France"}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": " is"}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {"content": " Paris."}, "finish_reason": null}]}

data: {"id": "chatcmpl-XXXXXXXXXXXXXXXXX", "object": "chat.completion.chunk", "created": 1678886384, "model": "Model A", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}

data: {"input_tokens": 7, "output_tokens": 6, "input_tokens_cost": 0.000007, "output_tokens_cost": 0.000012, "total_tokens_cost": 0.000019, "total_time_taken": 123, "tokens_per_second": 0.1057}

data: [DONE]
```

**Example (Non-Streaming):**

```bash
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
  "model": "Model A",
  "messages": [
    { "role": "user", "content": "What is the capital of France?" }
  ]
}' https://chatapi.ai-now.space/chat/completions
```

**Example (Streaming):**

```bash
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
  "model": "Model A",
  "messages": [
    { "role": "user", "content": "What is the capital of France?" }
  ],
  "stream": true
}' https://chatapi.ai-now.space/chat/completions
```

### `/tokens`

**POST** - Counts the number of tokens in a given text.

**Request Body:**

```json
{
  "text": "This is a test sentence."
}
```

**Response:**

```json
{
  "tokens": 6
}
```

**Example:**

```bash
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
  "text": "This is a test sentence."
}' https://chatapi.ai-now.space/tokens
```

### `/credits`

**GET** - Retrieves the remaining credits for the API key.

**Response:**

```json
{
  "credits": 1000
}
```

**Example:**

```bash
curl -H "Authorization: Bearer YOUR_API_KEY" https://chatapi.ai-now.space/credits
```

### `/moderate`

**POST** - Moderates the given input text using OpenAI's moderation API.

**Request Body:**

```json
{
  "input": "This is a test sentence."
}
```

**Response:**

```json
{
  "id": "modr-XXXXXXXXXXXXXXXXX",
  "model": "text-moderation-latest",
  "results": [
    {
      "categories": {
        "hate": false,
        "hate/threatening": false,
        "self-harm": false,
        "sexual": false,
        "sexual/minors": false,
        "violence": false,
        "violence/graphic": false
      },
      "category_scores": {
        "hate": 0.0000000000000000,
        "hate/threatening": 0.0000000000000000,
        "self-harm": 0.0000000000000000,
        "sexual": 0.0000000000000000,
        "sexual/minors": 0.0000000000000000,
        "violence": 0.0000000000000000,
        "violence/graphic": 0.0000000000000000
      },
      "flagged": false
    }
  ]
}
```

**Example:**

```bash
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
  "input": "This is a test sentence."
}' https://chatapi.ai-now.space/moderate
```

## Rate Limiting

The API is rate limited to 100 requests per minute per API key. Exceeding this limit will result in a `429 Too Many Requests` error.

## Error Handling

The API uses standard HTTP status codes to indicate the success or failure of a request. Common error codes include:

* **400 Bad Request:** The request was malformed or invalid.
* **401 Unauthorized:** The API key was missing or invalid.
* **429 Too Many Requests:** The rate limit has been exceeded.
* **500 Internal Server Error:** An unexpected error occurred on the server.

## Contact

For any questions or issues, please contact [email protected].



## Usage Examples

### Python

#### Non-Streaming Example

```python
import requests

headers = {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
}

data = {
    'model': 'GPT-4 Turbo',
    'messages': [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'What is the capital of France?'}
    ]
}

response = requests.post('https://chatapi.ai-now.space/chat/completions', headers=headers, json=data)

print(response.json())
```

#### Streaming Example

```python
import requests

headers = {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
}

data = {
    'model': 'Claude 3.5 Sonnet',
    'messages': [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Write a short poem about the sea.'}
    ],
    'stream': True
}

response = requests.post('https://chatapi.ai-now.space/chat/completions', headers=headers, json=data, stream=True)

for line in response.iter_lines():
    if line:
        decoded_line = line.decode('utf-8')
        if decoded_line.startswith('data: '):
            print(decoded_line[6:])
```

### C#

#### Non-Streaming Example

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class ChatCompletionExample
{
    public static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var requestBody = new
            {
                model = "GPT-4 Turbo",
                messages = new[]
                {
                    new { role = "system", content = "You are a helpful assistant." },
                    new { role = "user", content = "What is the capital of France?" }
                }
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync("https://chatapi.ai-now.space/chat/completions", content);
            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
        }
    }
}
```

#### Streaming Example

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class ChatCompletionStreamingExample
{
    public static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var requestBody = new
            {
                model = "Claude 3.5 Sonnet",
                messages = new[]
                {
                    new { role = "system", content = "You are a helpful assistant." },
                    new { role = "user", content = "Write a short poem about the sea." }
                },
                stream = true
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync("https://chatapi.ai-now.space/chat/completions", content);

            using (var stream = await response.Content.ReadAsStreamAsync())
            using (var reader = new System.IO.StreamReader(stream))
            {
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    if (line.StartsWith("data: "))
                    {
                        Console.WriteLine(line.Substring(6));
                    }
                }
            }
        }
    }
}
```

### Node.js

#### Non-Streaming Example

```javascript
const axios = require('axios');

const headers = {
  'Authorization': 'Bearer YOUR_API_KEY',
  'Content-Type': 'application/json'
};

const data = {
  model: 'GPT-4 Turbo',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What is the capital of France?' }
  ]
};

axios.post('https://chatapi.ai-now.space/chat/completions', data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
```

#### Streaming Example

```javascript
const axios = require('axios');

const headers = {
  'Authorization': 'Bearer YOUR_API_KEY',
  'Content-Type': 'application/json'
};

const data = {
  model: 'Claude 3.5 Sonnet',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Write a short poem about the sea.' }
  ],
  stream: true
};

axios.post('https://chatapi.ai-now.space/chat/completions', data, { headers, responseType: 'stream' })
  .then(response => {
    response.data.on('data', (chunk) => {
      const lines = chunk.toString().split('\n');
      lines.forEach(line => {
        if (line.startsWith('data: ')) {
          console.log(line.substring(6));
        }
      });
    });
  })
  .catch(error => {
    console.error(error);
  });
```

**Remember to replace `YOUR_API_KEY` with your actual API key.**
```
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9