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

# Chat Completion

> Generate text completions using AI models (OpenAI Compatible)

Generate natural language or code completions based on a list of messages. This endpoint is compatible with the OpenAI Chat Completions API.

### Headers

<ParamField header="x-api-key" type="string" required>
  Your Apollo AI API key. Alternatively, use `Authorization: Bearer <token>`.
</ParamField>

### Body Parameters

<ParamField body="messages" type="array" required>
  A list of messages comprising the conversation so far.

  <Expandable title="Message Object">
    <ResponseField name="role" type="string" required>
      The role of the messages author. One of `system`, `user`, `assistant`, or `tool`.
    </ResponseField>

    <ResponseField name="content" type="string | array" required>
      The contents of the message. Can be a string or an array of content parts (for multimodal inputs).
    </ResponseField>
  </Expandable>
</ParamField>

<ParamField body="model" type="string" required>
  The ID of the model to use (e.g., `gpt-oss-120b`, `llama3`).
  See [Models](/api-reference/models) for a full list.
</ParamField>

<ParamField body="stream" type="boolean">
  If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available.
</ParamField>

<ParamField body="max_tokens" type="integer">
  The maximum number of tokens to generate in the chat completion.
</ParamField>

<ParamField body="temperature" type="number">
  What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
</ParamField>

<ParamField body="tools" type="array">
  A list of tools the model may call. Currently, only functions are supported as a tool.
</ParamField>

### Response

<ResponseField name="id" type="string">
  A unique identifier for the chat completion.
</ResponseField>

<ResponseField name="choices" type="array">
  A list of chat completion choices.
</ResponseField>

<ResponseField name="created" type="integer">
  The Unix timestamp (in seconds) of when the chat completion was created.
</ResponseField>

<ResponseField name="model" type="string">
  The model used for the chat completion.
</ResponseField>

<ResponseField name="usage" type="object">
  Usage statistics for the completion request.
</ResponseField>

<RequestExample>
  ```bash Curl theme={null}
  curl https://apolloai.lol/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $APOLLO_API_KEY" \
    -d '{
      "model": "gpt-oss-120b",
      "messages": [
        {
          "role": "system",
          "content": "You are a helpful assistant."
        },
        {
          "role": "user",
          "content": "Hello!"
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import requests

  # For local development, use: http://localhost:3000/v1/chat/completions
  url = "https://apolloai.lol/v1/chat/completions"

  headers = {
      "Authorization": "Bearer <api_key>",
      "Content-Type": "application/json"
  }
  data = {
      "model": "gpt-oss-120b",
      "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
      ]
  }

  try:
      response = requests.post(url, headers=headers, json=data)
      response.raise_for_status() # Raise exception for 4xx/5xx status codes
      print(response.json())
  except requests.exceptions.HTTPError as err:
      print(f"HTTP Error: {err}")
      print(f"Response Body: {response.text}") # Print body to see non-JSON errors
  except Exception as err:
      print(f"Error: {err}")
  ```

  ```javascript JavaScript theme={null}
  // For local development, use: http://localhost:3000/v1/chat/completions
  const url = "https://apolloai.lol/v1/chat/completions";

  const headers = {
    "Authorization": "Bearer <api_key>",
    "Content-Type": "application/json"
  };
  const body = JSON.stringify({
    model: "gpt-oss-120b",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Hello!" }
    ]
  });

  fetch(url, { method: "POST", headers, body })
    .then(async response => {
      if (!response.ok) {
          const text = await response.text();
          throw new Error(`HTTP error! status: ${response.status}, body: ${text}`);
      }
      return response.json();
    })
    .then(console.log)
    .catch(console.error);
  ```

  ```go Go theme={null}
  package main

  import (
  	"bytes"
  	"fmt"
  	"net/http"
      "io/ioutil"
  )

  func main() {
      // For local development, use: http://localhost:3000/v1/chat/completions
  	url := "https://apolloai.lol/v1/chat/completions"
  	var jsonStr = []byte(`{
          "model": "gpt-oss-120b",
          "messages": [
              {"role": "system", "content": "You are a helpful assistant."},
              {"role": "user", "content": "Hello!"}
          ]
      }`)
  	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  	req.Header.Set("Authorization", "Bearer <api_key>")
  	req.Header.Set("Content-Type", "application/json")

  	client := &http.Client{}
  	resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()
      
      body, _ := ioutil.ReadAll(resp.Body)
      
      if resp.StatusCode >= 400 {
          fmt.Printf("Error (Status %d): %s\n", resp.StatusCode, string(body))
      } else {
          fmt.Println(string(body))
      }
  }
  ```

  ```java Java theme={null}
  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.http.HttpResponse.BodyHandlers;

  public class Main {
      public static void main(String[] args) throws Exception {
          // For local development, use: http://localhost:3000/v1/chat/completions
          String url = "https://apolloai.lol/v1/chat/completions";
          String json = "{"
              + "\"model\":\"gpt-oss-120b\","
              + "\"messages\":["
              + "{\"role\":\"system\",\"content\":\"You are a helpful assistant.\"},"
              + "{\"role\":\"user\",\"content\":\"Hello!\"}"
              + "]}";

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <api_key>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(json))
              .build();

          client.sendAsync(request, BodyHandlers.ofString())
              .thenAccept(response -> {
                  if (response.statusCode() >= 400) {
                      System.out.println("Error (Status " + response.statusCode() + "): " + response.body());
                  } else {
                      System.out.println(response.body());
                  }
              })
              .join();
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "id": "chatcmpl-123",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "gpt-oss-120b",
    "choices": [{
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello there, how may I assist you today?"
      },
      "finish_reason": "stop"
    }],
    "usage": {
      "prompt_tokens": 9,
      "completion_tokens": 12,
      "total_tokens": 21
    }
  }
  ```
</ResponseExample>
