osw README

README проекта с github.com/yinxulai/osw. Одним файлом markdown: README.md.

OSW

OSW

Put every LLM channel you own behind one local address. When one goes down, the next one takes over.

English | 简体中文

CI status Test coverage Latest release License: PolyForm Noncommercial 1.0.0 Total downloads GitHub stars Last commit

Node.js >=22 pnpm 12.14.0 Platforms: macOS, Windows, Linux

Every model, one address: automatic failover across all your providers

OSW runs a proxy on your machine. You register all the channels you have — different providers, different accounts, different models — put them in the order you want them tried, and point every AI client at a single local address. From then on it does the work: identify the protocol, pick a channel, send the request, move on when a channel fails, and record exactly what happened.

Your client only ever sees the attempt that succeeded.

OSW is short for One Switch. The name is the product: one switch for every channel you own — one local address going in, one place to configure providers, and one handle to flip when a channel breaks.


Features


Install

Download the installer for your platform from the latest release. Every asset follows OSW-<version>-<os>-<arch>.<ext>, and each installer ships a matching .sha256 file you can verify.

Platform Architecture File to download
macOS Apple silicon OSW-<version>-mac-arm64.dmg
macOS Intel OSW-<version>-mac-x64.dmg
Windows x64 OSW-<version>-win-x64.exe
Windows ARM64 OSW-<version>-win-arm64.exe
Linux x64 OSW-<version>-linux-x86_64.AppImage
Linux ARM64 OSW-<version>-linux-arm64.AppImage
  1. macOS — open the .dmg and drag OSW into Applications. Builds are ad-hoc signed and not notarized, so if macOS blocks the first launch, allow it under System Settings → Privacy & Security, or right-click the app in Finder and choose Open.

  2. Windows — run the .exe. If SmartScreen warns about an unknown publisher, choose More info → Run anyway.

  3. Linux — make the AppImage executable and run it:

    chmod +x OSW-*-linux-*.AppImage
    ./OSW-*-linux-*.AppImage
    

Once installed, OSW lives in the system tray and checks for updates itself. Windows and Linux download and install updates in place; on macOS the ad-hoc signature means it can only check for updates and open the DMG download page.

Next: Up and running in three steps. For a feature-by-feature walkthrough, see the apps/docs handbook (English and Chinese, a Clarify site published to Cloudflare Workers).

Screenshots

The images below follow your GitHub theme and show the English interface.

Logical models: drag to set priority, and every model carries its own recent track record.

Logical models: channel queue with live metrics

Smart Routing: the header switches between a node graph and a plain rule table — two interchangeable modes for "which requests land in which channel group" — and every save is a version you can roll back.

Smart Routing: node graph and request matching

Request Logs: one row per request, expandable into the full execution detail and raw usage.

Request Logs: per-attempt detail and usage

Analytics: success rate, latency, TTFT, TPS, cache hits, model ranking, failure reasons.

Analytics: metric cards, usage distribution and model ranking

Request Rewrite: stat cards, the rule list, and the templates behind New rule.

Request Rewrite: rule list and template menu

Client Config: which clients already point at OSW and which still need editing, with the address and key to copy and the files each one touches — every generated change is versioned and reversible.

Client Config: client list, copyable address and key, generated file versions

Up and running in three steps

1. Add a channel

Open Model Management → New provider. Fill in the name, API key, timeout, and the default endpoint for each protocol this provider speaks.

Then add the real model IDs under that provider (gpt-4.1-mini, deepseek-reasoner, claude-sonnet-4, …) and tick the protocols each one supports. A model that speaks several protocols still occupies a single row in the queue.

2. Order the queue

Go to Logical Models and drag the models you just added into the order you want them tried. Switch off whatever should sit out.

Things worth doing while you're here:

3. Repoint your client

Step 2 of the setup guide is the reference sheet for this local service: the one address a client should point at, and the paths the service accepts. The address is built from the current listener and has a copy button — only one address is shown, and the other spelling (with or without /v1) is demoted to a sentence of explanation, because two addresses that differ by a single /v1 sitting side by side is the most expensive mistake to make here. The accepted-path table is laid out in full — it is the reference sheet itself, so hiding it behind a "show me" row would only add a step.

The same step also answers the other half of the question: it embeds the config editor inline: pick a tool you use, then hit Generate config on the right of the Config content card header (it rewrites the config against the built-in default model) and Save content — Discard edits undoes it. A machine that already has a client installed can instead go to Client Config and hit Generate & apply all, and the app edits that client's own config file, keeping a restorable version beforehand.

