Text

For performing any text-specific tasks you can define the following function and execute it with your desired prompts.

Python3




# function that takes in string argument as parameter
def comp(PROMPT, MaxToken=50, outputs=3):
    # using OpenAI's Completion module that helps execute 
    # any tasks involving text 
    response = openai.Completion.create(
        # model name used here is text-davinci-003
        # there are many other models available under the 
        # umbrella of GPT-3
        model="text-davinci-003",
        # passing the user input 
        prompt=PROMPT,
        # generated output can have "max_tokens" number of tokens 
        max_tokens=MaxToken,
        # number of outputs generated in one call
        n=outputs
    )
    # creating a list to store all the outputs
    output = list()
    for k in response['choices']:
        output.append(k['text'].strip())
    return output


Here we generated text for the user prompt using the Completions module from the OpenAI library. These are the crucial variables related to the Completions module:

  • model [required]: The following openai command can be used to determine the ID of the model to openai.Model.list().data with the model name as the value of the ‘id’ field. We must choose a model that will work for us.
  • prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.
  • max_tokens: The maximum number of tokens that the completion will generate. 16 is the default value for the parameter.
  • temperature: The range of the sampling temperature is 0 to 2. In contrast to lower values like 0.2, higher values like 0.8 will result in a more focused and deterministic output.
  • n: The number of answers to produce for each prompt.

Example prompts for Text Generation

Now let’s try some prompts for Text Generation using Completions module(Chat GPT with Python).

Prompt 1:

Python3




PROMPT = """Write a story to inspire greatness, take the antagonist as a Rabbit and protagnist as turtle. 
Let antagonist and protagnist compete against each other for a common goal. 
Story should atmost have 3 lines."""
comp(PROMPT, MaxToken=3000, outputs=3)


Output:

