EmailWriterService.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import Foundation
  2. protocol EmailWriterServicing {
  3. func generateEmail(
  4. prompt: String,
  5. subject: String,
  6. emailType: EmailType,
  7. tone: EmailTone
  8. ) async throws -> String
  9. }
  10. struct EmailWriterService: EmailWriterServicing {
  11. private let openAI: OpenAIChatServicing
  12. init(openAI: OpenAIChatServicing = OpenAIChatService()) {
  13. self.openAI = openAI
  14. }
  15. func generateEmail(
  16. prompt: String,
  17. subject: String,
  18. emailType: EmailType,
  19. tone: EmailTone
  20. ) async throws -> String {
  21. let trimmed = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
  22. guard !trimmed.isEmpty else {
  23. throw OpenAIServiceError.apiError("Describe what the email should say.")
  24. }
  25. var userPrompt = "Email type: \(emailType.title)\nTone: \(tone.title)\n"
  26. let trimmedSubject = subject.trimmingCharacters(in: .whitespacesAndNewlines)
  27. if !trimmedSubject.isEmpty {
  28. userPrompt += "Subject: \(trimmedSubject)\n"
  29. }
  30. userPrompt += "\nContent instructions:\n\(trimmed)"
  31. return try await openAI.completeText(
  32. systemPrompt: """
  33. You are a professional email writer. Write a complete, ready-to-send email based on the \
  34. user's instructions. Include a subject line only if one was not already provided. \
  35. Return only the email text with no preamble or explanation.
  36. """,
  37. userPrompt: userPrompt
  38. )
  39. }
  40. }