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

# Chat Completions

<Callout icon="play" color="#0037ff" iconType="regular">
  [Test the Endpoint `POST /v1/chat/completions`](/apis/chat-completions)
</Callout>

The Chat Completions endpoint allows you to generate text responses using the distributed language models in the Fortytwo network. It supports both standard responses and streaming via Server-Sent Events (SSE).

## Create Chat Completion

Generate a response to a conversation using a specified network model's preset.

### Endpoint

```
POST https://api.fortytwo.network/v1/chat/completions
```

### Request Body

<ParamField path="model" type="string" required>
  ID of the model to use (from `/v1/models`).
</ParamField>

<ParamField path="messages" type="array" required>
  List of messages in the conversation.
</ParamField>

<ParamField path="stream" type="boolean" default="false">
  Enable Server-Sent Events streaming.
</ParamField>

#### Message Format

Each message in the `messages` array should have:

<ParamField path="role" type="string" required>
  One of: `system` | `user` | `assistant`.
</ParamField>

<ParamField path="content" type="string" required>
  The content of the message.
</ParamField>

## Response Modes

<Tabs>
  <Tab title="Standard Response Mode">
    In standard mode, the API returns a complete response once generation is finished.

    ### Example Request

    <CodeGroup>
      ```bash cURL theme={null}
      curl https://api.fortytwo.network/v1/chat/completions \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer YOUR_FORTYTWO_API_KEY" \
        -d '{
          "model": "fortytwo-xxxxxxxxxxxx",
          "messages": [
            {
              "role": "system",
              "content": "You are a helpful assistant."
            },
            {
              "role": "user",
              "content": "What is the Fortytwo network?"
            }
          ]
        }'
      ```

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

      api_key = "YOUR_FORTYTWO_API_KEY"
      url = "https://api.fortytwo.network/v1/chat/completions"

      headers = {
          "Content-Type": "application/json",
          "Authorization": f"Bearer {api_key}"
      }

      data = {
          "model": "fortytwo-xxxxxxxxxxxx",
          "messages": [
              {
                  "role": "system",
                  "content": "You are a helpful assistant."
              },
              {
                  "role": "user",
                  "content": "What is the Fortytwo network?"
              }
          ]
      }

      response = requests.post(url, headers=headers, json=data)
      result = response.json()
      print(result['choices'][0]['message']['content'])
      ```

      ```javascript JavaScript theme={null}
      const apiKey = 'YOUR_FORTYTWO_API_KEY';

      const response = await fetch('https://api.fortytwo.network/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: 'fortytwo-xxxxxxxxxxxx',
          messages: [
            {
              role: 'system',
              content: 'You are a helpful assistant.'
            },
            {
              role: 'user',
              content: 'What is the Fortytwo network?'
            }
          ]
        })
      });

      const data = await response.json();
      console.log(data.choices[0].message.content);
      ```
    </CodeGroup>

    ### Response Format

    ```json theme={null}
    {
      "id": "chatcmpl-abc123",
      "object": "chat.completion",
      "created": 1677858242,
      "model": "fortytwo-xxxxxxxxxxxx",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "The Fortytwo network is a decentralized AI protocol that leverages swarm intelligence..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 25,
        "completion_tokens": 50,
        "total_tokens": 75
      }
    }
    ```

    ### Response Fields

    <ParamField path="id" type="string">
      Unique identifier for the completion.
    </ParamField>

    <ParamField path="object" type="string">
      Always `chat.completion`.
    </ParamField>

    <ParamField path="created" type="integer">
      Unix timestamp of creation.
    </ParamField>

    <ParamField path="model" type="string">
      Model used for generation.
    </ParamField>

    <ParamField path="choices" type="array">
      List of completion choices.
    </ParamField>

    <ParamField path="usage" type="object">
      Token usage information.
    </ParamField>
  </Tab>

  <Tab title="Streaming Mode (SSE)">
    Enable streaming to receive tokens as they are generated, providing better user experience for real-time applications.

    ### Example Request

    <CodeGroup>
      ```bash cURL theme={null}
      curl https://api.fortytwo.network/v1/chat/completions \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer YOUR_FORTYTWO_API_KEY" \
        -d '{
          "model": "fortytwo-xxxxxxxxxxxx",
          "messages": [
            {
              "role": "user",
              "content": "Tell me a story"
            }
          ],
          "stream": true
        }'
      ```

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

      api_key = "YOUR_FORTYTWO_API_KEY"
      url = "https://api.fortytwo.network/v1/chat/completions"

      headers = {
          "Content-Type": "application/json",
          "Authorization": f"Bearer {api_key}"
      }

      data = {
          "model": "fortytwo-xxxxxxxxxxxx",
          "messages": [
              {"role": "user", "content": "Tell me a story"}
          ],
          "stream": True
      }

      response = requests.post(url, headers=headers, json=data, stream=True)

      # Process the stream
      for line in response.iter_lines():
          if line:
              line = line.decode('utf-8')
              if line.startswith('data: '):
                  data_str = line[6:]  # Remove 'data: ' prefix
                  if data_str == '[DONE]':
                      break
                  try:
                      chunk = json.loads(data_str)
                      content = chunk['choices'][0]['delta'].get('content', '')
                      if content:
                          print(content, end='', flush=True)
                  except json.JSONDecodeError:
                      pass
      ```

      ```javascript JavaScript theme={null}
      const apiKey = 'YOUR_FORTYTWO_API_KEY';

      const response = await fetch('https://api.fortytwo.network/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: 'fortytwo-xxxxxxxxxxxx',
          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');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data === '[DONE]') break;

            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices[0].delta.content;
              if (content) {
                process.stdout.write(content);
              }
            } catch (e) {
              // Skip invalid JSON
            }
          }
        }
      }
      ```
    </CodeGroup>

    ### Stream Response Format

    Each chunk in the stream follows this format:

    ```
    data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1677858242,"model":"fortytwo-xxxxxxxxxxxx","choices":[{"index":0,"delta":{"content":"Once"},"finish_reason":null}]}

    data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1677858242,"model":"fortytwo-xxxxxxxxxxxx","choices":[{"index":0,"delta":{"content":" upon"},"finish_reason":null}]}

    data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1677858242,"model":"fortytwo-xxxxxxxxxxxx","choices":[{"index":0,"delta":{"content":" a"},"finish_reason":null}]}

    data: [DONE]
    ```

    <Note>
      The stream ends with `data: [DONE]` to indicate completion.
    </Note>
  </Tab>
