Next.js Integration
BAML can be used with Vercel’s AI SDK to stream BAML functions to your UI.
The latest example code is found in our NextJS starter, but this tutorial will guide you on how to add BAML step-by-step.
See the live demo
You will need to use Server Actions, from the App Router, for this tutorial. You can still stream BAML functions from Route Handlers however.
Install BAML, and Generate a BAML client for TypeScript
- Follow the TS installation guide
- Install the VSCode extension and Save a baml file to generate the client (or use
npx baml-cli generate
).
Update next.config.mjs
@boundaryml/baml uses a native node addon to run the BAML functions. You need to tell NextJS to use the loader for these files.
Create some helper utilities to stream BAML functions
Let’s add some helpers to export our baml functions as streamable server actions. See the last line in this file, where we export the extractResume
function.
In app/utils/streamableObject.tsx
add the following code:
Export your BAML functions to streamable server actions
In app/actions/extract.tsx
add the following code:
Create a hook to use the streamable functions in React Components
This hook will work like react-query, but for BAML functions. It will give you partial data, the loading status, and whether the stream was completed.
In app/_hooks/useStream.ts
add:
And now you’re all set!
If you have issues with your environment variables not loading, you may want to use dotenv-cli to load your env vars before the nextjs process starts:
dotenv -- npm run dev