# GPT Academic User Guide

GPT Academic is a Gradio-based web UI providing academic writing, programming productivity, and research tools powered by large language models. It supports GPT, Claude, Gemini, Qwen, DeepSeek, and local models through a unified interface with a rich plugin ecosystem.

---

## 1. Quick Start

### Fastest Path to Running

```bash
# Clone the repository
git clone https://github.com/binary-husky/gpt_academic.git
cd gpt_academic

# Install dependencies
pip install -r requirements.txt

# Create your private config
cp config.py config_private.py
# Edit config_private.py — set at minimum API_KEY

# Launch
python main.py
```

The web UI opens automatically in your browser (unless `AUTO_OPEN_BROWSER = False`).

> [!TIP]
> If you only need basic GPT functionality, the minimum configuration is setting `API_KEY` in `config_private.py`. Everything else has sensible defaults.

### Docker Quick Start

```bash
git clone https://github.com/binary-husky/gpt_academic.git
cd gpt_academic
docker-compose up -d
```

Edit environment variables or mount a `config_private.py` into the container for configuration.

---

## 2. Installation

### System Requirements

| Requirement | Detail |
|---|---|
| Python | 3.9+ |
| OS | Windows, Linux, macOS |
| RAM | 2 GB minimum (more for local models) |
| Network | Internet access for cloud LLM APIs |
| Gradio | Exactly `3.32.15` (custom wheel, installed via requirements.txt) |

### Step-by-Step Installation

#### 1. Clone the Repository

```bash
git clone https://github.com/binary-husky/gpt_academic.git
cd gpt_academic
```

#### 2. Install Python Dependencies

```bash
pip install -r requirements.txt
```

> [!IMPORTANT]
> The project requires a specific custom build of Gradio (`3.32.15`). Do NOT upgrade Gradio independently — the custom wheel is referenced in `requirements.txt` and provides features the UI depends on. Installing a different Gradio version will cause `AttributeError: module 'gradio' has no attribute 'Floating'` and similar failures.

#### 3. Create Private Configuration

```bash
cp config.py config_private.py
```

Edit `config_private.py` with your API keys and preferences. This file is gitignored and overrides `config.py`.

#### 4. Launch

```bash
python main.py
```

The application starts a Gradio web server. By default it selects a random port (set `WEB_PORT` to fix it).

### Docker Installation

The repository includes `Dockerfile` and `docker-compose.yml` at the root:

```bash
docker-compose up -d
```

For custom configuration in Docker, either:
- Pass environment variables via `docker-compose.yml`
- Mount your `config_private.py` as a volume into the container

### Optional Dependencies

Some plugins require additional packages:

| Feature | Extra Dependency |
|---|---|
| PDF processing | `pymupdf` (included in requirements.txt) |
| LaTeX tools | A LaTeX distribution (e.g., TeX Live, MiKTeX) installed on the system |
| Text-to-Speech | `edge-tts` (included) or Aliyun SDK |
| Knowledge base / RAG | `llama-index`, `spacy` |
| ArXiv tools | `arxiv` (included) |
| Web scraping | `beautifulsoup4` (included) |
| Grobid PDF parsing | Running Grobid server (configure `GROBID_URLS`) |

---

## 3. Configuration

### Configuration Priority

Settings are resolved in this order (highest priority first):

1. **Environment variables** — override everything
2. **`config_private.py`** — your personal overrides (gitignored)
3. **`config.py`** — project defaults (tracked in git)

> [!NOTE]
> Never edit `config.py` directly for your local setup. Always create `config_private.py` with only the settings you want to change. This prevents merge conflicts on updates.

### Essential Settings

#### API Keys

```python
# Primary OpenAI-compatible key (comma-separate for round-robin load balancing)
API_KEY = "sk-xxxxxxxxxxxxxxxxxxxx"

# Or multiple keys for rotation:
API_KEY = "sk-key1,sk-key2,sk-key3"
```

Model-specific keys (set only those you use):

