> For clean Markdown of any page, append `.md` to the page URL.
> Documentation index: https://you.com/docs/llms.txt (section indexes: append `/llms.txt` to any section URL).
> Search these docs: Docs MCP at https://you.com/docs/_mcp/server (`searchDocs`, no API key).
> Call live You.com APIs: Product MCP at https://api.you.com/mcp (keyless `?profile=free` exposes `you-search` and `you-discover`. Research and finance use `/mcp/research`, `/mcp/finance`, or `?tools=` on `/mcp`). To pick an API or integration path, call `you-discover` on that server instead of guessing.
> OpenAPI: https://you.com/docs/openapi.json—auth header `X-API-Key`, env `YDC_API_KEY`.

# Create Chat Completion

POST https://api.you.com/v1/chat/completions
Content-Type: application/json

OpenAI-compatible Chat Completions. Send a `model` from `GET /v1/models` and a list of `messages`. Add a `web_search` or `web_extract` tool to let the router run You.com web searches and page fetches for the model. Parameters are forwarded to the model, and models differ in what they accept.

Reference: https://you.com/docs/api-reference/inference-router/create-chat-completion

## Authentication

- `Authorization` header (bearer token, required) — Your You.com API key, sent as `Authorization: Bearer <key>`. Get a key in the ["Get your API key" section of the documentation](https://you.com/docs/quickstart#get-your-api-key).

## Request

### Headers

- `x-request-id` (string, optional) — A client-chosen request ID for tracing. The router generates one when the header is absent or invalid, and returns it in the response.
- `x-session-id` (string, optional) — A conversation identifier of up to 256 characters. Requests that share a session ID are kept together where possible.

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — A model ID from `GET /v1/models`.
- `messages` (list of ChatMessage, required) — The conversation so far, in OpenAI Chat Completions format.
- `stream` (boolean, optional) — Stream the response as server-sent events.
- `stream_options` (ChatCompletionRequestStreamOptions, optional) — Options for streamed responses, such as `include_usage`.
- `temperature` (double, optional) — Sampling temperature. When omitted, the router applies the model vendor's reference value, where one is configured.
- `top_p` (double, optional) — Nucleus sampling probability. When omitted, the router applies the model vendor's reference value, where one is configured.
- `reasoning_effort` (string, optional) — How much reasoning the model applies, for models that support it. When omitted, the router applies the model vendor's reference value, where one is configured.
- `max_tokens` (integer, optional) — Maximum tokens to generate. Per-model limits are published as `max_tokens` in `GET /v1/models`.
- `max_completion_tokens` (integer, optional) — Upper bound on generated tokens, including reasoning tokens.
- `stop` (ChatCompletionRequestStop, optional) — Sequences where the model stops generating.
- `seed` (integer, optional) — A seed for best-effort deterministic sampling.
- `frequency_penalty` (double, optional) — Penalty for tokens by their frequency so far.
- `presence_penalty` (double, optional) — Penalty for tokens that have already appeared.
- `logit_bias` (map from string to double, optional) — Token ID to bias value.
- `logprobs` (boolean, optional) — Return log probabilities of output tokens.
- `top_logprobs` (integer, optional) — Number of most likely tokens to return at each position.
- `n` (integer, optional) — Number of completions to generate.
- `response_format` (map from string to any, optional) — Output format, such as `{"type": "json_object"}` or a `json_schema` definition.
- `tools` (list of ChatCompletionRequestToolsItems, optional) — Tools the model may call. Use `function` tools that your code executes, or the You.com web tools described below.
- `tool_choice` (ChatCompletionRequestToolChoice, optional) — Controls which tool the model calls: `none`, `auto`, `required`, or an object naming a function.
- `parallel_tool_calls` (boolean, optional) — Allow the model to call several tools in one turn. Defaults to `true` when a web tool is declared.
- `user` (string, optional) — A stable identifier for your end user.
- `metadata` (map from string to string, optional) — Key-value pairs attached to the request.

## Response

### 200

A chat completion, or a stream of `chat.completion.chunk` server-sent events when `stream` is `true`.

- `id` (string, optional)
- `object` (enum, optional)
  - Allowed values: `chat.completion`
- `created` (integer, optional)
- `model` (string, optional)
- `choices` (list of ChatCompletionResponseChoicesItems, optional)
- `usage` (ChatUsage, optional) — Token counts, the same in streamed and non-streamed responses. The object has no cost fields.
- `web_results` (WebResults, optional) — Every search and page fetch the router ran for the request. Present only when a web tool ran. Citation numbers are shared across searches and extractions.

## Errors

### 400 Bad Request Error

The request body or a tool definition is invalid.

- `error` (ErrorResponseError, required)

### 401 Unauthorized Error

The API key is missing or invalid.

- `error` (ErrorResponseError, required)

### 403 Forbidden Error

The API key has no access to the requested model or service.

- `error` (ErrorResponseError, required)

### 429 Too Many Requests Error

The request exceeded a rate limit.

- `error` (ErrorResponseError, required)

### 503 Service Unavailable Error

The router or the model is unavailable.

- `error` (ErrorResponseError, required)

## Types

### ChatMessage

- `role` (enum, required)
  - Allowed values: `system`, `developer`, `user`, `assistant`, `tool`
- `content` (ChatMessageContent, optional) — Message text, or an array of content parts.
- `name` (string, optional)
- `tool_calls` (list of map from string to any, optional) — Tool calls the assistant made in an earlier turn.
- `tool_call_id` (string, optional) — The tool call a `tool` message responds to.

### ChatCompletionRequestStreamOptions

Options for streamed responses, such as `include_usage`.

- `include_usage` (boolean, optional)

### ChatCompletionRequestStop

Sequences where the model stops generating.

- string
- list of string

### ChatCompletionRequestToolsItems

- FunctionTool: FunctionTool
- WebSearchTool: WebSearchTool
- WebExtractTool: WebExtractTool
- ClientWebSearchTool: ClientWebSearchTool

### ChatCompletionRequestToolChoice

Controls which tool the model calls: `none`, `auto`, `required`, or an object naming a function.

- string
- map from string to any

### ChatCompletionResponseChoicesItems

- `index` (integer, optional)
- `message` (ChatCompletionResponseChoicesItemsMessage, optional)
- `finish_reason` (string, optional)

### ChatUsage

Token counts, the same in streamed and non-streamed responses. The object has no cost fields.

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)
- `prompt_tokens_details` (ChatUsagePromptTokensDetails, optional)
- `completion_tokens_details` (ChatUsageCompletionTokensDetails, optional)

