Recursive agents

Recursive agents call themselves to solve sub-problems. When a problem is too complex, the agent decomposes it and delegates each sub-problem to a new instance of itself, with a maximum depth to prevent infinite recursion.

Recursive problem solving

That is why max_depth is essential. Without it, the agent could recurse indefinitely, burning tokens and time. When it hits the depth limit, it solves whatever it has directly instead of decomposing further.

patterns/27_recursive_agents.py
python
class RecursiveAgent:
    def __init__(self, max_depth=3):
        self.max_depth = max_depth
        self.llm = get_llm()

    def solve_problem(self, problem, depth=0):
        if depth >= self.max_depth:
            return self._solve_directly(problem)

        analysis = self._analyze_problem(problem)
        if analysis["should_decompose"]:
            sub_problems = analysis["sub_problems"]
            solutions = [
                self.solve_problem(sub, depth + 1)
                for sub in sub_problems
            ]
            return self._combine_solutions(problem, solutions)
        else:
            return self._solve_directly(problem)

    def _analyze_problem(self, problem):
        prompt = f"""Analyze: {problem}
        Should this be decomposed? (yes/no)
        If yes, list sub-problems."""
        response = self.llm.generate(prompt).content
        return {"should_decompose": "yes" in response.lower(),
                "sub_problems": self._extract_sub_problems(response)}

RecursiveAgent with depth control and sub-problem delegation.

Quiz: Quiz

Loading practice…

Flashcards: Flashcards

Loading practice…

Recursive agents can tackle arbitrarily complex problems by breaking them down. You have now completed all five system architecture patterns.