PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 03 / 100
3%

Build a Personal AI Agent: Memory, Reminders, Chat

Build a personal AI agent you host: chat over a signed webhook, memory that survives restarts, and reminders on a cron trigger, with runnable code.

Intermediate25 minAgent RuntimeAgent Memory
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. 03Build a Personal AI Agent: Memory, Reminders, Chat
  4. 04What Is an Agent Harness? Parts and How to Build One
  5. 05System Prompt Best Practices for AI Agents in Python
  6. 06Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. 07AI Agent YAML: Define and Run an Agent From a Config File
  8. 08Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. 09Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. 10Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. 11Gemini AI Agent with MCP: Use Google Models in Promptise
  12. 12Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. 13OpenRouter AI Agent with MCP: Many Models in Promptise
  14. 14Ollama AI Agent with MCP: Run Local Models in Promptise
  15. 15LLM Semantic Cache and Model Fallback in Python
  16. 16What Is MCP (Model Context Protocol)? A Developer's Guide
  17. 17What Is Tool Calling? LLM Function Calling Explained
  18. 18MCP Tools vs Resources vs Prompts (With Python Examples)
  19. 19How to Connect MCP Servers to Your AI Agent in Python
  20. 20Build a Production MCP Server in Python (Step by Step)
  21. 21MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. 22MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. 23OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. 24MCP Authentication in Python: API Keys, JWT and OAuth
  25. 25Build an Authenticated MCP Server for Your AI Agent (Python)
  26. 26MCP Security Best Practices: A Checklist for MCP Servers
  27. 27Testing MCP Servers in Python: pytest Without a Live Server
  28. 28Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. 29Idempotent Tool Calls: Make AI Agent Retries Safe
  30. 30AI Agent Tool Failures: Stop Unsafe Workarounds
  31. 31MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. 32MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. 33MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. 34LangChain vs MCP: Differences and How They Work Together
  35. 35FastMCP Alternatives for Production MCP Servers (2026)
  36. 36AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. 37AI Agent Human in the Loop: Approve Tool Calls in Python
  38. 38AI Agent Prompt Injection: How to Defend Against It
  39. 39Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. 40Build a Multi-Agent System in Python (and When Not To)
  41. 41Context Engineering for AI Agents: Context Window Management
  42. 42Context Compaction for AI Agents: Trim vs Summarize
  43. 43How to Deploy an AI Agent with Docker (2026 Guide)
  44. 44LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. 45MCP Long-Running Tasks: Background Jobs in Python
  46. 46MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. 47Best AI Agent Frameworks (2026): Python Options Compared
  48. 48Self-Improving AI Agent: Learn From Tool Failures in Python
  49. 49AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. 03Build a Personal AI Agent: Memory, Reminders, Chat
  4. 04What Is an Agent Harness? Parts and How to Build One
  5. 05System Prompt Best Practices for AI Agents in Python
  6. 06Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. 07AI Agent YAML: Define and Run an Agent From a Config File
  8. 08Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. 09Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. 10Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. 11Gemini AI Agent with MCP: Use Google Models in Promptise
  12. 12Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. 13OpenRouter AI Agent with MCP: Many Models in Promptise
  14. 14Ollama AI Agent with MCP: Run Local Models in Promptise
  15. 15LLM Semantic Cache and Model Fallback in Python
  16. 16What Is MCP (Model Context Protocol)? A Developer's Guide
  17. 17What Is Tool Calling? LLM Function Calling Explained
  18. 18MCP Tools vs Resources vs Prompts (With Python Examples)
  19. 19How to Connect MCP Servers to Your AI Agent in Python
  20. 20Build a Production MCP Server in Python (Step by Step)
  21. 21MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. 22MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. 23OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. 24MCP Authentication in Python: API Keys, JWT and OAuth
  25. 25Build an Authenticated MCP Server for Your AI Agent (Python)
  26. 26MCP Security Best Practices: A Checklist for MCP Servers
  27. 27Testing MCP Servers in Python: pytest Without a Live Server
  28. 28Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. 29Idempotent Tool Calls: Make AI Agent Retries Safe
  30. 30AI Agent Tool Failures: Stop Unsafe Workarounds
  31. 31MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. 32MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. 33MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. 34LangChain vs MCP: Differences and How They Work Together
  35. 35FastMCP Alternatives for Production MCP Servers (2026)
  36. 36AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. 37AI Agent Human in the Loop: Approve Tool Calls in Python
  38. 38AI Agent Prompt Injection: How to Defend Against It
  39. 39Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. 40Build a Multi-Agent System in Python (and When Not To)
  41. 41Context Engineering for AI Agents: Context Window Management
  42. 42Context Compaction for AI Agents: Trim vs Summarize
  43. 43How to Deploy an AI Agent with Docker (2026 Guide)
  44. 44LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. 45MCP Long-Running Tasks: Background Jobs in Python
  46. 46MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. 47Best AI Agent Frameworks (2026): Python Options Compared
  48. 48Self-Improving AI Agent: Learn From Tool Failures in Python
  49. 49AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

