bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! A conversation about one file, step by step: the user asks, the model plans tool calls,
//! BigText checks and runs them, their bounded results go back, the model answers. The app
//! drives it one request at a time on a worker thread (and asks before steps that change the
//! file); the command line and the tests use [`drive`].
//!
//! Models with tool calling use it; others reply with one JSON object per turn (see
//! [`super::prompt`]), so small local models can plan one step too. The conversation only ever
//! grows: the system prompt and the tools stay the same, so providers can cache them and
//! Anthropic's thinking blocks stay valid.

use serde_json::Value;

use super::chat::{Block, Effort, Event, Message, Reply, Request, Role, Stop, ToolSpec, Usage};
use super::privacy;
use super::tools::{self, Call, Output};
use super::{AiError, Provider};
use crate::jobs::CancelToken;

#[derive(Clone, Debug, PartialEq)]
pub struct Config {
    /// Native tool calling; otherwise one JSON object per reply.
    pub tools: bool,
    /// Tool steps one question may take (1: plan one step).
    pub max_steps: usize,
    /// Send the results back for an answer; otherwise stop when the steps ran.
    pub explain: bool,
    /// Offer the tools that change the file.
    pub writes: bool,
    pub effort: Option<Effort>,
    pub max_tokens: u32,
    /// The answers' language, by its English name.
    pub language: String,
    /// Bytes of file text one question may send.
    pub limit: usize,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            tools: true,
            max_steps: 8,
            explain: true,
            writes: true,
            effort: Some(Effort::Low),
            max_tokens: 8192,
            language: "English".into(),
            limit: privacy::LIMIT_DEFAULT,
        }
    }
}

/// A tool call the model asked for, checked.
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
    pub id: String,
    pub name: String,
    pub input: Value,
    pub call: Result<Call, String>,
    /// What the model said about it, for the user.
    pub note: String,
}

/// What to do after a reply.
#[derive(Clone, Debug, PartialEq)]
pub enum Next {
    /// Run these steps, then give their results (invalid ones are answered as errors).
    Calls(Vec<Step>),
    /// The model answered; the question is done.
    Answer(String),
    /// Send the conversation again (the model was asked to fix its reply).
    Again,
}

pub struct Session {
    pub cfg: Config,
    pub system: String,
    pub specs: Vec<ToolSpec>,
    pub messages: Vec<Message>,
    pub usage: Usage,
    /// Tool steps of the current question.
    pub steps: usize,
    /// Bytes of file text sent for the current question.
    pub sent: usize,
    /// Replies in a row that needed fixing.
    fixes: usize,
    /// Results not sent yet (when the results are not explained), sent with the next question.
    pending: Vec<Block>,
    next_id: usize,
}

/// The first JSON object in a reply (code fences and text around it ignored).
pub fn json_object(text: &str) -> Option<serde_json::Map<String, Value>> {
    let start = text.find('{')?;
    let mut it = serde_json::Deserializer::from_str(&text[start..]).into_iter::<Value>();
    match it.next()? {
        Ok(Value::Object(m)) => Some(m),
        _ => {
            // A brace inside text before the object: try the last object that parses.
            let end = text.rfind('}')?;
            serde_json::from_str::<Value>(&text[start..=end])
                .ok()?
                .as_object()
                .cloned()
        }
    }
}

impl Session {
    pub fn new(cfg: Config) -> Session {
        let system = super::prompt::system(&cfg.language, !cfg.tools, cfg.writes);
        let specs = if cfg.tools {
            tools::specs(cfg.writes)
        } else {
            Vec::new()
        };
        Session {
            cfg,
            system,
            specs,
            messages: Vec::new(),
            usage: Usage::default(),
            steps: 0,
            sent: 0,
            fixes: 0,
            pending: Vec::new(),
            next_id: 0,
        }
    }

    /// Starts a question. The first one carries the file's profile (already redacted).
    pub fn ask(&mut self, question: &str, profile: Option<&Value>) {
        self.steps = 0;
        self.sent = 0;
        self.fixes = 0;
        let text = match profile.filter(|_| self.messages.is_empty()) {
            Some(p) => {
                let t = super::prompt::first_message(p, question);
                self.sent += p.to_string().len();
                t
            }
            None => question.to_string(),
        };
        let mut blocks = std::mem::take(&mut self.pending);
        blocks.push(Block::Text(text));
        self.push_user(blocks);
    }

