Démarrage rapide
De votre première clé API à votre première requête.
Avant de commencer
Créez un compte et consultez les modèles de ce déploiement. Leurs identifiants, tarifs et endpoints figurent dans Modèles et tarifs.
- Utilisez le projet par défaut ou créez des projets distincts par application et client.
- Créez une clé API et choisissez son projet, ses modèles et son quota.
- Maintenez un solde suffisant sur le compte payeur.
- Utilisez l’URL fournie par votre opérateur. Conservez les clés API sur votre serveur.
Configurer l’environnement serveur
Définissez AI_BASE_URL sur https://easyrouteapi.com et AI_MODEL sur l’identifiant exact d’un modèle Chat Completions du catalogue. Saisissez AI_API_KEY en privé ; ne laissez pas de vraie clé dans l’historique des commandes.
Chaque exemple envoie une seule requête courte, sans streaming ni nouvelle tentative automatique, avec une limite de sortie de 64 tokens. Exécutez l’exemple d’un seul langage, puis consultez les journaux d’utilisation. La limite de tokens ne remplace pas le plafond de dépenses de la clé API.
export AI_BASE_URL='https://easyrouteapi.com'
export AI_MODEL='YOUR_MODEL_ID'
read -rs -p 'EasyRouteAPI key: ' AI_API_KEY; printf '\n'
export AI_API_KEYEnvoyer une requête Chat Completions
Enregistrez ce code dans chat.sh et lancez bash chat.sh avec Bash 4+ et curl 7.76+. La réponse JSON complète est affichée en cas de succès. La clé est transmise à curl par l’entrée standard, pas dans les arguments de commande.
#!/usr/bin/env bash
# Bash 4+ and curl 7.76+. API credentials are sent on stdin, not curl's argv.
set +x
set -euo pipefail
base="${AI_BASE_URL:-https://easyrouteapi.com}"
base="${base%/}"
base="${base%/v1}"
if [[ ! "$base" =~ ^https://[a-zA-Z0-9.-]+(:[0-9]+)?$ && ! "$base" =~ ^http://(localhost|127\.0\.0\.1)(:[0-9]+)?$ ]]; then
echo 'AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.' >&2; exit 1
fi
if [[ ! "${AI_API_KEY:-}" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo 'Set AI_API_KEY in your server environment.' >&2; exit 1
fi
if [[ ! "${AI_MODEL:-}" =~ ^[a-zA-Z0-9_.:/@+-]{1,200}$ || "$AI_MODEL" == 'YOUR_MODEL_ID' ]]; then
echo 'Set AI_MODEL to an available Chat Completions model or route ID.' >&2; exit 1
fi
limit="${AI_MAX_TOKENS:-64}"
if [[ ! "$limit" =~ ^[1-9][0-9]{0,2}$ ]] || (( 10#$limit > 256 )); then
echo 'AI_MAX_TOKENS must be an integer from 1 to 256.' >&2; exit 1
fi
session="${AI_SESSION_ID:-}"
if [[ -n "$session" && ! "$session" =~ ^[a-zA-Z0-9._:-]{1,128}$ ]]; then
echo 'AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.' >&2; exit 1
fi
# Ignore local curlrc defaults; keep TLS verification, no retries or redirects.
# Do not add --verbose or --trace.
set +e
result=$(printf 'header = "Authorization: Bearer %s"\n' "$AI_API_KEY" |
curl --disable --config - --silent --show-error --connect-timeout 10 --max-time 30 \
--request POST "$base/v1/chat/completions" \
--header 'Content-Type: application/json' --header "Session-Id: $session" \
--data-binary "{\"model\":\"$AI_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with OK only.\"}],\"max_tokens\":$limit,\"stream\":false}" \
--write-out $'\n%{http_code}')
result_code=$?
set -e
if (( result_code != 0 )); then
echo 'The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.' >&2; exit 1
fi
status="${result##*$'\n'}"
if [[ "$status" != 2[0-9][0-9] ]]; then
printf 'HTTP %s. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.\n' "$status" >&2; exit 1
fi
# Successful output is the full JSON completion, including token usage if supplied.
printf '%s\n' "${result%$'\n'*}"Appeler depuis un serveur Python
Enregistrez ce code dans chat.py et lancez python3 chat.py avec Python 3.11 ou ultérieur. L’exemple utilise la bibliothèque standard et affiche le texte de l’assistant ; aucun paquet pip n’est nécessaire.
"""One bounded Chat Completions request; Python 3.11+, no pip packages."""
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # Never forward the API key to a redirect target.
def chat(env=os.environ):
base = urllib.parse.urlsplit(env.get("AI_BASE_URL", "https://easyrouteapi.com"))
loopback = base.hostname in ("localhost", "127.0.0.1", "::1")
if ((base.scheme != "https" and not (base.scheme == "http" and loopback))
or not base.hostname or base.username is not None or base.password is not None
or base.query or base.fragment or base.path not in ("", "/", "/v1", "/v1/")):
raise ValueError("AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.")
key = env.get("AI_API_KEY", "")
if not key or key.strip() != key or re.search(r"[\x00-\x20\x7f]", key):
raise ValueError("Set AI_API_KEY in your server environment.")
model = env.get("AI_MODEL", "")
if not re.fullmatch(r"[A-Za-z0-9_.:/@+\-]{1,200}", model) or model == "YOUR_MODEL_ID":
raise ValueError("Set AI_MODEL to an available Chat Completions model or route ID.")
limit = env.get("AI_MAX_TOKENS", "64")
if not re.fullmatch(r"[0-9]{1,3}", limit) or not 1 <= int(limit) <= 256:
raise ValueError("AI_MAX_TOKENS must be an integer from 1 to 256.")
headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
session = env.get("AI_SESSION_ID", "")
if session:
if not re.fullmatch(r"[A-Za-z0-9._:\-]{1,128}", session):
raise ValueError("AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.")
headers["Session-Id"] = session
payload = json.dumps({"model": model, "messages": [{"role": "user", "content": "Reply with OK only."}], "max_tokens": int(limit), "stream": False}).encode()
request = urllib.request.Request(urllib.parse.urlunsplit((base.scheme, base.netloc, "/v1/chat/completions", "", "")), data=payload, headers=headers, method="POST")
try:
with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
completion = json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError(f"HTTP {error.code}. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.") from None
except (urllib.error.URLError, TimeoutError, OSError):
raise RuntimeError("The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.") from None
except (ValueError, UnicodeError):
raise RuntimeError("The server returned an invalid JSON response. Check Usage Logs before retrying.") from None
choices = completion.get("choices") if isinstance(completion, dict) else None
message = choices[0].get("message") if isinstance(choices, list) and choices and isinstance(choices[0], dict) else None
content = message.get("content") if isinstance(message, dict) else None
if not isinstance(content, str) or not content.strip():
raise RuntimeError("No text was returned. The output limit may have been spent on reasoning; inspect Usage Logs before changing the limit.")
return content
if __name__ == "__main__":
try:
print(chat())
except (ValueError, RuntimeError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)Appeler depuis un serveur Node.js
Enregistrez ce code dans chat.mjs et lancez node chat.mjs avec Node.js 22 ou ultérieur. L’exemple utilise fetch intégré et affiche le texte de l’assistant ; aucun paquet npm n’est nécessaire.
import process from 'node:process';
import { pathToFileURL } from 'node:url';
/** One bounded request, with no automatic retries or credential-bearing redirects. */
export async function chat(env = process.env) {
const base = new URL(env.AI_BASE_URL || 'https://easyrouteapi.com');
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname);
if ((base.protocol !== 'https:' && !(base.protocol === 'http:' && loopback)) ||
base.username || base.password || base.search || base.hash ||
!['', '/', '/v1', '/v1/'].includes(base.pathname)) {
throw new Error('AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.');
}
const key = env.AI_API_KEY || '';
if (!key || key.trim() !== key || /[\x00-\x20\x7f]/.test(key)) {
throw new Error('Set AI_API_KEY in your server environment.');
}
const model = env.AI_MODEL || '';
if (!/^[A-Za-z0-9_.:/@+-]{1,200}$/.test(model) || model === 'YOUR_MODEL_ID') {
throw new Error('Set AI_MODEL to an available Chat Completions model or route ID.');
}
const maxTokens = Number(env.AI_MAX_TOKENS || '64');
if (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > 256) {
throw new Error('AI_MAX_TOKENS must be an integer from 1 to 256.');
}
const headers = { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' };
if (env.AI_SESSION_ID) {
if (!/^[A-Za-z0-9._:-]{1,128}$/.test(env.AI_SESSION_ID)) {
throw new Error('AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.');
}
headers['Session-Id'] = env.AI_SESSION_ID;
}
let response;
try {
response = await fetch(new URL('/v1/chat/completions', base), {
method: 'POST', headers, redirect: 'error', signal: AbortSignal.timeout(30_000),
body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Reply with OK only.' }], max_tokens: maxTokens, stream: false }),
});
} catch {
throw new Error('The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.');
}
if (!response.ok) {
// Do not echo an upstream error body; it may contain private request details.
throw new Error(`HTTP ${response.status}. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.`);
}
let completion;
try { completion = await response.json(); } catch {
throw new Error('The server returned an invalid JSON response. Check Usage Logs before retrying.');
}
const content = completion?.choices?.[0]?.message?.content;
if (typeof content !== 'string' || !content.trim()) {
throw new Error('No text was returned. The output limit may have been spent on reasoning; inspect Usage Logs before changing the limit.');
}
return content;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try { console.log(await chat()); } catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}Dépanner votre première requête
401 : vérifiez la clé et son expiration. 403 : vérifiez les droits du modèle, du groupe et du projet. 429 : vérifiez les limites ou la capacité du fournisseur. En cas de solde insuffisant, vérifiez le solde du payeur et le quota de la clé. Pour une erreur 5xx, un délai dépassé ou une déconnexion, consultez les journaux avant de réessayer : le traitement a peut-être déjà commencé.
Un texte vide peut indiquer que le petit budget de sortie a été consommé par le raisonnement. Vérifiez l’utilisation avant d’augmenter AI_MAX_TOKENS. Ne journalisez pas les clés API, les prompts privés ni les erreurs brutes du fournisseur.
Vérifier le résultat
Consultez les journaux après la requête. Les totaux des projets reposent sur les journaux conservés et peuvent évoluer avec les remboursements.