Skip to main content
In this section, we will see how to build an agent that uses custom tools to edit and save a document.

Objectives

  1. Create custom tools using the @tool decorator.
  2. Maintain global state to update content across loop executions.
  3. Build a loop of execution (agent -> tools -> agent) that terminates only when a specific tool is called.

Agent V: Custom Tool Agent

Goal

Build a document drafting agent (Drafter) that loops using custom tools (update and save) to modify and save content to a local file.

Sample Input

Sequential instructions:
  1. "Write a basic email draft saying I am sick."
  2. "Save the document to email.txt."

Sample Output

  1. "Document updated successfully. Current content is: Hi, I am unable to attend today due to sickness."
  2. "Document has been saved successfully to 'email.txt'."

Plan

  1. Define the AgentState schema using add_messages to append messages to history.
  2. Create custom tools @tool for update (updates content in global variable) and save (saves content to a file).
  3. Write the our_agent node function and should_continue conditional router function.
  4. Compile and run the agent.

Code Implementation

1. Define the State Schema

We define a state schema using add_messages annotation:

2. Create Custom Tools

We define two custom tools that operate on a global document content variable:

3. Define Nodes and Routing Logic

We write the agent node (using a system prompt with current document content) and the router function that terminates execution when the save tool returns successfully:

4. Build and Compile the Graph

We hook up the loops:

Exercise: Todo List Manager Agent 🗃

Goal

Build a Todo List Manager Agent with custom tools to add items, mark them as complete, and save the todo list to a text file.

Sample Input

Sequential inputs:
  1. "Add buy milk to my todo list."
  2. "Save my todo list to todos.txt."

Sample Output

  1. "Todo list updated successfully. Current todos: ['buy milk']"
  2. "Todo list has been saved successfully to 'todos.txt'."

Plan

  1. Create an AgentState schema for messages and a global list todo_list = [] to store items.
  2. Create @tool for add_todo(todo: str) (appends to list) and save_todos(filename: str) (writes list to file).
  3. Initialize StateGraph, register agent and tool nodes, add loops, compile, and run.

Practice & Exercises

To reinforce what you’ve learned in this section, practice with the interactive notebook:

Practice & Exercises

Practice managing global variable states inside custom tools, executing loops until a termination response is triggered, and compiling custom tool workflows.💻 VS Code | 🚀 Colab | 📥 Download