> ## Documentation Index
> Fetch the complete documentation index at: https://docs.palico.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Long-Term Memory

> Create and restore conversation state without worrying about underlying storage infrastructure. Build chatbot with memory or complex stateless agent interactions.

## 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.

```typescript theme={null}
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.

```typescript theme={null}
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.

```typescript theme={null}
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.

```typescript theme={null}
await createConversationState<Schema>(conversationId, state);
```

## Usage

Here's an example of a conversational assistant that remember's the user's previous messages:

```typescript {9,20,34} theme={null}
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 };
};
```
