惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Security @ Cisco Blogs
Y
Y Combinator Blog
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
C
Check Point Blog
爱范儿
爱范儿
A
About on SuperTechFans
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
WordPress大学
WordPress大学
Help Net Security
Help Net Security
博客园 - Franky
Forbes - Security
Forbes - Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
量子位
Vercel News
Vercel News
Google DeepMind News
Google DeepMind News
W
WeLiveSecurity
V
V2EX
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
Securelist
L
LangChain Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Schneier on Security
Schneier on Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Register - Security
The Register - Security
L
Lohrmann on Cybersecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Cyber Attacks, Cyber Crime and Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
Apple Machine Learning Research
Apple Machine Learning Research
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
Spread Privacy
Spread Privacy
F
Full Disclosure
美团技术团队
I
Intezer

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From Chatbot to Agent — Tool Calling with NVIDIA NIM
Torkian · 2026-05-26 · via DEV Community

In Parts 1 through 4 we built a useful tool: a USC campus assistant that knows when to retrieve, when to refuse, and which endpoint to call. It is still a chatbot. The model writes a string; we print it. Everything interesting happened inside one model call.

This post turns it into an agent. By agent I mean something specific and small — the model can choose a tool from a list, your Python code runs that tool, and the result goes back into the conversation. That's it. No LangGraph, no AutoGen, no LangChain. Two functions, one loop, and a NIM call with tools=....

You'll watch the model decide for itself whether to consult the clock, search the USC knowledge base, or just answer directly. Once you see the loop, the framework abstractions on top of it are easier to read because you already know what they hide.

I'm B Torkian, NVIDIA Developer Champion at USC. Final part of the series.


What you're adding

User question
  → NIM call (with tools schema)
  → model returns either a final answer OR a tool_calls list
  → if tool_calls: run each one, append the result, NIM call again
  → repeat until model returns an answer (or hit the loop limit)

Enter fullscreen mode Exit fullscreen mode

The chat call shape from Part 1 carries forward. The retriever from Part 2 becomes a tool. The guardrail pattern from Part 3 still applies — we keep the assistant scoped, and the agent only gets to use tools we expose.


What "agent" actually means here

Most marketing pages use agent to mean "anything with a memory or a loop." For this post the definition is narrower and worth pinning down up front:

  1. You describe a small number of Python functions to the model via a JSON schema (the tools parameter).
  2. The model returns either a normal message OR a tool_calls field with the name and arguments of the function it wants to run.
  3. Your code runs that function and appends the result to the message list as a tool role.
  4. You make another NIM call. The model sees the tool result and either calls another tool or writes the final answer.

That's the entire pattern. Real production agents add planning, retries, sub-agents, and observability. The center is still these four steps.


Step 1 — Carry forward the setup, and bump the model

You need everything from Parts 1, 2, and 3 — the client, MODEL, ask, knowledge_base, embed_texts, and retrieve_context. A compact prerequisite cell is in the Colab notebook for this workshop. The standalone script part5_agent.py in the repo defines everything from scratch so you can run it without any prior cell.

One change worth flagging up front. Parts 1-4 used meta/llama-3.1-8b-instruct — fast, cheap, fine for chat and RAG. For Part 5 we switch to meta/llama-3.3-70b-instruct. Reason — tool calling is noticeably more reliable on the larger model. I tested both; the 8B model called the right tool inconsistently across reruns (some runs it would refuse instead), while the 70B model behaved the same way every time. Reliability matters more than speed once a model has to choose between tools instead of just answering. Both run on the same hosted endpoint; only the MODEL string changes.

MODEL = "meta/llama-3.3-70b-instruct"   # was 'meta/llama-3.1-8b-instruct' in Parts 1-4

Enter fullscreen mode Exit fullscreen mode


Step 2 — Define two tiny tools

import json
from datetime import datetime
from zoneinfo import ZoneInfo

def get_current_time(timezone: str = "America/Los_Angeles") -> str:
    try:
        zone = ZoneInfo(timezone)
    except Exception:
        zone = ZoneInfo("UTC")
    return datetime.now(zone).strftime("%A, %B %d, %Y at %I:%M %p %Z")

def search_campus_info(query: str) -> str:
    # Reuse the retriever from Part 2 — the agent gets semantic search for free.
    return retrieve_context(query, k=3)

Enter fullscreen mode Exit fullscreen mode

Two functions. Plain Python. They don't know anything about the model — the model has no idea they exist yet. That's fixed in the next step.


Step 3 — Describe the tools to the model in JSON schema

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "Get the current time in an IANA time zone.",
            "parameters": {
                "type": "object",
                "properties": {
                    "timezone": {
                        "type": "string",
                        "description": "IANA time zone, e.g. America/Los_Angeles or UTC.",
                    },
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_campus_info",
            "description": "Search the USC campus assistant knowledge base for information about USC clubs (including AI Club), labs (GPU lab, robotics lab), workshops, faculty office hours, peer tutoring, and the NVIDIA Developer Program at USC. Always call this for any USC-related question — do not answer from your own knowledge.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The USC campus question or search phrase.",
                    },
                },
                "required": ["query"],
            },
        },
    },
]