A personal AI agent is an assistant you run yourself: you chat with it, it remembers what you tell it, and it messages you when something is due. This tutorial builds one end to end in Python with Promptise Foundry 1.7.0 or later. You get a chat endpoint, durable memory, reminders on a cron trigger and delivery back to your chat, plus the parts most tutorials skip: who may talk to the agent, what idle minutes cost, and what survives a restart. Every step has real output.

[01]

How do you build a personal AI agent?

Run the agent as a long-lived process, not as a script you call. Give it two triggers: a signed webhook that receives your chat messages, and a cron trigger that wakes it when a reminder is due. Give it tools for reminders and for sending messages back to your chat, and a small memory it writes itself and that is saved to disk. Then put limits around it, because it runs while you're not watching.

  • Two triggers, one agent. Chat messages and the clock wake the same process, so reminders and conversations share one memory.

  • The agent replies through a tool. A webhook answers 202 Accepted at once; the answer goes back through a reply tool, the way a Telegram or Slack bot sends messages.

  • Filter the cron trigger. A check before the LLM call skips the minutes when nothing is due, so the agent costs nothing while idle.

  • Memory must survive restarts. Keep facts in a journaled state, and conversations in a buffer that is checkpointed after every run.

  • Sign the webhook. Anyone who can reach an unsigned endpoint can instruct your agent.


[02]

How does a personal AI agent work?

A chatbot waits for you. A personal agent also acts on its own schedule. That takes four parts:

  1. A chat channel in both directions: a way for your messages to reach the agent, and a way for the agent to send you messages it starts itself, such as reminders.

  2. Triggers that wake the agent: your messages, a clock, and later perhaps email or a calendar.

  3. Memory in two kinds. Short-term memory is the recent conversation. Long-term memory is the facts that should outlive it: you are vegetarian, you work from home on Fridays.

  4. Tools that change the world: store a reminder, cancel it, send a message. The model decides which to call; the tools do the work and keep the data.

A chat app sends signed messages to the webhook trigger on /chat, and a cron trigger fires every minute; its filter skips the run unless a reminder is due. Both feed the trigger queue of one agent process, whose memory is a journaled context state. The agent calls its own Python tools for reminders and replies, which store reminders and an outbox in SQLite; the chat app reads the outbox.
FigureA personal AI agent: two triggers wake one agent process, which acts through its own tools

In Promptise Foundry this maps onto the Agent Runtime. An AgentProcess owns the agent, its triggers and its state. The webhook and cron triggers put events on one queue, and the process runs the agent once per event. The context state holds the long-term facts, the conversation buffer holds recent messages, and the journal checkpoints both after every run. The tools are plain Python functions the process hands to its agent.

The reminder itself is not an LLM feature. A due time is data in a database, and a cron job finds it. The model's job is the language around it: understanding "in two minutes" or "tomorrow after lunch", and writing a reminder that uses what it knows about you.


[03]

When to build your own personal agent, and when not

Build your own when you want control over where your data lives, which model you use and what the agent may do, or when you want it to reach your own systems: a home server, a private calendar, a company API.

Use a ready-made assistant when phone reminders and a hosted chatbot cover what you need. A self-hosted agent is a service you operate, with a machine that stays on and backups. And don't hand it decisions with serious consequences, such as payments or messages to other people, until you have approval steps in place.


[04]

What you need

  • Python 3.10 or later.

  • Promptise Foundry 1.7.0 or later and httpx for the chat client.

  • An OpenAI API key in OPENAI_API_KEY (or any model Foundry supports).

  • A secret for signing chat messages in CHAT_WEBHOOK_SECRET.

