File size: 4,268 Bytes
9b93e00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import os
from abc import ABC, abstractmethod
from dotenv import load_dotenv, find_dotenv
import openai
from typing import List


class AIEmailGenerator(ABC):
    """Abstract base class for generating emails using AI."""

    @abstractmethod
    def _configure_api(self):
        """Configure the API settings."""
        pass

    @abstractmethod
    def generate_mail_contents(self, email_contents: List[str]) -> List[str]:
        """Generate more formal and elaborate content for each email topic."""
        pass

    @abstractmethod
    def generate_mail_format(self, sender: str, recipient: str, style: str, email_contents: List[str]) -> str:
        """Generate a formatted email with updated content."""
        pass


class AzureOpenAIEmailGenerator(AIEmailGenerator):
    """Concrete class for generating emails using OpenAI on Azure."""

    def __init__(self, engine: str):
        """Initialize the AzureOpenAIEmailGenerator class by loading environment variables and configuring OpenAI."""
        self.engine = engine
        self._load_environment()
        self._configure_api()

    def _load_environment(self):
        """Load environment variables from .env file."""
        load_dotenv(find_dotenv())

    def _configure_api(self):
        """Configure OpenAI API settings."""
        openai.api_type = "azure"
        openai.api_base = os.getenv('OPENAI_API_BASE')
        openai.api_version = "2023-03-15-preview"
        openai.api_key = os.getenv("OPENAI_API_KEY")

    def generate_mail_contents(self, email_contents: List[str]) -> List[str]:
        """Generates more formal and elaborate content for each email topic."""
        for i, input_text in enumerate(email_contents):
            prompt = (
                f"Rewrite the text to be elaborate and polite.\n"
                f"Abbreviations need to be replaced.\n"
                f"Text: {input_text}\n"
                f"Rewritten text:"
            )
            response = openai.ChatCompletion.create(
                engine=self.engine,
                messages=[
                    {"role": "system", "content": "You are an AI assistant that helps people find information."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0,
                max_tokens=len(input_text) * 3,
                top_p=0.95,
                frequency_penalty=0,
                presence_penalty=0
            )
            email_contents[i] = response['choices'][0]['message']['content']
        return email_contents

    def generate_mail_format(self, sender: str, recipient: str, style: str, email_contents: List[str]) -> str:
        """Generates a formatted email with updated content."""
        email_contents = self.generate_mail_contents(email_contents)
        contents_str = ""
        contents_length = 0

        for i, content in enumerate(email_contents):
            contents_str += f"\nContent{i + 1}: {content}"
            contents_length += len(content)

        prompt = (
            f"Write a professional email that sounds {style} and includes Content1 and Content2 in that order.\n\n"
            f"Sender: {sender}\n"
            f"Recipient: {recipient}{contents_str}\n\n"
            f"Email Text:"
        )
        response = openai.ChatCompletion.create(
            engine=self.engine,
            messages=[
                {"role": "system", "content": "You are an AI assistant that helps people find information."},
                {"role": "user", "content": prompt}
            ],
            temperature=0,
            max_tokens=contents_length * 2,
            top_p=0.95,
            frequency_penalty=0,
            presence_penalty=0
        )
        return response['choices'][0]['message']['content']

        # Esempio di utilizzo:

if __name__ == "__main__":
    engine = "gpt-4"  # Specificare l'engine desiderato
    email_generator = AzureOpenAIEmailGenerator(engine)
    sender = "example_sender@example.com"
    recipient = "example_recipient@example.com"
    style = "formal"
    email_contents = ["This is the first content.", "This is the second content."]
    formatted_email = email_generator.generate_mail_format(sender, recipient, style, email_contents)
    print(formatted_email)