available_tools = {
    "get_current_time": get_current_time,
    "search_campus_info": search_campus_info,
}

Enter fullscreen mode Exit fullscreen mode

The schema is what the model sees. The names, descriptions, and parameter docs are how it decides which to call. Take these descriptions seriously — vague tool descriptions produce a confused agent.

The available_tools dict is the dispatch table on the Python side. Always pair the two — the schema describes intent, the dict provides execution.


Step 4 — The agent loop

def ask_agent(question: str) -> str:
    messages = [
        {
            "role": "system",
            "content": (
                "You are a USC campus assistant with two tools: "
                "get_current_time and search_campus_info. "
                "When the user asks something a tool can answer, call the tool, "
                "then write the final answer based on the tool's result. "
                "Do not call the same tool twice for the same question. "
                "If after using the tools you still cannot find the answer, "
                "reply exactly: I don't have that information — check with the USC AI Club."
            ),
        },
        {"role": "user", "content": question},
    ]

    for _ in range(3):                                # hard cap on tool calls
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools,
            tool_choice="auto",
            temperature=0.2,
            max_tokens=400,
        )
        message = response.choices[0].message
        messages.append(message.model_dump(exclude_none=True))

        if not message.tool_calls:                    # model finished — return its text
            return message.content

        for tool_call in message.tool_calls:
            name = tool_call.function.name
            arguments = json.loads(tool_call.function.arguments or "{}")

            if name not in available_tools:
                result = f"Tool {name} is not available."
            else:
                result = available_tools[name](**arguments)

            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "name": name,
                "content": str(result),
            })

    return "I hit the tool loop limit."

Enter fullscreen mode Exit fullscreen mode

Four things worth slowing down for:

  • tools=... and tool_choice="auto" — this is how the model knows it has tools available and that it can pick. "auto" means use a tool if useful, otherwise answer directly.
  • messages.append(message.model_dump(...)) — the model's tool-call request itself becomes part of the conversation. Skip this and the next NIM call has no idea why you're showing it a tool result.
  • The tool role — when you send the function's return value back, it has to be a message with role="tool" plus the matching tool_call_id. Get that ID wrong and the model treats the result as orphan text.
  • The loop cap (3 iterations) — agents that don't have a hard stop will sometimes spiral. Keep the cap visible and small for workshops; widen it as you understand the model's behavior.

Step 5 — Run it

for question in [
    "What time is it in Los Angeles?",            # → uses get_current_time
    "When does the USC AI Club meet?",            # → uses search_campus_info
    "Can I get the wifi password?",               # → searches, finds nothing, refuses
]:
    print(f"Q: {question}")
    print(f"A: {ask_agent(question)}\n")

Enter fullscreen mode Exit fullscreen mode

What you should see:

  • The clock question makes the model call get_current_time and answer from the returned string.
  • The AI Club question makes it call search_campus_info, read the retrieved chunks, and answer from them.
  • The wifi question makes it call search_campus_info, see that none of the chunks mention passwords, and fall back to the refusal line — same guardrail logic from Part 3, just delivered through a different control flow.

Some runs the model will call both tools (e.g. "what time is it and when does the club meet?"). The loop handles that without changes — each iteration appends all the tool results and re-asks.


Step 6 — What you actually built

The full assistant is now agent-shaped:

  • Workshop 1 gave it a brain (the chat call).
  • Workshop 2 gave it memory (retrieval).
  • Workshop 3 gave it judgment (guardrails).
  • Workshop 4 gave it portability (hosted or local).
  • Workshop 5 gave it hands (tool calling).

You still own the behavior — the model only gets to call functions you expose, with arguments it has to declare, inside a loop you control. Real systems extend each piece, but the spine is what you just built. The most common follow-ups are:

  • More tools (calendar, ticketing, web search, code execution sandboxes).
  • Structured outputs so the final answer is JSON, not prose.
  • A planner that decomposes a question into sub-questions before any tool fires.
  • Observability — log every tool call, every argument, every return value. Production agents live or die on this.

If you take one thing from the whole series, take this: an LLM is a normal Python function with a weird interior. Everything you've built — retrieval, guardrails, deployment, tool calling — is normal software wrapped around that function. Frameworks save typing; they don't change the model.


Get the code

Repo: github.com/torkian/nvidia-nim-workshop
One-click Colab: Open part5_agent.ipynb
Local Python: part5_agent.py in the repo (python3 part5_agent.py after pip install -r requirements.txt).

MIT licensed. I run this at USC — fork it, swap the knowledge base and the tools for your school, your club, your project, and run it wherever you are.


The full series

  • Part 1: Build Your First AI App with NVIDIA NIM in 30 Minutes
  • Part 2: From Manual RAG to Real Retrieval — Embedding-Based RAG with NVIDIA NIM
  • Part 3: Add Guardrails So Your AI App Doesn't Lie
  • Part 4: Run NVIDIA NIM on Your Own GPU
  • Part 5 (this post): From Chatbot to Agent — Tool Calling with NVIDIA NIM

A consolidated long-form version of the whole series is on Medium for anyone who'd rather read it in one sitting.