OpenRouter連携を別のAPI Gatewayへ移行する方法
Requirements matrix、分離したcredential、protocol別endpoint、contract test、controlled canary、明確なrollback triggerで、reversibleなOpenRouter移行を設計します。
OpenRouter連携の移行は、production全体のBase URLを一度に置き換える作業ではありません。まず、applicationが現在依存しているcontractを記録します。対象はprotocol、SDK method、Model ID、response schema、streaming behavior、tool call、error、retry、usage fieldです。そのうえで、isolated keyと小さなcanaryを使ってcandidate gatewayを検証します。
現在のOpenRouter連携が安定し、そのmodel catalogやrouting behaviorがapplicationに重要なら、移行しない判断が適切な場合もあります。Primary routeを置き換えず、別gatewayをtested backupとして追加することも可能です。Full migrationは、candidateがworkload固有の同じcheckを通過した後に限ります。
この記事では、別gatewayの検証可能な例としてBetterTokenを使います。BetterTokenはOpenRouterのcloneではなく、OpenAI-compatibleという表記だけでmodel、feature、error、usage dataが同一になるわけではありません。
先にmigration scenarioを選ぶ
- 現在のintegration、billing path、model availability、operational behaviorがapplicationの要件を満たすなら、OpenRouterを継続します。
- Primary integrationは変えずに第2経路が必要なら、検証済みbackupを追加します。
- Candidate gatewayがprotocolとmodel要件を満たし、controlled trafficで実際のbehaviorを比較できる段階なら、migration canaryを実行します。
BetterTokenはOpenRouter accountを販売せず、OpenRouterのkeyやbalanceを移行することもできません。検証には自分のBetterToken accountとAPI keyを作り、現在のModel IDとkey requirementをWorkspaceまたは最新documentationから取得します。
Configuration変更前にrequirements matrixを作る
「OpenAI-compatible」はinterfaceの一部を示す言葉であり、service全体のbehaviorを意味しません。2つのgatewayが似たrequestを受け付けても、available model、streaming event、tool-call payload、error body、retry header、rate limit、usage accountingは異なる場合があります。
Candidateを試す前に、各requirementのcurrent behaviorとacceptance criterionを記録してください。
Model数だけでgatewayを選ばないでください。重要なのは、このapplicationに必要なcurrent Model IDとresponse contractが動くかどうかです。Model availabilityとpriceは動的なので、移行時にproviderのcurrent catalogとrate cardを確認します。
Scenario 1:OpenRouterを継続する
解決すべき具体的なgapがなければ、そのまま継続します。ApplicationがOpenRouterのcurrent catalog、routing、header、response behaviorに依存している場合、目的のない移行は見返りなしにfailure modeを増やします。
将来のportabilityには備えられます。
- Base URL、API key、Model IDをconfigurationへ移す
- Applicationが使うresponse fieldとerror fieldをdocument化する
- Provider-specific headerをshared request logicから分離する
- Isolated keyで実行できるcontract testを追加する
- Rollback ownerと許可するretry policyを記録する
これにより、production trafficを変えずに将来のmigration riskを下げられます。
Scenario 2:検証済みbackupを追加する
Backup routeは、primary routeと同じcontract testを通過して初めて役立ちます。Provider configurationは分離し、別requestが成功することを示すだけのためにOpenRouter settingsを上書きしないでください。
Fallback対象にするfailureを正確に定義します。Authentication failure、invalid Model ID、unsupported method、malformed request、その他多くのclient errorは、別providerへ自動retryすべきではありません。Transient failureでも、fallbackはidempotency、retry limit、timeout budget、candidateのfeature supportに制約されます。
Applicationに検証済みidempotency mechanismがあり、destination stateを確認できる場合を除き、同じmutating operationを2つのgatewayへ送らないでください。Backupは、すべてのrequestの完了や同一outputを保証しません。
Scenario 3:Canaryで移行する
Candidateがisolated testを通過し、primary routeの変更が目的ならcanaryを使います。まずnon-critical trafficの小さくcontrolledな部分だけを送ります。Observation windowとrollback checkが完了するまでcurrent routeを残してください。
Canary開始前にsuccessを定義します。
- Expected response schemaをfallback codeなしでparseできる
- Required streamingとtool-call behaviorが合格する
- Error typeを分類できる
- Usage recordをapplicationのaccepted boundary内で照合できる
- Latency、timeout、retry behaviorがdefined thresholdを満たす
- Duplicateまたはmissing side effectがない
Required conditionが1つでも失敗したら拡大を止め、new trafficをknown-good configurationへ戻します。
5ステップのmigration手順
ステップ1:Current contractを棚卸しする
Exact protocol、SDKとmethod、OpenRouter Base URL、Model ID、authentication variable、provider-specific header、streaming mode、tool use、timeout policy、retry policy、error field、request ID、usage fieldを記録します。
Hard requirementと変更可能なitemを分けます。Logging fieldは置き換えられても、production automationが使うtool-call contractは置き換えられないかもしれません。
WorksheetへAPI keyをcopyしないでください。Secretのvariable nameとstorage locationだけを記録します。
ステップ2:Isolated candidate configurationを作る
Candidate gatewayで別のtest keyを作ります。Production keyを再利用せず、secretをrepositoryへcommitしないでください。
BetterTokenでは自分のaccountを使い、Workspaceまたは現在のAPI documentationに表示されるcurrent Model IDとkey requirementを選びます。古いtutorialのModel IDをhardcodeしないでください。
Candidate configurationは、current OpenRouter configurationを上書きせず、並べて分離します。この分離によりcomparisonとrollbackが可能になります。
ステップ3:Protocolに合うBase URLを設定する
OpenAI-compatible BetterToken clientでは、次を使います。
Anthropic-compatible clientのBetterToken Base URLはhttps://bettertoken.aiで、/v1は付けません。OpenAI-compatibleのPython request shapeをAnthropic-compatible clientへ流用せず、そのpathのSDKとprotocol documentationに従ってください。
Clientがversion付きBase URLを要求するのか、pathの一部を自動でappendするのか確認します。/v1の重複や欠落はconfiguration errorであり、gateway全体が利用できない証拠ではありません。
ステップ4:同じminimal requestとcontract testを実行する
Applicationと同じSDK familyとmethodを使います。次のPython exampleは、environment variableを使ったOpenAI-compatible Chat Completions requestを検証します。
Placeholderは意図的です。Real keyはprojectのsecret mechanismからloadし、current Model IDはtest時点でproviderから取得してください。
Basic requestの後、production applicationが依存するならstreaming、tool call、invalid authentication、invalid Model IDを個別にtestします。Timestamp、status、利用可能ならrequest ID、response shape、usage field、application resultというnon-sensitive evidenceを記録します。
ステップ5:Canaryを送り、比較して判断する
Non-critical trafficのcontrolledな一部をcandidateへrouteします。Representative windowで両routeを比較してください。
- Success数と分類済みerror数
- Latency distributionとtimeout behavior
- Retry数と、存在する場合の
Retry-Afterhandling - Response schemaとtool-call schema
- Streaming completion
- Input、cached input、output usage
- Provider側のstatusとcharge record
- Duplicate、missing、delayed side effect
すべてのhard requirementが通過してからtrafficを増やします。Rollback triggerが発生したらnew trafficをOpenRouterへ戻し、candidateはofflineで調査してください。
Successful response以外も検証する
Successful HTTP statusで分かるのは、1つのrequestが返ったことだけです。Protocol equivalence、production readiness、正しいroutingまでは証明できません。
Errorを意図的に検証する
Isolated test keyでcontrolled failureを発生させます。
- Invalid Model ID
- Revokeした、または意図的にinvalidなtest key
- 安全に試せる場合はunsupported method
- Non-production environmentでのtimeout
HTTP status、error body、request ID、retry metadata、client behaviorを確認します。Terminal errorが無限にretryされず、logではcredentialとsensitive request contentがredactされることを確かめてください。
OpenRouter error referenceはOpenRouterのbehaviorを説明します。Candidateのcurrent documentationとobserved responseは別contractとして扱います。
Usageを照合する
SDKが返すusage objectをapplication logとprovider account recordに照らします。Required fieldにはinput token、cached input、output token、provider-specific unitなどがあります。
BetterToken Dashboardではrequest時刻、model、status、input、output、cache token、対応するchargeを確認できます。これはcomplete promptやresponseが保存・表示されるという意味ではありません。Test時刻と他のnon-secret metadataでrecordを照合し、successful replyだけからrouteを推測しないでください。
Streamingとtool callを別々にtestする
Streamingでは、first event、content delta、finish reason、提供される場合はfinal usage、disconnect handling、partial answerとcompleted answerをapplicationが区別できるかを確認します。
Tool callでは、tool name、call ID、serialized argument、validation failure、result submission flowを比較します。最初のtestにはread-only toolを使ってください。Normal text responseではtool-call pathのcompatibilityは証明できません。
Rollbackの境界
Canary開始前に、rollbackを明確かつreversibleにします。
次のようなhard requirement failureでは、すぐにrollbackします。
- Applicationがresponseまたはerror schemaをparseできない
- Required streamが不完全なまま終了する
- Tool-call argumentまたはIDが壊れる
- Required billing controlのためのusageを照合できない
- Timeoutまたはerror behaviorが合意したoperational thresholdを超える
- Mutating workflowで結果が不明、重複、欠落のいずれかになる
Rollback時は次の順で進めます。
- Candidate trafficの拡大を止める
- New requestをknown-good OpenRouter configurationへ向ける
- Outcomeが不明なmutating requestを自動でreplayしない
- Diagnosis用にtimestamp、request ID、status code、redacted logを保存する
- 原因が分かるまでcandidate keyをisolatedに保ち、不要ならrevokeする
Migration ownerがobservation window、rollback test、downstream reconciliationを確認するまで、old configurationやcredentialを削除しないでください。両routeをactiveにするなら、ownership、health check、eligible fallback error、maximum retry budgetをdocument化します。
Costとoperationの確認
Migration runbookへfixed priceを書かないでください。Test日に各providerのcurrent rate cardを読み、実際に記録されたusageと比較します。
Decisionには次を含めます。
- Modelとfeature availability
- Input、cached input、output rate
- 支払時に表示されるminimum fundingまたはaccount requirement
- Requestとconcurrency limit
- Timeoutとretry behavior
- Usage exportまたはDashboard visibility
- Key rotationとper-project control
- Supportとincident escalation path
BetterTokenでは古いscreenshotやcopyしたrateではなく、現在のpricing pageとWorkspaceを使います。このserviceはcandidate gatewayの1つであり、すべてのOpenRouter workloadを変更なしで移行できる証拠ではありません。
最終decision checklist
次の場合はOpenRouterを継続します。
- 具体的なintegrationまたはoperational gapがない
- Current catalogとcontractが必要
- Candidateがhard requirementを通過していない
次の場合はbackupを追加します。
- 第2routeに独立した価値がある
- 同じprotocol、error、usage、feature testを通過した
- Fallback ruleがboundedかつobservable
次の場合はmigrateします。
- Candidateがすべてのhard requirementを満たす
- Canaryがaccepted errorとlatency threshold内に収まる
- Usageとbilling recordを照合できる
- Rollbackをtest済みで、今も機能する
OpenAI-compatibleという表記はtest planの出発点であり、完全なequivalenceを示すevidenceではありません。最も安全なmigrationは、isolated、observable、incremental、reversibleです。
BetterTokenがintegrationのcandidateなら、現在のAPI documentationから始め、別のtest keyを作り、production trafficを変える前に5ステップのcanaryを実行してください。