baml_rest

package module
v0.0.0-...-3aa5eb3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: Unlicense Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

baml-rest

Embedding via dynclient

The dynamic endpoints (/call/_dynamic, /stream/_dynamic, etc.) are also available as an in-process Go library at github.com/invakid404/baml-rest/dynclient for projects that want to call LLMs through baml-rest's BuildRequest pipeline without running a separate server.

Install:

go get github.com/invakid404/baml-rest/dynclient@latest

Quickstart:

import "github.com/invakid404/baml-rest/dynclient"

c, err := dynclient.New(
    dynclient.WithLogger(logger),
    dynclient.WithMetricsRegistry(reg),
)
// c.DynamicCall(ctx, req)
// c.DynamicStream(ctx, req)

See dynclient/ for the full surface (10 options, 5 endpoint methods, iterator-style streaming). The patched-BAML CFFI library is bundled as a nested module — no separate setup required.

HTTP backend selection and tuning

The underlying HTTP backend (net/http vs fasthttp) is chosen by WithClientMode and tuned independently by WithNetHTTPClient (net/http only) and WithFastHTTPClient (fasthttp only). Selection and tuning are orthogonal axes: the default llmhttp.ClientModeAuto routes each origin to the appropriate backend via an ALPN probe, and either tuning option can apply in parallel.

import (
    "net/http"

    "github.com/invakid404/baml-rest/bamlutils/llmhttp"
    "github.com/invakid404/baml-rest/dynclient"
)

netClient := &http.Client{
    Transport: http.DefaultTransport.(*http.Transport).Clone(),
}

// Force net/http with a custom *http.Client:
dynclient.New(
    dynclient.WithClientMode(llmhttp.ClientModeNetHTTP),
    dynclient.WithNetHTTPClient(netClient),
)

// Force net/http with the package's tuned default transport
// (no custom client needed):
dynclient.New(dynclient.WithClientMode(llmhttp.ClientModeNetHTTP))

// Keep Auto mode and tune fasthttp routes only:
dynclient.New(
    dynclient.WithFastHTTPClient(llmhttp.FastHTTPClientOptions{MaxConns: 1024}),
)

// Keep Auto mode and tune both backend families:
dynclient.New(
    dynclient.WithNetHTTPClient(netClient),
    dynclient.WithFastHTTPClient(llmhttp.FastHTTPClientOptions{MaxConns: 1024}),
)

Forced modes reject tuning aimed at the unused backend — e.g. WithClientMode(ClientModeNetHTTP) combined with WithFastHTTPClient is a hard error from New so the misconfiguration surfaces at startup rather than as a silent no-op at request time.

BAML_REST_HTTP_CLIENT (auto/fasthttp/nethttp) is a server/worker env var only; dynclient stays explicit-only and never reads it.

Runtime configuration

baml-rest reads the following environment variables at startup:

  • BuildRequest is attempted by default whenever supported — the BuildRequest/StreamRequest route is taken automatically when the generated BAML client exposes those surfaces (BAML 0.219+). Older BAML versions without Request/StreamRequest, and unsupported/empty providers, use the legacy CallStream+OnTick path. /call{,-with-raw} use the non-streaming Request API whenever the generated client exposes Request and the provider supports it; the StreamRequest bridge is the automatic fallback when Request is unavailable for the request shape. The retired BAML_REST_USE_BUILD_REQUEST and BAML_REST_DISABLE_CALL_BUILD_REQUEST env vars are ignored; if either is still set, baml-rest logs a one-time startup deprecation warning. There is no rollback flag for the non-streaming Request path — roll back the deployment instead.

  • BAML_REST_BASE_URL_REWRITES — semicolon-separated URL rewrite rules applied to LLM provider base URLs, both at build time and at runtime. Format: from1=to1;from2=to2. See bamlutils/urlrewrite for the full semantics.

  • BAML_REST_CLIENT_DEFAULTS — JSON object pinning deployment-wide defaults for BAML ClientRegistry option values. Each key in options is merged into every caller's client_registry.clients[].options map unless the caller already set it. Example:

    {
      "client_defaults": {
        "options": {
          "allowed_role_metadata": ["cache_control"]
        }
      }
    }
    

    v1 recognizes allowed_role_metadata only. See bamlutils/clientdefaults for the merge contract, supported opt-outs, and supported-version caveats.

  • BAML_REST_PRESERVE_SCHEMA_ORDER_DEFAULT — when truthy (1/true/yes/on), dynamic requests that omit or set preserve_schema_order: null inherit true, so the rendered output_format follows the JSON key order captured from output_schema. Per-request preserve_schema_order: true or false always wins. Default unset/false keeps the alphabetical ordering introduced for deterministic prompts.

  • BAML_LOG — BAML internal log level (debug, info, warn, error).

  • BAML_REST_EXPECTED_ARTIFACT_PROFILE — the worker artifact profile this deployment slot expects, native_capable or baml_only (see Deployable worker artifact profiles). Unset or empty means "no expectation" and is the default. When set, an artifact whose profile differs logs an error-level alert at startup and sets baml_rest_debaml_artifact_profile_expectation_violation to 1 — it does not refuse to boot, because rolling back to the BAML-only artifact must work even in a slot still configured to expect the standard one. An unrecognized value is a configuration error and fails startup.

