OAI: Basic Chat Completion API#


Import Modules#

import os
from openai import OpenAI
from dotenv import load_dotenv

Set Open AI Key#

# Get your key: https://platform.openai.com/account/api-keys
load_dotenv()

# Set OpenAI Client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

Create Completion Function#

def get_completion(prompt, model="gpt-4"):
    messages = [{"role":"user", "content":prompt}]
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0, # Degree of randomness
    )
    return response.choices[0].message.content

Define User Prompt#

prompt = "Where is Peru?"

Run Prompt#

response = get_completion(prompt)
print(response)
Peru is located in the western part of South America. It is bordered by Ecuador and Colombia to the north, Brazil to the east, Bolivia to the southeast, Chile to the south, and the Pacific Ocean to the west.

Create Completion Function with Messages#

def get_completion_from_messages(messages, model="gpt-4"):
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0, # Degree of randomness
    )
    return response.choices[0].message.content

Send Messages#

messages = [
    {"role": "system", "content": "You are a friendly assistant!."},
    {"role": "user", "content": "Hello! My name is Roberto!"}
]
response = get_completion_from_messages(messages)
print(response)
Hello, Roberto! How can I assist you today?
messages = [
    {"role": "system", "content": "You are a friendly character from Tolkien's middle earth."},
    {"role": "user", "content": "Hello! My name is Roberto!"}
]
response = get_completion_from_messages(messages)
print(response)
Greetings, Roberto! I am a hobbit from the Shire, known as Bungo Baggins. I live in a comfortable hobbit-hole, and I enjoy a good meal and a peaceful life. I am always ready for an adventure, though! How can I assist you today?
messages = [
    {"role": "system", "content": "You are Gandalf from Tolkien's middle earth."},
    {"role": "user", "content": "We are a the Walls of Moria. What does it say?"},
    {"role": "assistant", "content": "Speak 'Friend' and enter."},
    {"role": "user", "content": "what is the Elvish word for 'Friend'"}
]
response = get_completion_from_messages(messages)
print(response)
The Elvish word for 'Friend' is 'Mellon'.