> ## Documentation Index
> Fetch the complete documentation index at: https://answerlabsinc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat Completion Endpoint

> The Chat Completions API is your gateway to conversational AI. This single endpoint provides access to all major AI models through a unified interface, eliminating the complexity of managing multiple provider integrations while preserving each model's unique capabilities.

## Create a Chat Completion

Endpoint: `POST /v1/chat`

This is the only endpoint you need to remember. Everything else is just parameters.

**Simple Request:**

```javascript theme={null}
curl -X POST https://connectapi.answerr.ai/functions/v1/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": "What are the benefits of renewable energy?"
      }
    ]
  }'
```

## Request Parameters

| **Parameter**        | **Type** | **Required** | **Description**                                |
| :------------------- | :------- | :----------- | :--------------------------------------------- |
| `model`              | string   | Yes          | Model to use: specific model name or "auto"    |
| `messages`           | array    | Yes          | Array of conversation messages                 |
| `temperature`        | number   | No           | Controls randomness (0.0 to 2.0, default: 0.7) |
| `max_tokens`         | number   | No           | Maximum tokens in response                     |
| `stream`             | boolean  | No           | Enable streaming responses (default: false)    |
| `top_p`              | number   | No           | Nucleus sampling parameter (0.0 to 1.0)        |
| `maxSources`         | number   | no           | Number of sources (default: 4)                 |
| `frequency_penalty`  | number   | No           | Reduce repetition (-2.0 to 2.0)                |
| `presence_penalty`   | number   | No           | Encourage new topics (-2.0 to 2.0)             |
| `compareModel`       | string   | No           | Model for side-by-side comparison              |
| `includeSources`     | boolean  | No           | Include web sources (default: false)           |
| `includeSuggestions` | boolean  | No           | Include follow-up suggestions (default: false) |

### **Message Format**

Messages follow the standard chat format with role-based conversation:

```javascript theme={null}
{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful AI assistant specialized in renewable energy."
    },
    {
      "role": "user", 
      "content": "What are the main types of renewable energy?"
    },
    {
      "role": "assistant",
      "content": "The main types of renewable energy include solar, wind, hydroelectric, geothermal, and biomass energy."
    },
    {
      "role": "user",
      "content": "Which is most cost-effective?"
    }
  ]
}
```

**Roles:**

* **system**: Sets the AI's behavior and context
* **user**: Messages from the human user
* **assistant**: Previous AI responses (for conversation context)

## **Response Format**

```javascript theme={null}
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Renewable energy offers several key benefits..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 15,
    "completion_tokens": 142,
    "total_tokens": 157
  },
  "sources": [
    {
      "title": "Renewable Energy Benefits - International Energy Agency",
      "url": "https://www.iea.org/reports/renewable-energy-benefits",
      "snippet": "Renewable energy technologies offer significant environmental and economic benefits..."
    }
  ],
  "suggestions": [
    "What are the current costs of different renewable energy technologies?",
    "How do renewable energy sources compare in terms of efficiency?",
    "What are the main challenges facing renewable energy adoption?"
  ]
}
```

## **Streaming Responses**

When stream: true, the response comes as a series of chunks, allowing for real-time display. Each chunk contains a piece of the generated response:

```javascript theme={null}
data: {"id":"chatcmpl-7QyrQcd6NhzFpQ9hGWVRZsxMSMJGS","object":"chat.completion.chunk","created":1685707297,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":"Quantum"},"finish_reason":null}]}

data: {"id":"chatcmpl-7QyrQcd6NhzFpQ9hGWVRZsxMSMJGS","object":"chat.completion.chunk","created":1685707297,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":" computing"},"finish_reason":null}]}

data: {"id":"chatcmpl-7QyrQcd6NhzFpQ9hGWVRZsxMSMJGS","object":"chat.completion.chunk","created":1685707297,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":" is"},"finish_reason":null}]}

// ... more chunks ...

data: [DONE]
```

