> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nemo/guardrails/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.nvidia.com/nemo/guardrails/_mcp/server.

# Create Chat Completion

POST http://localhost:8000/v1/chat/completions
Content-Type: application/json

Generate a chat completion with guardrails applied.

The request shape is compatible with the OpenAI Chat Completions API and
accepts Guardrails-specific options in the `guardrails` object.


Reference: https://docs.nvidia.com/nemo/guardrails/nemo/guardrails/reference/guardrails-api-server/chat-completions/chat-completions

## Request

### Body (application/json)

- `model` (string, required) — LLM model to use for the completion.
- `messages` (list of object, optional) — Chat messages in the current conversation.
  - `role` (string, required) — Message role, such as `system`, `user`, `assistant`, `tool`, or `context`.
  - `content` (string or list of map from string to any, required) — Message content.
- `stream` (boolean, optional, default: false) — Return partial message deltas as server-sent events.
- `max_tokens` (integer, optional) — Maximum number of tokens to generate.
- `temperature` (double, optional) — Sampling temperature.
- `top_p` (double, optional) — Top-p sampling parameter.
- `stop` (string or list of string, optional) — Stop sequence or sequences.
- `presence_penalty` (double, optional) — Presence penalty parameter.
- `frequency_penalty` (double, optional) — Frequency penalty parameter.
- `function_call` (map from string to any, optional) — Function call parameter.
- `logit_bias` (map from string to any, optional) — Logit bias parameter.
- `logprobs` (boolean, optional) — Log probabilities parameter.
- `guardrails` (object, optional) — Guardrails-specific request options.
  - `config_id` (string, optional) — Guardrails configuration ID to use. Mutually exclusive with `config_ids`.
  - `config_ids` (list of string, optional) — List of configuration IDs to combine. Mutually exclusive with `config_id`.
  - `thread_id` (string, optional) — Existing thread ID for Colang 1.0 conversation persistence.
  - `context` (map from string to any, optional) — Additional context data for the conversation.
  - `options` (object, optional)
    - `rails` (object, optional)
      - `input` (boolean or list of string, optional) — Enable, disable, or select named rails.
      - `output` (boolean or list of string, optional) — Enable, disable, or select named rails.
      - `retrieval` (boolean or list of string, optional) — Enable, disable, or select named rails.
      - `dialog` (boolean, optional, default: true) — Enable dialog rails.
      - `tool_input` (boolean or list of string, optional) — Enable, disable, or select named rails.
      - `tool_output` (boolean or list of string, optional) — Enable, disable, or select named rails.
    - `llm_params` (map from string to any, optional) — Additional parameters to pass to the LLM call.
    - `llm_output` (boolean, optional, default: false) — Include custom LLM output in the response.
    - `output_vars` (boolean or list of string, optional) — Context variables to return.
    - `log` (object, optional)
      - `activated_rails` (boolean, optional, default: false) — Include information about activated rails.
      - `llm_calls` (boolean, optional, default: false) — Include details about LLM calls.
      - `internal_events` (boolean, optional, default: false) — Include internal generated events.
      - `colang_history` (boolean, optional, default: false) — Include conversation history in Colang format.
  - `state` (map from string to any, optional) — Colang 1.0 transcript state for continuing a previous interaction.

## Response

### 200

Chat completion response or server-sent event stream.

- `id` (string, optional)
- `object` (string, optional)
- `created` (integer, optional)
- `model` (string, optional)
- `choices` (list of object, optional)
  - `index` (integer, optional)
  - `message` (object, optional)
    - `role` (string, required) — Message role, such as `system`, `user`, `assistant`, `tool`, or `context`.
    - `content` (string or list of map from string to any, required) — Message content.
  - `finish_reason` (string, optional, nullable)
- `guardrails` (object, optional)
  - `config_id` (string, optional, nullable)
  - `state` (map from string to any, optional, nullable)
  - `llm_output` (map from string to any, optional, nullable)
  - `output_data` (map from string to any, optional, nullable)
  - `log` (map from string to any, optional, nullable)

## Examples

### Basic guarded completion

**Request**

```json
{
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of France?"
    }
  ],
  "guardrails": {
    "config_id": "content_safety"
  }
}
```