The card itself carries nothing beyond that one address and a sentence explaining it. The API key and the model name are not values to copy: any non-empty string works for the key, and any non-empty name works as the model name, so neither belongs where it would read as "there are two values to copy here".

Your client Base URL
OpenAI compatible (Chat Completions / Responses) http://127.0.0.1:9300/v1
Anthropic http://127.0.0.1:9300

⚠️ The trap everyone falls into: Anthropic clients append /v1/messages themselves, so the Base URL stops at the port. Add /v1 and the request becomes /v1/v1/messages, which the proxy does not recognise — you get a 404.

The model name is up to you: default, or any non-empty name. OSW swaps it for the real model ID of whichever channel it selects. If your client insists on an API key, any placeholder will do — the real keys are injected per provider.

Check that the service is alive:

curl http://127.0.0.1:9300/v1/models

The listener host and port live in Settings → Network → Local Listener; save and the proxy moves to the new port.

Under the hood

The rest of this page is the detail behind those promises — skim what you need, and the handbook covers each area in full.

Failover rules

What happens upstream What OSW does
Network error, connection timeout, streaming idle timeout Try the next channel
401, 403 Try the next channel, and count the failure against that provider
408, 429 Try the next channel
5xx Try the next channel
Any other 4xx (a malformed request, say) Returned to you as-is — another channel would not fix it
Breaks off after the response has started streaming to you Aborts the request rather than splicing in another channel's output

The defaults are 3 consecutive failures before a provider enters cooldown, a 30-second initial cooldown that grows with each failure up to 5 minutes, and a 30-second streaming idle timeout. All three live in Settings → Reliability → Failover.

Supported protocols

Protocol Local path Typical upstreams
OpenAI Chat Completions /v1/chat/completions OpenAI, DeepSeek, Volcengine Ark, OpenRouter, Ollama — anything OpenAI compatible
OpenAI Responses /v1/responses Services that implement the Responses API
Anthropic Messages /v1/messages Claude and compatible services

These paths are recognised with or without the /v1 prefix. GET /v1/models is served locally and returns your model names; it is never forwarded upstream.

About protocol conversion: nothing is converted by default — requests pass through untouched, which is both the safest and the fastest behaviour. If you genuinely need a Claude client to talk to an OpenAI-only channel, turn conversion on for that endpoint binding. Conversion is a best-effort compatibility layer and some parameters may be lost; a single failover will only ever consider channels that match natively or that you have explicitly enabled conversion for.

Smart Routing

This is the landing page after install, and it answers one question: which requests belong to which channel group. Two modes, switched from the page header — exactly one is in effect at a time, and neither rewrites the other's definition:

Both modes are versioned separately, and both cover the same everyday behaviour out of the box.

The built-in default logical model is the safety net: anything no policy matches ends up there.

Request Rewrite

Maintain rules on the Request Rewrite page to smooth over small differences between providers:

Three templates ship with it: Override User-Agent (defaults to OSW/<version>), Drop a request header, and Set a request field.

New rules are enabled; disable one from the list if you change your mind. Every change is a structured add/delete/replace and nothing ever executes a script. Response-stage actions only touch complete non-streaming JSON — the body of a streaming response is never rewritten.

Data and privacy

Configuration, logs and request metadata live in one hidden directory in your home folder, and they are split into two SQLite files:

File Contents
~/.osw/config-v1.db Providers, models, routing and rewrite rules — your configuration, worth backing up
~/.osw/data-v1.db Request logs, captured bodies, usage and health state — safe to delete, you only lose history

The development build uses ~/.osw-development instead, so a dev instance never touches your real data.

A few more things worth knowing:

Not supported yet

Better to be clear about the edges than let you find them the hard way:

Local development

Node.js 22+ and pnpm 12 are required (the exact version is pinned by packageManager in the root package.json, so corepack installs it for you):

pnpm install
pnpm dev

Useful commands:

pnpm dev             # dev session: Electron + the console dev server it loads
pnpm dev:all         # everything: the app plus the website and the docs site
pnpm dev:preview     # console only, for looking at the UI in a browser
pnpm dev:www         # marketing site only
pnpm dev:docs        # docs site only
pnpm typecheck       # TypeScript
pnpm lint            # ESLint plus the layering and package-boundary guards
pnpm test            # the whole test suite
pnpm build           # compile every package (no installers)
pnpm build:docs      # build the docs site (Clarify → static output)
pnpm deploy:docs     # publish apps/docs/output to Cloudflare Workers
pnpm release:mac     # build macOS arm64 / x64 installers
pnpm release:win     # build Windows arm64 / x64 installers
pnpm release:linux   # build Linux arm64 / x64 installers

