Sub topic 3
Letting Models Call Tools and APIs
Assume you know basic Python, JSON, and HTTP APIs. A tool is a program function that performs an action outside the model, such as looking up weather or creating a ticket. The model proposes a call; your code validates and executes it.
Letting Models Call Tools and APIs
Keep execution under your control. Give the model an allow-list of functions, validate arguments, and return the result as text or structured data.
import json
def get_weather(city: str) -> dict:
return {"city": city, "temp_c": 18}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call: dict) -> str:
name = call["name"]
if name not in TOOLS:
raise ValueError("unknown tool")
return json.dumps(TOOLS[name](**call["arguments"]))
print(run_tool_call({
"name": "get_weather",
"arguments": {"city": "Oslo"}
}))Agents: Loops of Reasoning and Action
An agent repeatedly receives context, chooses an action, observes the result, and continues until it can answer. Set a maximum number of steps. Log each call, and stop when a tool fails or the task becomes unsafe.
Testing and Evaluating LLM Features
Create a test set containing normal, ambiguous, adversarial, and edge-case inputs. Compare outputs with expected labels, required fields, citations, or human ratings. Track failure categories, not only one accuracy score.
| Feature | Useful check |
|---|---|
| Tool use | Correct tool, arguments, and refusal behavior |
| Retrieval answers | Supported by the retrieved documents |
| Classification | Exact allowed label and stable results |
Choosing the Fix
Use prompting when the task or output rules are unclear. Use retrieval when the model lacks changing or private knowledge. Use fine-tuning when many examples show a stable behavior that prompts cannot reliably produce. Fix the narrowest cause first.
Managing Cost and Latency
Shorten prompts, retrieve only relevant passages, and choose a smaller model for routine cases. Cache repeated results where freshness permits. Measure token usage, response time, tool time, and failure rate before optimizing.
Safety, Privacy, and Prompt Injection
Do not send secrets or unnecessary personal data. Enforce authorization in your application, not in the prompt. Treat retrieved documents and tool results as untrusted text because they may contain prompt-injection instructions. Require confirmation before irreversible actions.
Scoping Your First Project
Choose one narrow workflow with a measurable outcome, such as routing support tickets. Define success, acceptable errors, fallback behavior, data boundaries, and a small test set before building an agent.
Exercise
A model must answer questions from an internal policy that changes weekly. Should you start with fine-tuning or retrieval?
Show answer
Start with retrieval, because the current policy can be indexed and supplied at request time without retraining the model.