cognis 0.2.1

LLM application framework built on cognis-core
Documentation
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::sync::Arc;

use async_trait::async_trait;
use regex::Regex;
use serde_json::{json, Value};

use cognis_core::error::{CognisError, Result};
use cognis_core::language_models::chat_model::BaseChatModel;
use cognis_core::messages::{HumanMessage, Message};
use cognis_core::output_parsers::base::OutputParser;
use cognis_core::output_parsers::json::JsonOutputParser;
use cognis_core::runnables::base::Runnable;
use cognis_core::runnables::config::RunnableConfig;

/// A chain that wraps a chat model and a JSON output parser to produce
/// structured (typed) output conforming to a given JSON schema.
///
/// The chain:
/// 1. Formats the user's prompt template with input variables
/// 2. Appends format instructions derived from the JSON schema
/// 3. Sends the combined prompt to the chat model
/// 4. Parses the model's text response through [`JsonOutputParser`]
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use serde_json::json;
/// use cognis::chains::structured_output::StructuredOutputChain;
/// use cognis_core::language_models::fake::FakeListChatModel;
/// use cognis_core::runnables::base::Runnable;
///
/// # async fn example() {
/// let model = Arc::new(FakeListChatModel::new(vec![
///     r#"{"name": "Alice", "age": 30}"#.to_string(),
/// ]));
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "name": { "type": "string" },
///         "age": { "type": "integer" }
///     },
///     "required": ["name", "age"]
/// });
///
/// let chain = StructuredOutputChain::builder()
///     .model(model)
///     .schema(schema)
///     .prompt("Extract person info from: {text}")
///     .build();
///
/// let result = chain
///     .invoke(json!({"text": "Alice is 30 years old"}), None)
///     .await
///     .unwrap();
///
/// assert_eq!(result["name"], "Alice");
/// assert_eq!(result["age"], 30);
/// # }
/// ```
pub struct StructuredOutputChain {
    model: Arc<dyn BaseChatModel>,
    parser: JsonOutputParser,
    prompt_template: String,
    output_key: Option<String>,
}

/// Builder for [`StructuredOutputChain`].
pub struct StructuredOutputChainBuilder {
    model: Option<Arc<dyn BaseChatModel>>,
    schema: Option<Value>,
    prompt_template: Option<String>,
    output_key: Option<String>,
}

impl StructuredOutputChainBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            model: None,
            schema: None,
            prompt_template: None,
            output_key: None,
        }
    }

    /// Set the chat model (required).
    pub fn model(mut self, model: Arc<dyn BaseChatModel>) -> Self {
        self.model = Some(model);
        self
    }

    /// Set the JSON schema describing the expected output shape (required).
    ///
    /// The schema is used both to generate format instructions appended to
    /// the prompt and to validate the model's response structure.
    pub fn schema(mut self, schema: Value) -> Self {
        self.schema = Some(schema);
        self
    }

    /// Set the prompt template with `{variable}` placeholders (required).
    ///
    /// Format instructions will be automatically appended after the template
    /// text when invoking the chain.
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt_template = Some(prompt.into());
        self
    }

    /// Set an optional output key. When set, the parsed JSON is wrapped in
    /// `{ output_key: <parsed> }`. When `None` (the default), the parsed
    /// JSON value is returned directly.
    pub fn output_key(mut self, key: impl Into<String>) -> Self {
        self.output_key = Some(key.into());
        self
    }

    /// Build the [`StructuredOutputChain`].
    ///
    /// # Panics
    ///
    /// Panics if `model`, `schema`, or `prompt` have not been set.
    pub fn build(self) -> StructuredOutputChain {
        let schema = self
            .schema
            .expect("schema is required for StructuredOutputChain");
        StructuredOutputChain {
            model: self
                .model
                .expect("model is required for StructuredOutputChain"),
            parser: JsonOutputParser::with_schema(schema),
            prompt_template: self
                .prompt_template
                .expect("prompt is required for StructuredOutputChain"),
            output_key: self.output_key,
        }
    }
}