>_Terminal
uv venv && uv pip install "promptise>=1.7.0" httpx
export OPENAI_API_KEY=sk-...
export CHAT_WEBHOOK_SECRET="$(python -c 'import secrets; print(secrets.token_hex(16))')"

[05]

Step 1: Give the agent tools for reminders and replies

The tools are Python functions declared with Promptise's @tool. They store reminders and an outbox in one SQLite file. Reminders are stored in UTC and shown in the owner's time zone, so "9:00" means 9:00 where you are, also after a daylight saving change.

Pythonassistant_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""The personal agent's tools: reminders and chat delivery, as @tool functions.

Everything is stored in one SQLite file, so the data survives restarts and the
chat app and the cron filter can read it too.
"""
import os
import sqlite3
import uuid
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

from promptise import ToolError, tool

DB = os.environ.get("ASSISTANT_DB", str(Path(__file__).parent.resolve() / "assistant.db"))
TZ = ZoneInfo(os.environ.get("OWNER_TIMEZONE", "Europe/Zurich"))


def db() -> sqlite3.Connection:
    conn = sqlite3.connect(DB)
    conn.row_factory = sqlite3.Row
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS reminders (
            id TEXT PRIMARY KEY, text TEXT NOT NULL, due_utc TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending');
        CREATE TABLE IF NOT EXISTS outbox (
            seq INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT UNIQUE, text TEXT NOT NULL,
            kind TEXT NOT NULL, sent_utc TEXT NOT NULL);
        """
    )
    return conn


def local(utc_iso: str) -> str:
    return datetime.fromisoformat(utc_iso).astimezone(TZ).strftime("%a %Y-%m-%d %H:%M")


@tool(read_only=True)
def current_time() -> str:
    """The owner's current local date and time, with the time zone."""
    return datetime.now(TZ).strftime("%A %Y-%m-%d %H:%M %Z")


@tool
def add_reminder(text: str, due_local: str) -> dict:
    """Schedule a reminder for the owner.

    Args:
        text: What to remind the owner about, in their words.
        due_local: When, in the owner's local time, as "YYYY-MM-DD HH:MM".
    """
    try:
        due = datetime.strptime(due_local, "%Y-%m-%d %H:%M").replace(tzinfo=TZ)
    except ValueError:
        raise ToolError(
            f"Can't read the time {due_local!r}.",
            suggestion='Use "YYYY-MM-DD HH:MM" in the owner\'s local time; call current_time first.',
        ) from None
    if due < datetime.now(TZ):
        raise ToolError(f"{due_local} is in the past.", suggestion="Ask the owner for a future time.")
    rid = "r-" + uuid.uuid4().hex[:6]
    with db() as conn:
        conn.execute(
            "INSERT INTO reminders (id, text, due_utc) VALUES (?, ?, ?)",
            (rid, text, due.astimezone(timezone.utc).isoformat()),
        )
    return {"id": rid, "text": text, "due": local(due.isoformat())}


@tool(read_only=True)
def list_reminders() -> list[dict]:
    """The owner's pending reminders, soonest first."""
    with db() as conn:
        rows = conn.execute(
            "SELECT id, text, due_utc FROM reminders WHERE status = 'pending' ORDER BY due_utc"
        ).fetchall()
    return [{"id": r["id"], "text": r["text"], "due": local(r["due_utc"])} for r in rows]


@tool(idempotent=True)
def cancel_reminder(reminder_id: str) -> str:
    """Cancel a pending reminder by its ID (see list_reminders)."""
    with db() as conn:
        changed = conn.execute(
            "UPDATE reminders SET status = 'cancelled' WHERE id = ? AND status = 'pending'",
            (reminder_id,),
        ).rowcount
    if not changed:
        raise ToolError(f"No pending reminder {reminder_id}.", suggestion="Call list_reminders.")
    return f"Cancelled {reminder_id}."


@tool(read_only=True)
def due_reminders() -> list[dict]:
    """Reminders that are due now and not yet delivered."""
    now = datetime.now(timezone.utc).isoformat()
    with db() as conn:
        rows = conn.execute(
            "SELECT id, text, due_utc FROM reminders WHERE status = 'pending' AND due_utc <= ?",
            (now,),
        ).fetchall()
    return [{"id": r["id"], "text": r["text"], "due": local(r["due_utc"])} for r in rows]


