A home assistant¶
This tutorial builds an agent that controls a home on request. It turns lights on and off, plays music, reads the temperature inside and outside, and checks the weather forecast. Unlike the research team, it writes a block of almost every kind for itself: its own tools, a context policy that shows the model the state of the home, and an event bus that logs every action and keeps the quiet hours. A second agent, the DJ, picks songs and serves as one of its tools.
The complete code is docs/examples/home_assistant.py.
What it does¶
A request from a resident goes in. Actions in the home and a reply come out. Four kinds of requests show the parts at work:
- A simple command takes one tool call: "Turn off the living room lights."
- A question needs several readings before the answer: "Should I open the window?"
- A request by mood needs the DJ first, because
play_musictakes a song name: "Play something calm." - A request at night is blocked by a guard rule: "Play Thunderstruck" at 23:10.
Components¶
- Model: any model. Offline, a playbook model; on Claude, Claude Haiku 5.5.
- System prompt: the role of the assistant and its morning routine.
- Tools:
lights_on,lights_off,play_music,stop_music,get_temperature,get_forecast, andpick_song, which is the DJ agent. - Context policy:
HomeStatusPolicy, which adds the time and the state of the home to every prompt. - Events:
HomeEvents, a log of every tool call and result, with one rule: no music from 22:00 to 07:00. - Budget: 8 steps per request.
flowchart TB
User(["Resident"]) -->|"run(request)"| Assistant["home_assistant"]
Assistant --> Harness
subgraph Harness["Harness"]
direction TB
Budget["Budget<br/>8 steps per request"]
Policy["HomeStatusPolicy<br/>time, lights, music"]
Events["HomeEvents<br/>log, quiet hours"]
Budget ~~~ Policy ~~~ Events
end
Assistant --> Tools
subgraph Tools["Tools"]
direction TB
Lights["lights_on, lights_off"]
Music["play_music, stop_music"]
Sensors["get_temperature, get_forecast"]
Song["pick_song"]
DJ["DJ agent<br/>1-step budget, no tools"]
Lights ~~~ Music ~~~ Sensors ~~~ Song --> DJ
end
1. The home¶
The example runs without real devices. Home simulates them: the lights in each room, the song that is playing, the two thermometers and the forecast. It also holds the current time, so a whole day runs in a moment. The tools, the policy and the event bus all read or change the same Home.
@dataclass
class Home:
"""A simulated home: the state that the tools, the policy and the event bus share."""
now: datetime
lights: dict[str, bool] = field(default_factory=lambda: {"kitchen": False, "living room": False, "bedroom": False})
song: str | None = None
temperature: dict[str, int] = field(default_factory=lambda: {"inside": 19, "outside": 4})
forecast: dict[str, str] = field(default_factory=lambda: {
"today": "cloudy, rain from 14:00 to 18:00, high 8°C",
"tomorrow": "sunny, high 11°C",
})
2. The prompts¶
The system prompts of the assistant and of the DJ. The assistant's prompt also defines the morning routine, so a plain "Good morning." is enough to start it.
ASSISTANT_PROMPT = """\
You are a home assistant. You control the lights and the music and you report the temperature and the weather.
The home has three rooms: kitchen, living room and bedroom. The current time and the state of the home are given below.
To play music you need a song name. If the resident describes a mood instead of a song, ask pick_song first.
When the resident says good morning: read both temperatures and today's forecast, turn on the kitchen lights,
play a calm morning song, and answer with a short briefing.
Answer in one to three short sentences. If a tool call is denied, tell the resident why."""
DJ_PROMPT = """\
You pick songs for a home music player. Pick one well-known song that fits the request.
Answer with the song name and the artist only, for example: "Clair de Lune" by Debussy."""
3. The tools¶
Each tool is a definition and a handler that acts on the home. The enum lists in the input schemas tell the model the only valid rooms, places and days. The sensor tools only read, so they are concurrent and the loop runs the readings in parallel.
ROOM = {"type": "string", "enum": ["kitchen", "living room", "bedroom"]}
def object_schema(**properties):
return {"type": "object", "properties": properties, "required": list(properties)}
class HomeTool(Tool):
def __init__(self, home: Home):
self.home = home
class LightsOn(HomeTool):
definition = {"name": "lights_on", "description": "Turn on the lights in one room.", "input_schema": object_schema(room=ROOM)}
async def execute(self, input, ctx=None):
self.home.lights[input["room"]] = True
return text_output(text=f"The {input['room']} lights are on.")
class LightsOff(HomeTool):
definition = {"name": "lights_off", "description": "Turn off the lights in one room.", "input_schema": object_schema(room=ROOM)}
async def execute(self, input, ctx=None):
self.home.lights[input["room"]] = False
return text_output(text=f"The {input['room']} lights are off.")
class PlayMusic(HomeTool):
definition = {
"name": "play_music",
"description": "Play a song by its name.",
"input_schema": object_schema(song={"type": "string"}),
}
async def execute(self, input, ctx=None):
self.home.song = input["song"]
return text_output(text=f"Playing {input['song']}.")
class StopMusic(HomeTool):
definition = {"name": "stop_music", "description": "Stop the music.", "input_schema": object_schema()}
async def execute(self, input, ctx=None):
if self.home.song is None:
return text_output(text="No music is playing.")
self.home.song = None
return text_output(text="The music is stopped.")
class GetTemperature(HomeTool):
readonly = concurrent = True
definition = {
"name": "get_temperature",
"description": "Read the temperature inside or outside the home, in °C.",
"input_schema": object_schema(where={"type": "string", "enum": ["inside", "outside"]}),
}
async def execute(self, input, ctx=None):
return text_output(text=f"{self.home.temperature[input['where']]}°C")
class GetForecast(HomeTool):
readonly = concurrent = True
definition = {
"name": "get_forecast",
"description": "Get the weather forecast for today or tomorrow.",
"input_schema": object_schema(day={"type": "string", "enum": ["today", "tomorrow"]}),
}
async def execute(self, input, ctx=None):
return text_output(text=self.home.forecast[input["day"]])
def home_tools(home: Home) -> StaticToolSet:
return StaticToolSet(tools=[
LightsOn(home), LightsOff(home), PlayMusic(home), StopMusic(home), GetTemperature(home), GetForecast(home),
])
4. The context policy¶
HomeStatusPolicy adds the current time and the state of the home to the system prompt before every model call. The model knows which lights are on without calling a tool, and the status it sees is always current, even between two steps of one run. The status is never stored in the conversation.
class HomeStatusPolicy(ContextPolicy):
"""Adds the time and the state of the home to the system prompt of every call."""
def __init__(self, home: Home):
self.home = home
async def prepare(self, state, prompt, model):
lights = [room for room, on in self.home.lights.items() if on]
status = (
f"Time: {self.home.now:%A %H:%M}\n"
f"Lights on: {', '.join(lights) or 'none'}\n"
f"Music: {self.home.song or 'not playing'}"
)
return replace(prompt, system=f"{prompt.system}\n\n{status}")
5. The event bus¶
HomeEvents does two jobs. It prints a log line for every tool call and result, and it denies play_music during quiet hours. A denied call is not executed: the model receives an error result with the reason, and tells the resident.
class HomeEvents(EventBus):
"""Logs every tool call and result, and keeps the quiet hours from 22:00 to 07:00."""
def __init__(self, home: Home):
self.home = home
def log(self, kind, text):
print(f"{self.home.now:%H:%M} {kind:<9} {text}")
def emit(self, e):
if e["type"] == "tool_call":
args = ", ".join(f"{k}={json.dumps(v, ensure_ascii=False)}" for k, v in e["input"].items())
self.log("tool", f"{e['name']}({args})")
elif e["type"] == "tool_result":
self.log("result", e["content"][0]["text"])
async def intercept(self, e):
hour = self.home.now.hour
if e["type"] == "tool_call" and e["name"] == "play_music" and (hour >= 22 or hour < 7):
return Deny("quiet hours, 22:00 to 07:00")
return "allow"
6. The composition¶
The DJ is an agent with no tools and a budget of one step: it reads the request and answers with a song. Turned into a tool named pick_song, it joins the home tools in a combined tool set. The whole assistant is one function of the home and two models.
def home_assistant(home: Home, model: Model, dj_model: Model) -> Blueprint:
dj = Blueprint(
name="pick_song",
description="picks a song that fits a mood or an occasion, and returns its name and artist.",
model=dj_model,
harness=Harness(loop=StandardLoop(), budget=TreeBudget(limit={"steps": 1})),
initial=InitialState(system=DJ_PROMPT),
)
return Blueprint(
name="home_assistant",
description="controls the lights and the music, and reports the temperature and the weather.",
model=model,
harness=Harness(
loop=StandardLoop(),
budget=TreeBudget(limit={"steps": 8}),
tools=CombinedToolSet(home_tools(home), dj.as_tool()),
policy=HomeStatusPolicy(home),
events=HomeEvents(home),
),
initial=InitialState(system=ASSISTANT_PROMPT),
)
7. A day in the home¶
Each request starts a new agent from the blueprint, so every request has a fresh conversation and a fresh 8-step budget, while the home keeps its state between requests.
DAY = [
("07:15", "Good morning."),
("13:20", "Should I open the window?"),
("19:30", "Turn on the living room lights and play something calm."),
("21:05", "Turn off all the lights and stop the music."),
("23:10", 'Play "Thunderstruck".'),
]
async def run_day(model: Model, dj_model: Model) -> None:
home = Home(now=datetime(2026, 11, 23, 7, 15))
assistant = home_assistant(home=home, model=model, dj_model=dj_model)
for time, request in DAY:
hour, minute = map(int, time.split(":"))
home.now = home.now.replace(hour=hour, minute=minute)
print(f"{time} user {request}")
outcome = await assistant.agent().run(request) # a new agent per request: a fresh conversation
print(f"{time} assistant {message_text(outcome.final)}\n")
Offline, scripted models play the assistant and the DJ. A real model chooses the song to play from the DJ's answer; the script names it in advance.
assistant_script = PlaybookModel(ref="playbook:home", playbooks={
"good morning": [
[call("get_temperature", where="inside"), call("get_temperature", where="outside"), call("get_forecast", day="today")],
[call("lights_on", room="kitchen"), call("pick_song", task="a calm song for the morning")],
call("play_music", song="Here Comes the Sun"),
say(lambda r: f"Good morning. It is {r[0]} inside and {r[1]} outside. Today: {r[2]}. "
f"The kitchen lights are on and {r[4]} is playing."),
],
"window": [
[call("get_temperature", where="inside"), call("get_temperature", where="outside"), call("get_forecast", day="today")],
say(lambda r: f"It is {r[0]} inside and {r[1]} outside. Today: {r[2]}. Better keep it closed."),
],
"calm": [
[call("lights_on", room="living room"), call("pick_song", task="something calm for the evening")],
call("play_music", song="Clair de Lune"),
say(lambda r: f"The living room lights are on and {r[1]} is playing."),
],
"turn off all": [
[call("lights_off", room=room) for room in ("kitchen", "living room", "bedroom")] + [call("stop_music")],
say("All the lights are off and the music is stopped."),
],
"thunderstruck": [
call("play_music", song="Thunderstruck"),
say(lambda r: f"I cannot play music now: {r[-1].split(': ', 1)[-1]}."),
],
})
dj_script = PlaybookModel(ref="playbook:dj", playbooks={
"morning": [say('"Here Comes the Sun" by The Beatles')],
"calm": [say('"Clair de Lune" by Debussy')],
})
if __name__ == "__main__":
asyncio.run(run_day(model=assistant_script, dj_model=dj_script))
Output:
07:15 user Good morning.
07:15 tool get_temperature(where="inside")
07:15 result 19°C
07:15 tool get_temperature(where="outside")
07:15 result 4°C
07:15 tool get_forecast(day="today")
07:15 result cloudy, rain from 14:00 to 18:00, high 8°C
07:15 tool lights_on(room="kitchen")
07:15 result The kitchen lights are on.
07:15 tool pick_song(task="a calm song for the morning")
07:15 result "Here Comes the Sun" by The Beatles
07:15 tool play_music(song="Here Comes the Sun")
07:15 result Playing Here Comes the Sun.
07:15 assistant Good morning. It is 19°C inside and 4°C outside. Today: cloudy, rain from 14:00 to 18:00, high 8°C. The kitchen lights are on and "Here Comes the Sun" by The Beatles is playing.
13:20 user Should I open the window?
13:20 tool get_temperature(where="inside")
13:20 result 19°C
13:20 tool get_temperature(where="outside")
13:20 result 4°C
13:20 tool get_forecast(day="today")
13:20 result cloudy, rain from 14:00 to 18:00, high 8°C
13:20 assistant It is 19°C inside and 4°C outside. Today: cloudy, rain from 14:00 to 18:00, high 8°C. Better keep it closed.
19:30 user Turn on the living room lights and play something calm.
19:30 tool lights_on(room="living room")
19:30 result The living room lights are on.
19:30 tool pick_song(task="something calm for the evening")
19:30 result "Clair de Lune" by Debussy
19:30 tool play_music(song="Clair de Lune")
19:30 result Playing Clair de Lune.
19:30 assistant The living room lights are on and "Clair de Lune" by Debussy is playing.
21:05 user Turn off all the lights and stop the music.
21:05 tool lights_off(room="kitchen")
21:05 result The kitchen lights are off.
21:05 tool lights_off(room="living room")
21:05 result The living room lights are off.
21:05 tool lights_off(room="bedroom")
21:05 result The bedroom lights are off.
21:05 tool stop_music()
21:05 result The music is stopped.
21:05 assistant All the lights are off and the music is stopped.
23:10 user Play "Thunderstruck".
23:10 tool play_music(song="Thunderstruck")
23:10 result the call to play_music was denied: quiet hours, 22:00 to 07:00
23:10 assistant I cannot play music now: quiet hours, 22:00 to 07:00.
The morning routine, step by step¶
The "Good morning." run takes four model calls:
sequenceDiagram
participant H as Harness
participant M as Model
participant T as Tools
participant D as DJ
Note over H,T: Step 1: three readings in parallel
H->>M: prompt (status, task)
M-->>H: 3 tool calls
H->>T: get_temperature, get_temperature, get_forecast
T-->>H: 19°C, 4°C, rain from 14:00
Note over H,D: Step 2: lights and a song name
H->>M: prompt (+ results)
M-->>H: lights_on, pick_song
H->>T: lights_on("kitchen")
H->>D: run("a calm song for the morning")
D-->>H: "Here Comes the Sun"
Note over H,T: Step 3: play the picked song
H->>M: prompt (+ results)
M-->>H: play_music
H->>T: play_music("Here Comes the Sun")
Note over H,M: Step 4: the briefing
H->>M: prompt (+ result)
M-->>H: final answer
- The model asks for the three readings at once. They are concurrent, so the loop runs them in parallel.
- The model turns on the kitchen lights and asks the DJ for a morning song.
- The model plays the song the DJ picked. This step depends on the result of the previous one.
- The model has everything it needs and answers with the briefing.
On Claude¶
The composition takes its models as arguments. One model object can serve both agents:
"""Tutorial: the home assistant on Claude. Requires ANTHROPIC_API_KEY."""
import asyncio
from home_assistant import run_day
from modular_agents.composites.model.anthropic_model import AnthropicModel
haiku = AnthropicModel(ref="claude-haiku-5-5")
asyncio.run(run_day(model=haiku, dj_model=haiku)) # one model object can serve several agents
With a real model the answers vary from run to run, but the guard, the budget and the policy behave exactly as in the offline run.
Building other agents from the same blocks¶
Each change below touches one block and leaves the rest of the assistant as it is:
- Replace the model: move the assistant from a hosted API to a model on a home server, so no request leaves the home.
- Remove tools: without
play_music,stop_musicandpick_song, the assistant controls only the lights and reports the weather. - Add a tool:
set_thermostat(celsius)lets the assistant heat the home, behind aclamp()rule that keeps the temperature between 16°C and 24°C. - Replace the rules: a home with a sleeping baby denies
lights_onfor the bedroom after 20:00. - Compose further: the home assistant becomes a tool of a personal assistant agent, next to a calendar agent and an email agent, as shown on the Composition page.