xtekky/gpt4free · error · RuntimeError

line.get("error")

Error message

line.get("error")

What it means

While processing each line of the OpenAI chat event stream, a line containing a truthy top-level 'error' field causes g4f to raise RuntimeError with that value (as written the message is the literal expression line.get("error") — the effective payload is the error content). It surfaces in-band errors the server embeds in the stream rather than as HTTP status.

Source

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

                        fields.is_thinking = True
                        yield Reasoning(
                            status=m.get("metadata", {}).get("initial_text")
                        )
                    # if c.get("content_type") == "multimodal_text":
                    #    for part in c.get("parts"):
                    #        if isinstance(part, dict) and part.get("content_type") == "image_asset_pointer":
                    #            yield await cls.get_generated_image(session, auth_result, part, fields.prompt, fields.conversation_id)
                    if m.get("author", {}).get("role") == "assistant":
                        if fields.parent_message_id is None:
                            fields.parent_message_id = v.get("message", {}).get("id")
                        fields.message_id = v.get("message", {}).get("id")
                    if m.get("status") == "finished_successfully" and m.get(
                        "metadata", {}
                    ).get("image_gen_task_id"):
                        fields.task = v
            return
        if "error" in line and line.get("error"):
            raise RuntimeError(line.get("error"))

    @classmethod
    async def synthesize(cls, params: dict) -> AsyncIterator[bytes]:
        async with StreamSession(impersonate="chrome", timeout=0) as session:
            async with session.get(
                f"{cls.url}/backend-api/synthesize", params=params, headers=cls._headers
            ) as response:
                await raise_for_status(response)
                async for chunk in response.iter_content():
                    yield chunk

    @classmethod
    async def login_generator(
        cls,
        proxy: str = None,
        api_key: str = None,
        proof_token: str = None,
        cookies: Cookies = None,

View on GitHub (pinned to 973504e177)

Solutions

  1. Log the error value — it carries the upstream reason string and dictates the remedy
  2. If session-related, re-authenticate and retry the prompt in a new conversation
  3. Shorten very long conversations/requests if the error fires near stream end
  4. Update g4f for the current stream error format

Example fix

// before
# error lost, no context
except RuntimeError: raise

// after
try:
    async for chunk in stream: process(chunk)
except RuntimeError as e:
    logging.error('OpenaiChat stream error payload: %s', e.args)
    raise
Defensive patterns

Strategy: try-catch

Type guard

def stream_line_has_error(line: dict) -> bool:
    return bool(line.get('error'))

Try / catch

try:
    async for chunk in stream:
        yield chunk
except RuntimeError as e:
    # e.args carries the in-band error payload from the stream
    logging.error('OpenaiChat stream aborted with: %s', e.args)
    if is_auth_related(e.args):
        await OpenaiChat.nodriver_auth()
    raise

Prevention

When it happens

Trigger: During iter_lines() of the conversation POST, any NDJSON line like {"error": {...}} — e.g. expired session mid-stream, content policy blocks, model errors, or deactivation of the conversation after it started.

Common situations: Long streams where the token expires before completion; moderation triggers mid-response; backend errors surfacing after a 200 OK start; concurrent use of the same session from two clients.

Related errors


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