Deployable worker artifact profiles

A subprocess build ships a host binary with a worker binary embedded in it. Two worker artifacts exist, and which one is embedded is a build-time choice:

  • native_capable — the standard artifact. The worker built from the isolated internal/nativebody/nanollmprepare module, which links the native engine and can serve a request natively. This is what baml-rest build produces by default (--native-worker, default true). Being able to serve natively is not the same as doing so: the enrollment policy ships empty, so every request declines before a socket and BAML serves 100% of traffic, and BAML_REST_USE_DEBAML=false additionally suppresses all native capability initialization, factories, Prepare and native sockets.
  • baml_only — the rollback artifact. The zero-options root cmd/worker, which links no native engine at all and therefore cannot serve natively under any flag or policy. Select it with --baml-only-rollback-worker (or --native-worker=false). It stays fully supported: BAML_REST_USE_DEBAML=false only promises a total BAML revert for as long as a BAML-capable artifact exists to revert to.

An in-process build (--inprocess) has no worker subprocess, so it is always baml_only; asking for both explicitly is rejected.

Every binary attests its own profile at startup. The build stamps the profile, a reproducible release artifact ID, and the inputs that ID was derived from; at startup the binary cross-checks all three against what it demonstrably is — the worker against its linked native capability, the host against its build tag — and re-derives the ID from its own stamped inputs. A contradicted profile, or an artifact ID those inputs do not produce, fails startup rather than producing a wrong label. Binaries built without the stamp (a plain go build) make no claim and boot normally, with artifact_id reported as unstamped.

The release artifact ID covers the build's provenance, not just its selection axes: the release revision, a content digest over the embedded source bundle the build was laid down from, and the content digest of the packaged native-worker module tar. Two releases that select the same axes therefore still get distinct IDs. Pass --source-revision (or BAML_REST_SOURCE_REVISION) to baml-rest build to record the release revision; the two content digests are always computed.

The startup log line carries artifact_profile, artifact_id, artifact_stamped, expected_artifact_profile and the three provenance fields (artifact_source_revision, artifact_source_bundle_digest, artifact_native_worker_tar_digest). The bounded identity is exported on /metrics as baml_rest_debaml_artifact_profile_info alongside baml_rest_debaml_artifact_profile_expectation_violation. If a worker's metric families cannot be decoded at the host bridge, the scrape FAILS (and bamlrest_worker_metrics_bridge_failures_total records it) rather than serving an aggregate that silently omits the profile signal.

In-process build mode

By default, a from-source go build of ./cmd/serve produces a single-process binary with the BAML worker handler linked directly into the server. The subprocess Go build tag opts back into the supervised pair of server + go-plugin gRPC worker subprocesses; the embedded worker binary is then extracted at startup. The project build wrapper (cmd/build) still defaults to subprocess output for distributed deployments and exposes --inprocess to flip back to the single-process layout.

Building
  • go build ./cmd/serve — default, single-process (in-process handler).
  • go build -tags=subprocess ./cmd/serve — supervised pair, requires a prebuilt cmd/worker to embed.
  • go run ./cmd/build … — distributed default; produces subprocess output.
  • go run ./cmd/build --inprocess … (or BAML_REST_INPROCESS=true for the project build wrapper) drives the in-process collapse through the Dockerfile.
What changes
  • The server and the worker handler run in one address space; there is no child process and no plugin handshake.
  • The pool is force-collapsed to a single worker. --pool-size > 1 logs a warning and has no effect — multiple in-process handlers would share the same FFI surface, defeating any isolation a larger pool implies.
  • Round-robin state still uses the same SharedStateStore, but the worker reads it through an in-process hook instead of dialling the host's shared-state gRPC broker.
  • Pool-side panic recovery (pool/recover_inprocess.go) converts Go panics at every worker method boundary into structured internal_error responses with the original stack attached, so a recoverable panic surfaces as a normal error envelope rather than crashing the server.