```python
ANTHROPIC_API_KEY = ""        # Claude models
GEMINI_API_KEY = ""           # Google Gemini
DASHSCOPE_API_KEY = ""        # Alibaba Qwen
DEEPSEEK_API_KEY = ""         # DeepSeek R1
ZHIPUAI_API_KEY = ""          # Zhipu/ChatGLM
MOONSHOT_API_KEY = ""         # Moonshot/Kimi
BAIDU_CLOUD_API_KEY = ""      # Baidu ERNIE
DOC2X_API_KEY = ""            # Doc2X PDF service
```

#### Model Selection

```python
# Default model used on startup
LLM_MODEL = "gpt-3.5-turbo-16k"

# Models available in the UI dropdown
AVAIL_LLM_MODELS = [
    "gpt-4-1106-preview", "gpt-4-turbo", "gpt-3.5-turbo-16k",
    "claude-3-opus-20240229", "claude-3-sonnet-20240229",
    "gemini-pro", "qwen-turbo", "deepseek-chat"
]
```

#### Network & Proxy

```python
# Set True if you need a proxy to reach APIs
USE_PROXY = False
proxies = {
    "http": "socks5h://localhost:10880",
    "https": "socks5h://localhost:10880",
}

# Redirect API URLs (useful for custom endpoints / Azure)
API_URL_REDIRECT = {}
# Example: API_URL_REDIRECT = {"https://api.openai.com/v1/chat/completions": "https://my-proxy.com/v1/chat/completions"}
```

#### Performance

```python
DEFAULT_WORKER_NUM = 8    # Concurrent LLM request threads
TIMEOUT_SECONDS = 30      # Per-request timeout
MAX_RETRY = 2             # Retry count on failure
CONCURRENT_COUNT = 100    # Gradio concurrent threads
```

### UI Settings

```python
THEME = "Default"              # Options: "Default", "Chuanhu-Small-and-Beautiful", "High-Contrast"
DARK_MODE = True               # Dark theme
LAYOUT = "LEFT-RIGHT"          # "LEFT-RIGHT" or "TOP-DOWN"
AUTO_OPEN_BROWSER = True       # Open browser on launch
WEB_PORT = -1                  # -1 for random, or specify e.g. 7860
ADD_WAIFU = False              # Live2D decoration
NUM_CUSTOM_BASIC_BTN = 4      # Number of custom function buttons
```

### Authentication

```python
# Empty list = no authentication (open access)
AUTHENTICATION = []

# Add username/password pairs to require login:
AUTHENTICATION = [("user1", "pass1"), ("user2", "pass2")]
```

### HTTPS / Deployment

```python
SSL_KEYFILE = ""      # Path to SSL key file
SSL_CERTFILE = ""     # Path to SSL certificate file
CUSTOM_PATH = ""      # Sub-path for reverse proxy deployment (e.g., "/academic")
```

### Audio & TTS

```python
ENABLE_AUDIO = False           # Aliyun real-time speech recognition
TTS_TYPE = "EDGE_TTS"         # "EDGE_TTS", "LOCAL_SOVITS_API", or "DISABLE"
```

### Plugin Groups

```python
# Plugin groups shown by default in the UI
DEFAULT_FN_GROUPS = ['对话', '编程', '学术', '智能体']
```

### Embedding (for RAG / Knowledge Base)

```python
EMBEDDING_MODEL = "text-embedding-3-small"
```

### Advanced: SearXNG Integration

```python
# For internet search plugin — point to your SearXNG instance(s)
SEARXNG_URLS = []
```

---

## 4. Core Usage

### UI Layout

The default **LEFT-RIGHT** layout:

| Left Panel | Right Panel |
|---|---|
| Chat display area | Input text box |
| Conversation history | Basic function buttons |
| | Plugin area with group tabs |
| | File upload zone |

Switch to **TOP-DOWN** layout by setting `LAYOUT = "TOP-DOWN"` for a vertical arrangement.

### Basic Conversation

1. Type your question or text in the input box
2. Press Enter or click Submit
3. The response streams in the chat panel on the left
4. Switch models anytime via the model dropdown

### Core Function Buttons

The basic area provides one-click academic tools. Select text in the input box, then click:

