## Why the Admin and Audit Logs API is Your New Best Friend for OpenAI Management
Get ready to level up your OpenAI API game! This beta powerhouse lets organization admins dive deep into audit logs, capturing every thrilling detail of API usage, user tweaks, and key events. Imagine having a crystal-clear record of who did what, when, and how – perfect for debugging wild issues, enforcing ironclad security, or nailing compliance audits. We're talking comprehensive visibility into your org's activity without breaking a sweat.
**Key Wins Right Out of the Gate:**
- **Real-Time Insights:** Spot API request patterns, successes, failures, and more.
- **User & Org Tracking:** Monitor creations, deletions, and role changes.
- **Scalable Queries:** Filter logs by time, order, and limits for laser-focused analysis.
- **Beta Excitement:** It's in beta, so expect rapid enhancements – join the early adopters!
In this guide, we'll blast through setup, endpoints, schemas, and pro tips with code snippets and real-world scenarios to make you an audit log ninja.
## 2. Nail Authentication: Secure Access in Seconds
No fumbling around – authentication is straightforward using your trusty OpenAI API key. But here's the kicker: **you must be an organization admin** to unlock these logs. Head to your OpenAI dashboard, snag your org API key, and you're golden.
**Pro Tip:** Always use organization-level API keys for admin tasks. Personal keys? Nope, they won't cut it here.
Real-world app: Picture your compliance team needing logs without handing over god-mode access. Issue a dedicated org key, and boom – controlled auditing!
## 3. Endpoint Extravaganza: Fetch Logs Like a Boss
This API packs two dynamite endpoints under `/v1/organization_logs/`. Let's deep-dive each with parameters, responses, and battle-tested code.
### 3.1 List Logs: Grab Batches of Action-Packed Events
Fire up `GET /v1/organization_logs/` to snag a list of recent logs. Customize with query params for ultimate control:
- **limit** (optional, int, max 100, default 20): How many logs to fetch.
- **after** (optional, string): Cursor for pagination – grab the 'id' from your last log.
- **order** (optional, 'asc' or 'desc', default 'desc'): Chronological or reverse?
**Response Magic:** JSON array of log objects, plus `has_more` boolean and `after` cursor.
**Python Power Move:** Check out this snippet from OpenAI's official repo:
```python
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
stream = client.organization_logs.list(limit=10)
stream = client._stream_to_generator(stream)
for log in stream:
print(log)
```
Full example? Dive into [OpenAI's Python list_logs.py on GitHub](https://github.com/openai/openai-python/blob/main/examples/admin_audit_logs/list_logs.py).
**Node.js Thrill:**
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function main() {
const response = await openai.beta.organizationLogs.list();
console.log(response);
}
main();
```
Snag the complete [Node.js version here](https://github.com/openai/openai-node/blob/main/examples/admin-audit-logs/list-logs.ts).
**Real-World Hack:** Paginate through a month's logs to analyze peak usage hours. Script it to export to CSV for your BI dashboard – compliance reports on autopilot!
### 3.2 Get Single Log: Zoom In on Specific Events
Want the nitty-gritty on one log? `GET /v1/organization_logs/{log_id}` delivers the full deets.
**Response:** A single, richly detailed log object.
**Python Precision Strike:**
```python
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
log_id = "log-123"
log = client.organization_logs.get(log_id)
print(log)
```
Complete code at [OpenAI's Python get_log.py](https://github.com/openai/openai-python/blob/main/examples/admin_audit_logs/get_log.py).
**Node.js Deep Dive:**
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const logId = 'log-123';
async function main() {
const response = await openai.beta.organizationLogs.get(logId);
console.log(response);
}
main();
```
Full script [on GitHub](https://github.com/openai/openai-node/blob/main/examples/admin-audit-logs/get-log.ts).
**Actionable Example:** User reports a failed API call? Pull the exact log_id from list, fetch details, and troubleshoot the error field – saves hours!
## 4. Log Schema Showdown: Every Field Demystified
Each log is a treasure trove of structured data. Here's the full schema breakdown – memorize these for audit mastery!
**Core Fields:**
- **id** (string): Unique log identifier (e.g., "log_abc123").
- **event** (string): The action type. Hot ones include:
- `chat.completions.create`: Chat completion requests.
- `organization.user.created`: New user added.
- `organization.api_key.created`: Fresh API key minted.
- And tons more like deletions, role updates!
- **actor** (object): Who pulled the trigger?
- `type`: "user", "organization", or "api_key".
- `id`: Their unique ID.
- `name`: Display name (email for users).
- **target** (object): What got affected?
- `type`: "chat_completion", "api_key", "user", etc.
- `id` & `name`: Matching the actor style.
- **created_at** (int): Unix timestamp of the event.
**API Request Deep Dive (if applicable):** Nested object with:
- `id`, `model`, `response_body_truncated` (boolean), `prompt_truncated` (boolean).
- `response` (object): Full response JSON.
- `error` (object): Details if it bombed.
**Status Check:**
- **success** (boolean): Did it work?
**Example Log in Action:**
```json
{
"id": "log_x7k9p2m",
"event": "chat.completions.create",
"actor": {
"type": "user",
"id": "user_abc",
"name": "
[email protected]"
},
"target": {
"type": "chat_completion",
"id": "ch_abc123"
},
"created_at": 1697059200,
"api_request": {
"id": "req_xyz",
"model": "gpt-4",
"success": true
}
}
```
**Pro Extensions:**
- Chain queries: List logs, filter by event='chat.completions.create', then aggregate success rates.
- Integrate with tools like Datadog or Splunk for alerting on failures.
- Security gold: Audit API key creations to prevent shadow IT.
## 5. Real-World Superpowers: From Compliance to Optimization
**Compliance Wizardry:** Export logs monthly for SOC 2 audits – prove every action is tracked.
**Debugging Dynamo:** Correlate `error` fields with `response` to fix model hallucinations or rate limits.
**Usage Analytics:** Sum API requests by actor to bill internal teams accurately.
**Automation Alert:** Build a Lambda function that emails on 'organization.user.deleted' events.
## 6. Best Practices & Gotchas
- **Pagination Power:** Always check `has_more` and use `after` – don't miss logs!
- **Rate Limits:** Respect OpenAI's quotas; batch wisely.
- **Data Retention:** Logs stick around, but query promptly for freshness.
- **Beta Vibes:** Report feedback via OpenAI support – shape the future!
With this toolkit, you're not just logging – you're dominating OpenAI ops. Dive in, experiment, and watch your org thrive!
---
<div style="text-align: center; margin-top: 2rem;">
<a href="https://help.openai.com/en/articles/9687866-admin-and-audit-logs-api-for-the-api-platform" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a>
</div>