yammer 0.16.0

yammer provides an ollama-compatible client library.
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use rustyline::config::EditMode;
use rustyline::error::ReadlineError;
use rustyline::hint::HistoryHinter;
use rustyline::{Cmd, CompletionType, Config, Editor, EventHandler, KeyEvent};
use utf8path::Path;

use crate::chat::{Chat, ChatLogLine, ChatOptions, ChatSummary};
use crate::cli::{CommandHint, ShellHelper, TabEventHandler};
use crate::types::ChatMessage;
use crate::{Error, Parameters};

/////////////////////////////////////////// ChatsOptions ///////////////////////////////////////////

/// CommandLine options for the `chats` command.
#[derive(Clone, Debug, Eq, PartialEq, arrrg_derive::CommandLine)]
pub struct ChatsOptions {
    /// The host to connect to.
    #[arrrg(optional, "The host to connect to.")]
    pub ollama_host: Option<String>,
    /// The model to use from the ollama library.
    #[arrrg(optional, "The model to use from the ollama library.")]
    pub model: String,
    /// The duration to keep the model in memory for after the call.
    #[arrrg(optional, "Duration to keep the model in memory for after the call.")]
    pub keep_alive: Option<String>,
    /// The parameters to pass to the model.
    #[arrrg(nested)]
    pub param: Parameters,
    /// Number of results to return per section.
    #[arrrg(optional, "Number of results to return per section.")]
    paginate: usize,
    /// Number of messages to replay when continuing a chat.
    #[arrrg(optional, "Number of messages to replay when continuing a chat.")]
    replay: usize,
}

impl Default for ChatsOptions {
    fn default() -> Self {
        Self {
            ollama_host: None,
            // TODO(rescrv): don't hard-code
            model: "gemma2".to_string(),
            keep_alive: None,
            param: Parameters::default(),
            paginate: 10,
            replay: 5,
        }
    }
}

impl From<ChatsOptions> for ChatOptions {
    fn from(options: ChatsOptions) -> Self {
        Self {
            ollama_host: options.ollama_host,
            model: options.model,
            keep_alive: options.keep_alive,
            param: options.param,
        }
    }
}

/////////////////////////////////////////////// Chats //////////////////////////////////////////////

/// The `chats` command.
pub struct Chats {
    options: ChatsOptions,
}

impl Chats {
    /// Create a new `Chats` command.
    pub fn new(options: ChatsOptions) -> Result<Self, Error> {
        Ok(Self { options })
    }

