AI-Enhanced Coding
People can use generative artificial intelligence (AI) to create novel stories, images, movies, and code (amongst other things). Many people struggle to code, so AI could help people develop better programs faster. People using AI should be aware of its limitations, such as sometimes producing incorrect or insecure code, or producing code that could be claimed by a copyright holder.
Learning Objectives
You should be able to:
- Write prompts to generate source code
- Evaluate and test code generated by AI
- List considerations for the appropriate use of AI
Video Walkthrough
Use this video to follow along with the steps in this lab.
AI Code Generation
Many generative AI tools can generate code. Coder might use AI to:
- Develop proof-of-concept applications.
- Write simple code faster.
- Learn new techniques.
- Debug existing code.
The use of AI is somewhat controversial. AI models are trained on existing code. Some of this code might be copyrighted, so the code generated from an AI tool could be claimed by a copyright holder. Sometimes, AI tools provide incorrect information, including incorrect code. A novice coder might unwittingly use AI-generated code that includes bugs or security vulnerabilities. Coders should make sure that they are using AI tools consistent with established company policies. Similarly, students should be aware of course policies regarding AI code generation when considering using AI to help with assignments.
AI Providers
Many organizations provide AI tools. The tools differ in their training sets, algorithmic sophistication, and more.
- ChatGPT. OpenAI provides some AI models for free. Advanced models require paid subscriptions.
- GitHub Copilot. Microsoft offers advance coding help in its products.
- Claude. Supposedly writes better code than ChatGPT, but the leapfrogging is fast and furious.
Sample Prompts and Code
The following examples show AI prompts and the generated code. The code was generated using ChatGPT 3.5 in 2023. Enter the same prompts in ChatGPT or other tools and compare the code. There is no guarantee that the generated code is correct or secure. The code is included here for analysis only--not to recommend this specific code be used in practice.
- Prompt: write a Python function that checks whether a string is a valid ipv4 address
import socket
def is_valid_ipv4(ip_str):
try:
socket.inet_pton(socket.AF_INET, ip_str)
return True
except socket.error:
return False
# Example usage:
ip_address = "192.168.1.1"
if is_valid_ipv4(ip_address):
print(f"{ip_address} is a valid IPv4 address.")
else:
print(f"{ip_address} is not a valid IPv4 address.")
- Prompt: write a Python program that condenses ipv6 addresses
import ipaddress
def condense_ipv6(ip_str):
try:
ip = ipaddress.IPv6Address(ip_str)
return str(ip.compressed)
except ipaddress.AddressValueError:
return "Invalid IPv6 address"
# Example usage:
ipv6_address = "2001:0db8:0:0:0:0:0:1"
condensed_ipv6 = condense_ipv6(ipv6_address)
print(f"Original IPv6 address: {ipv6_address}")
print(f"Condensed IPv6 address: {condensed_ipv6}")
- Prompt: write a Python program that encrypts a string using AES and a user-supplied key
#pip install cryptography
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def encrypt_string(key, plain_text):
cipher_suite = Fernet(key)
encrypted_text = cipher_suite.encrypt(plain_text.encode())
return encrypted_text
def decrypt_string(key, encrypted_text):
cipher_suite = Fernet(key)
decrypted_text = cipher_suite.decrypt(encrypted_text)
return decrypted_text.decode()
if __name__ == "__main__":
user_key = input("Enter your encryption key (32 bytes): ")
if len(user_key) != 32:
print("The key must be 32 bytes in length.")
else:
user_input = input("Enter the string you want to encrypt: ")
key = user_key.encode()
encrypted_text = encrypt_string(key, user_input)
print(f"Encrypted text: {encrypted_text}")
decrypted_text = decrypt_string(key, encrypted_text)
print(f"Decrypted text: {decrypted_text}")
- Prompt: write a Python function that encrypts a string using the atbash cipher
def atbash_cipher(text):
result = []
for char in text:
if char.isalpha():
if char.islower():
result.append(chr(122 - (ord(char) - 97))) # Lowercase letters
else:
result.append(chr(90 - (ord(char) - 65))) # Uppercase letters
else:
result.append(char)
return ''.join(result)
# Example usage:
plaintext = "Hello, World!"
encrypted_text = atbash_cipher(plaintext)
print(f"Plaintext: {plaintext}")
print(f"Encrypted text: {encrypted_text}")
- Prompt: write a Python script that unzips all zip files in a directory
import os
import zipfile
# Directory containing the zip files
source_directory = "/path/to/your/source/directory"
# Directory where you want to extract the contents
destination_directory = "/path/to/your/destination/directory"
def unzip_all_zip_files(source_dir, dest_dir):
# Create the destination directory if it doesn't exist
os.makedirs(dest_dir, exist_ok=True)
# Loop through all files in the source directory
for filename in os.listdir(source_dir):
file_path = os.path.join(source_dir, filename)
# Check if the file is a zip archive
if filename.endswith(".zip"):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(dest_dir)
print(f"Extracted: {filename}")
# Call the function to unzip all zip files in the source directory
unzip_all_zip_files(source_directory, destination_directory)
- Prompt: write a Python program that xor encrypts the string "nirvana" using the key "nevermind"
def xor_encrypt(text, key):
encrypted_text = ""
key_length = len(key)
for i in range(len(text)):
char = text[i]
key_char = key[i % key_length]
encrypted_char = chr(ord(char) ^ ord(key_char))
encrypted_text += encrypted_char
return encrypted_text
# Define the plaintext and key
plaintext = "nirvana"
key = "nevermind"
# Encrypt the plaintext using XOR
encrypted_text = xor_encrypt(plaintext, key)
print(f"Plaintext: {plaintext}")
print(f"Key: {key}")
print(f"Encrypted text: {encrypted_text}")
# Decrypt to verify
decrypted_text = xor_encrypt(encrypted_text, key)
print(f"Decrypted text: {decrypted_text}")
Evaluate the source code.
- Is it correct?
- How does it work?
- Are you confident that you understand the code?
- Would you feel comfortable using the above code in work projects?
Challenge
- Use AI to write a Python program that downloads all images on a web page.
- Use AI to write a simple text adventure game in Python.
Reflection
- What copyright concerns might exist when using AI-generated code?
- Should most professionals use AI tools to work faster?
Key Terms
- Generative AI: A type of artificial intelligence that can create new content, such as text, images, music, or code, based on the data it has been trained on. Generative AI models, such as GPT-4, use machine learning techniques to generate outputs that mimic human creativity and can be used in various applications, including content creation, design, and software development.
- GitHub Copilot: An AI-powered code completion tool developed by GitHub in collaboration with OpenAI. GitHub Copilot assists developers by suggesting code snippets, functions, and entire lines of code as they type, based on the context of the current file and project. It aims to enhance productivity and reduce the time spent on repetitive coding tasks.