AI Agents in Practice: Model Selection, Tool Calling, and Cost Control
This hands-on guide explains what truly distinguishes an AI agent from a chatbot, why tool calling is the make-or-break capability, and how to manage the higher token costs that agents incur. It walks through a four-step process to build a minimal working agent—covering API key setup, tool schemas, the scheduling loop, and hot-swappable models—and closes with essential safeguards and common pitfalls to avoid before letting an agent run autonomously.
1. Aligning Concepts First: An Agent Is Not a Smarter Chatbot
When people first encounter AI agents, many assume they are simply dialogue models with longer answers. The real difference is not the language, but the closed loop: a regular conversation is one question and one answer, while an agent follows a cycle of “given a goal — decompose into steps — call tools — observe results — revise the plan.”
This loop is typically built from four components:
- Model (the brain): understands intent, plans, and decides the next action;
- Toolset (the hands and feet): file read/write, command execution, retrieval, API calls, and so on;
- Context (the memory): stores the task goal, historical steps, and tool return values;
- Runtime (the skeleton): handles scheduling, permission checks, timeouts, and error handling.
In one sentence: the model determines the ceiling, tool calling determines the feel, and the runtime determines whether you can safely let it run on its own. Most complaints about agents being “unusable” trace back not to model intelligence, but to vague tool descriptions, oversized return values, and failures that never get fed back to the model.
2. Why Tool Calling Is the Make-or-Break Factor
Every step an agent takes boils down to the same thing: output a structured tool call request, wait for the execution result, then decide the next move. This imposes three hard requirements:
- The model must natively support tool calling (Function Calling / Tool Use), reliably emitting schema-compliant JSON rather than “pretending” to call tools in natural language.
- Leave ample headroom in the context window. The longer the task, the faster historical steps and tool outputs pile up. Tens of thousands of tokens is generally considered the baseline; long-chain tasks need more space, paired with summarization-based compression.
- Instruction following must be stable. The same tool description yields noticeably different recall rates across models, which directly determines whether it will actually use the tools you provide.
When selecting a model, build a minimal evaluation set: prepare 20–30 real tasks covering single-step calls, multi-step chains, follow-up questions when parameters are missing, and recovery from tool errors, then compare models side by side with the same prompts. This is more reliable than any leaderboard.
3. Cost: Only Cheap Enough to Afford Trial and Error
Agents consume far more tokens than chat applications, because tool return values are repeatedly fed back into the context. The cost structure is typically: input tokens and output tokens are priced separately, with output costing more; some platforms offer discounts for cached input or off-peak hours.
This means three engineering practices are essential:
- Trim tool return values: return only the necessary fields; save large results to disk and pass back a file path;
- Compress the context: summarize early steps, keeping conclusions and discarding intermediate processes;
- Use tiered models: a strong model for planning, lightweight models for mechanical execution.
For specific pricing, context lengths, and discount rules, refer to the official documentation of your chosen model provider. This article deliberately quotes no concrete figures, to avoid outdated and misleading numbers.
4. Four Steps to a Minimal Working Agent
Step 1: Obtain access credentials. On your chosen model platform, complete identity verification and top up your balance, then create an API Key. The key is usually shown in full only once at creation time and cannot be retrieved after you close the page. If it leaks, others can drain your quota—always store it in an environment variable or a secrets management service, never in a code repository.
Step 2: Describe the tools. Tool descriptions are part of prompt engineering. Make the purpose, parameters, boundaries, and failure semantics clear:
{"name": "search_docs","description": "Search the internal knowledge base for documents, returning titles and summaries; returns an empty array when no results are found","parameters": {"type": "object","properties": { "query": { "type": "string" } },"required": ["query"]}}
Step 3: Implement the scheduling loop. The core pattern is “the model proposes an action, the runtime executes it, and the result flows back”:
messages = [{"role": "user", "content": goal}]for _ in range(MAX_STEPS):resp = client.chat(model=MODEL, messages=messages, tools=TOOLS)if not resp.tool_calls:breakfor call in resp.tool_calls:result = dispatch(call.name, call.arguments) # includes permission checks and timeoutmessages.append({"role": "tool", "tool_call_id": call.id,"content": truncate(result)})
Step 4: Enable hot-swapping of models. Make the model name a configuration item so the runtime can switch models with a single slash command—no code changes required:
model: primary-modelfallback: light-modelmax_steps: 12timeout_seconds: 60
5. Four Safeguards to Add Before Letting Go
- Least privilege: write operations, deletions, and outbound network requests are off by default and enabled explicitly per task;
- Sandbox isolation: run command execution inside a container or restricted directory to avoid polluting the host environment;
- Observability: fully log each step’s tool name, parameters, latency, and a return-value summary for later review;
- Recoverable failures: set a maximum step count and timeouts; pass tool exceptions back as observations so the model can self-correct rather than crash outright.
6. Common Pitfalls
Too many tools causing selection difficulty (keep a single agent to ten tools or fewer); untruncated return values blowing up the context; prompts that say “you may call tools” without providing a schema; and the most insidious one—no logging, so when something breaks you can only guess.
Conclusion
An agent’s quality is not mysticism: a model that supports tool calling, ample context headroom, costs low enough to afford trial and error, and a runtime with permission controls and logging as a safety net—get these four things right, and “does exactly what you point it at” becomes the natural outcome. Start with a single tool and a single scenario, get the full loop working, and then add capabilities incrementally.
