Get started with AI agents in React Flow using Liveblocks and Next.js
Liveblocks is a realtime collaboration infrastructure for building performant
collaborative experiences. Follow the following steps to add an AI agent that
can read and edit a collaborative React Flow diagram
from your Next.js /app directory application using
mutateFlow from
@liveblocks/react-flow, the
Vercel AI SDK, and OpenAI.
Quickstart
Have a React Flow app ready
To let an AI edit your diagram, you first need a Liveblocks React Flow app set up with secret key authentication. Open up your app, or set up React Flow if you haven’t already.
Get started with React Flow
Install dependencies
Install
@liveblocks/nodeand the Node-side@liveblocks/react-flowentry point, along with the Vercel AI SDK, the OpenAI provider, andzodto validate tool inputs.TerminalAdd your environment variables
Create a
.env.localfile and add your Liveblocks secret key from the dashboard, and your OpenAI API key from the OpenAI dashboard..env.localCreate the AI agent
Create a server action that uses
mutateFlowto open the room’s flow on the server and let the AI add and update nodes and edges. Each Vercel AI SDK tool maps to one of theMutableFlowmethods likeflow.addNode,flow.updateNodeData, orflow.addEdge.app/run-flow-agent.tsmutateFlowopens the room’s flow for reading and mutating. Any changes made through theflowobject are intelligently synced to all connected clients via Liveblocks Storage, so the diagram updates in realtime as the AI works.Add a prompt form to the page
Now add a small form that lets users describe what the agent should do. It uses
useRoomto get the current room ID and passes it to the server action.app/FlowAgentForm.tsxThen render it next to your existing
Flowcomponent:app/page.tsxNext: show the agent in the room
Your AI agent now reads and writes to your React Flow diagram in realtime. Next, give the agent a face—show its avatar in the avatar stack and highlight the nodes it’s editing using Liveblocks Presence.
Add AI Presence
What to read next
Congratulations! You’ve set up the foundation for an AI agent that can edit your collaborative React Flow diagrams.