</Tabs>

## OpenAI SDK Integration

The Fortytwo API is fully compatible with the OpenAI Python and Node.js SDKs:

<CodeGroup>
  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="YOUR_FORTYTWO_API_KEY",
      base_url="https://api.fortytwo.network/v1"
  )

  # Standard completion
  response = client.chat.completions.create(
      model="fortytwo-xxxxxxxxxxxx",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
      ]
  )
  print(response.choices[0].message.content)

  # Streaming completion
  stream = client.chat.completions.create(
      model="fortytwo-xxxxxxxxxxxx",
      messages=[
          {"role": "user", "content": "Tell me a story"}
      ],
      stream=True
  )

  for chunk in stream:
      if chunk.choices[0].delta.content:
          print(chunk.choices[0].delta.content, end='')
  ```

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: 'YOUR_FORTYTWO_API_KEY',
    baseURL: 'https://api.fortytwo.network/v1'
  });

  // Standard completion
  const response = await client.chat.completions.create({
    model: 'fortytwo-xxxxxxxxxxxx',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'Hello!' }
    ]
  });
  console.log(response.choices[0].message.content);

  // Streaming completion
  const stream = await client.chat.completions.create({
    model: 'fortytwo-xxxxxxxxxxxx',
    messages: [
      { role: 'user', content: 'Tell me a story' }
    ],
    stream: true
  });

  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
  ```
</CodeGroup>

## Preview Rate Limiting

Chat completion requests are subject to rate limits while in Preview. See '[Preview Limits & Quotas](/docs/api-rate-limits)' for more details.

## Error Responses

Common error responses for chat completions can be found in '[Errors](/docs/api-errors#chat-completion-errors)'.

## Next Steps

* Learn about '[Preview Limits & Quotas](/docs/api-rate-limits)'.
* Review '[Authentication](/docs/api-authentication)' details.
