zlwu dd667101ef first commit há 1 ano atrás
..
src dd667101ef first commit há 1 ano atrás
venv dd667101ef first commit há 1 ano atrás
.DS_Store dd667101ef first commit há 1 ano atrás
.env dd667101ef first commit há 1 ano atrás
.env.example dd667101ef first commit há 1 ano atrás
Dockerfile dd667101ef first commit há 1 ano atrás
README.md dd667101ef first commit há 1 ano atrás
pyproject.toml dd667101ef first commit há 1 ano atrás
requirements.txt dd667101ef first commit há 1 ano atrás
run.py dd667101ef first commit há 1 ano atrás
使用豆包实时API说明.md dd667101ef first commit há 1 ano atrás
后端框架说明.md dd667101ef first commit há 1 ano atrás

README.md

Tolan Backend

AI-Powered English Conversation Backend with real-time voice chat capabilities.

Features

  • Real-time WebSocket Communication: Low-latency bidirectional communication
  • Doubao Realtime API Integration: ByteDance's real-time voice AI service
  • AI Integration: Support for Doubao (ByteDance) and OpenAI APIs
  • Audio Processing: Advanced audio format conversion and noise reduction
  • Session Management: Robust session lifecycle and cleanup
  • Rate Limiting: Configurable rate limiting and connection management
  • Monitoring: Structured logging and performance metrics
  • Scalable Architecture: Async/await design for high concurrency

Quick Start

Prerequisites

  • Python 3.9+
  • Virtual environment (recommended)
  • Audio processing dependencies (ffmpeg)

Installation

  1. Clone and navigate to backend directory:

    cd backend
    
    1. Create virtual environment: bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
  2. Install dependencies:

    pip install -r requirements.txt
    
    1. Install system dependencies (for audio processing): ```bash

      macOS

      brew install ffmpeg

    Ubuntu/Debian

    sudo apt update sudo apt install ffmpeg

    CentOS/RHEL

    sudo yum install ffmpeg ```

  3. Configure environment:

    cp .env.example .env
    # Edit .env with your API keys and configuration
    
    1. Run the server: bash python run.py

Configuration

Environment Variables

Copy .env.example to .env and configure the following:

Doubao Realtime API (Recommended)

# Doubao realtime voice conversation API
DOUBAO_APP_ID=your_doubao_app_id_here
DOUBAO_ACCESS_KEY=your_doubao_access_key_here
DOUBAO_BASE_URL=wss://openspeech.bytedance.com/api/v3/realtime/dialogue
DOUBAO_TTS_SPEAKER=zh_male_yunzhou_jupiter_bigtts

Alternative AI Services

# Doubao traditional API (backup)
DOUBAO_API_KEY=your_doubao_api_key_here
DOUBAO_MODEL=your_doubao_model_id_here

# OpenAI API (backup)
OPENAI_API_KEY=your_openai_api_key_here

Optional Configuration

# Server
HOST=0.0.0.0
PORT=8765
DEBUG=false

# Audio
MAX_AUDIO_DURATION=60
AUDIO_SAMPLE_RATE=24000

# Rate Limiting
RATE_LIMIT_PER_MINUTE=100
MAX_CONNECTIONS_PER_IP=10

# Security
CORS_ORIGINS=http://localhost:3000,https://yourdomain.com

Doubao Realtime API Setup

The backend now supports Doubao's real-time voice conversation API, which provides:

  • Real-time ASR (Automatic Speech Recognition)
  • Real-time TTS (Text-to-Speech)
  • Real-time conversation with AI
  • Low latency WebSocket communication

To use Doubao Realtime API:

  1. Get API credentials from ByteDance:

    • DOUBAO_APP_ID: Your application ID
    • DOUBAO_ACCESS_KEY: Your access key
  2. Configure in .env:

    DOUBAO_APP_ID=9775523795
    DOUBAO_ACCESS_KEY=70G0Dky0P24Ai2VsizJQ5bDLHIkKzLNt
    
    1. Optional customization: bash DOUBAO_TTS_SPEAKER=zh_male_yunzhou_jupiter_bigtts # Voice selection DOUBAO_BASE_URL=wss://openspeech.bytedance.com/api/v3/realtime/dialogue

