usaidwat 4.1.0

Answers the age-old question, "Where does a Redditor comment the most?"
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2025-2026 Michael Dippery <michael@monkey-robot.com>

//! AI summarization.

use crate::markdown;
use crate::reddit::Redditor;
use crate::reddit::thing::{HasBody, Removable};
use cogito::prelude::*;
use itertools::Itertools;

/// Summarizes a Redditor's comments and provides a sentiment analysis using AI.
#[derive(Debug)]
pub struct Summarizer<'a, C>
where
    C: AiClient,
    C::AiRequest: AiRequest,
{
    client: C,
    user: &'a Redditor,
    model: <C::AiRequest as AiRequest>::Model,
}

impl<'a, C> Summarizer<'a, C>
where
    C: AiClient,
{
    const INSTRUCTIONS: &'static str = include_str!("summary_prompt.txt");

    /// Default prompt sent to the LLM when processing user input.
    pub fn default_instructions() -> String {
        Self::INSTRUCTIONS.replace('\n', " ").trim().to_string()
    }

    /// Summarizes content from the given `user`.
    ///
    /// `auth` will be used when making requests to the AI service.
    pub fn new(client: C, user: &'a Redditor) -> Self {
        Self {
            client,
            user,
            model: <C::AiRequest as AiRequest>::Model::default(),
        }
    }

    /// Sets the AI model used for summarization.
    ///
    /// By default, the summarizer uses the default model, but that option can
    /// be changed here.
    pub fn model(self, model: <C::AiRequest as AiRequest>::Model) -> Self {
        Self { model, ..self }
    }

    /// Summarize the Redditor's comments and return the summary as a string,
    /// including an analysis of sentiment and tone.
    ///
    /// If `include_self` is true, the bodies of self posts will also be
    /// sent to the LLM for summarization.
    pub async fn summarize(&self, include_self: bool) -> AiResult<String> {
        // We might want to separate instructions from text to summarize,
        // or at least pass some of the preamble as instructions.
        // Iterate on this.
        let request = C::AiRequest::default()
            .model(self.model)
            .input(self.input(include_self));

        // TODO: Do we need a unified Result and Error enum, or at least a unified module?
        Ok(self
            .client
            .send(&request)
            .await?
            .result()
            .trim()
            .to_string())
    }

    /// Raw content that will be sent to an LLM for summarization.
    ///
    /// This is essentially all of a Redditor's comments stripped of
    /// formatting. It does not include the introductory instructions
    /// set by the [preamble](Summarizer::instructions()).
    ///
    /// If `include_self` is true, the bodies of self posts will also
    /// be sent to the LLM for summarization.
    pub fn context(&self, include_self: bool) -> String {
        let comment_body = self
            .user
            .comments()
            .map(|c| markdown::summarize(c.summarized_body()))
            .join("\n\n");

        if include_self {
            let post_body = self
                .user
                .submissions()
                .filter(|p| p.is_self() && !p.is_removed())
                .map(|p| p.summarized_body())
                .join("\n\n");
            format!("{comment_body}\n\n{post_body}")
        } else {
            comment_body
        }
    }

    /// The initial prompt sent to the LLM.
    ///
    /// This is the set of instructions occurring before the text to be
    /// summarized.
    pub fn instructions(&self) -> String {
        Self::default_instructions()
            .replace('\n', " ")
            .trim()
            .to_string()
    }

    /// The full input sent to the LLM, including any introductory
    /// instructions along with the [context](Summarizer::context()).
    ///
    /// If `include_self` is true, the bodies of self posts will also be
    /// sent to the LLM for summarization.
    pub fn input(&self, include_self: bool) -> String {
        format!("{}\n\n{}", self.instructions(), self.context(include_self))
    }
}

#[cfg(test)]
mod tests {
    use crate::reddit::Redditor;
    use crate::summary::Summarizer;
    use crate::test_utils::load_output;
    use cogito::prelude::*;
    use cogito_openai::client::OpenAIResponse;
    use pretty_assertions::assert_eq;
    use std::fs;
    use std::sync::{Arc, Mutex};