**Response**

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1709424000,
  "model": "meta/llama-3.1-8b-instruct",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Paris is the capital of France."
      },
      "finish_reason": "stop"
    }
  ],
  "guardrails": {
    "config_id": "content_safety",
    "state": null,
    "llm_output": null,
    "output_data": null,
    "log": null
  }
}
```

**SDK Code**

```python Basic guarded completion
import requests

url = "http://localhost:8000/v1/chat/completions"

payload = {
    "model": "meta/llama-3.1-8b-instruct",
    "messages": [
        {
            "role": "user",
            "content": "What is the capital of France?"
        }
    ],
    "guardrails": { "config_id": "content_safety" }
}
headers = {"Content-Type": "application/json"}

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

print(response.json())
```

```javascript Basic guarded completion
const url = 'http://localhost:8000/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"model":"meta/llama-3.1-8b-instruct","messages":[{"role":"user","content":"What is the capital of France?"}],"guardrails":{"config_id":"content_safety"}}'
};

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

```go Basic guarded completion
package main

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

func main() {

	url := "http://localhost:8000/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ],\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}")

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

	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))

}
```

```ruby Basic guarded completion
require 'uri'
require 'net/http'

url = URI("http://localhost:8000/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ],\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java Basic guarded completion
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("http://localhost:8000/v1/chat/completions")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ],\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}")
  .asString();
```

```php Basic guarded completion
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'http://localhost:8000/v1/chat/completions', [
  'body' => '{
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of France?"
    }
  ],
  "guardrails": {
    "config_id": "content_safety"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Basic guarded completion
using RestSharp;

var client = new RestClient("http://localhost:8000/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ],\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Basic guarded completion
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    [
      "role": "user",
      "content": "What is the capital of France?"
    ]
  ],
  "guardrails": ["config_id": "content_safety"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8000/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()
```

### Streaming guarded completion

**Request**

```json
{
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    {
      "role": "user",
      "content": "Tell me a short story."
    }
  ],
  "stream": true,
  "guardrails": {
    "config_id": "content_safety"
  }
}
```

**Response**

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1709424000,
  "model": "meta/llama-3.1-8b-instruct",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Paris is the capital of France."
      },
      "finish_reason": "stop"
    }
  ],
  "guardrails": {
    "config_id": "content_safety",
    "state": null,
    "llm_output": null,
    "output_data": null,
    "log": null
  }
}
```

**SDK Code**

```python Streaming guarded completion
import requests

url = "http://localhost:8000/v1/chat/completions"

payload = {
    "model": "meta/llama-3.1-8b-instruct",
    "messages": [
        {
            "role": "user",
            "content": "Tell me a short story."
        }
    ],
    "stream": True,
    "guardrails": { "config_id": "content_safety" }
}
headers = {"Content-Type": "application/json"}

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

print(response.json())
```

```javascript Streaming guarded completion
const url = 'http://localhost:8000/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"model":"meta/llama-3.1-8b-instruct","messages":[{"role":"user","content":"Tell me a short story."}],"stream":true,"guardrails":{"config_id":"content_safety"}}'
};

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

```go Streaming guarded completion
package main

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

func main() {

	url := "http://localhost:8000/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a short story.\"\n    }\n  ],\n  \"stream\": true,\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}")

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

	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))

}
```

```ruby Streaming guarded completion
require 'uri'
require 'net/http'

url = URI("http://localhost:8000/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a short story.\"\n    }\n  ],\n  \"stream\": true,\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java Streaming guarded completion
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("http://localhost:8000/v1/chat/completions")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a short story.\"\n    }\n  ],\n  \"stream\": true,\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}")
  .asString();
```

```php Streaming guarded completion
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'http://localhost:8000/v1/chat/completions', [
  'body' => '{
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    {
      "role": "user",
      "content": "Tell me a short story."
    }
  ],
  "stream": true,
  "guardrails": {
    "config_id": "content_safety"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Streaming guarded completion
using RestSharp;

var client = new RestClient("http://localhost:8000/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"meta/llama-3.1-8b-instruct\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a short story.\"\n    }\n  ],\n  \"stream\": true,\n  \"guardrails\": {\n    \"config_id\": \"content_safety\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Streaming guarded completion
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [
  "model": "meta/llama-3.1-8b-instruct",
  "messages": [
    [
      "role": "user",
      "content": "Tell me a short story."
    ]
  ],
  "stream": true,
  "guardrails": ["config_id": "content_safety"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8000/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()
```