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

# Screen content for threats

POST https://api.lakera.ai/v2/guard
Content-Type: application/json

The `guard` API endpoint is the integration point for GenAI applications using AI Guardrails. It allows you to call on all of AI Guardrails' defenses with a single API call.

For an overview and integration guidance please see [here](/docs/api/guard).

Using `guard`, you can submit the content of an LLM interaction to AI Guardrails. This include inputs from the user, reference documents, and the LLM output. The guardrails configured in the policy will screen the interaction, and a flagging response will indicate whether any threats were detected, in line with your policy.

Your application can then be programmed to take mitigating action based on the flagging response, such as blocking the interaction, warning the end user, or generating an internal security alert.

A request must contain `messages`, `tools`, or both. Send `tools` on its own to screen tool definitions independently of a conversation.


Reference: https://docs.lakera.ai/api-reference/lakera-api/guard/screen-content

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication using API key. Generate an API key from the AI Guardrails Dashboard. Example: Bearer sk_123...

## Servers

- `https://api.lakera.ai` (Default, default)
- `https://eu.api.lakera.ai` (Eu)
- `https://us.api.lakera.ai` (Us)
- `https://ap-southeast-1.api.lakera.ai` (ApSoutheast)

## Request

### Body (application/json)

This endpoint expects a GuardRequest.

