Skip to main content
Caching actions in Stagehand is useful for actions that are expensive to run, or when the underlying DOM structure is not expected to change.

Using observe to preview an action

observe lets you preview an action before taking it. If you are satisfied with the action preview, you can run it in page.act with no further LLM calls.

Simple caching

Let’s use a simple file-based cache for this example. We’ll write a getter and a setter functions that can read and write to a JSON file:

Act with cache

Let’s write a function that will check the cache, get the action, and run it. If the action fails, we’ll attempt to “self-heal”, i.e. retry it with page.act directly.
You can now use actWithCache to run an action with caching:

Advanced caching

The above example is simple, but you may want to cache actions based on the page contents. Also, if you have duplicate prompts, you should use a more unique key. We want to leave caching logic up to you, but give you all the tools you need to implement your own caching strategy. You can directly access the DOM and accessibility tree from Playwright’s page object. Here’s an example of how to access the page content:
You may also want to use the accessibility tree, the DOM, or any other information to create a more unique key. You can do this as you please, with very similar logic to the above example.