baml 0.221.0

BAML runtime for Rust - type-safe LLM function calls
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
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
#![allow(unsafe_code)]
use std::{
    collections::HashMap,
    ffi::{c_char, c_void, CString},
};

use prost::Message;

use crate::{
    args::FunctionArgs,
    async_stream::AsyncStreamingCall,
    codec::{traits::DecodeHandle, BamlDecode},
    error::BamlError,
    ffi::{self, callbacks},
    proto::baml_cffi_v1::{
        invocation_response::Response as InvResponse,
        invocation_response_success::Result as InvSuccessResult, CffiValueHolder,
        InvocationResponse,
    },
    raw_objects::{Audio, Collector, HTTPRequest, Image, Pdf, TypeBuilder, Video},
    stream::StreamingCall,
};

/// Handle to the BAML runtime
pub struct BamlRuntime {
    ptr: *const c_void,
}

// Safety: The runtime is thread-safe internally (protected by Rust's runtime)
#[allow(unsafe_code)]
unsafe impl Send for BamlRuntime {}
#[allow(unsafe_code)]
unsafe impl Sync for BamlRuntime {}

pub type StaticRuntimeType = once_cell::sync::Lazy<BamlRuntime>;

impl BamlRuntime {
    /// Create a new runtime from embedded BAML source files
    ///
    /// # Arguments
    /// * `baml_src_dir` - Base directory path for BAML sources
    /// * `files` - Map of relative file paths to file contents
    /// * `env` - Environment variables
    pub fn new(
        baml_src_dir: &str,
        files: &HashMap<String, String>,
        env: &HashMap<String, String>,
    ) -> Result<Self, BamlError> {
        // Initialize callbacks first - now returns Result
        callbacks::initialize_callbacks()
            .map_err(|e| BamlError::internal(format!("Failed to load BAML library: {e}")))?;

        // Encode files and env as JSON (matching CFFI format)
        let files_json = json_encode_map(files)?;
        let env_json = json_encode_map(env)?;

        let dir_cstr = CString::new(baml_src_dir)
            .map_err(|_| BamlError::internal("invalid baml_src_dir path (contains null byte)"))?;
        let files_cstr = CString::new(files_json)
            .map_err(|_| BamlError::internal("invalid files json (contains null byte)"))?;
        let env_cstr = CString::new(env_json)
            .map_err(|_| BamlError::internal("invalid env json (contains null byte)"))?;

        #[allow(unsafe_code)]
        let ptr = unsafe {
            ffi::create_baml_runtime(dir_cstr.as_ptr(), files_cstr.as_ptr(), env_cstr.as_ptr())
                .map_err(|e| BamlError::internal(format!("Failed to load BAML library: {e}")))?
        };

        if ptr.is_null() {
            return Err(BamlError::internal("failed to create runtime"));
        }

        Ok(BamlRuntime { ptr })
    }

    /// Call a function synchronously (blocks until complete)
    pub fn call_function<T: BamlDecode>(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<T, BamlError> {
        let encoded = args.encode()?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) = callbacks::create_callback();

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::call_function_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        // Set up cancellation callback if token provided
        // Guard is dropped when function returns, stopping the watcher
        let _cancel_guard = args.cancellation_token.as_ref().map(|token| {
            token.on_cancel(move || {
                #[allow(unsafe_code)]
                unsafe {
                    let _ = ffi::cancel_function_call(id);
                }
            })
        });

        // Wait for result
        let result = receiver.recv();
        match result {
            Ok(callbacks::CallbackResult::Final(data)) => {
                let holder = CffiValueHolder::decode(&data[..])
                    .map_err(|e| BamlError::internal(format!("decode error: {e}")))?;
                T::baml_decode(&holder)
            }
            Ok(callbacks::CallbackResult::Partial(_)) => Err(BamlError::internal(
                "unexpected partial result in sync call",
            )),
            Ok(callbacks::CallbackResult::Error(e)) => Err(e),
            Err(_) => Err(BamlError::internal("callback channel closed")),
        }
    }

