Python Examples

Python Examples

Integrate GovernanceAI with Python applications.

Installation

$pip install requests python-dotenv

Basic Setup

1import requests
2import os
3from dotenv import load_dotenv
4
5load_dotenv()
6
7API_KEY = os.getenv('GOVERNANCEAI_API_KEY')
8ORG_ID = os.getenv('GOVERNANCEAI_ORG_ID')
9BASE_URL = 'https://api.governanceai.com/v1'
10
11headers = {
12 'Authorization': f'Bearer {API_KEY}',
13 'Content-Type': 'application/json'
14}

Evaluate Guardrails

1def evaluate_guardrails(user_message, user_id):
2 """Evaluate a message against guardrails"""
3
4 payload = {
5 "messages": [
6 {"role": "user", "content": user_message}
7 ],
8 "context": {
9 "org_id": ORG_ID,
10 "user_id": user_id
11 }
12 }
13
14 response = requests.post(
15 f'{BASE_URL}/guardrails/evaluate',
16 headers=headers,
17 json=payload
18 )
19
20 if response.status_code == 200:
21 result = response.json()
22 return {
23 'decision': result['decision'],
24 'risk_score': result.get('risk_score', 0),
25 'violations': result.get('policy_violations', [])
26 }
27 else:
28 raise Exception(f"API error: {response.status_code}")
29
30# Usage
31result = evaluate_guardrails("My credit card is 4532-1111-2222-3333", "user_123")
32print(f"Decision: {result['decision']}")
33print(f"Risk Score: {result['risk_score']}")

Create Policy

1def create_policy(policy_name, guardrail_ids):
2 """Create a new policy"""
3
4 payload = {
5 "name": policy_name,
6 "guardrail_ids": guardrail_ids,
7 "scope": "organization",
8 "enforcement": {
9 "mode": "blocking",
10 "log_violations": True
11 }
12 }
13
14 response = requests.post(
15 f'{BASE_URL}/policies',
16 headers=headers,
17 json=payload
18 )
19
20 return response.json()
21
22# Usage
23policy = create_policy(
24 "Production Safety",
25 ["guardrail_pii", "guardrail_toxic"]
26)
27print(f"Policy created: {policy['policy_id']}")

Run Scan

1def run_scan(scan_type, repositories):
2 """Run a code scan"""
3
4 payload = {
5 "scan_type": scan_type,
6 "repositories": repositories
7 }
8
9 response = requests.post(
10 f'{BASE_URL}/scans',
11 headers=headers,
12 json=payload
13 )
14
15 scan = response.json()
16 return scan['scan_id']
17
18# Usage
19scan_id = run_scan("code_scan", ["repo_1", "repo_2"])
20print(f"Scan started: {scan_id}")

Error Handling

1def make_request(method, endpoint, data=None):
2 """Make API request with error handling"""
3
4 try:
5 if method == 'GET':
6 response = requests.get(f'{BASE_URL}{endpoint}', headers=headers)
7 elif method == 'POST':
8 response = requests.post(f'{BASE_URL}{endpoint}', headers=headers, json=data)
9
10 if response.status_code == 401:
11 raise ValueError("Invalid API key")
12 elif response.status_code == 403:
13 raise PermissionError("Insufficient permissions")
14 elif response.status_code >= 500:
15 raise RuntimeError("Server error")
16
17 return response.json()
18 except requests.RequestException as e:
19 print(f"Network error: {e}")
20 return None

Next Steps