๐ฏ What You'll Learn Today
LangGraph Tutorial: Advanced Message Classification with State Management - Unit 1.3 Exercise 1
This tutorial is also available in Google Colab here or for download here
Joint Initiative: This tutorial is part of a collaboration between AI Product Engineer and the Nebius Academy.
This tutorial demonstrates how to implement sophisticated message classification in LangGraph using TypedDict and proper annotations. We'll create a state structure that combines message handling with classification metadata for enhanced conversation understanding.
Key Concepts Covered
- Classification-Aware State Management
- Confidence Score Tracking
- Type-Safe Message Handling
- Message Classification Metadata
from typing import Annotated, TypedDict
!pip install langchain-core
!pip install langgraph
from langchain_core.messages import BaseMessage, HumanMessage
from langgraph.graph.message import add_messages
Step 1: Enhanced State Definition with Classification
We define a state structure that combines message handling with classification metadata for richer conversation understanding.
class State(TypedDict):
"""Advanced state container with classification capabilities.
This implementation demonstrates three key concepts:
1. Message storage with proper LangGraph annotations
2. Classification category tracking
3. Confidence score management
Attributes:
messages: List of conversation messages with proper message
handling annotation
classification: Category label for message content
confidence: Numerical confidence score for classification
Note:
The combination of classification and confidence enables
more nuanced conversation handling and decision making.
"""
messages: Annotated[list[BaseMessage], add_messages]
classification: str
confidence: float
Why This Matters
Classification-aware state management is crucial because:
- It enables intent-based conversation routing
- Supports confidence-based decision making
- Enables more sophisticated agent behaviors
- Facilitates conversation analytics
Step 2: State Usage and Type Safety
Demonstrate proper state initialization and usage patterns.
Initialize state with classification metadata
initial_state: State = {
"messages": [HumanMessage(content="hello there")],
"classification": "greeting",
"confidence": 0.9,
}
Debug Tips
- Classification Issues:
- Verify classification string formatting
- Check confidence score range (0.0 to 1.0)
- Validate message content types
- State Management:
- Monitor classification updates
- Track confidence score changes
- Verify message handling
- Common Errors:
- TypeError: Check field type consistency
- KeyError: Verify all required fields
- ValueError: Validate confidence scores
Key Takeaways
- State Design:
- Include both content and metadata
- Use proper type annotations
- Maintain field consistency
- Classification Management:
- Track message categories
- Maintain confidence scores
- Enable informed decision making
Common Pitfalls
- Missing type annotations
- Improper confidence score range
- Inconsistent classification labels
- Incomplete state initialization
Next Steps
- Add classification validation
- Implement confidence thresholds
- Add classification history
- Enable multi-label classification
Example Usage
example_state: State = {
"messages": [HumanMessage(content="hello there")],
"classification": "greeting",
"confidence": 0.9,
}
print("Message:", example_state["messages"][0].content)
print("Classification:", example_state["classification"])
print("Confidence:", example_state["confidence"])
Expected Output
Message: hello there Classification: greeting Confidence: 0.9
Variations and Extensions
- Enhanced Classification:
- Multi-label classification support
- Hierarchical classification schemes Example use case: Complex intent recognition
- Advanced Confidence:
- Confidence history tracking
- Threshold-based routing Scenario: High-stakes decision making
๐ฌ๐ง Chapter