# How to Troubleshoot API Connection Issues in GPT Academic: A Complete Guide

> Troubleshoot API connection issues in GPT Academic by verifying API keys proxy settings and timeout configurations. Resolve common problems with our complete guide.

- Repository: [binary-husky/gpt_academic](https://github.com/binary-husky/gpt_academic)
- Tags: how-to-guide
- Published: 2026-03-02

---

**To fix API connection issues in GPT Academic, verify your API key format in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py), ensure proxy settings include "Connect_OpenAI" in `WHEN_TO_USE_PROXY`, and check that `TIMEOUT_SECONDS` and `MAX_RETRY` values accommodate your network conditions.**

GPT Academic (binary-husky/gpt_academic) connects to large language model services through a thin HTTP wrapper built on Python's `requests` library. When API connections fail, the error typically surfaces in [`request_llms/bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/request_llms/bridge_chatgpt.py) with symptoms ranging from timeout errors to invalid key messages. This guide walks through the exact source code locations and configuration parameters you need to inspect to restore connectivity.

## Verify Your API Key Configuration

### Check Key Format and Validation

GPT Academic validates API keys using regex patterns defined in [`shared_utils/key_pattern_manager.py`](https://github.com/binary-husky/gpt_academic/blob/main/shared_utils/key_pattern_manager.py). For standard OpenAI keys, the system expects the pattern `^sk-[A-Za-z0-9]{48}$`.

```python

# shared_utils/key_pattern_manager.py

openai_regex = re.compile(r'^sk-[A-Za-z0-9]{48}$')
def is_openai_api_key(key):
    return bool(openai_regex.match(key))

```

If your key fails this validation, the framework treats it as "no key" and aborts with an "Incorrect API key" message. Verify your key matches the expected format for your provider—DashScope keys use `^dsk-.*`, while Azure keys follow a different pattern entirely.

### Handle Multiple Keys and Environment Variables

The [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py) file supports comma-separated key lists (`API_KEY = "key1,key2"`). The system selects the first key matching the selected model's pattern. Ensure your intended key appears before any incompatible keys in the list.

GPT Academic also reads `API_KEY` from environment variables before falling back to [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py):

```bash
export API_KEY="sk-…"

```

Confirm the environment variable is actually set by running `echo $API_KEY` in your terminal, and verify it matches the regex pattern expected by `is_openai_api_key()`.

## Configure Proxy Settings Correctly

The proxy configuration only routes OpenAI-related traffic when `"Connect_OpenAI"` appears in the `WHEN_TO_USE_PROXY` list (defined in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py)). If this string is missing, the system ignores proxy settings entirely.

```python

# toolbox.py – get_conf(...)

if "Connect_OpenAI" not in WHEN_TO_USE_PROXY:
    if proxies is not None:
        logger.error("虽然您配置了代理设置，但不会在连接OpenAI的过程中起作用，请检查WHEN_TO_USE_PROXY配置。")
        proxies = None

```

Common proxy configuration errors include:

- **Missing scheme**: Use `http://` or `socks5h://` prefixes (e.g., `socks5h://localhost:11284`)
- **Port conflicts**: Verify the proxy port matches your running proxy service
- **Authentication**: If your proxy requires auth, include credentials in the URL (`http://user:pass@host:port`)

Test your proxy independently before relying on it in GPT Academic:

```bash
curl -x socks5h://localhost:11284 https://api.openai.com/v1/models

```

## Validate Endpoint Configuration

### Check for Placeholder Values

Azure deployments often fail because the `AZURE_ENDPOINT` placeholder remains set to the default Chinese string `"你亲手写的api名称"` (meaning "the API name you wrote yourself"). The `verify_endpoint()` function in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) (lines 18-26) explicitly checks for this placeholder and raises a `ValueError` if found.

```python

# request_llms/bridge_chatgpt.py

def verify_endpoint(endpoint):
    if "你亲手写的api名称" in endpoint:
        raise ValueError("请配置AZURE_ENDPOINT")
    return endpoint

```

### Test Endpoint Accessibility

