metapi-go

module
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: AGPL-3.0

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、GitHub Copilot

特性

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

界面预览

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

快速开始(3 分钟)

推荐从 GHCR 拉取预构建 Docker 镜像,无需在部署机器上安装 Go、Bun 或编译源码。不使用 Docker 时,也可选择 Release 二进制或源码构建。配置 AUTH_TOKEN 后启动并登录后台,在「API 密钥」创建下游访问令牌。旧版本的根密钥会在升级时自动迁入。

方式一:GHCR Docker 镜像(推荐)

稳定部署使用完整版本标签或 digest;下例使用 0.27.0。镜像支持 linux/amd64 与 linux/arm64,Docker 自动选择匹配架构。edge 跟随 master,latest 只随稳定发布更新。升级前在 Releases 查看版本说明。

export AUTH_TOKEN=$(openssl rand -hex 32)
export ACCOUNT_CREDENTIAL_SECRET=$(openssl rand -hex 32)

docker pull ghcr.io/deliciousbuding/metapi-go:0.27.0
docker run -d --name metapi \
  -p 127.0.0.1:4000:4000 \
  -e AUTH_TOKEN \
  -e ACCOUNT_CREDENTIAL_SECRET \
  -e TZ=Asia/Shanghai \
  -v metapi_data:/app/data \
  --restart unless-stopped \
  ghcr.io/deliciousbuding/metapi-go:0.27.0

默认仅本机可访问。需要从其他设备访问时,经反向代理配置 TLS,或明确调整端口绑定。示例生成的管理令牌与加密密钥应保存到自己的密码管理器;也可先生成并设置为环境变量,再传给容器。

命名卷首次挂载继承镜像内属主;改用 bind mount(./data:/app/data)需先在宿主机 chown -R 1001:1001 ./data。使用仓库 Compose(Docker Compose >= 2.24):

cp .env.example .env   # 替换管理令牌和独立加密密钥;METAPI_IMAGE 已钉在 0.27.0
# .env 中其他运行配置也会传入容器,包括 PostgreSQL 和签到开关
docker compose pull
docker compose up -d

需要从源码构建镜像时使用 docker build -t metapi-go:dev .;更多部署选项见 部署指南。

方式二: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)      # 管理后台登录令牌
metapi

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

方式三:源码构建

需要 Go 1.26.10+ 与 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 ./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)。

第一个代理请求

在界面里添加至少一个上游站点与账号,再为要暴露的模型建一条路由,或在「设置 → 运维 → 任务调度」开启「自动创建模型路由」后重建(默认关闭;通道按账号模型可用性绑定),并在「API 密钥」创建允许该模型的令牌。把它设为 DOWNSTREAM_API_KEY,然后像调用 OpenAI 一样调用 Metapi:

curl http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $DOWNSTREAM_API_KEY" \
  -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。


部署与配置

环境变量的名称、alias、优先级、默认值和钳制规则由 配置参考统一维护,.env.example 是可直接复制的模板。未设置管理令牌时,首次启动会生成一个并写入 DATA_DIR/admin-token;生产环境还应设置独立的上游凭据加密密钥。下游访问令牌 在「API 密钥」页管理,旧根密钥仅在升级时一次性导入。

健康检查: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/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。

开发

前端设置、定向检查与完整本地门禁见 CONTRIBUTING.md。 常用入口是 make test(Go 快速套件)和 make web-check(前端完整检查); 前端本地开发在 web/ 下运行 bun run dev。命令与 web/package.json 的脚本 由贡献文档维护,这里不再保留第二份清单。

README 记录的最后一次全链路验收是 v0.19.0(安装器 → 真实中继);此后变化的 入口按仓库配置和 CI 核对,不据此声称当前版本已完成同样的端到端验收。版本证据 以 CHANGELOG.md 和 release notes 为准。

贡献与安全

致谢与相关项目

  • Metapi (TypeScript) — 原版 Node.js 实现,本项目为其 Go 重写
  • New API — 感谢项目及贡献者提供 RelayKit 协议转换库。本项目也参考了 New API 的渠道预设、前后端功能、管理界面和交互设计。
  • Magpie — 管理界面的视觉层级、图标使用与交互设计参考;也为供应商、模型与路由的呈现方式提供了借鉴。
  • AxonHub — 渠道类型、平台适配与导入模型的重要参考。
  • One API — 经典 OpenAI 接口聚合

