Skip to main content

Lesson 11 of 13

Module 8 Practice

Practice building AI API calls with safe, well-structured Python code.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practice: Test Your API Setup

Practice: Test Your API SetupHTML
HTML
✓ Valid
HTML|67 lines|✓ Valid syntax
UTF-8

Mini Project: Simple AI Text Generator

Mini Project: Simple AI Text Generator
# Mini Project: Build a simple AI text generator
# A command-line tool that answers questions using the OpenAI API

import os
from openai import OpenAI

def create_ai_assistant():
    """
    A simple interactive AI assistant for learning about Generative AI.
    """
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        print("Error: Set OPENAI_API_KEY environment variable first.")
        return

    client = OpenAI(api_key=api_key)

    system_prompt = """You are a helpful tutor teaching beginners about Generative AI.
- Use simple, clear language
- Provide one practical example with each explanation
- Keep answers concise (under 150 words)
- If a concept requires more detail, offer to explain further"""

    conversation_history = [{"role": "system", "content": system_prompt}]

    print("=== Generative AI Learning Assistant ===")
    print("Ask me anything about Generative AI!")
    print("Type 'quit' to exit, 'clear' to start a new conversation.")
    print()

    while True:
        # Get user input
        user_input = input("You: ").strip()

        if not user_input:
            continue

        if user_input.lower() == "quit":
            print("Goodbye!")
            break

        if user_input.lower() == "clear":
            conversation_history = [{"role": "system", "content": system_prompt}]
            print("Conversation cleared. Starting fresh.")
            continue

        # Add user message to history
        conversation_history.append({"role": "user", "content": user_input})

        try:
            # Call the API with full conversation history
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=conversation_history,
                max_tokens=200,
                temperature=0.7
            )

            ai_reply = response.choices[0].message.content

            # Add AI reply to history
            conversation_history.append({"role": "assistant", "content": ai_reply})

            print(f"AI: {ai_reply}")
            print()

        except Exception as e:
            print(f"Error: {e}")
            print()

create_ai_assistant()
Diagram
Loading diagram…

Practice Diagram

Key Takeaways from Module 8

  • An AI API allows your code to communicate with an AI model over the internet
  • API requests include the model name, messages, and your API key
  • API responses are JSON objects - the text is nested inside choices[0].message.content
  • NEVER hardcode API keys in your code - always use environment variables
  • Always add error handling for authentication errors, rate limits, and connection failures
  • Set spending limits in your API provider's dashboard to protect against unexpected costs
  • Call AI APIs from your server, not directly from browser-side JavaScript

Key Takeaways

  • Practice building AI API calls with safe, well-structured Python code.
  • An AI API allows your code to communicate with an AI model over the internet
  • API requests include the model name, messages, and your API key
  • API responses are JSON objects - the text is nested inside choices[0].message.content

Finished this lesson?

0 of 13 in Module 8
Sign in to save progress

Topics in This Module

0/13 done