If using custom endpoints via `API_URL_REDIRECT` (defined in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py) lines 79-82), verify the redirect mapping is correct:

```python

# bridge_all.py – endpoint selection logic

openai_endpoint = "https://api.openai.com/v1/chat/completions"
if API_URL != "https://api.openai.com/v1/chat/completions":
    openai_endpoint = API_URL
if openai_endpoint in API_URL_REDIRECT:
    openai_endpoint = API_URL_REDIRECT[openai_endpoint]

```

Test the resolved endpoint directly:

```python
from request_llms.bridge_chatgpt import verify_endpoint
print(verify_endpoint("https://api.openai.com/v1/chat/completions"))

```

If this raises an exception, your configuration contains invalid endpoint strings.

## Adjust Timeout and Retry Logic

`TIMEOUT_SECONDS` (default 30 seconds) controls the `requests.post(..., timeout=TIMEOUT_SECONDS)` parameter. When timeouts occur, the wrapper retries up to `MAX_RETRY` times (default 2).

```python

# request_llms/bridge_chatgpt.py – retry loop (lines 52-62)

except requests.exceptions.ReadTimeout as e:
    retry += 1
    if retry > MAX_RETRY:
        raise TimeoutError
    logger.error(f'请求超时，正在重试 ({retry}/{MAX_RETRY}) ……')

```

Adjust these parameters in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py) based on your network conditions:

- **High latency connections**: Increase `TIMEOUT_SECONDS` to 60 or 120
- **Unstable networks**: Increase `MAX_RETRY` to 3 or 5
- **Debugging**: Temporarily set `MAX_RETRY = 0` to see immediate errors without retry masking

## Debug Stream Parsing Errors

Third-party bridges (e.g., `api2d.net`, One-API) sometimes return malformed JSON or non-standard SSE formats. The `decode_chunk()` function in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) (lines 99-115) attempts to parse these streams and validates required fields (`choices`, `content`, `role`).

If a bridge returns an unexpected schema, the loop skips chunks (`continue`) and may eventually raise `RuntimeError("OpenAI拒绝了请求：" + error_msg)`.

To diagnose:

1. Enable verbose logging by adding `logger.info(chunk_decoded)` around line 80 in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py)
2. Compare the raw payload against OpenAI's expected format
3. If using a non-OpenAI bridge, verify [`request_llms/bridge_all.py`](https://github.com/binary-husky/gpt_academic/blob/main/request_llms/bridge_all.py) correctly rewrites the `endpoint` and `payload` for that provider's `model_info` entry

## Diagnostic Script for Systematic Troubleshooting

Run this comprehensive diagnostic to isolate configuration problems:

```python
import os
import json
import requests
from toolbox import get_conf
from request_llms.bridge_chatgpt import verify_endpoint, generate_payload
from shared_utils.key_pattern_manager import is_openai_api_key

def diagnose():
    # 1️⃣ Show effective configuration

    conf_keys = ['API_KEY', 'PROXIES', 'TIMEOUT_SECONDS', 'MAX_RETRY',
                 'WHEN_TO_USE_PROXY', 'API_URL_REDIRECT', 'AZURE_ENDPOINT']
    values = get_conf(*conf_keys)
    print("\n--- Effective Config ---")
    for k, v in zip(conf_keys, values):
        print(f"{k}: {v}")

    # 2️⃣ Validate API key format

    api_keys = os.getenv("API_KEY", "").split(",")
    if not api_keys or api_keys == ['']:
        api_keys = values[0].split(",")  # Fallback to config.py value

    
    print("\n--- Key Validation ---")
    for k in api_keys:
        if k:
            print(f"Key {k[:6]}… valid? {is_openai_api_key(k)}")

    # 3️⃣ Verify endpoint

    try:
        endpoint = verify_endpoint("https://api.openai.com/v1/chat/completions")
        print("\nEndpoint OK:", endpoint)
    except ValueError as e:
        print("\nEndpoint Error:", e)

    # 4️⃣ Send a tiny test request (no stream) with a 5‑second timeout

    print("\n--- Network Test ---")
    if api_keys and api_keys[0]:
        headers = {"Authorization": f"Bearer {api_keys[0]}", "Content-Type": "application/json"}
        payload = {"model": "gpt-3.5-turbo", "messages": [{"role":"user","content":"ping"}]}
        try:
            proxies = values[1] if values[1] else None
            r = requests.post("https://api.openai.com/v1/chat/completions", 
                            headers=headers, json=payload,
                            timeout=5, proxies=proxies)
            print("HTTP status:", r.status_code)
            print("Response snippet:", r.text[:200])
        except Exception as e:
            print("Test request failed:", e)
    else:
        print("No valid API key available for test")

if __name__ == "__main__":
    diagnose()

```

This script validates configuration against the actual source code logic, prints the effective proxy settings, and attempts a minimal HTTP request to isolate network versus configuration issues.

## Summary

- **API key validation** happens in [`shared_utils/key_pattern_manager.py`](https://github.com/binary-husky/gpt_academic/blob/main/shared_utils/key_pattern_manager.py) using regex patterns; ensure your key matches the expected format for your provider (OpenAI keys start with `sk-` followed by 48 alphanumeric characters).
- **Proxy activation** requires `"Connect_OpenAI"` in the `WHEN_TO_USE_PROXY` list; without this string, the `proxies` dictionary is ignored entirely.
- **Endpoint verification** occurs in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py); remove placeholder strings like `"你亲手写的api名称"` from Azure configurations and validate any `API_URL_REDIRECT` mappings.
- **Timeout handling** uses `TIMEOUT_SECONDS` (default 30s) and `MAX_RETRY` (default 2); increase these values for high-latency networks or unstable connections.
- **Stream parsing** errors indicate third-party bridge incompatibility; inspect raw chunks in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) to verify JSON schema compliance.

