3.2 KiB
3.2 KiB
Grok46 Gateway (gw46.py)
Location
C:\Users\User\Documents\grok46gw\gw46.py
Overview
A ready-made OpenAI-compatible API gateway for xAI's Grok models with OAuth auto-registration, device code flow, and SQLite-based account management.
Features
- OpenAI-compatible API:
/v1/chat/completions,/v1/models,/v1/responses - Multi-model support: grok-4.6, grok-4.5, grok-4.3, grok-build-0.1
- OAuth PKCE flow:
/oauth/login→ user signs in browser → callback → token - Device code flow:
/oauth/device→ user_code + verification_uri →/oauth/device/poll - SQLite database: accounts stored in
grok46_accounts.dbwith refresh tokens - API key pool: round-robin rotation across all stored credentials
- Token refresh: automatic refresh for expired tokens (if refresh_token is available)
Usage
# Start the gateway
cd ~/Documents/grok46gw
python gw46.py
# Listens on 127.0.0.1:20146 by default (configurable via GROK46_PORT)
Getting Tokens via Device Code Flow
- Start the gateway:
python gw46.py - Request a device code:
GET http://127.0.0.1:20146/oauth/device - Response includes
user_code(e.g.J2QB-MGQC) andverification_uri_complete(e.g.https://accounts.x.ai/oauth2/device?user_code=J2QB-MGQC) - Open the verification URI in a browser
- Sign in with an existing x.ai account (or create a new one)
- Enter the user_code and authorize the application
- Poll for the token:
GET http://127.0.0.1:20146/oauth/device/poll - When authorized, the response includes the
access_tokenand the token is saved to the database
Account Management
GET /accounts— list all stored accounts and API keysPOST /accounts/api-key?key=...&label=...— add a manual API keyGET /health— health check with credential count
Environment Variables
GROK46_PORT— port (default: 20146)GROK46_HOST— bind host (default: 127.0.0.1)GROK46_DB— SQLite DB path (default:./grok46_accounts.db)XAI_API_KEYS— comma-separated xAI API keys to add to the pool
Database Schema
CREATE TABLE accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE,
access_token TEXT NOT NULL,
refresh_token TEXT,
expires_at REAL,
scope TEXT,
created_at REAL DEFAULT (strftime('%s','now')),
last_used_at REAL,
use_count INTEGER DEFAULT 0
);
CREATE TABLE api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT UNIQUE NOT NULL,
label TEXT,
created_at REAL DEFAULT (strftime('%s','now')),
last_used_at REAL,
use_count INTEGER DEFAULT 0
);
OAuth Auto-Registration Flow
The gateway implements the full PKCE OAuth flow:
GET /oauth/login— redirects to x.ai OAuth authorization page with PKCE challenge- User signs in and authorizes in the browser
- Browser redirects to
http://127.0.0.1:20146/oauth/callback?code=... - Gateway exchanges the code for tokens using the PKCE verifier
- Tokens are saved to the SQLite database and added to the credential pool
Token Refresh
Tokens with refresh_token are automatically refreshed when they expire. The gateway calls the xAI token endpoint with grant_type=refresh_token to get new access tokens.