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.
State schema definition in LangChain
Start learning this pattern below
Jump into concepts and practice - no test required
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.
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
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", "")
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.
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)
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.
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.
Practice
state schema in a Langchain application?Solution
Step 1: Understand the role of state schema
A state schema defines the structure and rules for storing data in an app.Step 2: Differentiate from other app parts
UI components, SQL queries, and network handling are unrelated to state schema definition.Final Answer:
To specify how the app stores and manages its data -> Option AQuick Check:
State schema = data structure [OK]
- Confusing state schema with UI design
- Thinking state schema handles network calls
- Mixing state schema with database query writing
Solution
Step 1: Identify correct class syntax
class StateSchema: def __init__(self): self.value = None correctly defines a class with an __init__ method setting an instance variable.Step 2: Check other options for errors
def StateSchema(): value = None is a function, not a class; C is a dict, not a class; D defines a class but does not initialize instance variables properly.Final Answer:
class StateSchema:\n def __init__(self):\n self.value = None -> Option CQuick Check:
Class with __init__ and self.value = None = A [OK]
- Defining a function instead of a class
- Using dictionary syntax instead of class
- Not initializing instance variables inside __init__
class UserState:
def __init__(self):
self.name = ''
self.age = 0
state = UserState()
state.name = 'Alice'
state.age = 30
print(state.name, state.age)What will be printed?
Solution
Step 1: Understand class initialization
The UserState class initializes name as empty string and age as 0.Step 2: Check assigned values before print
state.name is set to 'Alice' and state.age to 30 before printing.Final Answer:
Alice 30 -> Option AQuick Check:
Assigned values printed = Alice 30 [OK]
- Assuming default values print instead of assigned
- Confusing variable names with strings
- Expecting error due to missing attributes
class AppState:
def __init__(self):
self.count = 0
state = AppState()
print(state.counter)Solution
Step 1: Check attribute names
The class defines 'count' but the print statement uses 'counter'.Step 2: Understand Python attribute errors
Accessing an undefined attribute causes AttributeError at runtime.Final Answer:
AttributeError because 'counter' is not defined -> Option DQuick Check:
Wrong attribute name = AttributeError [OK]
- Assuming print shows 0 despite wrong attribute
- Thinking it's a syntax error
- Confusing attribute error with type error
name (string), age (integer), and a list of tasks (strings). Which class definition correctly models this in Langchain?Solution
Step 1: Check correct initialization of instance variables
class UserState: def __init__(self): self.name = '' self.age = 0 self.tasks = [] initializes name as empty string, age as 0, and tasks as empty list, matching the required types.Step 2: Evaluate other options for type correctness
class UserState: name = '' age = 0 tasks = [] uses class variables, not instance variables; C sets tasks to None instead of list; D sets age and tasks as empty strings, wrong types.Final Answer:
class UserState:\n def __init__(self):\n self.name = ''\n self.age = 0\n self.tasks = [] -> Option BQuick Check:
Instance vars with correct types = B [OK]
- Using class variables instead of instance variables
- Setting wrong default types (e.g., string instead of int)
- Initializing list variables as None or empty string
