langchain-rust 7.0.0

LangChain for Rust, the easiest way to write LLM-based programs in Rust
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
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use futures::StreamExt;
use serde_json::json;

use super::{chain::parse_destination, *};
use crate::{
    chain::{Chain, ChainError, LLMChainBuilder},
    language_models::{GenerateResult, LLMEvent, TokenUsage},
    prompt::{HumanMessagePromptTemplate, PromptArgs},
    prompt_args,
    schemas::MessageType,
    template_fstring,
    test_utils::FakeLLM,
};

/// A destination that records its input and answers `"{name}: {input}"`.
#[derive(Clone)]
struct Spy {
    name: &'static str,
    seen: Arc<Mutex<Vec<PromptArgs>>>,
}

impl Spy {
    fn new(name: &'static str) -> Self {
        Self {
            name,
            seen: Default::default(),
        }
    }
    fn calls(&self) -> Vec<PromptArgs> {
        self.seen.lock().unwrap().clone()
    }
}

#[async_trait]
impl Chain for Spy {
    async fn call(&self, input: PromptArgs) -> Result<GenerateResult, ChainError> {
        let text = format!("{}: {}", self.name, input["input"].as_str().unwrap_or(""));
        self.seen.lock().unwrap().push(input);
        Ok(GenerateResult {
            generation: text,
            tokens: Some(TokenUsage::new(10, 5)),
            ..Default::default()
        })
    }
}

fn router(llm: FakeLLM, physics: &Spy, math: &Spy, default: Option<&Spy>) -> RouterChain {
    let mut builder = RouterChainBuilder::new()
        .llm(llm)
        .destination("physics", "Questions about physics", physics.clone())
        .destination(" math ", " Math problems ", math.clone());
    if let Some(default) = default {
        builder = builder.default_chain(default.clone());
    }
    builder.build().unwrap()
}

