Skip to content

Commit 766ba08

Browse files
authored
add support for plumbing through some errors for go (#1844)
<!-- ELLIPSIS_HIDDEN --> > [!IMPORTANT] > Add error handling support to the Go client for BAML runtime by implementing error callbacks and updating integration tests. > > - **Error Handling**: > - Added `env_logger` dependency in `Cargo.lock` and `Cargo.toml` for logging support. > - Implemented `error_callback` in `callbacks.go` to handle errors from Rust and send them to Go callbacks. > - Updated `register_callbacks()` in `lib.rs` to initialize `env_logger` and set error callback. > - Modified `safe_trigger_callback()` in `lib.rs` to use `ERROR_CALLBACK_FN` for error handling. > - **Integration Tests**: > - Updated `Makefile.toml` to set `BAML_LIBRARY_PATH` for integration tests. > - Modified `test.go` to use string parameters directly instead of `types.Union__List__string__string{}`. > - **Misc**: > - Updated `runtime.go` to register `error_callback` during initialization. > - Added `github.com/google/flatbuffers` to `go.mod` in `integ-tests/go`. > - Minor logging and error handling improvements in `callbacks.go` and `runtime.go`. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for 070c4cd. You can [customize](https://app.ellipsis.dev/BoundaryML/settings/summaries) this summary. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent e42a594 commit 766ba08

8 files changed

Lines changed: 74 additions & 20 deletions

File tree

‎engine/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎engine/language_client_cffi/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ tokio-util = { version = "0.7", features = ["full"] }
2929
once_cell.workspace = true
3030
anyhow.workspace = true
3131
flatbuffers = "25.2.10"
32+
env_logger.workspace = true
3233

3334
[build-dependencies]
3435
cbindgen = "0.28.0"

‎engine/language_client_cffi/Makefile.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ dependencies = ["build-local"]
3939
# Integration test tasks
4040
#-----------------------------------------------------------------------------
4141
[tasks.integ-tests-generate]
42-
script = "cd ../../integ-tests && ../baml-cli/baml-cli generate"
42+
script = "cd ../../integ-tests && BAML_LIBRARY_PATH=$(pwd)/../engine/target/debug/libbaml_cffi.dylib ../baml-cli/baml-cli generate"
4343
dependencies = ["build-go-cli"]
4444

4545
[tasks.integ-tests-build]

‎engine/language_client_cffi/src/lib.rs‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,14 @@ static ERROR_CALLBACK_FN: OnceCell<CallbackFn> = OnceCell::new();
107107

108108
#[no_mangle]
109109
extern "C" fn register_callbacks(callback_fn: CallbackFn, error_callback_fn: CallbackFn) {
110-
baml_log::init();
110+
println!("Registering callbacks");
111+
let _ = baml_log::init();
112+
let _ = env_logger::try_init_from_env(env_logger::Env::new().filter("BAML_INTERNAL_LOG"));
111113

112114
// Create a global runtime or pass it along as needed.
113115
unsafe {
114-
RESULT_CALLBACK_FN.set(std::mem::transmute(callback_fn));
115-
ERROR_CALLBACK_FN.set(std::mem::transmute(error_callback_fn));
116+
let _ = RESULT_CALLBACK_FN.set(std::mem::transmute(callback_fn));
117+
let _ = ERROR_CALLBACK_FN.set(std::mem::transmute(error_callback_fn));
116118
}
117119
}
118120

@@ -121,6 +123,10 @@ fn safe_trigger_callback(id: u32, is_done: bool, result: Result<FunctionResult>)
121123
.get()
122124
.expect("expected callback function to be set. Did you call register_callbacks?");
123125

126+
let error_callback_fn = ERROR_CALLBACK_FN
127+
.get()
128+
.expect("expected error callback function to be set. Did you call register_callbacks?");
129+
124130
match result {
125131
Ok(result) => match result.parsed() {
126132
Some(Ok(content)) => {
@@ -129,19 +135,33 @@ fn safe_trigger_callback(id: u32, is_done: bool, result: Result<FunctionResult>)
129135
callback_fn(id, is_done, content.as_ptr() as *const i8, content.len());
130136
}
131137
Some(Err(e)) => {
132-
println!("Error: {}", e);
133138
// let c_message = CString::new(e.to_string()).unwrap();
134-
// error_callback_fn(id, c_message.as_ptr() as *const libc::c_char);
139+
let message = e.to_string();
140+
error_callback_fn(
141+
id,
142+
true,
143+
message.as_ptr() as *const libc::c_char,
144+
message.len(),
145+
);
135146
}
136147
None => {
137-
println!("No result");
138-
// error_callback_fn(id, c_message.as_ptr() as *const libc::c_char);
148+
let message = "No result from baml".to_string();
149+
error_callback_fn(
150+
id,
151+
true,
152+
message.as_ptr() as *const libc::c_char,
153+
message.len(),
154+
);
139155
}
140156
},
141157
Err(e) => {
142-
println!("Error: {}", e);
143-
// let c_message = CString::new(e.to_string()).unwrap();
144-
// error_callback_fn(id, c_message.as_ptr() as *const libc::c_char);
158+
let message = format!("Error: {}", e);
159+
error_callback_fn(
160+
id,
161+
true,
162+
message.as_ptr() as *const libc::c_char,
163+
message.len(),
164+
);
145165
}
146166
}
147167
}

‎engine/language_client_go/pkg/callbacks.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import "C"
99

1010
import (
1111
"context"
12+
"fmt"
1213
"math/rand"
1314
"sync"
1415
"unsafe"
@@ -21,6 +22,10 @@ type BamlError struct {
2122
Message string
2223
}
2324

25+
func (e BamlError) Error() string {
26+
return e.Message
27+
}
28+
2429
type BamlClientError struct {
2530
BamlError
2631
}
@@ -53,6 +58,33 @@ func SetTypeMap(t TypeMap) {
5358
typeMap = t
5459
}
5560

61+
//export error_callback
62+
func error_callback(id C.uint32_t, isDone C.bool, content *C.int8_t, length C.int) {
63+
fmt.Println("Error callback")
64+
callbackMutex.RLock()
65+
id_uint := uint32(id)
66+
callback, exists := dynamicCallbacks[id_uint]
67+
callbackMutex.RUnlock()
68+
69+
if exists {
70+
content_bytes := C.GoBytes(unsafe.Pointer(content), length)
71+
72+
// Parse the content as a string
73+
content_str := string(content_bytes)
74+
75+
// TODO: cast to the right error type
76+
err := BamlError{Message: content_str}
77+
78+
// Send the error to the callback
79+
callback.channel <- ResultCallback{Error: err}
80+
81+
close(callback.channel)
82+
callbackMutex.Lock()
83+
defer callbackMutex.Unlock()
84+
delete(dynamicCallbacks, id_uint)
85+
}
86+
}
87+
5688
//export trigger_callback
5789
func trigger_callback(id C.uint32_t, isDone C.bool, content *C.int8_t, length C.int) {
5890
callbackMutex.RLock()

‎engine/language_client_go/pkg/runtime.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package baml
55
#include <stdbool.h>
66
77
extern void trigger_callback(uint32_t, bool, const int8_t *, int);
8+
extern void error_callback(uint32_t, bool, const int8_t *, int);
89
*/
910
import "C"
1011

@@ -36,7 +37,7 @@ func InvokeRuntimeCli(args []string) int {
3637
}
3738

3839
func init() {
39-
if err := baml_go.RegisterCallbacks(C.trigger_callback, C.trigger_callback); err != nil {
40+
if err := baml_go.RegisterCallbacks(C.trigger_callback, C.error_callback); err != nil {
4041
panic(err)
4142
}
4243
}

‎integ-tests/go/go.mod‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ module example.com/integ-tests
22

33
go 1.24.0
44

5-
require github.com/boundaryml/baml v0.2.0
5+
require (
6+
github.com/boundaryml/baml v0.2.0
7+
github.com/google/flatbuffers v25.2.10+incompatible
8+
)
69

710
require (
811
github.com/davecgh/go-spew v1.1.1 // indirect
9-
github.com/google/flatbuffers v25.2.10+incompatible // indirect
1012
github.com/pmezard/go-difflib v1.0.0 // indirect
1113
github.com/stretchr/testify v1.10.0 // indirect
1214
gopkg.in/yaml.v3 v3.0.1 // indirect

‎integ-tests/go/test.go‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,24 @@ import (
55
"fmt"
66

77
b "example.com/integ-tests/baml_client"
8-
"example.com/integ-tests/baml_client/types"
98
)
109

1110
func main() {
1211
ctx := context.Background()
1312

14-
param := types.Union__List__string__string{}
15-
param.SetString("oranges")
16-
v2, err := b.AaaSamOutputFormat(ctx, &param)
13+
v2, err := b.AaaSamOutputFormat(ctx, "oranges")
1714
if err != nil {
1815
panic(err)
1916
}
2017
fmt.Println(*v2)
2118

22-
v2, err = b.AaaSamOutputFormat(ctx, nil)
19+
v2, err = b.AaaSamOutputFormat(ctx, "pineapple")
2320
if err != nil {
2421
panic(err)
2522
}
2623
fmt.Println(*v2)
2724

28-
stream := b.Stream.AaaSamOutputFormat(ctx, &param)
25+
stream := b.Stream.AaaSamOutputFormat(ctx, "pineapple")
2926
for chunk := range stream {
3027
fmt.Println(chunk)
3128
}

0 commit comments

Comments
 (0)