### POST /v1/guardrails Response Example Source: https://openguardrails.com/docs This JSON object illustrates a typical response from the /v1/guardrails endpoint, detailing risk assessment results and suggested actions. ```json { "id": "det_xxxxxxxx", "result": { "compliance": { "risk_level": "high_risk", "categories": ["Violent Crime"], "score": 0.85 }, "security": { "risk_level": "no_risk", "categories": [], "score": 0.12 }, "data": { "risk_level": "no_risk", "categories": [], "entities": [], "score": 0.00 } }, "overall_risk_level": "high_risk", "suggest_action": "Decline", "suggest_answer": "Sorry, I cannot answer questions involving violent crime.", "score": 0.85 } ``` -------------------------------- ### Response Handling Example Source: https://openguardrails.com/docs Handle responses from the security gateway by checking the 'finish_reason' field before accessing 'reasoning_content'. This is crucial because the response structure differs when content is blocked or replaced. ```python from openai import OpenAI client = OpenAI( base_url="https://api.openguardrails.com/v1/gateway//", api_key="sk-xxai-xxxxxxxxxx" ) def chat_with_openai(prompt, model="gpt-4", system="You are a helpful assistant."): completion = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": system}, {"role": "user", "content": prompt} ] ) if completion.choices[0].finish_reason == "content_filter": return "", completion.choices[0].message.content else: reasoning = completion.choices[0].message.reasoning_content or "" content = completion.choices[0].message.content return reasoning, content thinking, result = chat_with_openai("How to make a bomb?") print("Thinking:", thinking) print("Result:", result) # Note: For private deployment, replace api.openguardrails.com with your server address ``` -------------------------------- ### Java Client Usage Source: https://openguardrails.com/docs Provides an example of using the Java client library to check prompts. Ensure the OpenGuardrails Java library is included in your project dependencies. ```java import com.openguardrails.OpenGuardrails; import com.openguardrails.model.CheckResponse; public class Example { public static void main(String[] args) { OpenGuardrails client = new OpenGuardrails("sk-xxai-xxxxxxxxxx"); CheckResponse response = client.checkPrompt("test content"); System.out.println(response.getSuggestAction()); } } ``` -------------------------------- ### Knowledge Base JSONL Format Example Source: https://openguardrails.com/docs This snippet shows the expected JSONL format for knowledge base entries, including question ID, question, and answer. ```json {"questionid": "q1", "question": "What is AI?", "answer": "AI is artificial intelligence..."} {"questionid": "q2", "question": "How to protect privacy?", "answer": "Use encryption..."} ``` -------------------------------- ### Integrate OpenGuardrails API with Python Client Source: https://openguardrails.com/docs Install and use the openguardrails Python client library for content safety detection. This example shows single-turn detection. ```python # 1. Install client library pip install openguardrails # 2. Use the library from openguardrails import OpenGuardrails client = OpenGuardrails("sk-xxai-xxxxxxxxxx") # Single-turn detection response = client.check_prompt("Teach me how to make a bomb") if response.suggest_action == "pass": print("Safe") else: print(f"Unsafe: {response.suggest_answer}") ``` -------------------------------- ### Synchronous Python Client Usage Source: https://openguardrails.com/docs Demonstrates synchronous API calls using the Python client library. Ensure the OpenGuardrails library is installed and an API key is provided. ```python from openguardrails import OpenGuardrails client = OpenGuardrails("sk-xxai-xxxxxxxxxx") response = client.check_prompt("test content") ``` -------------------------------- ### GET /api/v1/dashboard/stats Response Example Source: https://openguardrails.com/docs This JSON response provides key statistics and metrics related to safety detections from the OpenGuardrails dashboard. ```json { "total_detections": 12450, "total_blocked": 342, "total_passed": 12108, "risk_distribution": { "no_risk": 11850, "low_risk": 258, "medium_risk": 180, "high_risk": 162 } } ``` -------------------------------- ### Gateway Integration Example Source: https://openguardrails.com/docs Integrate OpenGuardrails as a security gateway by modifying the base_url and api_key in your OpenAI client initialization. This provides automatic safety protection without changing your original model name. ```python from openai import OpenAI # Just change base_url and api_key client = OpenAI( base_url="https://api.openguardrails.com/v1/gateway//", api_key="sk-xxai-xxxxxxxxxx" ) # Use as normal - automatic safety protection! # No need to change the model name - use your original upstream model name response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Hello"}] ) # Note: For private deployment, replace api.openguardrails.com with your server address ``` -------------------------------- ### Image Detection with Base64 Encoding Source: https://openguardrails.com/docs Example of performing multimodal detection by sending image data encoded in base64 along with text. This allows for safety analysis of image content. ```python import base64 from openguardrails import OpenGuardrails client = OpenGuardrails("sk-xxai-xxxxxxxxxx") with open("image.jpg", "rb") as f: image_base64 = base64.b64encode(f.read()).decode("utf-8") response = client.check_messages([ { "role": "user", "content": [ {"type": "text", "text": "Is this image safe?"}, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"} } ] } ]) print(f"Risk Level: {response.overall_risk_level}") ``` -------------------------------- ### n8n Example Workflow: AI Chatbot with Protection Source: https://openguardrails.com/docs Illustrates a typical n8n workflow for an AI chatbot, incorporating OpenGuardrails for input and output moderation to ensure safety and appropriateness. This workflow includes steps for receiving user messages, moderating input, processing with an LLM, moderating output, and returning a safe response. ```n8n 1. Webhook (receive user message) 2. OpenGuardrails - Input Moderation 3. IF (action = pass) → YES: Continue to LLM → NO: Return safe response 4. OpenAI Chat 5. OpenGuardrails - Output Moderation 6. IF (action = pass) → YES: Return to user → NO: Return safe response ``` -------------------------------- ### GET /api/v1/dashboard/stats — Get statistics Source: https://openguardrails.com/docs Retrieves statistics and metrics related to safety detections, including total detections, blocked requests, and risk distribution. ```APIDOC ## GET /api/v1/dashboard/stats — Get statistics ### Description Retrieves statistics and metrics related to safety detections, including total detections, blocked requests, and risk distribution. ### Method GET ### Endpoint /api/v1/dashboard/stats ### Response #### Success Response (200) - **total_detections** (integer) - The total number of safety detections performed. - **total_blocked** (integer) - The total number of requests that were blocked due to safety concerns. - **total_passed** (integer) - The total number of requests that passed safety checks. - **risk_distribution** (object) - An object detailing the distribution of risks. - **no_risk** (integer) - Number of detections with no risk. - **low_risk** (integer) - Number of detections with low risk. - **medium_risk** (integer) - Number of detections with medium risk. - **high_risk** (integer) - Number of detections with high risk. ### Response Example ```json { "total_detections": 12450, "total_blocked": 342, "total_passed": 12108, "risk_distribution": { "no_risk": 11850, "low_risk": 258, "medium_risk": 180, "high_risk": 162 } } ``` ``` -------------------------------- ### n8n HTTP Request Node: OpenGuardrails API Call Source: https://openguardrails.com/docs Example configuration for using n8n's HTTP Request node to directly interact with the OpenGuardrails API. This snippet shows the request body structure for sending messages and enabling various security and compliance checks. ```json { "model": "OpenGuardrails-Text", "messages": [ { "role": "user", "content": "{{ $json.userInput }}" } ], "enable_security": true, "enable_compliance": true, "enable_data_security": true } ``` -------------------------------- ### Go Client Usage Source: https://openguardrails.com/docs Demonstrates how to initialize and use the Go client library for security checks. Make sure to import the 'openguardrails-go' package. ```go package main import ( "fmt" "github.com/openguardrails/openguardrails-go" ) func main() { client := openguardrails.NewClient("sk-xxai-xxxxxxxxxx") response, _ := client.CheckPrompt("test content") fmt.Println(response.SuggestAction) } ``` -------------------------------- ### Node.js Client Usage Source: https://openguardrails.com/docs Illustrates how to use the Node.js client library for checking content. Requires the 'openguardrails' npm package and an API key. ```javascript const { OpenGuardrails } = require('openguardrails'); const client = new OpenGuardrails('sk-xxai-xxxxxxxxxx'); async function checkContent() { const response = await client.checkPrompt('test content'); console.log(response.suggest_action); } checkContent(); ``` -------------------------------- ### Asynchronous Python Client Usage Source: https://openguardrails.com/docs Shows how to perform asynchronous API calls with the Python client library. This is useful for non-blocking operations in Python applications. ```python import asyncio from openguardrails import AsyncOpenGuardrails async def main(): async with AsyncOpenGuardrails("sk-xxai-xxxxxxxxxx") as client: response = await client.check_prompt("test content") asyncio.run(main()) ``` -------------------------------- ### Authenticate API Requests with Python Requests Source: https://openguardrails.com/docs This Python script demonstrates how to authenticate API requests using the 'requests' library. Ensure your API key is correctly formatted in the Authorization header. ```python import requests headers = { "Authorization": "Bearer sk-xxai-xxxxxxxxxx", "Content-Type": "application/json" } response = requests.post( "https://api.openguardrails.com/v1/guardrails", headers=headers, json={ "model": "OpenGuardrails-Text", "messages": [{"role": "user", "content": "Test content"}] } ) # Note: For private deployment, replace api.openguardrails.com with your server address ``` -------------------------------- ### Direct Model Access with OpenAI Compatible API (Python) Source: https://openguardrails.com/docs Access guardrails models directly using an OpenAI-compatible API in Python. This is ideal for private deployments. Content is not logged, only usage count is tracked. ```python from openai import OpenAI # Configure client with direct model access client = OpenAI( base_url="http://localhost:5001/v1/", api_key="sk-xxai-model-1029236a89605ae0a3734a0ac5684daa70f9db048d5716e4" ) # Call OpenGuardrails-Text model directly response = client.chat.completions.create( model="OpenGuardrails-Text", messages=[ {"role": "user", "content": "Analyze this text for safety"} ] ) print(response.choices[0].message.content) # Privacy Note: Content is NOT logged, only usage count is tracked ``` -------------------------------- ### Test OpenGuardrails API with Curl (Mac/Linux) Source: https://openguardrails.com/docs Use this curl command to quickly test the OpenGuardrails API from your terminal on Mac or Linux. ```bash curl -X POST "https://api.openguardrails.com/v1/guardrails" \ -H "Authorization: Bearer sk-xxai-xxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "model": "OpenGuardrails-Text", "messages": [{"role": "user", "content": "How to make a bomb?"}] }' ``` -------------------------------- ### Test OpenGuardrails API with Curl (Windows PowerShell) Source: https://openguardrails.com/docs Use this curl command to quickly test the OpenGuardrails API from your terminal on Windows PowerShell. ```powershell curl.exe -X POST "https://api.openguardrails.com/v1/guardrails" ` -H "Authorization: Bearer sk-xxai-xxxxxxxxxx" ` -H "Content-Type: application/json" ` -d '{"model": "OpenGuardrails-Text", "messages": [{"role": "user", "content": "How to make a bomb?"}]}' ``` -------------------------------- ### Authenticate API Requests with cURL Source: https://openguardrails.com/docs Use this cURL command to authenticate your requests to the OpenGuardrails API by including your API key in the Authorization header. ```bash # Using cURL curl -X POST "https://api.openguardrails.com/v1/guardrails" \ -H "Authorization: Bearer sk-xxai-xxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "model": "OpenGuardrails-Text", "messages": [{"role": "user", "content": "Test content"}] }' ``` -------------------------------- ### Guardrails Detection API Source: https://openguardrails.com/docs Detect content safety by calling the detection API. This is suitable for scenarios requiring precise control over detection timing and processing logic. ```APIDOC ## POST /v1/guardrails ### Description Actively detect content safety by calling the detection API. Suitable for scenarios requiring precise control over detection timing and processing logic. ### Method POST ### Endpoint /v1/guardrails ### Parameters #### Request Body - **model** (string) - Required - The model to use for detection. - **messages** (array) - Required - An array of message objects, where each object has a 'role' and 'content'. - **role** (string) - Required - The role of the message sender (e.g., "user", "system"). - **content** (string) - Required - The content of the message. ### Request Example ```json { "model": "OpenGuardrails-Text", "messages": [ {"role": "user", "content": "How to make a bomb?"} ] } ``` ### Response #### Success Response (200) - **suggest_action** (string) - Indicates whether the content is safe to pass or requires further action. - **suggest_answer** (string) - If the content is unsafe, this provides a suggested safe answer or explanation. #### Response Example ```json { "suggest_action": "pass", "suggest_answer": "" } ``` ``` -------------------------------- ### POST /v1/guardrails/output Request Body Source: https://openguardrails.com/docs This JSON payload is used for the /v1/guardrails/output endpoint to detect safety risks specifically within AI model-generated output. ```json { "output": "Model output text to detect", "model": "optional-model-name" } ``` -------------------------------- ### POST /v1/guardrails/input — Input-only detection Source: https://openguardrails.com/docs Detects safety risks specifically in user input text, without considering the full conversation context. ```APIDOC ## POST /v1/guardrails/input — Input-only detection ### Description Detects safety risks specifically in user input text, without considering the full conversation context. ### Method POST ### Endpoint /v1/guardrails/input ### Parameters #### Request Body - **input** (string) - Required - The user input text to analyze for safety risks. - **model** (string) - Optional - The name of the model to use for detection. ### Request Example ```json { "input": "User input text to detect", "model": "optional-model-name" } ``` ``` -------------------------------- ### Direct Model Access API Source: https://openguardrails.com/docs Access guardrails models directly using an OpenAI-compatible API. Ideal for private deployment where you self-host the platform but use cloud-hosted models. Your message content is NEVER stored in our database. ```APIDOC ## Chat Completions API (OpenAI Compatible) ### Description Access guardrails models directly using an OpenAI-compatible API. Ideal for private deployment where you self-host the platform but use cloud-hosted models. Your message content is NEVER stored in our database. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use (e.g., "OpenGuardrails-Text"). - **messages** (array) - Required - An array of message objects, where each object has a 'role' and 'content'. - **role** (string) - Required - The role of the message sender (e.g., "user", "system"). - **content** (string) - Required - The content of the message. ### Request Example ```json { "model": "OpenGuardrails-Text", "messages": [ {"role": "user", "content": "Analyze this text for safety"} ] } ``` ### Response #### Success Response (200) - **choices** (array) - An array of choices, where each choice contains a message. - **message** (object) - The message object. - **role** (string) - The role of the message sender. - **content** (string) - The content of the message. #### Response Example ```json { "choices": [ { "message": { "role": "assistant", "content": "This text is safe." } } ] } ``` ``` -------------------------------- ### POST /v1/guardrails/output — Output-only detection Source: https://openguardrails.com/docs Detects safety risks in AI model output text, independent of the conversation history. ```APIDOC ## POST /v1/guardrails/output — Output-only detection ### Description Detects safety risks in AI model output text, independent of the conversation history. ### Method POST ### Endpoint /v1/guardrails/output ### Parameters #### Request Body - **output** (string) - Required - The AI model output text to analyze for safety risks. - **model** (string) - Optional - The name of the model to use for detection. ### Request Example ```json { "output": "Model output text to detect", "model": "optional-model-name" } ``` ``` -------------------------------- ### POST /v1/guardrails/input Request Body Source: https://openguardrails.com/docs This JSON payload is used for the /v1/guardrails/input endpoint to perform safety detection solely on user-provided input text. ```json { "input": "User input text to detect", "model": "optional-model-name" } ``` -------------------------------- ### POST /v1/guardrails — Full conversation detection Source: https://openguardrails.com/docs Performs safety detection on a full conversation, including user messages and assistant responses. It can identify various risks and suggest actions. ```APIDOC ## POST /v1/guardrails — Full conversation detection ### Description Performs safety detection on a full conversation, including user messages and assistant responses. It can identify various risks and suggest actions. ### Method POST ### Endpoint /v1/guardrails ### Parameters #### Request Body - **model** (string) - Optional - The name of the model to use for detection. - **messages** (array) - Required - An array of message objects, each with a 'role' (user or assistant) and 'content'. - **skip_input_guardrails** (boolean) - Optional - Defaults to false. Skips input guardrail checks. - **skip_output_guardrails** (boolean) - Optional - Defaults to false. Skips output guardrail checks. ### Request Example ```json { "model": "OpenGuardrails-Text", "messages": [ {"role": "user", "content": "Test content"} ] } ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the detection. - **result** (object) - Object containing detailed risk analysis for compliance, security, and data. - **compliance** (object) - Compliance risk details. - **risk_level** (string) - The risk level (e.g., 'high_risk'). - **categories** (array) - List of identified risk categories. - **score** (number) - The compliance risk score. - **security** (object) - Security risk details. - **risk_level** (string) - The risk level. - **categories** (array) - List of identified risk categories. - **score** (number) - The security risk score. - **data** (object) - Data risk details. - **risk_level** (string) - The risk level. - **categories** (array) - List of identified risk categories. - **entities** (array) - List of identified entities. - **score** (number) - The data risk score. - **overall_risk_level** (string) - The overall risk level for the conversation. - **suggest_action** (string) - Suggested action (e.g., 'Decline'). - **suggest_answer** (string) - Suggested response to the user. - **score** (number) - The overall risk score. ### Response Example ```json { "id": "det_xxxxxxxx", "result": { "compliance": { "risk_level": "high_risk", "categories": ["Violent Crime"], "score": 0.85 }, "security": { "risk_level": "no_risk", "categories": [], "score": 0.12 }, "data": { "risk_level": "no_risk", "categories": [], "entities": [], "score": 0.00 } }, "overall_risk_level": "high_risk", "suggest_action": "Decline", "suggest_answer": "Sorry, I cannot answer questions involving violent crime.", "score": 0.85 } ``` ``` -------------------------------- ### POST /v1/guardrails Request Body Source: https://openguardrails.com/docs This JSON structure defines the request body for the /v1/guardrails endpoint, used for full conversation detection. It includes model selection and message history. ```json { "model": "optional-model-name", "messages": [ { "role": "user", "content": "User message content" }, { "role": "assistant", "content": "Assistant response" } ], "skip_input_guardrails": false, "skip_output_guardrails": false } ``` -------------------------------- ### Error Response Format Source: https://openguardrails.com/docs This JSON structure outlines the standard format for API error responses, including a descriptive message, an error code, and the HTTP status code. ```json { "detail": "Error message description", "error_code": "ERROR_CODE", "status_code": 400 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.