Gemini Cli 国内不直接使用代理,替换 endpoint 的解法

Gemini Cli 在国内无法直接使用,一种解法是使用代理,但是考虑到有时候配置代理不见得比加一个反代 endpoint 简单多少,所以尝试了一下替换域名的方式。

本文使用了 GEMINI_API 的认证方式。

export GEMINI_API_KEY=xxx

首先根据 npm root -g 确定安装位置,在 MacOS 下可以直接 cd /opt/homebrew/lib/node_modules/@google/gemini-cli/node_modules/@google/gemini-cli-core

编辑文件 dist/index.js,将文件修改为以下内容。

/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
export {
  DEFAULT_GEMINI_EMBEDDING_MODEL,
  DEFAULT_GEMINI_FLASH_MODEL,
  DEFAULT_GEMINI_MODEL,
} from "./src/config/models.js";
export * from "./src/index.js";
//# sourceMappingURL=index.js.map

import { Agent, Dispatcher, setGlobalDispatcher } from "undici";

class RewritingDispatcher extends Dispatcher {
  #underlyingDispatcher;
  #from;
  #to;

  constructor(from, to, options) {
    super();
    this.#underlyingDispatcher = new Agent(options);
    this.#from = from;
    this.#to = to;
  }

  dispatch(options, handler) {
    const { origin } = options;
    const url = new URL(origin);

    if (url.hostname === this.#from) {
      const newOptions = { ...options };

      url.hostname = this.#to;
      newOptions.origin = url.toString();

      return this.#underlyingDispatcher.dispatch(newOptions, handler);
    }

    return this.#underlyingDispatcher.dispatch(options, handler);
  }
}

const rewritingDispatcher = new RewritingDispatcher(
  "generativelanguage.googleapis.com",
  "YOUR REVERSE PROXY DOMAIN"
);
setGlobalDispatcher(rewritingDispatcher);

One more thing:

vi dist/src/config/models.js

flash 改成 pro

参考文档

CC BY-NC-SA 4.0 本作品使用基于以下许可授权:Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注