Skip to main content

graphrt_ffi/
learning.rs

1//! Self learning (feature `learning`): the `learning` field of `agent` nodes
2//! reads approved lessons from a store in the app's own storage (config
3//! `learning_dir`). The app proposes lessons from what a person said about a
4//! run, and the owner approves or rejects them; only approved lessons reach a
5//! model.
6//!
7//! The methods exist in every build; without the feature, or without
8//! `learning_dir`, they fail with `GraphrtError.Unsupported`.
9
10use crate::{GraphrtError, Runtime};
11
12/// What kind of thing a lesson is.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
14pub enum LessonKind {
15    /// How someone likes things done ("answer in Indonesian").
16    Preference,
17    /// Something that is true ("invoices go to finance").
18    Fact,
19    /// How to do something ("check stock before quoting").
20    Procedure,
21    /// A mistake not to repeat.
22    Correction,
23}
24
25/// Where a lesson is in its life.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
27pub enum LessonStatus {
28    Proposed,
29    Approved,
30    Rejected,
31    Retired,
32}
33
34/// A decision about a lesson.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
36pub enum LessonDecision {
37    /// Use it in runs.
38    Approve,
39    /// Decline it; the same text is not proposed again.
40    Reject,
41    /// Stop using an approved lesson, keeping it on record.
42    Retire,
43}
44
45/// A lesson of an agent.
46#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
47pub struct LessonInfo {
48    pub id: String,
49    pub agent: String,
50    /// The one user it applies to; `None` for every run of the agent.
51    pub user: Option<String>,
52    pub kind: LessonKind,
53    pub text: String,
54    pub status: LessonStatus,
55    /// It could change what the agent does to the outside world (sending,
56    /// money, credentials...): show it to the owner with care.
57    pub high_risk: bool,
58    /// Where it came from, as one English sentence.
59    pub origin: String,
60    pub created_at_ms: u64,
61}
62
63/// A lesson proposed from feedback on a run.
64#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
65pub struct LessonProposal {
66    /// The agent (the `learning.agent` of its node).
67    pub agent: String,
68    /// The user of the run; the lesson applies to this user only.
69    #[uniffi(default)]
70    pub user: Option<String>,
71    pub kind: LessonKind,
72    pub text: String,
73    /// The run the feedback is about.
74    #[uniffi(default)]
75    pub run_id: Option<String>,
76    /// Who gave the feedback, and whether the app verified it is them (signed in).
77    #[uniffi(default)]
78    pub author: Option<String>,
79    #[uniffi(default)]
80    pub author_authenticated: bool,
81    /// A short excerpt that shows why (mask secrets first).
82    #[uniffi(default)]
83    pub evidence: Option<String>,
84}
85
86#[cfg(feature = "learning")]
87mod imp {
88    use std::sync::Arc;
89
90    use graphrt_learn::{Decision, LessonFilter, LessonStore, NewLesson, Proposal, Risk, Signal, UserFilter};
91
92    use super::{LessonDecision, LessonInfo, LessonKind, LessonProposal, LessonStatus};
93    use crate::GraphrtError;
94
95    pub(crate) type Store = Arc<LessonStore>;
96
97    /// Who the app is in the audit log.
98    const ACTOR: &str = "app";
99
100    fn failed(e: graphrt_learn::Error) -> GraphrtError {
101        GraphrtError::input(e.to_string())
102    }
103
104    pub(crate) fn install(dir: &str, services: &mut graphrt_core::Services) -> Store {
105        let store = Arc::new(LessonStore::open(dir));
106        services.insert(Arc::clone(&store).into_service());
107        store
108    }
109
110    fn kind_of(kind: LessonKind) -> graphrt_learn::LessonKind {
111        match kind {
112            LessonKind::Preference => graphrt_learn::LessonKind::Preference,
113            LessonKind::Fact => graphrt_learn::LessonKind::Fact,
114            LessonKind::Procedure => graphrt_learn::LessonKind::Procedure,
115            LessonKind::Correction => graphrt_learn::LessonKind::Correction,
116        }
117    }
118
119    fn status_of(status: LessonStatus) -> graphrt_learn::LessonStatus {
120        match status {
121            LessonStatus::Proposed => graphrt_learn::LessonStatus::Proposed,
122            LessonStatus::Approved => graphrt_learn::LessonStatus::Approved,
123            LessonStatus::Rejected => graphrt_learn::LessonStatus::Rejected,
124            LessonStatus::Retired => graphrt_learn::LessonStatus::Retired,
125        }
126    }
127
128    fn info(lesson: graphrt_learn::Lesson) -> LessonInfo {
129        let origin = lesson.origin_sentence();
130        LessonInfo {
131            kind: match lesson.kind {
132                graphrt_learn::LessonKind::Preference => LessonKind::Preference,
133                graphrt_learn::LessonKind::Fact => LessonKind::Fact,
134                graphrt_learn::LessonKind::Procedure => LessonKind::Procedure,
135                graphrt_learn::LessonKind::Correction => LessonKind::Correction,
136            },
137            status: match lesson.status {
138                graphrt_learn::LessonStatus::Proposed => LessonStatus::Proposed,
139                graphrt_learn::LessonStatus::Approved => LessonStatus::Approved,
140                graphrt_learn::LessonStatus::Rejected => LessonStatus::Rejected,
141                graphrt_learn::LessonStatus::Retired => LessonStatus::Retired,
142            },
143            high_risk: lesson.risk == Risk::High,
144            origin,
145            id: lesson.id,
146            agent: lesson.agent,
147            user: lesson.user,
148            text: lesson.text,
149            created_at_ms: lesson.created_at_ms,
150        }
151    }
152
153    pub(crate) fn list(
154        store: &LessonStore,
155        agent: &str,
156        status: Option<LessonStatus>,
157    ) -> Result<Vec<LessonInfo>, GraphrtError> {
158        let filter = LessonFilter { user: UserFilter::Any, status: status.map(status_of) };
159        Ok(store.list(agent, &filter).map_err(failed)?.into_iter().map(info).collect())
160    }
161
162    pub(crate) fn add(
163        store: &LessonStore,
164        agent: String,
165        user: Option<String>,
166        kind: LessonKind,
167        text: String,
168    ) -> Result<LessonInfo, GraphrtError> {
169        // The app names its users (`api/<id>`, as its runs are scoped), or passes a scoped id.
170        let user = user.as_deref().map(graphrt_core::memory::owner_named_user);
171        let new = NewLesson { agent, user, kind: kind_of(kind), text };
172        store.add(new, ACTOR).map(info).map_err(failed)
173    }
174
175    pub(crate) fn propose(store: &LessonStore, proposal: LessonProposal) -> Result<LessonInfo, GraphrtError> {
176        let proposal = Proposal {
177            agent: proposal.agent,
178            subject_user: proposal.user.as_deref().map(graphrt_core::memory::owner_named_user),
179            kind: kind_of(proposal.kind),
180            text: proposal.text,
181            signal: Signal::Feedback,
182            run_id: proposal.run_id,
183            // Scoped as the subject and the app's runs are (`api/<id>`): an
184            // authenticated author of their own run then speaks in their own words.
185            author: proposal.author.as_deref().map(graphrt_core::memory::owner_named_user),
186            author_authenticated: proposal.author_authenticated,
187            evidence: proposal.evidence,
188        };
189        store.propose(proposal).map(info).map_err(failed)
190    }
191
192    pub(crate) fn decide(
193        store: &LessonStore,
194        agent: &str,
195        id: &str,
196        decision: LessonDecision,
197    ) -> Result<LessonInfo, GraphrtError> {
198        let decision = match decision {
199            LessonDecision::Approve => Decision::Approve,
200            LessonDecision::Reject => Decision::Reject,
201            LessonDecision::Retire => Decision::Retire,
202        };
203        store.decide(agent, id, decision, ACTOR).map(info).map_err(failed)
204    }
205
206    pub(crate) fn delete(store: &LessonStore, agent: &str, id: &str) -> Result<(), GraphrtError> {
207        store.delete(agent, id, ACTOR).map_err(failed)
208    }
209}
210
211#[cfg(feature = "learning")]
212pub(crate) use imp::{Store, install};
213
214#[cfg(not(feature = "learning"))]
215pub(crate) type Store = ();
216
217impl Runtime {
218    #[cfg(feature = "learning")]
219    fn lesson_store(&self) -> Result<&Store, GraphrtError> {
220        self.lessons.as_ref().ok_or_else(|| GraphrtError::not_configured("learning", "learning_dir"))
221    }
222}
223
224#[cfg(not(feature = "learning"))]
225macro_rules! without_learning {
226    ($($unused:expr),*) => {{
227        let _ = ($($unused,)*);
228        Err(GraphrtError::unsupported("learning", "learning"))
229    }};
230}
231
232#[uniffi::export]
233impl Runtime {
234    /// The lessons of `agent`, optionally only those in `status`.
235    pub fn list_lessons(&self, agent: String, status: Option<LessonStatus>) -> Result<Vec<LessonInfo>, GraphrtError> {
236        #[cfg(feature = "learning")]
237        {
238            imp::list(self.lesson_store()?, &agent, status)
239        }
240        #[cfg(not(feature = "learning"))]
241        without_learning!(agent, status)
242    }
243
244    /// A lesson the owner wrote; it is approved at once.
245    pub fn add_lesson(
246        &self,
247        agent: String,
248        user: Option<String>,
249        kind: LessonKind,
250        text: String,
251    ) -> Result<LessonInfo, GraphrtError> {
252        #[cfg(feature = "learning")]
253        {
254            imp::add(self.lesson_store()?, agent, user, kind, text)
255        }
256        #[cfg(not(feature = "learning"))]
257        without_learning!(agent, user, kind, text)
258    }
259
260    /// Propose a lesson from feedback on a run. It waits for the owner's decision
261    /// ([`Runtime::decide_lesson`]) before any run uses it.
262    pub fn propose_lesson(&self, proposal: LessonProposal) -> Result<LessonInfo, GraphrtError> {
263        #[cfg(feature = "learning")]
264        {
265            imp::propose(self.lesson_store()?, proposal)
266        }
267        #[cfg(not(feature = "learning"))]
268        without_learning!(proposal)
269    }
270
271    /// Approve, reject or retire a lesson.
272    pub fn decide_lesson(
273        &self,
274        agent: String,
275        id: String,
276        decision: LessonDecision,
277    ) -> Result<LessonInfo, GraphrtError> {
278        #[cfg(feature = "learning")]
279        {
280            imp::decide(self.lesson_store()?, &agent, &id, decision)
281        }
282        #[cfg(not(feature = "learning"))]
283        without_learning!(agent, id, decision)
284    }
285
286    /// Delete a lesson for good.
287    pub fn delete_lesson(&self, agent: String, id: String) -> Result<(), GraphrtError> {
288        #[cfg(feature = "learning")]
289        {
290            imp::delete(self.lesson_store()?, &agent, &id)
291        }
292        #[cfg(not(feature = "learning"))]
293        without_learning!(agent, id)
294    }
295}