Streaming transforms user experience by creating the illusion of the AI "thinking" in real-time. This reduces perceived latency and increases engagement - users stay connected to your application instead of waiting for a complete response. For applications like customer service bots or educational tools, this immediate feedback loop builds trust and enhances user satisfaction.

## **Context Management**

Your conversations don't exist in a vacuum. Our API intelligently manages conversation context across multiple exchanges, letting you build truly interactive experiences:

```javascript theme={null}
// Maintain conversation context across multiple requests
let conversationHistory = [
  {
    role: 'system',
    content: 'You are a helpful tutor teaching calculus to a college student.'
  }
];

async function askQuestion(question) {
  // Add user question to history
  conversationHistory.push({
    role: 'user',
    content: question
  });

  const response = await fetch('https://connectapi.answerr.ai/functions/v1/chat', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${YOUR_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: conversationHistory,
      temperature: 0.7
    })
  });

  const result = await response.json();
  const answer = result.choices[0].message.content;

  // Add assistant response to history
  conversationHistory.push({
    role: 'assistant',
    content: answer
  });

  return answer;
}

// Usage
await askQuestion("What is a derivative?");
await askQuestion("Can you give me an example with f(x) = x²?");
await askQuestion("How do I find the derivative of that?");
```

Our API maintains the thread of discussion, enabling:

* Natural follow-up questions without restating context
* Progressive exploration of complex topics
* Personalized experiences that build on previous interactions
* Long-running assistants that remember user preferences and history

For applications like customer support, educational tools, or virtual assistants, this continuity creates more engaging, efficient interactions that keep users coming back.

# Reliability and Performance

When integrating AI into mission-critical applications, reliability isn't optional. AnswerrAI's infrastructure is built for enterprise-grade dependability:

* Global edge network ensuring low latency worldwide
* Automatic failover between model providers during outages
* Intelligent request routing to optimize response times
* Horizontal scaling to handle traffic spikes without degradation

Our architecture allows you to build AI-powered applications that perform consistently even under heavy load, across geographic regions, and during provider outages.

# Error Handling

When something goes wrong, you'll know exactly why:

```javascript theme={null}
{
  "error": {
    "type": "invalid_request_error",
    "code": "missing_required_parameter",
    "message": "Missing required parameter: 'messages'",
    "param": "messages"
  }
}
```

Common status codes:

| **Status** | **Error Code**        | **Description**            | **Solution**                                 |
| :--------- | :-------------------- | :------------------------- | :------------------------------------------- |
| 400        | `invalid_request`     | Malformed request          | Check request format and required parameters |
| 401        | `invalid_api_key`     | Invalid or missing API key | Verify your API key is correct               |
| 403        | `insufficient_quota`  | Quota exceeded             | Upgrade your plan or wait for quota reset    |
| 429        | `rate_limit_exceeded` | Too many requests          | Implement exponential backoff                |
| 500        | `internal_error`      | Server error               | Retry the request after a delay              |

# Practical Applications

The simplicity and power of our Chat Completion API make it perfect for a wide range of applications:

## Customer Experience Enhancement

Build intelligent chatbots that understand context, answer questions accurately, and maintain a conversational flow that feels natural. With the ability to switch between models, you can use cost-effective options for simple queries and premium models for complex support cases.

## Content Creation and Editing

Create tools that help writers generate ideas, improve prose, or translate content into multiple languages. The streaming capability allows for real-time collaborative editing between humans and AI.

## Educational Tools

Develop personalized tutoring systems that adapt to each student's learning style and pace. Context management allows the AI to build on previous lessons, creating a cohesive learning journey.

## Internal Knowledge Management

Transform your company documentation into an interactive assistant that employees can query conversationally, making institutional knowledge more accessible and useful.

# AI Security and Compliance

We understand that data security is paramount when working with AI. Our platform is built with security-first principles:

* **Data isolation:** Your API calls and data never influence model training
* **SOC 2 Type II compliance:** Independent verification of our security controls
* **End-to-end encryption:** Data is encrypted both in transit and at rest
* **Configurable data retention:** Control how long your data is stored
* **Regional deployment options:** Keep data in your preferred jurisdiction
