| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import Foundation
- protocol EmailWriterServicing {
- func generateEmail(
- prompt: String,
- subject: String,
- emailType: EmailType,
- tone: EmailTone
- ) async throws -> String
- }
- struct EmailWriterService: EmailWriterServicing {
- private let openAI: OpenAIChatServicing
- init(openAI: OpenAIChatServicing = OpenAIChatService()) {
- self.openAI = openAI
- }
- func generateEmail(
- prompt: String,
- subject: String,
- emailType: EmailType,
- tone: EmailTone
- ) async throws -> String {
- let trimmed = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else {
- throw OpenAIServiceError.apiError("Describe what the email should say.")
- }
- var userPrompt = "Email type: \(emailType.title)\nTone: \(tone.title)\n"
- let trimmedSubject = subject.trimmingCharacters(in: .whitespacesAndNewlines)
- if !trimmedSubject.isEmpty {
- userPrompt += "Subject: \(trimmedSubject)\n"
- }
- userPrompt += "\nContent instructions:\n\(trimmed)"
- return try await openAI.completeText(
- systemPrompt: """
- You are a professional email writer. Write a complete, ready-to-send email based on the \
- user's instructions. Include a subject line only if one was not already provided. \
- Return only the email text with no preamble or explanation.
- """,
- userPrompt: userPrompt
- )
- }
- }
|