    /// Call a function with streaming results
    ///
    /// If `args` contains an `on_tick` callback (set via `FunctionArgs::with_on_tick`),
    /// it will be invoked for each SSE streaming chunk received from the LLM.
    /// A collector is automatically created and injected when on_tick is present.
    pub fn call_function_stream<TPartial, TFinal>(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<StreamingCall<TPartial, TFinal>, BamlError>
    where
        TPartial: BamlDecode + Send + 'static,
        TFinal: Clone + BamlDecode + Send + 'static,
    {
        let on_tick_data = args.on_tick.as_ref().map(|cb| {
            let collector = self.new_collector("on-tick-collector");
            let data = callbacks::OnTickData {
                callback: cb.clone(),
                collector: collector.clone(),
            };
            (data, collector)
        });

        let extra_collector = on_tick_data.as_ref().map(|(_, c)| c);
        let encoded = args.encode_with_extra_collector(extra_collector)?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) =
            callbacks::create_callback_with_on_tick(on_tick_data.map(|(d, _)| d));

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::call_function_stream_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        let cancel_guard = args.cancellation_token.as_ref().map(|token| {
            token.on_cancel(move || {
                #[allow(unsafe_code)]
                unsafe {
                    let _ = ffi::cancel_function_call(id);
                }
            })
        });

        Ok(StreamingCall::new(id, receiver, cancel_guard))
    }

    /// Call a function asynchronously (non-blocking)
    pub async fn call_function_async<T: BamlDecode>(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<T, BamlError> {
        let encoded = args.encode()?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) = callbacks::create_async_callback();

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::call_function_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        // Set up cancellation callback if token provided
        // Guard is dropped when function returns, stopping the watcher
        let _cancel_guard = args.cancellation_token.as_ref().map(|token| {
            token.on_cancel(move || {
                #[allow(unsafe_code)]
                unsafe {
                    let _ = ffi::cancel_function_call(id);
                }
            })
        });

        // Await result (non-blocking)
        match receiver.recv().await {
            Ok(callbacks::CallbackResult::Final(data)) => {
                let holder = CffiValueHolder::decode(&data[..])
                    .map_err(|e| BamlError::internal(format!("decode error: {e}")))?;
                T::baml_decode(&holder)
            }
            Ok(callbacks::CallbackResult::Partial(_)) => Err(BamlError::internal(
                "unexpected partial result in async call",
            )),
            Ok(callbacks::CallbackResult::Error(e)) => Err(e),
            Err(_) => Err(BamlError::internal("callback channel closed")),
        }
    }

    /// Call a function with async streaming results
    ///
    /// If `args` contains an `on_tick` callback (set via `FunctionArgs::with_on_tick`),
    /// it will be invoked for each SSE streaming chunk received from the LLM.
    /// A collector is automatically created and injected when on_tick is present.
    pub fn call_function_stream_async<TPartial, TFinal>(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<AsyncStreamingCall<TPartial, TFinal>, BamlError>
    where
        TPartial: BamlDecode + Send + 'static,
        TFinal: Clone + BamlDecode + Send + 'static,
    {
        let on_tick_data = args.on_tick.as_ref().map(|cb| {
            let collector = self.new_collector("on-tick-collector");
            let data = callbacks::OnTickData {
                callback: cb.clone(),
                collector: collector.clone(),
            };
            (data, collector)
        });

        let extra_collector = on_tick_data.as_ref().map(|(_, c)| c);
        let encoded = args.encode_with_extra_collector(extra_collector)?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) =
            callbacks::create_async_callback_with_on_tick(on_tick_data.map(|(d, _)| d));

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::call_function_stream_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        // Set up cancellation callback if token provided
        let cancel_guard = args.cancellation_token.as_ref().map(|token| {
            token.on_cancel(move || {
                #[allow(unsafe_code)]
                unsafe {
                    let _ = ffi::cancel_function_call(id);
                }
            })
        });

        Ok(AsyncStreamingCall::new(id, receiver, cancel_guard))
    }

    /// Parse raw LLM output into typed result
    ///
    /// Given the name of a BAML function and the raw text response from an LLM,
    /// this method parses the response according to the function's output type.
    ///
    /// # Arguments
    /// * `function_name` - Name of the BAML function that defines the output
    ///   type
    /// * `llm_response` - Raw text response from the LLM
    ///
    /// # Example
    /// ```ignore
    /// let raw_response = "Hello, World!";
    /// let result: String = runtime.parse("SayHello", raw_response)?;
    /// ```
    pub fn parse<T: BamlDecode>(
        &self,
        function_name: &str,
        llm_response: &str,
        stream: bool,
    ) -> Result<T, BamlError> {
        // Build args using FunctionArgs with parse-specific fields
        let args = FunctionArgs::new().arg("text", llm_response);
        let args = if stream {
            args.arg("stream", true)
        } else {
            args
        };
        let encoded = args.encode()?;
        let name_cstr = CString::new(function_name)
            .map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) = callbacks::create_callback();

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::call_function_parse_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(format!("function parse error: {e}"))
        })?;

        // Wait for result
        match receiver.recv() {
            Ok(callbacks::CallbackResult::Final(data)) => {
                if stream {
                    Err(BamlError::internal("unexpected final result in parse call"))
                } else {
                    let holder = CffiValueHolder::decode(&data[..])
                        .map_err(|e| BamlError::internal(format!("decode error: {e}")))?;
                    T::baml_decode(&holder)
                }
            }
            Ok(callbacks::CallbackResult::Partial(data)) => {
                if stream {
                    let holder = CffiValueHolder::decode(&data[..])
                        .map_err(|e| BamlError::internal(format!("decode error: {e}")))?;
                    T::baml_decode(&holder)
                } else {
                    Err(BamlError::internal(
                        "unexpected partial result in parse call",
                    ))
                }
            }
            Ok(callbacks::CallbackResult::Error(e)) => Err(e),
            Err(_) => Err(BamlError::internal("callback channel closed")),
        }
    }

    // =========================================================================
    // Build Request Methods
    // =========================================================================

    /// Build an HTTP request for a BAML function without executing it (sync, non-streaming).
    /// The `stream` arg should already be set in the FunctionArgs.
    pub fn build_request(&self, name: &str, args: &FunctionArgs) -> Result<HTTPRequest, BamlError> {
        self.build_request_inner(name, args)
    }

    /// Build an HTTP request for a streaming BAML function without executing it (sync).
    /// The `stream` arg should already be set in the FunctionArgs.
    pub fn build_request_stream(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<HTTPRequest, BamlError> {
        self.build_request_inner(name, args)
    }

    /// Build an HTTP request for a BAML function without executing it (async, non-streaming).
    /// The `stream` arg should already be set in the FunctionArgs.
    pub async fn build_request_async(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<HTTPRequest, BamlError> {
        self.build_request_inner_async(name, args).await
    }

    /// Build an HTTP request for a streaming BAML function without executing it (async).
    /// The `stream` arg should already be set in the FunctionArgs.
    pub async fn build_request_stream_async(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<HTTPRequest, BamlError> {
        self.build_request_inner_async(name, args).await
    }

    /// Internal sync implementation for build_request
    fn build_request_inner(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<HTTPRequest, BamlError> {
        let encoded = args.encode()?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) = callbacks::create_callback();

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::build_request_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        // Wait for result
        match receiver.recv() {
            Ok(callbacks::CallbackResult::Final(data)) => {
                Self::decode_http_request_from_invocation_response(&data, self.ptr)
            }
            Ok(callbacks::CallbackResult::Partial(_)) => Err(BamlError::internal(
                "unexpected partial result in build_request call",
            )),
            Ok(callbacks::CallbackResult::Error(e)) => Err(e),
            Err(_) => Err(BamlError::internal("callback channel closed")),
        }
    }

    /// Internal async implementation for build_request
    async fn build_request_inner_async(
        &self,
        name: &str,
        args: &FunctionArgs,
    ) -> Result<HTTPRequest, BamlError> {
        let encoded = args.encode()?;
        let name_cstr =
            CString::new(name).map_err(|_| BamlError::internal("invalid function name"))?;

        let (id, receiver) = callbacks::create_async_callback();

        #[allow(unsafe_code)]
        let buf = unsafe {
            ffi::build_request_from_c(
                self.ptr,
                name_cstr.as_ptr(),
                encoded.as_ptr().cast::<c_char>(),
                encoded.len(),
                id,
            )
            .map_err(|e| {
                callbacks::remove_callback(id);
                BamlError::internal(format!("Failed to load BAML library: {e}"))
            })?
        };

        // Check for immediate error (decode Buffer response)
        ffi::decode_async_response(buf).map_err(|e| {
            callbacks::remove_callback(id);
            BamlError::internal(e)
        })?;

        // Await result (non-blocking)
        match receiver.recv().await {
            Ok(callbacks::CallbackResult::Final(data)) => {
                Self::decode_http_request_from_invocation_response(&data, self.ptr)
            }
            Ok(callbacks::CallbackResult::Partial(_)) => Err(BamlError::internal(
                "unexpected partial result in build_request async call",
            )),
            Ok(callbacks::CallbackResult::Error(e)) => Err(e),
            Err(_) => Err(BamlError::internal("callback channel closed")),
        }
    }

    /// Decode an InvocationResponse containing a BamlObjectHandle into an HTTPRequest
    fn decode_http_request_from_invocation_response(
        data: &[u8],
        runtime_ptr: *const c_void,
    ) -> Result<HTTPRequest, BamlError> {
        let response = InvocationResponse::decode(data)
            .map_err(|e| BamlError::internal(format!("decode InvocationResponse error: {e}")))?;

        match response.response {
            Some(InvResponse::Success(success)) => match success.result {
                Some(InvSuccessResult::Object(handle)) => {
                    HTTPRequest::decode_handle(handle, runtime_ptr)
                }
                other => Err(BamlError::internal(format!(
                    "expected object handle in InvocationResponse, got: {other:?}"
                ))),
            },
            Some(InvResponse::Error(msg)) => Err(BamlError::internal(msg)),
            None => Err(BamlError::internal(
                "empty response in InvocationResponse for build_request",
            )),
        }
    }

    // =========================================================================
    // Media Factory Methods
    // =========================================================================

    /// Create an Image from a URL
    pub fn new_image_from_url(&self, url: &str, mime_type: Option<&str>) -> Image {
        Image::from_url(self.ptr, url, mime_type)
    }

    /// Create an Image from base64-encoded data
    pub fn new_image_from_base64(&self, base64: &str, mime_type: Option<&str>) -> Image {
        Image::from_base64(self.ptr, base64, mime_type)
    }

    /// Create Audio from a URL
    pub fn new_audio_from_url(&self, url: &str, mime_type: Option<&str>) -> Audio {
        Audio::from_url(self.ptr, url, mime_type)
    }

    /// Create Audio from base64-encoded data
    pub fn new_audio_from_base64(&self, base64: &str, mime_type: Option<&str>) -> Audio {
        Audio::from_base64(self.ptr, base64, mime_type)
    }

    /// Create a PDF from a URL
    pub fn new_pdf_from_url(&self, url: &str, mime_type: Option<&str>) -> Pdf {
        Pdf::from_url(self.ptr, url, mime_type)
    }

    /// Create a PDF from base64-encoded data
    pub fn new_pdf_from_base64(&self, base64: &str, mime_type: Option<&str>) -> Pdf {
        Pdf::from_base64(self.ptr, base64, mime_type)
    }

    /// Create a Video from a URL
    pub fn new_video_from_url(&self, url: &str, mime_type: Option<&str>) -> Video {
        Video::from_url(self.ptr, url, mime_type)
    }

    /// Create a Video from base64-encoded data
    pub fn new_video_from_base64(&self, base64: &str, mime_type: Option<&str>) -> Video {
        Video::from_base64(self.ptr, base64, mime_type)
    }

    // =========================================================================
    // Collector Factory Methods
    // =========================================================================

    /// Create a new collector for telemetry
    pub fn new_collector(&self, name: &str) -> Collector {
        Collector::new(self.ptr, name)
    }

    // =========================================================================
    // TypeBuilder Factory Methods
    // =========================================================================

    /// Create a new `TypeBuilder` for dynamic type construction
    pub fn new_type_builder(&self) -> TypeBuilder {
        TypeBuilder::new(self.ptr)
    }
}

impl Drop for BamlRuntime {
    fn drop(&mut self) {
        #[allow(unsafe_code)]
        // Ignore errors during drop - the library should already be loaded at this point
        // and we can't do much about errors during cleanup anyway
        let _ = unsafe { ffi::destroy_baml_runtime(self.ptr) };
    }
}

/// Simple JSON encoding for maps
///
/// This is a minimal implementation to avoid adding `serde_json` as a
/// dependency. For simplicity, we assume keys and values don't contain
/// problematic characters that would require complex escaping beyond basic
/// escapes.
fn json_encode_map(map: &HashMap<String, String>) -> Result<String, BamlError> {
    serde_json::to_string(map)
        .map_err(|e| BamlError::internal(format!("failed to encode map: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_encode_empty_map() {
        let map: HashMap<String, String> = HashMap::new();
        let result = json_encode_map(&map).unwrap();
        assert_eq!(result, "{}");
    }

    #[test]
    fn test_json_encode_simple_map() {
        let mut map = HashMap::new();
        map.insert("key".to_string(), "value".to_string());
        let result = json_encode_map(&map).unwrap();
        assert_eq!(result, "{\"key\":\"value\"}");
    }
}