router.Nyuro.ai

Sample code

Call the gateway in Python, TypeScript, Go, Rust, Swift, or curl — three patterns, no Nyuro SDK required.

The gateway speaks OpenAI-compatible HTTP, so every language that can make an HTTP request can use it. Below: a basic call, auto routing, and an OpenRouter-style fallback array.

Basic call

# pip install openai
from openai import OpenAI

client = OpenAI(base_url="https://api.nyuro.ai/v1", api_key="neu_live_…")

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
)
print(resp.choices[0].message.content)
// npm i openai
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.nyuro.ai/v1",
  apiKey: process.env.NYURO_API_KEY!,
});

const resp = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [{ role: "user", content: "What is the capital of France?" }],
});

console.log(resp.choices[0].message.content);
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "os"
)

func main() {
    body, _ := json.Marshal(map[string]any{
        "model": "gpt-4o-mini",
        "messages": []map[string]string{
            {"role": "user", "content": "What is the capital of France?"},
        },
    })

    req, _ := http.NewRequest("POST",
        "https://api.nyuro.ai/v1/chat/completions", bytes.NewReader(body))
    req.Header.Set("Authorization", "Bearer "+os.Getenv("NYURO_API_KEY"))
    req.Header.Set("Content-Type", "application/json")

    resp, _ := http.DefaultClient.Do(req)
    defer resp.Body.Close()

    var result map[string]any
    json.NewDecoder(resp.Body).Decode(&result)
    choices := result["choices"].([]any)
    msg := choices[0].(map[string]any)["message"].(map[string]any)
    fmt.Println(msg["content"])
}
// reqwest = { version = "0.12", features = ["json"] }, tokio, serde_json
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde_json::{json, Value};
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = env::var("NYURO_API_KEY")?;
    let body = json!({
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "What is the capital of France?"}]
    });

    let resp: Value = reqwest::Client::new()
        .post("https://api.nyuro.ai/v1/chat/completions")
        .header(AUTHORIZATION, format!("Bearer {}", key))
        .header(CONTENT_TYPE, "application/json")
        .json(&body)
        .send().await?
        .json().await?;

    println!("{}", resp["choices"][0]["message"]["content"].as_str().unwrap_or(""));
    Ok(())
}
import Foundation

let apiKey = ProcessInfo.processInfo.environment["NYURO_API_KEY"] ?? ""
let url = URL(string: "https://api.nyuro.ai/v1/chat/completions")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let payload: [String: Any] = [
    "model": "gpt-4o-mini",
    "messages": [["role": "user", "content": "What is the capital of France?"]]
]
request.httpBody = try! JSONSerialization.data(withJSONObject: payload)

let (data, _) = try! await URLSession.shared.data(for: request)
let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any]
let choices = json["choices"] as! [[String: Any]]
let message = choices[0]["message"] as! [String: Any]
print(message["content"] as! String)
curl https://api.nyuro.ai/v1/chat/completions \
  -H "Authorization: Bearer neu_live_…" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
  }'

Auto routing + reading the decision

Pass auto and read the X-Nyuro-* response headers to see which model answered and why.

import httpx, os

resp = httpx.post(
    "https://api.nyuro.ai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['NYURO_API_KEY']}"},
    json={"model": "auto", "messages": [
        {"role": "user", "content": "Refactor this: def f(x): return x*x"}]},
)
print(resp.json()["choices"][0]["message"]["content"])
print("Model:    ", resp.headers.get("X-Nyuro-Model"))
print("Reason:   ", resp.headers.get("X-Nyuro-Route-Reason"))
print("Fallback: ", resp.headers.get("X-Nyuro-Fallback-Used"))
const resp = await fetch("https://api.nyuro.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NYURO_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "auto",
    messages: [{ role: "user", content: "Refactor this: def f(x): return x*x" }],
  }),
});

const data = await resp.json();
console.log(data.choices[0].message.content);
console.log("Model:", resp.headers.get("X-Nyuro-Model"));
# -D - dumps response headers to stdout
curl -D - https://api.nyuro.ai/v1/chat/completions \
  -H "Authorization: Bearer neu_live_…" \
  -H "Content-Type: application/json" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "Refactor this"}]}'

Fallback array

Send models (plural) for an OpenRouter-style fallback chain.

import httpx, os

resp = httpx.post(
    "https://api.nyuro.ai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['NYURO_API_KEY']}"},
    json={
        "models": ["gpt-4o", "gpt-4o-mini"],
        "messages": [{"role": "user", "content": "Summarize attention in 2 lines."}],
    },
)
print(f"Answered by {resp.headers.get('X-Nyuro-Model')} "
      f"(fallback={resp.headers.get('X-Nyuro-Fallback-Used')})")
const resp = await fetch("https://api.nyuro.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NYURO_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    models: ["gpt-4o", "gpt-4o-mini"],
    messages: [{ role: "user", content: "Summarize attention in 2 lines." }],
  }),
});
console.log("Answered by", resp.headers.get("X-Nyuro-Model"));

On this page