# ContextEdit

> **Interface** in `langchain`

📖 [View in docs](https://reference.langchain.com/javascript/langchain/index/ContextEdit)

Protocol describing a context editing strategy.

Implement this interface to create custom strategies for managing
conversation context size. The `apply` method should modify the
messages array in-place and return the updated token count.

## Signature

```javascript
interface ContextEdit
```

## Methods

- [`apply()`](https://reference.langchain.com/javascript/langchain/index/ContextEdit/apply)

## Examples

```ts
import { HumanMessage, type ContextEdit, type BaseMessage  } from "langchain";

class RemoveOldHumanMessages implements ContextEdit {
  constructor(private keepRecent: number = 10) {}

  async apply({ messages, countTokens }) {
    // Check current token count
    const tokens = await countTokens(messages);

    // Remove old human messages if over limit, keeping the most recent ones
    if (tokens > 50000) {
      const humanMessages: number[] = [];

      // Find all human message indices
      for (let i = 0; i < messages.length; i++) {
        if (HumanMessage.isInstance(messages[i])) {
          humanMessages.push(i);
        }
      }

      // Remove old human messages (keep only the most recent N)
      const toRemove = humanMessages.slice(0, -this.keepRecent);
      for (let i = toRemove.length - 1; i >= 0; i--) {
        messages.splice(toRemove[i]!, 1);
      }
    }
  }
}
```

---

[View source on GitHub](https://github.com/langchain-ai/langchainjs/blob/0c9440396c725d43b4758eb1b931c955e64ad8ec/libs/langchain/src/agents/middleware/contextEditing.ts#L72)