Python and ChatGPT API – Introduction

This class shows you how to use Python to interact with the ChatGPT API and create your own AI powered apps.

  • 00:00 Intro
  • 03:12 First Demo of Python and ChatGPT API
  • 06:33 What is ChatGPT API
  • 15:19 ChatGPT API Pricing
  • 21:16 Getting the API Key
  • 32:11 Code Samples
  • 33:35 Python ChatGPT Code for Non Streamed
  • 42:40 Python ChatGPT Script for Streamed Response
  • 47:01 Autoblog with ChatGPT Demonstration
  • 57:05 Final Thoughts

openai-streamed.py

import openai
openai.api_key = 'APIKEY'

completion = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "how many chuck can a wood chuck chuck if a woodchuck could chuck would!"}
  ],
  stream=True
)

for chunk in completion:
  print(chunk.choices[0].delta.content)

openai-nonstreamed.py

import openai
openai.api_key = 'APIKEY'

completion = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "what is the radius of jupiter"}
  ]
)

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

print(completion)

openai-autoblog.py

import openai
openai.api_key = 'APIKEY'

title = ['Why Fish Run', 'Why Cats Fly', 'Why Bats Swim']

file = open('autoblog.html', 'a+')
for x in title:
  completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
      {"role": "system", "content": "You are a journalist."},
      {"role": "system", "content": "Write a 250 word blog post."},
      {"role": "user", "content": x }
    ]
  )
  print(x)
  print(completion.choices[0].message.content)
  reply = completion.choices[0].message.content
  
  #Format returned text with HTML <p> tags
  reply = reply.split('\n')
  post =''
  for y in reply:
    post = f'{post} <p>{y}</p>'
  file.write(f'<h1>{x}</h1>{post}')

file.close()

Be the first to comment

Leave a Reply