LangChain OpenTutorial
  • 🦜️🔗 The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • TypedDict
  • Key Differences between dict and TypedDict
  • Benefits of using TypedDict
  • Example
  • Annotated
  • Benefits of using Annotated
  • Syntax
  • Usage Example
  • Example with Pydantic
  • add_messages
  • Key Features
  • Parameters:
  • Outputs:
  • Example
  1. 17-LangGraph
  2. 01-Core-Features

Understanding Common Python Syntax Used in LangGraph

Previous01-Core-FeaturesNextTitle

Last updated 28 days ago

  • Author:

  • Peer Review:

  • Proofread :

  • This is a part of

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

[Note]

%%capture --no-stderr
%pip install langchain-opentutorial
# Install required packages
from langchain_opentutorial import package

package.install(
    [
        "langsmith",
        "langchain",
        "langchain_core",
        "langchain-anthropic",
        "langchain_community",
        "langchain_text_splitters",
        "langchain_openai",
    ],
    verbose=False,
    upgrade=False,
)

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.

from dotenv import load_dotenv
from langchain_opentutorial import set_env

# Attempt to load environment variables from a .env file; if unsuccessful, set them manually.
if not load_dotenv():
    set_env(
        {
            "OPENAI_API_KEY": "",
            "LANGCHAIN_API_KEY": "",
            "LANGCHAIN_TRACING_V2": "true",
            "LANGCHAIN_ENDPOINT": "https://api.smith.langchain.com",
            "LANGCHAIN_PROJECT": "",  # set the project name same as the title
        }
    )
Environment variables have been set successfully.

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.

from typing import Dict, TypedDict

# Standard Python dictionary usage
sample_dict: Dict[str, str] = {
    "name": "Teddy",
    "age": "30",  # Stored as a string (allowed in dict)
    "job": "Developer",
}

# Using TypedDict
class Person(TypedDict):
    name: str
    age: int  # Defined as an integer
    job: str

typed_dict: Person = {"name": "Shirley", "age": 25, "job": "Designer"}

# Behavior with a standard dictionary
sample_dict["age"] = 35  # Type inconsistency is allowed
sample_dict["new_field"] = "Additional Info"  # Adding new keys is allowed

# Behavior with TypedDict
typed_dict["age"] = 35  # Correct usage
typed_dict["age"] = "35"  # Error: Type mismatch detected by type checker
typed_dict["new_field"] = "Additional Info"  # Error: Key not defined in TypedDict

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.

from typing import Annotated

# Basic usage of Annotated with metadata for descriptive purposes
name: Annotated[str, "User's name"]
age: Annotated[int, "User's age (0-150)"]

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.

from typing import Annotated, List
from pydantic import Field, BaseModel, ValidationError

class Employee(BaseModel):
    id: Annotated[int, Field(..., description="Employee ID")]
    name: Annotated[str, Field(..., min_length=3, max_length=50, description="Name")]
    age: Annotated[int, Field(gt=18, lt=65, description="Age (19-64)")]
    salary: Annotated[float, Field(gt=0, lt=10000, description="Salary (in units of 10,000, up to 10 billion)")]
    skills: Annotated[List[str], Field(min_items=1, max_items=10, description="Skills (1-10 items)")]

# Example of valid data
try:
    valid_employee = Employee(
        id=1, name="Teddynote", age=30, salary=1000, skills=["Python", "LangChain"]
    )
    print("Valid employee data:", valid_employee)
except ValidationError as e:
    print("Validation error:", e)

# Example of invalid data
try:
    invalid_employee = Employee(
        id=1,
        name="Ted",  # Name is too short
        age=17,  # Age is out of range
        salary=20000,  # Salary exceeds the maximum
        skills="Python",  # Skills is not a list
    )
except ValidationError as e:
    print("Validation errors:")
    for error in e.errors():
        print(f"- {error['loc'][0]}: {error['msg']}")
Valid employee data: id=1 name='Teddynote' age=30 salary=1000.0 skills=['Python', 'LangChain']
    Validation errors:
    - age: Input should be greater than 18
    - salary: Input should be less than 10000
    - skills: Input should be a valid list

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.

from langchain_core.messages import AIMessage, HumanMessage
from langgraph.graph.message import add_messages


# Example 1: Merging two message lists
# `msgs1` and `msgs2` are combined into a single list without overlapping IDs.
msgs1 = [HumanMessage(content="Hello?", id="1")]
msgs2 = [AIMessage(content="Nice to meet you!", id="2")]

result1 = add_messages(msgs1, msgs2)
print(result1)

# Example 2: Replacing messages with the same ID
# If `msgs2` contains a message with the same ID as one in `msgs1`,
# the message in `msgs2` replaces the corresponding message in `msgs1`.
msgs1 = [HumanMessage(content="Hello?", id="1")]
msgs2 = [HumanMessage(content="Nice to meet you!", id="1")]

result2 = add_messages(msgs1, msgs2)
print(result2)
[HumanMessage(content='Hello?', additional_kwargs={}, response_metadata={}, id='1'), AIMessage(content='Nice to meet you!', additional_kwargs={}, response_metadata={}, id='2')]
    [HumanMessage(content='Nice to meet you!', additional_kwargs={}, response_metadata={}, id='1')]

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.

LangGraph
Environment Setup
langchain-opentutorial
JeongHo Shin
Chaeyoon Kim
LangChain Open Tutorial
Overview
Environment Setup
Typedict
Annotated
add_messages