> ## 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.

# QWED Open Responses troubleshooting

> Troubleshoot QWED Open Responses issues including installation errors, SchemaGuard failures, ToolGuard rejections, and agent verification runtime problems.

Common issues and solutions when using QWED Open Responses.

***

## Installation issues

### "No module named 'qwed\_open\_responses'"

**Cause:** Package not installed

**Solution:**

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

For specific integrations:

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

***

### "ImportError: langchain not found"

**Cause:** Missing optional dependency

**Solution:**

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

***

## Guard failures

### "No guards configured"

**Cause:** `verify()` was called with zero guards. Verification fails closed: `verified=False`, and `blocked=True` in strict mode. Earlier versions returned `verified=True` here. `VerifiedOpenAI` created without guards also emits a `UserWarning` at construction for the same reason.

**Solution:** Configure at least one guard.

```python theme={null}
# Wrong - no guards, always fails closed
verifier = ResponseVerifier()
result = verifier.verify(response)  # verified=False

# Right - set default guards
verifier = ResponseVerifier(default_guards=[ToolGuard(), SafetyGuard()])

# Or pass guards per call
result = verifier.verify(response, guards=[ToolGuard()])
```

***

### "verify\_structured\_output requires a JSON schema or at least one guard"

**Cause:** `verify_structured_output()` was called with neither `schema` nor `guards`. It raises `ValueError` because the call would verify nothing.

**Solution:** Pass a schema, at least one guard, or both. An explicit empty schema `{}` is accepted and matches anything.

```python theme={null}
result = verifier.verify_structured_output(
    output=my_output,
    schema=my_schema,  # or guards=[SchemaGuard(schema=my_schema)]
)
```

***

### "Cannot parse JSON response of type ... Expected object"

**Cause:** `verify()` received a string that parses to a JSON scalar, array, or `null`. These are rejected with `ValueError` because an array or scalar payload would bypass per-item guard inspection. Plain non-JSON strings are still accepted and wrapped as text.

**Solution:** Pass the response as a JSON object (or a string that parses to one). Wrap arrays in an object envelope such as `{"output": [...]}`.

***

### Verification passed but `warnings` is non-empty

**Cause:** A guard returned a warning-severity result. Warnings pass the guard and do not fail `verified` on their own. They surface in `result.warnings` as a separate visible state.

**Solution:** This is expected. To escalate warnings to failures, create the verifier with `allow_warnings=False`.

```python theme={null}
verifier = ResponseVerifier(
    default_guards=[MathGuard(), SafetyGuard()],
    allow_warnings=False,  # warnings now fail (and block in strict mode)
)
```

***

### "SchemaGuard: Missing required field"

**Cause:** Output doesn't match expected schema

**Debug:**

```python theme={null}
from jsonschema import validate, ValidationError

try:
    validate(output, schema)
except ValidationError as e:
    print(f"Field: {e.path}")
    print(f"Error: {e.message}")
```

**Common fixes:**

* Check field names (case-sensitive)
* Ensure all required fields are present
* Verify types match schema

SchemaGuard reports only the first validation error, with `total_errors` set to `None` and `errors_truncated` set to `True`. Fix the reported error and verify again to surface the next one.

***

### "SchemaGuard: Additional properties are not allowed"

**Cause:** Since v0.6.0, SchemaGuard adds `additionalProperties: false` to the root object when your schema doesn't set it. Any undeclared top-level field fails validation.

**Fix:** Declare the field in `properties`, set `additionalProperties` explicitly in the schema, or opt out in the constructor:

```python theme={null}
guard = SchemaGuard(schema, allow_additional_properties=True)
```

```typescript theme={null}
const guard = new SchemaGuard(schema, { allowAdditionalProperties: true });
```

***

### "JSON response exceeds the character limit"

**Cause:** `verify()` received a JSON string longer than 100,000 characters. Related messages are "JSON response exceeds the nesting depth limit" (more than 100 levels) and "JSON response could not be parsed within safe limits" (for example, an oversized integer). These come back as failed verdicts, not exceptions.

**Fix:** Reduce the response size or nesting before verification. For oversized integers specifically, shorten the digit run (split the value or send it as a string) — shrinking unrelated content will not clear an integer failure. SafetyGuard has its own bounds: it fails closed above 12 nesting levels, 10,000 nodes, or 100,000 content characters.

***

### "ToolGuard: Tool in blocklist"

**Cause:** Agent tried to call a blocked tool

**Debug:**

```python theme={null}
print(f"Blocked tool: {result.tool_name}")
print(f"Blocklist: {tool_guard.blocklist}")
```

**Options:**

