Skip to content

Instantly share code, notes, and snippets.

@siberianmi
Created January 15, 2026 01:31
Show Gist options
  • Select an option

  • Save siberianmi/d4652bde2e8a579eb3601aa52313ae67 to your computer and use it in GitHub Desktop.

Select an option

Save siberianmi/d4652bde2e8a579eb3601aa52313ae67 to your computer and use it in GitHub Desktop.
Save your token
mkdir -p ~/.zai
echo 'ZAI_TOKEN_HERE' > ~/.zai/token
chmod 600 ~/.zai/token
#!/usr/bin/env python3
"""zai - Toggle script for Z.ai API configuration
Usage:
zai on - Enable Z.ai API configuration
zai off - Disable Z.ai API configuration
zai status - Show current configuration status
"""
import argparse
import json
import sys
from pathlib import Path
# Constants using portable paths
BASE_URL = "https://api.z.ai/api/anthropic"
CONFIG_DIR = Path.home() / ".zai"
TOKEN_FILE = CONFIG_DIR / "token"
SETTINGS_FILE = Path.home() / ".claude" / "settings.json"
def read_token() -> str:
"""Read API token from token file.
Returns:
The API token as a string.
Raises:
SystemExit: If the token file doesn't exist or cannot be read.
"""
if not TOKEN_FILE.exists():
print(f"❌ Token file not found: {TOKEN_FILE}")
print(f"πŸ“ Please create it with your Z.ai API token:")
print(f" mkdir -p {CONFIG_DIR}")
print(f" echo 'YOUR_API_TOKEN_HERE' > {TOKEN_FILE}")
print(f" chmod 600 {TOKEN_FILE} # Restrict to owner only")
sys.exit(1)
token = TOKEN_FILE.read_text().strip()
if not token:
print(f"❌ Token file is empty: {TOKEN_FILE}")
sys.exit(1)
return token
def backup_settings() -> None:
"""Create a backup of the settings file if it exists."""
if SETTINGS_FILE.exists():
import time
backup_path = SETTINGS_FILE.with_suffix(f".backup.{int(time.time())}")
SETTINGS_FILE.rename(backup_path)
def load_settings() -> dict:
"""Load settings from file, returning empty dict if file doesn't exist or is invalid."""
if SETTINGS_FILE.exists():
try:
return json.loads(SETTINGS_FILE.read_text())
except json.JSONDecodeError:
return {}
return {}
def save_settings(settings: dict) -> None:
"""Save settings to file, creating parent directory if needed."""
SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
SETTINGS_FILE.write_text(json.dumps(settings, indent=2))
def enable_zai() -> None:
"""Enable Z.ai API configuration."""
print("πŸ”§ Enabling Z.ai API configuration...")
api_key = read_token()
settings = load_settings()
# Update or add env section
if "env" not in settings:
settings["env"] = {}
settings["env"]["ANTHROPIC_AUTH_TOKEN"] = api_key
settings["env"]["ANTHROPIC_BASE_URL"] = BASE_URL
settings["env"]["API_TIMEOUT_MS"] = "3000000"
# Save settings
backup_settings()
save_settings(settings)
print("βœ… Z.ai configuration enabled")
print(f"πŸ“ Settings updated in: {SETTINGS_FILE}")
print("πŸš€ You can now run: claude")
def disable_zai() -> None:
"""Disable Z.ai API configuration."""
print("πŸ”§ Disabling Z.ai API configuration...")
if not SETTINGS_FILE.exists():
print("ℹ️ No settings file found")
return
settings = load_settings()
# Remove env section if it exists
if "env" in settings:
backup_settings()
del settings["env"]
save_settings(settings)
print("βœ… Z.ai configuration disabled")
print(f"πŸ“ Removed env section from: {SETTINGS_FILE}")
else:
print("ℹ️ No Z.ai configuration found to disable")
print("πŸš€ You can now run: claude (will use default Anthropic API)")
def show_status() -> None:
"""Show current configuration status."""
if not SETTINGS_FILE.exists():
print("❌ Z.ai configuration is currently DISABLED")
print("πŸ“ No settings file found")
return
settings = load_settings()
if "env" in settings and "ANTHROPIC_BASE_URL" in settings["env"]:
print("βœ… Z.ai configuration is currently ENABLED")
print(f"πŸ“ Settings file: {SETTINGS_FILE}")
else:
print("❌ Z.ai configuration is currently DISABLED")
print("πŸ“ Settings file exists but no env configuration")
def main() -> int:
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Toggle script for Z.ai API configuration",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"command",
choices=["on", "off", "status"],
help="Command to execute: on (enable), off (disable), status (check)"
)
args = parser.parse_args()
if args.command == "on":
enable_zai()
elif args.command == "off":
disable_zai()
elif args.command == "status":
show_status()
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment