Content
# ReACT Intelligent Assistant
A smart assistant system based on OpenAI Agents SDK, implementing the ReACT reasoning mode (Reasoning and Acting), supporting multi-round tool calls, conversation history management, streaming responses, MCP tool integration, and a modern web user interface.
## 📋 Table of Contents
- [Features](#features)
- [Tech Stack](#tech-stack)
- [System Architecture](#system-architecture)
- [Quick Start](#quick-start)
- [Configuration Guide](#configuration-guide)
- [Usage Guide](#usage-guide)
- [Project Structure](#project-structure)
- [Development Guide](#development-guide)
- [FAQ](#faq)
- [License](#license)
## ✨ Features
### Core Features
- **🧠 ReACT Reasoning Mode**
- **Observe**: Carefully analyze user questions and current available information
- **Think**: Reason what actions need to be taken to solve the problem
- **Act**: Execute necessary operations using available tools
- **Memory**: Remember previous conversations and operation results
- **🔧 Multi-Round Tool Calls**
- Support multi-step tool calls for complex tasks
- Automatically integrate results of multiple tool calls
- Intelligent decision-making on when to continue calling tools
- **💾 Conversation History Management**
- Use Redis to store conversation history
- Automatically save and load conversation history
- Maintain context continuity across multiple sessions
- **Multi-Session Management**: Support creating, switching, and deleting multiple independent sessions
- **⚡ Streaming Responses**
- Real-time output generation
- Typewriter-like interactive experience
- Reduced first-byte response time
- **🔌 Custom Model Providers**
- Flexible configuration of OpenAI or compatible service APIs
- Support custom base URL
- Support multiple model choices
- **🛠️ MCP Tool Integration**
- Support stdio protocol (standard input/output)
- Support SSE protocol (Server-Sent Events)
- Support StreamableHTTP protocol
- Support timeout configuration for SSE and StreamableHTTP
- Dynamic loading and management of tool servers
- **🌐 Web Interface**
- Modern web user interface (similar to ChatGPT)
- Multi-session management (create, switch, delete)
- Real-time streaming response display
- Visualization of tool calls and outputs
- WebSocket real-time communication
- **Markdown Rendering**: Assistant messages support complete Markdown format rendering
- Basic formats: headers, paragraphs, lists
- Code block syntax highlighting (supporting multiple programming languages)
- Tables, quotes, links, and other advanced formats
- GitHub Flavored Markdown support
- Streaming Markdown rendering (real-time updates)
### Technical Highlights
- ✅ Asynchronous IO design for efficient concurrent operation handling
- ✅ Modular architecture for easy extension and maintenance
- ✅ Complete error handling and resource cleanup mechanisms
- ✅ Elegant command-line interaction interface
- ✅ Modern web user interface (React + TypeScript + Tailwind CSS)
- ✅ Complete unit test coverage
- ✅ Type annotations and docstrings
## 🛠️ Tech Stack
### Backend
- **Python 3.8+**
- **OpenAI Agents SDK** - Agent framework and tool integration
- **FastAPI/WebSockets** - WebSocket server
- **Redis** - Session storage (required)
- **Pydantic** - Configuration validation
- **python-dotenv** - Environment variable management
### Frontend
- **React 18** - UI framework
- **TypeScript** - Type safety
- **Tailwind CSS** - Style framework
- **Vite** - Build tool
- **react-markdown** - Markdown rendering
- **remark-gfm** - GitHub Flavored Markdown support
- **react-syntax-highlighter** - Code block syntax highlighting
## 🏗️ System Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ User Interaction Layer │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Command Line Interface CLI │ │ Web Interface │ │
│ │ (main.py) │ │ (React + TS) │ │
│ └──────────────────┘ └──────────────────┘ │
└────────────────────────┬───────────────────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ WebSocket │ │ CLI Interface │ │ Web API │
│ Server │ │ │ │ (web_api) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────┼───────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Agent Core Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ ReACT Reasoning │ │ Tool Calls │ │ Streaming Output │ │
│ │ Engine │ │ Manager │ │ Processor │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Model Provider │ │ Session Management │ │ MCP Tool Integration│
│ (Custom │ │ (Redis) │ │ (stdio/sse/ │
│ Provider) │ │ │ │ http) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────┼───────────────┘
▼
┌─────────────────────────────────────────────────────────────┐
│ Configuration Management Layer │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ .env Config │ │ mcp_config │ │
│ │ Loader │ │ .json Loader │ │
│ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
## 🚀 Quick Start
### Requirements
- **Python 3.8+**
- **Redis** (required for session storage)
- **Node.js 16+** (only required for web interface)
- **npm** or **yarn** (only required for web interface)
### Installation Steps
1. **Clone Project**
```bash
git clone <repository-url>
cd react-agent-assistant
```
2. **Install and Start Redis**
```bash
# Windows (using Chocolatey)
choco install redis-64
# macOS (using Homebrew)
brew install redis
brew services start redis
# Linux (Ubuntu/Debian)
sudo apt-get install redis-server
sudo systemctl start redis-server
# Verify Redis is running
redis-cli ping
# Should return: PONG
```
3. **Install Backend Dependencies**
```bash
# Create virtual environment (recommended)
python -m venv .venv
# Activate virtual environment
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate
# Install dependencies
pip install -r requirements.txt
```
4. **Install Frontend Dependencies** (only required for web interface)
```bash
cd web
npm install
cd ..
```
5. **Configure Environment Variables**
```bash
# Copy example configuration file
cp .env.example .env
# Edit .env file to set your API key and configuration
```
6. **Configure MCP Tools** (optional)
```bash
# Copy example configuration file
cp mcp_config.example.json mcp_config.json
# Edit mcp_config.json to configure your MCP server
```
### Run Program
#### Method 1: Command Line Interface (CLI)
```bash
python main.py
```
#### Method 2: Web Interface
1. **Start Backend WebSocket Server**:
```bash
python web_main.py
```
Server runs on `ws://localhost:8000` by default.
2. **Start Frontend Development Server** (in a new terminal window):
```bash
cd web
npm run dev
```
Frontend runs on `http://localhost:5173` (Vite default port) by default.
3. **Access Web Interface**:
Open a browser and navigate to `http://localhost:5173`
## ⚙️ Configuration Guide
### 1. Environment Variable Configuration
Create `.env` file (copy from `.env.example`):
```env
# OpenAI API configuration
OPENAI_API_KEY=your_api_key_here # Required: Your API key
OPENAI_BASE_URL=https://api.openai.com/v1 # Required: API base URL
OPENAI_MODEL=gpt-4 # Required: Model name
# Redis configuration (required)
REDIS_URL=redis://localhost:6379/0 # Required: Redis connection URL
# Web service configuration (optional)
WEB_PORT=8000 # WebSocket server port (default 8000)
WEB_HOST=localhost # WebSocket server host (default localhost)
```
**Configuration Description:**
| Config Item | Description | Example |
|-------------|-------------|---------|
| `OPENAI_API_KEY` | OpenAI API key or compatible service key | `sk-...` |
| `OPENAI_BASE_URL` | API endpoint URL | `https://api.openai.com/v1` |
| `OPENAI_MODEL` | Model name | `gpt-4`, `gpt-4-turbo`, `gpt-3.5-turbo` |
| `REDIS_URL` | **Required** Redis connection URL | `redis://localhost:6379/0` |
| `WEB_PORT` | (Optional) WebSocket server port | `8000` |
| `WEB_HOST` | (Optional) WebSocket server host | `localhost` |
**Using Other API Services:**
If you are using a compatible service other than OpenAI, simply modify `OPENAI_BASE_URL`:
```env
OPENAI_BASE_URL=https://your-api-service.com/v1
```
### 2. MCP Tool Configuration
Create `mcp_config.json` file (copy from `mcp_config.example.json`):
```json
{
"servers": [
{
"name": "filesystem",
"protocol": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"]
},
{
"name": "weather",
"protocol": "sse",
"url": "http://localhost:8000/sse",
"timeout": 30
},
{
"name": "calculator",
"protocol": "streamablehttp",
"url": "http://localhost:8000/mcp",
"timeout": 30
}
]
}
```
**Protocol Description:**
| Protocol | Description | Required Fields | Optional Fields | Applicable Scenarios |
|----------|----------|----------------|----------------|---------------|
| `stdio` | Communication through standard input/output | `command`, `args` | `env` | Local command-line tools |
| `sse` | Communication through Server-Sent Events | `url` | `timeout`, `env` | SSE-supported HTTP services |
| `streamablehttp` | Communication through HTTP streaming requests | `url` | `timeout`, `env` | Standard HTTP API services |
**Timeout Configuration:**
- `timeout`: Timeout time (seconds), only applicable to SSE and StreamableHTTP protocols
- If not configured, default timeout or infinite wait will be used (depending on protocol implementation)
**Note:** If MCP tools are not needed, you can delete the `mcp_config.json` file or set the `servers` array to empty `[]`.
## 📖 Usage Guide
### CLI Interface Usage
After starting, you will see the welcome interface:
```
============================================================
Welcome to ReACT Intelligent Assistant!
============================================================
This is a smart assistant based on the ReACT reasoning mode,
capable of:
• Observing and understanding your questions
• Reasoning solutions
• Using tools to execute operations
• Remembering conversation history
Type 'exit' or 'quit' to exit the program
Type Ctrl+C to exit at any time
============================================================
You:
```
### Web Interface Usage
#### Session Management
- **Create New Session**: Click the "New Session" button on the left
- **Switch Sessions**: Click any session in the session list on the left
- **Delete Session**: Click the delete button on the right side of the session (will delete all chat records of the session)
- **Default Session**: A default session is automatically created upon first access
#### Send Messages
- Enter your question in the bottom input box
- Press `Enter` or click the "Send" button to send the message
- AI assistant will respond in real-time streaming, presenting a typewriter-like effect
#### Message Display
- **User Messages**: Displayed on the right, blue background
- **Assistant Messages**: Displayed on the left, white background
- Support complete Markdown format rendering
- Code blocks automatically highlight syntax
- Tables, lists, links, and other formats are displayed friendly
- **Tool Calls**: Displayed as independent cards
- Tool call cards: Display tool name and call parameters (default collapsed)
- Tool output cards: Display tool execution results (default collapsed)
- Status indication: Display "Processing..." or "Completed"
#### Markdown Rendering
Assistant messages support the following Markdown formats:
- **Headers**: `# H1`, `## H2`, `### H3`
- **Lists**: Ordered and unordered lists
- **Code Blocks**: Automatic syntax highlighting (supporting multiple programming languages)
- Use three backticks to wrap code blocks
- Specify language type: ```python
- **Inline Code**: Use single backticks to wrap
- **Links**: Automatically recognize and render as clickable links
- **Tables**: Support GitHub Flavored Markdown tables
- **Quotes**: Use `>` to mark quoted content
- **Bold/Italic**: `**bold**`, `*italic*`
## 📁 Project Structure
```
react-agent-assistant/
├── src/ # Backend source code
│ ├── agent_core.py # Agent core logic (ReACT reasoning)
│ ├── cli.py # CLI interface
│ ├── config.py # Configuration management
│ ├── mcp_manager.py # MCP tool manager
│ ├── model_provider.py # Model provider
│ ├── session_manager.py # Session manager
│ └── web_api.py # WebSocket API service
├── web/ # Frontend source code
│ ├── src/
│ │ ├── components/ # React components
│ │ │ ├── ChatWindow.tsx # Chat window component
│ │ │ ├── MessageInput.tsx # Message input component
│ │ │ └── SessionList.tsx # Session list component
│ │ ├── services/ # Service layer
│ │ │ └── websocket.ts # WebSocket client
│ │ ├── types/ # TypeScript type definitions
│ │ ├── App.tsx # Main application component
│ │ └── main.tsx # Entry file
│ ├── package.json # Frontend dependency configuration
│ └── vite.config.ts # Vite build configuration
├── tests/ # Unit tests
├── openspec/ # OpenSpec specification document
├── main.py # CLI entry point
├── web_main.py # Web service entry point
├── requirements.txt # Python dependencies
├── mcp_config.json # MCP tool configuration
└── README.md # Project documentation
```
## 🛠️ Development Guide
### Backend Development
1. **Run tests**:
```bash
pytest
```
2. **Code formatting**:
The project uses the Python standard code style. It is recommended to use `black` or `autopep8` to format the code.
### Frontend Development
1. **Development mode**:
```bash
cd web
npm run dev
```
2. **Build production version**:
```bash
cd web
npm run build
```
3. **Preview production build**:
```bash
cd web
npm run preview
```
4. **Code linting**:
```bash
cd web
npm run lint
```
### Adding new MCP tools
1. Add server configuration in `mcp_config.json`
2. Configure corresponding fields according to protocol type
3. Restart the service to use the new tool
### Customizing Markdown styles
Markdown style definitions are located in the `components` property of the `ReactMarkdown` component in `web/src/components/ChatWindow.tsx`. You can modify Tailwind CSS classes to customize styles.
## ❓ Frequently Asked Questions
### Web interface cannot connect
1. Ensure the backend WebSocket server is running (`python web_main.py`)
2. Check if the `WEB_PORT` environment variable matches the frontend configuration
3. Check for error messages in the browser console
### MCP tools cannot load
1. Check if the `mcp_config.json` file format is correct
2. For stdio protocol, ensure the command and parameters are correct
3. For SSE/StreamableHTTP protocol, ensure the URL is accessible and timeout configuration is reasonable
4. View backend logs for detailed error information
### Session history lost
1. Ensure the Redis service is running
2. Check if the Redis connection URL is correct (`REDIS_URL` environment variable)
3. Check if the Redis service is accessible
4. View backend logs for detailed error information
### Markdown rendering issues
1. Ensure frontend dependencies are correctly installed (`npm install`)
2. Check for JavaScript errors in the browser console
3. Code block syntax highlighting requires specifying the language type
## 📄 License
[This open-source software follows the MIT license]
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Agent-Reach
Give your AI agent eyes to see the entire internet. Read & search Twitter,...