File size: 1,699 Bytes
ea6afa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from openai import OpenAI
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()
key = os.getenv("OPENAI_API_KEY")

# Initialize the OpenAI client
client = OpenAI(api_key=key)

def generate_paraphrase(sentences, model="gpt-4", num_paraphrases=10, max_tokens=150, temperature=0.7):
    """Generate paraphrased sentences using the OpenAI GPT-4 model."""
    
    # Ensure sentences is a list
    if isinstance(sentences, str):
        sentences = [sentences]
    
    paraphrased_sentences_list = []

    for sentence in sentences:
        full_prompt = f"Paraphrase the following text: '{sentence}'"
        
        try:
            chat_completion = client.chat.completions.create(
                messages=[{"role": "user", "content": full_prompt}],
                model=model,
                max_tokens=max_tokens,
                temperature=temperature,
                n=num_paraphrases  # Number of paraphrased sentences to generate
            )
            # Extract paraphrased sentences
            paraphrased_sentences = [choice.message.content.strip() for choice in chat_completion.choices]
            paraphrased_sentences_list.extend(paraphrased_sentences)
        except Exception as e:
            print(f"Error paraphrasing sentence '{sentence}': {e}")

    return paraphrased_sentences_list

# Example usage
result = generate_paraphrase(
    "Mayor Eric Adams did not attend the first candidate forum for the New York City mayoral race, but his record — and the criminal charges he faces — received plenty of attention on Saturday from the Democrats who are running to unseat him."
)

print(f"Number of paraphrases generated: {len(result)}")