### WebResults

Every search and page fetch the router ran for the request. Present only when a web tool ran. Citation numbers are shared across searches and extractions.

- `searches` (list of WebResultsSearchesItems, optional)
- `extracts` (list of WebResultsExtractsItems, optional)

### ErrorResponseError

- `message` (string, required) — A description of the error.
- `type` (string, optional) — The error type.
- `param` (string, optional, nullable) — The request parameter that caused the error, when known.
- `code` (string, optional, nullable) — The error code.

### ChatMessageContent

Message text, or an array of content parts.

- string
- list of map from string to any

### FunctionTool

- `type` (enum, required)
  - Allowed values: `function`
- `function` (FunctionToolFunction, required)

### WebSearchTool

The router runs web searches for the model against the You.com Web Search API. All fields except `type` are optional. A value set here overrides the same parameter when the model supplies one.

- `type` (enum, required)
  - Allowed values: `web_search`
- `max_search_rounds` (integer, optional, default: 30) — Maximum search rounds. Each round is one model call plus every search the model issued in it. At the limit, the model must answer.
- `count` (integer, optional) — Results per search. The router returns 10 when unset and caps the value at 20.
- `offset` (integer, optional) — Page offset into the results.
- `freshness` (string, optional) — Recency filter: `day`, `week`, `month`, `year`, or a date range in `YYYY-MM-DDtoYYYY-MM-DD` format.
- `country` (string, optional) — Two-letter ISO 3166-1 alpha-2 country code, such as `US`.
- `language` (string, optional) — BCP 47 language tag, such as `en` or `en-US`.
- `safesearch` (enum, optional) — Explicit-content filter level.
  - Allowed values: `off`, `moderate`, `strict`
- `exclude_domains` (list of string, optional) — Domains to leave out of results.
- `boost_domains` (list of string, optional) — Domains to rank higher in results.
- `crawl_timeout` (integer, optional) — Seconds to wait for page content, from 1 to 60.

### WebExtractTool

