swiftide_indexing/transformers/
metadata_summary.rs

1//! Generate a summary and adds it as metadata
2//! This module defines the `MetadataSummary` struct and its associated methods,
3//! which are used for generating metadata in the form of a summary
4//! for a given text. It interacts with a client (e.g., `OpenAI`) to generate
5//! the summary based on the text chunk in an `Node`.
6
7use anyhow::Result;
8use async_trait::async_trait;
9use swiftide_core::{Transformer, indexing::Node};
10
11/// `MetadataSummary` is responsible for generating a summary
12/// for a given text chunk. It uses a templated prompt to interact with a client
13/// that implements the `SimplePrompt` trait.
14#[swiftide_macros::indexing_transformer(
15    metadata_field_name = "Summary",
16    default_prompt_file = "prompts/metadata_summary.prompt.md"
17)]
18pub struct MetadataSummary {}
19
20#[async_trait]
21impl Transformer for MetadataSummary {
22    /// Transforms an `Node` by extracting a summary
23    /// based on the text chunk within the node.
24    ///
25    /// # Arguments
26    ///
27    /// * `node` - The `Node` containing the text chunk to process.
28    ///
29    /// # Returns
30    ///
31    /// A `Result` containing the transformed `Node` with added metadata,
32    /// or an error if the transformation fails.
33    ///
34    /// # Errors
35    ///
36    /// This function will return an error if the client fails to generate
37    /// a summary from the provided prompt.
38    #[tracing::instrument(skip_all, name = "transformers.metadata_summary")]
39    async fn transform_node(&self, mut node: Node) -> Result<Node> {
40        let prompt = self.prompt_template.clone().with_node(&node);
41
42        let response = self.prompt(prompt).await?;
43
44        node.metadata.insert(NAME, response);
45
46        Ok(node)
47    }
48
49    fn concurrency(&self) -> Option<usize> {
50        self.concurrency
51    }
52}
53
54#[cfg(test)]
55mod test {
56    use swiftide_core::MockSimplePrompt;
57
58    use super::*;
59
60    #[tokio::test]
61    async fn test_template() {
62        let template = default_prompt();
63
64        let prompt = template.clone().with_node(&Node::new("test"));
65        insta::assert_snapshot!(prompt.render().unwrap());
66    }
67
68    #[tokio::test]
69    async fn test_metadata_summary() {
70        let mut client = MockSimplePrompt::new();
71
72        client
73            .expect_prompt()
74            .returning(|_| Ok("A Summary".to_string()));
75
76        let transformer = MetadataSummary::builder().client(client).build().unwrap();
77        let node = Node::new("Some text");
78
79        let result = transformer.transform_node(node).await.unwrap();
80
81        assert_eq!(result.metadata.get("Summary").unwrap(), "A Summary");
82    }
83}