Skip to content

Commit 16d3612

Browse files
authored
[docs] Add official docs for go (#2253)
<!-- ELLIPSIS_HIDDEN --> > [!IMPORTANT] > Adds official documentation and support for Go language in BAML, including setup, usage examples, and type mappings. > > - **Documentation**: > - Adds `go.mdx` to `fern/01-guide/02-languages/` for Go language setup and usage. > - Updates `docker.mdx`, `terminal-logs.mdx`, `upgrade-baml-versions.mdx`, `concurrent-calls.mdx`, `error-handling.mdx`, `multi-modal.mdx`, `my-first-function.mdx`, `streaming.mdx`, `checks-and-asserts.mdx`, `client-registry.mdx`, `collector.mdx`, `dynamic-types.mdx`, `modular-api.mdx`, `chat-history.mdx`, `tools.mdx`, `studio.mdx`, `what-are-function-definitions.mdx`, `what-is-baml_client.mdx`, `init.mdx`, `types.mdx`, `audio.mdx`, `client.mdx`, `image.mdx`, `pdf.mdx`, `typebuilder.mdx`, `with_options.mdx`, `generator.mdx` to include Go examples and instructions. > - Adds Go type mappings to `supported-types.mdx`. > - **Configuration**: > - Updates `docs.yml` to include Go in navigation. > - Updates `package.json` and `turbo.json` for Go support in development scripts. > > <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 8daebf8. 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 2958ae0 commit 16d3612

34 files changed

Lines changed: 2632 additions & 136 deletions

fern/01-guide/02-languages/go.mdx

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
---
2+
title: Go
3+
---
4+
5+
To set up BAML with Go do the following:
6+
7+
<Steps>
8+
### Install BAML VSCode/Cursor Extension
9+
https://marketplace.visualstudio.com/items?itemName=boundary.baml-extension
10+
11+
- syntax highlighting
12+
- testing playground
13+
- prompt previews
14+
15+
### Install BAML CLI and Initialize Project
16+
```bash go
17+
go install github.com/boundaryml/baml/go/baml-cli@latest && baml-cli init
18+
```
19+
20+
This command will:
21+
1. Install the BAML CLI tool globally
22+
2. Create starter BAML code in a `baml_src` directory
23+
3. Set up the basic project structure
24+
25+
### Install BAML Go Runtime
26+
After initializing your project, install the Go runtime library:
27+
28+
```bash go
29+
go get github.com/boundaryml/baml
30+
```
31+
32+
### Install Required Go Tools
33+
The BAML generator uses `gofmt` and `goimports` to format the generated Go code. Install these tools:
34+
35+
```bash go
36+
# gofmt comes with Go by default, but install goimports
37+
go install golang.org/x/tools/cmd/goimports@latest
38+
```
39+
40+
These tools are required by the `on_generate` command in your generator configuration and ensure the generated code is properly formatted.
41+
42+
### Generate the `baml_client` Go package from `.baml` files
43+
44+
One of the files in your `baml_src` directory will have a [generator block](/ref/baml/generator). This tells BAML how to generate the `baml_client` directory, which will have auto-generated Go code to call your BAML functions.
45+
46+
Any types defined in .baml files will be converted into Go structs in the `baml_client` directory.
47+
48+
```bash
49+
baml-cli generate
50+
```
51+
52+
You can modify your build process to always call baml-cli generate before building.
53+
54+
```makefile Makefile
55+
.PHONY: generate build
56+
57+
generate:
58+
baml-cli generate
59+
60+
build: generate
61+
go build ./...
62+
63+
test: generate
64+
go test ./...
65+
```
66+
67+
See [What is baml_client](/guide/introduction/baml_client) to learn more about how this works.
68+
69+
<Tip>
70+
If you set up the [VSCode extension](https://marketplace.visualstudio.com/items?itemName=Boundary.baml-extension), it will automatically run `baml-cli generate` on saving a BAML file.
71+
</Tip>
72+
73+
### Use a BAML function in Go!
74+
<Error>If `baml_client` doesn't exist, make sure to run the previous step! </Error>
75+
76+
```go main.go
77+
package main
78+
79+
import (
80+
"context"
81+
"fmt"
82+
"log"
83+
84+
b "example.com/myproject/baml_client"
85+
"example.com/myproject/baml_client/types"
86+
)
87+
88+
func main() {
89+
ctx := context.Background()
90+
91+
// BAML's internal parser guarantees ExtractResume
92+
// to always return a Resume type or an error
93+
resume, err := b.ExtractResume(ctx, rawResume)
94+
if err != nil {
95+
log.Fatal(err)
96+
}
97+
98+
fmt.Printf("Extracted resume: %+v\n", resume)
99+
}
100+
101+
func exampleStream(rawResume string) (*types.Resume, error) {
102+
ctx := context.Background()
103+
104+
stream, err := b.Stream.ExtractResume(ctx, rawResume)
105+
if err != nil {
106+
return nil, err
107+
}
108+
109+
for value := range stream {
110+
if value.IsError {
111+
return nil, value.Error
112+
}
113+
114+
if !value.IsFinal && value.Stream() != nil {
115+
partial := *value.Stream()
116+
fmt.Printf("Partial: %+v\n", partial) // This will be a partial Resume type
117+
}
118+
119+
if value.IsFinal && value.Final() != nil {
120+
final := *value.Final()
121+
return &final, nil // This will be a complete Resume type
122+
}
123+
}
124+
125+
return nil, fmt.Errorf("stream ended without final response")
126+
}
127+
```
128+
</Steps>
129+
130+
## Working with Go Modules
131+
132+
BAML integrates seamlessly with Go modules. Make sure your `go.mod` file includes the BAML dependency:
133+
134+
```go go.mod
135+
module example.com/myproject
136+
137+
go 1.21
138+
139+
require (
140+
github.com/boundaryml/baml v0.203.1
141+
)
142+
```
143+
144+
The generated `baml_client` package will use your module path, so you can import it as:
145+
146+
```go
147+
import (
148+
b "example.com/myproject/baml_client"
149+
"example.com/myproject/baml_client/types"
150+
)
151+
```
152+
153+
## Context and Cancellation
154+
155+
All BAML Go functions require a `context.Context` as the first parameter, allowing you to:
156+
157+
```go
158+
// Set timeouts
159+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
160+
defer cancel()
161+
162+
result, err := b.ExtractResume(ctx, resume)
163+
164+
// Handle cancellation
165+
ctx, cancel := context.WithCancel(context.Background())
166+
go func() {
167+
time.Sleep(5 * time.Second)
168+
cancel() // Cancel the request after 5 seconds
169+
}()
170+
171+
result, err := b.ExtractResume(ctx, resume)
172+
if errors.Is(err, context.Canceled) {
173+
fmt.Println("Request was canceled")
174+
}
175+
```
176+
177+
You're all set! Continue on to the [Deployment Guides](/guide/development/deploying/docker) for your language to learn how to deploy your BAML code or check out the [Interactive Examples](https://baml-examples.vercel.app/) to see more examples.

fern/01-guide/03-development/deploying/docker.mdx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,12 @@ RUN npx baml-cli generate --from path-to-baml_src
2626
RUN bundle add baml
2727
RUN bundle exec baml-cli generate --from path/to/baml_src
2828
```
29+
30+
```dockerfile Go Dockerfile
31+
# Install Go and BAML CLI
32+
RUN go install github.com/boundaryml/baml/go/baml-cli@latest
33+
# Generate BAML client
34+
RUN baml-cli generate --from path-to-baml_src
35+
```
2936
</CodeBlocks>
3037

fern/01-guide/03-development/terminal-logs.mdx

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,35 @@ To enable logging, set the `BAML_LOG` environment variable:
99
BAML_LOG=info
1010
```
1111

12+
<CodeBlocks>
13+
14+
```go Go
15+
// Set logging level in Go application
16+
os.Setenv("BAML_LOG", "info")
17+
18+
// Or run with environment variable:
19+
// BAML_LOG=info go run main.go
20+
```
21+
22+
```python Python
23+
# Set logging level in Python
24+
import os
25+
os.environ["BAML_LOG"] = "info"
26+
27+
# Or run with environment variable:
28+
# BAML_LOG=info python main.py
29+
```
30+
31+
```typescript TypeScript
32+
// Set logging level in TypeScript/JavaScript
33+
process.env.BAML_LOG = "info";
34+
35+
// Or run with environment variable:
36+
// BAML_LOG=info node main.js
37+
```
38+
39+
</CodeBlocks>
40+
1241
| Level | Description |
1342
|-------|-------------|
1443
| `error` | Fatal errors by BAML |
@@ -33,3 +62,40 @@ BOUNDARY_MAX_LOG_CHUNK_CHARS=3000
3362
```
3463

3564
This will truncate each part in a log entry to 3000 characters.
65+
66+
<CodeBlocks>
67+
68+
```go Go
69+
// Set log truncation in Go application
70+
os.Setenv("BOUNDARY_MAX_LOG_CHUNK_CHARS", "3000")
71+
72+
// Example with both logging and truncation
73+
func main() {
74+
// Configure logging
75+
os.Setenv("BAML_LOG", "info")
76+
os.Setenv("BOUNDARY_MAX_LOG_CHUNK_CHARS", "3000")
77+
78+
// Your application code here
79+
}
80+
```
81+
82+
```python Python
83+
# Set log truncation in Python
84+
import os
85+
os.environ["BOUNDARY_MAX_LOG_CHUNK_CHARS"] = "3000"
86+
87+
# Example with both logging and truncation
88+
os.environ["BAML_LOG"] = "info"
89+
os.environ["BOUNDARY_MAX_LOG_CHUNK_CHARS"] = "3000"
90+
```
91+
92+
```typescript TypeScript
93+
// Set log truncation in TypeScript/JavaScript
94+
process.env.BOUNDARY_MAX_LOG_CHUNK_CHARS = "3000";
95+
96+
// Example with both logging and truncation
97+
process.env.BAML_LOG = "info";
98+
process.env.BOUNDARY_MAX_LOG_CHUNK_CHARS = "3000";
99+
```
100+
101+
</CodeBlocks>

fern/01-guide/03-development/upgrade-baml-versions.mdx

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,14 @@ generator TypescriptGenerator {
1212
output_type "typescript"
1313
....
1414
// Version of runtime to generate code for (should match the package @boundaryml/baml version)
15-
version "0.62.0"
15+
version "0.205.0"
16+
}
17+
18+
generator GoGenerator {
19+
output_type "go"
20+
....
21+
// Version of runtime to generate code for (should match the github.com/boundaryml/baml version)
22+
version "0.205.0"
1623
}
1724
```
1825

@@ -30,6 +37,10 @@ npm install @boundaryml/baml@latest
3037
```sh ruby
3138
gem install baml
3239
```
40+
41+
```sh go
42+
go get -u github.com/boundaryml/baml
43+
```
3344
</CodeBlock>
3445

3546
3. Update VSCode BAML extension to point to the same version. Read here for how to keep VSCode in sync with your `baml_py` / `@boundaryml/baml` package dependency: [VSCode BAML Extension reference](/ref/editor-extension-settings/baml-cli-path)

fern/01-guide/04-baml-basics/concurrent-calls.mdx

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,58 @@ if (require.main === module) {
7777
```
7878
</Tab>
7979

80+
<Tab title="Go">
81+
82+
You can make concurrent `b.ClassifyMessage()` calls using goroutines:
83+
84+
```go main.go
85+
package main
86+
87+
import (
88+
"context"
89+
"sync"
90+
91+
b "example.com/myproject/baml_client"
92+
"example.com/myproject/baml_client/types"
93+
)
94+
95+
func main() {
96+
ctx := context.Background()
97+
98+
var wg sync.WaitGroup
99+
results := make(chan types.Category, 2)
100+
101+
// Launch concurrent goroutines
102+
wg.Add(2)
103+
104+
go func() {
105+
defer wg.Done()
106+
result, err := b.ClassifyMessage(ctx, "I want to cancel my order")
107+
if err == nil {
108+
results <- result
109+
}
110+
}()
111+
112+
go func() {
113+
defer wg.Done()
114+
result, err := b.ClassifyMessage(ctx, "I want a refund")
115+
if err == nil {
116+
results <- result
117+
}
118+
}()
119+
120+
wg.Wait()
121+
close(results)
122+
123+
// Collect results
124+
for result := range results {
125+
// Handle each result
126+
_ = result
127+
}
128+
}
129+
```
130+
</Tab>
131+
80132
<Tab title="Ruby (beta)">
81133

82134
BAML Ruby (beta) does not currently support async/concurrent calls.

fern/01-guide/04-baml-basics/error-handling.mdx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ async function example() {
5959

6060
```
6161

62+
```go Go
63+
// Error handling support coming soon for Go
64+
// Currently, Go functions return standard (non-typed) Go errors
65+
```
66+
6267
```ruby Ruby
6368
# Example coming soon
6469
```

0 commit comments

Comments
 (0)