The Wayback Machine - https://web.archive.org/web/20240816151122/https://www.geeksforgeeks.org/text-manipulation-using-openai/
Open In App

Text Manipulation using OpenAI

Last Updated : 08 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Open AI is a leading organization in the field of Artificial Intelligence and Machine Learning, they have provided the developers with state-of-the-art innovations like ChatGPT, WhisperAI, DALL-E, and many more to work on the vast unstructured data available. For text manipulation, OpenAI has compiled a Completions model which helps you to generate new text data, fill masks in strings, carry conversations, translate, and summarize. The completion module uses the power of GPT-3 to perform these tasks and give out fascinating results. In today’s article, we will be going through this Completions module and see how one can use this in Python.

Steps to perform text manipulation using OpenAI

Now let’s explore how one can use GPT-3 to manipulate text data

Step 1: Install the Openai library in your python environment

!pip install openai

Step 2: Import the openai library and assign the API key to openai environment

Python3




# import the library
import openai
# assign the API key to the environment by replacing
# API_KEY with your generated key
openai.api_key = "API_KEY"


If you do not have an API key, then log in to your OpenAI account after creating one. After logging in, select Personal from the top-right menu, and then select “View API keys”. A page containing API keys is displayed, and the button “Create new secret key” is visible. A secret key is generated when you click on that, copy it and save it somewhere else because it will be needed in further steps.

Step 3: Define a function to perform text manipulation using OpenAI API in python

Python3




# function that takes in string argument as parameter
def comp(PROMPT, MaxToken=50, outputs=3):
    # using OpenAI's Completion module that helps perform
    # text manipulations
    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 have used the Completions module from OpenAI library and generate text for the given user prompt. Here are the important parameters involved with Completions module:

  • model [required]: ID of the model to use can find out using the below command openai.Model.list().data where the value of ‘id’ represent the model name. we need to select a suitable model as per our use.
  • 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 to generate in the completion. The default value is 16.
  • temperature: Sampling temperature ranges between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
  • n: number of completions to generate for each prompt.

Example prompts for text manipulation

Now let’s try out some prompts with the completions module and see their results.

Prompt 1: Text Generation

Python3




p = """Tell me whether the tweet is positive, neutral, or negative.
Tweet: I don't like tomato!
Sentiment:"""
  
comp(p, outputs=1)


Output:

['Negative']

Prompt 2: Text Completion

Python3




p = """hey doctor, ____"""
  
comp(p,outputs=5)


Output:

['What seems to be the problem?',
'Good morning! How can I help you today?',
'What seems to be the trouble?',
'Good to see you! How can I help you today?',
'What seems to be the problem?']

Prompt 3: Text Generation

Python3




p = "Write a tagline for my shoe company"
Output = comp(p,outputs=3)
print(Output[0])
print(Output[1])
print(Output[2])


Output:

"Walk in Comfort, Walk with Us!"
"Walking in Style, Step by Step"
"Walk in style with our designer shoes!"

Prompt 4: Text Completion

Python3




p = """What is the sentiment of these tweets:
  
1. "GFG has the best DSA course"
2. "Got late for work and got fired for that"
3. "Can't wait for Diwali!!!"
4. "What do you have in mind?"
5. "I hate strawberry"
  
Tweet sentiment ratings:"""
  
print(comp(p, outputs=1)[0])


Output:

1. Positive
2. Negative
3. Positive
4. Neutral
5. Negative

Prompt 5: Text Completion

Python3




p="""Complete this conversation with an AI assistant. 
The assistant is helpful, sarcastic, clever, and very nice in nature. 
Human want to know some good places to eat.
  
Human: Hello, who are you?
AI: I am an AI created by OpenAI. How can I help you today?
Human:"""
Output = comp(p,MaxToken =35, outputs=3)
print(Output[0])
print('\n',Output[1])
print('\n',Output[2])


Output:

I'm looking for a good place to eat.
AI: Sounds like you've got a bit of a craving for something delicious. I know the perfect place! Let me
I'm looking for some good places to eat. Do you know any?
AI: Sure! Are you looking for something specific, like Italian, or do you just want
Could you recommend some good places to eat in this area?
AI: Of course! There are lots of great restaurants in the area. I recommend checking out the Seafood

Prompt 6: Translation

Python3




p="""
Translate this sentence in hindi, german and japanese:
'I am learning from GeeksforGeeks.'
"""
Output = comp(p,MaxToken=500,outputs=2)
print(Output[0])
print('\n',Output[1])