def deliver(key: str, text: str, kind: str) -> bool:
    """Put a message in the chat app's outbox once per key. False if it was already sent."""
    with db() as conn:
        cur = conn.execute(
            "INSERT OR IGNORE INTO outbox (key, text, kind, sent_utc) VALUES (?, ?, ?, ?)",
            (key, text, kind, datetime.now(timezone.utc).isoformat()),
        )
        return cur.rowcount == 1


@tool(idempotent=True)
def send_reminder(reminder_id: str, message: str) -> str:
    """Deliver a due reminder to the owner's chat and mark it done.

    Safe to call twice: a reminder is delivered at most once.

    Args:
        reminder_id: The reminder's ID from due_reminders.
        message: The short message the owner sees.
    """
    with db() as conn:
        row = conn.execute("SELECT status FROM reminders WHERE id = ?", (reminder_id,)).fetchone()
        if row is None:
            raise ToolError(f"No reminder {reminder_id}.")
        sent = deliver(f"reminder:{reminder_id}", message, "reminder")
        conn.execute("UPDATE reminders SET status = 'sent' WHERE id = ?", (reminder_id,))
    return "Delivered." if sent else "Already delivered earlier; nothing was sent again."


@tool(idempotent=True)
def reply(event_id: str, message: str) -> str:
    """Send your answer to the owner's chat message.

    Args:
        event_id: The event_id of the chat message you are answering.
        message: Your answer.
    """
    sent = deliver(f"reply:{event_id}", message, "reply")
    return "Sent." if sent else "Already answered; nothing was sent again."


TOOLS = [current_time, add_reminder, list_reminders, cancel_reminder, due_reminders, send_reminder, reply]

Six details matter more than they look:

  • add_reminder takes local time and converts it itself. Models are bad at time zone arithmetic, so the tool does it. current_time gives the model today's date, which it doesn't otherwise know.

  • Errors tell the model how to recover. ToolError(..., suggestion=...) reaches the model as a structured error, so "the time is in the past" leads to a question to you, not to a guess.

  • Sending is idempotent. The outbox has a unique key: reply:<event_id> for an answer and reminder:<id> for a reminder. If a run is retried, the message is not sent twice. Idempotent tool calls explains the pattern.

  • The annotations say what is safe to repeat. read_only=True marks the lookups and idempotent=True the tools whose key makes a repeat harmless. If you give one of them a timeout=, a timeout tells the model it may call it again; any other tool's timeout is reported as an unknown outcome to check first.

  • The outbox stands in for your chat service. In production, deliver() calls the Telegram or Slack API. Everything else stays the same.

  • No MCP server needed. The functions go to the process as extra_tools, next to any MCP servers you connect. Move them into an MCP server when other agents or apps should use them too.


[06]

Step 2: Define the agent process

The process configuration wires everything together: the tools, the two triggers, memory and limits.

Pythonassistant.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""A personal AI agent: chat over a signed webhook, reminders on a cron trigger,
memory in the journaled context state."""
import asyncio
import os
import sqlite3
from datetime import datetime, timezone

from promptise.runtime import (
    AgentProcess,
    AgentRuntime,
    BudgetConfig,
    ContextConfig,
    HealthConfig,
    JournalConfig,
    ProcessConfig,
    TriggerConfig,
)

from assistant_tools import DB, TOOLS

HERE = os.path.dirname(os.path.abspath(__file__))
OWNER_TIMEZONE = "Europe/Zurich"  # also the tools' default (OWNER_TIMEZONE)

INSTRUCTIONS = f"""You are Sam's personal assistant. Sam lives in {OWNER_TIMEZONE}.

Two kinds of events wake you:
- webhook: a chat message from Sam. Answer it with the reply tool, passing
  the event's event_id. Keep answers short, in plain text: no markdown.
- cron: a reminder is due. Call due_reminders, then send_reminder once for
  each one. Use what you know about Sam to make the message useful. Don't
  call reply for cron events: send_reminder is the message.

Memory: the [Context State] block is what you remember about Sam. When Sam
tells you a lasting fact or preference, save it with update_state under
"profile" (a short list of facts; rewrite the whole list). Never store
passwords, card numbers or other secrets.

