Skip to main content

keep_rs/
knowledge.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Map, Value, json};
5
6use crate::KeepClient;
7use crate::error::Result;
8use crate::scope::Scope;
9
10pub const FORGET_SOURCES_LIMIT: usize = 1000;
11pub const SOURCE_ALLOWLIST_LIMIT: usize = 1000;
12
13#[non_exhaustive]
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Episode {
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub id: Option<String>,
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub speaker: Option<String>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub occurred_at: Option<String>,
22    pub text: String,
23}
24
25impl Episode {
26    pub fn new(text: impl Into<String>) -> Self {
27        Self {
28            id: None,
29            speaker: None,
30            occurred_at: None,
31            text: text.into(),
32        }
33    }
34
35    pub fn id(mut self, id: impl Into<String>) -> Self {
36        self.id = Some(id.into());
37        self
38    }
39
40    pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
41        self.speaker = Some(speaker.into());
42        self
43    }
44
45    pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
46        self.occurred_at = Some(occurred_at.into());
47        self
48    }
49}
50
51#[non_exhaustive]
52#[derive(Debug, Clone, Default)]
53pub struct KnowledgeIngestRequest {
54    pub source_id: Option<String>,
55    pub title: Option<String>,
56    pub collection: Option<String>,
57    pub kind: Option<String>,
58    pub text: Option<String>,
59    pub occurred_at: Option<String>,
60    pub episodes: Option<Vec<Episode>>,
61    pub metadata: Option<BTreeMap<String, String>>,
62    pub replace: bool,
63}
64
65impl KnowledgeIngestRequest {
66    pub fn document(text: impl Into<String>) -> Self {
67        Self {
68            text: Some(text.into()),
69            ..Self::default()
70        }
71    }
72
73    pub fn episodes(episodes: Vec<Episode>) -> Self {
74        Self {
75            episodes: Some(episodes),
76            ..Self::default()
77        }
78    }
79
80    pub fn source_id(mut self, source_id: impl Into<String>) -> Self {
81        self.source_id = Some(source_id.into());
82        self
83    }
84
85    pub fn title(mut self, title: impl Into<String>) -> Self {
86        self.title = Some(title.into());
87        self
88    }
89
90    pub fn collection(mut self, collection: impl Into<String>) -> Self {
91        self.collection = Some(collection.into());
92        self
93    }
94
95    pub fn kind(mut self, kind: impl Into<String>) -> Self {
96        self.kind = Some(kind.into());
97        self
98    }
99
100    pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
101        self.occurred_at = Some(occurred_at.into());
102        self
103    }
104
105    pub fn metadata(mut self, metadata: BTreeMap<String, String>) -> Self {
106        self.metadata = Some(metadata);
107        self
108    }
109
110    pub fn replace(mut self, replace: bool) -> Self {
111        self.replace = replace;
112        self
113    }
114}
115
116#[non_exhaustive]
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct IngestReport {
119    #[serde(default)]
120    pub episodes_added: i64,
121    #[serde(default)]
122    pub episodes_unchanged: i64,
123    #[serde(default)]
124    pub replaced: bool,
125}
126
127#[non_exhaustive]
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct KnowledgeIngestResult {
131    pub scope: String,
132    pub source_id: String,
133    pub partition: String,
134    pub collection: String,
135    #[serde(default)]
136    pub captured: bool,
137    #[serde(default)]
138    pub replaced: bool,
139    pub report: IngestReport,
140    #[serde(default)]
141    pub jobs: Value,
142    #[serde(default)]
143    pub enrichment: Value,
144}
145
146#[non_exhaustive]
147#[derive(Debug, Clone)]
148pub struct KnowledgeSearchRequest {
149    pub query: String,
150    pub limit: Option<usize>,
151    pub budget_tokens: Option<usize>,
152    pub as_of: Option<String>,
153    pub valid_at: Option<String>,
154    pub source_ids: Option<Vec<String>>,
155    pub collections: Option<Vec<String>>,
156}
157
158impl KnowledgeSearchRequest {
159    pub fn new(query: impl Into<String>) -> Self {
160        Self {
161            query: query.into(),
162            limit: None,
163            budget_tokens: None,
164            as_of: None,
165            valid_at: None,
166            source_ids: None,
167            collections: None,
168        }
169    }
170
171    pub fn limit(mut self, limit: usize) -> Self {
172        self.limit = Some(limit);
173        self
174    }
175
176    pub fn budget_tokens(mut self, tokens: usize) -> Self {
177        self.budget_tokens = Some(tokens);
178        self
179    }
180
181    pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
182        self.as_of = Some(as_of.into());
183        self
184    }
185
186    pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
187        self.valid_at = Some(valid_at.into());
188        self
189    }
190
191    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
192        self.source_ids = Some(source_ids);
193        self
194    }
195
196    pub fn collections(mut self, collections: Vec<String>) -> Self {
197        self.collections = Some(collections);
198        self
199    }
200}
201
202#[non_exhaustive]
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct ItemRef {
205    pub kind: String,
206    pub id: String,
207}
208
209#[non_exhaustive]
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211pub struct Citation {
212    #[serde(default)]
213    pub reference: String,
214    pub source_id: String,
215    #[serde(default)]
216    pub source_title: String,
217    #[serde(default)]
218    pub episode_id: String,
219    #[serde(default)]
220    pub speaker: String,
221    #[serde(default)]
222    pub occurred_at: Option<String>,
223    #[serde(default)]
224    pub char_start: i32,
225    #[serde(default)]
226    pub char_end: i32,
227    #[serde(default)]
228    pub quote: String,
229    #[serde(default)]
230    pub source_metadata: BTreeMap<String, String>,
231}
232
233#[non_exhaustive]
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235pub struct SearchHit {
236    pub item: ItemRef,
237    #[serde(default)]
238    pub rank: usize,
239    pub score: f64,
240    pub text: String,
241    #[serde(default)]
242    pub tokens: usize,
243    pub source_id: String,
244    #[serde(default)]
245    pub occurred_at: Option<String>,
246    #[serde(default)]
247    pub fact: Option<Value>,
248    pub citation: Citation,
249}
250
251#[non_exhaustive]
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253pub struct Allowance {
254    pub limit: usize,
255    pub used: usize,
256}
257
258#[non_exhaustive]
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct KnowledgeSearchResult {
261    pub scope: String,
262    #[serde(default)]
263    pub hits: Vec<SearchHit>,
264    #[serde(default)]
265    pub used_tokens: usize,
266    #[serde(default)]
267    pub omitted: usize,
268    #[serde(default)]
269    pub degraded: Vec<String>,
270    #[serde(default)]
271    pub method: String,
272    #[serde(default)]
273    pub allowance: Option<Allowance>,
274}
275
276#[non_exhaustive]
277#[derive(Debug, Clone)]
278pub struct KnowledgeFetchRequest {
279    pub id: String,
280    pub budget_tokens: Option<usize>,
281    pub as_of: Option<String>,
282    pub valid_at: Option<String>,
283    pub source_ids: Option<Vec<String>>,
284    pub collections: Option<Vec<String>>,
285}
286
287impl KnowledgeFetchRequest {
288    pub fn new(id: impl Into<String>) -> Self {
289        Self {
290            id: id.into(),
291            budget_tokens: None,
292            as_of: None,
293            valid_at: None,
294            source_ids: None,
295            collections: None,
296        }
297    }
298
299    pub fn budget_tokens(mut self, tokens: usize) -> Self {
300        self.budget_tokens = Some(tokens);
301        self
302    }
303
304    pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
305        self.as_of = Some(as_of.into());
306        self
307    }
308
309    pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
310        self.valid_at = Some(valid_at.into());
311        self
312    }
313
314    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
315        self.source_ids = Some(source_ids);
316        self
317    }
318
319    pub fn collections(mut self, collections: Vec<String>) -> Self {
320        self.collections = Some(collections);
321        self
322    }
323}
324
325#[non_exhaustive]
326#[derive(Debug, Clone)]
327pub struct KnowledgeCiteRequest {
328    pub id: String,
329    pub source_ids: Option<Vec<String>>,
330    pub collections: Option<Vec<String>>,
331}
332
333impl KnowledgeCiteRequest {
334    pub fn new(id: impl Into<String>) -> Self {
335        Self {
336            id: id.into(),
337            source_ids: None,
338            collections: None,
339        }
340    }
341
342    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
343        self.source_ids = Some(source_ids);
344        self
345    }
346
347    pub fn collections(mut self, collections: Vec<String>) -> Self {
348        self.collections = Some(collections);
349        self
350    }
351}
352
353#[non_exhaustive]
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355pub struct KnowledgeCitations {
356    pub scope: String,
357    pub id: String,
358    #[serde(default)]
359    pub citations: Vec<Citation>,
360}
361
362#[non_exhaustive]
363#[derive(Debug, Clone, Default)]
364pub struct KnowledgeIndexRequest {
365    pub level: u8,
366    pub collection: Option<String>,
367    pub prefix: Option<String>,
368    pub cursor: Option<usize>,
369    pub budget_tokens: Option<usize>,
370    pub source_ids: Option<Vec<String>>,
371    pub collections: Option<Vec<String>>,
372}
373
374impl KnowledgeIndexRequest {
375    pub fn level(level: u8) -> Self {
376        Self {
377            level,
378            ..Self::default()
379        }
380    }
381
382    pub fn collection(mut self, collection: impl Into<String>) -> Self {
383        self.collection = Some(collection.into());
384        self
385    }
386
387    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
388        self.prefix = Some(prefix.into());
389        self
390    }
391
392    pub fn cursor(mut self, cursor: usize) -> Self {
393        self.cursor = Some(cursor);
394        self
395    }
396
397    pub fn budget_tokens(mut self, tokens: usize) -> Self {
398        self.budget_tokens = Some(tokens);
399        self
400    }
401
402    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
403        self.source_ids = Some(source_ids);
404        self
405    }
406
407    pub fn collections(mut self, collections: Vec<String>) -> Self {
408        self.collections = Some(collections);
409        self
410    }
411}
412
413#[non_exhaustive]
414#[derive(Debug, Clone)]
415pub struct KnowledgeTraverseRequest {
416    pub start: String,
417    pub depth: Option<usize>,
418    pub fanout: Option<usize>,
419    pub as_of: Option<String>,
420    pub valid_at: Option<String>,
421    pub source_ids: Option<Vec<String>>,
422    pub collections: Option<Vec<String>>,
423}
424
425impl KnowledgeTraverseRequest {
426    pub fn new(start: impl Into<String>) -> Self {
427        Self {
428            start: start.into(),
429            depth: None,
430            fanout: None,
431            as_of: None,
432            valid_at: None,
433            source_ids: None,
434            collections: None,
435        }
436    }
437
438    pub fn depth(mut self, depth: usize) -> Self {
439        self.depth = Some(depth);
440        self
441    }
442
443    pub fn fanout(mut self, fanout: usize) -> Self {
444        self.fanout = Some(fanout);
445        self
446    }
447
448    pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
449        self.as_of = Some(as_of.into());
450        self
451    }
452
453    pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
454        self.valid_at = Some(valid_at.into());
455        self
456    }
457
458    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
459        self.source_ids = Some(source_ids);
460        self
461    }
462
463    pub fn collections(mut self, collections: Vec<String>) -> Self {
464        self.collections = Some(collections);
465        self
466    }
467}
468
469#[non_exhaustive]
470#[derive(Debug, Clone, Default)]
471pub struct KnowledgeSummarizeRequest {
472    pub source_id: Option<String>,
473    pub text: Option<String>,
474    pub episodes: Option<Vec<Episode>>,
475    pub source_ids: Option<Vec<String>>,
476    pub collections: Option<Vec<String>>,
477}
478
479impl KnowledgeSummarizeRequest {
480    pub fn source_id(source_id: impl Into<String>) -> Self {
481        Self {
482            source_id: Some(source_id.into()),
483            ..Self::default()
484        }
485    }
486
487    pub fn text(text: impl Into<String>) -> Self {
488        Self {
489            text: Some(text.into()),
490            ..Self::default()
491        }
492    }
493
494    pub fn episodes(episodes: Vec<Episode>) -> Self {
495        Self {
496            episodes: Some(episodes),
497            ..Self::default()
498        }
499    }
500
501    pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
502        self.source_ids = Some(source_ids);
503        self
504    }
505
506    pub fn collections(mut self, collections: Vec<String>) -> Self {
507        self.collections = Some(collections);
508        self
509    }
510}
511
512#[non_exhaustive]
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct TokenUsage {
516    pub input_tokens: u64,
517    pub output_tokens: u64,
518}
519
520#[non_exhaustive]
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522pub struct KnowledgeSummary {
523    pub scope: String,
524    pub summary: String,
525    pub model: String,
526    pub usage: TokenUsage,
527}
528
529#[non_exhaustive]
530#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
531pub struct KnowledgeStatus {
532    pub scope: String,
533    pub enrichment: Value,
534}
535
536#[non_exhaustive]
537#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
538pub struct ForgetSourceReceipt {
539    pub episodes: i64,
540    pub chunks: i64,
541}
542
543#[non_exhaustive]
544#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(rename_all = "camelCase")]
546pub struct ForgottenSource {
547    pub source_id: String,
548    pub receipt: ForgetSourceReceipt,
549}
550
551#[non_exhaustive]
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553#[serde(rename_all = "camelCase")]
554pub struct KnowledgeForgetSourceResult {
555    pub scope: String,
556    pub source_id: String,
557    pub receipt: ForgetSourceReceipt,
558}
559
560#[non_exhaustive]
561#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
562pub struct KnowledgeForgetSourcesResult {
563    pub scope: String,
564    pub forgotten: Vec<ForgottenSource>,
565    pub missing: Vec<String>,
566}
567
568#[non_exhaustive]
569#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
570pub struct KnowledgeRebuildResult {
571    pub scope: String,
572    pub queued: usize,
573    pub jobs: Value,
574}
575
576#[derive(Debug, Clone, Copy)]
577pub struct KnowledgeClient<'a> {
578    client: &'a KeepClient,
579    scope: Option<&'a Scope>,
580}
581
582impl<'a> KnowledgeClient<'a> {
583    pub(crate) fn new(client: &'a KeepClient, scope: Option<&'a Scope>) -> Self {
584        Self { client, scope }
585    }
586
587    fn base_body(&self) -> Map<String, Value> {
588        let mut body = Map::new();
589        if let Some(scope) = self.scope
590            && !scope.is_empty()
591        {
592            body.insert("scope".into(), json!(scope));
593        }
594        body
595    }
596
597    pub async fn ingest(&self, req: KnowledgeIngestRequest) -> Result<KnowledgeIngestResult> {
598        let mut body = self.base_body();
599        if let Some(source_id) = req.source_id {
600            body.insert("source_id".into(), json!(source_id));
601        }
602        if let Some(title) = req.title {
603            body.insert("title".into(), json!(title));
604        }
605        if let Some(collection) = req.collection {
606            body.insert("collection".into(), json!(collection));
607        }
608        if let Some(kind) = req.kind {
609            body.insert("kind".into(), json!(kind));
610        }
611        if let Some(text) = req.text {
612            body.insert("text".into(), json!(text));
613        }
614        if let Some(occurred_at) = req.occurred_at {
615            body.insert("occurred_at".into(), json!(occurred_at));
616        }
617        if let Some(episodes) = req.episodes {
618            body.insert("episodes".into(), json!(episodes));
619        }
620        if let Some(metadata) = req.metadata {
621            body.insert("metadata".into(), json!(metadata));
622        }
623        if req.replace {
624            body.insert("replace".into(), json!(true));
625        }
626        self.client
627            .post_json("/v1/knowledge/ingest", Value::Object(body))
628            .await
629    }
630
631    pub async fn search(&self, req: KnowledgeSearchRequest) -> Result<KnowledgeSearchResult> {
632        let mut body = self.base_body();
633        body.insert("query".into(), json!(req.query));
634        if let Some(limit) = req.limit {
635            body.insert("limit".into(), json!(limit));
636        }
637        if let Some(budget_tokens) = req.budget_tokens {
638            body.insert("budget_tokens".into(), json!(budget_tokens));
639        }
640        if let Some(as_of) = req.as_of {
641            body.insert("as_of".into(), json!(as_of));
642        }
643        if let Some(valid_at) = req.valid_at {
644            body.insert("valid_at".into(), json!(valid_at));
645        }
646        if let Some(source_ids) = req.source_ids {
647            body.insert("source_ids".into(), json!(source_ids));
648        }
649        if let Some(collections) = req.collections {
650            body.insert("collections".into(), json!(collections));
651        }
652        self.client
653            .post_json("/v1/knowledge/search", Value::Object(body))
654            .await
655    }
656
657    pub async fn fetch(&self, req: KnowledgeFetchRequest) -> Result<Value> {
658        let mut body = self.base_body();
659        body.insert("id".into(), json!(req.id));
660        if let Some(budget_tokens) = req.budget_tokens {
661            body.insert("budget_tokens".into(), json!(budget_tokens));
662        }
663        if let Some(as_of) = req.as_of {
664            body.insert("as_of".into(), json!(as_of));
665        }
666        if let Some(valid_at) = req.valid_at {
667            body.insert("valid_at".into(), json!(valid_at));
668        }
669        if let Some(source_ids) = req.source_ids {
670            body.insert("source_ids".into(), json!(source_ids));
671        }
672        if let Some(collections) = req.collections {
673            body.insert("collections".into(), json!(collections));
674        }
675        self.client
676            .post_json("/v1/knowledge/fetch", Value::Object(body))
677            .await
678    }
679
680    pub async fn cite(&self, req: KnowledgeCiteRequest) -> Result<KnowledgeCitations> {
681        let mut body = self.base_body();
682        body.insert("id".into(), json!(req.id));
683        if let Some(source_ids) = req.source_ids {
684            body.insert("source_ids".into(), json!(source_ids));
685        }
686        if let Some(collections) = req.collections {
687            body.insert("collections".into(), json!(collections));
688        }
689        self.client
690            .post_json("/v1/knowledge/cite", Value::Object(body))
691            .await
692    }
693
694    pub async fn index(&self, req: KnowledgeIndexRequest) -> Result<Value> {
695        let mut body = self.base_body();
696        body.insert("level".into(), json!(req.level));
697        if let Some(collection) = req.collection {
698            body.insert("collection".into(), json!(collection));
699        }
700        if let Some(prefix) = req.prefix {
701            body.insert("prefix".into(), json!(prefix));
702        }
703        if let Some(cursor) = req.cursor {
704            body.insert("cursor".into(), json!(cursor));
705        }
706        if let Some(budget_tokens) = req.budget_tokens {
707            body.insert("budget_tokens".into(), json!(budget_tokens));
708        }
709        if let Some(source_ids) = req.source_ids {
710            body.insert("source_ids".into(), json!(source_ids));
711        }
712        if let Some(collections) = req.collections {
713            body.insert("collections".into(), json!(collections));
714        }
715        self.client
716            .post_json("/v1/knowledge/index", Value::Object(body))
717            .await
718    }
719
720    pub async fn traverse(&self, req: KnowledgeTraverseRequest) -> Result<Value> {
721        let mut body = self.base_body();
722        body.insert("start".into(), json!(req.start));
723        if let Some(depth) = req.depth {
724            body.insert("depth".into(), json!(depth));
725        }
726        if let Some(fanout) = req.fanout {
727            body.insert("fanout".into(), json!(fanout));
728        }
729        if let Some(as_of) = req.as_of {
730            body.insert("as_of".into(), json!(as_of));
731        }
732        if let Some(valid_at) = req.valid_at {
733            body.insert("valid_at".into(), json!(valid_at));
734        }
735        if let Some(source_ids) = req.source_ids {
736            body.insert("source_ids".into(), json!(source_ids));
737        }
738        if let Some(collections) = req.collections {
739            body.insert("collections".into(), json!(collections));
740        }
741        self.client
742            .post_json("/v1/knowledge/traverse", Value::Object(body))
743            .await
744    }
745
746    pub async fn status(&self) -> Result<KnowledgeStatus> {
747        let body = self.base_body();
748        self.client
749            .post_json("/v1/knowledge/status", Value::Object(body))
750            .await
751    }
752
753    pub async fn summarize(&self, req: KnowledgeSummarizeRequest) -> Result<KnowledgeSummary> {
754        let mut body = self.base_body();
755        if let Some(source_id) = req.source_id {
756            body.insert("source_id".into(), json!(source_id));
757        }
758        if let Some(text) = req.text {
759            body.insert("text".into(), json!(text));
760        }
761        if let Some(episodes) = req.episodes {
762            body.insert("episodes".into(), json!(episodes));
763        }
764        if let Some(source_ids) = req.source_ids {
765            body.insert("source_ids".into(), json!(source_ids));
766        }
767        if let Some(collections) = req.collections {
768            body.insert("collections".into(), json!(collections));
769        }
770        self.client
771            .post_json("/v1/knowledge/summarize", Value::Object(body))
772            .await
773    }
774
775    pub async fn forget_source(
776        &self,
777        source_id: impl Into<String>,
778    ) -> Result<KnowledgeForgetSourceResult> {
779        let mut body = self.base_body();
780        body.insert("source_id".into(), json!(source_id.into()));
781        self.client
782            .post_json("/v1/knowledge/forget_source", Value::Object(body))
783            .await
784    }
785
786    pub async fn forget_sources(
787        &self,
788        source_ids: Vec<String>,
789    ) -> Result<KnowledgeForgetSourcesResult> {
790        let mut body = self.base_body();
791        body.insert("source_ids".into(), json!(source_ids));
792        self.client
793            .post_json("/v1/knowledge/forget_sources", Value::Object(body))
794            .await
795    }
796
797    pub async fn rebuild_projection(&self) -> Result<KnowledgeRebuildResult> {
798        let body = self.base_body();
799        self.client
800            .post_json("/v1/knowledge/rebuild_projection", Value::Object(body))
801            .await
802    }
803}