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
|
use std::io::{IsTerminal, Write};
use std::time::Duration;
use crate::provider::{Outcome, Sink};
pub fn stdout_is_tty() -> bool {
std::io::stdout().is_terminal()
}
/// Streams to stdout. Colour is used only when stdout is a terminal, so piping
/// the output somewhere gives clean text.
pub struct Renderer {
color: bool,
dimmed: bool,
wrote_text: bool,
}
impl Renderer {
pub fn new(color: bool) -> Self {
Self {
color,
dimmed: false,
wrote_text: false,
}
}
fn undim(&mut self) {
if self.dimmed {
print!("\x1b[0m");
self.dimmed = false;
}
}
}
impl Sink for Renderer {
fn text(&mut self, s: &str) {
self.undim();
print!("{s}");
let _ = std::io::stdout().flush();
self.wrote_text = true;
}
fn reasoning(&mut self, s: &str) {
if !self.color {
return;
}
if !self.dimmed {
print!("\x1b[2m");
self.dimmed = true;
}
print!("{s}");
let _ = std::io::stdout().flush();
}
fn done(&mut self, outcome: &Outcome, elapsed: Duration) {
self.undim();
if self.wrote_text {
println!();
}
let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())];
if let Some(usage) = &outcome.usage {
let input = usage.get("prompt_tokens").and_then(|v| v.as_u64());
let output = usage.get("completion_tokens").and_then(|v| v.as_u64());
if let (Some(i), Some(o)) = (input, output) {
parts.push(format!("{i} in · {o} out"));
}
}
let line = format!("─ {}", parts.join(" · "));
if self.color {
println!("\x1b[2m{line}\x1b[0m");
} else {
println!("{line}");
}
}
}
|