langchain-ai / langgraphjs

⚡ Build language agents as graphs ⚡
https://langchain-ai.github.io/langgraphjs/
MIT License
532 stars 80 forks source link

How to reset the graph state property? #227

Open s97712 opened 3 months ago

s97712 commented 3 months ago

This is my state definition

interface IState {
  // Messages generated during the agent process, only keep the result and put into the history
  messages: BaseMessage[];
  history: BaseMessage[];
}

const graphState: StateGraphArgs<IState>["channels"] = {
  messages: {
    reducer: (a, b) => [...a, ...b],
    default: () => [],
  },
  history: {
    reducer: (a, b) => [...a, ...b],
    default: () => []
  },
};

I want to reset the messages after the agent process, and put the output into history.

But after hours of hard work, I found that all the ways to set state go through the reducer, and I can't directly set state to a certain value.

Can you provide a way to set the state without going through the'reducer ', so that we can reset the state?

hwchase17 commented 3 months ago

currently everything must go through the reducer

hinthornw commented 3 months ago

Hi @s97712 would love to hear more about your use case. The ways I do it depend on the context.

  1. Reset full state: In many cases, I would just start a new thread (if indeed this is meant to start a new interaction). The old thread is no longer needed.
  2. Reset specific values: I'd let the reducer also accept something like a "Delete" type. Something like the following pseudocode:
type reduceOperation = {
     action: "delete"
}
function reduceMessages(a?: BaseMessage[] , b?: BaseMessage[] | reduceOperation) -> BaseMessage[]{
     if (b?.action === "delete") {
         return []
     }
     return [...a, ...b];
}

const graphState: StateGraphArgs<IState>["channels"] = {
  messages: {
    reducer: (a, b) => [...a, ...b],
    default: () => [],
  },
  history: {
    reducer: (a, b) => [...a, ...b],
    default: () => []
  },
};