首页
/ 把 gpt4free 变成 Clawbot/OpenClaw 的本地 LLM 服务器:API 启动、config.yaml 路由与机器人补丁集成指南

把 gpt4free 变成 Clawbot/OpenClaw 的本地 LLM 服务器:API 启动、config.yaml 路由与机器人补丁集成指南

2026-09-03 16:04:59作者:乔或婵

本篇基于 gpt4free 仓库中的 SKILL.md 展开,教你把 g4f 作为本地 LLM 服务器运行:启动 OpenAI 兼容 REST API、用 config.yaml 定义带配额与错误条件判断的自定义模型路由,并通过补丁脚本让 Clawbot/OpenClaw 这类机器人直接对接本地端点。读完并跟着操作后,你可以独立完成"安装 → 起服务 → 配路由 → 补机器人配置 → 验证联调"的完整链路,并理解路由决策背后的 QuotaCacheErrorCounter 与条件表达式实现。

1. 整体思路:g4f 在 Bot 架构中的位置

SKILL.md 给出的技能目标是:将 gpt4free 作为本地 LLM 服务器,向 Clawbot/OpenClaw 等机器人暴露一个 OpenAI 兼容的 /v1 REST 接口,同时用 config.yaml 把"逻辑模型名"透明地聚合/降级到多个真实 provider。整体数据流如下:

Clawbot / OpenClaw
   └─(baseUrl: http://localhost:8080/v1, openai-completions)
g4f API Server (FastAPI, python -m g4f)
   └─ 自定义模型名(如 "openclaw")
        └─ config.yaml 路由:GeminiCLI → Antigravity → PollinationsAI
             └─ 真实 provider + 条件判断(quota / error_count)

三条要点(来自 SKILL.md 的 Best Practices):

  • 启动 API 服务器:python -m g4f --port 8080(或 g4f api --debug --port 8080);
  • 使用 /v1 端点接收 OpenAI 兼容请求,例如 POST http://localhost:8080/v1/chat/completions;
  • config.yaml 中定义自定义模型路由,做 provider 聚合与 fallback;
  • config.yaml 放到 cookies 目录(例如 ~/.g4f/cookies/config.yaml);
  • 对 Clawbot/OpenClaw,补丁其配置指向你的 gpt4free 服务器(见 scripts/patch-openclaw.py);
  • g4f client "Hello" --model openclaw 或 Python 客户端做验证。

2. 第一步:启动 OpenAI 兼容 API 服务器

2.1 启动命令

仓库入口是 g4f/main.py,它调用 g4f/cli/init.pymain(),按第一个位置参数选择运行模式(api/gui/client/mcp/auth/pa 等,默认 api)。SKILL.md 推荐两种等价写法:

python -m g4f --port 8080
# 或(显式 api 子命令 + 详细日志)
g4f api --debug --port 8080

API 模式下可用的关键参数(定义于 g4f/cli/init.pyget_api_parser()):

参数 默认值 说明
--bind None(即 0.0.0.0:{DEFAULT_PORT}) 绑定地址
--port / -p None API 服务器端口
--debug / -d - 开启详细日志
--no-gui / -ng False 不带 GUI 运行
--model None 默认 chat completion 模型
--provider None 默认 chat provider
--media-provider None 默认图像生成 provider
--proxy None 默认 HTTP 代理
--workers None 工作进程数
--ignore-cookie-files - 不读取 .har/cookie 文件
--cookies-dir None 自定义 cookies/HAR 目录(会据此覆盖 cookies 目录)
--g4f-api-key None 给 API 加鉴权 key
--ignored-providers [] 请求处理时忽略的 provider
--timeout / --stream-timeout DEFAULT_TIMEOUT / DEFAULT_STREAM_TIMEOUT 请求/流式超时(秒)
--ssl-keyfile / --ssl-certfile None 启用 HTTPS

参数经 run_api_args() 组装后,先通过 AppConfig.set_config(...) 应用配置(忽略 cookie 文件、API key、超时等),再调用 g4f.api.run_api(bind, port, debug, workers, ...) 启动服务器;若指定了 --cookies-dir,还会 os.makedirs 并调用 cookies.set_cookies_dir() 覆盖 cookies 目录——这正是 config.yaml 生效位置的关键(见第 3 节)。

2.2 端口说明:为什么 SKILL.md 强调 8080

这里有一个需要特别注意的事实差异:SKILL.md 的 Common Pitfalls 写着"Not exposing the correct port (default 8080)",而当前源码中 g4f/config.py 定义 DEFAULT_PORT = 1337,CLI 未传 --port 时实际监听 1337(仅 g4f dev 开发模式会把空端口兜底为 8080)。因此:

  • 务必显式传 --port 8080,与补丁脚本写死的 http://localhost:8080/v1 保持一致;
  • 若你习惯用 1337 默认端口,则必须同步修改机器人配置里的 baseUrl,否则机器人会连不上。

2.3 /v1 OpenAI 兼容端点

机器人侧按 OpenAI 协议调用,核心端点为:

POST http://localhost:8080/v1/chat/completions

请求体与 OpenAI Chat Completions 一致(modelmessagesstreammax_tokens 等)。model 字段可以填真实模型,也可以填 config.yaml 里定义的自定义路由名(如 openclaw),g4f 会自动展开到路由候选 provider。

3. 第二步:用 config.yaml 定义自定义模型路由

3.1 文件放置位置与加载时机

config.yaml 必须放在 cookies 目录(即存放 .har/.json cookie 文件的同一目录):

  • 默认位置:~/.config/g4f/cookies/config.yaml(详见 docs/config-yaml-routing.md);
  • 替代位置:./har_and_cookies/config.yaml;
  • SKILL.md 与 scripts/setup-openclaw.sh 使用的实际目录是 ~/.g4f/cookies/config.yaml,脚本内 CONFIG_DIR="${HOME}/.g4f/cookies"

加载时机由源码确认:g4f/cookies.pyread_cookie_files() 在读 cookie 目录时会同时探测同目录下的 config.yaml(约 L327-L336 处)并加载路由配置;因此 API 服务器启动时会自动加载,失败时仅记录 config.yaml: Failed to load routing config from ... 警告而不阻断启动。

前置依赖:需要安装 PyYAML(pip install pyyaml,完整 requirements.txt 已包含);缺失时 g4f 只打警告并跳过 config.yaml 加载——这也是"路由不生效"的常见原因之一。

3.2 文件格式

models:
  - name: "<model-name>"          # 客户端使用的模型名
    providers:
      - provider: "<ProviderName>"  # g4f provider 类名
        model: "<provider-model>"   # 转发给该 provider 的模型名
        condition: "<expression>"   # 可选 —— 条件表达式
      - provider: "..."             # fallback provider(无条件 = 始终可用)
        model: "..."
必填 说明
name 客户端使用的模型名
providers 有序的 provider 候选列表
provider provider 类名(如 "OpenaiAccount""PollinationsAI")
model - 转发给 provider 的模型名;缺省时取路由的 name
condition - 布尔表达式,控制该 provider 何时可用

仓库中有一份带完整注释的参考配置 etc/examples/config.yaml,与 docs/config-yaml-routing.md 中的示例对应。

3.3 condition 条件表达式

condition 是每次请求前求值的布尔表达式,可引用三类变量:

1) quota —— provider 的完整配额字典

