
Run Nemotron 3 Nano: Efficient Open Coding Agent
Summary
Build a frugal tool-calling coding agent on NVIDIA's open Nemotron 3 Nano via OpenRouter in Python.
NVIDIA just turned the open-model conversation upside down. The Nemotron 3 family — Nano, Super, and Ultra — ships with open weights, open training data, and open recipes, and it is built for one job above all others: running agents that think for a long time without bankrupting you on tokens. The headline news this week is the full family landing, with the 500B-class Ultra rounding out the lineup. But the model most developers will actually wire into their own projects is the smallest one: Nemotron 3 Nano.
Nano is a 30-billion-parameter hybrid mixture-of-experts model that activates only up to 3 billion parameters per token. It carries a 1-million-token context window, runs roughly 4x faster than the previous Nemotron 2 Nano, and was independently ranked by Artificial Analysis as the most efficient open model in its size class with leading accuracy. It is free to try on OpenRouter, downloadable from Hugging Face, and small enough to self-host. That combination is exactly why it is blowing up across developer communities right now.
This guide is hands-on. By the end you will have a working tool-calling coding agent running on Nemotron 3 Nano — an agent that can read files, run shell commands, and loop until a task is done — written in plain Python with the OpenAI SDK pointed at OpenRouter. We will also cover how the architecture earns its efficiency, the smart Super + Nano routing pattern, the real pitfalls, and how to self-host when you outgrow the free tier.
What Nemotron 3 actually is
Multi-agent systems generate up to 15x the tokens of a normal chat, because every turn re-sends history, tool outputs, and reasoning steps. Over long tasks this context explosion drives both cost and goal drift. Nemotron 3 was designed around that problem rather than around chatbot benchmarks. Three architectural choices matter for you as a builder:
- Hybrid Mamba-Transformer backbone. Mamba-2 state-space layers handle most of the sequence in linear time, which is what makes a 1M-token window practical instead of theoretical. Transformer attention layers are interleaved at key depths to preserve precise recall — finding the one fact buried in a huge context.
- Hybrid (latent) mixture-of-experts. Only a small slice of the model's parameters fire per token. Nano activates up to 3B of its 30B parameters, keeping latency low and throughput high while still carrying broad capability.
- Agentic post-training. The models were tuned with reinforcement learning across many verifiable environments (tool calls, code that must run, multi-step plans), using NVIDIA's open NeMo Gym and NeMo RL libraries. The result behaves reliably across multi-step workflows instead of just sounding good for one turn.
Nano specifically reduces reasoning-token generation by up to 60% versus its predecessor, which is the single biggest lever on agent cost. Fewer thinking tokens per step, multiplied across a long agent loop, is real money.
Prerequisites
- Python 3.9+ and
pip. - An OpenRouter account and API key (free to create). The Nano model has a free tier endpoint, so you can complete this guide at zero cost.
- The OpenAI Python SDK:
pip install openai. OpenRouter is OpenAI-API-compatible, so the official SDK works unchanged once you point it at OpenRouter's base URL. - Optional, for self-hosting later: an NVIDIA GPU plus
vllm, or LM Studio / llama.cpp for local desktop use.
Set your key as an environment variable so it never lands in source control:
export OPENROUTER_API_KEY="sk-or-..."
Step 1 - Your first Nemotron 3 Nano call
OpenRouter exposes Nemotron 3 Nano at the model id nvidia/nemotron-3-nano-30b-a3b:free. Because the API mirrors OpenAI's Chat Completions, the only thing that changes from a normal OpenAI script is the base_url and the model id.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
)
resp = client.chat.completions.create(
model="nvidia/nemotron-3-nano-30b-a3b:free",
messages=[
{"role": "system", "content": "You are a terse senior Python engineer."},
{"role": "user", "content": "In one sentence, when should I prefer a Mamba layer over attention?"},
],
temperature=0.2,
)
print(resp.choices[0].message.content)
Example output:
Prefer a Mamba layer when you need to process very long sequences cheaply,
since its compute scales linearly with length, and reserve attention for
spots that demand precise long-range recall.
That is the whole baseline. The model is a reasoning model, so for harder prompts it will think before answering; the visible content is the final answer. Keep temperature low (0.0-0.3) for coding and tool use where you want determinism.
Step 2 - Give the model tools
An agent is just a model that can call functions and act on the results. We define two tools a coding assistant constantly needs: read a file, and run a shell command. Tools are described with JSON Schema in the exact OpenAI tools format, which OpenRouter forwards to Nemotron.
import subprocess, json, pathlib
def read_file(path: str) -> str:
try:
return pathlib.Path(path).read_text()[:4000]
except Exception as e:
return f"ERROR: {e}"
def run_shell(command: str) -> str:
try:
out = subprocess.run(command, shell=True, capture_output=True,
text=True, timeout=30)
return (out.stdout + out.stderr)[:4000] or "(no output)"
except Exception as e:
return f"ERROR: {e}"
TOOLS = [
{"type": "function", "function": {
"name": "read_file",
"description": "Read a UTF-8 text file and return up to 4000 chars.",
"parameters": {"type": "object",
"properties": {"path": {"type": "string", "description": "Relative or absolute path"}},
"required": ["path"]}}},
{"type": "function", "function": {
"name": "run_shell",
"description": "Run a shell command and return combined stdout+stderr.",
"parameters": {"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"]}}},
]
DISPATCH = {"read_file": read_file, "run_shell": run_shell}
A safety note before you run shell commands from a model: keep this in a sandbox or a throwaway directory. We add a 30-second timeout and truncate output, but an LLM with a shell is powerful. Treat it like giving an intern root — fine in a container, reckless on your laptop's home directory.
Step 3 - The agent loop
The loop is the heart of any agent. Send the conversation; if the model returns tool_calls, run each one, append the results as tool messages, and send again. Repeat until the model answers with plain text or you hit a hard iteration cap. That cap is your seatbelt against runaway loops.
def run_agent(task: str, max_steps: int = 8) -> str:
messages = [
{"role": "system", "content":
"You are a coding agent. Use the tools to inspect the project "
"and run commands. When the task is done, reply with a short summary."},
{"role": "user", "content": task},
]
for step in range(max_steps):
resp = client.chat.completions.create(
model="nvidia/nemotron-3-nano-30b-a3b:free",
messages=messages,
tools=TOOLS,
tool_choice="auto",
temperature=0.1,
)
msg = resp.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls:
return msg.content # final answer
for call in msg.tool_calls:
args = json.loads(call.function.arguments or "{}")
result = DISPATCH[call.function.name](**args)
print(f" -> {call.function.name}({args}) => {result[:80]!r}")
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": str(result),
})
return "Stopped: hit max_steps without finishing."
if __name__ == "__main__":
print(run_agent(
"Count how many Python files are in the current directory, "
"then read the smallest one and tell me what it does."
))
Example run (against a small project folder):
-> run_shell({'command': 'ls *.py | wc -l'}) => '3\n'
-> run_shell({'command': 'wc -l *.py | sort -n | head -1'}) => ' 7 utils.py\n'
-> read_file({'path': 'utils.py'}) => "import re\n\ndef slugify(s):..."
There are 3 Python files. The smallest is utils.py (7 lines): it defines a
single slugify() helper that lowercases a string and replaces non-alphanumeric
runs with hyphens.
Notice the model chose to chain shell commands first to orient itself, then read the file it had identified, then summarized — without you scripting that order. That planning behavior is what the agentic RL post-training buys you, and Nano does it at a fraction of a frontier model's cost.
Step 4 - Streaming and controlling reasoning cost
For interactive UIs, stream tokens as they arrive. Set stream=True and iterate over chunks:
stream = client.chat.completions.create(
model="nvidia/nemotron-3-nano-30b-a3b:free",
messages=[{"role": "user", "content": "Explain MoE routing in 3 bullet points."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
Because Nano is a reasoning model, the biggest cost knob is how much it thinks. Two practical controls: keep prompts tight and specific so it does not over-deliberate, and steer effort in the system prompt (for example, "Think briefly, then answer" for simple steps). On long agent runs, fewer reasoning tokens per step compounds — this is precisely the lever Nano was optimized for with its up-to-60% reduction in reasoning-token generation.
A real-world pattern: route Nano and Super together
NVIDIA recommends a Super + Nano deployment pattern, and it maps cleanly onto a multi-agent system. Use Nano for the many small, targeted steps — file reads, summaries, simple edits, retrieval — and escalate to the larger Nemotron 3 Super (120B total, 12B active, also on OpenRouter as nvidia/nemotron-3-super-120b-a12b:free) only when a step needs deep planning across a whole codebase. Reserve a proprietary frontier model for the rare expert-level task. You get most of the intelligence at a fraction of the spend.
def pick_model(step_kind: str) -> str:
# Cheap, frequent steps stay on Nano; hard planning escalates to Super.
heavy = {"plan", "architect", "debug_whole_repo", "long_context_reason"}
if step_kind in heavy:
return "nvidia/nemotron-3-super-120b-a12b:free"
return "nvidia/nemotron-3-nano-30b-a3b:free"
# In the loop, choose the model per step instead of hardcoding it:
# model = pick_model(classify_step(messages))
This is the same idea Perplexity described for its agent router — direct each workload to the best-fitting open model and only reach for proprietary models when the task truly benefits. With the whole Nemotron 3 family sharing one API shape, switching is a one-line change.
Self-hosting when you outgrow the free tier
The free OpenRouter endpoint is rate-limited and shared. When you need throughput, privacy, or no per-token bill, self-host. Nano's FP8 weights live on Hugging Face at nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8, and it is supported by vLLM, SGLang, llama.cpp, and LM Studio. A minimal vLLM server:
pip install vllm
vllm serve nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8 \
--max-model-len 131072 \
--port 8000
# Then point the same client at your own box -- nothing else changes:
# client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
# model = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8"
That is the real payoff of an open model: your agent code does not care whether the tokens come from OpenRouter, your own GPU, or an enterprise NIM microservice. The OpenAI-compatible surface stays identical, so you prototype on the free tier and move to self-hosted for production with a URL swap.
Common pitfalls and how to avoid them
- Runaway tool loops. Always cap iterations (
max_steps). A model can get stuck re-reading the same file. The cap turns an infinite loop into a graceful stop. - Malformed tool arguments. Wrap
json.loads(call.function.arguments)in a try/except and feed the error back as a tool result so the model can self-correct, rather than crashing your process. - Reasoning-token blowup. Reasoning models can spend far more tokens thinking than answering. Watch
usageon responses, keep steps small, and prefer Nano for frequent steps. Do not point a reasoning model at a trivial loop with a giant context. - Treating 1M context as free. The window is real, but stuffing it on every turn is what causes context explosion in the first place. Pass only the slices of code or history a step needs.
- Running shell without a sandbox. Never give
run_shellto a model on a machine you care about. Use a container, a scratch directory, and an allowlist of commands for anything beyond a demo. - Wrong endpoint for self-host. The
:freesuffix is OpenRouter-only. When you self-host with vLLM, use the full Hugging Face repo id as the model name andbase_url=http://localhost:8000/v1. - Assuming every provider supports tool calling identically. Tool calling works on Nemotron via OpenRouter, but if you switch providers, confirm they forward the
toolsfield and returntool_callsrather than inlining JSON in the text.
Quick reference: the Nemotron 3 family
| Model | Total / active params | Context | Best for | OpenRouter id |
|---|---|---|---|---|
| Nano | 30B / up to 3B | 1M tokens | Frequent, targeted agent steps; cheap reasoning | nvidia/nemotron-3-nano-30b-a3b:free |
| Super | 120B / 12B | 1M tokens | Multi-agent planning, whole-repo coding | nvidia/nemotron-3-super-120b-a12b:free |
| Ultra | ~500B / ~50B | Long-context | Deep research, strategic long-horizon planning | (see build.nvidia.com / providers) |
All three are open-weight under the NVIDIA Nemotron Open Model License, share the hybrid MoE design, and are available on Hugging Face plus inference providers including OpenRouter, build.nvidia.com (as NIM), Together AI, Fireworks, DeepInfra, and Baseten.
Next steps
- Swap in the
pick_modelrouter and watch your token bill on a real multi-step task versus an all-frontier baseline. - Self-host Nano with vLLM and benchmark tokens/sec on your own GPU; compare FP8 throughput to the free endpoint.
- Add more tools: a code-search tool, a patch/apply-edit tool, and a test-runner tool to close the write-verify loop.
- Fine-tune Nano for your domain with LoRA via Unsloth, or explore agentic RL with NVIDIA's open NeMo Gym and NeMo RL environments.
- Read the technical report and the Hugging Face model card for exact eval numbers and license terms before shipping to production.
Sources: NVIDIA Newsroom, "NVIDIA Debuts Nemotron 3 Family of Open Models"; NVIDIA Technical Blog, "Introducing Nemotron 3 Super: An Open Hybrid Mamba-Transformer MoE for Agentic Reasoning"; NVIDIA Nemotron Hugging Face collection; OpenRouter Nemotron 3 model pages. Verify model ids and license terms against the official pages before deployment.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,605 newsletter subscribers.