Skip to main content

Questions

Struct Questions 

Source
pub struct Questions(/* private fields */);
Expand description

The questions of one request, each under an id you choose. The answer comes back under the same id; the id itself is not shown to the model.

Questions keep the order they are added in, and every question of a request is evaluated against the same state independently: one answer is never context for another.

use typesafe_jev::{Choice, Noul, Questions, Score};

let questions = Questions::new()
    .with("department", Choice::labels("Which team should handle this?", ["billing", "technical", "sales"]))
    .with("frustration", Score::new("How frustrated is the customer?", ["Calm", "Frustrated", "Very angry"]))
    .with("is_urgent", Noul::new("Does this convey urgency?"));
assert_eq!(questions.len(), 3);
assert_eq!(questions.ids().collect::<Vec<_>>(), ["department", "frustration", "is_urgent"]);

Implementations§

Source§

impl Questions

Source

pub fn new() -> Self

No questions yet.

Examples found in repository?
examples/ask.rs (line 28)
20fn main() -> Result<(), Error> {
21    let client = Client::from_env(Config::default())?;
22
23    let ticket = Ticket {
24        customer_plan: "business",
25        message: "Hi, I've been trying to connect my Stripe account for 3 days and the integration keeps failing. \
26                  I'm losing sales. Please help ASAP.",
27    };
28    let questions = Questions::new()
29        .with(
30            "department",
31            Choice::new(
32                "Which team should handle the `message`?",
33                [
34                    ("billing", "Payment or subscription issues"),
35                    ("technical", "Bugs or integration problems"),
36                    ("sales", "Pricing or account questions"),
37                ],
38            ),
39        )
40        .with(
41            "frustration",
42            Score::new(
43                "How frustrated the customer appears",
44                ["Calm, just stating facts", "Frustrated but civil", "Very angry, strong language"],
45            ),
46        )
47        .with("is_urgent", Noul::new("The message conveys urgency or time-sensitivity"));
48
49    let response = match client.ask(&ticket, &questions) {
50        Ok(response) => response,
51        // Too much state for one request: a real caller would split it and ask again.
52        Err(Error::TokenLimit(message)) => {
53            eprintln!("request too large: {message}");
54            return Ok(());
55        }
56        Err(other) => return Err(other),
57    };
58
59    if let Some(department) = response.choice("department") {
60        println!("department: {} (confidence {:.2})", department.choice, department.confidence);
61        for (option, probability) in &department.probabilities {
62            println!("  {option}: {probability:.2}");
63        }
64    }
65    if let Some(frustration) = response.score("frustration") {
66        println!("frustration: {:.2} of {} (confidence {:.2})", frustration.score, frustration.legend.len() - 1, frustration.confidence);
67    }
68    if let Some(urgent) = response.noul("is_urgent") {
69        println!("urgent: p={:.2}", urgent.noul);
70    }
71
72    let usage = client.usage();
73    println!(
74        "{}: {} request(s), {} retries, {} input tokens, ~${:.6}",
75        response.model,
76        usage.requests(),
77        usage.retries(),
78        usage.input_tokens(),
79        usage.cost_usd()
80    );
81    Ok(())
82}
Source

pub fn with(self, id: impl Into<String>, question: impl Into<Question>) -> Self

Adds a question and returns the set, for chaining.

Examples found in repository?
examples/ask.rs (lines 29-39)
20fn main() -> Result<(), Error> {
21    let client = Client::from_env(Config::default())?;
22
23    let ticket = Ticket {
24        customer_plan: "business",
25        message: "Hi, I've been trying to connect my Stripe account for 3 days and the integration keeps failing. \
26                  I'm losing sales. Please help ASAP.",
27    };
28    let questions = Questions::new()
29        .with(
30            "department",
31            Choice::new(
32                "Which team should handle the `message`?",
33                [
34                    ("billing", "Payment or subscription issues"),
35                    ("technical", "Bugs or integration problems"),
36                    ("sales", "Pricing or account questions"),
37                ],
38            ),
39        )
40        .with(
41            "frustration",
42            Score::new(
43                "How frustrated the customer appears",
44                ["Calm, just stating facts", "Frustrated but civil", "Very angry, strong language"],
45            ),
46        )
47        .with("is_urgent", Noul::new("The message conveys urgency or time-sensitivity"));
48
49    let response = match client.ask(&ticket, &questions) {
50        Ok(response) => response,
51        // Too much state for one request: a real caller would split it and ask again.
52        Err(Error::TokenLimit(message)) => {
53            eprintln!("request too large: {message}");
54            return Ok(());
55        }
56        Err(other) => return Err(other),
57    };
58
59    if let Some(department) = response.choice("department") {
60        println!("department: {} (confidence {:.2})", department.choice, department.confidence);
61        for (option, probability) in &department.probabilities {
62            println!("  {option}: {probability:.2}");
63        }
64    }
65    if let Some(frustration) = response.score("frustration") {
66        println!("frustration: {:.2} of {} (confidence {:.2})", frustration.score, frustration.legend.len() - 1, frustration.confidence);
67    }
68    if let Some(urgent) = response.noul("is_urgent") {
69        println!("urgent: p={:.2}", urgent.noul);
70    }
71
72    let usage = client.usage();
73    println!(
74        "{}: {} request(s), {} retries, {} input tokens, ~${:.6}",
75        response.model,
76        usage.requests(),
77        usage.retries(),
78        usage.input_tokens(),
79        usage.cost_usd()
80    );
81    Ok(())
82}
Source

pub fn insert( &mut self, id: impl Into<String>, question: impl Into<Question>, ) -> Option<Question>

Adds a question. A question already under id is replaced, in place, and returned.

Source

pub fn get(&self, id: &str) -> Option<&Question>

The question under id.

Source

pub fn len(&self) -> usize

How many questions there are.

Source

pub fn is_empty(&self) -> bool

Whether there are no questions.

Source

pub fn ids(&self) -> impl Iterator<Item = &str>

The ids, in order.

Source

pub fn iter(&self) -> Iter<'_, String, Question> ⓘ

The ids and their questions, in order.

Source

pub fn as_map(&self) -> &IndexMap<String, Question>

The questions as the map they are.

Trait Implementations§

Source§

impl Clone for Questions

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Questions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Questions

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Questions

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<I: Into<String>, Q: Into<Question>> Extend<(I, Q)> for Questions

Source§

fn extend<T: IntoIterator<Item = (I, Q)>>(&mut self, questions: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<IndexMap<String, Question>> for Questions

Source§

fn from(questions: IndexMap<String, Question>) -> Self

Converts to this type from the input type.
Source§

impl From<Questions> for IndexMap<String, Question>

Source§

fn from(questions: Questions) -> Self

Converts to this type from the input type.
Source§

impl<I: Into<String>, Q: Into<Question>> FromIterator<(I, Q)> for Questions

Source§

fn from_iter<T: IntoIterator<Item = (I, Q)>>(questions: T) -> Self

Creates a value from an iterator. Read more
Source§

impl IntoIterator for Questions

Source§

type Item = (String, Question)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<String, Question>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a Questions

Source§

type Item = (&'a String, &'a Question)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, String, Question>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Questions

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Questions

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Questions

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.