每个实现了 get_quota() 的 provider 返回各自格式的字典,结果在内存中缓存(TTL 5 分钟),遇到 HTTP 429 时立即失效。用点号语法访问嵌套字段:

Provider get_quota() 格式 示例条件
PollinationsAI {"balance": float} quota.balance > 0
Yupp {"credits": {"remaining": int, "total": int}} quota.credits.remaining > 100
PuterJS API 原始 metering JSON quota.total_requests < 1000
GeminiCLI {"buckets": [...]}(含 models.*.remainingFraction) error_count < 3
GithubCopilot usage details dict error_count < 5

缺失的键解析为 0.0,不会抛错。

2) balance —— 简写别名

quota.balance 的向后兼容简写,对返回 {"balance": float} 的 PollinationsAI 最有用;其他 provider 建议显式写 quota.*

3) error_count

该 provider 最近 1 小时内记录到的错误数,超过 1 小时的错误自动清除。用它在条件里避开反复失败的 provider。

运算符:> < >= <= 数值比较;== != 相等/不等;and or not 逻辑连接;( ) 分组。

条件缺省或求值为 True 时该 provider 可用;求值为 False 则跳过,尝试列表中下一个。常用写法:

condition: "balance > 0 or error_count < 3"          # PollinationsAI
condition: "quota.credits.remaining > 0"             # Yupp
condition: "error_count < 3"                          # 任意 provider 通用

3.4 配额缓存与错误计数(源码级机制)

