An agent that keeps going
A model can keep asking for tools and never answer. max_iter caps the loop: after that many rounds, CrewAI takes the tools away and asks for a final answer.
Lesson 9's loop ends when the model answers in words. Nothing forces it to. This model asks for the same lookup every time it has tools, however many results it has already seen.
from crewai import Agent, Crew, Task
from shop_llm import ShopLLM
from tools import lookup_order
clerk = Agent(
role="Order clerk",
goal="Find the status of customers' orders",
backstory="You can look up any order in the shop's system.",
llm=ShopLLM(model="shop"),
tools=[lookup_order],
)
task = Task(description="Answer the customer: {question}",
expected_output="The order's status in one sentence.", agent=clerk)
crew = Crew(agents=[clerk], tasks=[task])from shop_llm import ShopLLM
class Stuck(ShopLLM):
calls: int = 0
def call(self, messages, tools=None, **kwargs):
self.calls += 1
print("model call", self.calls, "with tools" if tools else "without tools")
if tools:
return self.decide(messages[:2], ["lookup_order"])
return "A17 shipped on 3 March. Sorry for the wait."Stuck passes only the first two messages to decide, so it never sees a tool result and asks again. It prints each call, and answers in words only when it is given no tools.
clerk.llm = Stuck(model="shop")
clerk.max_iter = 3
result = crew.kickoff(inputs={"question": "Where is my order A17?"})
print(result.raw)Three calls with tools, three lookups. On the fourth, CrewAI sent no tools and a message telling the model to give its best final answer now, and the model did. The Agents page gives the default for max_iter as 20; in 1.15.22 it is 25, which a stuck hosted model reaches slowly and expensively.
- Set
max_iterto 1 and count the model calls. - Print
clerk.llm.callsafter the run. - Remove the
if toolsbranch and see where the run ends.
Little by little, you're building something great.