Constructing the Graph and Running Tests

Agents are given a set of tools that they are able to reference when asked a specific question. When there is a user asking to cancel their order, the system should have clear instructions on how the agent actually goes about doing this.

In your Jupyter Lab notebook, put this one time, near the top of the notebook.

%load_ext autoreload
%autoreload 2

…​so that when something changes in tools.py, state.py, or graph.py, the environment knows to automatically reload anything from the imported modules that have changed.

We will have long sections of code in each of these three files:

  • tools.py

  • state.py

  • graph.py

as we work on the development of a single agent model. Rather than make the Python Notebook huge, and messy to work in, we will (instead) put our work into these three files. You can create the files using the File / Text File option from the menu. Make sure to save your files as ".py" instead of ".txt" files. Working in this way will help prepare you for what to do when you may be working someday to build an agent that some company is going to use. We can split long sections of code into the three different files.

Please call the files by the names tools.py and state.py and graph.py, not (for instance) by the name toolsversion1.py.

To see how the agent handles the cancel_order tool, we only have to construct the graph, and run tests.

from graph import construct_graph

# this must be run each time anything in the python files changes
# otherwise the graph will not be updated
# even while using auto-reload
graph = construct_graph()
# import again if needed
from langchain_core.messages import HumanMessage

# test using fake order IDs
tests = [
    (
        "CANCEL ORDER TEST",
        "B73973",
        "Please cancel order #B73973."
    )
]

for name, order_id, prompt in tests:
    result = graph.invoke({
        "messages": [HumanMessage(content=prompt)],
        "order_id": {"order_id": order_id}
    })

    print(f"\n{name}")

    for msg in result["messages"]:
        print(f"\n{type(msg).__name__}")
        print(msg.content)