The repository is a pnpm workspace: packages/{contracts,core,console} are libraries that can be consumed on their own, packages/toolkit holds the cross-package development scripts, apps/app is the desktop host, apps/docs is the end-user handbook (a bilingual Clarify site published to Cloudflare Workers; pnpm dev:docs to preview), and Turborepo runs the tasks. The stack is Electron + React + TypeScript + Vite + Drizzle ORM + SQLite.

Design goals, behaviour contracts and acceptance criteria have a single authority in apps/docs/specs/; build and packaging details live in packaging.md. Verbatim upstream API references are kept in apps/docs/upstream/. The layout of apps/docs itself (what each of source/, specs/, upstream/ and assets/ is for) is described in apps/docs/README.md.

Sponsors

Top-tier sponsor

Qiniu Cloud
Qiniu Cloud

Thanks to Qiniu Cloud for sponsoring OSW at the top tier. Qiniu offers object storage, CDN and large-model inference among its cloud services, and its AI inference service ships as a built-in provider preset in OSW — pick Qiniu under Model Management, paste an API key, and it works out of the box.


Feedback

Issues and ideas are welcome in Issues. The version number, operating system, protocol and a redacted runtime log go a long way — but please do not paste API keys, full prompts or other sensitive content.

For questions, ideas and day-to-day chat, join the community on Discord.


Contributors

Contributors

Thanks to everyone who has put work into OSW — code, bug reports, ideas and documentation fixes all count.


License

OSW is released under the PolyForm Noncommercial License 1.0.0.


Friends

osw (yinxulai/osw)

Ищем в базе…

201 ·GitHub
Что это?One Switch — локальный шлюз AI API: направьте своего ИИ-клиента на один локальный адрес, и он автоматически маршрутизирует и переключается между настроенными за ним провайдерами и моделями LLM.
Это облачный сервис или то, что я запускаю на своей машине?Это нативное десктопное приложение на Electron для macOS, Windows и Linux, которое запускает локальный прокси-сервер на 127.0.0.1; облачной составляющей нет.
Как его запустить?Скачайте установщик для своей ОС с GitHub Releases (.dmg для macOS Apple Silicon/Intel, .exe для Windows x64/ARM64, .AppImage для Linux), затем добавьте провайдера с его API-ключом в Model Management, добавьте восходящие модели под ним и задайте их порядок в Model Queue.
Нужны ли мои собственные API-ключи от каждого провайдера?Да, вы предоставляете свой API-ключ для каждого добавленного провайдера (OpenAI, DeepSeek, OpenRouter, Ollama, сервисы, совместимые с Anthropic, и т.д.). Сам ИИ-клиент не нуждается в настоящем ключе, поскольку One Switch подставляет реальный восходящий ключ.
Есть ли подводные камни установки на macOS?Сборка для macOS сейчас подписана только ad-hoc и не нотаризована, поэтому проверка подписи автообновления отключена, а первый запуск может быть заблокирован; нужно разрешить его через System Settings или правый клик > Open в Finder.
Что произойдёт, если соединение оборвётся посреди стрима?One Switch переключает восходящие потоки только до того, как какой-либо ответ отправлен клиенту. Если стриминговый ответ уже начался, а затем соединение прервалось, запрос завершается и логируется как сбой — он никогда не вклеит вывод другой модели в тот же ответ.
Поддерживает ли он Gemini?Пока нет. Сейчас он говорит только на OpenAI Chat Completions, OpenAI Responses и Anthropic Messages; Gemini и пользовательские протоколы числятся запланированными, но недоступны в текущей версии.
Можно исправить причуды провайдера без написания кода?Да — функция Request Rewrite позволяет добавлять, удалять или править заголовки и поля JSON-тела (с поддержкой regex) для каждого провайдера и модели через настраиваемые упорядочиваемые правила, без всякого скриптинга.
Можно вручную выбрать, какая модель обработает следующий запрос?Да, можно перетаскиванием менять порядок очереди или вручную задать предпочтительную модель в любой момент; переключение затрагивает только новые запросы и не прервёт уже идущие, а автоматический failover всё равно сработает, если ваш выбор не удастся.
Какие есть похожие проекты?casbin-gateway, freellmapi, ThinkWatch-Lite, open-codesign, opencodex, magpie, experiential, evenfire
Автор
yinxulai
Размер
70.9 MB
Звёзды
201
Возраст
3 мес
Коммиты · 90 дней