Python code to connect Open AI

Python code to connect Open AI

First, we have to install OpenAI libraries. So, use the following command to install OpenAI Libraries.

OpenAI Library Install Command:

python3 -m pip install openai

Sample Code:

import os
os.environ[ "OPENAI_API_KEY" ] = "<Your OpenAI API Key>"

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        { "role": "system", "content": "You are a helpful assistant." },
        {
            "role": "user",
            "content": "What is the capital of Canada"
        }
    ]
)

print( completion.choices[0].message )

Leave a Reply