getMutableAIState retrieves the current AI state on the server and returns a mutable handle for reading conversation history and recording updates. It is useful when a server action needs shared conversation state without receiving history as an argument. section 4.2.3
Use the handle to coordinate a streaming conversation:
- Call getMutableAIState inside a server action such as continueConversation. section 4.2.3
- Read the current messages with history.get(), then append the new user input before calling streamUI. section 4.2.3
- Call history.done(...) when the streamed response completes so the updated conversation becomes the AI state. section 4.2.3
- Initialize the surrounding state through createAI and expose its provider from the application layout. section 4.2.2
Streaming a conversation with mutable state
A server action can resolve the conversation history, send it to streamUI, and finalize the state when generation finishes: const history = getMutableAIState(); const result = await streamUI({ model, messages: [...history.get(), { role: 'user', content: input }], text: ({ content, done }) => { if (done) history.done([...history.get(), { role: 'assistant', content }]); return <ChatBubble role="assistant" text={content} />; } }); section 4.2.3
Listing 4.7 Managing the conversation history with getMutableAIState
export async function
continueConversation(input, provider, model) {
'use server';
const supportedModel = getSupportedModel(provider, model);
const history = getMutableAIState(); #1
const result = await streamUI({. #2
model: supportedModel,
messages: [...history.get(), { role: 'user', content: input }], #3
text: ({ content, done }) => {
if (done) {
history.done([...history.get(),
{ role: 'assistant', content: input }]); #4
}
return <ChatBubble role="assistant" text={content}
className={`mr-auto border-none`} />;
},
});
return {
id: generateId(),
role: 'assistant',
display: result.value, #5
};
}
export const AI = createAI({. #6
actions: {
continueConversation,
},
initialAIState: [],
initialUIState: {
messages: [],
},
});
Inspect the complete server action, including model selection, streamed UI output, state finalization, and createAI configuration. section 4.2.3