| Button | Function |
|---|---|
| 学术语料润色 | Academic text polishing — rewrites for scholarly tone and clarity |
| 总结绘制脑图 | Summarize content and generate a Mermaid mindmap diagram |
| 查找语法错误 | Grammar checking with corrections and explanations |
| 中译英 | Chinese-to-English translation |
| 学术英中互译 | Academic bidirectional English-Chinese translation |
| 解释代码 | Explain code with comments and logic breakdown |
| 参考文献转Bib | Convert reference lists to BibTeX format |

### Custom Buttons

Up to 4 custom buttons (configurable via `NUM_CUSTOM_BASIC_BTN`) can be defined for your own frequent prompts.

### Model Switching

Use the model dropdown to switch between any model in your `AVAIL_LLM_MODELS` list. The switch takes effect on the next message — no restart required.

### Multi-Model Comparison

The "多模型并行查询" (Multi-Model Parallel Query) plugin sends the same prompt to multiple models simultaneously and displays results side-by-side for comparison.

### File Upload

Upload files using the file upload zone in the right panel. Supported workflows:

- Upload PDF files for translation, summary, or Q&A
- Upload source code directories (as zip) for analysis
- Upload Word documents for summarization
- Upload images for vision-capable models

---

## 5. Common Tasks

### Academic Writing

#### Polish a Paper Draft

1. Paste your text into the input box
2. Click **学术语料润色** (Academic Polish)
3. The model returns refined text with scholarly tone improvements

#### Translate a Paper

1. Upload the PDF via the file upload zone
2. In the plugin area, select the **学术** (Academic) group
3. Click **PDF翻译** (PDF Translation)
4. Select target language when prompted
5. The translated document is generated and available for download

#### LaTeX Proofreading

1. Paste your LaTeX source or upload `.tex` files
2. Use the **LaTeX英文润色** or **LaTeX中文润色** plugin
3. Returns corrected LaTeX with tracked changes in comments

#### Generate BibTeX

1. Paste a list of references (any common citation format)
2. Click **参考文献转Bib**
3. Receive formatted BibTeX entries

#### ArXiv Paper Translation

1. In the plugin area (学术 group), select **Arxiv论文翻译**
2. Provide the ArXiv paper ID or URL
3. The paper is fetched, parsed, and translated

### Programming Tasks

#### Analyze a Code Project

1. Upload a zip file containing source code, or point to a local directory path
2. In the **编程** (Programming) plugin group, select the appropriate language analyzer:
   - 解析Python项目 (Python)
   - 解析C++项目 (C/C++)
   - 解析Java项目 (Java)
   - 解析Go项目 (Go)
   - 解析Rust项目 (Rust)
   - 解析前端项目 (Frontend/JS/TS)
   - 解析Matlab项目 (Matlab)
   - 解析Jupyter项目 (Jupyter notebooks)
3. The tool reads every file, produces a structural analysis, and generates documentation

#### Generate Code Comments

1. Upload source files
2. Use **Python批量注释** or **批量函数注释生成** from the 编程 group
3. Returns annotated source with docstrings and inline comments

#### Explain Code

1. Paste code into the input box
2. Click **解释代码**
3. Receive a step-by-step explanation of logic, data flow, and purpose

### Research & Search

#### Internet Search

From the **对话** (Conversation) plugin group, use the internet search plugin. Requires `SEARXNG_URLS` configured to point to a SearXNG instance.

#### Google Scholar Search

In the **学术** group, use the Google Scholar plugin to find papers by topic, author, or keywords.

#### PDF Question & Answer

1. Upload a PDF
2. Select **PDF问答** from the 学术 group
3. Ask questions about the document content in natural language

### Agents & Advanced

#### Void Terminal

The **虚空终端** (Void Terminal) is a natural language command interface. Type commands in plain language and the agent interprets and executes multi-step workflows.

> [!TIP]
> Void Terminal is the most powerful plugin — it can chain other plugins, execute multi-step research, and perform complex tasks that no single button covers. Access it from the 对话 or 智能体 group.

#### Image Generation

From the 对话 group, use the image generation plugin with vision-capable models (requires appropriate API key and model support).

#### Mermaid Diagrams

