Skip to main content

langfuse/prompts/
chat.rs

1//! Chat prompt client with `{{variable}}` template compilation across messages.
2
3use std::collections::HashMap;
4
5use langfuse_core::error::LangfuseError;
6use langfuse_core::types::ChatMessage;
7
8use crate::prompts::text::compile_template;
9
10/// A compiled chat prompt. Holds a list of messages with `{{variable}}` support.
11#[derive(Debug, Clone)]
12pub struct ChatPromptClient {
13    /// Prompt name.
14    pub name: String,
15    /// Prompt version.
16    pub version: i32,
17    /// Chat messages, each potentially containing `{{variable}}` placeholders in `content`.
18    pub messages: Vec<ChatMessage>,
19    /// Arbitrary configuration attached to the prompt.
20    pub config: serde_json::Value,
21    /// Labels associated with this prompt version.
22    pub labels: Vec<String>,
23    /// Tags for categorisation.
24    pub tags: Vec<String>,
25    /// Whether this prompt was served from an expired cache entry (fallback).
26    pub is_fallback: bool,
27}
28
29impl ChatPromptClient {
30    /// Compile all messages by replacing `{{variable}}` placeholders in each message's content.
31    ///
32    /// Returns [`LangfuseError::PromptCompilation`] if any message references a variable
33    /// that is not present in the map.
34    pub fn compile(
35        &self,
36        variables: &HashMap<String, String>,
37    ) -> Result<Vec<ChatMessage>, LangfuseError> {
38        self.messages
39            .iter()
40            .map(|msg| {
41                let compiled_content = compile_template(&msg.content, variables)?;
42                Ok(ChatMessage {
43                    role: msg.role.clone(),
44                    content: compiled_content,
45                })
46            })
47            .collect()
48    }
49}