> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qwedai.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI integration for verified AI agents

> Use the VerifiedOpenAI wrapper to add verified tool calls, structured output validation, and deterministic guards to OpenAI Assistants and agent workflows.

QWED Open Responses provides a verified wrapper for the OpenAI SDK.

***

## Installation

```bash theme={null}
pip install qwed-open-responses[openai]
```

***

## Quick start

```python theme={null}
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI
from qwed_open_responses import ToolGuard

# Create verified client
client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[ToolGuard()],
)

# Responses are automatically verified
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello"}],
)

# Check verification result
print(response._qwed_verification.verified)
# True
```

> [!WARNING]
>
> Always pass at least one guard. `VerifiedOpenAI` without `guards` emits a `UserWarning` at construction: verification is fail-closed, so with zero guards every response fails verification and either raises `ResponseBlocked` (`block_on_failure=True`) or is returned unverified (`block_on_failure=False`).

The attached `_qwed_verification` result also exposes:

* `warnings`: guard results that passed with warning severity
* `request_id`: correlation ID when a `request_id` was supplied in the verification context
* `binding` and `verify_binding()`: tamper-evidence tying the result to the exact response and guard list
* `timestamp`: timezone-aware UTC timestamp with the `+00:00` offset

See the [guards reference](https://docs.qwedai.tech/open-responses/guards.md#combining-guards) for details.

***

## Structured outputs

```python theme={null}
import json
from qwed_open_responses import ResponseVerifier, SafetyGuard, SchemaGuard
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI

# Define expected schema
order_schema = {
    "type": "object",
    "properties": {
        "product": {"type": "string"},
        "quantity": {"type": "integer", "minimum": 1},
        "price": {"type": "number", "minimum": 0},
    },
    "required": ["product", "quantity", "price"]
}

client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[SafetyGuard()],
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    response_format={"type": "json_object"},
)

# Check the model's JSON against the schema
order = json.loads(response.choices[0].message.content)
result = ResponseVerifier().verify_structured_output(
    output=order,
    guards=[SchemaGuard(schema=order_schema)],
)

# For {"product": "Widget", "quantity": 2, "price": 9.99}:
print(result.verified)
# True
```

Keep `SchemaGuard` out of the client's guards. It validates the whole response object (`id`, `choices`, `usage` and so on) rather than the model's JSON, so every response fails with "Schema validation failed". Parse the model's JSON and check it as above.

***

## Tool calling verification

```python theme={null}
from qwed_open_responses import ToolGuard

client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[
        ToolGuard(
            allowed_tools=["get_weather", "search"],
            blocked_tools=["execute_code"],
        )
    ],
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    tools=[...],
)
# Tool calls are verified before returning
```

***

## Handling blocked responses

```python theme={null}
from qwed_open_responses.middleware.openai_sdk import ResponseBlocked

try:
    response = client.chat.completions.create(...)
except ResponseBlocked as e:
    print(f"Response blocked: {e.result.block_reason}")
    
    # Access the original response
    original = e.response
    
    # Access verification details
    for guard_result in e.result.guard_results:
        if not guard_result.passed:
            print(f"  - {guard_result.guard_name}: {guard_result.message}")
```

***

## Non-blocking mode

```python theme={null}
# Don't raise exceptions, just mark results
client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[ToolGuard()],
    block_on_failure=False,  # Don't raise exceptions
)

response = client.chat.completions.create(...)

# Check verification manually
if response._qwed_verification.verified:
    process(response)
else:
    handle_failure(response._qwed_verification)
```

***

## Budget limits with verification context

Pass `verification_context` to `chat.completions.create()` or `responses.create()` to give guards trusted usage totals, such as the running `total_cost` and `total_tokens` for a session. `VerifiedOpenAI` removes `verification_context` from the request before calling OpenAI, so it never reaches the API. The context is then passed to every guard when the response is verified.

```python theme={null}
from qwed_open_responses import SafetyGuard
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI, ResponseBlocked

client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[SafetyGuard(max_cost=10.0, max_tokens=50_000)],
)

try:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Summarize this report"}],
        verification_context={"total_cost": 9.50, "total_tokens": 48_000},
    )
except ResponseBlocked:
    # Response pushed the totals past a SafetyGuard budget limit
    ...
```

You can also call `client.verify(response, context={...})` directly.

***

## Responses API (preview)

```python theme={null}
from qwed_open_responses import SafetyGuard, ToolGuard
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI

client = VerifiedOpenAI(api_key="sk-...", guards=[ToolGuard(), SafetyGuard()])

response = client.responses.create(
    model="gpt-4",
    input="Search for weather in NYC",
    tools=[{"type": "web_search"}],
)
# Verified before it is returned: a failed check raises ResponseBlocked
```

`client.responses.create(...)` runs the same guards on Responses API objects. From v0.6.2, `ToolGuard` checks each call item in the response's `output[]` the way it checks a single call. A `function_call`, `custom_tool_call` or `mcp_approval_request` is checked under its own name. A client action item (`local_shell_call`, `shell_call`, `apply_patch_call`, `computer_call`) is checked as its action tool, which the default blocklist blocks. The blocklist, allowlist and argument patterns apply to each call, and in Python so do custom validators and `max_calls_per_response`.

Unknown `*_call` and `*_request` items fail closed, and so do remote MCP `mcp_call` items that carry a `name` and `arguments`, as the API returns them. An `mcp_call` without `arguments` reads as tool-free. Text and the provider-hosted `web_search_call`, `file_search_call`, `code_interpreter_call` and `image_generation_call` items pass. The provider has already run those hosted tools by the time the response arrives, and `ToolGuard` doesn't check them, so `allowed_tools` and `blocked_tools` can't stop them. Limit hosted tools in the `tools` you send with the request.

> [!NOTE]
>
> In v0.6.1, `ToolGuard` didn't read call items in `output[]`. Every response with a function call raised `ResponseBlocked`, even a safe one. Upgrade to v0.6.2 to use your own function tools with `responses.create`.

***

## Full example

```python theme={null}
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI, ResponseBlocked
from qwed_open_responses import ToolGuard, SafetyGuard

# Create client with multiple guards
client = VerifiedOpenAI(
    api_key="sk-...",
    guards=[
        ToolGuard(blocked_tools=["execute_shell"]),
        SafetyGuard(check_pii=True),
    ],
)

try:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "user", "content": "Process this order"}
        ],
        tools=available_tools,
    )
    
    print("✅ Response verified!")
    print(f"Guards passed: {response._qwed_verification.guards_passed}")
    # ✅ Response verified!
    # Guards passed: 2

except ResponseBlocked as e:
    print(f"❌ Blocked: {e.result.block_reason}")
    # If the model called execute_shell:
    # ❌ Blocked: BLOCKED: Tool 'execute_shell' is not allowed
```


## Related topics

- [QWED Open Responses guards for verified AI agents](https://docs.qwedai.tech/open-responses/guards.md)
- [QWED Open Responses: verified tool calls for AI agents](https://docs.qwedai.tech/open-responses/overview.md)
- [LangChain integration for verified AI agents](https://docs.qwedai.tech/open-responses/langchain.md)
- [QWED Open Responses examples for verified AI agents](https://docs.qwedai.tech/open-responses/examples.md)
- [LLM verification with formal methods](https://docs.qwedai.tech/advanced/llm-verification.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.