Templates

5 runnable starters. Pick one, paste, ship.

Every template below is a complete working file. Set NORTHGATE_API_KEY and run — copy-paste time to first successful API call is under 10 minutes, no docs required.

AI Chatbot

Python Node.js

One-line setup for a multi-turn chatbot. Defaults to the cheapest first-hop provider and lets the SDK retry transient failures.

# chatbot.py — multi-turn chatbot via the NorthGate SDK # 1. pip install northgate-sdk # 2. export NORTHGATE_API_KEY=ngk_your_key_here # 3. python chatbot.py import os from northgate import NorthgateClient client = NorthgateClient( api_key=os.environ["NORTHGATE_API_KEY"], base_url="https://northgate-ai.polsia.app/v1", route="balanced", ) history = [ {"role": "system", "content": "You are a helpful assistant. Keep answers under 80 words."}, ] print("Chatbot ready. Type 'quit' to exit.\n") while True: user = input("you> ").strip() if not user or user.lower() == "quit": break history.append({"role": "user", "content": user}) response = client.chat.completions.create( model="gpt-4o-mini", messages=history, temperature=0.7, max_tokens=200, ) reply = response["choices"][0]["message"]["content"] history.append({"role": "assistant", "content": reply}) print(f"bot> {reply}\n")
// chatbot.js — multi-turn chatbot via the NorthGate SDK // 1. npm install northgate-sdk // 2. export NORTHGATE_API_KEY=ngk_your_key_here // 3. node chatbot.js const readline = require("readline"); const { NorthgateClient } = require("northgate-sdk"); const client = new NorthgateClient({ apiKey: process.env.NORTHGATE_API_KEY, baseUrl: "https://northgate-ai.polsia.app/v1", route: "balanced", }); const history = [ { role: "system", content: "You are a helpful assistant. Keep answers under 80 words." }, ]; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log("Chatbot ready. Type 'quit' to exit.\n"); async function ask(prompt) { return new Promise((resolve) => rl.question(prompt, resolve)); } (async () => { while (true) { const user = (await ask("you> ")).trim(); if (!user || user.toLowerCase() === "quit") break; history.push({ role: "user", content: user }); const response = await client.chat.completions.create({ model: "gpt-4o-mini", messages: history, temperature: 0.7, max_tokens: 200, }); const reply = response.choices[0].message.content; history.push({ role: "assistant", content: reply }); console.log("bot> " + reply + "\n"); } rl.close(); })();
Fork on GitHub
# Run it pip install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here python chatbot.py npm install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here node chatbot.js

Text Summarizer

Python Node.js

Single-shot summary with a hard output cap. Uses route=cheapest to walk Together → Groq → Fireworks first.

# summarizer.py — summarize any text with route=cheapest # 1. pip install northgate-sdk # 2. export NORTHGATE_API_KEY=ngk_your_key_here # 3. python summarizer.py < article.txt import os, sys from northgate import NorthgateClient text = sys.stdin.read() if not sys.stdin.isatty() else open(sys.argv[1]).read() if len(text) < 50: print("Provide text via stdin or a file path.", file=sys.stderr) sys.exit(1) client = NorthgateClient( api_key=os.environ["NORTHGATE_API_KEY"], base_url="https://northgate-ai.polsia.app/v1", route="cheapest", ) response = client.chat.completions.create( model="claude-3-5-haiku-20250514", messages=[ {"role": "system", "content": "Summarize the following text in 3 concise bullet points. Preserve key facts and figures."}, {"role": "user", "content": text}, ], max_tokens=300, ) print(response["choices"][0]["message"]["content"])
// summarizer.js — summarize any text with route=cheapest // 1. npm install northgate-sdk // 2. export NORTHGATE_API_KEY=ngk_your_key_here // 3. cat article.txt | node summarizer.js const fs = require("fs"); const { NorthgateClient } = require("northgate-sdk"); (async () => { const text = process.argv[2] ? fs.readFileSync(process.argv[2], "utf8") : fs.readFileSync(0, "utf8"); if (text.length < 50) { console.error("Provide text via stdin or a file path."); process.exit(1); } const client = new NorthgateClient({ apiKey: process.env.NORTHGATE_API_KEY, baseUrl: "https://northgate-ai.polsia.app/v1", route: "cheapest", }); const response = await client.chat.completions.create({ model: "claude-3-5-haiku-20250514", messages: [ { role: "system", content: "Summarize the following text in 3 concise bullet points. Preserve key facts and figures." }, { role: "user", content: text }, ], max_tokens: 300, }); console.log(response.choices[0].message.content); })();
Fork on GitHub
# Run it pip install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here python text-summarizer.py npm install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here node text-summarizer.js

Code Reviewer

Python Node.js

Reviews a diff with a system prompt + user message. Routes to Together AI via Qwen2.5-Coder-32B-Instruct.