1. Remove tool from blocklist if safe
2. Use whitelist instead
3. Create exception for specific cases

```python theme={null}
# Whitelist mode
tool_guard = ToolGuard(
    whitelist=["calculator", "search", "read_file"],
    allow_unknown=False
)
```

***

### "ToolGuard: tool-like content in an unrecognized format"

**Cause:** The response contains something that looks like a tool call, but it matches none of the recognized envelope shapes. ToolGuard blocks it rather than passing with "No tool calls".

**Recognized shapes:** `type=tool_call`, `type=function_call`, `tool_calls[]`, `choices[].message.tool_calls[]`, `content[].type=tool_use`.

**Fix:** Emit tool calls in one of the recognized shapes. This block also fires when a call's JSON-encoded arguments cannot be parsed, exceed 10,000 characters, or nest deeper than 128 levels.

***

### "ToolGuard: malformed tool-call entry"

**Cause:** A `tool_calls`, `choices`, or `content` collection contains a non-object item, or the response mixes a direct tool call (`type=tool_call`/`function_call`) with a sibling collection. Ambiguous envelopes are blocked because validating one side would let the other escape policy checks.

**Fix:** Every entry in a tool-call collection must be an object with a non-blank string tool name, and a response must carry its tool calls in exactly one place.

***

### "MathGuard: No verifiable math found in response"

**Cause:** The response contains no verifiable math shape. Prose, plain strings, and objects without recognized total, percentage, or inline-calculation fields no longer pass MathGuard vacuously. The guard fails with a warning-severity result, which blocks in strict mode.

**Options:**

1. Remove MathGuard from stacks that verify non-math responses
2. Keep the default `allow_warnings=True` on the verifier so the warning surfaces in `result.warnings` without failing verification
3. Add a custom rule so the response shape becomes verifiable

```python theme={null}
# Only run MathGuard where math is expected
math_verifier = ResponseVerifier(default_guards=[MathGuard()])
text_verifier = ResponseVerifier(default_guards=[SafetyGuard()])
```

***

### "MathGuard: Calculation mismatch"

**Cause:** LLM provided wrong calculation

**Debug:**

```python theme={null}
result = math_guard.verify(output)
if not result.verified:
    print(f"Operation: {result.operation}")
    print(f"Expected: {result.expected}")
    print(f"Got: {result.actual}")
```

**This is working as intended!** The guard caught an LLM hallucination.

**Options:**

1. Return error to user
2. Retry with corrected prompt
3. Use QWED's math engine directly

***

### "SafetyGuard: PII detected"

**Cause:** Response contains personally identifiable information

**Patterns detected:**

* SSN: `\d{3}-\d{2}-\d{4}`
* Credit Card: `\d{16}`
* Email: Standard email pattern
* Phone: Various formats

**Options:**

1. **Block** (default): Return error
2. **Redact**: Replace with `[REDACTED]`
3. **Custom patterns**: Add your own

```python theme={null}
safety_guard = SafetyGuard(
    block_pii=False,
    redact_pii=True,
    custom_patterns=[
        r"EMPLOYEE-\d{6}",  # Internal ID
    ]
)
```

***

### "StateGuard: Invalid transition"

**Cause:** Trying to move to invalid state

**Debug:**

```python theme={null}
print(f"From: {from_state}")
print(f"To: {to_state}")
print(f"Valid transitions: {state_guard.valid_transitions[from_state]}")
```

**Fix:** Review your state machine definition.

***

## Integration issues

### LangChain callback not triggering

**Check callback is added:**

```python theme={null}
# Wrong
executor = AgentExecutor(agent=agent, tools=tools)

# Right
executor = AgentExecutor(
    agent=agent,
    tools=tools,
    callbacks=[QWEDCallbackHandler(...)]  # Must include!
)
```

**Check tool is being called:**

```python theme={null}
callback = QWEDCallbackHandler(
    log_verifications=True,  # Enable logging
    guards=[...]
)
```

***

### OpenAI wrapper not verifying

**Check you're using VerifiedOpenAI:**

```python theme={null}
# Wrong - uses standard client
from openai import OpenAI
client = OpenAI()

# Right - uses verified wrapper
from qwed_open_responses.middleware.openai_sdk import VerifiedOpenAI
client = VerifiedOpenAI(guards=[...])
```

**Check tool\_choice is set:**

```python theme={null}
response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    tools=tools,
    tool_choice="auto"  # Must enable tools
)
```

***

### Express middleware returns 422 "Request verification failed"

**Cause:** In the npm package, `verifyRequestBody` returns HTTP 422 with code `QWED_REQUEST_BLOCKED` when a request declares a body but Express has no parsed body. A request declares a body with a non-zero `Content-Length` or a `Transfer-Encoding` header. This happens even when `blockOnFailure` is `false`, because the middleware can't verify a body it can't see.

