Python OpenAI API

November 27, 2023

Lang: cs en de es

Not only can you use ChatGPT through the web interface, but you can also use it in your own applications. This means using the program to connect to ChatGPT using an interface called an API. I'll describe how to get started using artificial intelligence in the Python programming language, specifically OpenAI, in this tutorial.

What is AI?

AI, or artificial intelligence, is a branch of computer science that deals with the development of computer systems that have the ability to perform tasks that usually require human intelligence. These tasks can be image recognition, speech recognition, language translation, decision making, learning, and many more. The goal in creating artificial intelligence is to create computer systems that are able to understand, learn and respond to different situations in a similar way to the human brain.
There are various approaches to artificial intelligence, including symbolic learning, evolutionary algorithms, neural networks, and deep learning. Neural networks, in particular, have become very popular recently and are used to solve complex tasks such as image, voice and natural language recognition.
Artificial intelligence has a wide range of applications, including autonomous vehicles, disease diagnosis, personalized marketing, industrial automation, and many other areas. AI can be strong (general) or narrow (specialized). Strong AI would be able to perform any intellectual task that a human can, while narrow AI is designed for a specific task, such as a voice assistant or a recommendation system.

Artificial Intelligence Experience

I've been testing AI tools since they were first published. More detailed information and experiences with various AI tools can be found in the article Artificial Intelligence: Dalle2, Chat GPT.

In contrast, in this article I will focus only on the programmatic use of OpenAI using Python.

What is OpenAI?

OpenAI is a research organization focused on artificial intelligence (AI). It was founded in December 2015 to promote and develop AI technologies for the benefit of all of human society. The organization was founded by several prominent figures in the technology field, including Elon Musk, Sam Altman, Ilya Sutskever, Greg Brockman, and others.

OpenAI has two main missions:

  1. Creating safe and beneficial artificial intelligence: OpenAI seeks to advance the field of artificial intelligence while ensuring, that this technology is used for the benefit of society as a whole. This means that the organization seeks to minimize the potential negative impacts of AI on society and addresses safety and ethical issues in AI.
  2. Provide public benefit: OpenAI is committed to sharing its researched knowledge and discoveries with the world. This includes publishing some scientific research results and releasing some tools and models to the public.

It should be taken into account that OpenAI, despite having "open" in its name, is not as open as it pretends to be and used to be more open. It is also a commercial entity, so any official statements and opinions about charity and usefulness should be taken with a grain of salt.

OpenAI is known for its research in deep learning and very large neural networks. Models developed by OpenAI, such as GPT (Generative Pre-trained Transformer), are currently (2023) one of the biggest advances in natural language processing and are already used in many applications such as chatbots, compilers and many others.

AI alternatives

There are other alternatives to OpenAI. Here are the two main alternatives:

  • Google Cloud AI: Google's platform provides a wide range of AI services, including NLP (Natural Language Processing), machine learning, and generative models. It offers services such as Google Cloud Natural Language API, Google Cloud Translation API, and TensorFlow, which is a machine learning framework.
  • Microsoft Azure AI: Microsoft Azure offers various tools for machine learning, speech recognition, natural language processing, and more. These include services such as Azure Cognitive Services and Azure Machine Learning.

Connections - API

You can connect to and use OpenAI using API. OpenAI provides a REST API that you can call directly or use a library that wraps the call. OpenAI API documentation.

If you're interested in more detail about REST APIs in practice, read the article How to implement custom REST APIs in the PHP programming language.

API key

I assume you already have an account on https://chat.openai.com/. To use the API the first thing you will need is to get an API key. An API key is a unique string whose knowledge proves that you have the right to use the API and is tied to your account.

After logging into your OpenAI account administration, you can choose a payment method and charge, for example, $5.
openai-billing-overview
openai-payment-method
openai-billing-history

If you're not a VAT payer, you have to pay $6.05 to charge $5, because VAT (21% in the Czech Republic) is added on top of that.

You can then generate your API key to use in your applications. openai-api-key

If you charge a larger amount, it's a good idea to set some limits on your API usage so that you don't use up the entire amount by mistake or if the API key is leaked. openai-usage-limits

Test API keys

You can check the functionality of the key on this page https://www.chatwithgpt.ai/. This is a clear web application that is a client of the OpenAI API and after you enter your key, you can send queries to the OpenAI API.

Python environment

We will prepare the python environment including the necessary libraries using docker. I have prepared a docker image configuration from which you will then drop the docker container.

Here is the Dockerfile with the docker image definition:

FROM python:3.11.3

WORKDIR /app
COPY requirements.txt .
RUN pip install --upgrade pip setuptools
RUN pip install --no-cache-dir -r requirements.txt

To build the image, use the command:

docker build -t python-openai ./

To start a docker container from a created docker image, use the following command:

docker run -it --rm -v $PWD:/app -e OPENAI_API_KEY=key --name python-openai-run python-openai /bin/bash
Instead of key, enter your API key.

Python program and OpenAI API

The source code for the application is in the app.py file. If you have prepared everything well, you can now run the program from the command line from the container:

python app.py

The main function that calls ChatGPT looks like this:

def getdata(display, data,temperature):
    prompt=command+" ```"+data+"```"
    model="gpt-3.5-turbo"

    response = openai.ChatCompletion.create(
        model=model, # You can use another model according to your preference
                temperature=temperature, # Set the temperature for creative responses
                max_tokens=500, # Set the maximum number of tokens in the response
        messages=[
            { "role": "system", "content": "You: how can I help you patient?"},
            {"role": "user", "content": prompt}
        ]
    )
    # Get response from model
    nova_response = response.choices[0].message['content']
    return nova_response

Detailed documentation for the Python OpenAI library

Source codes

You can find all the source code for the application and environment configuration on my GitHub profile, where the repository is: GitHub Python OpenAI example.

Video tutorial

Complete step by step video tutorial on how to use the OpenAI API using the Python programming language:

OpenAI use

In practice, I used the OpenAI API at a hackathon where I programmed an application that translated medical reports into text that was understandable to a non-expert.
At this link is presentation of a project using artificial intelligence. Here are more of my presentations and talks.

ChatGPT is great for example:

  • when you need to rephrase some text
  • you'd like to have a colleague to discuss an issue
  • as a smarter search engine
  • generate text
  • generate sample programs

Models & Price

ChatGPT has different language models. The differences are different. For example, they also differ in price. Details of the language model versions to use and pricing policy can be found at this url: https://platform.openai.com/docs/deprecations

You can check the API usage and therefore credit here: https://platform.openai.com/account/usage

Articles on a similar topic

Analysis of assignment and pricing of software project development
Python program to control Docker using the API
How to use MailCatcher to test emails
Creating a WebSocket web application and setting up a proxy
Project management: agile software development
How to run old PHP applications
What a good programmer should know
Rust programming language
NodeJS: development, server configuration
Nette security bug CVE-2020-15227
REST API: platform API
Custom web and mail hosting with ISP Config software
Programming in SQL: PostgreSQL, MySQL/MariaDB
HTTPS: secure web
NoSQL database Mongo DB
Connecting to Microsoft SQL Server from Linux
What is the job description of a programmer
Python application localization
Which mail and web hosting to choose
Digispark - Program Atmel ATtiny microcontroller with Arduino IDE
Development for ARM processors with Arduino IDE
How to program the ESP8266 WiFi processor
Open smartphone with Linux - Openmoko Neo FreeRunner

Newsletter

If you are interested in receiving occasional news by email.
You can register by filling in your email news subscription.


+