iflytek/astron-agent · error · Exception

API request failed

Error message

API request failed: {status} - {result}

What it means

_make_request is the shared HTTP client for the RAGFlow REST API in ragflow_client.py. After performing the request it checks the status code: anything other than HTTP 200 raises Exception(f"API request failed: {status} - {result}"), embedding the status and the parsed response body so callers can see the server-side reason.

Solutions

  1. Read the status and body embedded in the message: 401 → fix RAGFLOW_API_TOKEN; 404 → verify ids/endpoint paths; 400 → fix request payload
  2. Confirm RAGFLOW_BASE_URL points to the correct RAGFlow version's API (path compatibility)
  3. Validate the dataset/document id exists via list_datasets before update/retrieval calls
  4. Check RAGFlow server logs for the corresponding 4xx/5xx to get the server-side error detail

Example fix

# before
await update_dataset(dataset_id, {"name": new_name})  # id from stale cache -> 404
# after
datasets = await list_datasets()
if any(d['id'] == dataset_id for d in datasets):
    await update_dataset(dataset_id, {"name": new_name})
Defensive patterns

Strategy: try-catch

Validate before calling

async def ensure_dataset_exists(client, dataset_id: str) -> bool:
    datasets = await client.list_datasets()
    return any(d.get('id') == dataset_id for d in datasets)

Try / catch

try:
    result = await retrieval(dataset_id, query)
except Exception as e:
    if str(e).startswith('API request failed:'):
        status = str(e).split(' - ')[0].rsplit(' ', 1)[-1]
        if status == '401':
            refresh_ragflow_token()
        elif status == '404':
            handle_missing_dataset(dataset_id)

Prevention

When it happens

Trigger: Calling retrieval, retrieval_with_dataset, list_datasets, create_dataset, update_dataset, or update_document when the RAGFlow server answers with a non-200 status — e.g. 401 for a bad token, 404 for an unknown endpoint/dataset, 4xx/5xx validation or server errors.

Common situations: Expired or wrong RAGFLOW_API_TOKEN (401); requesting a dataset/document id that does not exist (404); malformed payload rejected by the API (400); RAGFlow version mismatch where the endpoint path changed; RAGFlow server 5xx during overload.

Understand the failure class

Background: "API error: {status}" and "HTTP 401/403/404/429/5xx" errors: non-2xx HTTP responses explained — this error's family across 27 libraries.

Related errors


AI-assisted analysis of iflytek/astron-agent@5e758547a8 (2026-09-12). Data as JSON: /api/errors/120d5ac05812c945. Report an issue: GitHub.

Appendix: source

Thrown at core/knowledge/infra/ragflow/ragflow_client.py:345

    for attempt in range(max_retries):
        try:
            session = await _get_session()
            url = urljoin(config["base_url"], endpoint)

            if files:
                form_data = await _create_file_form_data(files)
                result, status = await _send_file_request(
                    session, method, url, form_data, config
                )
            else:
                result, status = await _send_json_request(
                    session, method, url, data, config
                )

            logger.debug(f"{method} {endpoint} - Status: {status}")

            if status != 200:
                raise Exception(f"API request failed: {status} - {result}")

            return result

        except (aiohttp.ClientConnectionError, RuntimeError) as e:
            if _is_session_closed_error(e):
                await _handle_session_error(attempt, max_retries, e)
                continue
            else:
                raise e
        except Exception as e:
            logger.error(f"Request failed: {method} {endpoint} - {e}")
            logger.error(f"Request URL: {url}")
            if data:
                logger.error(f"Request data: {data}")
            raise

    # This should never be reached due to exceptions being raised
    raise Exception("All retry attempts failed")

View on GitHub (pinned to 5e758547a8)