Using the OpenAI API with Python

Tokens

Tokens are small text units — words or parts of words — used by the model to process and generate language.

 

Pricing

Source: https://platform.openai.com/docs/pricing?latest-pricing=standard 
Below is the current pricing for GPT-5 models (per 1 million tokens):
 

Model Input         Cached input            Output
gpt-5 $1.25 $0.125 $10.00
gpt-5-mini $0.25 $0.025 $2.00
gpt-5-nano     $0.05 $0.005 $0.40
*(per 1 million tokens)*

 

Model   Different models, offer different performances
Input   Cost per 1M input tokens
         Cached input   Discounted cost for repeated input
Output   Cost per 1M generated tokens

 

 
Example for gpt-5-nano:

 

         Input:           "Write a short poem about the ocean."               (Estimated 8 tokens)
         Output:   "The ocean whispers softly under the moonlight."      (Estimated 10 tokens)
 

     Input:      8 tokens × $0.05 / 1,000,000 = $0.0000004
Output:    10 tokens × $0.40 / 1,000,000 = $0.000004


Total cost ≈ $0.0000044

 

 

Installation

pip install openai

 

 

OpenAI account & Payment

  • Create an account on the OpenAI platform: https://platform.openai.com/docs/overview
  • Click the settings (cogwheel) icon in the top-right corner.
  • In the side menu click:  Billing 
  • Add funds to your account using   Add to credit balance 

 

API Key

  • Click the settings (cogwheel) icon in the top-right corner.
  • In the side menu click:  Billing 
  •   + Create new secret key 
  • Optionally give a name to they key
  • Select a Project. If you didn't create any, choose Default Project
  • Save your key 

 

 

Example

from openai import OpenAI

client = OpenAI(api_key="****")

response = client.chat.completions.create(
    model="gpt-5-nano",
    messages=[
        {"role": "user", "content": "Write a short poem about the ocean."}
    ]
)

print(response.choices[0].message.content)

 

model → defines which model will be used.
Available models: https://platform.openai.com/docs/models

messages → list of messages that make up the chat.
Each message has a role and a content.

role → indicates who is sending the text:

  • "user" — represents what the user writes.
     

content → the actual text of the message.

response.choices[0].message.content → contains the model’s generated reply.

 

Output

 


openai==2.3.0



15 Oct. 2025 | Last Updated: 03 Dec. 2025 | jaimedcsilva

Related
  • Using the OpenAI API with Python
  • Ollama: Install and Run Local LLMs
  • Audio to Text with Python

  • Buy Me a Coffee