    /// Run the `chats` interactive shell.
    pub async fn shell(self) -> Result<(), Error> {
        let config = Config::builder()
            .auto_add_history(true)
            .edit_mode(EditMode::Vi)
            .completion_type(CompletionType::List)
            .check_cursor_position(true)
            .max_history_size(1_000_000)
            .expect("this should always work")
            .history_ignore_dups(true)
            .expect("this should always work")
            .history_ignore_space(true)
            .build();
        let history = rustyline::history::FileHistory::new();
        let mut rl = Editor::with_history(config, history).expect("this should always work");
        const PROMPT: &str = "> ";
        let commands = vec![
            CommandHint::new("help", "help"),
            CommandHint::new("exit", "exit"),
            CommandHint::new("quit", "quit"),
            CommandHint::new("list", "list"),
            CommandHint::new("archive", "archive"),
            CommandHint::new("unarchive", "unarchive"),
            CommandHint::new("archived", "archived"),
            CommandHint::new("pin", "pin"),
            CommandHint::new("unpin", "unpin"),
            CommandHint::new("pinned", "pinned"),
            CommandHint::new("new", "new"),
            CommandHint::new("chat", "chat"),
            CommandHint::new("editor", "editor"),
        ];
        let h = ShellHelper {
            commands: commands.clone(),
            hinter: HistoryHinter::new(),
            hints: commands.clone(),
        };
        rl.set_helper(Some(h));
        rl.bind_sequence(
            KeyEvent::from('\t'),
            EventHandler::Conditional(Box::new(TabEventHandler)),
        );
        rl.bind_sequence(KeyEvent::ctrl('l'), EventHandler::Simple(Cmd::ClearScreen));
        self.list();
        loop {
            let line = rl.readline(PROMPT);
            let (args, line) = match line {
                Ok(line) => {
                    let args = match shvar::split(&line) {
                        Ok(args) => args,
                        Err(err) => {
                            eprintln!("could not split line: {:?}", err);
                            continue;
                        }
                    };
                    if args.is_empty() {
                        continue;
                    }
                    (args, line)
                }
                Err(ReadlineError::Interrupted) => {
                    continue;
                }
                Err(ReadlineError::Eof) => {
                    break Ok(());
                }
                Err(err) => {
                    eprintln!("could not read line: {}", err);
                    continue;
                }
            };
            match args[0].as_str() {
                "exit" | "quit" | ":wq" | ":q" => {
                    break Ok(());
                }
                "help" => {
                    eprintln!(
                        r#"chats
=====

Commands:

list        Show all chats.
archive     Archive a chat.
unarchive   Unarchive a chat.
archived    Show all archived chats.
pin         Pin a chat.
unpin       Unpin a chat.
pinned      Show all pinned chats.
new         Start a new chat.
chat        Continue a chat.
editor      Start a chat with a system message written in EDITOR.
"#
                    );
                    continue;
                }
                "list" => {
                    self.list();
                }
                "archive" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: archive <chat>");
                        continue;
                    }
                    self.archive(&args[1]);
                }
                "unarchive" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: unarchive <chat>");
                        continue;
                    }
                    self.unarchive(&args[1]);
                }
                "archived" => {
                    if args.len() != 1 {
                        eprintln!("USAGE: archived");
                        continue;
                    }
                    self.archived();
                }
                "pin" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: pin <chat>");
                        continue;
                    }
                    self.pin(&args[1]);
                }
                "unpin" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: unpin <chat>");
                        continue;
                    }
                    self.unpin(&args[1]);
                }
                "pinned" => {
                    if args.len() != 1 {
                        eprintln!("USAGE: pinned");
                        continue;
                    }
                    self.pinned();
                }
                "new" => {
                    self.new_chat(&line, args).await;
                }
                "chat" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: open <chat>");
                        continue;
                    }
                    self.continue_chat(&args[1]).await;
                }
                "editor" => {
                    if args.len() != 1 {
                        eprintln!("USAGE: editor");
                        continue;
                    }
                    self.editor_chat().await;
                }
                "copy" => {
                    if args.len() != 2 {
                        eprintln!("USAGE: copy <chat>");
                        continue;
                    }
                    let from = match super::chat_path(&args[1]) {
                        Ok(path) => path,
                        Err(err) => {
                            eprintln!("could not copy: {err}");
                            continue;
                        }
                    };
                    let chat_id = match crate::chat::chat_id() {
                        Ok(chat_id) => chat_id,
                        Err(err) => {
                            eprintln!("could not generate chat id: {err}");
                            continue;
                        }
                    };
                    let to = match super::chat_path(&chat_id) {
                        Ok(path) => path,
                        Err(err) => {
                            eprintln!("could not copy: {err}");
                            continue;
                        }
                    };
                    std::fs::create_dir_all(to.dirname())?;
                    if let Err(err) = std::fs::copy(from, to) {
                        eprintln!("could not copy: {err}");
                        continue;
                    }
                }
                _ => {
                    eprintln!("unknown command: {}", args[0]);
                    continue;
                }
            };
        }
    }

    fn load(&self) -> Result<Vec<ChatSummary>, Error> {
        let chat_root = super::chat_root()?;
        let dirents = std::fs::read_dir(chat_root.join("chats"))?;
        let mut chats = vec![];
        for dirent in dirents {
            let dirent = dirent?;
            let path = match Path::try_from(dirent.path()) {
                Ok(path) => path,
                Err(err) => {
                    eprintln!("could not convert path: {:?}", err);
                    continue;
                }
            };
            if path.as_str().ends_with(".ndjson") {
                chats.push(path);
            }
        }
        let mut summaries = Vec::with_capacity(chats.len());
        for chat in chats {
            summaries.push(ChatSummary::load(&chat)?);
        }
        Ok(summaries)
    }

    fn display(&self, mut summaries: Vec<ChatSummary>) {
        summaries.sort_by_key(|chat| chat.modified);
        summaries.reverse();
        let mut pinned_first = true;
        for summary in summaries
            .iter()
            .filter(|s| s.tags.contains("pinned"))
            .take(self.options.paginate)
        {
            if pinned_first {
                println!("pinned:");
            }
            pinned_first = false;
            println!("{}", summary);
        }
        let mut first = true;
        for summary in summaries
            .iter()
            .filter(|s| !s.tags.contains("pinned"))
            .take(self.options.paginate)
        {
            if first {
                if !pinned_first {
                    println!();
                }
                println!("recent:");
            }
            first = false;
            println!("{}", summary);
        }
    }

    fn list(&self) {
        let mut summaries = match self.load() {
            Ok(summaries) => summaries,
            Err(err) => {
                eprintln!("could not load chat summaries: {:?}", err);
                return;
            }
        };
        summaries.retain(|s| !s.tags.contains("archived"));
        self.display(summaries);
    }

    fn chat_for_slug(&self, slug: &str) -> Result<Chat, Error> {
        let chat_root = super::chat_root()?;
        let chat = chat_root.join("chats").join(format!("{}.ndjson", slug));
        Chat::new(Some(chat), ChatOptions::default())
    }

    fn tag(&self, slug: &str, tag: &str) {
        let mut chat = match self.chat_for_slug(slug) {
            Ok(chat) => chat,
            Err(err) => {
                eprintln!("could not load chat: {:?}", err);
                return;
            }
        };
        if let Err(err) = chat.log(&ChatLogLine::Tag {
            created_at: chrono::Local::now(),
            tag: tag.to_string(),
        }) {
            eprintln!("could not tag chat as {}: {:?}", tag, err);
        }
    }

    fn untag(&self, slug: &str, tag: &str) {
        let mut chat = match self.chat_for_slug(slug) {
            Ok(chat) => chat,
            Err(err) => {
                eprintln!("could not load chat: {:?}", err);
                return;
            }
        };
        if let Err(err) = chat.log(&ChatLogLine::Untag {
            created_at: chrono::Local::now(),
            tag: tag.to_string(),
        }) {
            eprintln!("could not untag chat as {}: {:?}", tag, err);
        }
    }

    fn archive(&self, slug: &str) {
        self.tag(slug, "archived");
    }

    fn unarchive(&self, slug: &str) {
        self.untag(slug, "archived");
    }

    fn archived(&self) {
        let mut summaries = match self.load() {
            Ok(summaries) => summaries,
            Err(err) => {
                eprintln!("could not load chat summaries: {:?}", err);
                return;
            }
        };
        summaries.sort_by_key(|chat| chat.modified);
        summaries.retain(|s| s.tags.contains("archived"));
        self.display(summaries);
    }

    fn pin(&self, slug: &str) {
        self.tag(slug, "pinned");
    }

    fn unpin(&self, slug: &str) {
        self.untag(slug, "pinned");
    }

    fn pinned(&self) {
        let mut summaries = match self.load() {
            Ok(summaries) => summaries,
            Err(err) => {
                eprintln!("could not load chat summaries: {:?}", err);
                return;
            }
        };
        summaries.sort_by_key(|chat| chat.modified);
        summaries.retain(|s| !s.tags.contains("archived") && s.tags.contains("pinned"));
        for summary in summaries.iter().take(self.options.paginate) {
            println!("{}", summary);
        }
    }

    async fn new_chat(&self, line: &str, args: Vec<String>) {
        let mut chat = match Chat::new(None, self.options.clone().into()) {
            Ok(chat) => chat,
            Err(err) => {
                eprintln!("could not create chat: {:?}", err);
                return;
            }
        };
        if args.len() != 1 {
            // SAFETY(rescrv):  This is safe because we know that args[0] is "new".
            let prompt = line.strip_prefix("new").unwrap().trim();
            let system = ChatLogLine::Message {
                created_at: chrono::Local::now(),
                message: ChatMessage {
                    role: "system".to_string(),
                    content: prompt.to_string(),
                    images: None,
                    tool_calls: None,
                },
            };
            if let Err(err) = chat.log(&system) {
                eprintln!("could not log system message: {:?}", err);
                return;
            }
            chat.apply(system);
        }
        if let Err(err) = chat.shell().await {
            eprintln!("could not chat: {:?}", err);
        }
    }

    async fn continue_chat(&self, chat: &str) {
        let chat = match self.chat_for_slug(chat) {
            Ok(chat) => chat,
            Err(err) => {
                eprintln!("could not load chat: {:?}", err);
                return;
            }
        };
        let replay = std::cmp::min(self.options.replay, chat.messages().len());
        for message in chat.messages().iter().rev().take(replay).rev() {
            match message.role.as_str() {
                "system" => {
                    if message.content.contains('\n') {
                        println!("SYSTEM \"\"\"\n{}\n\"\"\"", message.content);
                    } else {
                        println!("SYSTEM {}", message.content);
                    }
                }
                "user" => {
                    let lines = message.content.lines().enumerate().map(|(idx, line)| {
                        if idx == 0 {
                            format!(">>> {}", line)
                        } else {
                            format!("... {}", line)
                        }
                    });
                    println!("{}", lines.collect::<Vec<_>>().join("\n"));
                }
                "assistant" => {
                    println!("{}", message.content);
                }
                _ => {
                    eprintln!("unknown role: {}", message.role);
                    continue;
                }
            }
        }
        if let Err(err) = chat.shell().await {
            eprintln!("could not chat: {:?}", err);
        }
    }

    async fn editor_chat(&self) {
        let mut chat = match Chat::new(None, self.options.clone().into()) {
            Ok(chat) => chat,
            Err(err) => {
                eprintln!("could not create chat: {:?}", err);
                return;
            }
        };
        let system = match crate::editor("This will become the system prompt.") {
            Ok(system) => system,
            Err(err) => {
                eprintln!("could not get system message: {:?}", err);
                return;
            }
        };
        let content = match std::fs::read_to_string(system.as_ref()) {
            Ok(content) => content,
            Err(err) => {
                eprintln!("could not read system message: {:?}", err);
                return;
            }
        };
        let system = ChatLogLine::Message {
            created_at: chrono::Local::now(),
            message: ChatMessage {
                role: "system".to_string(),
                content,
                images: None,
                tool_calls: None,
            },
        };
        if let Err(err) = chat.log(&system) {
            eprintln!("could not log system message: {:?}", err);
            return;
        }
        chat.apply(system);
        if let Err(err) = chat.shell().await {
            eprintln!("could not chat: {:?}", err);
        }
    }
}