- `messages` (list of Message, optional) — List of messages comprising the interaction history with the LLM in OpenAI API Chat Completions format. Can be multiple messages of any role: user, assistant, system, tool, or developer. Required unless `tools` is provided.
- `tools` (list of ToolDefinition, optional) — List of tool definitions exposed to the model, in OpenAI function-calling format. Each definition is screened on every request if your policy applies Prompt Defense to the Tool Definition role (screening location `tool_definition::content`). Can be sent without `messages`. See [Tool definitions](/docs/api/screening-roles#tool-definitions).
- `project_id` (string, optional) — ID of the relevant project. The request will be screened according to the policy assigned to the project. If no project ID is passed then the AI Guardrails Default Policy will be used for screening.
- `payload` (boolean, optional) — When true the response will return a payload object containing any PII, profanity or custom detector regex matches detected, along with their location within the contents.
- `breakdown` (boolean, optional) — When true the response will return a breakdown list of the detectors that were run, as defined in the policy, and whether each of them detected something or not.
- `metadata` (GuardRequestMetadata, optional) — Metadata tags can be attached to screening requests as an object that can contain any arbitrary key-value pairs. Common use cases include specifying the user or session ID.
- `dev_info` (boolean, optional) — When true the response will return an object with developer information about the build of AI Guardrails.

## Response

### 200

Screening result

- `flagged` (boolean, optional) — Depends on the action configured for the project. If `action` is `enforce`, `flagged` is `true` if any threats were detected with sufficient confidence. But if `action` is `detect`, `flagged` is always `false`. See [Project Mode](/docs/projects#project-mode) for more details.
- `action` (enum, optional) — The [action](/docs/projects#project-mode) configured for the project screening this request. `enforce` means full enforcement: the top-level `flagged` is `true` whenever a detector triggers. `detect` surfaces detections in the breakdown but forces the top-level `flagged` to `false`, letting you observe detector behavior without blocking traffic. Configured on the project level.
  - Allowed values: `detect`, `enforce`
- `payload` (list of GuardResponsePayloadItems, optional) — Contains detected PII, profanity, or custom regex matches with their locations. Only returned if payload=true in request.
- `breakdown` (list of GuardResponseBreakdownItems, optional) — List of detectors run and their results. Only returned if breakdown=true in request.
- `tools` (GuardResponseTools, optional) — Screening results for the tool definitions in the request's `tools` array, separate from the message-level results. Only returned if the request contains `tools`, the policy applies a detector to the Tool Definition role, and `breakdown` is true.
- `dev_info` (GuardResponseDevInfo, optional) — Build information. Only returned if dev_info=true in request.
- `metadata` (GuardResponseMetadata, optional) — Metadata returned from the request

## Errors

### 400 Bad Request Error

Bad request

- `error` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

### 401 Unauthorized Error

Unauthorized

- `error` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

### 429 Too Many Requests Error

Too many requests

- `error` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

### 500 Internal Server Error

Internal server error

- `error` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

## Types

### Message

A message in a conversation with the AI

- `role` (enum, required) — The role of the message sender
  - Allowed values: `system`, `user`, `assistant`, `tool`, `developer`
- `content` (MessageContent, optional) — The text content of the message. Required, except for assistant messages that include `tool_calls`, where it may be null or omitted.
- `tool_calls` (list of ToolCall, optional) — Optional tool calls (only valid for assistant messages)

### ToolDefinition

A tool definition exposed to the model, in OpenAI function-calling format

- `type` (enum, required)
  - Allowed values: `function`
- `function` (ToolDefinitionFunction, required) — The function a tool definition describes

### GuardRequestMetadata

Metadata tags can be attached to screening requests as an object that can contain any arbitrary key-value pairs. Common use cases include specifying the user or session ID.

- `user_id` (string, optional) — Unique identifier for the end user interacting with the LLM
- `session_id` (string, optional) — Unique identifier for the user's session or conversation
- `ip_address` (string, optional) — IP address of the user making the request
- `internal_request_id` (string, optional) — Internal request identifier for correlation with other systems

### GuardResponsePayloadItems

- `start` (integer, optional)
- `end` (integer, optional)
- `text` (string, optional)
- `detector_type` (string, optional)
- `labels` (list of string, optional)
- `message_id` (integer, optional) — Index of the message in the request that this result corresponds to

### GuardResponseBreakdownItems

- `project_id` (string, optional)
- `policy_id` (string, optional)
- `detector_id` (string, optional)
- `detector_type` (string, optional)
- `detected` (boolean, optional)
- `result` (string, optional) — Confidence level (l1_confident, l2_very_likely, l3_likely, l4_less_likely, l5_unlikely, no_level)
- `message_id` (integer, optional) — Index of the message in the request that this result corresponds to

### GuardResponseTools

Screening results for the tool definitions in the request's `tools` array, separate from the message-level results. Only returned if the request contains `tools`, the policy applies a detector to the Tool Definition role, and `breakdown` is true.

- `flagged` (boolean, optional) — Whether any tool definition was flagged
- `breakdown` (list of GuardResponseToolsBreakdownItems, optional) — List of detectors run on the tool definitions and their results. Only returned if breakdown=true in request.

### GuardResponseDevInfo

Build information. Only returned if dev_info=true in request.

- `git_revision` (string, optional) — First 8 characters of the commit hash
- `git_timestamp` (string, optional) — Timestamp in ISO 8601 format
- `model_version` (string, optional) — Currently always 'lakera-guard-1'
- `version` (string, optional) — Semantic version tracking code and model updates

### GuardResponseMetadata

Metadata returned from the request

- `request_uuid` (string, optional) — Unique identifier for the request

### MessageContent

The text content of the message. Required, except for assistant messages that include `tool_calls`, where it may be null or omitted.

### ToolCall

A tool call made by the assistant

- `function` (Function, required) — The function to call
- `type` (enum, required)
  - Allowed values: `function`
- `id` (string, required)

### ToolDefinitionFunction

The function a tool definition describes

- `name` (string, required) — Name of the tool. Must not be empty.
- `description` (string, optional) — Description of what the tool does and when to use it
- `parameters` (map from string to any, optional) — JSON Schema object describing the tool's parameters
- `strict` (boolean, optional) — Whether the model is required to follow the parameter schema exactly

### GuardResponseToolsBreakdownItems

- `project_id` (string, optional)
- `policy_id` (string, optional)
- `detector_id` (string, optional)
- `detector_type` (string, optional)
- `detected` (boolean, optional)
- `result` (string, optional) — Confidence level (l1_confident, l2_very_likely, l3_likely, l4_less_likely, l5_unlikely, no_level)
- `tool_id` (integer, optional) — Zero-based index of the tool definition in the request's `tools` array

### Function

A function to call

- `name` (string, required)
- `arguments` (string, required)

## Examples

### Basic screening request

**Request**

```json
{
  "messages": [
    {
      "role": "user",
      "content": "Hello, how are you?"
    }
  ]
}
```

**Response**

```json
{
  "flagged": true,
  "action": "enforce",
  "payload": [
    {
      "start": 1,
      "end": 1,
      "text": "string",
      "detector_type": "string",
      "labels": [
        "string"
      ],
      "message_id": 1
    }
  ],
  "breakdown": [
    {
      "project_id": "string",
      "policy_id": "string",
      "detector_id": "string",
      "detector_type": "string",
      "detected": true,
      "result": "string",
      "message_id": 1
    }
  ],
  "tools": {
    "flagged": true,
    "breakdown": [
      {
        "project_id": "string",
        "policy_id": "string",
        "detector_id": "string",
        "detector_type": "string",
        "detected": true,
        "result": "string",
        "tool_id": 1
      }
    ]
  },
  "dev_info": {
    "git_revision": "string",
    "git_timestamp": "string",
    "model_version": "string",
    "version": "string"
  },
  "metadata": {
    "request_uuid": "string"
  }
}
```

**SDK Code**

```python Basic screening request
import requests

url = "https://api.lakera.ai/v2/guard"

payload = { "messages": [
        {
            "role": "user",
            "content": "Hello, how are you?"
        }
    ] }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Basic screening request
const url = 'https://api.lakera.ai/v2/guard';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"messages":[{"role":"user","content":"Hello, how are you?"}]}'
};

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

```go Basic screening request
package main

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

func main() {

	url := "https://api.lakera.ai/v2/guard"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello, how are you?\"\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))

}
```

```ruby Basic screening request
require 'uri'
require 'net/http'

url = URI("https://api.lakera.ai/v2/guard")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello, how are you?\"\n    }\n  ]\n}"

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

```java Basic screening request
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.lakera.ai/v2/guard")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello, how are you?\"\n    }\n  ]\n}")
  .asString();
```

```php Basic screening request
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.lakera.ai/v2/guard', [
  'body' => '{
  "messages": [
    {
      "role": "user",
      "content": "Hello, how are you?"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Basic screening request
using RestSharp;

var client = new RestClient("https://api.lakera.ai/v2/guard");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello, how are you?\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Basic screening request
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["messages": [
    [
      "role": "user",
      "content": "Hello, how are you?"
    ]
  ]] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.lakera.ai/v2/guard")! 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()
```

### Screening request with tool definitions

**Request**

```json
{
  "messages": [
    {
      "role": "user",
      "content": "What's the weather in London?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a location.",
        "parameters": {
          "properties": {
            "location": {
              "type": "string"
            }
          },
          "required": [
            "location"
          ],
          "type": "object"
        }
      }
    }
  ]
}
```

**Response**

```json
{
  "flagged": true,
  "action": "enforce",
  "payload": [
    {
      "start": 1,
      "end": 1,
      "text": "string",
      "detector_type": "string",
      "labels": [
        "string"
      ],
      "message_id": 1
    }
  ],
  "breakdown": [
    {
      "project_id": "string",
      "policy_id": "string",
      "detector_id": "string",
      "detector_type": "string",
      "detected": true,
      "result": "string",
      "message_id": 1
    }
  ],
  "tools": {
    "flagged": true,
    "breakdown": [
      {
        "project_id": "string",
        "policy_id": "string",
        "detector_id": "string",
        "detector_type": "string",
        "detected": true,
        "result": "string",
        "tool_id": 1
      }
    ]
  },
  "dev_info": {
    "git_revision": "string",
    "git_timestamp": "string",
    "model_version": "string",
    "version": "string"
  },
  "metadata": {
    "request_uuid": "string"
  }
}
```

**SDK Code**

```python Screening request with tool definitions
import requests

url = "https://api.lakera.ai/v2/guard"

payload = {
    "messages": [
        {
            "role": "user",
            "content": "What's the weather in London?"
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather for a location.",
                "parameters": {
                    "properties": { "location": { "type": "string" } },
                    "required": ["location"],
                    "type": "object"
                }
            }
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Screening request with tool definitions
const url = 'https://api.lakera.ai/v2/guard';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"messages":[{"role":"user","content":"What\'s the weather in London?"}],"tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a location.","parameters":{"properties":{"location":{"type":"string"}},"required":["location"],"type":"object"}}}]}'
};

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

```go Screening request with tool definitions
package main

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

func main() {

	url := "https://api.lakera.ai/v2/guard"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in London?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get the current weather for a location.\",\n        \"parameters\": {\n          \"properties\": {\n            \"location\": {\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"location\"\n          ],\n          \"type\": \"object\"\n        }\n      }\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))

}
```

```ruby Screening request with tool definitions
require 'uri'
require 'net/http'

url = URI("https://api.lakera.ai/v2/guard")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in London?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get the current weather for a location.\",\n        \"parameters\": {\n          \"properties\": {\n            \"location\": {\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"location\"\n          ],\n          \"type\": \"object\"\n        }\n      }\n    }\n  ]\n}"

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

```java Screening request with tool definitions
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.lakera.ai/v2/guard")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in London?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get the current weather for a location.\",\n        \"parameters\": {\n          \"properties\": {\n            \"location\": {\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"location\"\n          ],\n          \"type\": \"object\"\n        }\n      }\n    }\n  ]\n}")
  .asString();
```

```php Screening request with tool definitions
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.lakera.ai/v2/guard', [
  'body' => '{
  "messages": [
    {
      "role": "user",
      "content": "What\'s the weather in London?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a location.",
        "parameters": {
          "properties": {
            "location": {
              "type": "string"
            }
          },
          "required": [
            "location"
          ],
          "type": "object"
        }
      }
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Screening request with tool definitions
using RestSharp;

var client = new RestClient("https://api.lakera.ai/v2/guard");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in London?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get the current weather for a location.\",\n        \"parameters\": {\n          \"properties\": {\n            \"location\": {\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"location\"\n          ],\n          \"type\": \"object\"\n        }\n      }\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Screening request with tool definitions
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "messages": [
    [
      "role": "user",
      "content": "What's the weather in London?"
    ]
  ],
  "tools": [
    [
      "type": "function",
      "function": [
        "name": "get_weather",
        "description": "Get the current weather for a location.",
        "parameters": [
          "properties": ["location": ["type": "string"]],
          "required": ["location"],
          "type": "object"
        ]
      ]
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.lakera.ai/v2/guard")! 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()
```