new-api-vision-proxy

    High-performance MoonBit vision routing proxy for New API (caption user images with xing-vl2.0 before forwarding to Xing4.1-Preview)

    openai
    new-api
    vision
    proxy
    moonbit
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    11 hours ago
    Downloads
    9

    #new-api-vision-proxy (MoonBit)

    用 MoonBit Native 重写的 New API 高性能多模态视觉路由代理(/opt/new-api-vision-proxy/proxy.py 的原生无依赖替代实现)。

    默认监听 127.0.0.1:3001 并反向代理至 127.0.0.1:3000(New API):
    1. 非目标模型或纯文本请求零解析直通:单遍字节预检顶层 model 字段,非 Xing4.1-Preview 请求在百纳秒内直接原样透传,避免整包 JSON 反序列化。
    2. 多模态带图请求自动转述改写:当 POST /v1/chat/completions 目标模型为 Xing4.1-Preview(大小写不敏感)且 user 消息含图片(image_url / image)时,自动调用 xing-vl2.0 提取客观视觉描述,将图片替换为 【附图的视觉观察】\n<描述> 后再交由 Xing4.1-Preview 生成并逐块流式返回 SSE。
    3. O(1) 内存缓存 + 并发合并 + 异步双段日志持久化:带 Authorization 的内联 data: 图片按 SHA-256(auth + "\0" + prompt + "\0" + canonical_part)(与原版 Python proxy.py 缓存键公式逐字节一致)隔离缓存,默认保留 1 万条、TTL 30 天;同一张图的并发请求通过 @cond_var.Cond 合并为单次上游识图调用;远程 http(s):// 图片每次实时识别。


    #核心优化(相对原版 Python proxy.py)

    1. 双端 HTTP/1.1 Keep-Alive + 128 上游连接池 + DNS/IP 缓存(proxy/proxy.mbt):消除原版每请求新建并关闭 HTTPConnection 导致的动态端口耗尽(TIME_WAIT / HTTP 502),视觉子请求完成后热连接直接归还连接池供紧随其后的文本阶段复用。
    2. 零 DOM 字节级扫描与手术拼接 + 自动 DOM 回退(vision/rewrite.mbt):常规多模态请求直接在原始 UTF-8 Bytes 上定位图片切片并 FixedArray::blit_from_bytes 拼装请求体,零百万字节字符串编解码;遇到转义斜杠(\/)、扩展字段等复杂格式自动无缝回退 @json.parse,且两条路径生成完全一致的缓存键。
    3. 100% 纯 MoonBit SHA-256(internal/sha256/sha256.mbt):直接复用官方 moonbitlang/x/crypto 的 SHA256 增量接口,对原请求缓冲区中的 BytesView 切片原地零拷贝哈希,零 C 代码、零 OpenSSL 外部依赖。
    4. 纯内存 O(1) 命中 + 后台异步双段追加日志(cache/store.mbt):移除原版每次缓存命中都在全局锁内执行 SQLite UPDATE last_used_at + commit() 的阻塞开销;磁盘持久化在 moonbitlang/async/fs 线程池中每 200ms 批量顺序写 captions.{0,1}.log,支持双段轮转压缩与崩溃截断尾部自愈。
    5. 读写系统调用合并 + 首包 TTFB 指标日志:中小包头体合并为单次 Tcp::write,SSE 每个 chunk 合并为单次写;在保留原版 vision-assist images=... reused=... vision=...s text=...s status=... 日志格式完全兼容的基础上追加 ttfb=...s,便于定位文本上游首 token 排队延迟。
    6. Linux 多 Worker 扩展:支持 -j / --workers <N> 基于 Linux SO_REUSEPORT 多进程分摊多核负载。


    #同机实测性能(vs 硅谷原版 proxy.py)

    测试环境:Windows 11 x86_64(i5-14600KF),16 并发 Keep-Alive,统一连接 test/bench/mock-vision-upstream.mjs 本地模拟上游:

    场景(16 并发)直连模拟上游原版 proxy.py(Python + SQLite WAL)本代理(MoonBit Native Release)提升幅度
    小包 JSON 透传(61 B)34,085 RPS · p50 0.43ms1,748–3,002 RPS · p50 4.19ms · 端口耗尽报 50230,266 RPS · p50 0.49ms · p99 1.01ms · 0 错10×–17× 吞吐,p50 低 8.6×,零报错
    64 KiB + 30 段 SSE 透传17,406 RPS · p50 0.85ms936–1,182 RPS · p50 13.3–17.4ms · 首包 P95 4.1–5.3ms2,703 RPS · p50 5.86ms · 首包 P95 1.22ms · 0 错2.3×–2.9× 吞吐,首包快 3.4×–3.8×
    256 KiB Base64 带图命中 + 30 段 SSE—524–544 RPS · p50 28.1–28.8ms · p99 58.4ms357 RPS · p50 44.32ms · p99 53.70ms · 0 错纯 MoonBit 软件 SHA-256,p99 更稳且无端口/锁报错

    复现命令:
    node test/bench/mock-vision-upstream.mjs 18080 & ./_build/native/release/build/cmd/main/main.exe --listen 127.0.0.1:18081 --upstream 127.0.0.1:18080 & node test/bench/loadgen.mjs 18081 16 3 small node test/bench/loadgen.mjs 18081 16 4 sse64k node test/bench/loadgen.mjs 18081 16 4 vision256k


    #目录结构

    new-api-vision-proxy/ ├── moon.mod # 模块声明与依赖 (moonbitlang/async, spectacleCase/dotenv) ├── facade.mbt # 顶层公共 API 导出门面 ├── config/ # CLI 参数、环境变量与默认值解析 ├── internal/ │ ├── dotenv/ # .env 加载器(进程已有环境变量优先) │ ├── httpparse/ # 单遍零分配 HTTP/1.1 请求/响应头解析与上游序列化 │ └── sha256/ # 纯 MoonBit SHA-256 缓存键计算(基于官方 moonbitlang/x/crypto) ├── cache/ # O(1) 内存缓存 + @cond_var 并发合并 + 异步双段日志持久化 ├── vision/ # 零 DOM 字节级扫描拼接 + @json.parse 自动回退改写器 ├── proxy/ # 双端 Keep-Alive 连接池转发、SSE 流式透传与健康检查 ├── cmd/main/ # 原生可执行入口与 Linux SO_REUSEPORT 多进程监管器 └── test/bench/ # 模拟上游与多场景固定并发压测脚本


    #编译与测试

    #Linux (x86_64 / aarch64)

    moon check --target native moon test --target native moon build cmd/main --target native --release # 产物: _build/native/release/build/cmd/main/main.exe (Linux 下亦为 ELF 可执行文件,可重命名为 new-api-vision-proxy)

    #Windows (MSVC)

    在安装了 Visual Studio Build Tools 的环境下调用 vcvars64.bat 并指定 CC=cl:

    cmd.exe /d /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >nul && set "CC=cl" && moon test --target native && moon build cmd/main --target native --release'


    #运行与配置

    配置优先级:命令行参数 > 系统环境变量 > 工作目录 .env > 内置默认值(默认配置与线上 proxy.py 完全一致,零参数即可直接替换启动)。

    # 默认启动: 127.0.0.1:3001 -> 127.0.0.1:3000, 缓存写入当前目录 captions.{0,1}.log ./new-api-vision-proxy # 自定义监听、上游、缓存目录与 Linux 多 Worker ./new-api-vision-proxy \ --listen 127.0.0.1:3001 \ --upstream 127.0.0.1:3000 \ --cache-dir /opt/new-api-vision-proxy \ --workers 2 # 查看内置运行统计 curl http://127.0.0.1:3001/_vision_proxy/healthz

    #Linux systemd 与 Nginx 部署建议

    1. 将编译好的二进制放到 /opt/new-api-vision-proxy/new-api-vision-proxy(chmod +x),更新 /etc/systemd/system/new-api-vision-proxy.service:
      [Service] Type=simple WorkingDirectory=/opt/new-api-vision-proxy ExecStart=/opt/new-api-vision-proxy/new-api-vision-proxy --cache-dir /opt/new-api-vision-proxy Restart=always RestartSec=2
    2. 建议在 Nginx 配置中为 127.0.0.1:3001 开启上游长连接池,消除 Nginx 到本代理的每请求短连接握手:
      upstream vision_proxy_backend { server 127.0.0.1:3001; keepalive 32; } location = /v1/chat/completions { proxy_pass http://vision_proxy_backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_request_buffering off; proxy_read_timeout 900s; }

    AssistOutcome

    Outcome of inspecting/rewriting a POST /v1/chat/completions body.

    CaptionStore

    Persistent, O(1) in-memory caption store backed by an async 2-segment rotating append-only disk log (captions.0.log / captions.1.log) and zero-lock @cond_var concurrent in-flight deduplication.

    VisionFailure

    Upstream error or invalid caption returned during the vision stage.

    canonical_python_json_bytes

    fn canonical_python_json_bytes(v :
    Json
    ) -> Bytes

    Serialize a Json value in Python json.dumps(..., sort_keys=True) canonical ASCII format (", " / ": " separators, \uXXXX for non-ASCII) so fallback cache keys match proxy.py and the fast-path byte hash 100%.

    config_from_env

    Build base Config from environment variables (call after load_env).

    default_entry_model

    let default_entry_model : String

    default_vision_model

    let default_vision_model : String

    default_vision_prompt

    let default_vision_prompt : String

    Default objective image-captioning prompt matching production proxy.py.

    extract_caption_from_vision_response

    fn extract_caption_from_vision_response(raw : Bytes) -> Result[String,
    VisionFailure
    ]

    Parse the vision upstream JSON response and extract a non-empty, non-SKIP caption string (supporting both plain string and array-of-text content).

    format_ms_as_sec_2dp

    fn format_ms_as_sec_2dp(elapsed_ms : UInt64) -> String

    Format elapsed milliseconds as fixed 2-decimal seconds (0.00, 8.33, etc.).

    handle_connection

    Handle one client TCP connection in an HTTP/1.1 keep-alive loop.

    load_env

    async fn load_env(path? : String) -> Unit

    Load environment variables from a .env file (default: ./.env). Missing or unreadable files are silently ignored.

    maybe_rewrite_vision_chat

    Inspect a POST /v1/chat/completions request body; if it targets cfg.entry_model and contains user images, caption each image (via cache, coalesced in-flight slot, or fetch_vision) and splice the captions in.

    now_unix_sec

    fn now_unix_sec() -> Int64

    parse_config

    Parse CLI flags on top of base (typically config_from_env()).

    wants_help

    fn wants_help(args : Array[String]) -> Bool

    Whether CLI args request --help / -h.

    Source Files