swiftide_query/answers/
simple.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
//! Generate an answer based on the current query
use std::sync::Arc;
use swiftide_core::{
    document::Document,
    indexing::SimplePrompt,
    prelude::*,
    querying::{states, Query},
    template::Template,
    Answer,
};

/// Generate an answer based on the current query
///
/// For most general purposes, this transformer should provide a sensible default. It takes either
/// a transformation that has already been applied to the documents (in `Query::current`), or the documents themselves,
/// and will then feed them as context with the _original_ question to an llm to generate an
/// answer.
///
/// Optionally, a custom document template can be provided to render the documents in a specific way.
#[derive(Debug, Clone, Builder)]
pub struct Simple {
    #[builder(setter(custom))]
    client: Arc<dyn SimplePrompt>,
    #[builder(default = "default_prompt()")]
    prompt_template: Template,
    #[builder(default, setter(into, strip_option))]
    document_template: Option<Template>,
}

impl Simple {
    pub fn builder() -> SimpleBuilder {
        SimpleBuilder::default()
    }

    /// Builds a new simple answer generator from a client that implements [`SimplePrompt`].
    ///
    /// # Panics
    ///
    /// Panics if the build failed
    pub fn from_client(client: impl SimplePrompt + 'static) -> Simple {
        SimpleBuilder::default()
            .client(client)
            .to_owned()
            .build()
            .expect("Failed to build Simple")
    }
}

impl SimpleBuilder {
    pub fn client(&mut self, client: impl SimplePrompt + 'static) -> &mut Self {
        self.client = Some(Arc::new(client) as Arc<dyn SimplePrompt>);
        self
    }
}

fn default_prompt() -> Template {
    indoc::indoc! {"
    Answer the following question based on the context provided:
    {{ question }}

    ## Constraints
    * Do not include any information that is not in the provided context.
    * If the question cannot be answered by the provided context, state that it cannot be answered.
    * Answer the question completely and format it as markdown.

    ## Context

    ---
    {{ documents }}
    ---
    "}
    .into()
}

#[async_trait]
impl Answer for Simple {
    #[tracing::instrument(skip_all)]
    async fn answer(&self, query: Query<states::Retrieved>) -> Result<Query<states::Answered>> {
        let mut context = tera::Context::new();

        context.insert("question", query.original());

        let documents = if !query.current().is_empty() {
            query.current().to_string()
        } else if let Some(template) = &self.document_template {
            let mut rendered_documents = Vec::new();
            for document in query.documents() {
                let rendered = template
                    .render(&tera::Context::from_serialize(document)?)
                    .await?;
                rendered_documents.push(rendered);
            }

            rendered_documents.join("\n---\n")
        } else {
            query
                .documents()
                .iter()
                .map(Document::content)
                .collect::<Vec<_>>()
                .join("\n---\n")
        };
        context.insert("documents", &documents);

        let answer = self
            .client
            .prompt(self.prompt_template.to_prompt().with_context(context))
            .await?;

        Ok(query.answered(answer))
    }
}

#[cfg(test)]
mod test {
    use std::sync::Mutex;

    use insta::assert_snapshot;
    use swiftide_core::{indexing::Metadata, MockSimplePrompt};

    use super::*;

    assert_default_prompt_snapshot!("question" => "What is love?", "documents" => "My context");

    #[tokio::test]
    async fn test_uses_current_if_present() {
        let mut mock_client = MockSimplePrompt::new();

        // I'll buy a beer for the first person who can think of a less insane way to do this
        let received_prompt = Arc::new(Mutex::new(None));
        let cloned = received_prompt.clone();
        mock_client
            .expect_prompt()
            .withf(move |prompt| {
                cloned.lock().unwrap().replace(prompt.clone());
                true
            })
            .once()
            .returning(|_| Ok(String::default()));

        let documents = vec![
            Document::new("First document", Some(Metadata::from(("some", "metadata")))),
            Document::new(
                "Second document",
                Some(Metadata::from(("other", "metadata"))),
            ),
        ];
        let query: Query<states::Retrieved> = Query::builder()
            .original("original")
            .current("A fictional generated summary")
            .state(states::Retrieved)
            .documents(documents)
            .build()
            .unwrap();

        let transformer = Simple::builder().client(mock_client).build().unwrap();

        transformer.answer(query).await.unwrap();

        let received_prompt = received_prompt.lock().unwrap().take().unwrap();
        let rendered = received_prompt.render().await.unwrap();
        assert_snapshot!(rendered);
    }

    #[tokio::test]
    async fn test_custom_document_template() {
        let mut mock_client = MockSimplePrompt::new();

        // I'll buy a beer for the first person who can think of a less insane way to do this
        let received_prompt = Arc::new(Mutex::new(None));
        let cloned = received_prompt.clone();
        mock_client
            .expect_prompt()
            .withf(move |prompt| {
                cloned.lock().unwrap().replace(prompt.clone());
                true
            })
            .once()
            .returning(|_| Ok(String::default()));

        let documents = vec![
            Document::new("First document", Some(Metadata::from(("some", "metadata")))),
            Document::new(
                "Second document",
                Some(Metadata::from(("other", "metadata"))),
            ),
        ];
        let query: Query<states::Retrieved> = Query::builder()
            .original("original")
            .current(String::default())
            .state(states::Retrieved)
            .documents(documents)
            .build()
            .unwrap();

        let transformer = Simple::builder()
            .client(mock_client)
            .document_template(indoc::indoc! {"
                {% for key, value in metadata -%}
                    {{ key }}: {{ value }}
                {% endfor -%}

                {{ content }}"})
            .build()
            .unwrap();

        transformer.answer(query).await.unwrap();

        let received_prompt = received_prompt.lock().unwrap().take().unwrap();
        let rendered = received_prompt.render().await.unwrap();
        assert_snapshot!(rendered);
    }
}