-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathmod.rs
More file actions
2122 lines (1913 loc) · 73.5 KB
/
mod.rs
File metadata and controls
2122 lines (1913 loc) · 73.5 KB
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod generator;
pub mod runtime_prompt;
use std::{collections::HashMap, path::PathBuf, str::FromStr};
use anyhow::Context;
use baml_runtime::{
internal::{
llm_client::{
orchestrator::{ExecutionScope, OrchestrationScope, OrchestratorNode},
LLMResponse,
},
prompt_renderer::PromptRenderer,
},
internal_baml_diagnostics::SerializedSpan,
BamlRuntime, BamlSrcReader, DiagnosticsError, FunctionResult, IRHelper,
InternalRuntimeInterface, RenderCurlSettings, RenderedPrompt,
};
use baml_types::{BamlValue, GeneratorOutputType, ResponseCheck};
use futures::{channel::mpsc, StreamExt};
use indexmap::IndexMap;
use internal_baml_codegen::version_check::{check_version, GeneratorType, VersionCheckMode};
use internal_baml_core::{feature_flags::FeatureFlags, ir::repr::Walker};
use internal_llm_client::AllowedRoleMetadata;
use itertools::join;
use js_sys::{Promise, Uint8Array};
use jsonish::ResponseBamlValue;
use serde::{Deserialize, Serialize};
use wasm_bindgen::{prelude::*, JsError, JsValue};
use wasm_bindgen_futures::JsFuture;
use self::runtime_prompt::WasmScope;
use crate::{
abort_controller::js_abort_signal_to_tripwire, runtime_wasm::runtime_prompt::WasmPrompt,
};
type JsResult<T> = core::result::Result<T, JsError>;
// trait IntoJs<T> {
// fn into_js(self) -> JsResult<T>;
// }
// impl<T, E: Into<anyhow::Error> + Send> IntoJs<T> for core::result::Result<T, E> {
// fn into_js(self) -> JsResult<T> {
// self.map_err(|e| JsError::new(format!("{:#}", anyhow::Error::from(e)).as_str()))
// }
// }
//Run: wasm-pack test --firefox --headless --features internal,wasm
// but for browser we likely need to do
// wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
// Node is run using: wasm-pack test --node --features internal,wasm
#[wasm_bindgen(start)]
pub fn on_wasm_init() {
// TODO: set LOG_LEVEL to ::Debug if you wish to see logs.
// this is disabled by default because its slows down release mode builds.
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
const LOG_LEVEL: log::Level = log::Level::Info;
} else {
const LOG_LEVEL: log::Level = log::Level::Info;
}
};
// I dont think we need this line anymore -- seems to break logging if you add it.
//wasm_logger::init(wasm_logger::Config::new(LOG_LEVEL));
match console_log::init_with_level(LOG_LEVEL) {
Ok(_) => web_sys::console::log_1(
&format!("Initialized BAML runtime logging as log::{LOG_LEVEL}").into(),
),
Err(e) => web_sys::console::log_1(
&format!("Failed to initialize BAML runtime logging: {e:?}").into(),
),
}
console_error_panic_hook::set_once();
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct WasmProject {
#[wasm_bindgen(readonly)]
pub root_dir_name: String,
// This is the version of the file on disk
files: HashMap<String, String>,
// This is the version of the file that is currently being edited
// (unsaved changes)
unsaved_files: HashMap<String, String>,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Debug)]
pub struct WasmDiagnosticError {
errors: DiagnosticsError,
pub all_files: Vec<String>,
}
// use serde::Serialize;
#[wasm_bindgen(getter_with_clone)]
#[derive(Debug)]
pub struct SymbolLocation {
pub uri: String,
pub start_line: usize,
pub start_character: usize,
pub end_line: usize,
pub end_character: usize,
}
#[wasm_bindgen]
impl WasmDiagnosticError {
#[wasm_bindgen]
pub fn errors(&self) -> Vec<WasmError> {
self.errors
.errors()
.iter()
.map(|e| {
let (start, end) = e.span().line_and_column();
WasmError {
file_path: e.span().file.path(),
start_ch: e.span().start,
end_ch: e.span().end,
start_line: start.0,
start_column: start.1,
end_line: end.0,
end_column: end.1,
r#type: "error".to_string(),
message: e.message().to_string(),
}
})
.chain(self.errors.warnings().iter().map(|e| {
let (start, end) = e.span().line_and_column();
WasmError {
file_path: e.span().file.path(),
start_ch: e.span().start,
end_ch: e.span().end,
start_line: start.0,
start_column: start.1,
end_line: end.0,
end_column: end.1,
r#type: "warning".to_string(),
message: e.message().to_string(),
}
}))
.collect()
}
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Debug)]
pub struct WasmError {
#[wasm_bindgen(readonly)]
pub r#type: String,
#[wasm_bindgen(readonly)]
pub file_path: String,
#[wasm_bindgen(readonly)]
pub start_ch: usize,
#[wasm_bindgen(readonly)]
pub end_ch: usize,
#[wasm_bindgen(readonly)]
pub start_line: usize,
#[wasm_bindgen(readonly)]
pub start_column: usize,
#[wasm_bindgen(readonly)]
pub end_line: usize,
#[wasm_bindgen(readonly)]
pub end_column: usize,
#[wasm_bindgen(readonly)]
pub message: String,
}
#[wasm_bindgen]
impl WasmProject {
#[wasm_bindgen]
pub fn new(root_dir_name: &str, files: JsValue) -> Result<WasmProject, JsError> {
let files: HashMap<String, String> = serde_wasm_bindgen::from_value(files)?;
Ok(WasmProject {
root_dir_name: root_dir_name.to_string(),
files,
unsaved_files: HashMap::new(),
})
}
#[wasm_bindgen]
pub fn files(&self) -> Vec<String> {
let mut saved_files = self.files.clone();
self.unsaved_files.iter().for_each(|(k, v)| {
saved_files.insert(k.clone(), v.clone());
});
let formatted_files = saved_files
.iter()
.map(|(k, v)| format!("{k}BAML_PATH_SPLTTER{v}"))
.collect::<Vec<String>>();
formatted_files
}
#[wasm_bindgen]
pub fn update_file(&mut self, name: &str, content: Option<String>) {
if let Some(content) = content {
self.files.insert(name.to_string(), content);
} else {
self.files.remove(name);
}
}
#[wasm_bindgen]
pub fn save_file(&mut self, name: &str, content: &str) {
self.files.insert(name.to_string(), content.to_string());
self.unsaved_files.remove(name);
}
#[wasm_bindgen]
pub fn set_unsaved_file(&mut self, name: &str, content: Option<String>) {
if let Some(content) = content {
self.unsaved_files.insert(name.to_string(), content);
} else {
self.unsaved_files.remove(name);
}
}
#[wasm_bindgen]
pub fn diagnostics(&self, rt: &WasmRuntime) -> WasmDiagnosticError {
let mut hm = self.files.iter().collect::<HashMap<_, _>>();
hm.extend(self.unsaved_files.iter());
WasmDiagnosticError {
errors: rt.runtime.internal().diagnostics().clone(),
all_files: hm.keys().map(|s| s.to_string()).collect(),
}
}
#[wasm_bindgen]
pub fn runtime(
&self,
env_vars: JsValue,
feature_flags: JsValue,
) -> Result<WasmRuntime, JsValue> {
let mut hm = self.files.iter().collect::<HashMap<_, _>>();
hm.extend(self.unsaved_files.iter());
let env_vars: HashMap<String, String> =
serde_wasm_bindgen::from_value(env_vars).map_err(|e| {
JsValue::from_str(&format!(
"Expected env_vars to be HashMap<string, string>. {e}"
))
})?;
let feature_flags = if feature_flags.is_undefined() || feature_flags.is_null() {
FeatureFlags::new()
} else {
let flags: Vec<String> =
serde_wasm_bindgen::from_value(feature_flags).map_err(|e| {
JsValue::from_str(&format!("Expected feature_flags to be Array<string>. {e}"))
})?;
FeatureFlags::from_vec(flags)
.map_err(|e| JsValue::from_str(&format!("Invalid feature flags: {e:?}")))?
};
BamlRuntime::from_file_content(&self.root_dir_name, &hm, env_vars, feature_flags)
.map(|r| WasmRuntime { runtime: r })
.map_err(|e| match e.downcast::<DiagnosticsError>() {
Ok(e) => {
let wasm_error = WasmDiagnosticError {
errors: e,
all_files: hm.keys().map(|s| s.to_string()).collect(),
}
.into();
wasm_error
}
Err(e) => {
log::debug!("Error: {e:#?}");
JsValue::from_str(&e.to_string())
}
})
}
#[wasm_bindgen]
pub fn run_generators(
&self,
no_version_check: Option<bool>,
) -> Result<Vec<generator::WasmGeneratorOutput>, wasm_bindgen::JsError> {
let fake_map: HashMap<String, String> = HashMap::new();
let no_version_check = no_version_check.unwrap_or(false);
let js_value = serde_wasm_bindgen::to_value(&fake_map).unwrap();
let empty_flags = JsValue::undefined();
let runtime = self.runtime(js_value, empty_flags);
log::info!("Files are: {:#?}", self.files);
let res = match runtime {
Ok(runtime) => runtime.run_generators(&self.files, no_version_check),
Err(e) => Err(wasm_bindgen::JsError::new(
format!("Failed to create runtime: {e:#?}").as_str(),
)),
};
res
}
}
#[wasm_bindgen(inspectable, getter_with_clone)]
#[derive(Clone)]
pub struct WasmRuntime {
runtime: BamlRuntime,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmFunction {
#[wasm_bindgen(readonly)]
pub name: String,
#[wasm_bindgen(readonly)]
pub span: WasmSpan,
#[wasm_bindgen(readonly)]
pub test_cases: Vec<WasmTestCase>,
#[wasm_bindgen(readonly)]
pub test_snippet: String,
#[wasm_bindgen(readonly)]
pub signature: String,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmSpan {
#[wasm_bindgen(readonly)]
pub file_path: String,
#[wasm_bindgen(readonly)]
pub start: usize,
#[wasm_bindgen(readonly)]
pub end: usize,
#[wasm_bindgen(readonly)]
pub start_line: usize,
#[wasm_bindgen(readonly)]
pub end_line: usize,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmGeneratorConfig {
#[wasm_bindgen(readonly)]
pub output_type: String,
#[wasm_bindgen(readonly)]
pub version: String,
#[wasm_bindgen(readonly)]
pub span: WasmSpan,
}
impl From<&baml_runtime::internal_baml_diagnostics::Span> for WasmSpan {
fn from(span: &baml_runtime::internal_baml_diagnostics::Span) -> Self {
let (start, end) = span.line_and_column();
WasmSpan {
file_path: span.file.path().to_string(),
start: span.start,
end: span.end,
start_line: start.0,
end_line: end.0,
}
}
}
impl Default for WasmSpan {
fn default() -> Self {
WasmSpan {
file_path: "".to_string(),
start: 0,
end: 0,
start_line: 0,
end_line: 0,
}
}
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmParentFunction {
#[wasm_bindgen(readonly)]
pub start: usize,
#[wasm_bindgen(readonly)]
pub end: usize,
#[wasm_bindgen(readonly)]
pub name: String,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmTestCase {
#[wasm_bindgen(readonly)]
pub name: String,
#[wasm_bindgen(readonly)]
pub inputs: Vec<WasmParam>,
#[wasm_bindgen(readonly)]
pub error: Option<String>,
#[wasm_bindgen(readonly)]
pub span: WasmSpan,
#[wasm_bindgen(readonly)]
pub parent_functions: Vec<WasmParentFunction>,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Clone, Debug)]
pub struct WasmParam {
#[wasm_bindgen(readonly)]
pub name: String,
#[wasm_bindgen(readonly)]
pub value: Option<String>,
#[wasm_bindgen(readonly)]
pub error: Option<String>,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Debug, Clone)]
pub struct WasmFunctionTestPair {
#[wasm_bindgen(readonly)]
pub function_name: String,
#[wasm_bindgen(readonly)]
pub test_name: String,
}
#[wasm_bindgen]
pub struct WasmFunctionResponse {
function_response: baml_runtime::FunctionResult,
func_test_pair: WasmFunctionTestPair,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
#[derive(Debug)]
pub struct WasmTestResponses {
responses: Vec<WasmTestResponse>,
}
#[wasm_bindgen]
impl WasmTestResponses {
// #[wasm_bindgen(typescript_type = "WasmTestResponse | null")]
#[wasm_bindgen]
pub fn yield_next(&mut self) -> Option<WasmTestResponse> {
self.responses.pop()
}
}
#[wasm_bindgen]
#[derive(Debug)]
#[allow(dead_code)]
pub struct WasmTestResponse {
test_response: anyhow::Result<baml_runtime::TestResponse>,
span: Option<String>,
tracing_project_id: Option<String>,
func_test_pair: WasmFunctionTestPair,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
pub struct WasmParsedTestResponse {
#[wasm_bindgen(readonly)]
pub value: String,
#[wasm_bindgen(readonly)]
pub check_count: usize,
#[wasm_bindgen(readonly)]
/// JSON-string of the explanation, if there were any ParsingErrors
pub explanation: Option<String>,
}
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub enum TestStatus {
Passed,
LLMFailure,
ParseFailure,
FinishReasonFailed,
ConstraintsFailed,
AssertFailed,
UnableToRun,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
pub struct WasmLLMResponse {
scope: OrchestrationScope,
pub model: String,
prompt: RenderedPrompt,
pub content: String,
pub start_time_unix_ms: u64,
pub latency_ms: u64,
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
pub total_tokens: Option<u64>,
pub stop_reason: Option<String>,
}
#[wasm_bindgen(getter_with_clone, inspectable)]
pub struct WasmLLMFailure {
scope: OrchestrationScope,
pub model: Option<String>,
prompt: RenderedPrompt,
pub start_time_unix_ms: u64,
pub latency_ms: u64,
pub message: String,
pub code: String,
}
#[wasm_bindgen]
impl WasmLLMFailure {
#[wasm_bindgen]
pub fn client_name(&self) -> String {
self.scope.name()
}
pub fn prompt(&self) -> WasmPrompt {
// TODO: This is a hack. We shouldn't hardcode AllowedRoleMetadata::All
// here, but instead plumb it through the LLMErrors
(&self.prompt, &self.scope, &AllowedRoleMetadata::All).into()
}
}
#[wasm_bindgen]
impl WasmLLMResponse {
#[wasm_bindgen]
pub fn client_name(&self) -> String {
self.scope.name()
}
pub fn prompt(&self) -> WasmPrompt {
// TODO: This is a hack. We shouldn't hardcode AllowedRoleMetadata::All
// here, but instead plumb it through the LLMErrors
(&self.prompt, &self.scope, &AllowedRoleMetadata::All).into()
}
}
#[wasm_bindgen]
impl WasmFunctionResponse {
pub fn parsed_response(&self) -> Option<String> {
self.function_response
.result_with_constraints_content()
.map(|p| serde_json::to_string(&p.serialize_partial()))
.map_or_else(|_| None, |s| s.ok())
}
#[wasm_bindgen]
pub fn llm_failure(&self) -> Option<WasmLLMFailure> {
llm_response_to_wasm_error(
self.function_response.llm_response(),
self.function_response.scope(),
)
}
#[wasm_bindgen]
pub fn llm_response(&self) -> Option<WasmLLMResponse> {
(
self.function_response.llm_response(),
self.function_response.scope(),
)
.to_wasm()
}
#[wasm_bindgen]
pub fn func_test_pair(&self) -> WasmFunctionTestPair {
self.func_test_pair.clone()
}
}
fn serialize_value_counting_checks(value: &ResponseBamlValue) -> (serde_json::Value, usize) {
let checks = value
.0
.meta()
.1
.iter()
.map(|ResponseCheck { name, status, .. }| (name.clone(), status.clone()))
.collect::<IndexMap<String, String>>();
let sub_check_count: usize = value.0.iter().map(|node| node.meta().1.len()).sum();
let json_value: serde_json::Value = serde_json::to_value(value.serialize_final())
.unwrap_or("Error converting value to JSON".into());
let check_count = checks.len() + sub_check_count;
(json_value, check_count)
}
#[wasm_bindgen]
impl WasmTestResponse {
#[wasm_bindgen]
pub fn status(&self) -> TestStatus {
match &self.test_response {
Ok(t) => match t.status() {
baml_runtime::TestStatus::Pass => TestStatus::Passed,
baml_runtime::TestStatus::NeedsHumanEval(_) => TestStatus::ConstraintsFailed,
baml_runtime::TestStatus::Fail(r) => match r {
baml_runtime::TestFailReason::TestUnspecified(_) => TestStatus::UnableToRun,
baml_runtime::TestFailReason::TestLLMFailure(_) => TestStatus::LLMFailure,
baml_runtime::TestFailReason::TestParseFailure(_) => TestStatus::ParseFailure,
baml_runtime::TestFailReason::TestFinishReasonFailed(_) => {
TestStatus::FinishReasonFailed
}
baml_runtime::TestFailReason::TestConstraintsFailure {
failed_assert, ..
} => {
if failed_assert.is_some() {
TestStatus::AssertFailed
} else {
TestStatus::ConstraintsFailed
}
}
},
},
Err(_) => TestStatus::UnableToRun,
}
}
fn parsed_response_impl(&self) -> anyhow::Result<WasmParsedTestResponse> {
let maybe_parsed_response = &self
.test_response
.as_ref()
.ok()
.context("No test response")?
.function_response
.parsed()
.as_ref();
let parsed_response = match maybe_parsed_response {
Some(Ok(value)) => Ok(value),
_ => Err(anyhow::anyhow!("No parsed value")),
}
.context("No parsed value")?;
let (flattened_checks, check_count) = serialize_value_counting_checks(parsed_response);
Ok(WasmParsedTestResponse {
value: serde_json::to_string(&flattened_checks)?,
check_count,
explanation: {
let j = parsed_response.explanation_json();
if j.is_empty() {
None
} else {
Some(serde_json::to_string(&j)?)
}
},
})
}
#[wasm_bindgen]
pub fn parsed_response(&self) -> Option<WasmParsedTestResponse> {
self.parsed_response_impl().ok()
}
#[wasm_bindgen]
pub fn llm_failure(&self) -> Option<WasmLLMFailure> {
self.test_response.as_ref().ok().and_then(|r| {
llm_response_to_wasm_error(
r.function_response.llm_response(),
r.function_response.scope(),
)
})
}
#[wasm_bindgen]
pub fn llm_response(&self) -> Option<WasmLLMResponse> {
self.test_response.as_ref().ok().and_then(|r| {
(
r.function_response.llm_response(),
r.function_response.scope(),
)
.to_wasm()
})
}
#[wasm_bindgen]
pub fn failure_message(&self) -> Option<String> {
match self.test_response.as_ref() {
Ok(r) => match r.status() {
baml_runtime::TestStatus::Pass => None,
baml_runtime::TestStatus::Fail(r) => r.render_error(),
baml_runtime::TestStatus::NeedsHumanEval(checks) => Some(format!(
"Checks require human validation: {}",
join(checks, ", ")
)),
},
Err(e) => Some(format!("{e:#}")),
}
}
fn _trace_url(&self) -> anyhow::Result<String> {
let test_response = match self.test_response.as_ref() {
Ok(t) => t,
Err(e) => anyhow::bail!("Failed to get test response: {:?}", e),
};
let start_time = match test_response.function_response.llm_response() {
LLMResponse::Success(s) => s.start_time,
LLMResponse::LLMFailure(f) => f.start_time,
_ => anyhow::bail!("Test has no start time"),
};
let _start_time = time::OffsetDateTime::from_unix_timestamp(
start_time
.duration_since(web_time::UNIX_EPOCH)?
.as_secs()
.try_into()?,
)?
.format(&time::format_description::well_known::Rfc3339)?;
// TODO: update this.
// let event_span_id = self
// .span
// .as_ref()
// .ok_or(anyhow::anyhow!("Test has no span ID"))?
// .to_string();
// let subevent_span_id = test_response
// .function_call
// .as_ref()
// .ok_or(anyhow::anyhow!("Function call has no span ID"))?
// .to_string();
// Ok(format!(
// "https://app.boundaryml.com/dashboard/projects/{}/drilldown?start_time={start_time}&eid={event_span_id}&s_eid={subevent_span_id}&test=false&onlyRootEvents=true",
// self.tracing_project_id.as_ref().ok_or(anyhow::anyhow!("No project ID specified"))?
// ))
Ok("https://app.boundaryml.com/dashboard/projects/".to_string())
}
#[wasm_bindgen]
pub fn trace_url(&self) -> Option<String> {
self._trace_url().ok()
}
#[wasm_bindgen]
pub fn func_test_pair(&self) -> WasmFunctionTestPair {
self.func_test_pair.clone()
}
}
fn llm_response_to_wasm_error(
r: &baml_runtime::internal::llm_client::LLMResponse,
scope: &OrchestrationScope,
) -> Option<WasmLLMFailure> {
match &r {
LLMResponse::LLMFailure(f) => Some(WasmLLMFailure {
scope: scope.clone(),
model: f.model.clone(),
prompt: f.prompt.clone(),
start_time_unix_ms: f
.start_time
.duration_since(web_time::UNIX_EPOCH)
.unwrap_or(web_time::Duration::ZERO)
.as_millis() as u64,
latency_ms: f.latency.as_millis() as u64,
message: f.message.clone(),
code: f.code.to_string(),
}),
_ => None,
}
}
trait ToWasm {
type Output;
fn to_wasm(&self) -> Self::Output;
}
impl ToWasm
for (
&baml_runtime::internal::llm_client::LLMResponse,
&OrchestrationScope,
)
{
type Output = Option<WasmLLMResponse>;
fn to_wasm(&self) -> Self::Output {
match &self.0 {
baml_runtime::internal::llm_client::LLMResponse::Success(s) => Some(WasmLLMResponse {
scope: self.1.clone(),
model: s.model.clone(),
prompt: s.prompt.clone(),
content: s.content.clone(),
start_time_unix_ms: s
.start_time
.duration_since(web_time::UNIX_EPOCH)
.unwrap_or(web_time::Duration::ZERO)
.as_millis() as u64,
latency_ms: s.latency.as_millis() as u64,
input_tokens: s.metadata.prompt_tokens,
output_tokens: s.metadata.output_tokens,
total_tokens: s.metadata.total_tokens,
stop_reason: s.metadata.finish_reason.clone(),
}),
_ => None,
}
}
}
trait WithRenderError {
fn render_error(&self) -> Option<String>;
}
impl WithRenderError for baml_runtime::TestFailReason<'_> {
fn render_error(&self) -> Option<String> {
match &self {
baml_runtime::TestFailReason::TestUnspecified(e) => Some(format!("{e:#}")),
baml_runtime::TestFailReason::TestLLMFailure(f) => f.render_error(),
baml_runtime::TestFailReason::TestParseFailure(e)
| baml_runtime::TestFailReason::TestFinishReasonFailed(e) => {
match e.downcast_ref::<baml_runtime::errors::ExposedError>() {
Some(exposed_error) => match exposed_error {
baml_runtime::errors::ExposedError::ValidationError { message, .. } => {
Some(message.clone())
}
baml_runtime::errors::ExposedError::FinishReasonError {
message, ..
} => Some(message.clone()),
baml_runtime::errors::ExposedError::ClientHttpError { message, .. } => {
Some(message.clone())
}
baml_runtime::errors::ExposedError::AbortError => {
Some("AbortError".to_string())
}
},
None => Some(format!("{e:#}")),
}
}
baml_runtime::TestFailReason::TestConstraintsFailure {
checks,
failed_assert,
} => {
let checks_msg = if !checks.is_empty() {
let check_msgs = checks.iter().map(|(name, pass)| {
format!("{name}: {}", if *pass { "Passed" } else { "Failed" })
});
format!("Check results:\n{}", join(check_msgs, "\n"))
} else {
String::new()
};
let assert_msg = failed_assert
.as_ref()
.map_or("".to_string(), |name| format!("\nFailed assert: {name}"));
Some(format!("{checks_msg}{assert_msg}"))
}
}
}
}
impl WithRenderError for baml_runtime::internal::llm_client::LLMResponse {
fn render_error(&self) -> Option<String> {
match self {
baml_runtime::internal::llm_client::LLMResponse::Success(_) => None,
baml_runtime::internal::llm_client::LLMResponse::LLMFailure(f) => {
format!("{} {}", f.message, f.code).into()
}
baml_runtime::internal::llm_client::LLMResponse::UserFailure(e) => {
format!("user error: {e}").into()
}
baml_runtime::internal::llm_client::LLMResponse::InternalFailure(e) => {
e.to_string().into()
}
baml_runtime::internal::llm_client::LLMResponse::Cancelled(msg) => {
format!("cancelled: {msg}").into()
}
}
}
}
// Rust-only methods
impl WasmRuntime {
pub fn run_generators(
&self,
input_files: &HashMap<String, String>,
no_version_check: bool,
) -> Result<Vec<generator::WasmGeneratorOutput>, wasm_bindgen::JsError> {
Ok(self
.runtime
// convert the input_files into HashMap(PathBuf, string)
.run_codegen(
&input_files
.iter()
.map(|(k, v)| (PathBuf::from(k), v.clone()))
.collect(),
no_version_check,
)
.map_err(|e| JsError::new(format!("{e:#}").as_str()))?
.into_iter()
.map(|g| g.into())
.collect())
}
}
#[wasm_bindgen]
impl WasmRuntime {
#[wasm_bindgen]
pub fn check_if_in_prompt(&self, cursor_idx: usize) -> bool {
self.runtime.internal().ir().walk_functions().any(|f| {
f.elem().configs().expect("configs").iter().any(|config| {
let span = &config.prompt_span;
cursor_idx >= span.start && cursor_idx <= span.end
})
})
}
#[wasm_bindgen]
pub fn list_functions(&self) -> Vec<WasmFunction> {
let ctx = &self
.runtime
.create_ctx_manager(BamlValue::String("wasm".to_string()), None);
let ctx = ctx.create_ctx_with_default();
let ctx = ctx.eval_ctx(false);
self.runtime
.internal()
.ir()
.walk_functions()
.chain(
self.runtime
.internal()
.ir()
.expr_fns_as_functions()
.iter()
.map(|f| Walker {
ir: self.runtime.internal().ir(),
item: f,
}),
)
.map(|f| {
let snippet = format!(
r#"test TestName {{
functions [{name}]
args {{
{args}
}}
}}
"#,
name = f.name(),
args = {
// Convert baml_runtime::TypeIR inputs to baml_types::TypeIR and use our improved dummy generator
let params = f
.inputs()
.iter()
.map(|(k, runtime_type)| (k.clone(), runtime_type.clone()))
.collect::<indexmap::IndexMap<String, _>>();
// Use the IR's get_dummy_args method
self.runtime
.internal()
.ir()
.get_dummy_args(2, true, ¶ms)
}
);
let wasm_span = match f.span() {
Some(span) => span.into(),
None => WasmSpan::default(),
};
WasmFunction {
name: f.name().to_string(),
span: wasm_span,
signature: {
let inputs = {
let params = f
.inputs()
.iter()
.map(|(k, runtime_type)| (k.clone(), runtime_type.clone()))
.collect::<indexmap::IndexMap<String, _>>();
self.runtime
.internal()
.ir()
.get_dummy_args(2, false, ¶ms)
.split('\n')
.map(|line| line.trim().to_string())
.collect::<Vec<_>>()
.join(", ")
};
format!("({}) -> {}", inputs, f.output())
},
test_snippet: snippet,
test_cases: f
.walk_tests()
.map(|tc| {
let params = match tc.test_case_params(&ctx) {
Ok(params) => Ok(params
.iter()
.map(|(k, v)| {
let as_str = match v {
Ok(v) => match serde_json::to_string(v) {
Ok(s) => Ok(s),
Err(e) => Err(e.to_string()),
},
Err(e) => Err(e.to_string()),
};
let (value, error) = match as_str {
Ok(s) => (Some(s), None),
Err(e) => (None, Some(e)),
};
WasmParam {
name: k.to_string(),
value,
error,
}
})
.collect()),
Err(e) => Err(e.to_string()),
};
let (mut params, error) = match params {
Ok(p) => (p, None),
Err(e) => (Vec::new(), Some(e)),
};