#[test]
fn parses_the_destination() {
    assert_eq!(parse_destination(r#"{"destination": "math"}"#), "math");
    assert_eq!(
        parse_destination("```json\n{\"destination\": \" physics \"}\n```"),
        "physics"
    );
    assert_eq!(
        parse_destination(
            "Sure! {\"destination\": \"DEFAULT\", \"why\": \"none fit\"} hope it helps"
        ),
        "DEFAULT"
    );
    assert_eq!(parse_destination("  \"math\". "), "math");
    assert_eq!(parse_destination("`physics`"), "physics");
    assert_eq!(
        parse_destination(r#"{"destination": "math", "why": {"confidence": 0.9}}"#),
        "math",
        "nested objects"
    );
    // Not the JSON we asked for: fall back to the raw answer.
    assert_eq!(
        parse_destination(r#"{"route": "math"}"#),
        r#"{"route": "math"}"#
    );
    assert_eq!(parse_destination("} math {"), "} math {");
    assert_eq!(
        parse_destination(r#"{"destination": 3}"#),
        r#"{"destination": 3}"#
    );
}

#[tokio::test]
async fn routes_to_the_chosen_destination_with_the_full_input() {
    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    let llm = FakeLLM::new([r#"{"destination": "MATH"}"#]);
    let chain = router(llm.clone(), &physics, &math, None);

    let result = chain
        .call(prompt_args! { "input" => "2 + 2?", "lang" => "es" })
        .await
        .unwrap();
    assert_eq!(result.generation, "math: 2 + 2?");
    // Destination tokens (10/5) + routing call (1/1).
    assert_eq!(result.tokens, Some(TokenUsage::new(11, 6)));
    assert!(physics.calls().is_empty());
    let seen = math.calls();
    assert_eq!(seen.len(), 1);
    assert_eq!(seen[0]["lang"], "es", "every input is forwarded");
    assert_eq!(seen[0]["input"], "2 + 2?");

    // The router prompt lists every destination, trimmed, and the input goes as is.
    let calls = llm.calls();
    assert_eq!(calls.len(), 1);
    let [system, human] = &calls[0][..] else {
        panic!("{:?}", calls[0])
    };
    assert_eq!(system.message_type, MessageType::SystemMessage);
    assert!(
        system
            .content
            .contains("physics: Questions about physics\nmath: Math problems\n"),
        "{}",
        system.content
    );
    assert!(system.content.contains("DEFAULT"), "{}", system.content);
    assert_eq!(human.message_type, MessageType::HumanMessage);
    assert_eq!(human.content, "2 + 2?");
}

#[tokio::test]
async fn default_and_unknown_answers_use_the_default_chain() {
    for answer in [r#"{"destination": "DEFAULT"}"#, "default", "chemistry"] {
        let (physics, math, general) = (Spy::new("physics"), Spy::new("math"), Spy::new("general"));
        let chain = router(FakeLLM::new([answer]), &physics, &math, Some(&general));
        let result = chain
            .call(prompt_args! { "input" => "hello" })
            .await
            .unwrap();
        assert_eq!(result.generation, "general: hello", "{answer}");
        assert_eq!(general.calls().len(), 1);
        assert!(physics.calls().is_empty() && math.calls().is_empty());
    }
}

#[tokio::test]
async fn without_a_default_unroutable_inputs_fail() {
    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    let chain = router(FakeLLM::new(["chemistry"]), &physics, &math, None);
    let err = chain
        .call(prompt_args! { "input" => "x" })
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("\"chemistry\""), "{err}");
    assert!(err.contains("[\"physics\", \"math\"]"), "{err}");

    let chain = router(FakeLLM::new(["DEFAULT", "DEFAULT"]), &physics, &math, None);
    // Answering DEFAULT is a valid decision even without a default chain...
    assert_eq!(
        chain
            .route(&prompt_args! { "input" => "x" })
            .await
            .unwrap()
            .destination,
        None
    );
    // ...but there's nothing to run.
    let err = chain
        .call(prompt_args! { "input" => "x" })
        .await
        .unwrap_err()
        .to_string();
    assert_eq!(
        err,
        "Error: no destination fits and there is no default chain"
    );
    assert!(physics.calls().is_empty() && math.calls().is_empty());
}

#[tokio::test]
async fn route_only_decides() {
    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    let chain = router(
        FakeLLM::new([r#"{"destination": "physics"}"#, "DEFAULT"]),
        &physics,
        &math,
        Some(&Spy::new("general")),
    );
    let input = prompt_args! { "input" => "gravity?" };
    assert_eq!(
        chain.route(&input).await.unwrap(),
        Route {
            destination: Some("physics".into()),
            tokens: Some(TokenUsage::new(1, 1)),
        }
    );
    assert_eq!(chain.route(&input).await.unwrap().destination, None);
    assert!(physics.calls().is_empty(), "route doesn't run the chain");
}

#[tokio::test]
async fn errors_are_returned() {
    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    // Missing input: fails before calling the LLM.
    let llm = FakeLLM::new(["math"]);
    let chain = router(llm.clone(), &physics, &math, None);
    let err = chain
        .call(prompt_args! { "question" => "x" })
        .await
        .unwrap_err();
    assert!(
        matches!(err, ChainError::MissingInputVariable(ref k) if k == "input"),
        "{err}"
    );
    assert!(llm.calls().is_empty());

    // LLM failure.
    let chain = router(FakeLLM::default(), &physics, &math, None);
    let err = chain
        .call(prompt_args! { "input" => "x" })
        .await
        .unwrap_err();
    assert!(matches!(err, ChainError::LLMError(_)), "{err}");

    // Destination failure.
    let chain = RouterChainBuilder::new()
        .llm(FakeLLM::new(["bad"]))
        .destination("bad", "always fails", greet_chain(FakeLLM::default()))
        .build()
        .unwrap();
    let err = chain
        .call(prompt_args! { "input" => "x", "name" => "a" })
        .await
        .unwrap_err();
    assert!(matches!(err, ChainError::LLMError(_)), "{err}");
}

#[tokio::test]
async fn custom_input_and_output_keys() {
    let llm = FakeLLM::new([r#"{"destination": "greet"}"#, "greet"]);
    let chain = RouterChainBuilder::new()
        .llm(llm.clone())
        .destination(
            "greet",
            "Greets people",
            greet_chain(FakeLLM::new(["hi a", "hi b"])),
        )
        .input_key("name")
        .output_key("answer")
        .build()
        .unwrap();
    assert_eq!(chain.get_input_keys(), ["name"]);
    assert_eq!(
        chain.get_output_keys(),
        ["answer", "generate_result", "destination"]
    );

    let output = chain.execute(prompt_args! { "name" => "a" }).await.unwrap();
    assert_eq!(output["answer"], "hi a");
    assert_eq!(output["destination"], "greet");
    assert_eq!(
        output["output"], "hi a",
        "the destination's own outputs are kept"
    );
    let result: GenerateResult = serde_json::from_value(output["generate_result"].clone()).unwrap();
    assert_eq!(result.generation, "hi a");
    assert_eq!(result.tokens, Some(TokenUsage::new(2, 2)));
    assert_eq!(llm.calls()[0][1].content, "a");

    let answer = chain.invoke(prompt_args! { "name" => "b" }).await.unwrap();
    assert_eq!(answer, "hi b");
}

#[tokio::test]
async fn execute_reports_the_default_destination() {
    let (physics, math, general) = (Spy::new("physics"), Spy::new("math"), Spy::new("general"));
    let chain = router(FakeLLM::new(["DEFAULT"]), &physics, &math, Some(&general));
    let output = chain
        .execute(prompt_args! { "input" => "hey" })
        .await
        .unwrap();
    assert_eq!(output["destination"], "DEFAULT");
    assert_eq!(output["output"], "general: hey");
    let result: GenerateResult = serde_json::from_value(output["generate_result"].clone()).unwrap();
    assert_eq!(result.tokens, Some(TokenUsage::new(11, 6)));
}

#[tokio::test]
async fn execute_without_a_result_key_uses_the_first_output_key() {
    struct Plain(&'static str);
    #[async_trait]
    impl Chain for Plain {
        async fn call(&self, _: PromptArgs) -> Result<GenerateResult, ChainError> {
            unreachable!()
        }
        async fn execute(
            &self,
            _: PromptArgs,
        ) -> Result<std::collections::HashMap<String, serde_json::Value>, ChainError> {
            Ok([(self.0.to_string(), json!("plain answer"))].into())
        }
        fn get_output_keys(&self) -> Vec<String> {
            match self.0 {
                // No declared keys: the answer is expected under `output`.
                "output" => vec![],
                key => vec![key.into()],
            }
        }
    }
    for key in ["text", "output"] {
        let chain = RouterChainBuilder::new()
            .llm(FakeLLM::new(["plain"]))
            .destination("plain", "plain", Plain(key))
            .output_key("answer")
            .build()
            .unwrap();
        let output = chain
            .execute(prompt_args! { "input" => "x" })
            .await
            .unwrap();
        assert_eq!(output["answer"], "plain answer", "{key}");
        assert_eq!(output[key], "plain answer");
        let result: GenerateResult =
            serde_json::from_value(output["generate_result"].clone()).unwrap();
        assert_eq!(result.generation, "plain answer");
        assert_eq!(result.tokens, Some(TokenUsage::new(1, 1)));
    }
}

#[tokio::test]
async fn call_stream_routes_then_streams() {
    let chain = RouterChainBuilder::new()
        .llm(FakeLLM::new(["greet"]))
        .destination(
            "greet",
            "Greets",
            greet_chain(FakeLLM::new(["hello there friend"])),
        )
        .input_key("name")
        .build()
        .unwrap();
    let events: Vec<_> = chain
        .call_stream(prompt_args! { "name" => "a" })
        .collect()
        .await;
    let events: Vec<LLMEvent> = events.into_iter().map(Result::unwrap).collect();
    let texts: Vec<_> = events
        .iter()
        .filter_map(|e| match e {
            LLMEvent::Text(t) => Some(t.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(texts, ["hello ", "there ", "friend"], "streamed for real");
    let Some(LLMEvent::Done(done)) = events.last() else {
        panic!("{events:?}")
    };
    assert_eq!(done.generation, "hello there friend");
    assert_eq!(done.tokens, Some(TokenUsage::new(2, 2)));

    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    let chain = router(FakeLLM::new(["chemistry"]), &physics, &math, None);
    let events: Vec<_> = chain
        .call_stream(prompt_args! { "input" => "x" })
        .collect()
        .await;
    assert_eq!(events.len(), 1);
    assert!(events[0]
        .as_ref()
        .unwrap_err()
        .to_string()
        .contains("chemistry"));
}

#[test]
fn builder_validates() {
    let err = |b: RouterChainBuilder| b.build().err().unwrap().to_string();
    let spy = Spy::new("x");
    assert!(err(RouterChainBuilder::new().destination("a", "a", spy.clone())).contains("llm"));
    assert!(err(RouterChainBuilder::new().llm(FakeLLM::default())).contains("destination"));
    for (a, b, expected) in [
        ("math", " MATH ", "duplicate"),
        ("math", "default", "invalid"),
        ("math", "  ", "invalid"),
    ] {
        let e = err(RouterChainBuilder::new()
            .llm(FakeLLM::default())
            .destination(a, "a", spy.clone())
            .destination(b, "b", spy.clone()));
        assert!(e.contains(expected), "{a}/{b}: {e}");
    }
}

#[tokio::test]
async fn call_runs_in_a_router_span() {
    let (spans, _guard) = crate::observability::testing::capture();
    let (physics, math) = (Spy::new("physics"), Spy::new("math"));
    router(FakeLLM::new(["physics"]), &physics, &math, None)
        .call(prompt_args! { "input" => "x" })
        .await
        .unwrap();
    router(
        FakeLLM::new(["DEFAULT"]),
        &physics,
        &math,
        Some(&Spy::new("general")),
    )
    .execute(prompt_args! { "input" => "x" })
    .await
    .unwrap();
    router(FakeLLM::new(["nope"]), &physics, &math, None)
        .call(prompt_args! { "input" => "x" })
        .await
        .unwrap_err();
    let spans: Vec<_> = spans
        .named("chain.call")
        .into_iter()
        .filter(|s| s.field("chain") == Some("router"))
        .collect();
    assert_eq!(spans.len(), 3);
    assert_eq!(spans[0].field("destination"), Some("physics"));
    assert_eq!(spans[1].field("destination"), Some("DEFAULT"));
    assert!(spans[2].field("error").unwrap().contains("nope"));
}

fn greet_chain(llm: FakeLLM) -> crate::chain::LLMChain {
    LLMChainBuilder::new()
        .prompt(HumanMessagePromptTemplate::new(template_fstring!(
            "Hello {name}!",
            "name"
        )))
        .llm(llm)
        .build()
        .unwrap()
}