许可证

GNU AGPLv3(AGPL-3.0-only)。本版本起整体采用 AGPLv3;此前已按 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.
user
Package user owns the ordinary user's independent HTTP surface.
Package user owns the ordinary user's independent HTTP surface.
internal
admintoken
Package admintoken generates the admin bearer token and exposes the one-time on-disk handoff used when no AUTH_TOKEN is configured.
Package admintoken generates the admin bearer token and exposes the one-time on-disk handoff used when no AUTH_TOKEN is configured.
golden
Package golden is a test-only snapshot harness for the protocol-conversion golden suites.
Package golden is a test-only snapshot harness for the protocol-conversion golden suites.
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 resets shared PostgreSQL fixtures between tests.
Package pgtest resets shared PostgreSQL fixtures between tests.
sqlitetest
Package sqlitetest provides isolated, migrated SQLite fixtures for business tests.
Package sqlitetest provides isolated, migrated SQLite fixtures for business tests.
ssrf
Package ssrf provides shared SSRF guards for outbound transports.
Package ssrf provides shared SSRF guards for outbound transports.
trustedproxy
Package trustedproxy carries the per-request "arrived through an explicitly configured reverse proxy" signal from router.TrustedRealIP to downstream consumers that must not trust client-supplied forwarding headers on their own (cookie Secure flags, exported base URLs).
Package trustedproxy carries the per-request "arrived through an explicitly configured reverse proxy" signal from router.TrustedRealIP to downstream consumers that must not trust client-supplied forwarding headers on their own (cookie Secure flags, exported base URLs).
version
Package version exposes the build-time version of the metapi binary.
Package version exposes the build-time version of the metapi binary.
BaseAdapter (base.go) ├── StandardAdapter (standard.go) │ ├── OpenAiAdapter (openai.go) │ ├── ClaudeAdapter (claude.go) │ ├── GeminiAdapter (gemini.go) │ │ └── GeminiCliAdapter (gemini_cli.go) │ └── CliProxyApiAdapter (cliproxyapi.go) ├── CodexAdapter (codex.go) ├── AntigravityAdapter (antigravity.go) ├── OneApiAdapter (oneapi.go) │ └── OneHubAdapter (onehub.go) │ └── DoneHubAdapter (donehub.go) ├── VeloeraAdapter (veloera.go) ├── Sub2ApiAdapter (sub2api.go) └── NewApiAdapter (newapi.go)
BaseAdapter (base.go) ├── StandardAdapter (standard.go) │ ├── OpenAiAdapter (openai.go) │ ├── ClaudeAdapter (claude.go) │ ├── GeminiAdapter (gemini.go) │ │ └── GeminiCliAdapter (gemini_cli.go) │ └── CliProxyApiAdapter (cliproxyapi.go) ├── CodexAdapter (codex.go) ├── AntigravityAdapter (antigravity.go) ├── OneApiAdapter (oneapi.go) │ └── OneHubAdapter (onehub.go) │ └── DoneHubAdapter (donehub.go) ├── VeloeraAdapter (veloera.go) ├── Sub2ApiAdapter (sub2api.go) └── NewApiAdapter (newapi.go)
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.
Package events is the single source of truth for structured event emission.
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).
upstream
Package upstream owns transactional changes to the direct-upstream graph.
Package upstream owns transactional changes to the direct-upstream graph.
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.
anthropic/messages
Package messages bridges Anthropic Messages and OpenAI Chat Completions.
Package messages bridges Anthropic Messages and OpenAI Chat Completions.
ollama
Package ollama translates the native Ollama Chat wire protocol to OpenAI Chat.
Package ollama translates the native Ollama Chat wire protocol to OpenAI Chat.
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.
relaykitbridge
Package relaykitbridge adapts RelayKit's four conversational protocols to the gateway's byte-oriented conversion boundary.
Package relaykitbridge adapts RelayKit's four conversational protocols to the gateway's byte-oriented conversion boundary.
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