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

# Create a chat completion

> Generate an OpenAI-compatible chat completion with messages, streaming, tools, vision, and JSON output.

Creates a model response from an ordered list of conversation messages. This endpoint is the broadest compatibility choice for existing OpenAI SDK integrations.

## Endpoint

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST https://api.yelu.ai/v1/chat/completions
```

## Headers

<ParamField header="Authorization" type="string" required>
  API key using the format `Bearer $YELU_API_KEY`.
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`.
</ParamField>

## Request body

<ParamField body="model" type="string" required>
  A model ID returned by [`GET /v1/models`](/en/api-reference/models).
</ParamField>

<ParamField body="messages" type="array" required>
  Ordered conversation messages. Each item has a `role` (`system`, `developer`, `user`, `assistant`, or `tool`, as supported by the model) and `content`. Content can be text or a multimodal content array.
</ParamField>

<ParamField body="temperature" type="number" default="1">
  Sampling temperature from `0` to `2`. Prefer changing either `temperature` or `top_p`, not both.
</ParamField>

<ParamField body="top_p" type="number" default="1">
  Nucleus sampling probability from `0` to `1`.
</ParamField>

<ParamField body="max_completion_tokens" type="integer">
  Maximum tokens the model may generate. Support and accounting of reasoning tokens are model-specific.
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  When `true`, returns Server-Sent Events with incremental completion chunks.
</ParamField>

<ParamField body="stream_options" type="object">
  Streaming options. Set `include_usage` to `true` to request a final usage chunk when supported.
</ParamField>

<ParamField body="stop" type="string | string[]">
  Up to the model's supported number of sequences that stop generation.
</ParamField>

<ParamField body="presence_penalty" type="number" default="0">
  Value from `-2` to `2` that adjusts reuse based on whether tokens appeared.
</ParamField>

<ParamField body="frequency_penalty" type="number" default="0">
  Value from `-2` to `2` that adjusts reuse based on token frequency.
</ParamField>

<ParamField body="tools" type="array">
  Function definitions the model may call. Validate all generated arguments before execution.
</ParamField>

<ParamField body="tool_choice" type="string | object">
  Use `none`, `auto`, `required`, or a named function choice when supported.
</ParamField>

<ParamField body="response_format" type="object">
  Requests JSON object or JSON schema output on compatible models. See [Structured output](/en/guides/structured-output).
</ParamField>

<ParamField body="reasoning_effort" type="string">
  `low`, `medium`, or `high` on compatible reasoning models.
</ParamField>

<ParamField body="user" type="string">
  A stable, non-sensitive identifier for your end user. Do not send direct personal information.
</ParamField>

## Response

<ResponseField name="id" type="string" required>
  Unique completion identifier.
</ResponseField>

<ResponseField name="object" type="string" required>
  `chat.completion` for non-streaming requests; streaming chunks use `chat.completion.chunk`.
</ResponseField>

<ResponseField name="created" type="integer" required>
  Unix timestamp for creation.
</ResponseField>

<ResponseField name="model" type="string" required>
  Model that produced the completion.
</ResponseField>

<ResponseField name="choices" type="array" required>
  Generated alternatives. Each choice contains `index`, an assistant `message`, and `finish_reason` such as `stop`, `length`, `tool_calls`, or `content_filter`.
</ResponseField>

<ResponseField name="usage" type="object">
  Token accounting, commonly `prompt_tokens`, `completion_tokens`, and `total_tokens`. Additional fields can appear for supported models.
</ResponseField>

<RequestExample>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl https://api.yelu.ai/v1/chat/completions \
    -H "Authorization: Bearer $YELU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-4o-mini",
      "messages": [
        {"role": "system", "content": "You are a concise technical editor."},
        {"role": "user", "content": "Rewrite: APIs should fail in predictable ways."}
      ],
      "temperature": 0.2,
      "max_completion_tokens": 80
    }'
  ```

  ```javascript JavaScript (Fetch) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch('https://api.yelu.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.YELU_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'system', content: 'You are a concise technical editor.' },
        { role: 'user', content: 'Rewrite: APIs should fail in predictable ways.' },
      ],
      temperature: 0.2,
      max_completion_tokens: 80,
    }),
  });

  if (!response.ok) throw new Error(await response.text());
  console.log((await response.json()).choices[0].message.content);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import os
  import requests

  response = requests.post(
      "https://api.yelu.ai/v1/chat/completions",
      headers={"Authorization": f"Bearer {os.environ['YELU_API_KEY']}"},
      json={
          "model": "gpt-4o-mini",
          "messages": [
              {"role": "system", "content": "You are a concise technical editor."},
              {"role": "user", "content": "Rewrite: APIs should fail in predictable ways."},
          ],
          "temperature": 0.2,
          "max_completion_tokens": 80,
      },
      timeout=60,
  )
  response.raise_for_status()
  print(response.json()["choices"][0]["message"]["content"])
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "id": "chatcmpl_01JYELU8D1",
    "object": "chat.completion",
    "created": 1783900800,
    "model": "gpt-4o-mini",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "APIs should return consistent, well-defined errors."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 29,
      "completion_tokens": 10,
      "total_tokens": 39
    }
  }
  ```

  ```json 400 theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "error": {
      "message": "The model field is required.",
      "type": "invalid_request_error",
      "param": "model",
      "code": "missing_required_parameter"
    }
  }
  ```
</ResponseExample>

## Error codes

| Status      | Code or type            | Meaning                                                      |
| ----------- | ----------------------- | ------------------------------------------------------------ |
| `400`       | `invalid_request_error` | Invalid messages, fields, values, JSON, or model capability. |
| `401`       | `authentication_error`  | Missing or invalid API key.                                  |
| `403`       | `permission_denied`     | The key cannot use the requested model or operation.         |
| `404`       | `model_not_found`       | Model ID is unavailable; refresh the model list.             |
| `413`       | `request_too_large`     | Context or request body is too large.                        |
| `429`       | `rate_limit_error`      | Account or group request limit reached.                      |
| `500`–`504` | `server_error`          | Temporary gateway or upstream failure.                       |

<CardGroup cols={2}>
  <Card title="Streaming" icon="activity" href="/en/guides/streaming">Parse SSE completion chunks safely.</Card>
  <Card title="Function calling" icon="wrench" href="/en/guides/function-calling">Connect chat models to application tools.</Card>
</CardGroup>