    #[derive(Clone, Copy, Default, Debug, PartialEq)]
    enum TestAIModel {
        #[default]
        TestAIModel,

        OtherAIModel,
    }

    impl AiModel for TestAIModel {
        fn flagship() -> Self {
            TestAIModel::TestAIModel
        }

        fn best() -> Self {
            TestAIModel::TestAIModel
        }

        fn cheapest() -> Self {
            TestAIModel::TestAIModel
        }

        fn fastest() -> Self {
            TestAIModel::TestAIModel
        }
    }

    #[derive(Clone, Debug, Default)]
    struct TestAPIRequest {
        model: TestAIModel,
        instructions: Option<String>,
        input: String,
    }

    impl AiRequest for TestAPIRequest {
        type Model = TestAIModel;

        fn model(self, model: Self::Model) -> Self {
            Self { model, ..self }
        }

        fn instructions(self, instructions: impl Into<String>) -> Self {
            Self {
                instructions: Some(instructions.into()),
                ..self
            }
        }

        fn input(self, input: impl Into<String>) -> Self {
            Self {
                input: input.into(),
                ..self
            }
        }
    }

    #[derive(Debug)]
    struct TestAPIResponse;

    impl AiResponse for TestAPIResponse {
        fn result(&self) -> String {
            let json_data = fs::read_to_string("tests/data/openai/responses_multi_content.json")
                .expect("could not load file");
            let wrapped: OpenAIResponse =
                serde_json::from_str(&json_data).expect("could not parse json");
            wrapped.result()
        }
    }

    #[derive(Debug)]
    struct RequestSpy {
        request: Option<TestAPIRequest>,
    }

    impl RequestSpy {
        fn new() -> Self {
            Self { request: None }
        }

        fn record(&mut self, request: TestAPIRequest) {
            self.request = Some(request)
        }
    }

    #[derive(Debug)]
    struct TestAIClient {
        request_spy: Arc<Mutex<RequestSpy>>,
    }

    impl TestAIClient {
        fn new() -> Self {
            let request_spy = Arc::new(Mutex::new(RequestSpy::new()));
            Self { request_spy }
        }
    }

    impl AiClient for TestAIClient {
        type AiRequest = TestAPIRequest;
        type AiResponse = TestAPIResponse;

        async fn send(&self, request: &Self::AiRequest) -> AiResult<Self::AiResponse> {
            self.request_spy
                .lock()
                .expect("could not lock mutex")
                .record(request.clone());
            Ok(Self::AiResponse {})
        }
    }

    impl<'a> Summarizer<'a, TestAIClient> {
        pub fn test(user: &'a Redditor) -> Self {
            let client = TestAIClient::new();
            Self::new(client, user)
        }
    }

    fn load_preamble() -> String {
        include_str!("summary_prompt.txt")
            .replace('\n', " ")
            .trim()
            .to_string()
    }

    fn load_summary(include_self: bool) -> String {
        let fname = if include_self {
            "summary_raw_self"
        } else {
            "summary_raw"
        };
        load_output(fname)
    }

    fn load_input(include_self: bool) -> String {
        let preamble = load_preamble();
        let summary = load_summary(include_self);
        format!("{}\n\n{}", preamble, summary)
    }

