Skip to content

Provides high-performance proxy services supporting multiple AI providers such as Z.AI, K2Think, and LongCat.

License

Notifications You must be signed in to change notification settings

Kirazul/GLM2api

 
 

Repository files navigation

Z.AI2API - English Version

This is a fork of the Chinese version: https://github.com/ZyphrZero/z.ai2api_python
Translated to English with enhanced admin dashboard and monitoring system.

Overview

Z.AI2API is a FastAPI-based OpenAI-compatible API server that provides access to multiple AI providers including Z.AI, K2Think, and LongCat. This English version includes a fully functional admin dashboard with real-time monitoring, request logging, and token management.

✨ Features

Core API Features

  • OpenAI-compatible API - Drop-in replacement for OpenAI API
  • Multi-provider support - Z.AI, K2Think, LongCat
  • Token pool management - Automatic failover and load balancing
  • Streaming support - Real-time response streaming
  • Function calling - Tool/function call support
  • Anonymous mode - Automatic temporary token acquisition

Admin Dashboard Features

  • Real-time statistics - Live request counts, success rates, uptime
  • Request logging - Comprehensive logging of all API requests
  • Token management - Add, validate, enable/disable tokens
  • Health monitoring - Token pool health checks and status
  • Configuration management - Web-based settings management
  • Live monitoring - Real-time logs and provider status

🚀 Quick Start

Prerequisites

  • Python 3.8+
  • pip or uv package manager

Installation

  1. Clone the repository

    git clone <your-repo-url>
    cd z.ai2api_python
  2. Install dependencies

    pip install -r requirements.txt
  3. Configure environment

    cp .env.example .env
    # Edit .env with your settings
  4. Start the server

    python main.py
  5. Access admin dashboard

    • URL: http://localhost:8080/admin
    • Default password: admin123

📊 Admin Dashboard

Dashboard Overview

  • Live Statistics: Real-time request counts, success rates, service uptime
  • Token Pool Health: Visual status of available authentication tokens
  • Recent Requests: Live feed of API requests with success/failure status

Token Management

  • Add Tokens: Single or bulk token addition with validation
  • Health Checks: Automatic token validation and health monitoring
  • Usage Statistics: Per-token success rates and request counts
  • Provider Management: Support for multiple AI providers

Configuration

  • Service Settings: Port, debug mode, anonymous mode
  • Authentication: API keys and token management
  • Advanced Options: Failure thresholds, recovery timeouts
  • Hot Reload: Configuration changes without restart

Monitoring

  • Provider Status: Real-time status of all AI providers
  • Live Logs: Streaming log viewer with filtering
  • System Health: Service metrics and performance monitoring

🔧 Configuration

Environment Variables

# Server Configuration
SERVICE_NAME=z-ai2api-server
LISTEN_PORT=8080
DEBUG_LOGGING=true

# Authentication
AUTH_TOKEN=sk-your-api-key
SKIP_AUTH_TOKEN=false
ANONYMOUS_MODE=true

# Features
TOOL_SUPPORT=true
SCAN_LIMIT=200000

# Token Pool
TOKEN_FAILURE_THRESHOLD=3
TOKEN_RECOVERY_TIMEOUT=1800

# Providers
DEFAULT_PROVIDER=zai
LONGCAT_TOKEN=your-longcat-token

Admin Dashboard

  • Default Password: admin123
  • Change Password: Set ADMIN_PASSWORD in .env
  • Session Timeout: 24 hours

� API 型Usage

OpenAI Compatible Endpoint

curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "Hello, world!"}
    ],
    "stream": false
  }'

Available Models

  • Z.AI: GLM-4.5, GLM-4.5-Thinking, GLM-4.5-Search, GLM-4.6, etc.
  • K2Think: MBZUAI-IFM/K2-Think
  • LongCat: LongCat-Flash, LongCat, LongCat-Search

Streaming Support

curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Authorization: Bearer your-api-key" \
  -d '{"model": "gpt-4o", "messages": [...], "stream": true}'