## Frequently Asked Questions

### Why do I get "Incorrect API key" even with a valid key?

This error typically triggers when `shared_utils/key_pattern_manager.is_openai_api_key()` returns `False` because your key does not match the expected regex pattern. OpenAI keys must match `^sk-[A-Za-z0-9]{48}$`. Additionally, if you have multiple keys in a comma-separated list, ensure the first key in `API_KEY` matches the model you are using, as the system selects the first valid key for the specific provider.

### How do I fix "Request timeout" errors in GPT Academic?

Increase the `TIMEOUT_SECONDS` value in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py) from the default 30 seconds to 60 or 120 seconds if you have high network latency. The timeout occurs in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) where `requests.post()` is called with `timeout=TIMEOUT_SECONDS`. Also verify that `MAX_RETRY` is set to a positive integer (default is 2) so the system attempts retries before failing completely.

### Why is my proxy configuration being ignored?

The proxy only activates for OpenAI connections when the string `"Connect_OpenAI"` appears in the `WHEN_TO_USE_PROXY` list in [`config.py`](https://github.com/binary-husky/gpt_academic/blob/main/config.py). If this string is missing, [`toolbox.py`](https://github.com/binary-husky/gpt_academic/blob/main/toolbox.py) explicitly sets `proxies = None` and logs a warning that the proxy will not be used for OpenAI connections. Additionally, ensure your proxy URL includes the proper scheme (`http://` or `socks5h://`) and that the port matches your running proxy service.

### How do I troubleshoot third-party API bridges in GPT Academic?

Third-party bridges (like One-API or API2D) often return non-standard JSON schemas that cause `decode_chunk()` in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) to skip chunks or raise `RuntimeError`. To diagnose, temporarily add logging around line 80 in [`bridge_chatgpt.py`](https://github.com/binary-husky/gpt_academic/blob/main/bridge_chatgpt.py) to print `chunk_decoded` values. Verify that the response contains the expected fields (`choices`, `delta`, `content`). If the schema differs, check [`request_llms/bridge_all.py`](https://github.com/binary-husky/gpt_academic/blob/main/request_llms/bridge_all.py) to ensure the `model_info` entry for your provider correctly rewrites the endpoint and payload structure.