路由机制实现位于 g4f/providers/config_provider.py,关键组件:

组件 位置 职责
QuotaCache L82 缓存各 provider 的 get_quota() 结果,默认 TTL 5 分钟;429 时 invalidate() 立即失效
ErrorCounter L134 记录各 provider 错误计数,1 小时滑动窗口自动清理
evaluate_condition L301 对条件字符串做安全求值
ProviderRouteConfig / ModelRouteConfig L346 / L360 单个 provider 候选与整条路由的数据结构
RouterConfig L375 路由注册表;load(path) 从指定路径加载(L382),get(model_name) 查询路由(L435)

这套"条件缺省即可用 + 失败计数冷却"的设计,让路由既能在配额健康时优先走高质量 provider,又能在其限流/出错时自动让位到 fallback,而不需要重启服务。

3.5 OpenClaw 场景的完整 config.yaml

SKILL.md 给出的路由定义(与 scripts/setup-openclaw.sh 生成的配置一致)如下,策略是"配额健康且未连错就优先 Gemini 系,否则落到 PollinationsAI":

models:
  - name: "openclaw"
    providers:
      - provider: "GeminiCLI"
        model: "gemini-3-flash-preview"
        condition: "quota.models.gemini-3-flash-preview.remainingFraction > 0 and error_count < 3"
      - provider: "Antigravity"
        model: "gemini-3-flash"
        condition: "quota.models.gemini-3-flash.quotaInfo.remainingFraction > 0 and error_count < 3"
      - provider: "PollinationsAI"
        model: "openai"
        condition: "balance > 0 or error_count < 3"

注意 SKILL.md 的原始示例中 Antigravity 与 PollinationsAI 两条没写 condition(无条件即始终可用,天然充当兜底);setup 脚本生成的版本给三条都加了条件,属于更保守的变体。GeminiCLI/Antigravity 属于需登录的 provider,需要先用 g4f auth gemini-cli loging4f auth antigravity login 完成认证(auth 模式支持 gemini-cli/antigravity/qwencode/github-copilot,见 g4f/cli/init.pyhandle_auth()),setup 脚本的收尾说明也明确提示"And auth into Antigravity and GeminiCLI (or any other provider you wish to use)"。

3.6 编程接口:直接用 Python API 调试路由

路由机制以模块形式暴露,便于单测与排查:

from g4f.providers.config_provider import (
    RouterConfig,        # 加载 / 查询路由
    QuotaCache,          # 查看 / 失效配额缓存
    ErrorCounter,        # 查看 / 重置错误计数
    evaluate_condition,  # 直接对条件字符串求值
)

# 从自定义路径重新加载路由
RouterConfig.load("/path/to/config.yaml")

# 检查路由是否存在(返回 ModelRouteConfig 或 None)
route = RouterConfig.get("openclaw")

# 手动失效某个 provider 的配额缓存(例如检测到 429 后)
QuotaCache.invalidate("OpenaiAccount")

# 查询错误计数
count = ErrorCounter.get_count("OpenaiAccount")

# 对条件字符串求值(参数:条件、配额字典、错误数)
ok = evaluate_condition("balance > 0 or error_count < 3", {"balance": 0.0}, 2)  # True

4. 第三步:补丁 OpenClaw/Clawbot 配置指向本地 g4f

4.1 patch-openclaw.py 做了什么

scripts/patch-openclaw.py 是一个幂等的配置补丁脚本,逻辑非常直白:

  1. 读取 ~/.openclaw/openclaw.json;若不存在则提示"请先执行 openclaw onboard",直接退出;
  2. models.providers 注入两个 provider:
provider = {
    "baseUrl": "http://localhost:8080/v1",
    "api": "openai-completions",
    "models": [
        {
            "id": "openclaw",
            "name": "Custom GPT4Free",
            "reasoning": True,
            "input": ["text", "image"],
            "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
            "contextWindow": 256000,
            "maxTokens": 8192,
        }
    ],
}
cfg["models"]["providers"]["gpt4free"] = provider
  • gpt4free:指向本地的 http://localhost:8080/v1,模型 id 就是 config.yaml 里的路由名 openclaw,声明支持文本+图像输入、256k 上下文窗口、8192 最大输出;
  • g4f-perplexity:指向远端 Perplexity 兼容端点,并把 tools.web.search.provider 设为 g4f-perplexity,让 OpenClaw 的联网搜索也走 g4f 系服务;
  1. 写回 JSON,并提示后续命令:openclaw models set gpt4free/openclaw(应用新模型)与 openclaw gateway restart(重启网关)。

