molten-herald 0.1.0

Automated viral tweet generation and scheduling for developer releases ๐Ÿ“ข
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Tweet generation using LLMs

use crate::config::{LlmConfig, TweetDefaults};
use crate::error::{HeraldError, Result};
use crate::events::Event;
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

/// Generated tweet with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratedTweet {
    /// The tweet content
    pub content: String,

    /// Character count
    pub length: usize,

    /// Alternative versions
    #[serde(default)]
    pub alternatives: Vec<String>,

    /// Suggested hashtags (not included in content)
    #[serde(default)]
    pub suggested_hashtags: Vec<String>,

    /// Source event
    pub event_id: String,

    /// Generation timestamp
    pub generated_at: chrono::DateTime<chrono::Utc>,
}

impl GeneratedTweet {
    /// Check if tweet is within length limit
    pub fn is_valid_length(&self, max: usize) -> bool {
        self.length <= max
    }
}

/// Tweet generator using LLM
pub struct TweetGenerator {
    config: LlmConfig,
    defaults: TweetDefaults,
    client: reqwest::Client,
}

impl TweetGenerator {
    /// Create a new generator
    pub fn new(config: LlmConfig, defaults: TweetDefaults) -> Self {
        Self {
            config,
            defaults,
            client: reqwest::Client::new(),
        }
    }

    /// Generate a tweet for an event
    pub async fn generate(&self, event: &Event) -> Result<GeneratedTweet> {
        let prompt = self.build_prompt(event);
        debug!("Generating tweet with prompt: {}", prompt);

        let content = match self.config.provider.as_str() {
            "anthropic" => self.generate_anthropic(&prompt).await?,
            "openai" => self.generate_openai(&prompt).await?,
            "ollama" => self.generate_ollama(&prompt).await?,
            _ => return Err(HeraldError::Config(format!(
                "Unknown LLM provider: {}",
                self.config.provider
            ))),
        };

        let tweet = self.parse_response(&content, &event.id)?;
        info!("Generated tweet: {} chars", tweet.length);

        Ok(tweet)
    }

    /// Generate multiple variations
    pub async fn generate_variations(&self, event: &Event, count: usize) -> Result<Vec<GeneratedTweet>> {
        let mut tweets = Vec::new();
        
        for i in 0..count {
            let mut modified_event = event.clone();
            modified_event.context.tags.push(format!("variation_{}", i));
            
            if let Ok(tweet) = self.generate(&modified_event).await {
                tweets.push(tweet);
            }
        }

        Ok(tweets)
    }

