Bootstrap FreeKB - OpenAI - Getting Started with Python OpenAI on Linux
OpenAI - Getting Started with Python OpenAI on Linux

Updated:   |  OpenAI articles

Let's create a Python virtual environment.

python -m venv my_virtual_env

 

And activate the Python virtual environment.

source my_virtual_env/bin/activate

 

Then install the openai package in the Python virtual environment.

pip install openai

 

And let's create a Python script that contains the following markup.

Notice in this example that model gpt-4o-mini i is being used.

import os
from openai import OpenAI

client = OpenAI()

def get_completion(prompt):
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "user", "content": prompt}
            ]
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"An error occurred: {e}"

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        prompt = " ".join(sys.argv[1:])
        print(get_completion(prompt))
    else:
        print("Please provide a prompt as a command line argument.")

 

Last but not least before running the application, at https://platform.openai.com/api-keys, create an API key and issue the following command to set the OPENAI_API_KEY variable.

export OPENAI_API_KEY=<your API key>

 

And now let's use the Python script to ask a question.

~]$ python a "who was the president of the United States in 2015"
The President of the United States in 2015 was Barack Obama. He served as the 44th president from January 20, 2009, to January 20, 2017.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 0b9ff7 in the box below so that we can be sure you are a human.