---
layout: default
---

# Middleware: Limitar Historial (Trim)

<div class="mt-4 text-xs">

<v-click>

```typescript
import { RemoveMessage } from "@langchain/core/messages";
import { createAgent, createMiddleware } from "langchain";
import { MemorySaver, REMOVE_ALL_MESSAGES } from "@langchain/langgraph";

const trimMessages = createMiddleware({
  name: "TrimMessages",
  beforeModel: (state) => {
    const messages = state.messages;
    if (messages.length <= 5) return;  // No recortar si hay pocos

    // Mantener primer mensaje + últimos 4
    const firstMsg = messages[0];
    const recentMsgs = messages.slice(-4);
    const newMessages = [firstMsg, ...recentMsgs];

    return {
      messages: [
        new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),
        ...newMessages,
      ],
    };
  },
});

const agent = createAgent({
  model: "mistral:mistral-large-latest",
  tools: [],
  middleware: [trimMessages],
  checkpointer: new MemorySaver(),
});
```

</v-click>

</div>
