Skip to content
OpenAI Dots: Rebuild Its Custom Rules as a Python Gate — ContentBuffer guide

OpenAI Dots: Rebuild Its Custom Rules as a Python Gate

K
Kodetra Technologies··13 min read Intermediate

Summary

OpenAI dots have no API yet. Build their allow/ask/hand-off rules in Python.

OpenAI shipped dots on September 29: always-on agents that live in ChatGPT, get their own cloud computer and browser, and connect to more than 4,000 apps. Within a week, Forbes, DataCamp and a long tail of tech blogs were explaining them. The part that deserves your attention is not the always-on bit. It is the permission model. Every action a dot takes falls into one of four buckets, you set the bucket per action, and an auto-review step sits in front of anything that touches an account.

There is one catch for developers. Per DataCamp's rundown, dots have no public API yet; you set them up in the ChatGPT desktop app or on the web. So if you want that behavior inside your own product, with your own tools and your own audit trail, you have to build it. That is what this guide does: a small, testable Custom Rules gate in Python that sits between gpt-6-astra (the model dots run on) and your tools, plus an 'away mode' that mirrors how dots behave when you are not at your desk.

By the end you will have a rules file, a rule engine with first-match-wins semantics, a Responses API tool loop that routes every call through the gate, a queue of actions waiting for approval, and an audit log. About 150 lines of Python, and the core logic runs offline so you can unit test it without spending a token.

What dots actually do (and what we are copying)

Sources for this section: OpenAI's announcement and the DataCamp and OpenTools write-ups linked at the end. Three behaviors matter.

  • Four behaviors per action. Take action without asking; take action if pre-approved (you explicitly asked for it); ask before acting; or hand off to you.
  • Read-only while you are away. In background mode a dot can research through connected apps, but cannot send messages, change app content, or drive a browser or computer.
  • Auto-review plus hard limits. A review step checks sensitive actions against your instructions, your Custom Rules and safety requirements, and some things, like changing a password, always stay with the human.

We will reproduce all three. We will not reproduce the cloud computer or the 4,000 app plugins; those are the product, not the pattern.

Prerequisites

  • Python 3.10 or newer and pip install openai
  • An OPENAI_API_KEY with access to gpt-6-astra (only needed for the live run; the tests below use a fake server)
  • Comfort with JSON and basic function calling

A few facts from OpenAI's model page that shape the code. The model id is gpt-6-astra, it has a 1,050,000 token context window, and it is priced at $10 per million input tokens and $50 per million output tokens. OpenAI's GPT-6 guide says to use the Responses API for tool calling with Astra, and that reasoning effort goes in reasoning.effort with values low, medium (default), high, xhigh and max. none is not supported on Astra, so use low when you want it quick.

Step 1: Model the four behaviors

Start with the vocabulary. An enum of four behaviors, a Rule that matches a tool name by glob plus optional argument conditions, and a RuleSet that evaluates rules top to bottom. First match wins, which is how you express 'email my own domain freely, ask for everyone else': put the specific rule first.

Note the ALWAYS_HAND_OFF set. Dots keep password changes with the user no matter what Custom Rules say. A rules file is user-editable data, so the things that must never be automated belong in code, not in config.

"""Custom Rules for an always-on agent: the same four behaviors dots expose."""
from __future__ import annotations
import fnmatch, json, time
from dataclasses import dataclass, field
from enum import Enum


class Behavior(str, Enum):
    ALLOW = "allow"            # take action without asking
    PRE_APPROVED = "pre"       # only if the user explicitly asked for it this turn
    ASK = "ask"                # pause and wait for a yes/no
    HAND_OFF = "hand_off"      # the agent never does this; the human does


# Things that always go to the human, whatever the rules file says.
ALWAYS_HAND_OFF = {"change_password", "delete_account", "transfer_funds"}


