dynamo_llm/preprocessor/prompt/template/
context.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::{ContextMixins, PromptContextMixin};
17
18use chrono::{DateTime, Utc};
19use minijinja::value::{Object, Value};
20use std::sync::Arc;
21
22impl Object for ContextMixins {
23    fn get_value(self: &Arc<Self>, field: &Value) -> Option<Value> {
24        match field.as_str()? {
25            "datetime" => self.datetime(),
26            _ => None,
27        }
28    }
29}
30
31impl ContextMixins {
32    pub fn new(allowed_mixins: &[PromptContextMixin]) -> Self {
33        ContextMixins {
34            context_mixins: allowed_mixins.iter().cloned().collect(),
35        }
36    }
37
38    /// Implements the `datetime` context mixin.
39    /// Different mixins can be implemented here for the same key.
40    /// We need to valiate that multiple mixins do not conflict with each other.
41    fn datetime(&self) -> Option<Value> {
42        if self
43            .context_mixins
44            .contains(&PromptContextMixin::Llama3DateTime)
45        {
46            let now = chrono::Utc::now();
47            Some(Value::from(llama3_datetime(now)))
48        } else {
49            None
50        }
51    }
52}
53
54fn llama3_datetime(datetime: DateTime<Utc>) -> String {
55    datetime.format("%d, %B, %Y").to_string()
56}