In this tutorial, we construct a sophisticated agentic AI system using the OpenAI API, with a hidden terminal prompt for the API key. The agent is designed as a pipeline of specialized roles: planner, tool-using executor, and critic, separating strategy, action, and quality control. It integrates structured tools such as a calculator, mini knowledge-base search, JSON extraction, and file writing, enabling reliable computation, information retrieval, structured outputs, and artifact saving.
We begin by installing the OpenAI SDK and importing only essential modules to keep the notebook lightweight and reproducible in Colab. The API key is securely obtained via getpass() to remain hidden. We create an OpenAI client and set the model string consistently for reuse.
A small internal knowledge base simulates playbooks or team documentation that the agent can consult via tool calls. Each tool returns structured dictionaries to ensure machine-readable and robust output. The tools include:
calc: Safely evaluates numeric expressions.kb_search: Searches the knowledge base by keyword.extract_json: Parses the first JSON object from text.write_file: Saves content to a file with a SHA-256 hash.
We register these tools in a mapping for dynamic invocation during function calling, and declare tool schemas to inform the model of correct argument structures. An AgentState dataclass holds the goal, memory, and tool-call trace for debugging.
The system uses three prompt templates:
- Planner: Returns a JSON plan with objective, steps, and tool checkpoints.
- Executor: Uses tools as needed, keeps intermediate notes short, and produces a draft output with verification checklist.
- Critic: Given goal and draft, identifies issues, suggests fixes, and provides an improved final answer.
The plan() function calls the planner to generate a JSON plan. The execute() function runs the executor with the plan and memory, allowing up to 12 tool-calling iterations, appending tool results to the message history. Finally, the critic reviews the draft and refines it.
This three-role pipeline ensures that complex tasks are broken down, executed with tool support, and quality-checked, resulting in a robust agentic system.