    /// Adds to the last user message, or starts one (roles must alternate).
    fn push_user(&mut self, blocks: Vec<Block>) {
        let blocks = if self.cfg.tools {
            blocks
        } else {
            // JSON mode: results as text.
            let text: Vec<String> = blocks
                .into_iter()
                .map(|b| match b {
                    Block::Text(t) => t,
                    Block::ToolResult { content, .. } => content,
                    _ => String::new(),
                })
                .filter(|t| !t.is_empty())
                .collect();
            vec![Block::Text(text.join("\n\n"))]
        };
        match self.messages.last_mut() {
            Some(m) if m.role == Role::User => m.blocks.extend(blocks),
            _ => self.messages.push(Message {
                role: Role::User,
                blocks,
            }),
        }
    }

    /// The request for the conversation as it is.
    pub fn request(&self) -> Request<'_> {
        Request {
            model: "",
            system: &self.system,
            messages: &self.messages,
            tools: &self.specs,
            max_tokens: self.cfg.max_tokens,
            json: None,
            effort: self.cfg.effort,
        }
    }

    fn id(&mut self) -> String {
        self.next_id += 1;
        format!("step_{}", self.next_id)
    }

    /// Takes the model's reply and says what comes next.
    pub fn on_reply(&mut self, reply: &Reply) -> Next {
        self.usage.add(&reply.usage);
        let mut msg = reply.message();
        if !self.cfg.tools {
            return self.on_json_reply(msg);
        }
        let note = msg.text();
        let calls: Vec<(String, String, Value)> = msg
            .tool_uses()
            .into_iter()
            .map(|(id, name, input)| (id.to_string(), name.to_string(), input.clone()))
            .collect();
        if msg.blocks.is_empty() {
            msg.blocks.push(Block::Text(String::new()));
        }
        self.messages.push(msg);
        if calls.is_empty() {
            return Next::Answer(match reply.stop {
                Stop::Refusal if note.trim().is_empty() => {
                    "The provider declined to answer this request.".into()
                }
                Stop::MaxTokens if note.trim().is_empty() => {
                    "The answer was cut off (too long).".into()
                }
                _ => note,
            });
        }
        let over = self.steps >= self.cfg.max_steps;
        let steps: Vec<Step> = calls
            .into_iter()
            .map(|(id, name, input)| Step {
                call: if over {
                    Err("the step limit for this question is reached: answer now with what you have, without tools".into())
                } else {
                    tools::parse(&name, &input)
                },
                id,
                name,
                input,
                note: note.clone(),
            })
            .collect();
        self.check_fixes(steps)
    }

    fn check_fixes(&mut self, steps: Vec<Step>) -> Next {
        if steps.iter().all(|s| s.call.is_err()) {
            self.fixes += 1;
            if self.fixes > 2 || self.steps > self.cfg.max_steps {
                let e = steps
                    .iter()
                    .find_map(|s| s.call.clone().err())
                    .unwrap_or_default();
                // The conversation must stay valid for a next question.
                self.pending = steps
                    .iter()
                    .map(|s| Block::ToolResult {
                        id: s.id.clone(),
                        content: "not run".into(),
                        is_error: true,
                    })
                    .collect();
                return Next::Answer(format!("The model did not manage a valid step: {e}"));
            }
        } else {
            self.fixes = 0;
        }
        Next::Calls(steps)
    }

    fn on_json_reply(&mut self, msg: Message) -> Next {
        let text = msg.text();
        self.messages.push(Message::assistant(if text.is_empty() {
            "{}"
        } else {
            &text
        }));
        let Some(obj) = json_object(&text) else {
            self.fixes += 1;
            if text.trim().is_empty() {
                return Next::Answer("The model gave an empty answer.".into());
            }
            if self.fixes > 2 {
                return Next::Answer(text);
            }
            self.push_user(vec![Block::Text(
                "Reply with one JSON object only, as the instructions say.".into(),
            )]);
            return Next::Again;
        };
        if let Some(a) = obj.get("answer") {
            return Next::Answer(
                a.as_str()
                    .map(str::to_string)
                    .unwrap_or_else(|| a.to_string()),
            );
        }
        let Some(name) = obj.get("tool").and_then(|t| t.as_str()).map(str::to_string) else {
            return Next::Answer(text);
        };
        let input = obj
            .get("args")
            .cloned()
            .unwrap_or(Value::Object(Default::default()));
        let note = obj
            .get("note")
            .and_then(|n| n.as_str())
            .unwrap_or_default()
            .to_string();
        let call = if self.steps >= self.cfg.max_steps {
            Err(
                "the step limit for this question is reached: reply with {\"answer\": …} now"
                    .into(),
            )
        } else {
            tools::parse(&name, &input)
        };
        let step = Step {
            id: self.id(),
            name,
            input,
            call,
            note,
        };
        self.check_fixes(vec![step])
    }

    /// Gives the results of the steps (in the order of the calls): a result for the model, or
    /// an error. Returns whether to send the conversation again for the model to go on.
    pub fn give_results(&mut self, results: Vec<(Step, Result<Value, String>)>) -> bool {
        // Valid calls count as steps, even when the tool failed; invalid ones are fixes.
        self.steps += results.iter().filter(|(s, _)| s.call.is_ok()).count();
        let mut blocks = Vec::new();
        for (step, r) in results {
            let (content, is_error) = match r {
                Ok(mut v) => {
                    let room = self.cfg.limit.saturating_sub(self.sent).max(400);
                    privacy::fit(&mut v, room);
                    let s = v.to_string();
                    self.sent += s.len();
                    (s, false)
                }
                Err(e) => (e, true),
            };
            let content = if self.cfg.tools {
                content
            } else if is_error {
                format!("Error from {}: {content}. Fix the arguments and reply with a corrected JSON object.", step.name)
            } else {
                format!("Result of {}: {content}", step.name)
            };
            blocks.push(Block::ToolResult {
                id: step.id,
                content,
                is_error,
            });
        }
        let errors = blocks
            .iter()
            .any(|b| matches!(b, Block::ToolResult { is_error: true, .. }));
        if !self.cfg.explain && !errors {
            // Shown in BigText's panels; the results go with the next question.
            self.pending = blocks;
            return false;
        }
        if self.steps >= self.cfg.max_steps {
            blocks.push(Block::Text(if self.cfg.tools {
                "That was the last step for this question: answer now, without calling tools."
                    .into()
            } else {
                "That was the last step: reply with {\"answer\": …} now.".into()
            }));
        }
        self.push_user(blocks);
        true
    }
}