Surrendered guarantees

The supervision boundary is gone, so several behaviours that the default build inherits from process isolation no longer apply:

  • Rust/native aborts, segfaults, fatal runtime throws, and OOMs terminate the whole server. The orchestrator must restart it.
  • Go panics on the direct worker method boundary are caught and returned as errors, but panics inside unrelated goroutines spawned by BAML or generated code can still crash the server.
  • Native memory growth, goroutine leaks, OS-thread leaks, and FD leaks accumulate in the server process.
  • Hung native calls cannot be killed independently of the request; a request timeout returns to the caller while the stuck work persists until the server is restarted.
  • Per-worker GOMEMLIMIT and RSS monitoring no longer isolate a child.
  • /_debug/kill-worker cannot terminate the server-side worker; the debug endpoint is degraded. /_debug/native-stacks reports native worker stacks are unavailable in in-process builds.
When to use it

Memory-constrained deployments where running two Go runtimes (server + worker) is the dominant overhead, the workload tolerates whole-process restarts on FFI failure, and an orchestrator (Kubernetes, systemd, etc.) already restarts the container on crash.

When NOT to use it

Deployments that rely on BAML FFI panic/crash isolation, that need a worker to die and be replaced without dropping unrelated in-flight requests, or that drive /_debug/kill-worker and /_debug/native-stacks as part of their operational toolkit.

Operator requirements

A container restart policy, a memory limit sized for the merged process, liveness/readiness probes that actually exercise the request path, and tolerance for losing in-flight requests when the process crashes.

Known bugs/limitations

Upstream
  • Compiler error if prompt inputs collide with imported package names in the generated BAML client (issue)
  • Dynamic classes that do not include any static fields aren't properly handled (issue)
  • BAML runtime leaks goroutines (workaround) (issue)
  • LLM client serialization fails if options contain a nested map (workaround applied) (issue; fixed in >=0.215.0)
  • Streaming API doesn't propagate dynamically created classes to the parser. When creating a new class via TypeBuilder and referencing it from an existing @@dynamic class, the streaming API fails with "Class X not found". The sync API and Parse API work correctly. (reported to BAML team)
baml-rest
  • Optional (nullable) media types (image?, (image | null)[], etc.) are not supported on BAML versions prior to 0.215.0. The BAML runtime's encoder rejects *Image with unsupported type for BAML encoding. Non-optional media types and nil optional values work on all versions.

Known broken versions

Recommended version: v0.223.0

The BuildRequest code path requires BAML v0.219.0 or newer and is taken automatically when the generated client exposes the Request/StreamRequest surfaces. Older BAML versions remain functional via the CallStream+OnTick path, but baml-rest logs a warning at startup when no BuildRequest API is detected in the generated client.

  • v0.215.0: Type builder is fully broken and panics the entire application when used (issue)
  • ≥v0.216.0 <0.218.0: Various issues in dynamic field handling (e.g., issue)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ParseMethods = map[string]bamlutils.ParseMethod{}
View Source
var Sources = make(map[string]embed.FS)

Functions

func InitBamlRuntime

func InitBamlRuntime()

func MakeAdapter

func MakeAdapter(context.Context) bamlutils.Adapter

Types

This section is empty.

Directories

