TitleOptimizationService.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import Foundation
  2. protocol TitleOptimizationServiceProtocol: Sendable {
  3. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult
  4. }
  5. enum TitleOptimizationServiceFactory {
  6. static func makeDefault() -> any TitleOptimizationServiceProtocol {
  7. if let apiKey = AIConfiguration.apiKey {
  8. return OpenAITitleOptimizationService(apiKey: apiKey)
  9. }
  10. return MockTitleOptimizationService()
  11. }
  12. }
  13. enum TitleOptimizationError: LocalizedError {
  14. case emptyTopic
  15. case emptySubreddit
  16. case emptyTitle
  17. case apiUnavailable(String)
  18. case invalidResponse
  19. var errorDescription: String? {
  20. switch self {
  21. case .emptyTopic: "Enter a topic or keywords to guide title generation."
  22. case .emptySubreddit: "Enter a subreddit to tailor titles for that community."
  23. case .emptyTitle: "Enter a title to optimize, or provide a topic to generate from scratch."
  24. case .apiUnavailable(let message): message
  25. case .invalidResponse: "The AI returned an unexpected response. Please try again."
  26. }
  27. }
  28. }
  29. // MARK: - OpenAI
  30. struct OpenAITitleOptimizationService: TitleOptimizationServiceProtocol {
  31. let apiKey: String
  32. var model: String = "gpt-4o-mini"
  33. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  34. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  35. throw TitleOptimizationError.emptySubreddit
  36. }
  37. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  38. throw TitleOptimizationError.emptyTopic
  39. }
  40. guard !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty else {
  41. throw TitleOptimizationError.emptyTitle
  42. }
  43. let subreddit = PostDraftValidator.normalizedSubreddit(draft.subreddit)
  44. let prompt = buildPrompt(draft: draft, subreddit: subreddit)
  45. var request = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!)
  46. request.httpMethod = "POST"
  47. request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
  48. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  49. let body: [String: Any] = [
  50. "model": model,
  51. "temperature": 0.85,
  52. "response_format": ["type": "json_object"],
  53. "messages": [
  54. [
  55. "role": "system",
  56. "content": """
  57. You optimize Reddit post titles. Respond with JSON only using keys:
  58. analysis (object with overallScore, lengthScore, engagementScore, clarityScore as integers 0-100, \
  59. and suggestions as string array),
  60. variants (array of exactly \(draft.variantCount.rawValue) objects with title, score 0-100, reasoning strings).
  61. Titles must be under 300 characters. Match subreddit culture and the requested goal/tone.
  62. """,
  63. ],
  64. ["role": "user", "content": prompt],
  65. ],
  66. ]
  67. request.httpBody = try JSONSerialization.data(withJSONObject: body)
  68. let (data, response) = try await URLSession.shared.data(for: request)
  69. guard let http = response as? HTTPURLResponse else {
  70. throw TitleOptimizationError.apiUnavailable("Couldn't reach the AI service.")
  71. }
  72. if http.statusCode == 401 {
  73. throw TitleOptimizationError.apiUnavailable("Invalid OpenAI API key.")
  74. }
  75. guard (200 ... 299).contains(http.statusCode) else {
  76. let message = String(data: data, encoding: .utf8) ?? "HTTP \(http.statusCode)"
  77. throw TitleOptimizationError.apiUnavailable("AI request failed: \(message)")
  78. }
  79. return try parseResponse(data)
  80. }
  81. private func buildPrompt(draft: TitleDraft, subreddit: String) -> String {
  82. var lines = [
  83. "Subreddit: r/\(subreddit)",
  84. "Topic: \(draft.topic.trimmingCharacters(in: .whitespaces))",
  85. "Original title: \(draft.originalTitle.trimmingCharacters(in: .whitespaces))",
  86. "Goal: \(draft.titleGoal.title) — \(draft.titleGoal.subtitle)",
  87. "Tone: \(draft.tone.title)",
  88. "Post type: \(draft.postType.title)",
  89. ]
  90. if draft.isNSFW { lines.append("Tag: NSFW") }
  91. if draft.isSpoiler { lines.append("Tag: Spoiler") }
  92. if draft.isOC { lines.append("Tag: Original Content") }
  93. if !draft.flair.isEmpty { lines.append("Flair: \(draft.flair)") }
  94. return lines.joined(separator: "\n")
  95. }
  96. private func parseResponse(_ data: Data) throws -> TitleOptimizationResult {
  97. struct APIEnvelope: Decodable {
  98. struct Choice: Decodable {
  99. struct Message: Decodable {
  100. let content: String
  101. }
  102. let message: Message
  103. }
  104. let choices: [Choice]
  105. }
  106. struct AnalysisPayload: Decodable {
  107. let overallScore: Int
  108. let lengthScore: Int
  109. let engagementScore: Int
  110. let clarityScore: Int
  111. let suggestions: [String]
  112. }
  113. struct VariantPayload: Decodable {
  114. let title: String
  115. let score: Int
  116. let reasoning: String
  117. }
  118. struct Payload: Decodable {
  119. let analysis: AnalysisPayload
  120. let variants: [VariantPayload]
  121. }
  122. let envelope = try JSONDecoder().decode(APIEnvelope.self, from: data)
  123. guard let content = envelope.choices.first?.message.content.data(using: .utf8) else {
  124. throw TitleOptimizationError.invalidResponse
  125. }
  126. let payload = try JSONDecoder().decode(Payload.self, from: content)
  127. guard !payload.variants.isEmpty else {
  128. throw TitleOptimizationError.invalidResponse
  129. }
  130. let analysis = TitleAnalysis(
  131. overallScore: clampScore(payload.analysis.overallScore),
  132. lengthScore: clampScore(payload.analysis.lengthScore),
  133. engagementScore: clampScore(payload.analysis.engagementScore),
  134. clarityScore: clampScore(payload.analysis.clarityScore),
  135. suggestions: payload.analysis.suggestions
  136. )
  137. let variants = payload.variants.map {
  138. TitleVariant(
  139. title: String($0.title.prefix(PostDraftValidator.maxTitleLength)),
  140. score: clampScore($0.score),
  141. reasoning: $0.reasoning
  142. )
  143. }
  144. return TitleOptimizationResult(analysis: analysis, variants: variants)
  145. }
  146. private func clampScore(_ value: Int) -> Int {
  147. min(100, max(0, value))
  148. }
  149. }
  150. struct MockTitleOptimizationService: TitleOptimizationServiceProtocol {
  151. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  152. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  153. throw TitleOptimizationError.emptySubreddit
  154. }
  155. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  156. throw TitleOptimizationError.emptyTopic
  157. }
  158. let hasTitle = !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty
  159. if !hasTitle {
  160. throw TitleOptimizationError.emptyTitle
  161. }
  162. try await Task.sleep(for: .milliseconds(900))
  163. let subreddit = draft.subreddit.replacingOccurrences(of: "r/", with: "")
  164. let topic = draft.topic.trimmingCharacters(in: .whitespaces)
  165. let original = draft.originalTitle.trimmingCharacters(in: .whitespaces)
  166. let analysis = analyzeTitle(original, goal: draft.titleGoal)
  167. let variants = makeVariants(
  168. original: original,
  169. topic: topic,
  170. subreddit: subreddit,
  171. tone: draft.tone,
  172. goal: draft.titleGoal,
  173. count: draft.variantCount.rawValue
  174. )
  175. return TitleOptimizationResult(analysis: analysis, variants: variants)
  176. }
  177. private func analyzeTitle(_ title: String, goal: TitleGoal) -> TitleAnalysis {
  178. let length = title.count
  179. let lengthScore = scoreLength(length)
  180. let engagementScore = scoreEngagement(title, goal: goal)
  181. let clarityScore = scoreClarity(title)
  182. let overall = (lengthScore + engagementScore + clarityScore) / 3
  183. let suggestions = makeSuggestions(title: title, length: length, goal: goal)
  184. return TitleAnalysis(
  185. overallScore: overall,
  186. lengthScore: lengthScore,
  187. engagementScore: engagementScore,
  188. clarityScore: clarityScore,
  189. suggestions: suggestions
  190. )
  191. }
  192. private func scoreLength(_ length: Int) -> Int {
  193. switch length {
  194. case 0: 0
  195. case 1...50: 95
  196. case 51...80: 85
  197. case 81...120: 70
  198. case 121...200: 50
  199. case 201...300: 30
  200. default: 10
  201. }
  202. }
  203. private func scoreEngagement(_ title: String, goal: TitleGoal) -> Int {
  204. var score = 50
  205. let lower = title.lowercased()
  206. if title.contains("?") { score += 10 }
  207. if title.range(of: #"\d+"#, options: .regularExpression) != nil { score += 8 }
  208. if lower.contains("how") || lower.contains("why") || lower.contains("what") { score += 6 }
  209. if lower.contains("you") || lower.contains("your") { score += 5 }
  210. if title == title.uppercased() && title.count > 5 { score -= 15 }
  211. switch goal {
  212. case .question where !title.contains("?"): score -= 10
  213. case .listicle where title.range(of: #"\d+"#, options: .regularExpression) == nil: score -= 8
  214. case .curiosity where !lower.contains("secret") && !lower.contains("nobody") && !lower.contains("actually"): score -= 3
  215. default: break
  216. }
  217. return min(100, max(0, score))
  218. }
  219. private func scoreClarity(_ title: String) -> Int {
  220. var score = 70
  221. let words = title.split(separator: " ").count
  222. if words >= 4 && words <= 12 { score += 15 }
  223. if words < 3 { score -= 20 }
  224. if words > 20 { score -= 15 }
  225. if title.contains(" ") { score -= 5 }
  226. if title.hasPrefix(" ") || title.hasSuffix(" ") { score -= 10 }
  227. return min(100, max(0, score))
  228. }
  229. private func makeSuggestions(title: String, length: Int, goal: TitleGoal) -> [String] {
  230. var tips: [String] = []
  231. if length > 120 {
  232. tips.append("Shorten to under 80 characters for better mobile visibility.")
  233. } else if length < 20 {
  234. tips.append("Add more context — very short titles can feel vague in feeds.")
  235. }
  236. if !title.contains("?") && goal == .question {
  237. tips.append("Reframe as a question to invite comments.")
  238. }
  239. if title.range(of: #"\d+"#, options: .regularExpression) == nil && goal == .listicle {
  240. tips.append("Include a number (e.g. \"5 tips\") for listicle-style engagement.")
  241. }
  242. let lower = title.lowercased()
  243. if goal == .curiosity && !lower.contains("?") {
  244. tips.append("Add a curiosity hook — hint at a surprising outcome.")
  245. }
  246. if tips.isEmpty {
  247. tips.append("Strong base title — try variants with different hooks below.")
  248. }
  249. return tips
  250. }
  251. private func makeVariants(
  252. original: String,
  253. topic: String,
  254. subreddit: String,
  255. tone: PostTone,
  256. goal: TitleGoal,
  257. count: Int
  258. ) -> [TitleVariant] {
  259. let templates = variantTemplates(
  260. original: original,
  261. topic: topic,
  262. subreddit: subreddit,
  263. tone: tone,
  264. goal: goal
  265. )
  266. return Array(templates.prefix(count)).enumerated().map { index, template in
  267. TitleVariant(
  268. title: template.title,
  269. score: template.score - index * 2,
  270. reasoning: template.reasoning
  271. )
  272. }
  273. }
  274. private func variantTemplates(
  275. original: String,
  276. topic: String,
  277. subreddit: String,
  278. tone: PostTone,
  279. goal: TitleGoal
  280. ) -> [(title: String, score: Int, reasoning: String)] {
  281. let base = original.isEmpty ? topic : original
  282. var results: [(title: String, score: Int, reasoning: String)] = []
  283. switch goal {
  284. case .curiosity:
  285. results = [
  286. ("The \(topic) trick nobody on r/\(subreddit) talks about", 92, "Curiosity gap with community reference"),
  287. ("I tried \(base) for 30 days — here's what actually happened", 89, "Personal experiment hook"),
  288. ("Why \(topic) is quietly changing everything (and most people miss it)", 87, "Insider knowledge angle"),
  289. ("\(base) — am I the only one who noticed this?", 84, "Relatability + intrigue"),
  290. ("What r/\(subreddit) taught me about \(topic) that I wish I knew sooner", 82, "Community wisdom framing"),
  291. ("The uncomfortable truth about \(topic)", 80, "Bold curiosity opener"),
  292. ("\(base): a deep dive you didn't know you needed", 78, "Value promise"),
  293. ("This \(topic) approach changed my mind completely", 76, "Transformation narrative"),
  294. ]
  295. case .question:
  296. results = [
  297. ("What's your experience with \(topic)?", 91, "Direct community question"),
  298. ("Am I wrong about \(base)?", 88, "Invites debate and replies"),
  299. ("How do you approach \(topic) on r/\(subreddit)?", 86, "Subreddit-specific ask"),
  300. ("Is \(topic) actually worth it in 2026?", 84, "Timely relevance question"),
  301. ("Anyone else struggling with \(base)?", 82, "Shared struggle hook"),
  302. ("What's the best \(topic) advice you've ever received?", 80, "Experience-sharing prompt"),
  303. ("\(base) — what am I missing here?", 78, "Humble knowledge seeker"),
  304. ("Hot take or common knowledge: \(topic)?", 76, "Opinion solicitation"),
  305. ]
  306. case .listicle:
  307. results = [
  308. ("7 \(topic) tips that actually work on r/\(subreddit)", 93, "Numbered list with community anchor"),
  309. ("5 mistakes everyone makes with \(base)", 90, "Problem-awareness listicle"),
  310. ("3 reasons \(topic) is underrated right now", 87, "Concise numbered hook"),
  311. ("10 things I learned about \(topic) the hard way", 85, "Lessons-learned format"),
  312. ("The top 5 \(topic) resources you need in 2026", 83, "Resource roundup angle"),
  313. ("\(base): 4 key takeaways from my experience", 81, "Summary-style list"),
  314. ("6 signs you're ready for \(topic)", 79, "Checklist engagement"),
  315. ("8 \(topic) hacks r/\(subreddit) swears by", 77, "Community-endorsed list"),
  316. ]
  317. case .emotional:
  318. results = [
  319. ("\(base) hit me harder than I expected", 91, "Emotional vulnerability"),
  320. ("I wasn't ready for what \(topic) taught me", 88, "Personal revelation"),
  321. ("This \(topic) moment changed everything for me", 86, "Transformation story"),
  322. ("Honestly, \(base) has been on my mind lately", 84, "Authentic confession"),
  323. ("The \(topic) journey nobody prepares you for", 82, "Empathy-driven framing"),
  324. ("Why \(base) still keeps me up at night", 80, "Emotional intensity"),
  325. ("\(topic) — a love letter to r/\(subreddit)", 78, "Community appreciation"),
  326. ("I finally understand \(base) and it's bittersweet", 76, "Reflective tone"),
  327. ]
  328. case .direct:
  329. results = [
  330. ("\(base) — a complete guide for r/\(subreddit)", 92, "Clear value proposition"),
  331. ("Everything you need to know about \(topic)", 89, "Comprehensive promise"),
  332. ("\(topic): what works, what doesn't, and why", 87, "Balanced direct framing"),
  333. ("My honest take on \(base)", 85, "Straightforward opinion"),
  334. ("\(topic) explained simply", 83, "Accessibility focus"),
  335. ("The definitive \(base) breakdown", 81, "Authority positioning"),
  336. ("\(topic) for beginners — start here", 79, "Audience targeting"),
  337. ("\(base): facts, not hype", 77, "No-nonsense angle"),
  338. ]
  339. case .provocative:
  340. results = [
  341. ("Unpopular opinion: \(base) is overrated", 93, "Classic debate starter"),
  342. ("\(topic) is a scam and here's why", 90, "Strong contrarian hook"),
  343. ("Hot take: r/\(subreddit) is wrong about \(topic)", 87, "Community challenge"),
  344. ("Stop doing \(base) — seriously", 85, "Command attention"),
  345. ("\(topic) culture has gone too far", 83, "Cultural critique"),
  346. ("I'll say it: \(base) isn't that impressive", 81, "Mild controversy"),
  347. ("Why everyone is sleeping on the real \(topic) issue", 79, "Contrarian insight"),
  348. ("\(base) — fight me", 77, "Maximum engagement bait"),
  349. ]
  350. }
  351. if tone == .humorous {
  352. results = results.map { variant in
  353. (title: variant.title + " 😅", score: variant.score - 3, reasoning: variant.reasoning + " (humorous tone)")
  354. }
  355. } else if tone == .professional {
  356. results = results.map { variant in
  357. (title: "[Analysis] " + variant.title, score: variant.score - 2, reasoning: variant.reasoning + " (professional tone)")
  358. }
  359. }
  360. return results.sorted { $0.score > $1.score }
  361. }
  362. }