Welcome to the final chapter of the SleepTool tutorial!
In the previous chapter, Periodic Heartbeat Handling, we taught our AI to "check the pool" periodically to see if anything changed. We called this a Heartbeat.
But a new question arises: How often should the heart beat?
If it beats every second, we waste money. If it beats once an hour, the AI might "forget" what it was doing. This chapter covers Cache Lifecycle Management, which is the art of finding the economic "sweet spot."
To understand this problem, imagine you are standing in a hallway with a motion-sensor light. The light stays on for 5 minutes after it sees movement.
We want our AI to use the Smart Approach.
When building AI tools, we balance two costs:
The Goal: Wake up just frequently enough to keep the cache alive (reset the 5-minute timer), but infrequently enough to save money on API calls.
Unlike previous chapters where we wrote Typescript code for logic, this feature is implemented purely through Prompt Engineering. We rely on the AI's intelligence to manage its own schedule.
We simply explain the rules of the "game" to the AI in prompt.ts.
We add a specific paragraph to our SLEEP_TOOL_PROMPT that explains the 5-minute rule.
// In prompt.ts
export const SLEEP_TOOL_PROMPT = `...
Each wake-up costs an API call, but the prompt cache expires
after 5 minutes of inactivity โ balance accordingly.`
Explanation:
When the user gives a command, the AI now calculates the optimal sleep time based on these instructions.
Scenario: The user says, "Wait for 20 minutes."
Without our instructions, the AI might call Sleep(1200) (20 minutes).
With our instructions, the flow looks like this:
Let's look at the final assembly of our prompt.ts file. This single string now controls Identity, Behavior, Heartbeats, and Cache Management.
// prompt.ts
import { TICK_TAG } from '../../constants/xml.js'
// ... Metadata ...
export const SLEEP_TOOL_PROMPT = `Wait for a specified duration.
The user can interrupt the sleep at any time.
Use this when... (usage rules)
You may receive <${TICK_TAG}> prompts... (Heartbeat rules)
Each wake-up costs an API call, but the prompt cache expires
after 5 minutes of inactivity โ balance accordingly.` // (Cache rules)
Example Input/Output:
Call Tool: Sleep(290)
Congratulations! You have built the complete SleepTool.
Let's review what you have accomplished across these five chapters:
SLEEP_TOOL_NAME) so the system can find your tool.SLEEP_TOOL_PROMPT) so the AI knows what the tool is for.setTimeout) using Promises to wait without freezing the computer.TICK_TAG) so the AI stays responsive.You now have a fully functional, efficient, and cost-effective tool that allows an AI Agent to exist over long periods of time. This is the foundation for building autonomous agents that can monitor servers, wait for emails, or manage long-running workflows.
End of Tutorial.
Generated by Code IQ