0
0
LangChainframework~5 mins

State schema definition in LangChain

Choose your learning style9 modes available
Introduction

State schema definition helps you organize and control the data your app uses. It makes sure your app knows what kind of information to expect and how to handle it.

When you want to keep track of user inputs in a chat or form.
When you need to remember previous steps in a conversation.
When you want to validate the data your app processes.
When you want to structure complex data for easier management.
When you want to ensure consistent data formats across your app.
Syntax
LangChain
from langchain.memory import BaseMemory

class MyStateSchema(BaseMemory):
    def __init__(self):
        self.user_name: str = ""
        self.user_age: int = 0

    def load_memory_variables(self):
        return {"user_name": self.user_name, "user_age": self.user_age}

    def save_context(self, inputs, outputs):
        self.user_name = inputs.get("name", "")
        self.user_age = int(inputs.get("age", 0))

State schema is usually a class that holds variables representing your app's data.

It includes methods to load and save data, so your app can remember information between steps.

Examples
This example counts how many times the state is updated.
LangChain
class SimpleState(BaseMemory):
    def __init__(self):
        self.count = 0

    def load_memory_variables(self):
        return {"count": self.count}

    def save_context(self, inputs, outputs):
        self.count += 1
This example stores and retrieves a user's email address.
LangChain
class UserInfoState(BaseMemory):
    def __init__(self):
        self.user_email = ""

    def load_memory_variables(self):
        return {"email": self.user_email}

    def save_context(self, inputs, outputs):
        self.user_email = inputs.get("email", "")
Sample Program

This program defines a simple chat state that remembers the last message sent by the user. It saves the message and then loads it to show what is stored.

LangChain
from langchain.memory import BaseMemory

class ChatState(BaseMemory):
    def __init__(self):
        self.last_message = ""

    def load_memory_variables(self):
        return {"last_message": self.last_message}

    def save_context(self, inputs, outputs):
        self.last_message = inputs.get("message", "")

# Simulate usage
chat_state = ChatState()

# User sends a message
chat_state.save_context({"message": "Hello!"}, {})

# Load stored state
state_data = chat_state.load_memory_variables()
print(state_data)
OutputSuccess
Important Notes

Always define clear methods to load and save your state data.

Keep your state schema simple and focused on the data you need to remember.

Test your state schema by simulating inputs and checking stored outputs.

Summary

State schema defines how your app stores and retrieves data.

It uses classes with variables and methods to manage state.

Good state management helps your app remember important information smoothly.