metapi-go

module
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT

README

Metapi Go

Metapi Go

中转站的中转站 —— 把分散的 AI API 站点聚合为一个统一网关

将你在各处注册的 New API / One API / OneHub / Sub2API 等站点,
汇聚成一个 API Key、一个入口:自动发现模型、智能路由、成本最优。

中文 · English

CI Release Docker Go License

特性 · 界面 · 快速开始 · 部署与配置 · 迁移 · 限制


什么是 Metapi

AI 生态里基于 New API / One API 系列的聚合中转站越来越多,多站点的余额、模型列表和 API 密钥往往分散在各处。Metapi 是这些中转站之上的元聚合层(Meta-Aggregation Layer):把多个站点统一到一个入口,下游所有工具(Cursor、Claude Code、Codex、Open WebUI 等)即可无感接入全部模型。

支持的上游:

  • 聚合面板:New API、One API、OneHub、DoneHub、Veloera、AnyRouter、Sub2API
  • 通用兼容接口:OpenAI / Claude / Gemini 兼容端点,以及 cliproxyapi / CPA
  • OAuth 连接:Codex、Claude、Gemini CLI、Antigravity

特性

能力 说明
16 个上游适配器 New API / One API / OneHub / DoneHub / Veloera / AnyRouter / Sub2API / OpenAI / Claude / Gemini / Gemini CLI / Codex / Antigravity / Grok / CLIProxyAPI / SenseTime
统一代理 OpenAI 与 Claude 双协议:Chat / Responses / Messages / Embeddings / Images / Models / Files,全量 SSE 流式,自动互转
路由与容错 模型自动发现、零配置建路由;按成本/余额/使用权重分配多通道;失败通道自动冷却并重试下一通道;运行时熔断 + half-open 探测
计费真值 四级成本信号(实测 → 账号配置 → models.dev 目录参考价 → 兜底);使用日志逐请求记录 Token 与成本
管理 UI 站点 / 账号 / 路由 / 模型 / 日志 / 告警一站管理,React SPA 预构建后嵌入二进制,无需额外前端服务
运营自动化 定时签到、定时余额刷新、九种告警渠道、模型批量验证、审计日志、实时 QPS 面板
轻量部署 单二进制即跑;SQLite 默认、PostgreSQL 可选;启动自动执行幂等 schema 升级
桌面外壳 Electron 薄壳(托盘 + 原生通知,electron/README.md);手动构建,不含在 Release 产物中
TS 版无缝接管 同数据库 Schema、同环境变量名、同 API 契约;停旧服务、用同样环境变量启动即完成接管

界面预览

仪表盘
仪表盘 — 余额分布、签到与定时任务健康
模型市场
模型市场 — 跨站模型覆盖、品牌与实测指标
智能路由
智能路由 — 多通道概率分配、成本优先选路
账号管理
账号管理 — 多站点多账号、健康状态追踪
站点管理
站点管理 — 上游站点配置与状态一览
使用日志
使用日志 — 代理请求日志与成本明细
模型操练场
模型操练场 — 在线对比不同通道输出
系统设置
系统设置 — 全局参数、主题与安全配置

快速开始(3 分钟)

