“`html
AI Automation Playbook
Step-by-step workflows for automating content, email, social media, and research with AI agents.
How to Build Your First AI Assistant with Python – A Practical Step-by-Step Tutorial
1. Setting Up Your Development Environment
- Install Python 3.9+ and create a dedicated virtual environment (e.g.,
python -m venv ai_env). - Sign up for an OpenAI account, create an API key, and install the
openailibrary via pip. - Verify the setup by running a minimal “Hello World” completion call using the
gpt-3.5-turbomodel.
2. Understanding the Core Concepts: Prompts and Completions
- Learn the role of system, user, and assistant messages in the chat completion format.
- Craft clear and specific prompts to guide the model toward the desired output.
- Experiment with the
temperature(0–2) andmax_tokensparameters to control creativity and response length.
3. Writing the Basic Chat Loop
- Create a Python list (e.g.,
messages = []) to store the full conversation history. - Implement a
while Trueloop that accepts user input and appends it to the messages list. - Call the OpenAI API with the updated messages list and print the assistant’s response in real time.
4. Adding Personality and Constraints with System Messages
- Prepend a system message (e.g., “You are a friendly coding tutor”) to set the assistant’s behavior and tone.
- Use system instructions to enforce constraints – for example, “Only answer in one sentence” or “Never mention competitors.”
- Test multiple system prompts side by side to observe how the same user input yields different responses.
5. Handling Errors and API Rate Limits
- Wrap every API call inside a
try-exceptblock to catchopenai.error.APIError,RateLimitError, andAuthenticationError. - Implement exponential backoff logic (using
time.sleep()) when a rate limit is hit. - Log errors to a file and provide user-friendly fallback messages instead of crashing.
6. Enhancing with Simple Memory and Context
- Maintain contextual conversation history by keeping the messages list across loop iterations.
- Implement a token counting function to truncate the oldest messages when the total exceeds a cost threshold (e.g., 3000 tokens).
- Optionally save the conversation to a local JSON file so users can review past chats.


