← Back to home
§ INTEGRATION · OPENAI CHAT COMPLETIONS
OpenAI client wrapper
Wrap the openai client once — every chat.completions.create call enforces policies on the user prompt and records an LLM span with model and token usage.
§ 01
Prerequisites
- Execlave account with an active API key — Settings → API keys.
- A registered agent in Execlave. Use its lowercase-kebab
agent_id. - OpenAI SDK:
openai >=1.0(Python) oropenai >=4(JS).
§ 02
Install
Instrumentation is shipped in the SDK; the openai SDK is the only additional dependency you need.
Python
pip install 'execlave-sdk[openai]'JavaScript / TypeScript
npm install @execlave/sdk openai§ 03
Instant setup with a copilot
Paste this prompt into your AI coding assistant.
§ Copy prompt · paste into your AI coding assistant
You are adding Execlave (an AI agent governance platform) to an existing project that calls the OpenAI Chat Completions API directly via the official `openai` SDK. Do not rewrite prompt construction — only wrap the client. Rules you MUST follow:1. Install the correct extra. Python: `pip install 'execlave-sdk[openai]'`. JS/TS: `npm install @execlave/sdk openai` (the openai SDK is already a project dependency in most cases).2. Read `EXECLAVE_API_KEY` from environment variables. Never hardcode. Add it to `.env.example`.3. Create exactly ONE Execlave client per process and reuse it.4. Wrap the openai client IMMEDIATELY AFTER construction, BEFORE any `chat.completions.create` call. Python: `openai = instrument_openai(OpenAI(), exe, agent_id="<stable-kebab-id>")`. JS: `const openai = instrumentOpenAI(new OpenAI(), exe, { agentId: '<stable-kebab-id>' })`. Both return the SAME client for fluent assignment.5. The wrap supports BOTH sync (`OpenAI`) and async (`AsyncOpenAI`) clients in Python, and is idempotent — a `_execlaveInstrumented` / `_execlave_instrumented` marker prevents double-wrapping.6. `agent_id` is a stable kebab-case string identifying THIS LLM-call site in the Execlave dashboard.7. Wrap call sites in try/except for `execlave.errors.PolicyBlockedError` (Python) or `PolicyBlockedError` from `@execlave/sdk` (JS). On block, return a structured 4xx response containing `exc.violations`. Do NOT swallow.8. Do NOT call `exe.enforce_policy` manually — the wrapper enforces using the LAST user message as the policy input. If the prompt is multimodal, only the `text` parts are extracted for the policy check.9. Token usage, model name, and the response `content` are captured automatically into the span. Do NOT add manual `trace.set_*` calls around `create`.10. On process shutdown, call `exe.flush()` (Python) or `await exe.shutdown()` (JS). Deliverables:- Wrap the client at the single bootstrap site that constructs it.- Add env vars to `.env.example`.- One diff per file. Reference: https://www.execlave.com/docs/integrations/openai-chatAPI reference: https://www.execlave.com/docs/sdk-reference§ 04
Quick start
Wrap the client once at bootstrap. Both sync and async OpenAI clients are supported; multimodal content parts are unwrapped to text for the policy check.
Python
from openai import OpenAIfrom execlave import Execlavefrom execlave.integrations.openai_chat import instrument_openai exe = Execlave(api_key="exe_prod_...")openai = instrument_openai(OpenAI(), exe, agent_id="support-bot") # Enforcement runs on the LAST user message before the request leaves;# the response model + token usage is captured automatically.resp = openai.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are concise."}, {"role": "user", "content": "Summarise our Q3 pipeline"}, ],)JavaScript / TypeScript
import OpenAI from 'openai';import { Execlave } from '@execlave/sdk';import { instrumentOpenAI } from '@execlave/sdk/integrations/openai-chat'; const exe = new Execlave({ apiKey: process.env.EXECLAVE_API_KEY! });const openai = instrumentOpenAI(new OpenAI(), exe, { agentId: 'support-bot' }); const resp = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [ { role: 'system', content: 'You are concise.' }, { role: 'user', content: 'Summarise our Q3 pipeline' }, ],});§ 05
Handling blocks
A blocked prompt raises PolicyBlockedError BEFORE the request leaves the process; tokens are not billed by OpenAI.
Python
from execlave.errors import PolicyBlockedError try: resp = openai.chat.completions.create(model="gpt-4o-mini", messages=messages)except PolicyBlockedError as exc: return {"error": "blocked", "violations": exc.violations}JavaScript / TypeScript
import { PolicyBlockedError } from '@execlave/sdk'; try { await openai.chat.completions.create({ model: 'gpt-4o-mini', messages });} catch (err) { if (err instanceof PolicyBlockedError) { return { error: 'blocked', violations: err.violations }; } throw err;}§ 06