在 LangChain 中使用 OAIRoute
- 保留 ChatOpenAI,只改 base_url
- 链、工具、回调全部不用动
- 同一套代码对比不同厂商
第一步:获取 API Key
在 OAIRoute 控制台 创建。
Create one in the OAIRoute console.
第二步:指向网关
装好 langchain-openai 后,保留 ChatOpenAI,只把 base_url 指过来:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="claude-sonnet-5-5",
api_key="YOUR_OAIROUTE_KEY",
base_url="https://api.oairoute.com/v1",
)
print(llm.invoke("用一句话解释什么是 API 网关。").content)After installing langchain-openai, keep ChatOpenAI and just point base_url here:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="claude-sonnet-5-5",
api_key="YOUR_OAIROUTE_KEY",
base_url="https://api.oairoute.com/v1",
)
print(llm.invoke("Explain API gateways in one sentence.").content)第三步:验证
跑一遍上面的脚本。能返回一段正常文本,说明 LangChain 到网关这条链路已经通了。
Run the script above. A normal text response means the LangChain-to-gateway path works.
换模型不用改代码
模型名只是一个字符串。想换厂商,改 model 的值就行:
| 想做什么 | 改什么 |
|---|---|
| 对比两个厂商 | 把 model 换成另一家的模型 ID,其余代码不变 |
| 按环境切换 | 从环境变量读 model 名,dev 用便宜的、prod 用强的 |
| 按实验隔离成本 | 给每个实验单独建 Key,网关按 Key 统计花费 |
LlamaIndex、Vercel AI SDK 以及任何 OpenAI 兼容客户端,接到同一个端点的方式都一样。
The model name is just a string. To change vendors, change the value of model:
| Goal | What to change |
|---|---|
| Compare two vendors | Swap model for another vendor ID; nothing else changes |
| Switch per environment | Read the model name from an env var: cheap for dev, strong for prod |
| Isolate experiment cost | Give each experiment its own key; the gateway reports spend per key |
LlamaIndex, the Vercel AI SDK and any OpenAI-compatible client all connect to the same endpoint the same way.
常见问题
报 model not found
模型 ID 写错了。先调 /v1/models 拿一份准确列表。
流式输出不工作
确认 base_url 以 /v1 结尾,少了这一段请求会 404,看起来像流式中断。
工具调用 / 结构化输出异常
不是所有模型都支持 tool calling。换 claude-sonnet-5-5 通常就好。
model not found
The model ID is wrong. Call /v1/models for the exact list.
Streaming does not work
Make sure base_url ends in /v1; without it the request 404s and looks like a broken stream.
Tool calling or structured output misbehaves
Not every model supports tool calling. Switching to claude-sonnet-5-5 usually fixes it.