Exercises to complete:
- Obtain an API key
- Make sure that you have the OpenAI Python client installed
- Create a python 3 script
- Create a Bash script
- Make scripts executable and run the Bash script
To be able to run chatGPT in command line, you can follow these steps. Please note that you need to have sudo privileges or root access.
- Obtain an API key
To use the OpenAI API, you need an API key. If you don’t have one, you can sign up on the OpenAI website and create a new API key.
Note: The API is priced at $0.002 per 1K tokens. You have free credit to use, though.
Remember that OpenAI wonβt display your secret API key again after you generate it, so copy your API key and save it. Iβll create an environment variable named OPENAI_API_KEY that will contain my API key for this tutorial.
- You can use the OpenAI API with Python in a Bash script. To do this, first make sure that you have the OpenAI Python client installed:
Now, you can install Docker with the following command.
SLES | openSUSE Leap 15.4
|
|
Debian
|
|
Red Hat
|
|
- Create a python 3 script:
vim chatgpt.py
put he below content into the file:
|
|
- Now, you can use a Python script in a Bash script that invokes the OpenAI API. Here’s an example Bash script that runs a Python script:
|
|
- Set permissions:
|
|
The script runs this Python code directly.
Note that this script must be run in an environment where Python and the openai
package are available.
Add to .bashrc or .zshrc below variable:
export OPENAI_API_KEY=your-API-key
And then load it with the following command:
source .bashrc
or
source .zshrc
Remember to secure your API keys and consider environment variables or other secure methods to store them, as hard coding them in scripts can lead to security vulnerabilities.
- Now you can use the script to get responses from ChatGPT by running:
|
|
Remember to declare in a py file a proper path to the proper python version. For openSUSE 15.4 it will be:
#!/usr/bin/python3.9
That’s it! You now have a basic tutorial on how to use ChatGPT with the API in the Linux CLI. Feel free to customize the script or explore more advanced features of the OpenAI API.