Times: call current_time before you schedule anything. Give due times to
add_reminder in Sam's local time."""


def reminder_due(event) -> bool:
    """Cron filter: run the agent only when a reminder is due (no LLM call otherwise)."""
    now = datetime.now(timezone.utc).isoformat()
    try:
        with sqlite3.connect(DB) as conn:
            row = conn.execute(
                "SELECT 1 FROM reminders WHERE status = 'pending' AND due_utc <= ? LIMIT 1", (now,)
            ).fetchone()
    except sqlite3.Error:  # no database yet
        return False
    return row is not None


def make_config() -> ProcessConfig:
    return ProcessConfig(
        model="openai:gpt-5-mini",
        instructions=INSTRUCTIONS,
        extra_tools=TOOLS,
        triggers=[
            TriggerConfig(
                type="webhook",
                webhook_path="/chat",
                webhook_port=9090,
                hmac_secret=os.environ["CHAT_WEBHOOK_SECRET"],
                trusted=True,  # signed by Sam's app: the payload is Sam's request
            ),
            TriggerConfig(
                type="cron",
                cron_expression="* * * * *",  # every minute
                cron_timezone=OWNER_TIMEZONE,
                filter_expression=reminder_due,
            ),
        ],
        context=ContextConfig(
            state_tool=True,
            writable_keys=["profile"],
            conversation_history=True,
            conversation_max_messages=30,
        ),
        journal=JournalConfig(level="checkpoint", path=os.path.join(HERE, ".promptise", "journal")),
        budget=BudgetConfig(
            enabled=True, max_tool_calls_per_run=12, max_runs_per_day=300, on_exceeded="pause"
        ),
        health=HealthConfig(enabled=True, on_anomaly="pause"),
        drain_timeout=30,  # on SIGTERM, let a run in flight finish
    )


async def main() -> None:
    runtime = AgentRuntime()
    await runtime.add_process("assistant", make_config())
    print("assistant starting; Ctrl+C or SIGTERM stops it after the current run", flush=True)
    await runtime.run_forever()


if __name__ == "__main__":
    asyncio.run(main())

Here is what each part does.

The webhook trigger listens on 127.0.0.1:9090/chat. With hmac_secret set, a request without a valid X-Webhook-Signature header is refused with 401 before the agent sees it. The agent gets the request body as the event's payload, and the event's ID, which it passes to reply.

trusted=True tells the agent that this payload is your request. By default Foundry wraps every trigger payload in a block marked as untrusted data and tells the model not to follow instructions inside it, which is right for a GitHub webhook or a watched folder and wrong for your own chat. A webhook can only be trusted with an hmac_secret: without one, TriggerConfig raises an error. Whoever holds the chat secret directs the agent as you do.

The cron trigger fires every minute in your time zone. Its filter_expression is a plain Python function that runs before the LLM call: it asks the database whether any reminder is due and returns False if none is. Filtered events never reach the model, so 1,440 ticks a day cost a SQLite query each, not an LLM call. AI agent event filters covers filters in more depth.

Memory has two layers. state_tool=True gives the agent an update_state tool, and writable_keys=["profile"] limits it to one key. The state is injected into every prompt as [Context State], and every write is journaled. conversation_history=True keeps the last 30 messages as short-term memory, across chat and cron runs.

The journal writes a checkpoint after every run to .promptise/journal. On the next start, the process restores the state, the conversation and the budget counters from it.

drain_timeout=30 lets a run in flight finish for up to 30 seconds when the process is stopped by SIGTERM or Ctrl+C under run_forever().

The limits are the budget and health monitor. max_tool_calls_per_run=12 stops a run that calls tools in circles, and max_runs_per_day=300 caps a flood of messages. The health monitor pauses the process if the agent gets stuck calling the same tool with the same arguments. Both pause rather than stop, so you can look and resume.

The instructions say what to do for each kind of event. For cron events they also say not to call reply: without that line, the agent may send a second chat message ("Reminder delivered") after the reminder itself.


[07]

Step 3: Add a chat app

The chat app signs each message with the shared secret, posts it to the webhook and waits for the agent's reply to appear in the outbox. With --listen it prints every message the agent sends, which is how reminders reach you.