Output:

Hindi: मैं GeeksforGeeks से सीख रहा हूँ।
German: Ich lerne von GeeksforGeeks.
Japanese: 私はGeeksforGeeksから学んでいます。
Hindi: मैं GeeksforGeeks से सीख रहा हूँ।
German: Ich lerne von GeeksforGeeks.
Japanese: 私はGeeksforGeeksから学んでいます。

Prompt 7: Summarization

Python3




p="""
Summarize the below paragraph for a pre-school student explaining 
how dangerous Mt. Everest is:
  
Mount Everest, located in the Himalayas, is the highest 
peak in the world and a popular destination for mountaineers. 
Standing at an impressive elevation of 29,029 feet (8,848 meters), 
it poses a significant challenge to climbers due to its extreme 
altitude and unpredictable weather conditions. The mountain is 
situated on the border between Nepal and China, and it attracts 
adventurers from around the globe who are determined to conquer 
its formidable slopes. Mount Everest has a rich history of expeditions 
and has been a subject of fascination for explorers and adventurers
for centuries. Despite its allure, scaling Mount Everest is a 
dangerous undertaking that requires meticulous planning, physical
fitness, and mountaineering expertise.
"""
Output = comp(p,MaxToken=20,outputs=3)
print(Output[0])
print(Output[1])
print(Output[2])


Output:

Mount Everest is the highest mountain in the world. It's very dangerous- you have to be
Mount Everest is a very tall mountain located in the Himalayas. People from all around the
Mt. Everest is the highest peak in the world and it is very dangerous and hard to

Prompt 8: Translation

Python3




p="""
How would Indian say this paragraph:
  
Mount Everest, located in the Himalayas, is the highest 
peak in the world and a popular destination for mountaineers. 
Standing at an impressive elevation of 29,029 feet (8,848 meters), 
it poses a significant challenge to climbers due to its extreme 
altitude and unpredictable weather conditions. The mountain is 
situated on the border between Nepal and China, and it attracts 
adventurers from around the globe who are determined to conquer 
its formidable slopes. Mount Everest has a rich history of expeditions 
and has been a subject of fascination for explorers and adventurers
for centuries. Despite its allure, scaling Mount Everest is a 
dangerous undertaking that requires meticulous planning, physical
fitness, and mountaineering expertise.
"""
Output = comp(p,MaxToken=1200,outputs=1)
print(Output[0])


Output:

माउंट एवरेस्ट, हिमालयों में स्थित, विश्व में सर्वोच्च चोटी है और पर्यावरण में श्रमिकों के लिए एक लोकप्रिय गंतव्य है। 
29,029 फीट (8,848 मीटर) की सुंदर ऊँचाई के साथ, यह अत्यधिक ऊँचाई और अनपेक्षित मौसम के कारण पर्यावरण में श्रमिकों को एक महत्वपूर्ण चुनौती देता है।
यह पर्वत नेपाल और चीन के सीमा पर स्थित है और यह पृथ्वी के हर कोणस्थल से ऊर्जा और अहंकार से प्रतीक्षा करने वाले अभ्यासीयकों को आकर्षित करता है।
माउंट एवरेस्ट का एक अत्यंत अधिक प्रयासों और आगमनों का अत्यधिक इतिहास है और यह दो घंटों से अन्वेषकों और आगमनाकारों के लिए आकर्षण रहा है।
माउंट एवरेस्ट के आकर्षण के बावजूद, उसे छोड़ने के लिए सख्त योजना की आवश्यकता, शारीरिक स्वस्थता और पर्वतारोहण के विद्या की आवश्यकता होती है।

Prompt 9: Text Conversion

Python3




PROMPT = """
Convert the below text to emoji's
Text:###
1. Hi
2. Geeks
3. For
###
Answer:
"""
print(comp(PROMPT, MaxToken=300, outputs=1)[0])


Output:

1. ????
2. ????
3. ????

Prompt 10: Text Conversion

Python3




PROMPT = """
Convert the below text to only special characters
Text:###
1. Hi
2. Geeks
3. For
###
Answer:
"""
print(comp(PROMPT, MaxToken=300, outputs=1)[0])


Output:

§1. ㅎㅣ
2. ㄱㅣㅇㄱㅅ
3. ㄹㅗ

Prompt 11: Retrieve factual information

Python3




PROMPT = """
How many states are in India?
Answer:
"""
print(comp(PROMPT, MaxToken=300, outputs=1)[0])


