Claude Code 如何在 NixOS 搭配多个 API 供应商
在体验琳琅满目的大模型时,如何管理各个 AI 平台的配置(安全地保存 API_KEY )就成为了一种负担。
但如果你们像我一样使用 home-manager 来管理 dotfiles 的话(能保证在多设备上安装的软件及配置一致)。
推荐像我这样,把 API_KEY 通过 age 加密,当 rebuild 时把解密后的 token 挂载成文件。
再使用 pkgs.writeShellScriptBin
包装一下原始命令,把对应的环境变量配置好。
使用方式
# 运行使用订阅版的 claude-code
claude
# 运行使用 ZhiPu 的大模型 claude-code
zhipu
# 临时运行极速版的 ZhiPu 大模型 claude-code
ANTHROPIC_MODEL=glm-4.5-x zhipu
配置示例
其中的
config.age.secrets
来自 yaxitech/ragenix。 使用非对称加解密算法,来管理环境中的密钥等需要特殊注意的数据。
{
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";
})
];
}
Thanks for reading! Read other posts?
This work by 林玮 (Jade Lin) is licensed under
CC BY-NC-ND 4.0