Skip to main content

langchain_rust/prompt/
mod.rs

1mod chat;
2mod error;
3mod example_selector;
4mod few_shot;
5#[cfg(test)]
6mod few_shot_tests;
7mod prompt;
8
9use std::collections::HashMap;
10
11pub use chat::*;
12pub use error::*;
13pub use example_selector::*;
14pub use few_shot::*;
15pub use prompt::*;
16use serde_json::Value;
17
18use crate::schemas::{messages::Message, prompt::PromptValue};
19
20// pub type PromptArgs<'a> = HashMap<&'a str, &'a str>;
21pub type PromptArgs = HashMap<String, Value>;
22pub trait PromptFromatter: Send + Sync {
23    fn template(&self) -> String;
24    fn variables(&self) -> Vec<String>;
25    fn format(&self, input_variables: PromptArgs) -> Result<String, PromptError>;
26}
27impl<PA> From<PA> for Box<dyn PromptFromatter>
28where
29    PA: PromptFromatter + 'static,
30{
31    fn from(prompt: PA) -> Self {
32        Box::new(prompt)
33    }
34}
35
36/// Represents a generic template for formatting messages.
37pub trait MessageFormatter: Send + Sync {
38    fn format_messages(&self, input_variables: PromptArgs) -> Result<Vec<Message>, PromptError>;
39
40    /// Returns a list of required input variable names for the template.
41    fn input_variables(&self) -> Vec<String>;
42}
43impl<MF> From<MF> for Box<dyn MessageFormatter>
44where
45    MF: MessageFormatter + 'static,
46{
47    fn from(prompt: MF) -> Self {
48        Box::new(prompt)
49    }
50}
51
52#[async_trait::async_trait]
53pub trait FormatPrompter: Send + Sync {
54    fn format_prompt(&self, input_variables: PromptArgs) -> Result<PromptValue, PromptError>;
55    fn get_input_variables(&self) -> Vec<String>;
56
57    /// Formats the prompt, for prompts that need async work to do it (e.g. a
58    /// [`FewShotPromptTemplate`] choosing examples by embedding similarity). Chains call
59    /// this one. Defaults to [`format_prompt`](Self::format_prompt).
60    async fn format_prompt_async(
61        &self,
62        input_variables: PromptArgs,
63    ) -> Result<PromptValue, PromptError> {
64        self.format_prompt(input_variables)
65    }
66}
67impl<FP> From<FP> for Box<dyn FormatPrompter>
68where
69    FP: FormatPrompter + 'static,
70{
71    fn from(prompt: FP) -> Self {
72        Box::new(prompt)
73    }
74}