🗄️ Database

The system uses SQLite for data persistence:

  • tokens.db - Token management and request logs
  • Automatic cleanup - Old logs removed after 30 days
  • Backup recommended - Regular database backups suggested

Database Schema

-- Request logs table
CREATE TABLE request_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    provider TEXT NOT NULL,
    model TEXT NOT NULL,
    success BOOLEAN NOT NULL,
    duration REAL,
    input_tokens INTEGER DEFAULT 0,
    output_tokens INTEGER DEFAULT 0,
    total_tokens INTEGER DEFAULT 0,
    error_message TEXT
);

-- Tokens table (managed by TokenDAO)
CREATE TABLE tokens (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    provider TEXT NOT NULL,
    token TEXT NOT NULL UNIQUE,
    token_type TEXT DEFAULT 'unknown',
    is_enabled BOOLEAN DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

🔍 Monitoring & Logging

Request Logging

  • All API requests are automatically logged
  • Success/failure tracking with error messages
  • Performance metrics including response times
  • Token usage statistics per provider

Health Monitoring

  • Token validation - Automatic health checks
  • Provider status - Real-time availability monitoring
  • System metrics - Memory, CPU, uptime tracking
  • Error tracking - Comprehensive error logging

Log Management

  • Automatic cleanup - Old logs removed after 30 days
  • Log rotation - Prevents disk space issues
  • Real-time viewing - Live log streaming in dashboard

🛠️ Development

Project Structure

z.ai2api_python/
├── app/
│   ├── admin/          # Admin dashboard
│   ├── core/           # Core API functionality
│   ├── models/         # Database models
│   ├── providers/      # AI provider implementations
│   ├── services/       # Data access layer
│   ├── templates/      # HTML templates
│   └── utils/          # Utility functions
├── logs/               # Application logs
├── main.py            # Application entry point
└── requirements.txt   # Dependencies

Adding New Providers

  1. Create provider class in app/providers/
  2. Implement required methods
  3. Register in provider_factory.py
  4. Add model mappings
  5. Update admin dashboard

Customizing Dashboard

  • Templates: Modify files in app/templates/
  • Styling: Update CSS in app/static/css/
  • Update intervals: Adjust HTMX trigger timings
  • Statistics: Modify API endpoints in app/admin/api.py

📋 Changelog

English Translation & Dashboard Enhancement

Translation Complete

  • All UI elements translated from Chinese to English
  • Admin dashboard fully localized
  • Log messages and system notifications translated
  • Documentation and comments updated

Enhanced Admin Dashboard

  • Real-time statistics - Live updating dashboard with request counts, success rates
  • Request logging system - Comprehensive logging of all API requests to database
  • Token pool monitoring - Visual health status of authentication tokens
  • Recent request logs - Live feed showing success/failure of recent API calls
  • Improved UX - Clean, professional interface with color-coded status indicators

New Features Added

  • Live updates - Dashboard refreshes automatically without page reload
  • Request tracking - All API calls logged with success/failure status
  • Performance monitoring - Service uptime and response time tracking
  • Error handling - Comprehensive error logging and display
  • Database integration - SQLite-based persistence for logs and statistics

Technical Improvements

  • HTMX integration - Seamless live updates without JavaScript complexity
  • Database optimization - Indexed queries and automatic cleanup
  • Error resilience - Graceful handling of database and logging failures
  • Performance - Minimal impact on API response times

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Original Project: ZyphrZero/z.ai2api_python
  • Z.AI Platform: For providing the AI services
  • FastAPI: For the excellent web framework
  • HTMX: For seamless frontend interactions

Note: This is an English translation and enhancement of the original Chinese project. All core functionality remains the same with added monitoring and dashboard capabilities.

About

Provides high-performance proxy services supporting multiple AI providers such as Z.AI, K2Think, and LongCat.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 73.3%
  • HTML 26.6%
  • Dockerfile 0.1%