xtekky/gpt4free · error · RuntimeError

(await response.json()), data

Error message

(await response.json()), data

What it means

When the conversation POST returns HTTP 422, OpenaiChat raises RuntimeError with a tuple of (parsed JSON body, request data). 422 means the request payload failed validation — the JSON error body names which field, and the second tuple element is the exact data dict that was sent, enabling direct comparison.

Source

Thrown at g4f/Provider/needs_auth/OpenaiChat.py:704

                if proofofwork is not None:
                    headers["openai-sentinel-proof-token"] = proofofwork
                if (
                    need_turnstile
                    and getattr(auth_result, "turnstile_token", None) is not None
                ):
                    headers[
                        "openai-sentinel-turnstile-token"
                    ] = auth_result.turnstile_token
                async with session.post(
                    backend_anon_url if cls._api_key is None else backend_url,
                    json=data,
                    headers=headers,
                ) as response:
                    cls._update_request_args(auth_result, session)
                    if response.status in (401, 403, 429, 500):
                        raise MissingAuthError("Access token is not valid")
                    elif response.status == 422:
                        raise RuntimeError((await response.json()), data)
                    await raise_for_status(response)
                    buffer = ""
                    matches = []
                    async for line in response.iter_lines():
                        pattern = re.compile(r"file-service://[\w-]+")
                        for match in pattern.finditer(line.decode(errors="ignore")):
                            if match.group(0) in matches:
                                continue
                            matches.append(match.group(0))
                            generated_image = await cls.get_generated_image(
                                session, auth_result, match.group(0), prompt
                            )
                            if generated_image is not None:
                                yield generated_image
                        async for chunk in cls.iter_messages_line(
                            session,
                            auth_result,
                            line,

View on GitHub (pinned to 973504e177)

Solutions

  1. Inspect both tuple members: response JSON states the invalid field, data shows what was sent
  2. Start a new conversation (drop cached conversation_id/parent_message_id) and retry
  3. Update g4f so the payload builder matches the current backend schema
  4. Verify the model slug against OpenaiChat.get_models()

Example fix

// before
resp = await client.chat.completions.create(model='...', messages=msgs)  # 422 tuple error

// after
# inspect then reset conversation state
except RuntimeError as e:
    body, payload = e.args
    logging.error('422 detail: %s sent: %s', body, payload)
resp = await client.chat.completions.create(model=..., messages=msgs)  # fresh conversation
Defensive patterns

Strategy: try-catch

Validate before calling

models = await OpenaiChat.get_models()
assert model in models, f'model {model} rejected by backend (422 risk)'

Try / catch

try:
    resp = await client.chat.completions.create(model=model, messages=msgs)
except RuntimeError as e:
    if isinstance(e.args, tuple) and len(e.args) == 2:
        body, payload = e.args  # 422: (server detail, sent data)
        logging.error('422 on field per %s; sent %s', body, payload)
        resp = await client.chat.completions.create(model=model, messages=msgs)  # fresh conversation
    else:
        raise

Prevention

When it happens

Trigger: POSTing the constructed data dict (model, messages, conversation_id, parent_message_id, features, etc.) where the backend rejects a field — e.g. unknown model slug, malformed message references, stale conversation/parent IDs, or schema changes after an OpenAI deploy.

Common situations: Reusing a conversation_id/parent_message_id from an expired session; model name not accepted by the backend; g4f version lagging a payload-schema change; features flags the backend no longer accepts.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/0bec3093e26f5f44. Report an issue: GitHub.