Click **总结绘制脑图** to auto-generate Mermaid diagrams from any text. The diagrams render directly in the chat interface.

### Saving and Exporting

- **Save conversations** — use the conversation save plugin from the 对话 group to export chat history
- **Download generated files** — translated PDFs, analyzed reports, and other outputs appear as downloadable links in the chat

---

## 6. Troubleshooting

### Error: `ModuleNotFoundError: No module named 'pkg_resources'`

**Cause:** Python 3.12+ removed `pkg_resources` from the standard library. Some dependencies still import it.

**Solution:**
```bash
pip install setuptools
```

**Prevention:** Always run `pip install -r requirements.txt` which includes setuptools as a dependency.

---

### Error: `AttributeError: module 'gradio' has no attribute 'Floating'`

**Cause:** You have a standard Gradio install instead of the custom `3.32.15` wheel required by this project.

**Solution:**
```bash
pip uninstall gradio
pip install -r requirements.txt
```

**Prevention:** Never run `pip install --upgrade gradio`. The project depends on a patched version with custom components.

---

### Error: Connection Timeout / `TIMEOUT_SECONDS` exceeded

**Cause:** The LLM API is unreachable within the configured timeout (default 30 seconds).

**Solution:**
1. Check your network connection and proxy settings
2. Increase the timeout:
   ```python
   # In config_private.py
   TIMEOUT_SECONDS = 120
   ```
3. If behind a firewall, configure `USE_PROXY` and `proxies`

**Prevention:** Set `TIMEOUT_SECONDS` to at least 60 for large requests. Verify API endpoint reachability before first use.

---

### Error: API_KEY Format Validation Issues

**Cause:** The API key format does not match expected patterns, or keys contain extra whitespace.

**Solution:**
1. Verify there are no leading/trailing spaces in your key
2. For multiple keys, separate with commas only — no spaces:
   ```python
   API_KEY = "sk-key1,sk-key2"  # Correct
   API_KEY = "sk-key1, sk-key2"  # May cause issues
   ```
3. Ensure the key matches the model provider (OpenAI keys start with `sk-`, etc.)

**Prevention:** Copy-paste keys directly from your provider dashboard. Test with a single key first.

---

### Error: Google Gemini API Errors

**Cause:** Gemini API requires correct key format and may have regional restrictions.

**Solution:**
1. Verify `GEMINI_API_KEY` is set correctly in `config_private.py`
2. Ensure your Google Cloud project has the Gemini API enabled
3. Check regional availability — some regions require proxy access

---

### Error: Stream Response Truncation (finish_reason: null)

**Cause:** The streaming response was interrupted mid-generation, often due to network instability or server-side limits.

**Solution:**
1. Increase `TIMEOUT_SECONDS` to 120 or higher
2. Increase `MAX_RETRY` to 3:
   ```python
   MAX_RETRY = 3
   ```
3. Check if the input is excessively long — some models truncate at context limits

**Prevention:** Keep inputs within model context limits. Use models with larger context windows for long documents.

---

### Error: Claude / Anthropic API Errors for Overseas Users

**Cause:** Anthropic API has regional access restrictions.

**Solution:**
1. Verify `ANTHROPIC_API_KEY` is set (not the generic `API_KEY`)
2. Configure proxy if needed:
   ```python
   USE_PROXY = True
   proxies = {
       "http": "socks5h://localhost:10880",
       "https": "socks5h://localhost:10880",
   }
   ```
3. Or use `API_URL_REDIRECT` to route through an accessible endpoint

---

### Error: Knowledge Base Dependency Conflicts

**Cause:** The RAG/knowledge base plugins require `llama-index` and `spacy` which may conflict with other installed packages.

**Solution:**
1. Use a virtual environment:
   ```bash
   python -m venv venv
   source venv/bin/activate  # Linux/Mac
   # or: venv\Scripts\activate  # Windows
   pip install -r requirements.txt
   ```
2. If conflicts persist, install the knowledge base extras separately after base install

---

### General: UI Won't Load / Blank Page

**Cause:** Port conflict, or Gradio failed to start.