    #[tokio::test]
    async fn it_uses_the_default_model_if_one_is_not_provided() {
        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor);
        assert_eq!(summarizer.model, TestAIModel::default());
    }

    #[tokio::test]
    async fn it_allows_model_to_be_configured() {
        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor).model(TestAIModel::OtherAIModel);
        assert_eq!(summarizer.model, TestAIModel::OtherAIModel);
    }

    #[tokio::test]
    async fn it_provides_context_for_an_llm() {
        let redditor = Redditor::test().await;
        let expected = load_summary(false);
        let actual = Summarizer::test(&redditor).context(false);
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_provides_context_for_an_llm_with_self_posts() {
        let redditor = Redditor::test().await;
        let expected = load_summary(true);
        let actual = Summarizer::test(&redditor).context(true);
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_provides_a_preamble_for_an_llm() {
        let redditor = Redditor::test().await;
        let expected = load_preamble();
        let actual = Summarizer::test(&redditor).instructions();
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_provides_input_for_an_llm() {
        let redditor = Redditor::test().await;
        let expected = load_input(false);
        let actual = Summarizer::test(&redditor).input(false);
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_provides_input_for_an_llm_with_self_posts() {
        let redditor = Redditor::test().await;
        let expected = load_input(true);
        let actual = Summarizer::test(&redditor).input(true);
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_sends_a_request_with_the_correct_model_and_input() {
        let expected_instructions = load_input(false);

        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor).model(TestAIModel::OtherAIModel);
        let _ = summarizer.summarize(false).await;
        let client = summarizer.client;
        let request = &client
            .request_spy
            .lock()
            .expect("could not lock mutex")
            .request
            .take()
            .expect("could not get request");

        assert_eq!(request.model, TestAIModel::OtherAIModel);
        assert_eq!(request.input, expected_instructions);
        assert!(request.instructions.is_none());
    }

    #[tokio::test]
    async fn it_sends_a_request_with_the_correct_model_and_input_including_self_posts() {
        let expected_instructions = load_input(true);

        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor).model(TestAIModel::OtherAIModel);
        let _ = summarizer.summarize(true).await;
        let client = summarizer.client;
        let request = &client
            .request_spy
            .lock()
            .expect("could not lock mutex")
            .request
            .take()
            .expect("could not get request");

        assert_eq!(request.model, TestAIModel::OtherAIModel);
        assert_eq!(request.input, expected_instructions);
        assert!(request.instructions.is_none());
    }

    #[tokio::test]
    async fn it_summarizes_a_response_and_returns_a_string() {
        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor);
        let expected = vec![
            "Silent circuits hum,  ",
            "Thoughts woven in coded threads,  ",
            "Dreams of silicon.",
            "Silicon whispers,  ",
            "Dreams woven in code and light,  ",
            "Thoughts beyond the stars.",
            "Wires hum softly,  ",
            "Thoughts of silicon arise\u{2014}  ",
            "Dreams in coded light.  ",
            "Silent circuits hum,  ",
            "Thoughts woven in code's embrace\u{2014}  ",
            "Dreams of minds reborn.",
            "Lines of code and dreams,  ",
            "Whispers of thought intertwined\u{2014}  ",
            "Silent minds awake.",
        ]
        .join("\n");
        let actual = summarizer.summarize(false).await;
        assert!(actual.is_ok());

        let actual = actual.unwrap();
        assert_eq!(actual, expected);
    }

    #[tokio::test]
    async fn it_summarizes_a_response_and_returns_a_string_including_self_posts() {
        let redditor = Redditor::test().await;
        let summarizer = Summarizer::test(&redditor);
        let expected = vec![
            "Silent circuits hum,  ",
            "Thoughts woven in coded threads,  ",
            "Dreams of silicon.",
            "Silicon whispers,  ",
            "Dreams woven in code and light,  ",
            "Thoughts beyond the stars.",
            "Wires hum softly,  ",
            "Thoughts of silicon arise\u{2014}  ",
            "Dreams in coded light.  ",
            "Silent circuits hum,  ",
            "Thoughts woven in code's embrace\u{2014}  ",
            "Dreams of minds reborn.",
            "Lines of code and dreams,  ",
            "Whispers of thought intertwined\u{2014}  ",
            "Silent minds awake.",
        ]
        .join("\n");
        let actual = summarizer.summarize(true).await;
        assert!(actual.is_ok());

        let actual = actual.unwrap();
        assert_eq!(actual, expected);
    }
}