State Management Function
You can use the following functions to manage conversation state in your application.
Get Conversation State
Gets the conversation state for a given conversation ID.
const state = await getConversationState<Schema>(conversationId);
Set Conversation State
Sets the conversation state for a given conversation ID. If the conversation state already exists, it will be overwritten.
await setConversationState<Schema>(conversationId, state);
Update Conversation State
Updates the conversation state for a given conversation ID. If the conversation state does not exist, it will throw an error.
await updateConversationState<Schema>(conversationId, state);
Create Conversation State
Creates a new conversation state for a given conversation ID. If the conversation state already exists, it will throw an error.
await createConversationState<Schema>(conversationId, state);
Usage
Here’s an example of a conversational assistant that remember’s the user’s previous messages:
import {
Chat,
// import conversation state management functions
getConversationState,
setConversationState,
} from "@palico-ai/app";
const handler: Chat = async ({
conversationId,
isNewConversation,
userMessage,
}) => {
let state: {
messages: OpenAIMessage[];
};
// create or restore conversation state
if (isNewConversation) {
state = { messages: [] };
} else {
state = await getConversationState(conversationId);
}
// add user message to conversation state and call LLM
state.messages.push({ role: "user", content: userMessage });
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo-0125",
messages: state.messages,
});
const responseMessage = response.choices[0].message.content;
// add agent message to conversation state
state.messages.push({ role: "agent", content: responseMessage });
// save conversation state
await setConversationState(conversationId, state);
return { message: responseMessage };
};