TitleOptimizationService.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. enum CodingKeys: String, CodingKey {
  113. case overallScore, lengthScore, engagementScore, clarityScore, suggestions
  114. }
  115. init(from decoder: Decoder) throws {
  116. let container = try decoder.container(keyedBy: CodingKeys.self)
  117. overallScore = try container.decodeIfPresent(FlexibleInt.self, forKey: .overallScore)?.value ?? 70
  118. lengthScore = try container.decodeIfPresent(FlexibleInt.self, forKey: .lengthScore)?.value ?? 70
  119. engagementScore = try container.decodeIfPresent(FlexibleInt.self, forKey: .engagementScore)?.value ?? 70
  120. clarityScore = try container.decodeIfPresent(FlexibleInt.self, forKey: .clarityScore)?.value ?? 70
  121. suggestions = try container.decodeIfPresent([String].self, forKey: .suggestions) ?? []
  122. }
  123. }
  124. struct VariantPayload: Decodable {
  125. let title: String
  126. let score: Int
  127. let reasoning: String
  128. enum CodingKeys: String, CodingKey {
  129. case title, score, reasoning
  130. }
  131. init(from decoder: Decoder) throws {
  132. let container = try decoder.container(keyedBy: CodingKeys.self)
  133. title = try container.decode(String.self, forKey: .title)
  134. score = try container.decode(FlexibleInt.self, forKey: .score).value
  135. reasoning = try container.decode(FlexibleStringOrArray.self, forKey: .reasoning).value
  136. }
  137. }
  138. struct Payload: Decodable {
  139. let analysis: AnalysisPayload
  140. let variants: [VariantPayload]
  141. }
  142. let envelope = try JSONDecoder().decode(APIEnvelope.self, from: data)
  143. guard let content = envelope.choices.first?.message.content,
  144. let payloadData = AIJSONDecoding.payloadData(from: content) else {
  145. throw TitleOptimizationError.invalidResponse
  146. }
  147. let payload: Payload
  148. do {
  149. payload = try JSONDecoder().decode(Payload.self, from: payloadData)
  150. } catch {
  151. throw TitleOptimizationError.apiUnavailable("Couldn't parse the AI response. Please try again.")
  152. }
  153. guard !payload.variants.isEmpty else {
  154. throw TitleOptimizationError.invalidResponse
  155. }
  156. let analysis = TitleAnalysis(
  157. overallScore: clampScore(payload.analysis.overallScore),
  158. lengthScore: clampScore(payload.analysis.lengthScore),
  159. engagementScore: clampScore(payload.analysis.engagementScore),
  160. clarityScore: clampScore(payload.analysis.clarityScore),
  161. suggestions: payload.analysis.suggestions
  162. )
  163. let variants = payload.variants.map {
  164. TitleVariant(
  165. title: String($0.title.prefix(PostDraftValidator.maxTitleLength)),
  166. score: clampScore($0.score),
  167. reasoning: $0.reasoning
  168. )
  169. }
  170. return TitleOptimizationResult(analysis: analysis, variants: variants)
  171. }
  172. private func clampScore(_ value: Int) -> Int {
  173. min(100, max(0, value))
  174. }
  175. }
  176. struct MockTitleOptimizationService: TitleOptimizationServiceProtocol {
  177. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  178. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  179. throw TitleOptimizationError.emptySubreddit
  180. }
  181. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  182. throw TitleOptimizationError.emptyTopic
  183. }
  184. let hasTitle = !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty
  185. if !hasTitle {
  186. throw TitleOptimizationError.emptyTitle
  187. }
  188. try await Task.sleep(for: .milliseconds(900))
  189. let subreddit = draft.subreddit.replacingOccurrences(of: "r/", with: "")
  190. let topic = draft.topic.trimmingCharacters(in: .whitespaces)
  191. let original = draft.originalTitle.trimmingCharacters(in: .whitespaces)
  192. let analysis = analyzeTitle(original, goal: draft.titleGoal)
  193. let variants = makeVariants(
  194. original: original,
  195. topic: topic,
  196. subreddit: subreddit,
  197. tone: draft.tone,
  198. goal: draft.titleGoal,
  199. count: draft.variantCount.rawValue
  200. )
  201. return TitleOptimizationResult(analysis: analysis, variants: variants)
  202. }
  203. private func analyzeTitle(_ title: String, goal: TitleGoal) -> TitleAnalysis {
  204. let length = title.count
  205. let lengthScore = scoreLength(length)
  206. let engagementScore = scoreEngagement(title, goal: goal)
  207. let clarityScore = scoreClarity(title)
  208. let overall = (lengthScore + engagementScore + clarityScore) / 3
  209. let suggestions = makeSuggestions(title: title, length: length, goal: goal)
  210. return TitleAnalysis(
  211. overallScore: overall,
  212. lengthScore: lengthScore,
  213. engagementScore: engagementScore,
  214. clarityScore: clarityScore,
  215. suggestions: suggestions
  216. )
  217. }
  218. private func scoreLength(_ length: Int) -> Int {
  219. switch length {
  220. case 0: 0
  221. case 1...50: 95
  222. case 51...80: 85
  223. case 81...120: 70
  224. case 121...200: 50
  225. case 201...300: 30
  226. default: 10
  227. }
  228. }
  229. private func scoreEngagement(_ title: String, goal: TitleGoal) -> Int {
  230. var score = 50
  231. let lower = title.lowercased()
  232. if title.contains("?") { score += 10 }
  233. if title.range(of: #"\d+"#, options: .regularExpression) != nil { score += 8 }
  234. if lower.contains("how") || lower.contains("why") || lower.contains("what") { score += 6 }
  235. if lower.contains("you") || lower.contains("your") { score += 5 }
  236. if title == title.uppercased() && title.count > 5 { score -= 15 }
  237. switch goal {
  238. case .question where !title.contains("?"): score -= 10
  239. case .listicle where title.range(of: #"\d+"#, options: .regularExpression) == nil: score -= 8
  240. case .curiosity where !lower.contains("secret") && !lower.contains("nobody") && !lower.contains("actually"): score -= 3
  241. default: break
  242. }
  243. return min(100, max(0, score))
  244. }
  245. private func scoreClarity(_ title: String) -> Int {
  246. var score = 70
  247. let words = title.split(separator: " ").count
  248. if words >= 4 && words <= 12 { score += 15 }
  249. if words < 3 { score -= 20 }
  250. if words > 20 { score -= 15 }
  251. if title.contains(" ") { score -= 5 }
  252. if title.hasPrefix(" ") || title.hasSuffix(" ") { score -= 10 }
  253. return min(100, max(0, score))
  254. }
  255. private func makeSuggestions(title: String, length: Int, goal: TitleGoal) -> [String] {
  256. var tips: [String] = []
  257. if length > 120 {
  258. tips.append("Shorten to under 80 characters for better mobile visibility.")
  259. } else if length < 20 {
  260. tips.append("Add more context — very short titles can feel vague in feeds.")
  261. }
  262. if !title.contains("?") && goal == .question {
  263. tips.append("Reframe as a question to invite comments.")
  264. }
  265. if title.range(of: #"\d+"#, options: .regularExpression) == nil && goal == .listicle {
  266. tips.append("Include a number (e.g. \"5 tips\") for listicle-style engagement.")
  267. }
  268. let lower = title.lowercased()
  269. if goal == .curiosity && !lower.contains("?") {
  270. tips.append("Add a curiosity hook — hint at a surprising outcome.")
  271. }
  272. if tips.isEmpty {
  273. tips.append("Strong base title — try variants with different hooks below.")
  274. }
  275. return tips
  276. }
  277. private func makeVariants(
  278. original: String,
  279. topic: String,
  280. subreddit: String,
  281. tone: PostTone,
  282. goal: TitleGoal,
  283. count: Int
  284. ) -> [TitleVariant] {
  285. let templates = variantTemplates(
  286. original: original,
  287. topic: topic,
  288. subreddit: subreddit,
  289. tone: tone,
  290. goal: goal
  291. )
  292. return Array(templates.prefix(count)).enumerated().map { index, template in
  293. TitleVariant(
  294. title: template.title,
  295. score: template.score - index * 2,
  296. reasoning: template.reasoning
  297. )
  298. }
  299. }
  300. private func variantTemplates(
  301. original: String,
  302. topic: String,
  303. subreddit: String,
  304. tone: PostTone,
  305. goal: TitleGoal
  306. ) -> [(title: String, score: Int, reasoning: String)] {
  307. let base = original.isEmpty ? topic : original
  308. var results: [(title: String, score: Int, reasoning: String)] = []
  309. switch goal {
  310. case .curiosity:
  311. results = [
  312. ("The \(topic) trick nobody on r/\(subreddit) talks about", 92, "Curiosity gap with community reference"),
  313. ("I tried \(base) for 30 days — here's what actually happened", 89, "Personal experiment hook"),
  314. ("Why \(topic) is quietly changing everything (and most people miss it)", 87, "Insider knowledge angle"),
  315. ("\(base) — am I the only one who noticed this?", 84, "Relatability + intrigue"),
  316. ("What r/\(subreddit) taught me about \(topic) that I wish I knew sooner", 82, "Community wisdom framing"),
  317. ("The uncomfortable truth about \(topic)", 80, "Bold curiosity opener"),
  318. ("\(base): a deep dive you didn't know you needed", 78, "Value promise"),
  319. ("This \(topic) approach changed my mind completely", 76, "Transformation narrative"),
  320. ]
  321. case .question:
  322. results = [
  323. ("What's your experience with \(topic)?", 91, "Direct community question"),
  324. ("Am I wrong about \(base)?", 88, "Invites debate and replies"),
  325. ("How do you approach \(topic) on r/\(subreddit)?", 86, "Subreddit-specific ask"),
  326. ("Is \(topic) actually worth it in 2026?", 84, "Timely relevance question"),
  327. ("Anyone else struggling with \(base)?", 82, "Shared struggle hook"),
  328. ("What's the best \(topic) advice you've ever received?", 80, "Experience-sharing prompt"),
  329. ("\(base) — what am I missing here?", 78, "Humble knowledge seeker"),
  330. ("Hot take or common knowledge: \(topic)?", 76, "Opinion solicitation"),
  331. ]
  332. case .listicle:
  333. results = [
  334. ("7 \(topic) tips that actually work on r/\(subreddit)", 93, "Numbered list with community anchor"),
  335. ("5 mistakes everyone makes with \(base)", 90, "Problem-awareness listicle"),
  336. ("3 reasons \(topic) is underrated right now", 87, "Concise numbered hook"),
  337. ("10 things I learned about \(topic) the hard way", 85, "Lessons-learned format"),
  338. ("The top 5 \(topic) resources you need in 2026", 83, "Resource roundup angle"),
  339. ("\(base): 4 key takeaways from my experience", 81, "Summary-style list"),
  340. ("6 signs you're ready for \(topic)", 79, "Checklist engagement"),
  341. ("8 \(topic) hacks r/\(subreddit) swears by", 77, "Community-endorsed list"),
  342. ]
  343. case .emotional:
  344. results = [
  345. ("\(base) hit me harder than I expected", 91, "Emotional vulnerability"),
  346. ("I wasn't ready for what \(topic) taught me", 88, "Personal revelation"),
  347. ("This \(topic) moment changed everything for me", 86, "Transformation story"),
  348. ("Honestly, \(base) has been on my mind lately", 84, "Authentic confession"),
  349. ("The \(topic) journey nobody prepares you for", 82, "Empathy-driven framing"),
  350. ("Why \(base) still keeps me up at night", 80, "Emotional intensity"),
  351. ("\(topic) — a love letter to r/\(subreddit)", 78, "Community appreciation"),
  352. ("I finally understand \(base) and it's bittersweet", 76, "Reflective tone"),
  353. ]
  354. case .direct:
  355. results = [
  356. ("\(base) — a complete guide for r/\(subreddit)", 92, "Clear value proposition"),
  357. ("Everything you need to know about \(topic)", 89, "Comprehensive promise"),
  358. ("\(topic): what works, what doesn't, and why", 87, "Balanced direct framing"),
  359. ("My honest take on \(base)", 85, "Straightforward opinion"),
  360. ("\(topic) explained simply", 83, "Accessibility focus"),
  361. ("The definitive \(base) breakdown", 81, "Authority positioning"),
  362. ("\(topic) for beginners — start here", 79, "Audience targeting"),
  363. ("\(base): facts, not hype", 77, "No-nonsense angle"),
  364. ]
  365. case .provocative:
  366. results = [
  367. ("Unpopular opinion: \(base) is overrated", 93, "Classic debate starter"),
  368. ("\(topic) is a scam and here's why", 90, "Strong contrarian hook"),
  369. ("Hot take: r/\(subreddit) is wrong about \(topic)", 87, "Community challenge"),
  370. ("Stop doing \(base) — seriously", 85, "Command attention"),
  371. ("\(topic) culture has gone too far", 83, "Cultural critique"),
  372. ("I'll say it: \(base) isn't that impressive", 81, "Mild controversy"),
  373. ("Why everyone is sleeping on the real \(topic) issue", 79, "Contrarian insight"),
  374. ("\(base) — fight me", 77, "Maximum engagement bait"),
  375. ]
  376. }
  377. if tone == .humorous {
  378. results = results.map { variant in
  379. (title: variant.title + " 😅", score: variant.score - 3, reasoning: variant.reasoning + " (humorous tone)")
  380. }
  381. } else if tone == .professional {
  382. results = results.map { variant in
  383. (title: "[Analysis] " + variant.title, score: variant.score - 2, reasoning: variant.reasoning + " (professional tone)")
  384. }
  385. }
  386. return results.sorted { $0.score > $1.score }
  387. }
  388. }