Path Synopsis
common module
bamlutils module
cmd
build command
build/artifactattest command
Command artifactattest computes the reproducible de-BAML serving-cutover S2 RELEASE ARTIFACT ID for a build selection and prints it on stdout.
Command artifactattest computes the reproducible de-BAML serving-cutover S2 RELEASE ARTIFACT ID for a build selection and prints it on stdout.
build/gen-nativeworker-src command
Command gen-nativeworker-src regenerates the committed opaque tar of the isolated internal/nativebody/nanollmprepare module (de-BAML cutover Slice 2).
Command gen-nativeworker-src regenerates the committed opaque tar of the isolated internal/nativebody/nanollmprepare module (de-BAML cutover Slice 2).
build/nativeworker-overlay command
Command nativeworker-overlay applies the build-time go.mod overlay to the extracted isolated nanollm worker module under GOWORK=off.
Command nativeworker-overlay applies the build-time go.mod overlay to the extracted isolated nanollm worker module under GOWORK=off.
build/nativeworkersrc
Package nativeworkersrc packages the out-of-go.work internal/nativebody/nanollmprepare module's source into a single deterministic tar so the production builder can carry it as an OPAQUE build asset (de-BAML cutover Slice 2).
Package nativeworkersrc packages the out-of-go.work internal/nativebody/nanollmprepare module's source into a single deterministic tar so the production builder can carry it as an OPAQUE build asset (de-BAML cutover Slice 2).
embed command
gen-native-spine-worker command
Command gen-native-spine-worker emits the DEPLOYMENT-SPECIFIC native spine registry for the ExecBridge packaged workers — BOTH the native-only artifact (via the emitted NewRuntime) AND the ExecBridge-U1c standard native-capable serve worker (via the emitted NewExecutor).
Command gen-native-spine-worker emits the DEPLOYMENT-SPECIFIC native spine registry for the ExecBridge packaged workers — BOTH the native-only artifact (via the emitted NewRuntime) AND the ExecBridge-U1c standard native-capable serve worker (via the emitted NewExecutor).
hacks command
introspect command
regenerate-dynclient command
Command regenerate-dynclient orchestrates the full dynclient regeneration pipeline: patched BAML fork, BAML Go client generation off cmd/build/dynamic.baml, generated-client hacks, import rewrite, introspection, and the genadapter run that emits the framework adapter.
Command regenerate-dynclient orchestrates the full dynclient regeneration pipeline: patched BAML fork, BAML Go client generation off cmd/build/dynamic.baml, generated-client hacks, import rewrite, introspection, and the genadapter run that emits the framework adapter.
schema command
serve command
verify-adapter-pins command
verify-adapter-pins asserts that every module listed in adapterversions.PinnedModules still resolves github.com/boundaryml/baml to its canonical pin.
verify-adapter-pins asserts that every module listed in adapterversions.PinnedModules still resolves github.com/boundaryml/baml to its canonical pin.
verify-framework-adapter command
verify-framework-adapter is the CI-side gate for the codegen-emit framework adapter.go produced by adapters/common/codegen.
verify-framework-adapter is the CI-side gate for the codegen-emit framework adapter.go produced by adapters/common/codegen.
worker command
Command worker is the BAML-only subprocess worker: the default distributed build and the immediate-reversal target for the de-BAML cutover.
Command worker is the BAML-only subprocess worker: the default distributed build and the immediate-reversal target for the de-BAML cutover.
dynclient module
baml-patched module
internal
apierror
Package apierror provides utilities for returning consistent JSON error responses.
Package apierror provides utilities for returning consistent JSON error responses.
artifactprofile
Package artifactprofile is the de-BAML serving-cutover S2 artifact identity: which WORKER PROFILE a shipped baml-rest artifact carries, the release artifact ID that names the exact build, and the startup attestation that proves the two agree.
Package artifactprofile is the de-BAML serving-cutover S2 artifact identity: which WORKER PROFILE a shipped baml-rest artifact carries, the release artifact ID that names the exact build, and the startup attestation that proves the two agree.
bamlprofile
Package bamlprofile is baml-rest's leaf BAML profile over the pinned pure-Go minijinja fork github.com/invakid404/minijinja-go/v2@v2.16.0-baml.6.
Package bamlprofile is baml-rest's leaf BAML profile over the pinned pure-Go minijinja fork github.com/invakid404/minijinja-go/v2@v2.16.0-baml.6.
bamlprofile/profileoracle
Package profileoracle is the de-BAML Slice 2 PROFILE differential oracle.
Package profileoracle is the de-BAML Slice 2 PROFILE differential oracle.
codegenspine
Package codegenspine carries the M0 "contract freeze" artifacts for the rank-1 native codegen spine (see docs/codegen-spine/).
Package codegenspine carries the M0 "contract freeze" artifacts for the rank-1 native codegen spine (see docs/codegen-spine/).
debaml
Package debaml provides the root-module wiring for native de-BAML behaviour.
Package debaml provides the root-module wiring for native de-BAML behaviour.
debaml/bamlunicode
Package bamlunicode reproduces, byte-for-byte, the Unicode primitives the stock BoundaryML BAML 0.223.0 CFFI matcher (match_string) uses when it lowercases, normalizes, strips punctuation, and trims whitespace before comparing strings, enum values, and literals.
Package bamlunicode reproduces, byte-for-byte, the Unicode primitives the stock BoundaryML BAML 0.223.0 CFFI matcher (match_string) uses when it lowercases, normalizes, strips punctuation, and trims whitespace before comparing strings, enum values, and literals.
debaml/bamlunicode/cmd/driftcheck command
Command driftcheck is the pure-Go half of the #555 Unicode-parity drift guard (checks A and D of the CI job).
Command driftcheck is the pure-Go half of the #555 Unicode-parity drift guard (checks A and D of the CI job).
debaml/bamlunicode/cmd/gen command
Command gen deterministically regenerates the committed bamlunicode tables and provenance manifest from pinned UCD inputs.
Command gen deterministically regenerates the committed bamlunicode tables and provenance manifest from pinned UCD inputs.
nativebody
Package nativebody is the de-BAML Phase 4a native canonical OpenAI chat-completions body builder.
Package nativebody is the de-BAML Phase 4a native canonical OpenAI chat-completions body builder.
nativeprompt
Package nativeprompt is baml-rest's native Go implementation of BAML's prompt template renderer: a dynamic parity renderer for the generated Baml_Rest_Dynamic prompt plus a deliberately narrow static candidate, both rendered through internal/bamlprofile — the leaf BAML profile over the pinned BAML-exact minijinja fork github.com/invakid404/minijinja-go/v2.
Package nativeprompt is baml-rest's native Go implementation of BAML's prompt template renderer: a dynamic parity renderer for the generated Baml_Rest_Dynamic prompt plus a deliberately narrow static candidate, both rendered through internal/bamlprofile — the leaf BAML profile over the pinned BAML-exact minijinja fork github.com/invakid404/minijinja-go/v2.
nativeschema
Package nativeschema is the de-BAML P3 native static-schema builder (issue #586).
Package nativeschema is the de-BAML P3 native static-schema builder (issue #586).
nativespine
Package nativespine builds the neutral projectdescriptor.Project from the facts cmd/introspect already computes for the current .baml project, and classifies each method into the one native class M1 admits (unary final-call + final-parse) or a stable decline.
Package nativespine builds the neutral projectdescriptor.Project from the facts cmd/introspect already computes for the current .baml project, and classifies each method into the one native class M1 admits (unary final-call + final-parse) or a stable decline.
nativespinefixture
Package nativespinefixture is the M1 pure-Go native runtime fixture for the codegen spine (codegen-spine scope §4).
Package nativespinefixture is the M1 pure-Go native runtime fixture for the codegen spine (codegen-spine scope §4).
nativespinejsonfixture
Package nativespinejsonfixture is the ExecBridge-U1 real-population carrier fixture: the emitted hermetic native package for the single admitted static-unary method whose return is the EXACT proven direct five-arm `JSON` recursive alias (StaticRecursiveAliasJSON(topic) -> JSON).
Package nativespinejsonfixture is the ExecBridge-U1 real-population carrier fixture: the emitted hermetic native package for the single admitted static-unary method whose return is the EXACT proven direct five-arm `JSON` recursive alias (StaticRecursiveAliasJSON(topic) -> JSON).
nativespinelistfixture
Package nativespinelistfixture is the scalar-LIST input cohort's carrier fixture: the emitted hermetic native package for the single admitted method whose inputs mix required scalars with required single-level lists of non-nullable primitives and whose return is the UNCHANGED exact five-arm `JSON` recursive alias (StaticListArgsJSON(topic, ratio, tags, counts, flags) -> JSON).
Package nativespinelistfixture is the scalar-LIST input cohort's carrier fixture: the emitted hermetic native package for the single admitted method whose inputs mix required scalars with required single-level lists of non-nullable primitives and whose return is the UNCHANGED exact five-arm `JSON` recursive alias (StaticListArgsJSON(topic, ratio, tags, counts, flags) -> JSON).
rootruntime
Package rootruntime adapts the root baml_rest generated package to the small Runtime interface the worker package depends on for dispatch.
Package rootruntime adapts the root baml_rest generated package to the small Runtime interface the worker package depends on for dispatch.
schema
Package schema is baml-rest's own compact schema model, mirroring BAML's runtime spine: TypeIR (the recursive type enum) plus OutputFormatContent (the compact bundle of enum/class/recursive-alias definitions keyed for lookup).
Package schema is baml-rest's own compact schema model, mirroring BAML's runtime spine: TypeIR (the recursive type enum) plus OutputFormatContent (the compact bundle of enum/class/recursive-alias definitions keyed for lookup).
schema/outputformat
Package outputformat is a native Go port of BAML's `ctx.output_format` renderer.
Package outputformat is a native Go port of BAML's `ctx.output_format` renderer.
unsafeutil
Package unsafeutil provides unsafe operations for performance-critical code paths.
Package unsafeutil provides unsafe operations for performance-critical code paths.
workerboot
Package workerboot holds the subprocess worker's startup bootstrap, factored out of cmd/worker/main.go so more than one worker entry point can share it (de-BAML cutover Slice 2).
Package workerboot holds the subprocess worker's startup bootstrap, factored out of cmd/worker/main.go so more than one worker entry point can share it (de-BAML cutover Slice 2).
introspected module
nativeserve module
pool module
worker module
workerplugin module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址