Open In App

Prompt Engineering for Transformation of Text

Last Updated : 27 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the series of learning “How to write better prompts and customize them as per the specific use?” so, that we do not need to read articles that say 30 prompts to make your life easy with ChatGPT:). In this article, we will see how can we use ChatGPT to transform a piece of text and use the LLM as a ChatBot. But before that, we need to set the API key as well as define the function to get the model’s response for a particular chat or piece of text.

Import the Openai package and assign the Openai API key

Python3




import openai
import os
 
openai.api_key = "<OpenAI API Key>"


Let’s check How it works

Python3




prompt = f"""
Translate the following Hindi text to English: \
``` यदि आप कोडिंग सीखना चाहते हैं, तो गीक्सफोरगीक्स आपके लिए सबसे अच्छी जगह हो सकती है।```
"""
 
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content":prompt },
    ]
)
 
# Print the output
response


Output:

<OpenAIObject chat.completion id=chatcmpl-7T5xhJ3bd7mi29nJa3Lo5ZMGuHvRA at 0x7f50412e2db0> JSON: {
"id": "chatcmpl-7T5xhJ3bd7mi29nJa3Lo5ZMGuHvRA",
"object": "chat.completion",
"created": 1687168785,
"model": "gpt-3.5-turbo-0301",
"usage": {
"prompt_tokens": 111,
"completion_tokens": 20,
"total_tokens": 131
},
"choices": [
{
"message": {
"role": "assistant",
"content": "\"If you want to learn coding, then Geeksforgeeks can be the best place for you.\""
},
"finish_reason": "stop",
"index": 0
}
]
}

Prompt Engineering for Transforming Text

While browsing through different websites we must have used the feature that enables us to view the same content in different languages. Now these things can be easily powered or backed by AI models like ChatGPT which is able to convert text in more than 50 languages and is efficient in over a dozen programming languages.

Prompt:

MASSAGE = [{“role”: “user”, “content”: <PROMPT>}]

PROMPT

PROMPT = f “””

Transform from <TYPE 1> to < TYPE 2>\

“` <SENTENCES>“`

“””

Create a function for transformation

Python3




def get_completion(prompt, temperature=0):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=temperature
    )
     
    return response.choices[0].message["content"]


Example 1:

Python3




prompt = f"""
Translate the following English text to Spanish: \
``` If you want to learn coding,
   then Geeksforgeeks can be the best place for you.```
"""
response = get_completion(prompt)
print(response)


Output:

Si quieres aprender a programar, entonces Geeksforgeeks puede ser el mejor lugar para ti.

Example 2: Multiple Language

we can convert the same piece of text in multiple languages but we have to include it in the prompt that we are passing into the model.

Python3




prompt = f"""
Translate the following  text to Hindi, French and Spanish
and Sanskrit: \
```If you want to learn coding,
   then Geeksforgeeks can be the best place for you.```
"""
response = get_completion(prompt)
print(response)


Output:

Hindi: यदि आप कोडिंग सीखना चाहते हैं, तो गीक्सफॉरगीक्स आपके लिए सबसे अच्छा स्थान हो सकता है।
French: Si vous voulez apprendre à coder, Geeksforgeeks peut être le meilleur endroit pour vous.
Spanish: Si quieres aprender a codificar, Geeksforgeeks puede ser el mejor lugar para ti.
Sanskrit: यदि त्वं कोडिंगं शिक्षितुं इच्छसि, तदा गीक्सफॉरगीक्स तवानुग्रहाय सर्वोत्तमस्थानमस्ति।

Those who can write and understand multiple languages can easily understand in which language the current piece of text has been written.

Prompt for Language Detection in a piece of Text.

prompt = f”””
Tell me which language this is: 
“`Combien coûte le lampadaire?“`
“””

Type Transformation

Transformation of text is not only limited to language transformation we can covert the tone and format of some pieces of text as well. For e,g if we have an individual who uses slang quite often in his day-to-day conversation and due to this unknowingly includes it in emails and official communications as well it can be misunderstood by the reader and sound unprofessional. For such cases, ChatGPT becomes a savior.

Python3




prompt = f"""
Translate the following from slang to a business letter:
'Hey bro, I am facing some issues with my lapi.
See if you are freen then do knock my cubicle as well.'
"""
response = get_completion(prompt)
print(response)


Output:

Dear Sir/Madam,
I am writing to inform you that I am experiencing some technical difficulties with my laptop.
If you are available, I would greatly appreciate it if you could come to my cubicle and assist me with this matter.
Thank you for your time and attention to this matter.
Sincerely,
[Your Name]

Code Transformation

Wow! That’s an amazing transformation to save the day from getting judged to be unprofessional. The same is the case with programming Languages as well. There have been many use cases of these AI models in the conversion of language from one to another for example from Java to Python or any other such combinations.

Python3




binary_search_code = '''
// Java code to implement the approach
import java.io.*;
 
// Class describing a node of tree
class Node {
 
    int data;
    Node left;
    Node right;
    Node(int v)
    {
        this.data = v;
        this.left = this.right = null;
    }
}
 
class GFG {
    // Inorder Traversal
    public static void printInorder(Node node)
    {
        if (node == null)
            return;
 
        // Traverse left subtree
        printInorder(node.left);
 
        // Visit node
        System.out.print(node.data + " ");
 
        // Traverse right subtree
        printInorder(node.right);
    }
    // Driver Code
    public static void main(String[] args)
    {
        // Build the tree
        Node root = new Node(1000);
        root.left = new Node(200);
        root.right = new Node(2000);
        root.left.left = new Node(100);
        root.left.right = new Node(300);
        root.right.left = new Node(1500);
        root.right.right = new Node(3000);
 
        // Function call
        System.out.print("Inorder Traversal: ");
        printInorder(root);
    }
}
 
'''
 
prompt = f"""
Translate the following Java code of Binary Search Tree (BST) Traversals
in Python  {binary_search_code}
"""
response = get_completion(prompt)
print(response)


Output:

# Python code to implement the approach
# Class describing a node of tree
class Node:
def __init__(self, v):
self.data = v
self.left = None
self.right = None
# Inorder Traversal
def printInorder(node):
if node is None:
return
# Traverse left subtree
printInorder(node.left)
# Visit node
print(node.data, end=" ")
# Traverse right subtree
printInorder(node.right)
# Driver Code
if __name__ == '__main__':
# Build the tree
root = Node(1000)
root.left = Node(200)
root.right = Node(2000)
root.left.left = Node(100)
root.left.right = Node(300)
root.right.left = Node(1500)
root.right.right = Node(3000)
# Function call
print("Inorder Traversal: ", end="")
printInorder(root)

This is not it in the process of transforming text we can also convert and take the help of the ChatGPT model to get our text or article get proofread by the model for any grammatical mistakes or to change the style of the text or the tone used. This helps a lot of time to save time that was usually spent in this process of proofreading.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads