Understanding Common Python Syntax Used in LangGraph
Last updated
Last updated
Author:
Peer Review:
Proofread :
This is a part of
LangGraph is a powerful framework that allows you to design complex workflows for language models using a graph-based structure. It enhances the 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.
[Note]
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
, a feature within Python's typing
module, empowers developers to define dictionaries possessing a fixed structure and explicit key-value types. This enforces type safety and improves code readability.
dict
and TypedDict
Type Checking
dict
: Does not provide type checking during runtime and development.
TypedDict
: Supports static type checking using tools like mypy
or IDEs with type checking functionality enabled.
Key and Value Specification
dict
: Specifies generic key-value types (e.g., Dict[str, str]
).
TypedDict
: Explicitly defines the exact keys and their respective types.
Flexibility
dict
: Allows runtime addition or removal of keys without restriction.
TypedDict
: Enforces a predefined structure, prohibiting extra keys unless specifically designated.
TypedDict
Type Safety : Raises errors during development.
Readability : Provides a clear schema for dictionaries.
IDE Support : Enhances autocompletion and documentation.
Documentation : Serves as self-documenting code.
TypedDict
ensures type safety by enforcing fixed keys and types, unlike standard dictionaries that allow flexible key-value modifications.
The advantages of TypedDict
are highlights when utilized in pair with static type checkers like mypy
, and become apparent on IDEs such as PyCharm or VS Code, of which type-checking is enabled. These tools detect type inconsistencies and undefined keys during development, providing invaluable feedback to prevent runtime errors.
Annotated
, also residing in Python's typing
module, allows the addition of metadata to type hints. This feature supports functionality with additional context, improving code clarity and usability for both developers and development tools alike. For example, metadata can serve as supplementary documentation for readers or convey actionable information to tools.
Annotated
Additional Context : Adds metadata to enrich type hints, improving clarity for both developers and tools.
Enhanced Documentation : Serves as self-contained documentation that can clarify the purpose and constraints of variables.
Validation : Integrates with libraries like Pydantic to enforce data validation based on annotated metadata.
Framework-Specific Behavior : Enables advanced features in frameworks like 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"
).
Annotated
enriches type hints with metadata, improving code clarity and intent.
Pydantic
When used with Pydantic
, Annotated
ensures strict validation by enforcing constraints like type, range, and length. Invalid inputs trigger detailed error messages identifying the issue.
The add_messages
reducer function, referenced by the messages
key, directs LangGraph to append new messages to an existing list.
In scenarios where state keys lack annotations, each update overwrites the previous value, retaining only the most recent data.
The add_messages
function merges two inputs (left
and right
) into a consolidated message list.
Message Lists Merging : Combines two separate message lists into a signle unified list.
Append-Only State Maintenance : Ensures new messages are added while preserving existing messages.
Messages with Matching IDs : If an incoming message in right
shares an ID with an existing message in left
, it replaces the existing message. All remaining messages from right
are appended to left
.
left
(Messages): The initial message list.
right
(Messages): A list of new messages to merge or a single message to add.
Messages
: Returns a new message list with replacements as described above, merging right
into left
.
add_messages
merges message lists by appending new messages when IDs differ and replacing existing ones if IDs match.
Setting up your environment is the first step. See the guide for more details.
The langchain-opentutorial is a package of easy-to-use environment setup guidance, useful functions and utilities for tutorials. Check out the for more details.