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 {
pub tools: bool,
pub max_steps: usize,
pub explain: bool,
pub writes: bool,
pub effort: Option<Effort>,
pub max_tokens: u32,
pub language: String,
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,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
pub id: String,
pub name: String,
pub input: Value,
pub call: Result<Call, String>,
pub note: String,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Next {
Calls(Vec<Step>),
Answer(String),
Again,
}
pub struct Session {
pub cfg: Config,
pub system: String,
pub specs: Vec<ToolSpec>,
pub messages: Vec<Message>,
pub usage: Usage,
pub steps: usize,
pub sent: usize,
fixes: usize,
pending: Vec<Block>,
next_id: usize,
}
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),
_ => {
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,
}
}
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);
}
fn push_user(&mut self, blocks: Vec<Block>) {
let blocks = if self.cfg.tools {
blocks
} else {
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,
}),
}
}
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)
}
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();
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])
}
pub fn give_results(&mut self, results: Vec<(Step, Result<Value, String>)>) -> bool {
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 {
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
}
}
#[derive(Debug)]
pub struct Done {
pub step: Step,
pub output: Option<Output>,
}
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();
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,
}
}
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));
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());
}
}