**Solution:**
1. Check terminal output for error messages
2. Try a specific port:
   ```python
   WEB_PORT = 7860
   ```
3. Kill any existing process on that port
4. Verify Gradio version is `3.32.15`:
   ```bash
   pip show gradio
   ```

> [!WARNING]
> If you see import errors related to Gradio components (`Floating`, `KeyUpData`, etc.), the wrong Gradio version is installed. Uninstall and reinstall from requirements.txt.

---

## 7. FAQ

**Q: What models does GPT Academic support?**

GPT Academic supports any OpenAI-compatible API, plus native integrations for: OpenAI GPT-3.5/4/4-Turbo, Anthropic Claude (all versions), Google Gemini, Alibaba Qwen (via DashScope), DeepSeek, Zhipu ChatGLM, Moonshot/Kimi, Baidu ERNIE, iFlytek Spark, and local models via compatible APIs. Configure the appropriate API key and add models to `AVAIL_LLM_MODELS`.

**Q: Can I use multiple API keys for load balancing?**

Yes. Set `API_KEY` to a comma-separated list of keys. The system rotates through them for each request, distributing load and avoiding rate limits.

**Q: How do I add a custom LLM endpoint (e.g., Azure OpenAI)?**

Use the `API_URL_REDIRECT` configuration:
```python
API_URL_REDIRECT = {
    "https://api.openai.com/v1/chat/completions": "https://your-azure-endpoint.openai.azure.com/..."
}
```

**Q: Is there authentication / multi-user support?**

Yes. Set `AUTHENTICATION` in `config_private.py`:
```python
AUTHENTICATION = [("alice", "password123"), ("bob", "securepass")]
```
Each user gets an isolated conversation session. Leave the list empty for open access.

**Q: Can I deploy this on a server for my team?**

Yes. Set `WEB_PORT` to a fixed port, configure `AUTHENTICATION` for user accounts, optionally set `SSL_KEYFILE`/`SSL_CERTFILE` for HTTPS, and use `CUSTOM_PATH` if deploying behind a reverse proxy. Docker deployment is also fully supported.

**Q: How do I use it in English instead of Chinese?**

The interface is primarily Chinese, but all LLM interactions work in any language. Type your prompts in English and responses will be in English. Plugin names remain in Chinese in the UI but their functionality is language-agnostic.

**Q: What is the Void Terminal?**

The Void Terminal (虚空终端) is a natural-language agent interface that interprets complex instructions and chains multiple plugins/actions to complete tasks. It is the most flexible way to interact with the system for multi-step workflows.

> [!CAUTION]
> The Void Terminal can execute complex chains of actions. Review its outputs carefully, especially when it processes files or makes external API calls.

**Q: How do I update to a new version?**

```bash
cd gpt_academic
git pull
pip install -r requirements.txt
```

Your `config_private.py` is gitignored and will not be overwritten. Review the updated `config.py` for any new settings you may want to add to your private config.

**Q: Can I run local models without any API keys?**

Yes, if you set up a local model server that exposes an OpenAI-compatible API (e.g., using llama.cpp server, Ollama, or vLLM). Point `API_URL_REDIRECT` to your local endpoint and add the model name to `AVAIL_LLM_MODELS`.

> [!NOTE]
> Local model support requires the model server to implement the OpenAI Chat Completions API format. Performance depends entirely on your hardware.

**Q: Why does PDF translation take so long?**

PDF translation involves parsing (via PyMuPDF or Grobid), segmenting, translating each segment through the LLM, and reassembling. Large PDFs with many pages naturally take time. Increase `DEFAULT_WORKER_NUM` to parallelize segment processing, and ensure `TIMEOUT_SECONDS` is high enough for long documents.

**Q: How do I enable text-to-speech?**

Set `TTS_TYPE` in your config:
```python
TTS_TYPE = "EDGE_TTS"  # Free, uses Microsoft Edge TTS
```
Options are `"EDGE_TTS"` (free, requires internet), `"LOCAL_SOVITS_API"` (requires local SoVITS server), or `"DISABLE"`.

---

_Generated May 2026 from binary-husky/gpt_academic at d6bde0f. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