impl Default for StructuredOutputChainBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl StructuredOutputChain {
    /// Create a new builder.
    pub fn builder() -> StructuredOutputChainBuilder {
        StructuredOutputChainBuilder::new()
    }

    /// Return the JSON schema used for this chain.
    pub fn schema(&self) -> Option<&Value> {
        self.parser.schema.as_ref()
    }

    /// Return the format instructions that will be appended to the prompt.
    pub fn format_instructions(&self) -> Option<String> {
        self.parser.get_format_instructions()
    }

    /// Format the prompt template by replacing `{variable}` placeholders with
    /// values from the input JSON object, then append format instructions.
    fn format_prompt(&self, input: &Value) -> Result<String> {
        let re = Regex::new(r"\{(\w+)\}").unwrap();
        let obj = input.as_object().ok_or_else(|| CognisError::TypeMismatch {
            expected: "JSON object".into(),
            got: format!("{}", input),
        })?;

        let mut missing: Vec<String> = Vec::new();
        let result = re.replace_all(&self.prompt_template, |caps: &regex::Captures| {
            let key = &caps[1];
            match obj.get(key) {
                Some(Value::String(s)) => s.clone(),
                Some(v) => v.to_string(),
                None => {
                    missing.push(key.to_string());
                    String::new()
                }
            }
        });

        if !missing.is_empty() {
            return Err(CognisError::InvalidKey(format!(
                "Missing input variable(s): {}",
                missing.join(", ")
            )));
        }

        let mut prompt = result.into_owned();

        // Append format instructions from the parser
        if let Some(instructions) = self.parser.get_format_instructions() {
            prompt.push_str("\n\n");
            prompt.push_str(&instructions);
        }

        Ok(prompt)
    }
}

#[async_trait]
impl Runnable for StructuredOutputChain {
    fn name(&self) -> &str {
        "StructuredOutputChain"
    }

