OpenAI Integration
Integrate AIVory Guard with OpenAI Assistants and custom AI agents to add real-time compliance and security scanning to your OpenAI-powered coding workflows.
- Direct API integration - Call AIVory Guard REST endpoints from your OpenAI agents
- Multiple language support - Python, JavaScript/TypeScript examples included
- Batch scanning - Scan multiple files in a single request
- MCP bridge coming soon - Standardized protocol integration in development
Prerequisites
Before you begin, make sure you have:
Integration Approaches
There are two main ways to integrate AIVory Guard with OpenAI:
Direct API Integration
API Endpoints
AIVory Guard provides REST API endpoints that your OpenAI agent can call:
Base URL: https://app.aivory.net
Endpoints:
- POST /api/scan - Scan code for violations
- POST /api/batch-scan - Batch scan multiple files
- GET /api/config - Get compliance configuration
- GET /api/rules - List compliance rules
- GET /api/health - Health check
Authentication
All requests require Bearer token authentication:
Authorization: Bearer your_aivory_api_key
Code Examples
Python Example (OpenAI Assistants)
import openai
import requests
# AIVory Guard API configuration
AIVORY_BASE_URL = "https://app.aivory.net"
AIVORY_API_KEY = "your_aivory_api_key"
def scan_code_with_aivory(code, language, filename="main.py"):
"""Scan code using AIVory Guard API"""
headers = {
"Authorization": f"Bearer {AIVORY_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"code": code,
"language": language,
"filename": filename,
"standards": ["OWASP", "GDPR", "HIPAA"]
}
response = requests.post(
f"{AIVORY_BASE_URL}/api/scan",
headers=headers,
json=payload
)
return response.json()
# Use in OpenAI Assistant
client = openai.OpenAI(api_key="your_openai_key")
# Create an assistant with code scanning capability
assistant = client.beta.assistants.create(
name="Secure Code Generator",
instructions="""You are a secure code generator. When writing code:
1. Generate the code as requested
2. Scan it using the scan_code_with_aivory function
3. Review the results and fix any violations found
4. Re-scan to verify fixes before completing the task
Always report both violations found and fixes applied.""",
model="gpt-4",
tools=[{"type": "function", "function": {
"name": "scan_code_with_aivory",
"description": "Scan generated code for security and compliance violations",
"parameters": {
"type": "object",
"properties": {
"code": {"type": "string", "description": "The code to scan"},
"language": {"type": "string", "description": "Programming language"},
"filename": {"type": "string", "description": "Filename"}
},
"required": ["code", "language"]
}
}}]
)
JavaScript/TypeScript Example
import OpenAI from 'openai';
import fetch from 'node-fetch';
const AIVORY_BASE_URL = 'https://app.aivory.net';
const AIVORY_API_KEY = process.env.AIVORY_API_KEY;
async function scanCodeWithAIVory(code: string, language: string, filename: string = 'main.js') {
const response = await fetch(`${AIVORY_BASE_URL}/api/scan`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${AIVORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
code,
language,
filename,
standards: ['OWASP', 'GDPR', 'PCI-DSS']
})
});
return await response.json();
}
// Use with OpenAI
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
const assistant = await openai.beta.assistants.create({
name: 'Secure Code Generator',
instructions: 'Generate secure code and scan it for compliance violations using the scan_code function.',
model: 'gpt-4',
tools: [{
type: 'function',
function: {
name: 'scan_code',
description: 'Scan code for security and compliance violations',
parameters: {
type: 'object',
properties: {
code: { type: 'string' },
language: { type: 'string' },
filename: { type: 'string' }
},
required: ['code', 'language']
}
}
}]
});
OpenAI Agent SDK Example
from openai_agent import Agent
class SecureCodeAgent(Agent):
def __init__(self):
super().__init__(name="Secure Code Agent")
self.aivory_api_key = os.getenv("AIVORY_API_KEY")
def generate_and_scan_code(self, prompt):
# Generate code with OpenAI
code = self.generate_code(prompt)
# Scan with AIVory Guard
scan_result = self.scan_code(code)
# Return results
return {
"code": code,
"scan_result": scan_result
}
def scan_code(self, code, language="python"):
import requests
response = requests.post(
"https://app.aivory.net/api/scan",
headers={"Authorization": f"Bearer {self.aivory_api_key}"},
json={"code": code, "language": language}
)
return response.json()
API Request/Response Examples
Scan Code Request
POST https://app.aivory.net/api/scan
Authorization: Bearer aiv_your_api_key
Content-Type: application/json
{
"code": "def login(username, password):\n if username == 'admin' and password == 'admin':\n return True",
"language": "python",
"filename": "auth.py",
"standards": ["OWASP", "GDPR"]
}
Scan Code Response
{
"status": "completed",
"violations": [
{
"severity": "high",
"standard": "OWASP",
"rule": "A07:2021 - Identification and Authentication Failures",
"message": "Hardcoded credentials detected",
"line": 2,
"column": 8,
"suggestion": "Use environment variables or secure vault for credentials"
}
],
"summary": {
"total_violations": 1,
"critical": 0,
"high": 1,
"medium": 0,
"low": 0
}
}
summary object in responses to quickly determine if code passes compliance checks without parsing individual violations.
Batch Scanning
For scanning multiple files at once, use the batch endpoint to reduce API calls:
const response = await fetch(`${AIVORY_BASE_URL}/api/batch-scan`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${AIVORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
files: [
{
code: "// File 1 content",
language: "javascript",
filename: "main.js"
},
{
code: "# File 2 content",
language: "python",
filename: "utils.py"
}
],
standards: ["OWASP", "SOC2"]
})
});
Error Handling
Robust Error Handling Example
Always implement proper error handling in production:
def scan_code_safe(code, language):
try:
response = requests.post(
f"{AIVORY_BASE_URL}/api/scan",
headers={"Authorization": f"Bearer {AIVORY_API_KEY}"},
json={"code": code, "language": language},
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
return {"error": "Scan timeout - code may be too large"}
except requests.exceptions.HTTPError as e:
return {"error": f"API error: {e.response.status_code}"}
except Exception as e:
return {"error": f"Unexpected error: {str(e)}"}
Best Practices
MCP Bridge (Coming Soon)
We’re developing an MCP bridge that will allow OpenAI agents to natively use AIVory Guard’s MCP server. This will provide:
Interested in beta testing? Contact us to join the early access program.
Troubleshooting
Common Issues and Solutions
Authentication Errors (401)
- Verify your API token is correct and not expired
- Ensure the
Authorizationheader usesBearerprefix - Check that your token has the required scopes
Timeout Errors
- Reduce the size of code being scanned
- Use batch scanning for multiple small files instead of one large scan
- Increase timeout value (max recommended: 60s)
Rate Limit Errors (429)
- Implement exponential backoff retry logic
- Cache scan results for unchanged code
- Consider upgrading to a higher tier for increased limits
Debug Mode
Enable verbose logging to debug integration issues:
import logging
logging.basicConfig(level=logging.DEBUG)
# Your API calls will now show detailed request/response info
Next Steps
Need help? Contact support or check the FAQ.