# HTTP 422 `invalid_tool_schema` — API Store Hub

> VI: HTTP 422 phát sinh khi khai báo `tools`, `tool_choice` hoặc `response_format.json_schema` không đúng đặc tả JSON Schema mà model yêu cầu, hoặc lịch sử tin nhắn chứa `tool_use` thiếu `tool_result` tương ứng.
> EN: HTTP 422 occurs when `tools`, `tool_choice`, or `json_schema` violate strict JSON Schema constraints or when assistant tool calls lack matching tool result messages.

- Canonical VI: https://apistorehub.com/vi/loi-api/422-tool-use-json-schema-invalid
- Canonical EN: https://apistorehub.com/en/loi-api/422-tool-use-json-schema-invalid
- Retry Policy: Do not retry unchanged 422 payloads; correct the tool schema or tool result pairing first.

## Root Causes
- Tool names containing spaces, dots, or exceeding 64 characters.
- Missing `"type": "object"` or missing `"additionalProperties": false` under `strict: true`.
- Assistant `tool_calls` not immediately followed by matching `role: "tool"` responses.

## Step-by-Step Resolution
1. Restrict tool names strictly to `^[a-zA-Z0-9_-]{1,64}$`.
2. Ensure every object schema defines `type: "object"`, `properties`, `required`, and `additionalProperties: false`.
3. Pair every assistant `tool_call.id` with a matching `role: "tool"` or `tool_result` message.
4. Validate individual tool definitions in isolation before registering large toolsets.

## Diagnostic cURL
```bash
curl https://apistorehub.com/v1/chat/completions \
  -H "Authorization: Bearer sk-ash-your_key" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-6.2-sol","tools":[{"type":"function","function":{"name":"get_price","description":"Get ST rate","parameters":{"type":"object","properties":{"model_id":{"type":"string"}},"required":["model_id"],"additionalProperties":false}}}],"messages":[{"role":"user","content":"Check price of deepseek-v4-flash"}]}'
```

## Production Fix (TypeScript)
```
export function sanitizeToolName(raw: string): string {
  return raw.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "tool_fn";
}
```

## FAQ
- **Why can one tool schema pass on GPT yet return 422 on Gemini or Claude?**: Providers vary on `$ref`, `anyOf`, and `default` keywords. Keeping schemas flat with explicit types guarantees cross-family compatibility.
- **How many tools should I attach per request?**: Keep active tools under 20-30 to maximize tool-selection accuracy and avoid unnecessary input token bloat.
- **Must `role: "tool"` content be a string?**: Yes. Always serialize structured tool results with `JSON.stringify` before placing them in `content`.
