Claude Code with Multiple API Providers on NixOS
When experiencing various large models, managing configurations for different AI
platforms (securely storing API keys) becomes a burden.
However, if you use home-manager to manage dotfiles like me (which ensures
consistent software and configuration across multiple devices),
I recommend encrypting API keys with age and mounting the decrypted tokens as
files during rebuild.
Then use pkgs.writeShellScriptBin
to wrap the original commands and configure
the corresponding environment variables.
Usage
# Run claude-code with subscription
claude
# Run claude-code with ZhiPu's large model
zhipu
# Temporarily run claude-code with ZhiPu's fast model
ANTHROPIC_MODEL=glm-4.5-x zhipu
Configuration Example
The
config.age.secrets
comes from yaxitech/ragenix. It uses asymmetric encryption algorithms to manage sensitive data like keys in the environment.
{
lib,
config,
inputs,
...
}: let
pkgs = import inputs.nixpkgs-unstable {
# Allow proprietary/unfree software (like claude-code)
config.allowUnfree = true;
};
claude_alt = {
name,
url,
token_path,
reasoner,
chat,
}: (
pkgs.writeShellScriptBin name ''
# Environment variables for the Anthropic CLI tool.
# https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables
export ANTHROPIC_AUTH_TOKEN=''${ANTHROPIC_AUTH_TOKEN-$(cat ${token_path})}
export ANTHROPIC_BASE_URL=${url}
export ANTHROPIC_MODEL=''${ANTHROPIC_MODEL-"${reasoner}"}
export ANTHROPIC_SMALL_FAST_MODEL=''${ANTHROPIC_SMALL_FAST_MODEL-"${chat}"}
exec claude "$@"
''
);
in {
home.packages = with pkgs; [
claude-code
(claude_alt {
name = "zhipu";
url = "https://open.bigmodel.cn/api/anthropic";
token_path = config.age.secrets.zhipu.path;
reasoner = "glm-4.5";
chat = "glm-4.5-air";
})
(claude_alt {
name = "deepseek";
url = "https://api.deepseek.com/anthropic";
token_path = config.age.secrets.deepseek.path;
reasoner = "deepseek-reasoner";
chat = "deepseek-chat";
})
(claude_alt {
name = "kimi-turbo";
url = "https://api.moonshot.cn/anthropic";
token_path = config.age.secrets.kimi.path;
reasoner = "kimi-k2-turbo-preview";
chat = "moonshot-v1-8k";
})
(claude_alt {
name = "kimi";
url = "https://api.moonshot.cn/anthropic";
token_path = config.age.secrets.kimi.path;
reasoner = "kimi-k2-0711-preview";
chat = "moonshot-v1-8k";
})
];
}
This work by 林玮 (Jade Lin) is licensed under
CC BY-NC-ND 4.0