    async fn invoke(&self, input: Value, _config: Option<&RunnableConfig>) -> Result<Value> {
        // 1. Format prompt with variables and schema instructions
        let formatted = self.format_prompt(&input)?;

        // 2. Send to the chat model
        let messages = vec![Message::Human(HumanMessage::new(&formatted))];
        let ai_msg = self.model.invoke_messages(&messages, None).await?;
        let text = ai_msg.base.content.text();

        // 3. Parse through JSON output parser
        let parsed = self.parser.parse(&text)?;

        // 4. Wrap in output key if specified
        match &self.output_key {
            Some(key) => Ok(json!({ key: parsed })),
            None => Ok(parsed),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cognis_core::language_models::fake::{FakeListChatModel, GenericFakeChatModel};
    use cognis_core::messages::AIMessage;

    fn fake_model(responses: Vec<&str>) -> Arc<dyn BaseChatModel> {
        Arc::new(FakeListChatModel::new(
            responses.into_iter().map(String::from).collect(),
        ))
    }

    fn person_schema() -> Value {
        json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "integer" }
            },
            "required": ["name", "age"]
        })
    }

    #[tokio::test]
    async fn test_basic_structured_output() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "Alice", "age": 30}"#]))
            .schema(person_schema())
            .prompt("Extract person info from: {text}")
            .build();

        let result = chain
            .invoke(json!({"text": "Alice is 30 years old"}), None)
            .await
            .unwrap();

        assert_eq!(result["name"], "Alice");
        assert_eq!(result["age"], 30);
    }

    #[tokio::test]
    async fn test_structured_output_with_output_key() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "Bob", "age": 25}"#]))
            .schema(person_schema())
            .prompt("Extract: {text}")
            .output_key("person")
            .build();

        let result = chain
            .invoke(json!({"text": "Bob is 25"}), None)
            .await
            .unwrap();

        assert_eq!(result["person"]["name"], "Bob");
        assert_eq!(result["person"]["age"], 25);
    }

    #[tokio::test]
    async fn test_structured_output_with_markdown_fences() {
        let response = "```json\n{\"name\": \"Carol\", \"age\": 40}\n```";
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![response]))
            .schema(person_schema())
            .prompt("Extract: {text}")
            .build();

        let result = chain
            .invoke(json!({"text": "Carol is 40"}), None)
            .await
            .unwrap();

        assert_eq!(result["name"], "Carol");
        assert_eq!(result["age"], 40);
    }

    #[tokio::test]
    async fn test_structured_output_invalid_json_error() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec!["this is not json"]))
            .schema(person_schema())
            .prompt("Extract: {text}")
            .build();

        let result = chain.invoke(json!({"text": "something"}), None).await;

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Failed to parse JSON"),
            "Expected JSON parse error, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_structured_output_missing_variable() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "X", "age": 1}"#]))
            .schema(person_schema())
            .prompt("Extract from {text} in {language}")
            .build();

        let result = chain.invoke(json!({"text": "something"}), None).await;

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("language"),
            "Error should mention missing variable: {err}"
        );
    }

    #[tokio::test]
    async fn test_structured_output_complex_schema() {
        let schema = json!({
            "type": "object",
            "properties": {
                "title": { "type": "string" },
                "tags": {
                    "type": "array",
                    "items": { "type": "string" }
                },
                "metadata": {
                    "type": "object",
                    "properties": {
                        "source": { "type": "string" },
                        "confidence": { "type": "number" }
                    }
                }
            },
            "required": ["title", "tags"]
        });

        let response = r#"{"title": "Rust Guide", "tags": ["rust", "programming"], "metadata": {"source": "web", "confidence": 0.95}}"#;
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![response]))
            .schema(schema)
            .prompt("Analyze: {input}")
            .build();

        let result = chain
            .invoke(json!({"input": "A guide about Rust programming"}), None)
            .await
            .unwrap();

        assert_eq!(result["title"], "Rust Guide");
        assert_eq!(result["tags"][0], "rust");
        assert_eq!(result["tags"][1], "programming");
        assert_eq!(result["metadata"]["confidence"], 0.95);
    }

    #[tokio::test]
    async fn test_structured_output_with_generic_fake_model() {
        let model = Arc::new(GenericFakeChatModel::from_messages(vec![AIMessage::new(
            r#"{"name": "Dave", "age": 35}"#,
        )]));

        let chain = StructuredOutputChain::builder()
            .model(model)
            .schema(person_schema())
            .prompt("Extract: {text}")
            .build();

        let result = chain
            .invoke(json!({"text": "Dave is 35"}), None)
            .await
            .unwrap();

        assert_eq!(result["name"], "Dave");
        assert_eq!(result["age"], 35);
    }

    #[tokio::test]
    async fn test_structured_output_as_runnable() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "Eve", "age": 28}"#]))
            .schema(person_schema())
            .prompt("Extract: {text}")
            .build();

        let runnable: &dyn Runnable = &chain;
        assert_eq!(runnable.name(), "StructuredOutputChain");

        let result = runnable
            .invoke(json!({"text": "Eve is 28"}), None)
            .await
            .unwrap();

        assert_eq!(result["name"], "Eve");
        assert_eq!(result["age"], 28);
    }

    #[tokio::test]
    async fn test_format_instructions_included() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "X", "age": 1}"#]))
            .schema(person_schema())
            .prompt("Extract: {text}")
            .build();

        let instructions = chain.format_instructions();
        assert!(instructions.is_some());
        let instructions = instructions.unwrap();
        assert!(instructions.contains("JSON"));
        assert!(instructions.contains("schema"));
    }

    #[tokio::test]
    async fn test_schema_accessor() {
        let schema = person_schema();
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{}"#]))
            .schema(schema.clone())
            .prompt("test {x}")
            .build();

        assert_eq!(chain.schema(), Some(&schema));
    }

    #[tokio::test]
    async fn test_structured_output_multiple_variables() {
        let chain = StructuredOutputChain::builder()
            .model(fake_model(vec![r#"{"name": "Frank", "age": 50}"#]))
            .schema(person_schema())
            .prompt("Extract {entity_type} from: {text}")
            .build();

        let result = chain
            .invoke(
                json!({"entity_type": "person", "text": "Frank is 50 years old"}),
                None,
            )
            .await
            .unwrap();

        assert_eq!(result["name"], "Frank");
        assert_eq!(result["age"], 50);
    }
}