小型紅寶石原型,用於OpenAI相容的LLM代理程式,具有可補充的token桶.
它只使用Ruby標準函庫:沒有gem,沒有Rack,沒有WEBrick.
執行
BASE_API_URL=http://192.168.0.124:8888/v1 \ BASE_API_KEY=1mmer \ BASE_MODEL=gemma4 \ ruby llm_proxy.rb
代理程式預設監聽在0.0.0.0:8899.
對於您本地的LLM在192.168.0.124:8888,執行儲存的本地設定:
./run_local_proxy.sh
這會啟動Ruby代理程式在http://127.0.0.1:8899/v1 和轉發到 http://192.168.0.124:8888/v1.
儲存的本地 curl 檢查是:
./curl_local_proxy.sh
手動等價:
curl -sS -i -m 60 http://127.0.0.1:8899/v1/chat/completions \ -H 'Authorization: Bearer user-a' \ -H 'Content-Type: application/json' \ -d '{ "model": "gemma4", "messages": [{"role": "user", "content": "Reply with exactly: proxy ok"}], "max_tokens": 16 }'
透過代理伺服器驗證結果:上游回應了 proxy ok,而代理伺服器回傳了 X-RateLimit-Remaining: 0,並使用本地測試儲存桶。
執行煙測試:
ruby test_llm_proxy.rb
令牌儲存桶設定
MAX_TOKENS=10 # max saved tokens per user REFILL_TOKENS=2 # tokens added each refill REFILL_INTERVAL_SECONDS=300 # 5 minutes REQUEST_TOKEN_COST=1 # cost per accepted completion request
每個攜帶權杖的令牌都獲得它自己的桶。沒有攜帶權杖的請求會根據遠程 IP 分桶。如果代理應該拒絕未知客戶密鑰,請設置PROXY_API_KEYS=key1,key2。
當桶為空時,/v1/chat/completions和/v1/completions會返回一個正常的 OpenAI �風格的助手響應:
limit reached, wait 5 min
測試請求
curl http://localhost:8888/v1/chat/completions \ -H 'Authorization: Bearer user-a' \ -H 'Content-Type: application/json' \ -d '{ "model": "anything", "messages": [{"role": "user", "content": "hello"}] }'
選擇性估計令牌模式
預設情況下,一次完成請求耗費REQUEST_TOKEN_COST桶代幣。為根據提示大小加上預期輸出大致收費:
TOKEN_COST_MODE=estimate RESPONSE_TOKEN_RESERVE=256 ruby llm_proxy.rb
這僅是原型的一個近似值。












