TitleOptimizationService.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import Foundation
  2. protocol TitleOptimizationServiceProtocol: Sendable {
  3. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult
  4. }
  5. enum TitleOptimizationServiceFactory {
  6. static func make(usesLiveAI: Bool) -> any TitleOptimizationServiceProtocol {
  7. if usesLiveAI, 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):
  25. UserFacingError.sanitized(message) ?? UserFacingError.generic
  26. case .invalidResponse:
  27. UserFacingError.generic
  28. }
  29. }
  30. }
  31. // MARK: - OpenAI
  32. struct OpenAITitleOptimizationService: TitleOptimizationServiceProtocol {
  33. let apiKey: String
  34. var model: String = AIRequestConfiguration.model
  35. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  36. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  37. throw TitleOptimizationError.emptySubreddit
  38. }
  39. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  40. throw TitleOptimizationError.emptyTopic
  41. }
  42. guard !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty else {
  43. throw TitleOptimizationError.emptyTitle
  44. }
  45. let subreddit = PostDraftValidator.normalizedSubreddit(draft.subreddit)
  46. let prompt = buildPrompt(draft: draft, subreddit: subreddit)
  47. var request = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!)
  48. request.httpMethod = "POST"
  49. request.timeoutInterval = AIRequestConfiguration.requestTimeout
  50. request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
  51. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  52. let variantCount = draft.variantCount.rawValue
  53. let body: [String: Any] = [
  54. "model": model,
  55. "temperature": 0.6,
  56. "max_tokens": AIRequestConfiguration.titleOptimizerMaxTokens(variantCount: variantCount),
  57. "response_format": ["type": "json_object"],
  58. "messages": [
  59. [
  60. "role": "system",
  61. "content": """
  62. Optimize Reddit titles. JSON only: {"variants":[{"title":"...","score":85}]}.
  63. Return exactly \(variantCount) variants. Titles under 300 chars. Match subreddit, goal, and tone.
  64. """,
  65. ],
  66. ["role": "user", "content": prompt],
  67. ],
  68. ]
  69. request.httpBody = try JSONSerialization.data(withJSONObject: body)
  70. let data: Data
  71. let response: URLResponse
  72. do {
  73. (data, response) = try await NetworkClient.aiData(for: request)
  74. } catch let error as URLError {
  75. throw TitleOptimizationError.apiUnavailable(UserFacingError.networkMessage(for: error))
  76. }
  77. if let http = response as? HTTPURLResponse, !(200 ... 299).contains(http.statusCode) {
  78. throw TitleOptimizationError.apiUnavailable(
  79. OpenAIHTTPError.userMessage(statusCode: http.statusCode, data: data)
  80. )
  81. }
  82. return try parseResponse(data, draft: draft)
  83. }
  84. private func buildPrompt(draft: TitleDraft, subreddit: String) -> String {
  85. var lines = [
  86. "Subreddit: r/\(subreddit)",
  87. "Topic: \(draft.topic.trimmingCharacters(in: .whitespaces))",
  88. "Original title: \(draft.originalTitle.trimmingCharacters(in: .whitespaces))",
  89. "Goal: \(draft.titleGoal.title) — \(draft.titleGoal.subtitle)",
  90. "Tone: \(draft.tone.title)",
  91. "Post type: \(draft.postType.title)",
  92. ]
  93. if draft.isNSFW { lines.append("Tag: NSFW") }
  94. if draft.isSpoiler { lines.append("Tag: Spoiler") }
  95. if draft.isOC { lines.append("Tag: Original Content") }
  96. if !draft.flair.isEmpty { lines.append("Flair: \(draft.flair)") }
  97. return lines.joined(separator: "\n")
  98. }
  99. private func parseResponse(_ data: Data, draft: TitleDraft) throws -> TitleOptimizationResult {
  100. struct APIEnvelope: Decodable {
  101. struct Choice: Decodable {
  102. struct Message: Decodable {
  103. let content: String
  104. }
  105. let message: Message
  106. }
  107. let choices: [Choice]
  108. }
  109. struct VariantPayload: Decodable {
  110. let title: String
  111. let score: Int
  112. enum CodingKeys: String, CodingKey {
  113. case title, score
  114. }
  115. init(from decoder: Decoder) throws {
  116. let container = try decoder.container(keyedBy: CodingKeys.self)
  117. title = try container.decode(String.self, forKey: .title)
  118. score = try container.decode(FlexibleInt.self, forKey: .score).value
  119. }
  120. }
  121. struct Payload: Decodable {
  122. let variants: [VariantPayload]
  123. }
  124. let envelope = try JSONDecoder().decode(APIEnvelope.self, from: data)
  125. guard let content = envelope.choices.first?.message.content,
  126. let payloadData = AIJSONDecoding.payloadData(from: content) else {
  127. throw TitleOptimizationError.invalidResponse
  128. }
  129. let payload: Payload
  130. do {
  131. payload = try JSONDecoder().decode(Payload.self, from: payloadData)
  132. } catch {
  133. throw TitleOptimizationError.invalidResponse
  134. }
  135. guard !payload.variants.isEmpty else {
  136. throw TitleOptimizationError.invalidResponse
  137. }
  138. let original = draft.originalTitle.trimmingCharacters(in: .whitespaces)
  139. let analysis = TitleAnalysisEngine.analyze(title: original, goal: draft.titleGoal)
  140. let defaultReasoning = "\(draft.titleGoal.title) hook"
  141. let variants = payload.variants.map {
  142. TitleVariant(
  143. title: String($0.title.prefix(PostDraftValidator.maxTitleLength)),
  144. score: clampScore($0.score),
  145. reasoning: defaultReasoning
  146. )
  147. }
  148. return TitleOptimizationResult(analysis: analysis, variants: variants)
  149. }
  150. private func clampScore(_ value: Int) -> Int {
  151. min(100, max(0, value))
  152. }
  153. }
  154. struct MockTitleOptimizationService: TitleOptimizationServiceProtocol {
  155. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  156. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  157. throw TitleOptimizationError.emptySubreddit
  158. }
  159. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  160. throw TitleOptimizationError.emptyTopic
  161. }
  162. let hasTitle = !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty
  163. if !hasTitle {
  164. throw TitleOptimizationError.emptyTitle
  165. }
  166. let subreddit = draft.subreddit.replacingOccurrences(of: "r/", with: "")
  167. let topic = draft.topic.trimmingCharacters(in: .whitespaces)
  168. let original = draft.originalTitle.trimmingCharacters(in: .whitespaces)
  169. let analysis = TitleAnalysisEngine.analyze(title: original, goal: draft.titleGoal)
  170. let variants = makeVariants(
  171. original: original,
  172. topic: topic,
  173. subreddit: subreddit,
  174. tone: draft.tone,
  175. goal: draft.titleGoal,
  176. count: draft.variantCount.rawValue
  177. )
  178. return TitleOptimizationResult(analysis: analysis, variants: variants)
  179. }
  180. private func makeVariants(
  181. original: String,
  182. topic: String,
  183. subreddit: String,
  184. tone: PostTone,
  185. goal: TitleGoal,
  186. count: Int
  187. ) -> [TitleVariant] {
  188. let templates = variantTemplates(
  189. original: original,
  190. topic: topic,
  191. subreddit: subreddit,
  192. tone: tone,
  193. goal: goal
  194. )
  195. return Array(templates.prefix(count)).enumerated().map { index, template in
  196. TitleVariant(
  197. title: template.title,
  198. score: template.score - index * 2,
  199. reasoning: template.reasoning
  200. )
  201. }
  202. }
  203. private func variantTemplates(
  204. original: String,
  205. topic: String,
  206. subreddit: String,
  207. tone: PostTone,
  208. goal: TitleGoal
  209. ) -> [(title: String, score: Int, reasoning: String)] {
  210. let base = original.isEmpty ? topic : original
  211. var results: [(title: String, score: Int, reasoning: String)] = []
  212. switch goal {
  213. case .curiosity:
  214. results = [
  215. ("The \(topic) trick nobody on r/\(subreddit) talks about", 92, "Curiosity gap with community reference"),
  216. ("I tried \(base) for 30 days — here's what actually happened", 89, "Personal experiment hook"),
  217. ("Why \(topic) is quietly changing everything (and most people miss it)", 87, "Insider knowledge angle"),
  218. ("\(base) — am I the only one who noticed this?", 84, "Relatability + intrigue"),
  219. ("What r/\(subreddit) taught me about \(topic) that I wish I knew sooner", 82, "Community wisdom framing"),
  220. ("The uncomfortable truth about \(topic)", 80, "Bold curiosity opener"),
  221. ("\(base): a deep dive you didn't know you needed", 78, "Value promise"),
  222. ("This \(topic) approach changed my mind completely", 76, "Transformation narrative"),
  223. ]
  224. case .question:
  225. results = [
  226. ("What's your experience with \(topic)?", 91, "Direct community question"),
  227. ("Am I wrong about \(base)?", 88, "Invites debate and replies"),
  228. ("How do you approach \(topic) on r/\(subreddit)?", 86, "Subreddit-specific ask"),
  229. ("Is \(topic) actually worth it in 2026?", 84, "Timely relevance question"),
  230. ("Anyone else struggling with \(base)?", 82, "Shared struggle hook"),
  231. ("What's the best \(topic) advice you've ever received?", 80, "Experience-sharing prompt"),
  232. ("\(base) — what am I missing here?", 78, "Humble knowledge seeker"),
  233. ("Hot take or common knowledge: \(topic)?", 76, "Opinion solicitation"),
  234. ]
  235. case .listicle:
  236. results = [
  237. ("7 \(topic) tips that actually work on r/\(subreddit)", 93, "Numbered list with community anchor"),
  238. ("5 mistakes everyone makes with \(base)", 90, "Problem-awareness listicle"),
  239. ("3 reasons \(topic) is underrated right now", 87, "Concise numbered hook"),
  240. ("10 things I learned about \(topic) the hard way", 85, "Lessons-learned format"),
  241. ("The top 5 \(topic) resources you need in 2026", 83, "Resource roundup angle"),
  242. ("\(base): 4 key takeaways from my experience", 81, "Summary-style list"),
  243. ("6 signs you're ready for \(topic)", 79, "Checklist engagement"),
  244. ("8 \(topic) hacks r/\(subreddit) swears by", 77, "Community-endorsed list"),
  245. ]
  246. case .emotional:
  247. results = [
  248. ("\(base) hit me harder than I expected", 91, "Emotional vulnerability"),
  249. ("I wasn't ready for what \(topic) taught me", 88, "Personal revelation"),
  250. ("This \(topic) moment changed everything for me", 86, "Transformation story"),
  251. ("Honestly, \(base) has been on my mind lately", 84, "Authentic confession"),
  252. ("The \(topic) journey nobody prepares you for", 82, "Empathy-driven framing"),
  253. ("Why \(base) still keeps me up at night", 80, "Emotional intensity"),
  254. ("\(topic) — a love letter to r/\(subreddit)", 78, "Community appreciation"),
  255. ("I finally understand \(base) and it's bittersweet", 76, "Reflective tone"),
  256. ]
  257. case .direct:
  258. results = [
  259. ("\(base) — a complete guide for r/\(subreddit)", 92, "Clear value proposition"),
  260. ("Everything you need to know about \(topic)", 89, "Comprehensive promise"),
  261. ("\(topic): what works, what doesn't, and why", 87, "Balanced direct framing"),
  262. ("My honest take on \(base)", 85, "Straightforward opinion"),
  263. ("\(topic) explained simply", 83, "Accessibility focus"),
  264. ("The definitive \(base) breakdown", 81, "Authority positioning"),
  265. ("\(topic) for beginners — start here", 79, "Audience targeting"),
  266. ("\(base): facts, not hype", 77, "No-nonsense angle"),
  267. ]
  268. case .provocative:
  269. results = [
  270. ("Unpopular opinion: \(base) is overrated", 93, "Classic debate starter"),
  271. ("\(topic) is a scam and here's why", 90, "Strong contrarian hook"),
  272. ("Hot take: r/\(subreddit) is wrong about \(topic)", 87, "Community challenge"),
  273. ("Stop doing \(base) — seriously", 85, "Command attention"),
  274. ("\(topic) culture has gone too far", 83, "Cultural critique"),
  275. ("I'll say it: \(base) isn't that impressive", 81, "Mild controversy"),
  276. ("Why everyone is sleeping on the real \(topic) issue", 79, "Contrarian insight"),
  277. ("\(base) — fight me", 77, "Maximum engagement bait"),
  278. ]
  279. }
  280. if tone == .humorous {
  281. results = results.map { variant in
  282. (title: variant.title + " 😅", score: variant.score - 3, reasoning: variant.reasoning + " (humorous tone)")
  283. }
  284. } else if tone == .professional {
  285. results = results.map { variant in
  286. (title: "[Analysis] " + variant.title, score: variant.score - 2, reasoning: variant.reasoning + " (professional tone)")
  287. }
  288. }
  289. return results.sorted { $0.score > $1.score }
  290. }
  291. }