Output:

There are 28 states and 8 union territories in India.

Prompt 12: Retrieve factual information

Python3




PROMPT = """
How many countries are there in world?
Answer:
"""
print(comp(PROMPT, MaxToken=300, outputs=1)[0])


Output:

There are currently 195 countries in the world, according to the United Nations. This number includes 193 member states that are UN members, as well as 2 non-member observer states.

Frequently Asked Questions (FAQs)

1. What is completion in OpenAI?

The most fundamental OpenAI model is the Completions API, which has a simple interface yet is highly versatile and powerful. It answers with a text completion that you’ve instructed it to prepare when you prompt it.

2. What is the difference between chat completion and completion in OpenAI?

The /chat/completions endpoint completes a specific dialogue and demands input in a specific way that matches the message history, in contrast to the /completions endpoint, which completes a single prompt and accepts a single string.

To use chatGPT models, you must use the /chat/completions API, but your request must be modified accordingly.

3. What is text completion AI?

Complete the sentence, a specialised model or system created to automatically create text or complete phrases from a partial input or prompt is referred to as having artificial intelligence (AI). In order to identify the statistical patterns, linguistic structures, and semantic linkages present in the training data, these models are trained on large volumes of text data. The text completion AI makes use of this newly discovered knowledge to create a logical and contextually appropriate continuation of the text when given an unfinished sentence or prompt.

4. How does OpenAI generate text?

The GPT-3 language model is used in the Open AI text generator to create intelligent text. This tool enables you to create a wide range of texts. The Open AI text generator is among the newest and most well-liked forms of text generators, however there are many different varieties.

5. Can Completions API write an essay?

You may ask it to write anything for you, in any style, including business taglines, essays, research papers, software code, song lyrics about your dog, and poems using the name of your child.

6. Can Completions API generate images?

No, the completions API can only generate text. It does not have image generating capabilities. If you want to generate images using text prompts you can check out DALL-E by OpenAI.

Conclusion

The Completions module, which uses the power of GPT-3 to generate new text, fill in masked strings, facilitate discussions, translate languages, and summarise content, is one of the primary features provided by OpenAI, as we saw in this article. Python programmers may make use of the OpenAI library and unlock the power of the Completions module by following a few straightforward steps.

The article’s prompts show off the versatility of the Completions module by providing illustrations of how to create text responses for various scenarios and contexts. The factors temperature, maximum tokens, prompt structure, and model choice all help to give the outputs that are produced flexibility and control.

Although the findings from OpenAI’s text completion AI models can be rather interesting, it is vital to use caution and evaluate the generated text for correctness, coherence, and appropriateness. Text completion AI models that rely on statistical patterns rather than actual comprehension may occasionally produce incorrect or absurd results. Developers may take advantage of text completion AI’s potential while assuring the accuracy and dependability of the generated text by understanding its capabilities and constraints.



Previous Article
Next Article

Similar Reads