# code_reviewer.py — review a git diff with a senior-engineer system prompt # 1. pip install northgate-sdk # 2. export NORTHGATE_API_KEY=ngk_your_key_here # 3. git diff | python code_reviewer.py OR python code_reviewer.py diff.patch import os, sys from northgate import NorthgateClient diff = sys.stdin.read() if not sys.stdin.isatty() else open(sys.argv[1]).read() if "diff --git" not in diff: print("Provide a unified diff via stdin or a .patch file.", file=sys.stderr) sys.exit(1) client = NorthgateClient( api_key=os.environ["NORTHGATE_API_KEY"], base_url="https://northgate-ai.polsia.app/v1", route="best_quality", ) response = client.chat.completions.create( model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=[ { "role": "system", "content": ( "You are a senior engineer doing thorough code review. For each change:\n" "- Point out bugs, edge cases, and security issues.\n" "- Suggest concrete fixes with code snippets.\n" "- Be terse. Numbered list. No preamble." ), }, {"role": "user", "content": f"Review this diff:\n\n{diff}"}, ], max_tokens=800, temperature=0.2, ) print(response["choices"][0]["message"]["content"])
// code_reviewer.js — review a git diff with a senior-engineer system prompt // 1. npm install northgate-sdk // 2. export NORTHGATE_API_KEY=ngk_your_key_here // 3. git diff | node code_reviewer.js OR node code_reviewer.js diff.patch const fs = require("fs"); const { NorthgateClient } = require("northgate-sdk"); (async () => { const diff = process.argv[2] ? fs.readFileSync(process.argv[2], "utf8") : fs.readFileSync(0, "utf8"); if (!diff.includes("diff --git")) { console.error("Provide a unified diff via stdin or a .patch file."); process.exit(1); } const client = new NorthgateClient({ apiKey: process.env.NORTHGATE_API_KEY, baseUrl: "https://northgate-ai.polsia.app/v1", route: "best_quality", }); const response = await client.chat.completions.create({ model: "Qwen/Qwen2.5-Coder-32B-Instruct", messages: [ { role: "system", content: "You are a senior engineer doing thorough code review. For each change:\n" + "- Point out bugs, edge cases, and security issues.\n" + "- Suggest concrete fixes with code snippets.\n" + "- Be terse. Numbered list. No preamble." }, { role: "user", content: "Review this diff:\n\n" + diff }, ], max_tokens: 800, temperature: 0.2, }); console.log(response.choices[0].message.content); })();
Fork on GitHub
# Run it pip install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here python code-reviewer.py npm install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here node code-reviewer.js

Streaming Chat

Python Node.js

Streams a chat completion via Server-Sent Events. The SDK does not yet stream, so this template uses fetch directly.

# streaming_chat.py — stream tokens as they arrive from the gateway # The Python SDK does not yet expose a streaming helper, so we read SSE directly. # 1. pip install requests (stdlib urllib also works — see semantic_search.py) # 2. export NORTHGATE_API_KEY=ngk_your_key_here # 3. python streaming_chat.py import os, json, urllib.request, sys api_key = os.environ["NORTHGATE_API_KEY"] url = "https://northgate-ai.polsia.app/v1/chat/completions?route=balanced" payload = json.dumps({ "model": "meta-llama/Llama-3.3-70B-Instruct", "messages": [{"role": "user", "content": "Write a haiku about Canadian data residency."}], "stream": True, }).encode() req = urllib.request.Request(url, data=payload, headers={ "Content-Type": "application/json", "X-API-Key": api_key, "Accept": "text/event-stream", }, method="POST") with urllib.request.urlopen(req, timeout=60) as resp: print("assistant> ", end="", flush=True) for line in resp: line = line.decode("utf-8").strip() if not line.startswith("data: "): continue chunk = line[6:] if chunk == "[DONE]": print("\n"); break try: delta = json.loads(chunk)["choices"][0]["delta"].get("content") except (KeyError, json.JSONDecodeError): continue if delta: print(delta, end="", flush=True)
// streaming_chat.js — stream tokens as they arrive from the gateway // The Node SDK does not yet expose a streaming helper, so we read SSE directly. // 1. node 18+ // 2. export NORTHGATE_API_KEY=ngk_your_key_here // 3. node streaming_chat.js (async () => { const apiKey = process.env.NORTHGATE_API_KEY; const url = "https://northgate-ai.polsia.app/v1/chat/completions?route=balanced"; const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": apiKey, "Accept": "text/event-stream" }, body: JSON.stringify({ model: "meta-llama/Llama-3.3-70B-Instruct", messages: [{ role: "user", content: "Write a haiku about Canadian data residency." }], stream: true, }), }); process.stdout.write("assistant> "); const reader = r.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let idx; while ((idx = buffer.indexOf("\n")) !== -1) { const line = buffer.slice(0, idx).trim(); buffer = buffer.slice(idx + 1); if (!line.startsWith("data: ")) continue; const chunk = line.slice(6); if (chunk === "[DONE]") { console.log("\n"); return; } try { const delta = JSON.parse(chunk).choices[0].delta.content || ""; process.stdout.write(delta); } catch (_) { /* skip malformed */ } } } })();
Fork on GitHub
# Run it pip install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here python streaming-chat.py npm install northgate-sdk export NORTHGATE_API_KEY=ngk_your_key_here node streaming-chat.js

Need an API key first?

Sign up and get a key in under a minute — then come back and run any of the above.

Get API Key