Sebuah simulator endpoint OpenAI yang dibangun dengan Rust menggunakan framework Actix-web. Aplikasi ini mensimulasikan API chat completions OpenAI dengan dukungan streaming response dan dapat mengambil data dari file markdown atau database ClickHouse.
- Simulasi OpenAI Chat Completions API - Endpoint
/v1/chat/completionsyang kompatibel - Streaming Response - Dukungan Server-Sent Events (SSE) untuk streaming chunks
- Dual Data Source - Mendukung sumber data dari file markdown atau database ClickHouse
- Redis Caching - High-performance caching dengan Redis untuk response database dan file
- Rate Limiting - Menggunakan semaphore untuk mengontrol concurrent requests
- Configurable Workers - Jumlah worker threads dapat dikonfigurasi
- Logging Konfigurabel - Multiple level logging (trace, debug, info, warn, error)
- Docker Support - Dockerfile optimized dengan static linking
- Test Endpoint - Endpoint testing untuk verifikasi konektivitas
- Rust 1.70+ (latest stable)
- Redis 6+ (untuk caching)
- ClickHouse database (jika menggunakan database source)
- Docker (optional, untuk containerization)
-
Clone repository
git clone https://github.com/fullstack-aidev/rai-endpoint-simulator.git cd rai-endpoint-simulator -
Install dependencies
cargo build --release
-
Start Redis
# Using Docker docker run -d --name redis -p 6379:6379 redis:7-alpine # Or install locally redis-server
-
Setup konfigurasi
Copy
config.local.ymlkeconfig.ymluntuk development lokal:cp config.local.yml config.yml
-
Persiapkan response files (jika menggunakan file source)
Buat folder
zresponsedan isi dengan file markdown (.md) yang berisi response content. -
Run
cargo run --release
-
Run dengan Docker Compose (recommended)
docker-compose up -d
Ini akan menjalankan:
- Redis server
- 3 replicas simulator
- HAProxy load balancer
-
Build image manual
docker build -t rai-endpoint-simulator . -
Run container manual
docker run -p 4545:4545 \ -v $(pwd)/config.yml:/app/config.yml \ -v $(pwd)/zresponse:/app/zresponse \ rai-endpoint-simulator
binding:
port: 4545
host: 0.0.0.0
source: file # file or database
database:
url: http://127.0.0.1:8123
username: simulator_app
password: "your_password"
redis:
url: redis://127.0.0.1:6379
prefix: rai_simulator
tracking:
enabled: false
log_level: info
channel_capacity: 1000
semaphore_limit: 10000
workers: 8
cache_ttl: 60| Parameter | Deskripsi | Default |
|---|---|---|
source |
Sumber data: "file" atau "database" | "file" |
log_level |
Level logging: trace/debug/info/warn/error | "info" |
channel_capacity |
Kapasitas channel untuk streaming | 1000 |
semaphore_limit |
Limit concurrent requests | 10000 |
workers |
Jumlah worker threads | 8 |
cache_ttl |
Cache TTL dalam detik | 60 |
binding.host |
Host binding server | "0.0.0.0" |
binding.port |
Port server | 4545 |
database.username |
Username ClickHouse | - |
database.password |
Password ClickHouse | - |
database.url |
URL ClickHouse | - |
redis.url |
URL Redis server | "redis://127.0.0.1:6379" |
redis.prefix |
Prefix untuk Redis keys | "rai_simulator" |
tracking.enabled |
Enable detailed logging | false |
Aplikasi menggunakan Redis untuk caching dengan struktur key berikut:
| Key Pattern | Deskripsi | TTL |
|---|---|---|
{prefix}:db_responses |
Cache responses dari database | cache_ttl |
{prefix}:file:{filename} |
Cache konten file markdown | cache_ttl |
{prefix}:file_list |
Cache daftar file markdown | 600s (10 menit) |
Jika menggunakan database source, pastikan tabel response_simulator memiliki struktur:
CREATE TABLE response_simulator (
qa_id UUID,
pertanyaan String,
jawaban String,
referensi String
) ENGINE = MergeTree()
ORDER BY qa_id;# Development
cargo run
# Production
cargo run --releaseServer akan berjalan di http://localhost:4545
POST /test_completionResponse untuk testing konektivitas:
{
"id": "chatcmpl-AjoahzpVUCsJmOQZRKZUze7qBjEjn",
"object": "chat.completion",
"created": 1735482595,
"model": "gpt-4o-2024-08-06",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "============>> Selamat! Aplikasi anda telah sukses terhubung ke OpenAI Simulator. <============="
},
"logprobs": null,
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 57,
"completion_tokens": 92,
"total_tokens": 149
}
}POST /v1/chat/completions
Content-Type: application/json
{
"model": "gpt-4o-2024-08-06",
"messages": [
{"role": "user", "content": "Hello!"}
],
"stream": true
}Response streaming dalam format Server-Sent Events dengan chunks yang mensimulasikan response OpenAI.
# Test endpoint
curl -X POST http://localhost:4545/test_completion
# Chat completions
curl -X POST http://localhost:4545/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "gpt-4o-2024-08-06", "messages": [{"role": "user", "content": "Hello!"}], "stream": true}'rai-endpoint-simulator/
βββ src/
β βββ main.rs # Entry point dan HTTP handlers
β βββ stream.rs # Streaming logic dan chunk generation
β βββ response.rs # File dan database response handling
β βββ config_loader.rs # Configuration loading
βββ zresponse/ # Markdown response files (jika source=file)
βββ config.yml # Konfigurasi aplikasi (Docker)
βββ config.local.yml # Konfigurasi aplikasi (Local development)
βββ docker-compose.yaml # Docker Compose configuration
βββ haproxy.cfg # HAProxy load balancer config
βββ Cargo.toml # Rust dependencies
βββ Cargo.lock # Locked dependencies
βββ Dockerfile # Container configuration
- Database responses di-cache di Redis dengan TTL yang dapat dikonfigurasi
- File content di-cache untuk menghindari disk I/O berulang
- File list di-cache dengan TTL lebih lama (10 menit)
- Menggunakan
ConnectionManageruntuk connection pooling ke Redis
- Menggunakan
tokio::task::spawn_blockinguntuk file I/O - Non-blocking Redis operations dengan
redis::aio - Async database queries dengan ClickHouse async client
- Configurable worker threads via
workersconfig - Semaphore-based rate limiting
- Lock-free caching dengan Redis sebagai distributed cache
- Streaming response tanpa buffering seluruh content
- Efficient chunk generation dengan configurable chunk size
Aplikasi menggunakan env_logger dengan level yang dapat dikonfigurasi:
# Set log level via config.yml
log_level: "debug"Log output contoh:
[INFO] Starting server at http://0.0.0.0:4545
[INFO] Configuration: workers=8, semaphore_limit=10000, cache_ttl=60s
[INFO] Connecting to Redis at redis://127.0.0.1:6379
[INFO] Successfully connected to Redis
[DEBUG] Cache hit: returning 150 cached responses from Redis
Gunakan test endpoint untuk health checking:
curl -f http://localhost:4545/test_completion || exit 1# Connect ke Redis CLI
redis-cli
# Lihat semua keys
KEYS rai_simulator:*
# Lihat TTL
TTL rai_simulator:db_responses
# Monitor cache activity
MONITORβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HAProxy β
β (Port 4545) β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββΌββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββ βββββββββββββ βββββββββββββ
β Replica 1 β β Replica 2 β β Replica 3 β
βββββββ¬ββββββ βββββββ¬ββββββ βββββββ¬ββββββ
β β β
βββββββββββββββΌββββββββββββββ
β
βΌ
βββββββββββββββββ
β Redis β
β (Shared Cache)β
βββββββββββββββββ
- Fork repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
Distributed under the MIT License. See LICENSE file for more information.
Jika Anda mengalami masalah atau memiliki pertanyaan:
- Check existing Issues
- Create new issue dengan detail lengkap
- Sertakan log output dan konfigurasi (redact sensitive information)
- Security: Pastikan Redis dan database credentials aman
- Redis: Gunakan Redis dengan persistence (AOF/RDB) untuk production
- Monitoring: Setup logging, metrics, dan alerting
- Scaling: Adjust
workersdansemaphore_limitsesuai kapasitas server - Backup: Backup database dan response files secara berkala
binding:
port: 4545
host: 0.0.0.0
source: file
redis:
url: redis://your-redis-cluster:6379
prefix: rai_prod
log_level: warn
channel_capacity: 1000
semaphore_limit: 5000
workers: 8
cache_ttl: 300
tracking:
enabled: falseBuilt with β€οΈ using Rust and Actix-web