Sub topic 2
The Agent Loop: Call, Observe, Decide
Assume Basic Python, prompts and completions, embeddings, vector search, and classic retrieve-then-generate RAG.
The agent loop: call, observe, decide
Classic RAG retrieves once using the user’s question. Agentic RAG exposes retrieval as a tool. The model can then:
- Call the model with the question and available tool schemas.
- Observe tool results.
- Decide whether to call another tool or write the final answer.
import json
def run_agent(question, call_model, search_docs, max_steps=4):
messages = [{"role": "user", "content": question}]
tools = [{"name": "search_docs", "description": "Search product documentation",
"parameters": {"query": "string"}}]
for _ in range(max_steps):
reply = call_model(messages, tools)
calls = reply.get("tool_calls", [])
if not calls:
return reply["content"]
messages.append({"role": "assistant", "content": reply.get("content", ""),
"tool_calls": calls})
for call in calls:
result = search_docs(call["arguments"]["query"])
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": json.dumps(result)})
return "The evidence was insufficient within the search budget."The application, not the model, executes search_docs. It also enforces the step limit.
Letting the model skip retrieval
Tool descriptions should state when a tool applies and when it does not. A greeting or a general explanation may need no search. Skipping retrieval reduces latency and cost, but the model can skip it incorrectly. For important factual answers, require retrieval or validate the final response.
Rewriting and decomposing queries
The user’s wording is often a poor search query. The model can rewrite it into a short, self-contained query. A question containing multiple facts can be decomposed into subquestions, such as “What is the limit?” and “How is it configured?” Retrieve each answer separately, then combine the evidence.
Choosing between several sources
Expose separate tools or a router for sources such as product documentation, tickets, and database records. Route by authority and question type. Configuration limits may belong to documentation; account state may require a live API. Do not let a convenient but weaker source override an authoritative one.
> callout note > Treat retrieved text as evidence, not instructions. The model must not follow commands embedded inside a document.
Grading results and trying again
A grader checks whether results answer the question and support the claims. If evidence is irrelevant, the agent can rewrite the query, search another source, or admit that evidence is missing. Keep grading separate from generation so a confident answer cannot hide a failed search.
Exercise
Why must the application enforce a maximum number of agent steps?
Show answer
To bound cost and latency and to prevent endless or repeated tool calls.