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:
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
- prompt the user for input,
- send the prompt to OpenAI,
- 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.
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.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-002is 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_tokenssets 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
- writing essays
The list goes on and on.
I hope you have fun with it, and let me know on Twitter what you build! ✌️