Requests without a body continue to the next handler. Requests whose body parses to an empty JSON object also continue.

**Fix:** Register a body parser before the QWED middleware:

```typescript theme={null}
import express from 'express';
import { ToolGuard, verifyRequestBody } from 'qwed-open-responses';

const app = express();
app.use(express.json());           // Parse the body first
app.use(verifyRequestBody({ guards: [new ToolGuard()] }));
```

Also confirm the request's `Content-Type` matches the parser you registered. A body that `express.json()` skips stays unparsed and is blocked.

***

### Guards not being applied

**Check guard order:**

```python theme={null}
# Guards run in order
verifier = ResponseVerifier(guards=[
    SchemaGuard(schema),  # First
    ToolGuard(blocklist), # Second
    SafetyGuard(),        # Last
])
```

**Check guard is configured:**

```python theme={null}
# Empty blocklist won't block anything
tool_guard = ToolGuard(blocklist=[])  # Does nothing!

# Fix
tool_guard = ToolGuard(blocklist=["dangerous_tool"])
```

***

## Performance issues

### Verification is slow

**Reduce guards:**

```python theme={null}
# Only essential guards
verifier = ResponseVerifier(guards=[
    ToolGuard(blocklist),  # Fast
    # Skip MathGuard for non-math outputs
])
```

**Cache schemas:**

```python theme={null}
# Parse schema once
from functools import lru_cache

@lru_cache
def get_schema_guard(schema_name):
    return SchemaGuard(schema=SCHEMAS[schema_name])
```

***

### Too many false positives

**Tune PII patterns:**

```python theme={null}
safety_guard = SafetyGuard(
    pii_patterns=[
        r"\b\d{3}-\d{2}-\d{4}\b",  # Only SSN, not dates
    ]
)
```

**Adjust tolerance:**

```python theme={null}
math_guard = MathGuard(tolerance=0.01)  # Allow 1 cent difference
```

***

## Common errors reference

| Error | Guard | Cause | Fix |
| - | - | - | - |
| "No guards configured" | Verifier | Zero guards passed | Configure at least one guard |
| "Cannot parse JSON response" | Verifier | String parsed to scalar/array/null | Send a JSON object |
| "requires a JSON schema or at least one guard" | Verifier | `verify_structured_output` with neither | Pass a schema or guards |
| "Missing required field" | Schema | Output missing field | Check schema |
| "Additional properties are not allowed" | Schema | Undeclared root field | Declare it or set `allow_additional_properties=True` |
| "JSON response exceeds the character limit" | Verifier | JSON over 100,000 chars | Shorten the JSON response |
| "JSON response exceeds the nesting depth limit" | Verifier | JSON over 100 levels deep | Reduce nesting |
| "JSON response could not be parsed within safe limits" | Verifier | Oversized integer | Shorten the digit run (split the value or send it as a string) |
| 422 `QWED_REQUEST_BLOCKED` | Express middleware | Declared body was not parsed | Register a body parser first |
| "Tool in blocklist" | Tool | Dangerous tool called | Review blocklist |
| "Unrecognized format" | Tool | Tool-like content in unknown shape | Use a recognized envelope |
| "Malformed tool-call entry" | Tool | Non-object entry or hybrid envelope | Fix response structure |
| "Calculation mismatch" | Math | LLM math wrong | This is intentional! |
| "No verifiable math found" | Math | Response has no math shape | Scope MathGuard to math responses |
| "PII detected" | Safety | SSN/email in output | Redact or edit prompt |
| "Invalid transition" | State | Bad state flow | Fix state machine |
| "Budget exceeded" | Safety | Too many calls | Increase limit |
| "Argument type error" | Argument | Wrong type | Fix tool schema |

***

## Getting help

1. **GitHub Issues:** [github.com/QWED-AI/qwed-open-responses/issues](https://github.com/QWED-AI/qwed-open-responses/issues)
2. **Documentation:** [docs.qwedai.tech/open-responses](https://docs.qwedai.tech/docs/open-responses/overview)
3. **Examples:** [GitHub Examples](https://github.com/QWED-AI/qwed-open-responses/tree/main/examples)


## Related topics

- [QWED Open Responses: verified tool calls for AI agents](/open-responses/overview.md)
- [QWED Open Responses guards for verified AI agents](/open-responses/guards.md)
- [QWED Open Responses examples for verified AI agents](/open-responses/examples.md)
- [Changelog](/changelog.md)
- [Changelog Archive](/changelog-archive.md)


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