skies.dev

Build an AI in 10 Lines of Code

3 min read

We're going to write a program that takes user input, and the program will respond with an intelligent response. Pretty much any kind of input works. You can

  • ask it questions,
  • ask it to give you ideas,
  • ask it to help you with a writing task,

and much more.

Remarkably, we can accomplish all of this in 10 lines of Python code. We'll use OpenAI API to generate the responses.

You'll need to sign up to use the OpenAI API. At the time of writing this, a free tier is available and no credit card is required to use the API.

Once you've signed up, you'll want to find your API key and export it as an environment variable. It should look something like this:

export OPENAPI_API_KEY=sk-YDY6F73RKyBAFz4uiMNuaE2budH2QDNXkKUH6Zdq9WuLteRd

We'll set up a new Python project.

# Create and switch to the project folder
mkdir openai-ama
cd openai-ama

# Set up a virtual environment
python3 -m venv env

# Activate the virtual environment
source env/bin/activate

# Define dependencies
echo "openai==0.23.1" > requirements.txt

# Install dependencies
pip3 install -r requirements.txt

# Create the script file
touch ama.py

We're all set to write code. Our program is simple; we'll

  1. prompt the user for input,
  2. send the prompt to OpenAI,
  3. then print the response to the console.

We'll do this in an infinite loop, so the user can play with it until they kill the script.

ama.py
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

while True:
    prompt = input("Ask OpenAI Anything: ")
    completions = openai.Completion.create(prompt=prompt,
                                           engine="text-davinci-002",
                                           max_tokens=100)
    completion = completions.choices[0].text
    print(completion)

A couple of notes about the parameters we're passing to OpenAI:

  • We're using OpenAI's most capable model: text-davinci-002. With great power comes great responsibility. text-davinci-002 is 50 times more expensive than the Ada model. For personal use, this should be fine though.
  • Next, we're setting max_tokens=100. Tokens are the unit OpenAI bills on. Roughly speaking, "1 token is approximately 4 characters." Setting max_tokens sets the maximum amount of tokens you'll send to and receive from OpenAI per request.

That's it! This little script is simple, but hopefully you can see the possibilities for interesting app ideas using AI, such as

  • tweet generation
  • chatbots
  • writing essays

The list goes on and on.

I hope you have fun with it, and let me know on Twitter what you build! โœŒ๏ธ

Hey, you! ๐Ÿซต

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like