PythonArtificial Intelligence

How to Use OpenAI API in Python?

How to use GPT3.5 or GPT4 in your application or software?

Download Code Here

1. Install & Import Packages

In [1]:

!pip install openai
Requirement already satisfied: openai in c:\python\lib\site-packages (0.27.6)
[notice] A new release of pip is available: 23.3.2 -> 24.0
[notice] To update, run: python.exe -m pip install --upgrade pip
Requirement already satisfied: requests>=2.20 in c:\python\lib\site-packages (from openai) (2.28.1)
Requirement already satisfied: tqdm in c:\python\lib\site-packages (from openai) (4.66.1)
Requirement already satisfied: aiohttp in c:\python\lib\site-packages (from openai) (3.8.4)
Requirement already satisfied: charset-normalizer<3,>=2 in c:\python\lib\site-packages (from requests>=2.20->openai) (2.1.0)
Requirement already satisfied: idna<4,>=2.5 in c:\python\lib\site-packages (from requests>=2.20->openai) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\python\lib\site-packages (from requests>=2.20->openai) (1.26.11)
Requirement already satisfied: certifi>=2017.4.17 in c:\python\lib\site-packages (from requests>=2.20->openai) (2022.6.15)
Requirement already satisfied: attrs>=17.3.0 in c:\python\lib\site-packages (from aiohttp->openai) (22.1.0)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\python\lib\site-packages (from aiohttp->openai) (6.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in c:\python\lib\site-packages (from aiohttp->openai) (4.0.2)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\python\lib\site-packages (from aiohttp->openai) (1.9.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\python\lib\site-packages (from aiohttp->openai) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in c:\python\lib\site-packages (from aiohttp->openai) (1.3.1)
Requirement already satisfied: colorama in c:\python\lib\site-packages (from tqdm->openai) (0.4.5)

In [2]:

import openai

In [3]:

pip install python-dotenv
Requirement already satisfied: python-dotenv in c:\python\lib\site-packages (1.0.0)
Note: you may need to restart the kernel to use updated packages.

In [4]:

from dotenv import load_dotenv
load_dotenv()

Out[4]:

True

In [5]:

import os

2. Setup your API key

In [ ]:

# you can even copy-paste you open ai key directly here.
# openai.api_key ="sk-fdsfsgfhfjjhjghjkghkgkgkg"

In [8]:

openai.api_key = os.getenv("OPENAI_API_KEY")

3. Try Open AI API

In [13]:

model = "gpt-3.5-turbo"
response = openai.ChatCompletion.create(
    model = model,
    messages = [
        {"role": "user",
        "content":"Translate the following text into French: 'Hello, How are you?'"}
    ])

In [ ]:

response

In [14]:

print(response['choices'][0]['message']['content'])
Salut, comment vas-tu ?

Download Code Here

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button