The router fetches page content for the model with the You.com Contents API. The model chooses the URLs, up to 5 per call.

- `type` (enum, required)
  - Allowed values: `web_extract`
- `formats` (list of enum, optional) — Content formats to return. Defaults to `markdown`.
  - Allowed values: `markdown`, `html`, `metadata`
- `crawl_timeout` (integer, optional) — Seconds to wait for page content, from 1 to 60.
- `max_age` (integer, optional) — Maximum age of cached content in seconds. `0` ignores the cache.

### ClientWebSearchTool

Declares a `web_search` function to the model. The router does not run it. The model's call comes back in `tool_calls` for your code to execute.

- `type` (enum, required)
  - Allowed values: `client:web_search`

### ChatCompletionResponseChoicesItemsMessage

- `role` (enum, optional)
  - Allowed values: `assistant`
- `content` (string, optional, nullable)
- `refusal` (string, optional, nullable) — The refusal message, when the model refused the request.
- `reasoning_content` (string, optional, nullable) — The model's reasoning text. Present for reasoning models.
- `reasoning_details` (list of map from string to any, optional) — Structured reasoning, present only when it carries more than `reasoning_content`.
- `thinking_blocks` (list of map from string to any, optional) — Claude thinking blocks.
- `tool_calls` (list of map from string to any, optional)

### ChatUsagePromptTokensDetails

- `cached_tokens` (integer, optional) — Prompt tokens read from a cache.
- `text_tokens` (integer, optional) — Prompt tokens that are neither cached nor audio or image tokens.

### ChatUsageCompletionTokensDetails

- `reasoning_tokens` (integer, optional)
- `text_tokens` (integer, optional) — Completion tokens that are not reasoning, audio, or image tokens.

### WebResultsSearchesItems

- `query` (string, optional)
- `results` (list of WebResultsSearchesItemsResultsItems, optional)

### WebResultsExtractsItems

- `urls` (list of string, optional)
- `pages` (list of WebResultsExtractsItemsPagesItems, optional)

### FunctionToolFunction

- `name` (string, required)
- `description` (string, optional)
- `parameters` (map from string to any, optional) — A JSON Schema for the function arguments.

### WebResultsSearchesItemsResultsItems

- `citation` (integer, optional)
- `title` (string, optional)
- `url` (string, optional)
- `snippet` (string, optional)
- `published_at` (string, optional)

### WebResultsExtractsItemsPagesItems

- `citation` (integer, optional)
- `title` (string, optional)
- `url` (string, optional)
- `content` (string, optional)
- `content_format` (string, optional)

## Examples

**Request**

```json
{
  "model": "string",
  "messages": [
    {
      "role": "system"
    }
  ]
}
```

**Response**

```json
{
  "id": "string",
  "object": "chat.completion",
  "created": 1,
  "model": "string",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "assistant",
        "content": "string",
        "refusal": "string",
        "reasoning_content": "string",
        "reasoning_details": [
          {}
        ],
        "thinking_blocks": [
          {}
        ],
        "tool_calls": [
          {}
        ]
      },
      "finish_reason": "string"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1,
    "prompt_tokens_details": {
      "cached_tokens": 1,
      "text_tokens": 1
    },
    "completion_tokens_details": {
      "reasoning_tokens": 1,
      "text_tokens": 1
    }
  },
  "web_results": {
    "searches": [
      {
        "query": "string",
        "results": [
          {
            "citation": 1,
            "title": "string",
            "url": "string",
            "snippet": "string",
            "published_at": "string"
          }
        ]
      }
    ],
    "extracts": [
      {
        "urls": [
          "string"
        ],
        "pages": [
          {
            "citation": 1,
            "title": "string",
            "url": "string",
            "content": "string",
            "content_format": "string"
          }
        ]
      }
    ]
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.you.com/v1/chat/completions"

payload = {
    "model": "string",
    "messages": [{ "role": "system" }]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.you.com/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"string","messages":[{"role":"system"}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.you.com/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"string\",\n  \"messages\": [\n    {\n      \"role\": \"system\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.you.com/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"string\",\n  \"messages\": [\n    {\n      \"role\": \"system\"\n    }\n  ]\n}")
  .asString();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.you.com/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"string\",\n  \"messages\": [\n    {\n      \"role\": \"system\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "string",
  "messages": [["role": "system"]]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.you.com/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```