三种等价方式,任选其一。启动只需要两个令牌:AUTH_TOKEN(管理后台登录)与 PROXY_TOKEN(下游调用 /v1/* 的 Key)。

方式一:Release 二进制(推荐)

发布页提供 Linux / macOS / Windows 预编译二进制,单文件即跑:

curl -fsSL https://github.com/DeliciousBuding/metapi-go/releases/latest/download/install.sh | bash

export AUTH_TOKEN=$(openssl rand -hex 16)      # 管理后台登录令牌
export PROXY_TOKEN=sk-$(openssl rand -hex 24)  # 下游客户端调用 /v1/* 的 Key
metapi

脚本自动校验 SHA-256 并安装到 /usr/local/bin/metapi(默认安装最新发布,METAPI_VERSION 可钉住版本,METAPI_INSTALL_PREFIX 可换安装目录)。Windows 直接从 Releases 下载 metapi-windows-amd64.exe。

方式二:Docker(命名卷,零配置)

docker run -d --name metapi \
  -p 4000:4000 \
  -e AUTH_TOKEN=your-admin-token \
  -e PROXY_TOKEN=your-proxy-sk-token \
  -e ACCOUNT_CREDENTIAL_SECRET=$(openssl rand -hex 32) \
  -e TZ=Asia/Shanghai \
  -v metapi_data:/app/data \
  --restart unless-stopped \
  ghcr.io/deliciousbuding/metapi-go:latest

命名卷首次挂载自动继承镜像内属主,开箱即用;改用 bind mount(./data:/app/data)需先在宿主机 chown -R 1001:1001 ./data。Compose 方式(生产硬化配置):

cp .env.example .env   # 填入 AUTH_TOKEN / PROXY_TOKEN / ACCOUNT_CREDENTIAL_SECRET
docker compose -f docker-compose.prod.yml up -d

方式三:源码构建

需要 Go 1.26+ 与 Bun 1.x。前端必须先构建——产物经 go:embed 打包进二进制,跳过会报 pattern dist: no matching files found:

git clone https://github.com/DeliciousBuding/metapi-go.git
cd metapi-go
cd web && bun install --frozen-lockfile && bun run build:web && cd ..
go build -o metapi ./cmd/server
AUTH_TOKEN=your-admin-token PROXY_TOKEN=your-proxy-sk-token ./metapi

验证

curl http://localhost:4000/health
# {"status":"ok"}
curl http://localhost:4000/ready
# {"status":"ok","database":"ok"}

打开 http://localhost:4000,用 AUTH_TOKEN 登录。数据默认存放在 ./data(SQLite)。端口被占用时用 PORT=<端口> 覆盖(默认 4000)。

第一个代理请求

在界面里添加至少一个上游站点与账号、执行「重建全部路由」后(完整流程见 快速上手),像调用 OpenAI 一样调用 Metapi:

curl http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $PROXY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<任意已路由模型>",
    "messages": [{ "role": "user", "content": "hello" }]
  }'

Metapi 自动在所有上游站点中选择成本最优、状态健康的通道;通道失败自动冷却并重试下一个。未配置任何路由时返回如实的 503:

{ "error": { "message": "No available channels", "type": "server_error", "request_id": "…" } }

Claude 原生格式(/v1/messages)、Responses、Embeddings、Images、/v1/models 与 /v1/files 同样支持;完整端点清单见 HTTP API,客户端接入见 client-integration。


部署与配置

全部配置由环境变量驱动,启动只需两个必填项:

变量 说明
AUTH_TOKEN 管理后台登录令牌
PROXY_TOKEN 下游客户端调用 /v1/* 的 Key

常用项:

变量 默认值 说明
ACCOUNT_CREDENTIAL_SECRET 回退 AUTH_TOKEN 上游凭据加密密钥,建议 32+ 字节随机串
PORT 4000 监听端口
DATA_DIR ./data 数据目录(SQLite 库与上传文件)
DATABASE_URL 空 PostgreSQL 连接串;留空使用 SQLite
LOG_LEVEL info 日志级别:debug / info / warn / error
CHECKIN_CRON 0 8 * * * 签到时间
BALANCE_REFRESH_CRON 0 * * * * 余额刷新频率

完整清单(约 150 项)见 配置参考 与 .env.example。

健康检查:GET /health(liveness)、GET /ready(readiness,检查数据库);Docker 镜像内置 metapi healthcheck 等价探测 /ready。

深入阅读:

文档 用途
docs/getting-started.md 快速上手:安装到第一个代理请求
docs/deployment.md 反向代理 / TLS / PostgreSQL / 备份 / 升级回滚
docs/configuration.md 环境变量完整参考
docs/client-integration.md 客户端接入(Cursor / Claude Code / Codex / Open WebUI)
docs/api.md HTTP API 端点清单
docs/migration.md TS → Go 迁移(SQLite / PG / MySQL)
docs/faq.md 常见问题
docs/api/routes-inventory.md 已注册 /api 路由全量清单(由 docs/api_inventory_parity_test.go 与代码对账)
docs/configuration.md 每个环境变量的真实默认值与钳制规则(由 docs/env_parity_test.go 与 .env.example、config/config.go 对账)
docs/architecture.md 分层与所有权边界、一次 /v1 请求经过哪些阶段(改代码或排查归属前读)
CHANGELOG.md 版本变更

从 TypeScript 版迁移

数据库 Schema 完全一致:停止旧服务,用同样的环境变量启动 Go 版即可,启动时自动执行幂等迁移。SQLite / PostgreSQL 直接接管,MySQL 需先经 TypeScript 版内置迁移转出。Go 镜像以 uid 1001 运行,旧版 root 写入的 bind mount 目录需先 chown -R 1001:1001 ./data(命名卷无需处理)。完整步骤、metapi-migrate 工具与回滚方案见 迁移指南。

已知限制

  • 少量管理端点当前如实返回 501(未实现),清单见 api.md 中的「501 残留」标注。
  • 代理上游未配置时返回 503,不做合成成功响应。
  • 单进程语义为主;多实例部署的共享语义(Redis 共享 RPM/TPM 准入、PostgreSQL advisory lock)见 FAQ。

开发

后端(Go)

make build    # 构建
make test     # 全部测试(含 -race)
make vet      # go vet
make lint     # golangci-lint
make vuln     # govulncheck 漏洞扫描

前端(web/,Bun)

cd web
bun install
bun run dev         # 本地开发(/api /v1 代理到后端 :4000)
bun run typecheck   # tsgo 类型检查
bun run test        # vitest 全量
bun run build       # rsbuild 构建(产物经 go:embed 打包进 Go 二进制)

贡献流程(分支模型、PR 门禁)见 CONTRIBUTING.md。

验证说明

本项目的文档命令按以下口径核实,集中说明一次,正文不再重复:

路径 核实口径
Release 二进制:安装 → 启动 → 健康检查 端到端实测(v0.16.20)
源码构建:前端构建 → go build → 启动 端到端实测
Docker / Compose 命令 与仓库 Dockerfile / docker-compose.prod.yml 逐项核对
未配置路由返回 503、健康检查退出码 实测

贡献与安全

相关项目

许可证

MIT。Metapi 完全自托管:所有数据存储在你自己的部署环境中,代理请求仅在你的服务器与上游站点之间直连传输。

Directories

Path Synopsis
app
observability
Package observability is a true leaf (stdlib-only) holding cross-cutting counters that lower layers (scheduler) must record without importing handler/shared or app.
Package observability is a true leaf (stdlib-only) holding cross-cutting counters that lower layers (scheduler) must record without importing handler/shared or app.
Package auth provides admin and downstream proxy authentication middleware with IP allowlisting and rate limiting.
Package auth provides admin and downstream proxy authentication middleware with IP allowlisting and rate limiting.
cmd
migrate command
Command metapi-migrate is a standalone CLI that transfers all 18 application tables between a SQLite database and a PostgreSQL database (either direction).
Command metapi-migrate is a standalone CLI that transfers all 18 application tables between a SQLite database and a PostgreSQL database (either direction).
server command
Package config loads and validates all server configuration from environment variables.
Package config loads and validates all server configuration from environment variables.
Package e2e contains end-to-end integration tests for the proxy pipeline.
Package e2e contains end-to-end integration tests for the proxy pipeline.
handler
admin
Package admin implements the REST API handlers for the admin dashboard.
Package admin implements the REST API handlers for the admin dashboard.
proxy
Package proxyhandler implements the OpenAI-compatible proxy endpoint handlers.
Package proxyhandler implements the OpenAI-compatible proxy endpoint handlers.
shared
Package shared provides common HTTP handler utilities used across admin and proxy handler packages.
Package shared provides common HTTP handler utilities used across admin and proxy handler packages.
internal
golden
Package golden is a test-only snapshot harness for the protocol-conversion golden suites (P0-1).
Package golden is a test-only snapshot harness for the protocol-conversion golden suites (P0-1).
httpclient
Package httpclient is the shared construction point for outbound HTTP transports and clients outside the platform site-proxy regime.
Package httpclient is the shared construction point for outbound HTTP transports and clients outside the platform site-proxy regime.
pgtest
Package pgtest is a test-only helper for the PostgreSQL-gated suites (PG_TEST_DSN).
Package pgtest is a test-only helper for the PostgreSQL-gated suites (PG_TEST_DSN).
ssrf
Package ssrf provides shared SSRF guards for outbound transports.
Package ssrf provides shared SSRF guards for outbound transports.
version
Package version exposes the build-time version of the metapi binary.
Package version exposes the build-time version of the metapi binary.
Package proxy implements the dual-loop proxy orchestration core with channel retry, session leasing, and failure classification.
Package proxy implements the dual-loop proxy orchestration core with channel retry, session leasing, and failure classification.
types
Package types holds shared type definitions for the proxy module.
Package types holds shared type definitions for the proxy module.
Package routing implements the token-based channel selection engine with Fibonacci backoff cooldown and weighted random distribution.
Package routing implements the token-based channel selection engine with Fibonacci backoff cooldown and weighted random distribution.
Package scheduler manages background job schedulers for checkin, balance, cleanup, and aggregation.
Package scheduler manages background job schedulers for checkin, balance, cleanup, and aggregation.
Package service contains the business logic layer: checkin, balance, notify, OAuth, and backup services.
Package service contains the business logic layer: checkin, balance, notify, OAuth, and backup services.
catalogsync
Package catalogsync owns the model-catalog data source registry: a DB-persisted, ordered list of catalog sources (llm-metadata / models.dev presets plus operator-added custom URLs) that are fetched in order and merged first-wins into the runtime catalog snapshot consumed by routing and the models marketplace.
Package catalogsync owns the model-catalog data source registry: a DB-persisted, ordered list of catalog sources (llm-metadata / models.dev presets plus operator-added custom URLs) that are fetched in order and merged first-wins into the runtime catalog snapshot consumed by routing and the models marketplace.
events
Package events is the single source of truth for structured event emission (F5).
Package events is the single source of truth for structured event emission (F5).
pricing
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens.
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens.
pricingcatalog
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router.
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router.
prompt_filter
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok).
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok).
Package store provides the database layer with SQLite and PostgreSQL dual-dialect support.
Package store provides the database layer with SQLite and PostgreSQL dual-dialect support.
Package transform provides protocol conversion between OpenAI, Anthropic, Gemini, and Codex formats via a canonical intermediate representation.
Package transform provides protocol conversion between OpenAI, Anthropic, Gemini, and Codex formats via a canonical intermediate representation.
openai/completions
Package completions provides OpenAI Completions (legacy) transformer — pass-through.
Package completions provides OpenAI Completions (legacy) transformer — pass-through.
openai/embeddings
Package embeddings provides OpenAI Embeddings transformer — pass-through.
Package embeddings provides OpenAI Embeddings transformer — pass-through.
openai/images
Package images provides OpenAI Images transformer — pass-through.
Package images provides OpenAI Images transformer — pass-through.
openai/responses
Package responses provides OpenAI Responses API transformer and compact mode.
Package responses provides OpenAI Responses API transformer and compact mode.
Package web bundles the built React SPA frontend via go:embed.
Package web bundles the built React SPA frontend via go:embed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL