Understanding Common Python Syntax Used in LangGraph
Last updated
Last updated
Author: JeongHo Shin
Design:
Peer Review:
This is a part of LangChain Open Tutorial
LangGraph is a powerful framework that allows you to design complex workflows for language models using a graph-based structure. It enhances modularity, scalability, and efficiency in building AI-driven applications.
This tutorial explains key Python concepts frequently used in LangGraph, including TypedDict
, Annotated
, and the add_messages
function. We will also compare these concepts with standard Python features to highlight their advantages and typical use cases.
Setting up your environment is the first step. See the Environment Setup guide for more details.
[Note]
The langchain-opentutorial is a package of easy-to-use environment setup guidance, useful functions and utilities for tutorials. Check out the langchain-opentutorial
for more details.
You can set API keys in a .env
file or set them manually.
[Note] If you’re not using the .env
file, no worries! Just enter the keys directly in the cell below, and you’re good to go.
TypedDict
is a feature introduced in Python's typing
module that enables developers to define dictionaries with a fixed structure and explicit key-value types. It ensures type safety and improves code readability.
dict
and TypedDict
Type Checking
dict
: Does not provide type checking at runtime or during development.
TypedDict
: Supports static type checking using tools like mypy
or IDEs with type checking enabled.
Key and Value Specification
dict
: Specifies generic key-value types (e.g., Dict[str, str]
).
TypedDict
: Specifies the exact keys and their respective types.
Flexibility
dict
: Allows runtime addition or removal of keys without restriction.
TypedDict
: Enforces a predefined structure, disallowing extra keys unless explicitly marked.
TypedDict
?Type Safety : Helps catch errors during development.
Readability : Provides a clear schema for dictionaries.
IDE Support : Enhances autocompletion and documentation.
Documentation : Serves as self-documenting code.
TypedDict
truly shines when paired with static type checkers like mypy
or when using IDEs such as PyCharm or VS Code with type-checking enabled. These tools detect type mismatches and undefined keys at development time, providing valuable feedback to prevent runtime errors.
Annotated
is a feature in Python's typing
module that allows metadata to be added to type hints. This feature provides enhanced functionality by including additional context, improving code readability and usability for developers and tools alike. For example, metadata can act as additional documentation for readers or as actionable information for tools.
Annotated
?Additional Context : Adds metadata to enrich type hints, improving clarity for developers and tools.
Enhanced Documentation : Serves as self-contained documentation that can clarify the purpose and constraints of variables.
Validation : Can be combined with libraries like Pydantic to enforce data validation using the annotated metadata.
Framework-Specific Behavior : Enables advanced features in frameworks such as LangGraph by defining specialized operations.
Type: Defines the variable's data type (e.g., int
, str
, List[str]
, etc.).
Metadata: Adds descriptive information about the variable (e.g., "unit: cm"
, "range: 0-100"
).
Pydantic
The add_messages
reducer function, referenced by the messages
key, instructs LangGraph to append new messages to an existing list.
For state keys without annotations, each update overwrites the value, storing only the most recent data.
The add_messages
function operates by merging two inputs (left
and right
) into a unified list of messages.
Merges Two Message Lists : Combines two separate message lists into one.
Maintains Append-Only State : Ensures that new messages are added while retaining existing ones.
Replaces Messages with Matching IDs : If a message in right
has the same ID as one in left
, it replaces the existing message.
Messages in right
with IDs that match those in left
replace the corresponding messages in left
.
All other messages in right
are appended to left
.
left
(Messages): The base list of messages.
right
(Messages): A list of new messages to merge or a single message to add.
Messages
: A new list of messages that merges right
into left
.