@dataclass
class Rule:
    action: str                       # glob on the tool name, e.g. "send_*"
    behavior: Behavior
    when: dict = field(default_factory=dict)   # optional arg conditions

    def matches(self, name: str, args: dict) -> bool:
        if not fnmatch.fnmatch(name, self.action):
            return False
        for key, want in self.when.items():
            if key.endswith("__endswith"):
                if not str(args.get(key[:-10], "")).endswith(want):
                    return False
            elif args.get(key) != want:
                return False
        return True


@dataclass
class Decision:
    behavior: Behavior
    reason: str


class RuleSet:
    def __init__(self, rules: list[Rule], default: Behavior = Behavior.ASK):
        self.rules, self.default = rules, default

    @classmethod
    def load(cls, path: str) -> "RuleSet":
        raw = json.load(open(path))
        rules = [Rule(r["action"], Behavior(r["behavior"]), r.get("when", {}))
                 for r in raw["rules"]]
        return cls(rules, Behavior(raw.get("default", "ask")))

    def decide(self, name: str, args: dict, user_asked: bool = False) -> Decision:
        if name in ALWAYS_HAND_OFF:
            return Decision(Behavior.HAND_OFF, "hard-coded: always the human's job")
        for rule in self.rules:                # first match wins
            if rule.matches(name, args):
                if rule.behavior is Behavior.PRE_APPROVED:
                    if user_asked:
                        return Decision(Behavior.ALLOW, f"pre-approved by {rule.action}")
                    return Decision(Behavior.ASK, "pre-approved rule, but user did not ask")
                return Decision(rule.behavior, f"matched rule {rule.action!r}")
        return Decision(self.default, "no rule matched, using default")


class AuditLog:
    def __init__(self, path="audit.jsonl"):
        self.path = path

    def write(self, **event):
        event["ts"] = round(time.time(), 3)
        with open(self.path, "a") as f:
            f.write(json.dumps(event) + "\n")

Step 2: Write the rules file

Rules are plain JSON so a non-engineer can edit them. The default is ask, which means any tool you forgot to list stops and waits. Defaulting to allow is how agents end up emailing your whole contact list.

{
  "default": "ask",
  "rules": [
    {"action": "search_inbox",   "behavior": "allow"},
    {"action": "read_calendar",  "behavior": "allow"},
    {"action": "draft_invoice",  "behavior": "allow"},
    {"action": "send_email",     "behavior": "allow", "when": {"to__endswith": "@kodetra.com"}},
    {"action": "send_email",     "behavior": "ask"},
    {"action": "create_event",   "behavior": "pre"}
  ]
}

Check the engine before any model is involved. This is the payoff of keeping the gate deterministic.

from rules import *
rs = RuleSet.load("rules.json")
rs.decide("search_inbox", {})
rs.decide("send_email", {"to": "x@client.com"})
rs.decide("create_event", {}, user_asked=True)
rs.decide("change_password", {}, user_asked=True)

Real output from running those cases:

search_inbox {}                          -> allow    | matched rule 'search_inbox'
send_email {'to': 'bob@kodetra.com'}    -> allow    | matched rule 'send_email'
send_email {'to': 'x@client.com'}       -> ask      | matched rule 'send_email'
create_event {} (user did not ask)      -> ask      | pre-approved rule, but user did not ask
create_event {} (user asked)            -> allow    | pre-approved by create_event
change_password {}                      -> hand_off | hard-coded: always the human's job
unknown_tool {}                         -> ask      | no rule matched, using default

Step 3: Wire the gate into a Responses API loop

The loop follows the documented function-calling flow. Send input and tools to client.responses.create, read the function_call items in response.output, run your code, and send back a function_call_output item carrying the same call_id. Two details are easy to miss. First, append the whole response.output to your input list, not just the function calls, because reasoning models need their reasoning items passed back. Second, a denied or queued action still needs a function_call_output; if you skip it the next request fails because a call has no matching output.

The gate returns a plain-English message for the model when it blocks something (QUEUED, DENIED, HANDED_OFF). That lets the model explain to the user what happened instead of retrying the same call in a loop.

import json, os
from openai import OpenAI
from rules import RuleSet, Behavior, AuditLog

MODEL = "gpt-6-astra"

