How AI wiped out an entire industry in Nairobi
Back to Tutorials
aiTutorialintermediate

How AI wiped out an entire industry in Nairobi

September 7, 202637 views5 min read

Learn to build an AI-powered academic writing assistant using OpenAI's API that can generate scholarly content on any topic, demonstrating the technology that disrupted the Nairobi writing industry.

Introduction

In Nairobi, Kenya, the rise of AI-powered writing tools like ChatGPT has dramatically disrupted a thriving industry of academic paper writing services. This tutorial will teach you how to build a simple AI-powered academic writing assistant using Python and OpenAI's API. You'll learn how to interact with the OpenAI API, process academic prompts, and generate human-like text responses. This is the kind of technology that transformed the Kenyan writing industry, and understanding it will help you leverage AI for content creation.

Prerequisites

  • Basic Python programming knowledge
  • OpenAI API key (free to get at platform.openai.com)
  • Python 3.7 or higher installed
  • pip package manager
  • Basic understanding of API interactions and JSON data structures

Step-by-Step Instructions

1. Set Up Your Development Environment

1.1 Install Required Packages

First, we need to install the OpenAI Python library to interact with the API. Open your terminal and run:

pip install openai

This package provides a clean interface to communicate with OpenAI's API endpoints, making it easier to send prompts and receive responses.

1.2 Create a Configuration File

Create a file named config.py to store your API key:

import os

class Config:
    OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

# Set your API key as an environment variable
# export OPENAI_API_KEY='your_actual_api_key_here'

This approach keeps your API key secure and allows you to easily switch between different environments.

2. Initialize the OpenAI Client

2.1 Create the Main Script

Create a file named academic_writer.py and start with the basic setup:

import openai
from config import Config

# Initialize the OpenAI client
openai.api_key = Config.OPENAI_API_KEY

# Set up the model parameters
def create_academic_prompt(topic, word_count=500):
    return f"Write an academic essay on {topic} with approximately {word_count} words. The content should be suitable for a university-level student."

# Function to generate academic content
async def generate_academic_content(prompt):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are an academic writing assistant. Provide well-structured, scholarly content."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=1500,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error generating content: {str(e)}"

if __name__ == "__main__":
    print("Academic Writing Assistant Initialized")

This setup defines the basic structure for interacting with the AI model, including system instructions that guide the AI's behavior to be academic-focused.

3. Build the Core Functionality

3.1 Add Prompt Engineering

Enhance your prompt engineering capabilities by creating more sophisticated prompts:

def create_detailed_prompt(topic, section, word_count=300):
    return f"\n\nWrite a detailed academic section on {section} within the topic of {topic}.\n\nRequirements:\n- Use scholarly language\n- Include relevant academic references\n- Maintain logical flow\n- Keep approximately {word_count} words\n\nBegin writing now:"

# Enhanced content generation function
async def generate_section_content(topic, section, word_count=300):
    prompt = create_detailed_prompt(topic, section, word_count)
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a university-level academic writing assistant. Your writing is scholarly, precise, and well-structured. Always cite references when appropriate."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=1000,
            temperature=0.6
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error generating section content: {str(e)}"

Prompt engineering is crucial because it determines how the AI interprets your request. The more specific your instructions, the better the output quality.

3.2 Implement Content Validation

Add basic content validation to ensure quality output:

def validate_content(content):
    if not content or len(content.strip()) < 50:
        return False
    
    # Check for basic academic language indicators
    indicators = ['however', 'therefore', 'furthermore', 'moreover', 'thus']
    academic_words = sum(1 for word in indicators if word in content.lower())
    
    return academic_words >= 2

# Enhanced generation with validation
async def generate_and_validate(topic, section, word_count=300):
    content = await generate_section_content(topic, section, word_count)
    
    if validate_content(content):
        return content
    else:
        return "Content validation failed. Please try again with a different prompt."

This validation ensures that generated content meets basic academic writing standards, which is important when dealing with educational content.

4. Create a User Interface

4.1 Build a Simple CLI Interface

Add a command-line interface to interact with your academic writing assistant:

import asyncio
import sys

async def main():
    print("=== Academic Writing Assistant ===")
    print("Enter 'quit' to exit")
    
    while True:
        topic = input("\nEnter the main topic: ")
        if topic.lower() == 'quit':
            break
            
        section = input("Enter the section to write about: ")
        word_count = input("Enter desired word count (default 300): ")
        
        if not word_count:
            word_count = 300
        else:
            word_count = int(word_count)
            
        print("\nGenerating content...")
        content = await generate_and_validate(topic, section, word_count)
        
        print("\nGenerated Content:")
        print("=" * 50)
        print(content)
        print("=" * 50)

if __name__ == "__main__":
    asyncio.run(main())

This interface allows you to easily test different topics and sections, simulating how a real academic writing service might operate.

5. Test Your Academic Writer

5.1 Run Your Script

Execute your script in the terminal:

python academic_writer.py

You'll be prompted to enter topics and sections. Try entering something like:

  • Topic: Climate Change
  • Section: Impact on Developing Countries

This will demonstrate how AI can quickly generate academic content that would have previously required human writers.

5.2 Analyze the Output

Notice how the AI responds to your prompts. The system instructions guide the AI to produce academic content with scholarly language and structure. This is the same technology that disrupted the Nairobi writing industry - it can produce content at scale with minimal human intervention.

Summary

In this tutorial, you've built a basic academic writing assistant using OpenAI's API. You've learned how to:

  • Initialize and configure the OpenAI client
  • Engineer effective prompts for academic content
  • Generate structured academic text using AI
  • Validate content quality
  • Create a simple command-line interface

This demonstrates the core technology behind the AI disruption in Nairobi. The ability to quickly generate high-quality academic content has fundamentally changed how educational writing services operate. As you've seen, with just a few lines of code, you can create tools that produce content at scale - a capability that has transformed entire industries.

Source: The Decoder

Related Articles