> This page is for version v0.23.0.
> For other versions, use one of these documentation indexes:
> - Latest (default): https://docs.nvidia.com/nemo/guardrails/latest/llms.txt
> - v0.24.1: https://docs.nvidia.com/nemo/guardrails/v0.24.1/llms.txt
> - v0.24.0: https://docs.nvidia.com/nemo/guardrails/v0.24.0/llms.txt
> - v0.23.0: https://docs.nvidia.com/nemo/guardrails/v0.23.0/llms.txt
> - v0.22.0: https://docs.nvidia.com/nemo/guardrails/v0.22.0/llms.txt

> 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/reference/guardrails-api-server/chat-completions/chat-completions

## Request

### Body (application/json)

This endpoint expects a GuardrailsChatCompletionRequest.

- `model` (string, required) — LLM model to use for the completion.
- `messages` (list of ChatMessage, optional) — Chat messages in the current conversation.
- `stream` (boolean, optional, default: false) — Return partial message deltas as server-sent events.
- `max_tokens` (integer, optional) — Maximum number of tokens to generate.
- `temperature` (float, optional) — Sampling temperature.
- `top_p` (float, optional) — Top-p sampling parameter.
- `stop` (GuardrailsChatCompletionRequestStop, optional) — Stop sequence or sequences.
- `presence_penalty` (float, optional) — Presence penalty parameter.
- `frequency_penalty` (float, 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` (GuardrailsRequestOptions, optional) — Guardrails-specific request options.

## 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 ChatCompletionChoice, optional)
- `guardrails` (GuardrailsResponseData, optional)

## Errors

### 422 Unprocessable Entity Error

Invalid request or unsupported state continuation.

- `detail` (ErrorResponseDetail, optional) — Error detail.

## Types

### ChatMessage

- `role` (string, required) — Message role, such as `system`, `user`, `assistant`, `tool`, or `context`.
- `content` (ChatMessageContent, required) — Message content.

### GuardrailsChatCompletionRequestStop

Stop sequence or sequences.

- string
- list of string

### GuardrailsRequestOptions

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` (GenerationOptions, optional)
- `state` (map from string to any, optional) — Colang 1.0 transcript state for continuing a previous interaction.

### ChatCompletionChoice

- `index` (integer, optional)
- `message` (ChatMessage, optional)
- `finish_reason` (string, optional, nullable)

### GuardrailsResponseData

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

### ErrorResponseDetail

Error detail.

- string
- map from string to any

### ChatMessageContent

Message content.

- string
- list of map from string to any

### GenerationOptions

- `rails` (GenerationRailsOptions, optional)
- `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` (GenerationOptionsOutputVars, optional) — Context variables to return.
- `log` (GenerationLogOptions, optional)

### GenerationRailsOptions

- `input` (RailSelection, optional) — Enable, disable, or select named rails.
- `output` (RailSelection, optional) — Enable, disable, or select named rails.
- `retrieval` (RailSelection, optional) — Enable, disable, or select named rails.
- `dialog` (boolean, optional, default: true) — Enable dialog rails.
- `tool_input` (RailSelection, optional) — Enable, disable, or select named rails.
- `tool_output` (RailSelection, optional) — Enable, disable, or select named rails.

### GenerationOptionsOutputVars

Context variables to return.

- boolean
- list of string

### GenerationLogOptions

- `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.

### RailSelection

Enable, disable, or select named rails.

- boolean
- list of string

## 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()
```