Sam Altman fired as CEO by OpenAI board - Who is the New CEO of OpenAI?
In a surprising turn of events, OpenAI, the creator of ChatGPT, made a major announcement on Friday regarding significant shifts in its leadership structure. The company revealed a notable shakeup in its top positions, removing Co-founder and current CEO, Sam Altman, from his role. The board's decision also led to the repositioning of the current C
6 min read
OpenAI Whisper - Converting Speech to Text
In the digital era, the demand for precise and efficient transcription of audio content is everywhere, spanning across professions and purposes. Whether you're creating subtitles, conducting research, or pursuing various other tasks, the conversion of audio and video to text is a common requirement. While numerous modules exist for this purpose, th
6 min read
Develop an LLM Application using Openai
Language Models (LMs) play a crucial role in natural language processing applications, enabling the development of tools that generate human-like text. OpenAI's Generative Pre-Trained Transformer (GPT) models, such as GPT-3.5-turbo, are widely used in this domain. They excel in understanding context, learning language patterns, and generating coher
5 min read
Spam Classification using OpenAI
The majority of people in today's society own a mobile phone, and they all frequently get communications (SMS/email) on their phones. But the key point is that some of the messages you get may be spam, with very few being genuine or important interactions. You may be tricked into providing your personal information, such as your password, account n
6 min read
Create a ChatBot with OpenAI and Gradio in Python
Computer programs known as chatbots may mimic human users in communication. They are frequently employed in customer service settings where they may assist clients by responding to their inquiries. The usage of chatbots for entertainment, such as gameplay or storytelling, is also possible. OpenAI ChatGPT has developed a large model called GPT(Gener
3 min read
Level up your ChatGPT Game with OpenAI's Free Course on Prompt Engineering for Developers
Want to learn Prompt Engineering? OpenAI made it possible for you! The parent company of ChatGPT launched a free ChatGPT course on prompt engineering for developers. An interesting new course on prompt engineering called "ChatGPT Prompt Engineering for Developers" has been curated by renowned artificial intelligence (AI) experts Andrew Ng from Deep
3 min read
PandasAI Library from OpenAI
We spend a lot of time editing, cleaning, and analyzing data using various methodologies in today's data-driven environment. Pandas is a well-known Python module that aids with data manipulation. It keeps data in structures known as dataframes and enables you to alter, clean up, or analyze data by carrying out various operations like generating a b
10 min read
Create a ChatBot with OpenAI and Streamlit in Python
ChatGPT is an advanced chatbot built on the powerful GPT-3.5 language model developed by OpenAI.There are numerous Python Modules and today we will be discussing Streamlit and OpenAI Python API to create a chatbot in Python streamlit. The user can input his/her query to the chatbot and it will send the response. Required Modules pip install openaip
5 min read
OpenAI announces DALL-E 3 API, Audio API, and Whisper large-v3
OpenAI, a pioneer in artificial intelligence research, recently hosted its first developer day and unveiled a range of new APIs. These cutting-edge tools are set to revolutionize the way we interact with technology. In this article, we will delve into the details of OpenAI's latest offerings, including DALL-E 3, the text-to-speech Audio API, and th
3 min read
Google Gemini AI vs OpenAI ChatGPT: Everything to Know About It
The field of AI has seen surprising breakthroughs in recent years, with the advancement of strong generative models that can compose text, pictures, and different kinds of content based on natural language inputs. Two of the most prominent instances of such models are Google Gemini and OpenAI ChatGPT, which compete for the title of the most develop
8 min read
OpenAI’s GPT Store Launched! How to Use and Make Money
OpenAI, a leading player in the field of artificial intelligence, has launched its much-anticipated GPT Store. This innovative platform allows users to find useful and popular custom versions of ChatGPT, the company’s flagship chatbot product. ChatGPT is powered by GPTs, which are specialized language models that can be created and customized by an
7 min read
OpenAI’s Sam Altman’s Most Used App
In the world of artificial intelligence, few names are as prominent as Sam Altman, the CEO of OpenAI. Known for his leadership in one of the most innovative AI companies in the world, Altman is a figure who constantly pushes the boundaries of technology. However, a recent revelation about his most used app has left many surprised. During a conversa
2 min read
OpenAI Codex vs. GitHub Copilot: Which AI Assists Programmers More Effectively?
What if developing a game was as easy as writing a command like "bounce an object" in plain English? You could manipulate digital objects in any way you wanted, without any programming knowledge whatsoever. Thanks to text-to-code models like OpenAI Codex, this dream isn't that far away anymore. As OpenAI has already demonstrated, non-technical user
6 min read
New Boundaries of AI: From OpenAI's Sora to Google's Gemini 1.5 Model
In today's world, Artificial Intelligence (AI) is continuously evolving at an exceptional rate, changing the way we live and work. This week, two developments have caught the attention of people worldwide – OpenAI's Sora and Google's Gemini 1.5 model. This article will talk about the specifics of these two, examining their implications, application
4 min read
OpenAI tests ChatGPT widget for Android Home Screen - Check how to Use it
OpenAI has introduced a game-changing widget for its widely-used chatbot, ChatGPT, specifically designed for Android smartphones. This innovative feature empowers users to interact with ChatGPT directly from their home screens, eliminating the need to launch the app itself. This signifies a significant step forward in user experience and accessibil
5 min read
OpenAI Whisper
In today's time, data is available in many forms, like tables, images, text, audio, or video. We use this data to gain insights and make predictions for certain events using various machine learning and deep learning techniques. There are many techniques that help us work on tables, images, texts, and videos, but there are not a lot of techniques t
9 min read
OpenAI ChatGPT 5 Launch: Release date, Upgrades, Pricing and Everything Else
The world of Artificial Intelligence is abuzz with anticipation for the upcoming launch of OpenAI's ChatGPT 5. This next-generation language model promises to be a big step forward, pushing the boundaries of human-machine interaction and artificial intelligence capabilities. While the exact ChatGPT 5 release date remains unconfirmed, rumours and sp
6 min read
OpenAI Launches GPT-4o Omni
OpenAI has announced its latest innovation, "GPT 4o Omni," a free and significantly faster version of its predecessor, GPT 4. This advanced language model builds on the success of GPT 4 including the ability to understand and respond to information across multiple modalities—text, speech, and images. This "omnimodal" capability means a substantial
4 min read
Generate Images With OpenAI in Python
We are currently living in the age of AI. Images to automate processes including image generation for logos, advertisements, stock images, etc. So here we will use OpenAI to generate Images with Python [ChatGPT API]. There are numerous uses of the DALL - E model and today we will be discussing how one can use its Python ChatGPT API [OpenAI API] to
8 min read
What is OpenAI SearchGPT? How it works and How to Get it?
OpenAI, the company behind the popular ChatGPT AI assistant, has announced the launch of its own search engine called SearchGPT. This highly anticipated move positions OpenAI as a potential rival to established search giants like Google and Bing. OpenAI SearchGPT is a cutting-edge search engine optimization (SEO) tool powered by artificial intellig
8 min read
Mastering Polars: High-Efficiency Data Analysis and Manipulation
In the ever-evolving landscape of data science and analytics, efficient data manipulation and analysis are paramount. While pandas has been the go-to library for many Python enthusiasts, a new player, Polars, is making waves with its performance and efficiency. This article delves into the world of Polars, providing a comprehensive introduction, hi
11 min read
Processing text using NLP | Basics
In this article, we will be learning the steps followed to process the text data before using it to train the actual Machine Learning Model. Importing Libraries The following must be installed in the current working environment: NLTK Library: The NLTK library is a collection of libraries and programs written for processing of English language writt
2 min read
Python | Tokenize text using TextBlob
TextBlob module is a Python library and offers a simple API to access its methods and perform basic NLP tasks. It is built on the top of NLTK module. Install TextBlob using the following commands in terminal: pip install -U textblob python -m textblob.download_corpora This will install TextBlob and download the necessary NLTK corpora. The above ins
3 min read
Build a Text Translator Web App using Flask and Azure Cognitive Services
We're going to create a website that will translate text into multiple languages using Artificial Intelligence(AI). We'll use Flask framework for the Front end and Azure Cognitive Services(collection of AI services) for the Back end. To get started writing our Flask application with Python, we need to set up our development environment, which will
7 min read
Clustering Text Documents using K-Means in Scikit Learn
Clustering text documents is a typical issue in natural language processing (NLP). Based on their content, related documents are to be grouped. The k-means clustering technique is a well-liked solution to this issue. In this article, we'll demonstrate how to cluster text documents using k-means using Scikit Learn. K-means clustering algorithm The k
2 min read
Read and Write Rectangular Text Data Quickly using R
Reading and writing rectangular text data quickly in R Programming Language can be achieved using various packages and functions, depending on your specific needs and the data format. Two commonly used packages for this purpose are readr and data. table. Here's how you can do it with these packages. Rectangular Text DataIn R, to manipulate and anal
8 min read
Text Generation using Fnet
Transformer-based models excel in understanding and processing sequences due to their utilization of a mechanism known as "self-attention." This involves scrutinizing each token to discern its relationship with every other token in the sequence. Despite the effectiveness of self-attention, its drawback lies in its computational cost. For a sequence
14 min read
Text Generation using Recurrent Long Short Term Memory Network
This article will demonstrate how to build a Text Generator by building a Recurrent Long Short Term Memory Network. The conceptual procedure of training the network is to first feed the network a mapping of each character present in the text on which the network is training to a unique number. Each character is then hot-encoded into a vector which
5 min read
ML | Text Generation using Gated Recurrent Unit Networks
This article will demonstrate how to build a Text Generator by building a Gated Recurrent Unit Network. The conceptual procedure of training the network is to first feed the network a mapping of each character present in the text on which the network is training to a unique number. Each character is then hot-encoded into a vector which is the requi
6 min read
Text Analysis Using Turicreate
What is Text Analysis? Text is a group of words or sentences.Text analysis is analyzing the text and then extracting information with the help of text.Text data is one of the biggest factor that can make a company big or small.For example On E-Commerce website people buy things .With Text Analysis the E-Commerce website can know what it's customer
3 min read
Practice Tags :
three90RightbarBannerImg