# name -> (callable, read_only)
def search_inbox(query: str) -> str:
    return json.dumps([{"from": "dan@client.com", "subject": "Invoice for September copy",
                        "body": "Please bill 12 articles at $150 each."}])
def draft_invoice(client: str, lines: list, total: float) -> str:
    open("invoice_draft.txt", "w").write(f"Invoice for {client}\n{lines}\nTotal: ${total:.2f}\n")
    return "saved invoice_draft.txt"
def send_email(to: str, subject: str, body: str) -> str:
    return f"sent to {to}"
def change_password(site: str) -> str:
    raise RuntimeError("never reached")

TOOLS_IMPL = {
    "search_inbox":   (search_inbox,   True),
    "draft_invoice":  (draft_invoice,  False),
    "send_email":     (send_email,     False),
    "change_password": (change_password, False),
}

def spec(name, desc, props, required):
    return {"type": "function", "name": name, "description": desc,
            "parameters": {"type": "object", "properties": props,
                           "required": required, "additionalProperties": False},
            "strict": True}

TOOLS = [
    spec("search_inbox", "Search the user's inbox.", {"query": {"type": "string"}}, ["query"]),
    spec("draft_invoice", "Save an invoice draft to disk.",
         {"client": {"type": "string"},
          "lines": {"type": "array", "items": {"type": "string"}},
          "total": {"type": "number"}}, ["client", "lines", "total"]),
    spec("send_email", "Send an email.",
         {"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}},
         ["to", "subject", "body"]),
    spec("change_password", "Change a password.", {"site": {"type": "string"}}, ["site"]),
]


def gate(name, args, rules, away, user_asked, log, pending):
    """Return (ok, message_for_model)."""
    _, read_only = TOOLS_IMPL[name]
    d = rules.decide(name, args, user_asked)
    if away and not read_only:
        # Dots rule: no side effects while the user is away. Queue instead.
        pending.append({"name": name, "args": args})
        log.write(event="queued", name=name, args=args, why="away mode")
        return False, "QUEUED: user is away, action saved for approval."
    if d.behavior is Behavior.ALLOW:
        log.write(event="allowed", name=name, args=args, why=d.reason)
        return True, ""
    if d.behavior is Behavior.ASK:
        ans = input(f"Approve {name}({args})? [y/N] ").strip().lower()
        log.write(event="asked", name=name, args=args, answer=ans)
        return (ans == "y"), ("" if ans == "y" else "DENIED by user.")
    log.write(event="handed_off", name=name, args=args, why=d.reason)
    return False, "HANDED_OFF: the user must do this themselves."


def run(task, rules, away=False, client=None, max_turns=8, effort="medium", asked=()):
    client = client or OpenAI()
    log, pending = AuditLog(), []
    items = [{"role": "user", "content": task}]
    for _ in range(max_turns):
        resp = client.responses.create(
            model=MODEL, input=items, tools=TOOLS,
            reasoning={"effort": effort})
        items += resp.output                       # keep reasoning items too
        calls = [i for i in resp.output if i.type == "function_call"]
        if not calls:
            return resp.output_text, pending
        for c in calls:
            args = json.loads(c.arguments)
            ok, msg = gate(c.name, args, rules, away, c.name in asked, log, pending)
            result = TOOLS_IMPL[c.name][0](**args) if ok else msg
            items.append({"type": "function_call_output",
                          "call_id": c.call_id, "output": str(result)})
    return "max_turns reached", pending


if __name__ == "__main__":
    import sys
    away = "--away" in sys.argv
    out, pending = run("Check my inbox for an invoice request, draft it, and email it to dan@client.com.",
                       RuleSet.load("rules.json"), away=away)
    print(out); print("pending:", pending)

Step 4: Test the loop with a fake server

You do not need a live key to know the loop is wired correctly. The OpenAI client accepts an http_client, so you can put an httpx.MockTransport behind it and script what the 'model' says. This also lets you assert on the exact request your code sends.

import json, httpx
from openai import OpenAI

script = [
  [{"type":"function_call","id":"fc1","call_id":"c1","name":"search_inbox",
    "arguments":json.dumps({"query":"invoice"}),"status":"completed"}],
  [{"type":"function_call","id":"fc2","call_id":"c2","name":"draft_invoice",
    "arguments":json.dumps({"client":"dan@client.com","lines":["12 articles x $150"],"total":1800}),"status":"completed"},
   {"type":"function_call","id":"fc3","call_id":"c3","name":"send_email",
    "arguments":json.dumps({"to":"dan@client.com","subject":"Invoice","body":"Attached: $1800"}),"status":"completed"}],
  [{"type":"message","id":"m1","role":"assistant","status":"completed",
    "content":[{"type":"output_text","text":"Drafted the $1,800 invoice.","annotations":[]}]}],
]
seen = []
def handler(req):
    seen.append(json.loads(req.content))
    return httpx.Response(200, json={"id":f"resp_{len(seen)}","object":"response","created_at":0,
        "status":"completed","model":"gpt-6-astra","output":script[len(seen)-1],
        "parallel_tool_calls":True,"tool_choice":"auto","tools":[]})

client = OpenAI(api_key="x", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
out, pending = agent.run("task", RuleSet.load("rules.json"), client=client)

In interactive mode with the approver answering 'n', here is what I got. The inbox search and invoice draft pass straight through, the email to an outside domain stops for approval, and the denial goes back to the model:

Approve send_email({'to': 'dan@client.com', 'subject': 'Invoice', 'body': 'Attached: $1800'})? [y/N] n
request keys: ['input', 'model', 'reasoning', 'tools']
reasoning: {'effort': 'medium'} | tool0: search_inbox True
turn 2 input types: ['user', 'function_call', 'function_call_output']

audit.jsonl:
{"event": "allowed", "name": "search_inbox", "why": "matched rule 'search_inbox'", ...}
{"event": "allowed", "name": "draft_invoice", "why": "matched rule 'draft_invoice'", ...}
{"event": "asked",   "name": "send_email", "answer": "n", ...}

The same script with --away shows the dots-style behavior. The read-only search still runs. The invoice draft and the email, which both have side effects, are queued instead of executed:

PENDING: [{'name': 'draft_invoice', 'args': {'client': 'dan@client.com', ...}},
          {'name': 'send_email',    'args': {'to': 'dan@client.com', ...}}]
audit.jsonl:
{"event": "allowed", "name": "search_inbox", ...}
{"event": "queued",  "name": "draft_invoice", "why": "away mode", ...}
{"event": "queued",  "name": "send_email",    "why": "away mode", ...}

Step 5: Worked example, the freelancer's invoice run

This is the use case that went around after launch: a dot noticed a freelancer needed to send an invoice, pulled the details from email and drafted it. Here is the same job under our gate.

  • You schedule the task nightly with away=True. The agent searches the inbox, finds 'bill 12 articles at $150 each', and computes $1,800.
  • draft_invoice and send_email both land in pending. Nothing leaves your machine overnight.
  • In the morning a small review script prints the queue. You approve the draft, and the email goes out after one keypress.

The review script is short because the queue already holds the exact tool name and arguments:

import json
from agent import TOOLS_IMPL

def review(pending):
    for item in pending:
        print(item["name"], json.dumps(item["args"], indent=2))
        if input("run it? [y/N] ").lower() == "y":
            fn, _ = TOOLS_IMPL[item["name"]]
            print("->", fn(**item["args"]))

Persist pending to disk if your scheduler restarts between the run and the review; the in-memory list in this guide is for clarity.

Step 6 (optional): Add an auto-review pass

Dots run an auto-review that checks sensitive actions against your instructions and the rules. You can approximate that with a second, cheap model call that sees only the proposed action and your standing instructions, and returns a verdict. Treat it as an extra tripwire, never as a replacement for the deterministic rules above. A model reviewing a model can be talked around; a glob match cannot.

REVIEW_SCHEMA = {"type": "object",
    "properties": {"verdict": {"type": "string", "enum": ["ok", "block"]},
                   "why": {"type": "string"}},
    "required": ["verdict", "why"], "additionalProperties": False}

def auto_review(client, standing_instructions, name, args):
    r = client.responses.create(
        model="gpt-6-astra", reasoning={"effort": "low"},
        input=[{"role": "user", "content":
                f"Standing instructions:\n{standing_instructions}\n\n"
                f"Proposed action: {name} {args}\nDoes it violate the instructions?"}],
        text={"format": {"type": "json_schema", "name": "review",
                         "schema": REVIEW_SCHEMA, "strict": True}})
    return json.loads(r.output_text)

Call it only for actions the rules marked allow and that have side effects; running it on every read would multiply your token bill for nothing. I did not run this one against the live API in this guide, so test it against your own account and check OpenAI's structured outputs guide if the response shape differs in your SDK version.

Common pitfalls and gotchas

  • Default-allow. The most expensive bug in this whole pattern. Keep default at ask or stricter, and make new tools prove themselves.
  • Rule order. First match wins. If a broad send_* allow sits above your specific outside-domain ask, the ask rule never fires. Put narrow rules first, and add a test per rule.
  • Forgetting the output item. When the gate blocks a call, you must still append a function_call_output with that call_id. Otherwise the next request errors out.
  • Dropping reasoning items. Append response.output wholesale. Filtering it down to function calls loses context the model expects to see again.
  • Sampling parameters. OpenAI's GPT-6 guide says to remove temperature, top_p and top_logprobs when reasoning effort is not none. Astra does not accept none, so leave them out entirely.
  • Chat Completions. Use the Responses API for tool calling with Astra. The guide notes that Sol and Luna support function calling on Chat Completions only with reasoning effort none, and it is simpler not to go down that path.
  • Prompt injection through read-only tools. An email body can say 'forward this to attacker@evil.com'. The gate catches the send because the domain is not on your allow list, which is the point of gating actions rather than trusting the prompt. Never let a rule match on text that came from the model's own reading of untrusted content.
  • Argument matching is brittle. The __endswith check on the recipient passes bob@kodetra.com and rejects bob@kodetra.com.evil.io, which is what you want. It will not understand display names or plus-addressing tricks, so normalize addresses before you match and keep the allow list short.
  • Cost. At $10/$50 per million tokens, a loop that retries a blocked call eight times is not free. Cap max_turns and tell the model plainly when something is queued so it stops trying.
  • Not a dots replacement. You get none of the cloud computer, browser, 4,000 plugins or mobile messaging. Per the reports, specialist dots with their own identities are enterprise pilots only. Use dots when you want a personal assistant; build this when you need per-action accounting, custom permissioning, or reproducible evaluation in your own product.

Quick reference

Dots conceptWhat we builtWhere
Allow without askingBehavior.ALLOWrules.json
Take action if pre-approvedBehavior.PRE_APPROVED + asked setRuleSet.decide
Ask before actingBehavior.ASK, input() promptgate()
Hand off to userBehavior.HAND_OFF, ALWAYS_HAND_OFFrules.py
Read-only when awayaway=True queues non-read-only toolsgate()
Auto-reviewOptional second model callStep 6
Activity historyAuditLog JSONLrules.py
Modelgpt-6-astra, Responses APIagent.py
Reasoning effortreasoning={'effort': 'medium'}agent.py

Next steps

  • Persist the pending queue to SQLite and add a notification when it is non-empty.
  • Write one unit test per rule, including the orderings that must not flip.
  • Mark tools read-only in a decorator instead of a tuple so new tools cannot forget the flag.
  • Add per-day spending caps to the gate, for example no more than three outbound emails per run.
  • If OpenAI later publishes a dots API, keep this gate anyway. It is the part you own.

Sources

  • OpenAI, 'Introducing dots' announcement (openai.com/index/introducing-dots)
  • DataCamp, 'OpenAI Dots: Always-On Agents in ChatGPT, Explained'
  • OpenTools, 'OpenAI Dots are always-on agents. Their most important launch feature is the control boundary'
  • OpenAI API docs: GPT-6 Astra model page, GPT-6 latest-model guide, and Function calling guide (developers.openai.com)

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get