1use ratatui::text::Line;
14use serde_json::Value;
15use typesafe::{Answer, Question, SystemOneResponse, Usage};
16
17use crate::cost::Rates;
18use crate::format::{answer_lines, cost_lines};
19use crate::session::Session;
20use crate::{codegen, cost, mock, session, sketch};
21
22pub const COMMANDS: &[(&str, &str)] = &[
24 ("run", "send the request and print the answers"),
25 (
26 "eval",
27 "run a page over a file of labelled cases and score the answers",
28 ),
29 ("json", "the exact request body this session POSTs"),
30 (
31 "cost",
32 "what a call costs, per question and on both sides of the wire",
33 ),
34 ("rust", "the session as a program against typesafe-ai-sdk"),
35 ("check", "parse the input and report what is wrong with it"),
36];
37
38pub fn is_command(word: &str) -> bool {
40 COMMANDS.iter().any(|(name, _)| *name == word)
41}
42
43pub type Answered = (String, Option<Answer>);
45
46pub fn load(text: &str) -> Result<Session, String> {
52 if text.trim().is_empty() {
53 return Err("Nothing to read: the input is empty.".to_owned());
54 }
55 if text.trim_start().starts_with('{') {
56 return session::from_body(text);
57 }
58 let page = sketch::parse(text);
59 match page.problems.first() {
60 Some(problem) => Err(format!("line {}: {}", problem.line + 1, problem.message)),
61 None => Ok(page.to_session()),
62 }
63}
64
65pub fn check_text(text: &str) -> Result<String, String> {
67 if text.trim().is_empty() {
68 return Err("Nothing to read: the input is empty.".to_owned());
69 }
70 if text.trim_start().starts_with('{') {
71 return session::from_body(text).map(|s| describe(&s));
72 }
73 let page = sketch::parse(text);
74 if !page.ok() {
75 return Err(page
76 .problems
77 .iter()
78 .map(|p| format!("line {}: {}", p.line + 1, p.message))
79 .collect::<Vec<_>>()
80 .join("\n"));
81 }
82 Ok(describe(&page.to_session()))
83}
84
85fn describe(session: &Session) -> String {
87 let n = session.questions.len();
88 let kinds = session
89 .questions
90 .iter()
91 .map(|(name, q)| format!("{name} ({})", kind_of(q)))
92 .collect::<Vec<_>>()
93 .join(", ");
94 let plural = if n == 1 { "" } else { "s" };
95 let head = if kinds.is_empty() {
96 format!("{n} question{plural}")
97 } else {
98 format!("{n} question{plural}: {kinds}")
99 };
100 if session.state_is_empty() {
101 return format!("{head}\nno state — pass --state <text> before sending");
102 }
103 match session.turns() {
104 Some(turns) => {
105 let plural = if turns.len() == 1 { "" } else { "s" };
106 format!(
107 "{head}\nthe state is a conversation of {} turn{plural}",
108 turns.len()
109 )
110 }
111 None => head,
112 }
113}
114
115fn kind_of(question: &Question) -> String {
117 match question {
118 Question::Noul(_) => "noul".to_owned(),
119 Question::Choice(_) => "choice".to_owned(),
120 Question::Score(_) => "score".to_owned(),
121 Question::Raw(value) => value
122 .get("type")
123 .and_then(Value::as_str)
124 .unwrap_or("raw")
125 .to_owned(),
126 _ => "question".to_owned(),
128 }
129}
130
131pub fn sendable(session: &Session) -> Option<String> {
133 if session.questions.is_empty() {
134 return Some("No questions: the request would ask nothing.".to_owned());
135 }
136 if session.state_is_empty() {
137 return Some("No state: pass --state <text>, or put one above the `---`.".to_owned());
138 }
139 None
140}
141
142pub fn request_text(session: &Session, model: &str) -> String {
144 format!("{}\n", session.request_json(model))
145}
146
147pub fn mock_answers(session: &Session) -> Vec<Answered> {
149 session
150 .questions
151 .iter()
152 .map(|(name, q)| {
153 let json = serde_json::to_value(q).unwrap_or(Value::Null);
154 (name.clone(), mock::answer(&session.state, name, &json))
155 })
156 .collect()
157}
158
159pub fn live_answers(session: &Session, response: &SystemOneResponse) -> Vec<Answered> {
161 session
162 .questions
163 .iter()
164 .map(|(name, _)| (name.clone(), response.answers.get(name).cloned()))
165 .collect()
166}
167
168pub fn cached_answers(session: &Session, body: &Value) -> Option<(Vec<Answered>, Option<Usage>)> {
174 let object = body.as_object()?;
175 object.get("model")?.as_str()?;
176 let mut decoded: Vec<(String, Answer)> = Vec::new();
177 for (name, value) in object.get("answers")?.as_object()? {
178 let answer = match value.get("type")?.as_str()? {
179 "noul" => Answer::Noul(serde_json::from_value(value.clone()).ok()?),
180 "choice" => Answer::Choice(serde_json::from_value(value.clone()).ok()?),
181 "score" => Answer::Score(serde_json::from_value(value.clone()).ok()?),
182 _ => continue,
184 };
185 decoded.push((name.clone(), answer));
186 }
187 let answers = session
188 .questions
189 .iter()
190 .map(|(name, _)| {
191 let answer = decoded
192 .iter()
193 .find(|(n, _)| n == name)
194 .map(|(_, a)| a.clone());
195 (name.clone(), answer)
196 })
197 .collect();
198 let usage = object
199 .get("usage")
200 .and_then(|u| serde_json::from_value::<Usage>(u.clone()).ok());
201 Some((answers, usage))
202}
203
204pub fn answers_text(answers: &[Answered], threshold: f64) -> String {
206 let mut out = String::new();
207 for (name, answer) in answers {
208 match answer {
209 Some(a) => out.push_str(&plain(answer_lines(name, a, threshold))),
210 None => out.push_str(&format!(
211 " {name}: no answer came back for this question.\n"
212 )),
213 }
214 }
215 out
216}
217
218pub fn answers_json(answers: &[Answered], model: &str, raw: Option<&Value>) -> String {
220 match raw {
221 Some(value) => format!(
222 "{}\n",
223 serde_json::to_string_pretty(value).unwrap_or_default()
224 ),
225 None => format!("{}\n", mock::body(answers, model)),
226 }
227}
228
229pub fn cost_text(session: &Session, model: &str, rates: Option<Rates>) -> String {
231 let estimate = cost::estimate(session, model);
232 let hint = "--price 0.20/1.00 prices it: dollars per million tokens, input then output";
233 plain(cost_lines(
234 &estimate,
235 rates,
236 hint,
237 cost::thread(session, model).as_ref(),
238 ))
239}
240
241pub fn usage_text(
243 session: &Session,
244 model: &str,
245 rates: Option<Rates>,
246 usage: Option<&Usage>,
247) -> String {
248 if let Some(usage) = usage
249 && let (Some(input), Some(output)) = (usage.input_tokens, usage.output_tokens)
250 {
251 let money = match rates.and_then(|r| cost::price_usage(usage, r)) {
252 Some(cost) => format!(" · {}", cost::usd(cost.total)),
253 None => String::new(),
254 };
255 return format!(" {input} in / {output} out tokens{money}\n");
256 }
257 let estimate = cost::estimate(session, model);
258 let money = match rates {
259 Some(rates) => format!(
260 " · {}",
261 cost::usd(cost::price_estimate(&estimate, rates).total)
262 ),
263 None => String::new(),
264 };
265 format!(
266 " ≈ {} in / {} out tokens{money} — estimated, nothing was counted\n",
267 estimate.input_tokens, estimate.output_tokens
268 )
269}
270
271pub fn code_text(session: &Session, model: &str, threshold: f64) -> String {
273 let code = codegen::rust(session, model, threshold);
274 if code.ends_with('\n') {
275 code
276 } else {
277 format!("{code}\n")
278 }
279}
280
281fn plain(lines: Vec<Line<'static>>) -> String {
283 let mut out = String::new();
284 for line in lines {
285 for span in &line.spans {
286 out.push_str(span.content.as_ref());
287 }
288 out.push('\n');
289 }
290 out
291}