Sub topic 10
Adding tools and building agents
This chapter assumes you can already call a served chat model from Python and have built the RAG function from the previous chapters. You should also be comfortable with Python decorators and JSON.
From fixed pipelines to agents
The RAG function you built always runs the same steps: retrieve, then generate. An agent lets the model choose the steps. You give the model a set of tools, which are functions it can ask your code to run. The model sees each tool's name, description, and parameters. When it needs one, it replies with a tool call instead of a final answer.
The model never runs code itself. Your application executes the function, sends the result back, and the model continues. This repeats until the model answers in plain text.
Defining a tool
A tool has two parts. The first is a Python function. The second is a JSON schema in the chat completions format. The description fields matter a lot, because the model decides when to call a tool from them.
A minimal agent loop
The example below uses the same OpenAI-compatible client as before. The get_order_status function is a stand-in for a real lookup, such as a SQL query or an API call.
import json
import mlflow
from databricks.sdk import WorkspaceClient
ENDPOINT_NAME = "<your-chat-endpoint-name>"
client = WorkspaceClient().serving_endpoints.get_open_ai_client()
@mlflow.trace(span_type="TOOL")
def get_order_status(order_id: str) -> str:
orders = {"A100": "shipped", "A101": "processing"}
return orders.get(order_id, "not found")
TOOLS = [
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order ID, such as A100"}
},
"required": ["order_id"],
},
},
}
]
REGISTRY = {"get_order_status": get_order_status}
@mlflow.trace(span_type="AGENT")
def run_agent(question: str, max_steps: int = 5) -> str:
messages = [
{"role": "system", "content": "You are a support agent. Use tools when needed."},
{"role": "user", "content": question},
]
for _ in range(max_steps):
response = client.chat.completions.create(
model=ENDPOINT_NAME, messages=messages, tools=TOOLS
)
message = response.choices[0].message
if not message.tool_calls:
return message.content
messages.append(message.model_dump(exclude_none=True))
for call in message.tool_calls:
args = json.loads(call.function.arguments)
result = REGISTRY[call.function.name](**args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": str(result)}
)
return "Stopped: step limit reached."
print(run_agent("Where is order A100?"))Run it and open the trace. You will see an AGENT span containing each model call and each TOOL span, which is the observability you set up in the tracing chapter.
Retrieval as a tool
Your retrieve function from the RAG chapter can become a tool too. The agent then decides whether a question needs documents at all. A greeting needs no retrieval, while a product question does. This costs fewer calls on simple questions but gives you less predictable behavior than a fixed pipeline.
Common errors
- Invalid arguments. The model may produce JSON that is malformed or missing a field. Wrap
json.loadsand the tool call in atryblock, and return the error text as the tool result so the model can retry. - Unknown tool names. Look the name up with
REGISTRY.getand report a clear error instead of raising. - Endless loops. Always cap the number of steps, as
max_stepsdoes above. - Vague descriptions. If the model picks the wrong tool, improve the description before changing anything else.
- Models without tool support. Not every served model accepts the
toolsparameter. Check the model's documentation.
Exercise
Exercise
In the loop above, why must the assistant message containing the tool call be appended to messages before the tool result?
Show answer
The tool result message refers to the call by tool_call_id. The model needs the earlier assistant message, which holds that call, in the history to match the result to its request. Without it, the endpoint rejects the conversation or the model loses track of what it asked.