[Python] Langgraph: How to retrieve and store chat history throughout the session

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to the Langgraph. I am trying to retrieve chathistory from state into a variable untill the session close.

    below what i have tried

    llm = ChatOpenAI(temperature=1.0)

    class State(TypedDict):
    messages : Annotated[list, add_messages]

    graph_builder = StateGraph(State)

    print(graph_builder)

    def chatbot(state:State):
    user_message = state["messages"][-1].content
    ai_response = llm.invoke(user_message)
    return {"messages": [AIMessage(content=ai_response)]}

    def past_message_node(state: State):
    print("Conversation history")
    past_message = state['messages']
    contents = [msg.content for msg in past_message]
    print("Message History:", ", ".join(contents))
    return state

    raph_builder.add_node("chatbot", chatbot)
    graph_builder.add_edge(START, "chatbot")
    graph_builder.add_node("past_message_node", past_message_node)
    graph_builder.add_edge("chatbot", "past_message_node")
    graph_builder.add_edge("past_message_node", END)
    graph = graph_builder.compile()
    while True:
    user_input = input("User: ")

    if user_input.lower() in ['quit', 'q']:
    print("Chat Ended")
    break
    for event in graph.stream({"messages": ("user", user_input)}):
    for value in event.values():
    messages = value["messages"]
    if (isinstance(messages, list)):
    last_message = messages[-1]
    else:
    last_message = messages
    print("Assistent: ", last_message.content)


    #Expected: Along with AI_message, i want to print the chathistory from begining

    For eg:
    input1: Hi
    Ai_message: How can i help you
    Message History: Hi, How can i help you

    input2: What is the capital of UK?
    Ai_message: London
    Message History: Hi, How can i help you, What is the capital of UK?, London



    ideally i am expecting the chat_hisitory from the state["message"] appended each time, so that i can retrieve the chat_hisitory

    #Actual

    Getting multiple error
    pydantic_core._pydantic_core.ValidationError: 21 validation errors for AIMessage
    content.str
    Input should be a valid string [type=string_type, input_value=AIMessage(content='Hello!...o': 0, 'reasoning': 0}}), input_type=AIMessage]


    so what is the best solution to retrive and store chat_history in one variable and print through out the session?

    Continue reading...

Compartilhe esta Página