Pythonchat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""A minimal chat app for the personal agent: send a signed message, print the answer.

    python chat.py "Remind me to call the dentist tomorrow at 9"
    python chat.py --listen        # print every message the agent sends
"""
import asyncio
import hashlib
import hmac
import json
import os
import sqlite3
import sys
import time
from pathlib import Path

import httpx

DB = str(Path(__file__).parent.resolve() / "assistant.db")
URL = "http://127.0.0.1:9090/chat"


def outbox_after(seq: int) -> list[sqlite3.Row]:
    try:
        with sqlite3.connect(DB) as conn:
            conn.row_factory = sqlite3.Row
            return conn.execute("SELECT * FROM outbox WHERE seq > ? ORDER BY seq", (seq,)).fetchall()
    except sqlite3.Error:
        return []


async def send(text: str, timeout: float = 120) -> str | None:
    body = json.dumps({"from": "sam", "text": text}).encode()
    signature = hmac.new(os.environ["CHAT_WEBHOOK_SECRET"].encode(), body, hashlib.sha256).hexdigest()
    async with httpx.AsyncClient() as http:
        response = await http.post(
            URL,
            content=body,
            headers={"Content-Type": "application/json", "X-Webhook-Signature": f"sha256={signature}"},
        )
    response.raise_for_status()
    event_id = response.json()["event_id"]  # 202 {"status": "accepted", "event_id": ...}
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        for row in outbox_after(0):
            if row["key"] == f"reply:{event_id}":
                return row["text"]
        await asyncio.sleep(0.5)
    return None


async def listen() -> None:
    seen = max((row["seq"] for row in outbox_after(0)), default=0)
    while True:
        for row in outbox_after(seen):
            print(f"[{row['kind']}] {row['text']}", flush=True)
            seen = row["seq"]
        await asyncio.sleep(1)


if __name__ == "__main__":
    if sys.argv[1:] == ["--listen"]:
        asyncio.run(listen())
    else:
        print(asyncio.run(send(" ".join(sys.argv[1:]))))

Start the agent in one terminal and chat from another, with the same CHAT_WEBHOOK_SECRET in both:

>_Terminal
python assistant.py
python chat.py "What do you remember about me?"
python chat.py --listen

[08]

Step 4: Chat, remember and get a reminder

A short demo script starts the process, sends an unsigned request, then two signed messages, and waits for the reminder. Here is one run:

Output
state: running
WebhookTrigger: rejected request from 127.0.0.1 (missing X-Webhook-Signature header)
unsigned request: 401 {'status': 'error', 'message': 'Missing or invalid signature'}

you> Hi! I'm vegetarian, and on Fridays I work from home.
agent> Thanks — noted: you're vegetarian and work from home on Fridays. I'll remember that.

you> Remind me in 2 minutes to take the bread out of the oven.
agent> Okay — I’ll remind you at 09:34.
context state: {'profile': ['vegetarian', 'works from home on Fridays']}

[reminder after 106s] Take the bread out of the oven.
runs: 3 | filtered cron ticks: 1

--- restart: a new process object with the same name ---
recovered: {'lifecycle_state': 'stopped', 'entries_replayed': 1, 'context_keys': ['profile'], 'mission_restored': False, 'budget_restored': True, 'conversation_messages': 6, 'invocation_count': 3, 'interrupted_runs': 0}

you> What should I cook tonight? Keep it short.
agent> Quick ideas (vegetarian):
1) Chickpea curry with rice — ~30 min, hearty.
2) Tomato-basil pasta + salad — ~20 min, simple.
3) Tofu & veg stir-fry with noodles — ~20–25 min, high protein.
Want a recipe for any of these?

Read it top to bottom:

  • The unsigned request got 401, and no run started.

  • The first message was a statement, not a request. The agent stored two facts with update_state, and the context state shows them.

  • The second message became a reminder. The agent called current_time, then add_reminder with a local time, and replied.

  • One cron tick was filtered because nothing was due yet. On the next tick the filter found the reminder, the agent ran, called due_reminders and then send_reminder, and the chat app received the message.

The reminder came after 106 seconds, not exactly 120. add_reminder takes a time to the minute, so "in 2 minutes" became the start of a minute, and the cron trigger checks once a minute; a reminder can arrive up to a minute early or late. If you need more precision, accept seconds in the tool and use a six-field cron expression (its last field is seconds), or use a scheduler built for timers.


[09]

Step 5: Restart the agent and check its memory

The second half of the output is a restart: a new AgentProcess object with the same name, as after a crash or a deploy. process.recovered reports what came back from the journal: the profile key, six conversation messages, the run count and the budget counters. The cooking question shows the memory at work. Nobody repeated that the user is vegetarian, and the answer is vegetarian.

Long-term facts belong in the context state rather than in the conversation: the buffer keeps only the last 30 messages, while the state stays until the agent changes it. That is also why the instructions tell the agent to rewrite the whole profile list: update_state replaces a key's value. AI agent memory in Python compares memory types, and AI agent state between runs covers the context state and its audit trail.

When the facts outgrow a short list, add a long-term memory provider. ContextConfig(memory_provider="chroma", memory_persist_directory=..., memory_auto_store=True) stores past exchanges in a local ChromaDB collection and puts the most relevant ones into each prompt. The context state stays the right place for the few facts that should be in every prompt.


[10]

Connect Telegram instead of the local chat app

The webhook pattern carries over directly, because Telegram's Bot API is a webhook in and an HTTP call out. These are the changes, based on the Telegram Bot API docs and Foundry's webhook docs:

  • Inbound. Register your public HTTPS URL with setWebhook. Telegram supports ports 443, 80, 88 and 8443, so put a reverse proxy in front of the trigger.

  • Authentication. Telegram doesn't sign requests with HMAC. Instead, setWebhook takes a secret_token, which Telegram sends in the X-Telegram-Bot-Api-Secret-Token header. Foundry checks it with signature_scheme="telegram", comparing the header with hmac_secret and answering 401 otherwise. Telegram allows 1 to 256 letters, digits, _ or - in a secret_token, and Foundry rejects a secret outside those rules. The secret proves the request came through your bot, not who wrote the message, so also check that the sender's ID (payload["message"]["from"]["id"]) is yours in a filter_expression.

Python
1
2
3
4
5
6
7
TriggerConfig(
    type="webhook",
    webhook_path="/telegram",
    hmac_secret=os.environ["TELEGRAM_WEBHOOK_SECRET"],  # the secret_token given to setWebhook
    signature_scheme="telegram",
    trusted=True,
)
  • Outbound. In deliver(), call sendMessage with your chat_id and the text.

  • Retries. Telegram repeats a webhook request that doesn't get a 2xx answer, and each update has an update_id that the docs suggest using to ignore repeated updates. Key replies by update_id instead of the Foundry event ID, so a repeated update never gets two answers.

Slack, Discord or WhatsApp work the same way: a signed webhook in, an API call out, a key that makes the send happen once.


[11]

Running a personal agent in production

Decide who may talk to it. The webhook is the agent's front door. Keep the signature check, bind to 127.0.0.1 behind a reverse proxy, and use allowed_sources if your chat service publishes its IP ranges. The agent can do whatever its tools allow, so treat the chat secret like a password.

Keep secrets out of memory. The context state and conversation are written to the journal in plain text. The instructions tell the agent not to store passwords or card numbers, but the safe design is not to send them to it. For API keys the agent's tools need, use the runtime's secret scoping, which redacts secret values from the journal.

Know what the budget does and doesn't count. BudgetConfig counts tool calls, runs and abstract cost units. It does not track LLM token spend. Cap that with max_runs_per_day and max_llm_turns_per_run, and set a spending limit with your model provider as well. AI agent cost control explains how to size these limits.

Stop it gracefully. Under run_forever(), SIGTERM and Ctrl+C stop the process gracefully: no new event starts, and a run in flight gets up to drain_timeout seconds to finish, and its result is journaled before the process stops. A run still going when the drain ends is cancelled, logged and journaled as run_interrupted. The next start of a process with the same name lists it in dead_letters (and in recovered["interrupted_runs"]), and redeliver_dead_letters() runs it again. Idempotent reply and send_reminder tools make that re-run safe, and a reminder that was due during a restart is still pending in the database, so the next cron tick sends it. A plain stop() in your own code still cancels at once; pass stop(drain_timeout=...) to wait.

Run it under a supervisor. restart_policy restarts a process that failed, but it can't restart a Python process that was killed, so use systemd, Docker or your platform's restart policy. Deploy an AI agent with Docker shows the container setup.

Get told when something breaks. Budget and health limits pause the process. Add an EscalationTarget with a webhook URL, or an event notifier with a Slack sink, so a paused assistant sends you a message instead of going quiet. See AI agent notifications.

Back up two things: the SQLite database (reminders and outbox) and the journal directory (memory and conversation). Use absolute paths, as assistant.py does.


[12]

Common problems and fixes

Symptom

Cause

Fix

The agent won't act on chat messages, or treats them as untrusted data

The webhook trigger isn't marked trusted

trusted=True together with hmac_secret

Every chat message gets 401

Different CHAT_WEBHOOK_SECRET in the agent and the chat app

Export the same secret in both shells

The agent answers but the chat app times out

The agent didn't call reply, or used the wrong event_id

Say in the instructions that every chat message is answered with reply and the event's event_id

Reminders are an hour off

The model converted the time zone itself

Let the tool convert local time; give the model current_time

The agent forgot a fact after a restart

No journal, or a relative journal path started a fresh one

Set JournalConfig with an absolute path

A fact disappeared from profile

update_state replaces the whole value

Tell the agent to rewrite the full list; keep it short

An LLM call every minute

The cron trigger has no filter

Add a filter_expression that checks for due reminders

The agent stopped answering

The budget or health monitor paused it

Check process.status()["suspend_reason"], fix the cause, call resume()

A message was answered twice

The chat service retried and the send wasn't keyed

Key sends by the service's message or update ID


[13]

Limitations

  • One user. This agent has one owner and one memory. For a family or a team, give each person their own process, with its own name, journal, database and chat secret.

  • Minute precision. A reminder is sent on the first cron tick after its due time.

  • No Telegram or Slack client in Foundry. Foundry checks Telegram's webhook secret, but sending messages (sendMessage, Slack's API) is your deliver() code.

  • Webhook replies are asynchronous. The trigger answers 202 at once; the reply arrives through the outbox. If you need a synchronous HTTP answer, call an agent built with build_agent from your own web handler instead.

  • The model can still get dates wrong. "Next Friday" can be read two ways; have the agent repeat the due time in its reply.


[14]

FAQ

What is a personal AI agent?

A personal AI agent is an assistant that works for one person and acts on its own schedule as well as on request. Unlike a chatbot, it keeps memory across conversations, holds tools that change things, such as reminders or messages, and wakes up from triggers like a clock or incoming email.

How do I build a personal AI assistant with reminders?

Store each reminder with a due time in UTC in a database, and run a cron job every minute that finds due reminders and sends them to your chat. Let the agent create reminders through a tool that converts your local time, and send them through a tool that delivers each reminder once. A filter before the LLM call keeps idle minutes free.

How does a personal AI agent remember things?

It needs memory that survives restarts. Short-term memory is the recent conversation; long-term memory is facts such as preferences, stored where every run can read them. In Promptise, the agent writes facts with update_state into the context state, and the journal checkpoints the state and the conversation after every run.

Can I connect my personal AI agent to Telegram?

Yes. Point Telegram's setWebhook at your agent's webhook trigger with a secret_token, and in Promptise set signature_scheme="telegram" with that secret as hmac_secret, so requests without it get 401. Send replies with sendMessage from your reply tool. Telegram retries failed webhook requests, so key replies by update_id.

How much does a self-hosted personal AI agent cost to run?

The model cost depends on how often the agent runs. With a filtered cron trigger, idle minutes make no LLM calls, so you pay mainly for the messages you send and the reminders it delivers. Cap runs per day and set a spending limit with your model provider.

Is a self-hosted AI assistant private?

It keeps memory, reminders and logs on a machine you control. The messages still go to the model provider you choose, unless you run a local model. Keep secrets out of chat, since memory and conversations are stored in plain text in the journal.


[15]

Next steps

  • AI agent cron jobs covers schedules, time zones and missed ticks.

  • AI agent webhook trigger goes deeper on signatures and source allowlists.

  • Durable AI agents explains crash recovery and the journal.

  • The Foundry docs on triggers and the journal list every option used here.

← PreviousHow to Build an AI Agent in Python (2026 Guide)Next lesson →What Is an Agent Harness? Parts and How to Build One