    /// Build the prompt for tweet generation
    fn build_prompt(&self, event: &Event) -> String {
        let tone_instruction = match self.defaults.tone.as_str() {
            "casual" => "Write in a casual, developer-friendly tone. Be conversational and relatable.",
            "professional" => "Write in a professional but approachable tone. Be informative and credible.",
            "hype" => "Write with excitement and energy! Use impactful words. Build anticipation.",
            "technical" => "Write with technical precision. Focus on the technical merits and details.",
            _ => "Write in a casual, engaging tone.",
        };

        let emoji_instruction = if self.defaults.emojis {
            "Include 1-3 relevant emojis strategically placed."
        } else {
            "Do not use emojis."
        };

        let hashtag_instruction = if self.defaults.hashtags {
            "Include 1-2 relevant hashtags at the end."
        } else {
            "Do not include hashtags in the tweet."
        };

        let link_note = if self.defaults.include_link {
            if let Some(ref url) = event.url {
                format!("\n\nInclude this link at the end: {}", url)
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        let highlights = if !event.context.highlights.is_empty() {
            format!("\n\nKey highlights to mention:\n{}", 
                event.context.highlights.iter()
                    .map(|h| format!("- {}", h))
                    .collect::<Vec<_>>()
                    .join("\n"))
        } else {
            String::new()
        };

        format!(r#"Generate a viral tweet announcing the following:

Project: {}
Event: {:?}
Title: {}
{}
{}
{}

Requirements:
1. Maximum {} characters (including any links)
2. {}
3. {}
4. {}
5. Make it shareable and engaging
6. Focus on the value/benefit to developers
7. Avoid corporate jargon
8. Be authentic and direct

Output ONLY the tweet text, nothing else."#,
            event.project,
            event.event_type,
            event.title,
            event.description.as_deref().map(|d| format!("Description: {}", d)).unwrap_or_default(),
            highlights,
            link_note,
            self.defaults.max_length,
            tone_instruction,
            emoji_instruction,
            hashtag_instruction,
        )
    }

    /// Generate using Anthropic Claude
    async fn generate_anthropic(&self, prompt: &str) -> Result<String> {
        let url = self.config.base_url.as_deref()
            .unwrap_or("https://api.anthropic.com/v1/messages");

        let body = serde_json::json!({
            "model": self.config.model,
            "max_tokens": self.config.max_tokens,
            "temperature": self.config.temperature,
            "messages": [
                {"role": "user", "content": prompt}
            ]
        });

        let response = self.client
            .post(url)
            .header("x-api-key", &self.config.api_key)
            .header("anthropic-version", "2023-06-01")
            .header("content-type", "application/json")
            .json(&body)
            .send()
            .await?;

        if !response.status().is_success() {
            let error = response.text().await?;
            return Err(HeraldError::Llm(format!("Anthropic API error: {}", error)));
        }

        let data: AnthropicResponse = response.json().await?;
        
        data.content
            .first()
            .map(|c| c.text.clone())
            .ok_or_else(|| HeraldError::Llm("Empty response from Anthropic".to_string()))
    }

    /// Generate using OpenAI
    async fn generate_openai(&self, prompt: &str) -> Result<String> {
        let url = self.config.base_url.as_deref()
            .unwrap_or("https://api.openai.com/v1/chat/completions");

        let body = serde_json::json!({
            "model": self.config.model,
            "max_tokens": self.config.max_tokens,
            "temperature": self.config.temperature,
            "messages": [
                {"role": "user", "content": prompt}
            ]
        });

        let response = self.client
            .post(url)
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?;

        if !response.status().is_success() {
            let error = response.text().await?;
            return Err(HeraldError::Llm(format!("OpenAI API error: {}", error)));
        }

        let data: OpenAIResponse = response.json().await?;
        
        data.choices
            .first()
            .map(|c| c.message.content.clone())
            .ok_or_else(|| HeraldError::Llm("Empty response from OpenAI".to_string()))
    }

    /// Generate using local Ollama
    async fn generate_ollama(&self, prompt: &str) -> Result<String> {
        let url = self.config.base_url.as_deref()
            .unwrap_or("http://localhost:11434/api/generate");

        let body = serde_json::json!({
            "model": self.config.model,
            "prompt": prompt,
            "stream": false,
            "options": {
                "temperature": self.config.temperature
            }
        });

        let response = self.client
            .post(url)
            .json(&body)
            .send()
            .await?;

        if !response.status().is_success() {
            let error = response.text().await?;
            return Err(HeraldError::Llm(format!("Ollama API error: {}", error)));
        }

        let data: OllamaResponse = response.json().await?;
        Ok(data.response)
    }

    /// Parse LLM response into a GeneratedTweet
    fn parse_response(&self, content: &str, event_id: &str) -> Result<GeneratedTweet> {
        let content = content.trim().to_string();
        let length = content.chars().count();

        if length > self.defaults.max_length {
            return Err(HeraldError::TweetTooLong {
                max: self.defaults.max_length,
                actual: length,
            });
        }

        Ok(GeneratedTweet {
            content,
            length,
            alternatives: Vec::new(),
            suggested_hashtags: Vec::new(),
            event_id: event_id.to_string(),
            generated_at: chrono::Utc::now(),
        })
    }
}

/// Anthropic API response
#[derive(Debug, Deserialize)]
struct AnthropicResponse {
    content: Vec<AnthropicContent>,
}

#[derive(Debug, Deserialize)]
struct AnthropicContent {
    text: String,
}

/// OpenAI API response
#[derive(Debug, Deserialize)]
struct OpenAIResponse {
    choices: Vec<OpenAIChoice>,
}

#[derive(Debug, Deserialize)]
struct OpenAIChoice {
    message: OpenAIMessage,
}

#[derive(Debug, Deserialize)]
struct OpenAIMessage {
    content: String,
}

/// Ollama API response
#[derive(Debug, Deserialize)]
struct OllamaResponse {
    response: String,
}

/// Pre-built tweet templates for common scenarios
pub struct TweetTemplates;

impl TweetTemplates {
    /// Template for crate release
    pub fn crate_release(name: &str, version: &str, tagline: &str, url: &str) -> String {
        format!(
            "just shipped {} v{}\n\n{}\n\ncargo add {}\n\n{}",
            name, version, tagline, name, url
        )
    }

    /// Template for GitHub release
    pub fn github_release(name: &str, highlights: &[&str], url: &str) -> String {
        let bullets = highlights.iter()
            .map(|h| format!("โ€ข {}", h))
            .collect::<Vec<_>>()
            .join("\n");
        
        format!(
            "๐Ÿš€ {} is out!\n\n{}\n\n{}",
            name, bullets, url
        )
    }

    /// Template for feature announcement
    pub fn feature(name: &str, feature: &str, benefit: &str) -> String {
        format!(
            "{} now supports {}\n\n{}\n\nmore in thread ๐Ÿงต",
            name, feature, benefit
        )
    }

    /// Template for milestone
    pub fn milestone(name: &str, metric: &str, value: &str) -> String {
        format!(
            "๐ŸŽ‰ {} just hit {} {}\n\nthank you to everyone who's been building with us",
            name, value, metric
        )
    }

    /// Template for open source announcement
    pub fn open_source(name: &str, description: &str, url: &str) -> String {
        format!(
            "just open-sourced {}\n\n{}\n\n{}",
            name, description, url
        )
    }

    /// Thread opener for multiple items
    pub fn thread_opener(topic: &str, count: usize) -> String {
        format!(
            "{}\n\n{} things you need to know ๐Ÿงต๐Ÿ‘‡",
            topic, count
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::EventType;

    #[test]
    fn test_generated_tweet_length() {
        let tweet = GeneratedTweet {
            content: "Hello world!".to_string(),
            length: 12,
            alternatives: Vec::new(),
            suggested_hashtags: Vec::new(),
            event_id: "test".to_string(),
            generated_at: chrono::Utc::now(),
        };

        assert!(tweet.is_valid_length(280));
        assert!(tweet.is_valid_length(12));
        assert!(!tweet.is_valid_length(11));
    }

    #[test]
    fn test_crate_release_template() {
        let tweet = TweetTemplates::crate_release(
            "herald",
            "0.1.0",
            "automated viral tweets for developers",
            "https://crates.io/crates/herald"
        );

        assert!(tweet.contains("herald"));
        assert!(tweet.contains("0.1.0"));
        assert!(tweet.contains("cargo add"));
    }

    #[test]
    fn test_github_release_template() {
        let tweet = TweetTemplates::github_release(
            "Herald v0.1.0",
            &["LLM-powered generation", "Twitter API v2", "Scheduling"],
            "https://github.com/moltenlabs/herald"
        );

        assert!(tweet.contains("๐Ÿš€"));
        assert!(tweet.contains("โ€ข"));
    }

    #[test]
    fn test_open_source_template() {
        let tweet = TweetTemplates::open_source(
            "herald",
            "tweet automation for developers who ship",
            "https://github.com/moltenlabs/herald"
        );

        assert!(tweet.contains("open-sourced"));
        assert!(tweet.len() < 280);
    }

    #[test]
    fn test_prompt_building() {
        use crate::events::{Event, EventContext};
        
        let generator = TweetGenerator::new(
            LlmConfig::default(),
            TweetDefaults::default(),
        );

        let event = Event {
            id: "test".to_string(),
            event_type: EventType::Release,
            project: "herald".to_string(),
            title: "Herald v0.1.0".to_string(),
            description: Some("Tweet automation".to_string()),
            version: Some("0.1.0".to_string()),
            url: Some("https://example.com".to_string()),
            timestamp: chrono::Utc::now(),
            author: None,
            context: EventContext::default(),
        };

        let prompt = generator.build_prompt(&event);
        assert!(prompt.contains("herald"));
        assert!(prompt.contains("Release"));
        assert!(prompt.contains("280"));
    }
}