How to use OpenAI API with Python?

OpenAI's API unlocks a treasure trove of possibilities for developers. This tutorial dives into using the OpenAI Python library to seamlessly integrate these powerful functionalities into your Python projects.

If you have installed Jan or LMStudio or Ollama then no need to worry and do anything just sit back for a while. Those of you who want to explore the real OpenAI API please follow the steps:

Account and API Key: Head to https://platform.openai.com/ and create an account. Navigate to your API keys and generate a new secret key. This key is essential for authentication.

Package Installation: Open your favorite terminal or command prompt and run pip install openai. This installs the official OpenAI Python library.

from openai import OpenAI
client = OpenAI(api_key="sk-WznED1")

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ]
)

print(completion.choices[0].message)

If you are on a local jupyter notebook and do not want to use OpenAI API then you can use the below code:

from openai import OpenAI

# Point to the local server
client = OpenAI(base_url="http://localhost:8099/v1", api_key="lm-studio")

completion = client.chat.completions.create(
  model="model-identifier",
  messages=[
    {"role": "system", "content": "You are an expert Python Developer."},
    {"role": "user", "content": "Write the program to reverse a list."}
  ],
  temperature=0.7,
)

print(completion.choices[0].message)

 

generative-ai.io

Bridging the gap between basic tutorials and industry-grade applications, generative-ai.io is dedicated to bringing you the best in generative AI education.

Our content is designed to challenge and elevate your skills, ensuring you are well-prepared for real-world AI development.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright Algoholic (OPC) Private Limited