- Python 3.11 and a virtual environment
- The OpenAI Python SDK installed
- Your working directory:
/root/code
patterns_agent.py. Start from the minimal ReAct structure: import modules, create an OpenAI client, set a system prompt that describes the Thought / Action / Observation markers, add a check_calendar tool and handler, and wire up the loop that runs until the agent produces a final answer.
Minimal starting template (ReAct structure):
The
check_input guard runs locally before any API call, so disallowed queries never reach the model and cost no tokens.patterns_agent.py):
- Structured output
- The system prompt instructs the model to emit actions in a single-line JSON
Actionform and to conclude with a JSON summary block containingsummaryandactions_taken. This makes downstream parsing deterministic and machine-readable.
- The system prompt instructs the model to emit actions in a single-line JSON
- Input guardrails
check_inputruns entirely locally before any API call. If it detects blocked terms (for example:medical,legal, orfinancial advice), the script rejects the user request and never calls the model — saving tokens and preventing the model from handling sensitive requests.
- Human-in-the-loop
- When the agent emits an action whose
nameissend_email, the driver pauses and prompts a human operator to confirm. If the user denies, the tool returns an “Email cancelled by user.” observation and the agent re-plans. Lower-risk tools such ascheck_calendarrun automatically.
- When the agent emits an action whose
Run the full stack
- Ensure the environment variables
OPENAI_API_KEY(andOPENAI_API_BASEif using a non-default base) are set. - Run:
python patterns_agent.py
- Example behavior with
user_message = "Email Sarah my calendar summary for today.":- The guardrail runs and passes.
- The agent may call
check_calendarautomatically. - When the agent requests
send_email, the script prompts:Send this email? (y/n):- Type
yto simulate sending (thesend_emailimplementation is a stub).
- Type
- The agent finishes and prints a final machine-readable JSON summary.
- Replace the stubbed
check_calendarandsend_emailwith real integrations and robust error handling in production. - Consider adding a loop counter or timeout to protect against infinite planning loops.
- Expand
check_inputto use more advanced safety checks (regular expressions, allowlists, or a dedicated moderation service). - Log
actions_takenand Observations to a secure audit trail for observability and compliance.
- OpenAI Python SDK docs
- ReAct and agent design patterns: search for ReAct agent papers and blog posts for design inspiration.