Understanding Common Python Syntax Used in LangGraph

Open in ColabOpen in GitHub

Overview

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.

Table of Contents

References


Environment Setup

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

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.

Key Differences between dict and TypedDict

  1. 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.

  1. 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.

  1. Flexibility

  • dict : Allows runtime addition or removal of keys without restriction.

  • TypedDict : Enforces a predefined structure, prohibiting extra keys unless specifically designated.

Benefits of using 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.

Example

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

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.

Benefits of using 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.

Syntax

  • 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").

Usage Example

Annotated enriches type hints with metadata, improving code clarity and intent.

Example with 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.

add_messages

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.

Key Features

  • 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.

Parameters:

  • left (Messages): The initial message list.

  • right (Messages): A list of new messages to merge or a single message to add.

Outputs:

  • Messages : Returns a new message list with replacements as described above, merging right into left.

Example

add_messages merges message lists by appending new messages when IDs differ and replacing existing ones if IDs match.

Last updated