lm_studio_api/chat/
message.rs

1use crate::prelude::*;
2use super::Role;
3
4// A message
5#[derive(Debug, Clone, From, Serialize, Deserialize, Eq, PartialEq)]
6#[from(String, "Self { role: Role::User, content: vec![value.into()] }")]
7#[from(&str, "Self { role: Role::User, content: vec![value.into()] }")]
8pub struct Message {
9    pub role: Role,
10    pub content: Vec<Content>,
11}
12
13impl Message {
14    // Creates a new message from text
15    pub fn new<S: Into<String>>(role: Role, text: S) -> Self {
16        Self {
17            role,
18            content: vec![text.into().into()],
19        }
20    }
21
22    /// Returns content chars count
23    pub fn len(&self) -> usize {
24        let mut count = 0;
25
26        for content in &self.content {
27            match &content {
28                Content::Text { text } => count += text.chars().count(),
29                _ => {}
30            }
31        }
32
33        count
34    }
35
36    /// Returns message texts
37    pub fn texts(&self) -> Vec<&String> {
38        let mut texts = vec![];
39
40        for content in &self.content {
41            match &content {
42                Content::Text { text } => texts.push(text),
43                _ => {}
44            }
45        }
46        
47        texts
48    }
49
50    /// Returns message full text
51    pub fn text(&self) -> String {
52        self.texts()
53            .iter()
54            .map(|s| s.as_str())
55            .collect::<Vec<_>>()
56            .join("\n\n")
57    }
58}