/// One step's outcome in [`drive`].
#[derive(Debug)]
pub struct Done {
    pub step: Step,
    pub output: Option<Output>,
}

/// Runs a whole question: asks, runs each checked step with `run`, gives the results, until the
/// model answers. Steps that change the file only get their preview from `run`; nothing is
/// applied here.
pub fn drive(
    session: &mut Session,
    provider: &Provider,
    question: &str,
    profile: Option<&Value>,
    run: &mut dyn FnMut(&Call) -> Result<Output, String>,
    cancel: &CancelToken,
    on_event: &mut dyn FnMut(Event),
) -> Result<(String, Vec<Done>), AiError> {
    session.ask(question, profile);
    let mut done = Vec::new();
    // Each round is one request; a runaway conversation stops.
    for _ in 0..(session.cfg.max_steps + 6) {
        if cancel.is_cancelled() {
            return Err(AiError::Cancelled);
        }
        let reply = provider.send(&session.request(), cancel, on_event)?;
        match session.on_reply(&reply) {
            Next::Answer(a) => return Ok((a, done)),
            Next::Again => continue,
            Next::Calls(steps) => {
                let mut results = Vec::new();
                for step in steps {
                    let (r, out) = match &step.call {
                        Ok(c) => match run(c) {
                            Ok(o) => (Ok(o.for_model.clone()), Some(o)),
                            Err(e) => (Err(e), None),
                        },
                        Err(e) => (Err(e.clone()), None),
                    };
                    done.push(Done {
                        step: step.clone(),
                        output: out,
                    });
                    results.push((step, r));
                }
                if !session.give_results(results) {
                    return Ok((String::new(), done));
                }
            }
        }
    }
    Ok(("The question took too many steps.".into(), done))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::fake::{FakeReply, FakeServer};
    use crate::ai::profile::{tests::buf, Profile};
    use crate::ai::Protocol;
    use serde_json::json;

    const LOG: &str = "2024-05-01 10:00:00 INFO start\n2024-05-01 10:00:01 ERROR db timeout\n2024-05-01 10:00:02 ERROR db timeout\n";

    fn provider(server: &FakeServer) -> Provider {
        Provider {
            id: "custom".into(),
            protocol: Protocol::OpenAi,
            url: server.url.clone(),
            model: "fake".into(),
            key: None,
            workspace: String::new(),
        }
    }

    fn ask(
        cfg: Config,
        replies: Vec<FakeReply>,
        question: &str,
    ) -> (String, Vec<Done>, Vec<crate::ai::fake::FakeRequest>) {
        let server = FakeServer::start(replies).unwrap();
        let p = provider(&server);
        let (_f, b) = buf(LOG);
        let cancel = CancelToken::new();
        let profile = Profile::build(&b, "app.log", &cancel).to_json(&mut |s| s.to_string());
        let mut s = Session::new(cfg);
        let mut id = |s: &str| s.to_string();
        let mut run = |c: &Call| {
            tools::run(
                &mut tools::Run {
                    buf: &b,
                    cancel: &cancel,
                    name: "app.log",
                    selection: None,
                    bookmarks: &[],
                    redact: &mut id,
                },
                c,
            )
        };
        let (a, done) = drive(
            &mut s,
            &p,
            question,
            Some(&profile),
            &mut run,
            &cancel,
            &mut |_| {},
        )
        .unwrap();
        (a, done, server.requests())
    }

    #[test]
    fn find_errors_with_tool_calling() {
        let (answer, done, reqs) = ask(
            Config::default(),
            vec![
                FakeReply::openai_tool("levels", r#"{"levels":["error"]}"#),
                FakeReply::openai_text("There are 2 error lines (L2, L3): db timeout."),
            ],
            "find all errors",
        );
        assert_eq!(answer, "There are 2 error lines (L2, L3): db timeout.");
        assert_eq!(done.len(), 1);
        assert_eq!(done[0].output.as_ref().unwrap().n, Some(2));
        // The second request carries the tool result after the call.
        let msgs = reqs[1].json()["messages"].as_array().unwrap().clone();
        assert_eq!(msgs[2]["tool_calls"][0]["function"]["name"], "levels");
        assert_eq!(msgs[3]["role"], "tool");
        assert!(msgs[3]["content"].as_str().unwrap().contains("\"error\":2"));
        assert!(reqs[0].body.contains("The open file's profile"));
        assert!(reqs[0].json()["tools"].as_array().unwrap().len() > 10);
    }

    #[test]
    fn a_bad_regex_goes_back_to_the_model_to_fix() {
        let (answer, done, reqs) = ask(
            Config::default(),
            vec![
                FakeReply::openai_tool("find_all", r#"{"pattern":"(timeout","regex":true}"#),
                FakeReply::openai_tool("find_all", r#"{"pattern":"timeout"}"#),
                FakeReply::openai_text("2 timeouts."),
            ],
            "timeouts?",
        );
        assert_eq!(answer, "2 timeouts.");
        assert!(done[0].step.call.is_err());
        assert_eq!(done[1].output.as_ref().unwrap().n, Some(2));
        let m = reqs[1].json()["messages"].as_array().unwrap().clone();
        assert!(m[3]["content"]
            .as_str()
            .unwrap()
            .starts_with("Error: the regular expression does not compile"));
    }

    #[test]
    fn json_mode_for_models_without_tools() {
        let cfg = Config {
            tools: false,
            max_steps: 1,
            ..Config::default()
        };
        let (answer, done, reqs) = ask(
            cfg,
            vec![
                FakeReply::openai_text("Sure! ```json\n{\"tool\": \"count\", \"args\": {\"pattern\": \"ERROR\"}, \"note\": \"Counting errors.\"}\n```"),
                FakeReply::openai_text("{\"answer\": \"2 lines have ERROR.\"}"),
            ],
            "how many errors",
        );
        assert_eq!(answer, "2 lines have ERROR.");
        assert_eq!(done[0].step.note, "Counting errors.");
        assert!(reqs[0].json().get("tools").is_none());
        let m = reqs[1].json()["messages"].as_array().unwrap().clone();
        let last = m.last().unwrap()["content"].as_str().unwrap().to_string();
        assert!(last.starts_with("Result of count: {\"lines\":2}"), "{last}");
        assert!(last.contains("last step"));
    }

    #[test]
    fn without_explaining_the_results_wait_for_the_next_question() {
        let cfg = Config {
            explain: false,
            ..Config::default()
        };
        let server = FakeServer::start(vec![
            FakeReply::openai_tool("count", r#"{"pattern":"ERROR"}"#),
            FakeReply::openai_text("ok"),
        ])
        .unwrap();
        let p = provider(&server);
        let (_f, b) = buf(LOG);
        let cancel = CancelToken::new();
        let mut s = Session::new(cfg);
        let mut id = |x: &str| x.to_string();
        let mut run = |c: &Call| {
            tools::run(
                &mut tools::Run {
                    buf: &b,
                    cancel: &cancel,
                    name: "a",
                    selection: None,
                    bookmarks: &[],
                    redact: &mut id,
                },
                c,
            )
        };
        let (a, done) = drive(
            &mut s,
            &p,
            "count errors",
            None,
            &mut run,
            &cancel,
            &mut |_| {},
        )
        .unwrap();
        assert_eq!(a, "");
        assert_eq!(done.len(), 1);
        let mut run2 = |_: &Call| Err::<Output, String>("unused".into());
        let (a, _) = drive(
            &mut s,
            &p,
            "and warnings?",
            None,
            &mut run2,
            &cancel,
            &mut |_| {},
        )
        .unwrap();
        assert_eq!(a, "ok");
        let m = server.requests()[1].json()["messages"]
            .as_array()
            .unwrap()
            .clone();
        assert_eq!(m[3]["role"], "tool");
        assert_eq!(m[4]["content"], "and warnings?");
    }

    #[test]
    fn the_step_limit_ends_the_question() {
        let cfg = Config {
            max_steps: 1,
            ..Config::default()
        };
        let (answer, done, _) = ask(
            cfg,
            vec![
                FakeReply::openai_tool("count", r#"{"pattern":"ERROR"}"#),
                FakeReply::openai_tool("count", r#"{"pattern":"INFO"}"#),
                FakeReply::openai_text("Done."),
            ],
            "count",
        );
        assert_eq!(answer, "Done.");
        assert!(done[1]
            .step
            .call
            .as_ref()
            .unwrap_err()
            .contains("step limit"));
    }

    #[test]
    fn the_size_limit_cuts_results() {
        let cfg = Config {
            limit: privacy::LIMIT_MIN,
            ..Config::default()
        };
        let mut s = Session::new(cfg);
        s.ask("q", Some(&json!({"kind": "log"})));
        s.sent = privacy::LIMIT_MIN;
        let step = Step {
            id: "a".into(),
            name: "find_all".into(),
            input: json!({}),
            call: Ok(Call::FileProfile),
            note: String::new(),
        };
        let big = json!({"matches": 9, "first_lines": (0..20).map(|i| json!({"line": i, "text": "z".repeat(190)})).collect::<Vec<_>>()});
        assert!(s.give_results(vec![(step, Ok(big))]));
        let content = s
            .messages
            .last()
            .unwrap()
            .blocks
            .iter()
            .find_map(|b| match b {
                Block::ToolResult { content, .. } => Some(content.clone()),
                _ => None,
            });
        let content = content.unwrap();
        assert!(content.len() <= 400, "{}", content.len());
        assert!(content.contains("\"matches\":9"));
    }

    #[test]
    fn json_objects_are_found_in_text() {
        assert_eq!(json_object("x {\"a\": 1} y").unwrap()["a"], 1);
        assert_eq!(
            json_object("```json\n{\"answer\": \"hi\"}\n```").unwrap()["answer"],
            "hi"
        );
        assert!(json_object("no json").is_none());
    }
}