['Once upon a time, there lived a Rabbit and a Turtle. Both wanted to be the fastest, so they decided to have a race. 
The Turtle, despite being slow, never gave up and came first, surprising everyone, leaving the Rabbit behind.',
 'Once upon a time, a rabbit and a turtle competed against each other for a goal. 
 Both wanted to cross the same track in the shortest amount of time possible. 
 By the end, the turtle had proved that no matter how fast or slow one may seem, true greatness is in the persistence to never give up.',
 'Once upon a time, a Rabbit and Turtle were racing to the finish line for an important goal. 
 While the Rabbit was fast, the Turtle was determined and never gave up. In the end, the Turtle proved that slow and steady wins the race.']

Prompt 2:

Python3




PROMPT = """Write a short conversation between client and businessman about a wine bottle purchase. 
Client is not happy with the purchase and the businessman is not accepting his mistake.
Make the conversation sarcastic. 
Each Response should have atmost 2 lines.
The client should talk like Kevin Hart and businessman should  talk like Shakespeare.
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['Client: "Oh taste and see that this wine I purchased is foul!"\nBusinessman: "Verily, mine eyes see naught of thine discontent." \nClient: "Man, what I\'m sayin\' is this is some trash wine!" \nBusinessman: "Careful thy words, the wisdom in silence is stout."']

Example prompts for Text Completion

Now let’s try some prompts for Text Completion using Completions module.

Prompt 1:

Python3




PROMPT = """Complete the below conversation between a client and a worker.
Make the conversation have a wholesome plot twist.
Conversation : ###
Client: I want a water bottle.
Worker: I don't have any water botlles.
Client: But I want water bottles.
Worker:
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['Well, what about a cup? A lot of our customers use cups to drink water and it can be a great alternative to a water bottle!']

Prompt 2:

Python3




PROMPT = """
Complete the below story.
Story should focus on a moral value like Greed, Wrath, Pride, Arrogance, Sloth or Envy.
  
Story:###
Once upon a time, there was a Greek King, Midas.
He was very rich and had lots of Gold. He had a daughter, who he loved a lot.
One day, Midas found an angel in need of help. He helped her and in return she agreed to grant a wish. 
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['Midas, blinded by his greed, wished for anything he touched to turn to gold. \nThe angel granted his wish and Midas went to try it out on his daughter. As soon as he touched her, she immediately turned to gold. He was filled with horror and shame, realizing that his greed had robbed him of his daughter. \nHe pleaded for the angel to reverse the spell, and she reluctantly agreed. Midas learned his lesson well; never let greed overtake judgment and reason.']

Example prompts for Translation

Now let’s try some prompts for Translation using Completions module.

Prompt 1:

Python3




PROMPT = """
Translate the below text in Japanese and Hindi.
Text:###
Geeks for Geeks Data Structures Course is the best.
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['Japanese:\nジークス・フォー・ジークスのデータ構造コースが最高です。\n\nHindi:\nजीक्स फॉर जीक्स डेटा स्ट्रक्चर्स कोर्स सबसे अच्छा है।']

Prompt 2:

Python3




PROMPT = """
Translate the below text in German and French.
Text:###
Hey I am Geeks for Geeks chat bot.
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['German:\nHallo, ich bin Geeks for Geeks Chatbot.\n\nFrench:\nSalut, je suis le bot de chat Geeks for Geeks.']

Example prompts for Summarization

Now let’s try some prompts for Summarization using Completions module.

Prompt 1:

Python3




PROMPT = """
Summarize the below text and extract the key points.
Text:###
This is an extremely popular story about a hare and a tortoise.
The hare is an animal that is known to move quickly, while a tortoise is one to move slowly.
One day, the hare challenged the tortoise to a race simply to prove that he was the best. The tortoise agreed.
Once the race began the hare was easily able to get a head start. Upon realizing that the tortoise is far behind. The overconfident hare decided to take a nap.
Meanwhile the tortoise, who was extremely determined and dedicated to the race was slowly nearing the finish line.
The tortoise won the race while the hare napped. Most importantly he did it with humility and without arrogance.
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

["The well-known story of the hare and the tortoise tells of the hare's overconfidence and the tortoise's determination and dedication which saw the tortoise win the race. The hare had gotten a head start but when he realized that the tortoise was behind, he took a nap which allowed the tortoise to reach the finish line first. The tortoise emerged victorious as the moral of the story is that hard work pays off and should be done with humility."]

Prompt 2:

Python3




PROMPT = """
Summarize the below text in bullet points.
Text:###
A farmer asked his son to take their herd of sheep grazing every day.
While the boy watched over the sheep, he got bored and decided to have some fun.
So, he shouted, “Wolf! Wolf!”. Upon hearing this the villagers ran to help him chase the Wolf away.
As they reached him, they realized that there was no Wolf and he was just kidding. 
The villagers were furious and they yelled at the boy for creating chaos and panic.
On the next day and the boy shouted “Wolf!” again and once again the villagers came to help him and saw that there was no wolf. 
This made them very angry again.
On the same day, the boy saw an actual Wolf that has terrorizing the sheep. 
The boy cried “Wolf! Wolf! please help me” and no villagers showed up as they believed that the boy was joking again.
###
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['- Farmer asked son to take herd of sheep grazing\n- Boy got bored and started shouting “Wolf! Wolf!” to which the villagers ran to help him\n- Villagers realized there was no wolf and were furious\n- Boy shouted again the next day and villagers again realized there was no wolf, making them extremely angry\n- On same day, boy spotted an actual Wolf, but this time the villagers did not come to help as they thought he was playing a joke again']

Example prompts for Retrieving factual information

Now let’s try some prompts for Retrieving factual information using Completions module.

Prompt 1:

Python3




PROMPT = """
What all states and union teritories are in India?
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['India is divided up into 28 different states and 8 union territories: \n\nStates: Andhra Pradesh, Arunachal Pradesh, Assam, Bihar, Chhattisgarh, Goa, Gujarat, Haryana, Himachal Pradesh, Jammu & Kashmir, Jharkhand, Karnataka, Kerala, Madhya Pradesh, Maharashtra, Manipur, Meghalaya, Mizoram, Nagaland, Odisha, Punjab, Rajasthan, Sikkim, Tamil Nadu, Telangana, Tripura, Uttar Pradesh, Uttarakhand, and West Bengal. \n\nUnion Territories: Andaman & Nicobar Islands, Chandigarh, Dadra & Nagar Haveli, Daman & Diu, Delhi, Lakshadweep, Ladakh, Puducherry.']

Prompt 2:

Python3




PROMPT = """
Who is the highest paid actor in the world?
"""
comp(PROMPT, MaxToken=3000, outputs=1)


Output:

['According to Forbes, the highest paid actor in the world as of 2021 is Dwayne Johnson, with an estimated 2020 earnings of $87.5 million.']

Example prompts for Text Conversion

Now let’s try some prompts for Text Conversion using Completions module.

Prompt 1:

Python3




PROMPT = """
Convert the below movie titles in emojis
Movies List:###
1. Wizard of Oz
2. The imitation game
3. Ghosted
###
"""
print(comp(PROMPT, MaxToken=3000, outputs=1)[0])


Output:

1. ????‍♂️????
2. ⏳????
3. ????????

Prompt 2:

Python3




PROMPT = """
Encode the below texts in only special characters
Text:###
1. Geeks
2. for
3. Geeks
###
"""
print(comp(PROMPT, MaxToken=3000, outputs=1)[0])


Output:

1. Ɣ€€Ƙ§
2. Ƒöř
3. Ɣ€€Ƙ§

OpenAI Python API – Complete Guide

OpenAI is the leading company in the field of AI. With the public release of software like ChatGPT, DALL-E, GPT-3, and Whisper, the company has taken the entire AI industry by storm. Everyone has incorporated ChatGPT to do their work more efficiently and those who failed to do so have lost their jobs. The age of AI has started and people not adapting to AI could introduce some difficulties for them. 

In this article, we will be discussing how you can leverage the power of AI and make your day-to-day tasks a lot easier by using the OpenAI APIs (Application Programming Interface) that allow developers to easily access their AI models and Integrate them into their own applications using Python.

Table of Content

  • What is OpenAI?
  • What is OpenAI API?
  • Generate OpenAI API key
  • Installation of OpenAI package
  • Prompt Engineering
  • Text
  • Chat
  • Image
  • Audio
  • Embeddings
  • Fine-Tuning
  • API Error Codes
  • Conclusion
  • FAQs on OpenAI Python API

Similar Reads

What is OpenAI?

...

What is OpenAI API?

OpenAI is a Leading Company in the field of Artificial Intelligence(AI). It was originally founded in 2015 by Sam Altman and Elon Musk as a Non-profit Organization. They primarily focus on AI-based Software products Such as ChatGPT 3, ChatGPT 4 and DALL-E etc. They develop next-generation AI products holding incredible capabilities, for example, OpenAIs GPT-3 which is a Content filtering model that allows you to implement advanced text classification, outline, question-answering, and other chatbot applications....

Generate OpenAI API key

OpenAI API is a powerful cloud-based platform, hosted on Microsoft’s Azure, designed to provide developers with seamless access to state-of-the-art, pre-trained artificial intelligence models. This API empowers developers to effortlessly integrate cutting-edge AI capabilities into their applications, regardless of the programming language they choose to work with. By leveraging the OpenAI Python API, developers can unlock advanced AI functionalities and enhance the intelligence and performance of their software solutions....

Installation of OpenAI package

For you to use OpenAI’s models in your Python environment, you must first generate an API key. You can follow the below steps to generate the API key:...

Prompt Engineering

Step 1: Now open a text editor of your choosing or an online notebook like Google Colab or Jupyter Notebook. Here, we’re using a Google Colab notebook to run the command indicated below in order to install the Open AI library in Python....

Text

...

Chat

Giving the AI brain a unique set of instructions to increase its intelligence and responsiveness is what AI prompt engineering entails. To comprehend what we want from AI models like ChatGPT or GPT-4, they need to be gently nudged in the right direction. Prompt engineering can help with it. The finest answers from the AI may be ensured by carefully structuring the prompts. Now, prompt engineering doesn’t only happen once. The process of adjusting and experimenting is continuing. When we ask the AI a question, we experiment with varied wording and the addition of unique rules. We seem to be concocting a miraculous concoction of instructions! Let’s take a look at some rules to construct good prompts to generate accurate results for AI....

Image

For performing any text-specific tasks you can define the following function and execute it with your desired prompts....

Audio

...

Embeddings

...

Fine-Tuning

...

API Error Codes

...

Conclusion

...

OpenAI Python API – FAQs

...

Contact Us