把 gpt4free 变成 Clawbot/OpenClaw 的本地 LLM 服务器:API 启动、config.yaml 路由与机器人补丁集成指南
本篇基于 gpt4free 仓库中的 SKILL.md 展开,教你把 g4f 作为本地 LLM 服务器运行:启动 OpenAI 兼容 REST API、用 config.yaml 定义带配额与错误条件判断的自定义模型路由,并通过补丁脚本让 Clawbot/OpenClaw 这类机器人直接对接本地端点。读完并跟着操作后,你可以独立完成"安装 → 起服务 → 配路由 → 补机器人配置 → 验证联调"的完整链路,并理解路由决策背后的 QuotaCache、ErrorCounter 与条件表达式实现。
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.py 的 main(),按第一个位置参数选择运行模式(api/gui/client/mcp/auth/pa 等,默认 api)。SKILL.md 推荐两种等价写法:
python -m g4f --port 8080
# 或(显式 api 子命令 + 详细日志)
g4f api --debug --port 8080
API 模式下可用的关键参数(定义于 g4f/cli/init.py 的 get_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 一致(model、messages、stream、max_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.py 中 read_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 login、g4f auth antigravity login 完成认证(auth 模式支持 gemini-cli/antigravity/qwencode/github-copilot,见 g4f/cli/init.py 的 handle_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 是一个幂等的配置补丁脚本,逻辑非常直白:
- 读取
~/.openclaw/openclaw.json;若不存在则提示"请先执行openclaw onboard",直接退出; - 往
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 系服务;
- 写回 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 均可),步骤为:
- 检查 Python 与 g4f 安装(缺失则
pip install -U g4f[all]); - 向
~/.g4f/cookies/config.yaml写入 3.5 节的openclaw路由,并向同目录.env写入POLLINATIONS_API_KEY等环境变量; - 若检测到
openclawCLI 且配置不存在,执行非交互openclaw onboard(以http://localhost:8080/v1为 custom base URL、gpt4free为 provider id、openclaw为 model id); - 内嵌 Python 段执行与 patch-openclaw.py 相同的配置补丁;
- 收尾执行
openclaw models set gpt4free/openclaw与openclaw 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=True、response_format、max_tokens、stop、工具调用等参数。未指定 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/openclaw、openclaw gateway restart |
7. 完整工作流速查
- 安装并配置 gpt4free(见 README.md);
- 启动 API 服务器:
python -m g4f --port 8080(或g4f api --debug --port 8080); - (可选)在 cookies 目录创建/编辑
config.yaml,定义如openclaw的多 provider 路由(3.5 节); - 用 scripts/patch-openclaw.py(或一体化 scripts/setup-openclaw.sh)把 OpenClaw 的
baseUrl指向http://localhost:8080/v1; - 启动机器人,确认其连接 gpt4free;
- 监控日志,用
g4f client "Hello" --model openclaw或 Python 客户端回归验证。
8. 延伸阅读
- SKILL.md:本篇的技能文档原文(最佳实践、坑位、工作流);
- docs/config-yaml-routing.md:
config.yaml路由的完整设计说明(条件语法、配额缓存、错误计数、Python API); - etc/examples/config.yaml:带逐行注释的官方示例路由(含
my-gpt4、yupp-chat、llama-fast三条路由); - scripts/patch-openclaw.py、scripts/setup-openclaw.sh:机器人侧补丁与一体化部署脚本;
- g4f/providers/config_provider.py:
RouterConfig/QuotaCache/ErrorCounter/evaluate_condition实现; - g4f/cookies.py:cookies 目录解析与
config.yaml自动加载时机; - g4f/client/init.py:OpenAI 风格 Python 客户端(
Client/AsyncClient/ClientFactory); - g4f/cli/init.py:API/MCP/auth 等全部 CLI 参数与
run_api_args()启动链路。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0623
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00