关键点:baseUrl 必须与 g4f api --port 的端口一致,这正是 SKILL.md 把"端口不一致"列为高频坑的原因。

4.2 setup-openclaw.sh 一体化脚本

scripts/setup-openclaw.sh 把整条链路自动化(macOS/Linux/Windows WSL 均可),步骤为:

  1. 检查 Python 与 g4f 安装(缺失则 pip install -U g4f[all]);
  2. ~/.g4f/cookies/config.yaml 写入 3.5 节的 openclaw 路由,并向同目录 .env 写入 POLLINATIONS_API_KEY 等环境变量;
  3. 若检测到 openclaw CLI 且配置不存在,执行非交互 openclaw onboard(以 http://localhost:8080/v1 为 custom base URL、gpt4free 为 provider id、openclaw 为 model id);
  4. 内嵌 Python 段执行与 patch-openclaw.py 相同的配置补丁;
  5. 收尾执行 openclaw models set gpt4free/openclawopenclaw gateway restart

脚本打印的 Next steps 即为验证入口:

g4f client "Hello OpenClaw" --model openclaw
# 或
from g4f.client import Client
client = Client()
resp = client.chat.completions.create(model='openclaw', messages=[{'role':'user','content':'Hello'}])
print(resp.choices[0].message.content)

5. 第四步:验证与联调

5.1 CLI 客户端验证

g4f client "Hello" --model openclaw

g4f client 模式由 g4f/cli/client.py 实现,走与 Python 客户端相同的路径。

5.2 Python 客户端验证

客户端实现位于 g4f/client/init.py:Client 提供 chat.completions.create(...)images.generate(...) 等 OpenAI 风格接口,支持 stream=Trueresponse_formatmax_tokensstop、工具调用等参数。未指定 provider 时默认走 AnyProvider 自动选择,因此 model="openclaw" 这类自定义路由名可直接透传到路由层:

from g4f.client import Client

client = Client()
response = client.chat.completions.create(
    model="openclaw",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)

5.3 监控日志

g4f api --debug --port 8080 开启 verbose 日志后,可观察每次请求实际命中哪个 provider、条件求值与 429 缓存失效行为;机器人侧则确认其请求确实落到 http://localhost:8080/v1(常见于"忘记补丁机器人配置"或"服务器未先启动")。

6. 常见坑与排查清单

SKILL.md 列出的 5 个坑,结合源码给出对应排查手段:

现象 排查/解决
机器人连接前未启动服务器 机器人侧连接被拒 g4f api --debug --port 8080,再起机器人;看 access log 是否有请求
config.yaml 路径错误或语法错误 路由不生效、openclaw 模型名无响应 确认文件在 cookies 目录(可 --cookies-dir 显式指定);YAML 缩进错误会被 g4f/cookies.py 捕获并打 Failed to load routing config 警告;可用 RouterConfig.get("openclaw") 确认是否加载成功
缺少 Python 依赖 模块导入失败 pip install -r requirements.txt(含 PyYAML);PyYAML 缺失时 g4f 只警告并跳过 config.yaml
端口不一致 连不上/404 当前源码默认端口是 1337(g4f/config.py DEFAULT_PORT = 1337),务必显式 --port 8080 与补丁里的 baseUrl 对齐
忘记补丁机器人配置 机器人仍走原云端模型 运行 scripts/patch-openclaw.py 或 setup 脚本,再执行 openclaw models set gpt4free/openclawopenclaw gateway restart

7. 完整工作流速查

  1. 安装并配置 gpt4free(见 README.md);
  2. 启动 API 服务器:python -m g4f --port 8080(或 g4f api --debug --port 8080);
  3. (可选)在 cookies 目录创建/编辑 config.yaml,定义如 openclaw 的多 provider 路由(3.5 节);
  4. scripts/patch-openclaw.py(或一体化 scripts/setup-openclaw.sh)把 OpenClaw 的 baseUrl 指向 http://localhost:8080/v1;
  5. 启动机器人,确认其连接 gpt4free;
  6. 监控日志,用 g4f client "Hello" --model openclaw 或 Python 客户端回归验证。

8. 延伸阅读

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.12 K
2.72 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
528
588
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
906
1.83 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
854
1.34 K
docsdocs
暂无描述
Markdown
891
5.79 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.53 K
1.01 K
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.34 K
1.45 K
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
988
506
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
540
384