Skip to main content

graphrt_core/
learning.rs

1//! Lesson contract between a lesson store and the nodes that learn.
2//!
3//! A lesson is one short statement an agent learned from earlier work: a
4//! preference, a fact, a procedure or a correction. This module holds only
5//! the contract. A host registers a [`Lessons`] service (for example the store
6//! of the `graphrt-learn` crate) and the `agent` node asks it for the notes of
7//! one [`LessonScope`] when a run starts.
8//!
9//! A source returns only lessons that were approved, and only those of the
10//! scope it is asked for: the lessons of the agent as a whole plus the lessons
11//! of the one user the run is for. Nothing here writes a lesson. Learning
12//! happens outside the run.
13
14use std::fmt;
15use std::sync::Arc;
16
17use futures::future::BoxFuture;
18
19/// Whose lessons a run reads.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct LessonScope {
22    /// The agent the lessons belong to.
23    pub agent: String,
24    /// The user the run is for. `None` reads only the lessons of the agent as a whole.
25    pub user: Option<String>,
26}
27
28/// The approved lessons of one scope, ready for a system prompt.
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
30pub struct LessonNotes {
31    /// The notes section, or an empty string when there is nothing to add.
32    pub text: String,
33    /// Ids of the lessons in `text`, in order.
34    pub ids: Vec<String>,
35}
36
37impl LessonNotes {
38    /// Whether there is nothing to add to the prompt.
39    pub fn is_empty(&self) -> bool {
40        self.text.is_empty()
41    }
42}
43
44/// The lessons of a scope could not be read.
45#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
46#[error("{message}")]
47pub struct LearningError {
48    /// Stable error kind, for example `learning_store`.
49    pub kind: &'static str,
50    /// What went wrong, safe to show to the owner.
51    pub message: String,
52}
53
54impl LearningError {
55    /// An error of `kind` with `message`.
56    pub fn new(kind: &'static str, message: impl Into<String>) -> Self {
57        Self { kind, message: message.into() }
58    }
59}
60
61/// A source of approved lessons.
62pub trait LessonSource: Send + Sync + fmt::Debug {
63    /// The approved lessons `scope` may read.
64    fn notes<'a>(&'a self, scope: &'a LessonScope) -> BoxFuture<'a, Result<LessonNotes, LearningError>>;
65}
66
67/// Service registered in [`crate::node::Services`]: where nodes find lessons.
68#[derive(Clone, Debug)]
69pub struct Lessons(pub Arc<dyn LessonSource>);
70
71impl Lessons {
72    /// Wrap a lesson source as a service.
73    pub fn new(source: Arc<dyn LessonSource>) -> Self {
74        Self(source)
75    }
76}