Skip to main content

zai_rs/knowledge/
document_list.rs

1use super::types::DocumentListResponse;
2use crate::ZaiResult;
3use crate::client::ZaiClient;
4
5/// Query parameters for listing documents under a knowledge base
6#[derive(Clone, serde::Serialize, validator::Validate)]
7pub struct DocumentListQuery {
8    /// Knowledge base id (required)
9    #[validate(length(min = 1))]
10    pub knowledge_id: String,
11    /// Page index (default 1)
12    #[serde(skip_serializing_if = "Option::is_none")]
13    #[validate(range(min = 1))]
14    pub page: Option<u32>,
15    /// Page size (default 10)
16    #[serde(skip_serializing_if = "Option::is_none")]
17    #[validate(range(min = 1))]
18    pub size: Option<u32>,
19    /// Document name filter
20    #[serde(skip_serializing_if = "Option::is_none")]
21    #[validate(length(min = 1))]
22    pub word: Option<String>,
23}
24
25impl std::fmt::Debug for DocumentListQuery {
26    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        formatter
28            .debug_struct("DocumentListQuery")
29            .field("knowledge_id", &"[REDACTED]")
30            .field("page", &self.page)
31            .field("size", &self.size)
32            .field("word", &self.word.as_ref().map(|_| "[REDACTED]"))
33            .finish()
34    }
35}
36
37impl DocumentListQuery {
38    /// Create a new query for the given knowledge base id (page 1, size 10).
39    pub fn new(knowledge_id: impl Into<String>) -> Self {
40        Self {
41            knowledge_id: knowledge_id.into(),
42            page: Some(1),
43            size: Some(10),
44            word: None,
45        }
46    }
47    /// Set the page index (1-based).
48    pub fn with_page(mut self, page: u32) -> Self {
49        self.page = Some(page);
50        self
51    }
52    /// Set the page size.
53    pub fn with_size(mut self, size: u32) -> Self {
54        self.size = Some(size);
55        self
56    }
57    /// Filter by document name.
58    pub fn with_word(mut self, word: impl Into<String>) -> Self {
59        self.word = Some(word.into());
60        self
61    }
62
63    /// Build the `(&str, String)` query pairs (in stable order) used to form
64    /// the request URL.
65    fn pairs(&self) -> Vec<(&'static str, String)> {
66        let mut params: Vec<(&'static str, String)> = Vec::new();
67        params.push(("knowledge_id", self.knowledge_id.clone()));
68        if let Some(page) = self.page.as_ref() {
69            params.push(("page", page.to_string()));
70        }
71        if let Some(size) = self.size.as_ref() {
72            params.push(("size", size.to_string()));
73        }
74        if let Some(word) = self.word.as_ref() {
75            params.push(("word", word.clone()));
76        }
77        params
78    }
79}
80
81/// Document list request (GET /llm-application/open/document)
82///
83/// Credentials and transport live on the [`ZaiClient`], passed to
84/// [`send_via`](Self::send_via).
85pub struct DocumentListRequest {
86    query: DocumentListQuery,
87}
88
89impl DocumentListRequest {
90    /// Create a document-list request for the required knowledge-base id.
91    pub fn new(knowledge_id: impl Into<String>) -> Self {
92        Self {
93            query: DocumentListQuery::new(knowledge_id),
94        }
95    }
96
97    /// Apply a query (replaces the current one).
98    pub fn with_query(mut self, q: DocumentListQuery) -> Self {
99        self.query = q;
100        self
101    }
102
103    /// Set the one-based page index.
104    pub fn with_page(mut self, page: u32) -> Self {
105        self.query.page = Some(page);
106        self
107    }
108
109    /// Set the requested page size.
110    pub fn with_size(mut self, size: u32) -> Self {
111        self.query.size = Some(size);
112        self
113    }
114
115    /// Filter documents by name.
116    pub fn with_word(mut self, word: impl Into<String>) -> Self {
117        self.query.word = Some(word.into());
118        self
119    }
120
121    /// Validate the configured query, send it, and parse the typed response.
122    pub async fn send_via(&self, client: &ZaiClient) -> ZaiResult<DocumentListResponse> {
123        use validator::Validate;
124        self.query.validate()?;
125        crate::client::validation::require_non_blank(&self.query.knowledge_id, "knowledge_id")?;
126        if self
127            .query
128            .word
129            .as_deref()
130            .is_some_and(|word| word.trim().is_empty())
131        {
132            return Err(crate::client::validation::invalid(
133                "word must not be blank when provided",
134            ));
135        }
136        let params = self.query.pairs();
137        let route = crate::client::routes::DOCUMENTS_LIST;
138        let url = client.endpoints().resolve_route_with_query(
139            route,
140            &[],
141            &params
142                .iter()
143                .map(|(k, v)| (*k, v.as_str()))
144                .collect::<Vec<_>>(),
145        )?;
146        client
147            .send_empty::<DocumentListResponse>(route.method(), url)
148            .await
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn query_debug_redacts_knowledge_id_and_word() {
158        let query = DocumentListQuery::new("private-knowledge").with_word("private-document");
159        let debug = format!("{query:?}");
160        assert!(!debug.contains("private-knowledge"));
161        assert!(!debug.contains("private-document"));
162    }
163}