Skip to main content

headless_lms_chatbot/chatbot_tools/
argument_parsing.rs

1//! Shared helpers for parsing model-supplied tool arguments.
2
3use std::str::FromStr;
4
5use serde::{Deserialize, Deserializer};
6use uuid::Uuid;
7
8use crate::prelude::{BackendError, ChatbotError, ChatbotErrorType, ChatbotResult, chatbot_err};
9
10/// Deserializes an optional string field and parses it into an Uuid, doing this
11/// optionally without failure. If an error occurs, a None is returned. This is
12/// desired for truly optional id fields generated by an LLM, which can be None or
13/// a non-Uuid string in some cases. If any errors should occur, they are emitted
14/// in ChatbotTools's from_db_and_arguments.
15pub fn deserialize_to_optional_uuid_and_errors_to_none<'de, D>(
16    deserializer: D,
17) -> Result<Option<Uuid>, D::Error>
18where
19    D: Deserializer<'de>,
20{
21    let res = String::deserialize(deserializer)
22        .ok()
23        .and_then(|s| Uuid::from_str(&s).ok());
24    Ok(res)
25}
26
27/// Parses a required UUID tool argument, reporting a parse failure as
28/// [ChatbotErrorType::InvalidToolArguments] naming `field_name` and the offending value.
29pub fn parse_required_uuid(field_name: &str, value: &str) -> ChatbotResult<Uuid> {
30    Uuid::from_str(value).map_err(|e| {
31        chatbot_err!(
32            InvalidToolArguments,
33            format!("'{value}' is not a valid {field_name} (UUID)."),
34            e
35        )
36    })
37}