Connect to iRouter with the OpenAI SDK
Configure the compatible endpoint in Python and Node.js and send a text request.
Prerequisites
Prepare Python or Node.js and an iRouter API key. Choose a model that supports Chat Completions from the console catalog. Replace <model-id> with the full ID permitted on your line.
Configuration
Set these variables in the terminal that will run your program. The API endpoint comes from the current gateway configuration and includes /v1.
export IROUTER_API_BASE='https://gateway.irouter.io/v1'
export IROUTER_API_KEY='<your-irouter-api-key>'
export IROUTER_MODEL='<model-id>'Use the equivalent environment variable syntax in PowerShell.
$env:IROUTER_API_BASE = 'https://gateway.irouter.io/v1'
$env:IROUTER_API_KEY = '<your-irouter-api-key>'
$env:IROUTER_MODEL = '<model-id>'Python
Run python -m pip install openai and save this code as example.py.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["IROUTER_API_BASE"],
api_key=os.environ["IROUTER_API_KEY"],
)
result = client.chat.completions.create(
model=os.environ["IROUTER_MODEL"],
messages=[{"role": "user", "content": "Reply with a short greeting."}],
)
print(result.choices[0].message.content)Node.js
Run npm install openai and save this code as example.mjs.
import OpenAI from 'openai';
const { IROUTER_API_BASE, IROUTER_API_KEY, IROUTER_MODEL } = process.env;
if (!IROUTER_API_BASE || !IROUTER_API_KEY || !IROUTER_MODEL) {
throw new Error('Set IROUTER_API_BASE, IROUTER_API_KEY, and IROUTER_MODEL');
}
const client = new OpenAI({ baseURL: IROUTER_API_BASE, apiKey: IROUTER_API_KEY });
const result = await client.chat.completions.create({
model: IROUTER_MODEL,
messages: [{ role: 'user', content: 'Reply with a short greeting.' }],
});
console.log(result.choices[0].message.content);Verify
Run python example.py or node example.mjs in the same terminal. After receiving text, check the model and request in Usage details. Charges follow the actual model and line configuration.
Troubleshooting
Check inherited environment variables, key status, model protocol, line, and IP allowlist. Python uses base_url and Node.js uses baseURL. Use the SDK error status and request identifier to investigate failures, and remove keys before sharing diagnostics.
References
The official references cover SDK installation and client configuration. Use the endpoint and model configured in iRouter. Python SDK · Node.js SDK