API Documentation

The server implements a WebSocket-based API for real-time communication. See API Documentation for detailed specifications.

WebSocket Endpoint

ws://localhost:8765

Message Types

  • session_start - Start a new conversation session
  • session_end - End a conversation session
  • audio_data - Send audio data for processing
  • audio_response - Receive AI-generated audio response
  • error - Error messages
  • ping/pong - Connection keepalive

Architecture

AI Service Priority

The backend uses a priority-based AI service selection:

  1. Doubao Realtime API (Primary) - If DOUBAO_APP_ID and DOUBAO_ACCESS_KEY are configured
  2. Doubao Traditional API (Secondary) - If DOUBAO_API_KEY and DOUBAO_MODEL are configured
  3. OpenAI API (Fallback) - If OPENAI_API_KEY is configured

Configuration Structure

backend/
├── src/
│   ├── config/
│   │   ├── config.py          # Main configuration
│   │   └── doubao_config.py   # Doubao realtime API config
│   ├── services/
│   │   ├── ai_service.py      # AI service manager
│   │   ├── doubao_client.py   # Doubao realtime client
│   │   ├── websocket_server.py
│   │   ├── audio_processor.py
│   │   └── session_manager.py
│   └── ...

Development

Project Structure

backend/
├── src/
│   ├── core/               # Core configuration and utilities
│   │   ├── config.py      # Configuration management
│   │   └── logger.py      # Logging setup
│   ├── config/            # Configuration modules
│   │   ├── config.py      # Main settings
│   │   └── doubao_config.py # Doubao realtime config
│   ├── models/            # Data models
│   │   └── messages.py    # WebSocket message models
│   ├── services/          # Business logic services
│   │   ├── session_manager.py     # Session lifecycle management
│   │   ├── websocket_server.py    # WebSocket server implementation
│   │   ├── audio_processor.py     # Audio processing and conversion
│   │   ├── ai_service.py          # AI integration manager
│   │   └── doubao_client.py       # Doubao realtime client
│   └── main.py            # Application entry point
├── tests/                 # Test files
├── requirements.txt       # Python dependencies
├── pyproject.toml        # Project configuration
├── .env.example          # Environment variables template
└── run.py               # Simple startup script

Running Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=src

Code Quality

# Format code
black src tests

# Lint code
flake8 src tests

# Type checking
mypy src

Development Server

For development with auto-reload:

# Set environment variables
export RELOAD=true
export DEBUG=true

# Run with auto-reload
python run.py

Deployment

Docker Deployment

# Build image
docker build -t tolan-backend .

# Run container
docker run -d \
  --name tolan-backend \
  -p 8765:8765 \
  --env-file .env \
  tolan-backend

Systemd Service

Create /etc/systemd/system/tolan-backend.service:

[Unit]
Description=Tolan Backend Server
After=network.target

[Service]
Type=exec
User=tolan
Group=tolan
WorkingDirectory=/opt/tolan/backend
Environment=PATH=/opt/tolan/backend/venv/bin
EnvironmentFile=/opt/tolan/backend/.env
ExecStart=/opt/tolan/backend/venv/bin/python run.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable tolan-backend
sudo systemctl start tolan-backend

Troubleshooting

Common Issues

  1. Audio processing fails:

    • Ensure ffmpeg is installed
    • Check audio format compatibility
    • Verify file permissions
  2. Doubao realtime API unavailable:

    • Check API credentials (APP_ID and ACCESS_KEY)
    • Verify network connectivity to openspeech.bytedance.com
    • Check API service status
  3. AI service unavailable:

    • Check API keys configuration
    • Verify network connectivity
    • Check API service status
  4. WebSocket connection fails:

    • Check port availability
    • Verify firewall settings
    • Check CORS configuration

Debug Mode

Enable debug logging:

export DEBUG=true
export LOG_LEVEL=DEBUG
python run.py

Performance Tuning

  1. Audio Processing:

    • Adjust chunk size for better throughput
    • Configure noise reduction parameters
    • Optimize sample rate conversion
  2. Concurrency:

    • Tune max concurrent sessions
    • Adjust rate limiting parameters
    • Configure connection timeouts

License

MIT License - see LICENSE file for details.