Type hints and typeddict
Type hints document what types your functions expect and return. They do not change behavior at runtime, but they help editors catch bugs and make code self-documenting. TypedDict is how LangGraph defines agent state.
Typeddict as schema
How TypedDict enforces structure on agent state
# Basic type hints
name: str = "gemini-2.0-flash"
temperature: float = 0.7
max_tokens: int = 8000
is_active: bool = True
# Function with type hints
def truncate(text: str, max_len: int = 50) -> str:
if len(text) <= max_len:
return text
return text[:max_len] + "..."
result = truncate("This is a very long text that needs shortening", 20)
print(f"Truncated: {result}")
# Collection types
scores: list[int] = [3, 5, 1, 4]
config: dict[str, str] = {"role": "user", "content": "hello"}Type hints use : for variables and -> for return types. They are documentation that your editor can check.
Optional[str] means "either a str or None". Use it when a value might not exist. In Python 3.10+, you can write str | None instead. Both are common in AI code for optional parameters and nullable return values.
from typing import Optional, TypedDict
# Optional = str | None
def get_env(key: str, default: str | None = None) -> str | None:
import os
return os.getenv(key, default)
# TypedDict: used in LangGraph agent state
class AgentState(TypedDict):
question: str
sql_query: str
query_result: str
error: str
iteration: int
# Create a state (it is just a dict with structure)
state: AgentState = {
"question": "How many orders?",
"sql_query": "",
"query_result": "",
"error": "",
"iteration": 0,
}
state["sql_query"] = "SELECT COUNT(*) FROM orders"
print(f"SQL: {state['sql_query']}")TypedDict gives dictionaries a defined shape. It is exactly how the text-to-sql agent defines its state. The dict works normally at runtime, but your editor knows the valid keys.
Matching exercise: Match type hints
Loading practice…
Ordering exercise: Define an agent state
Loading practice…
Validation checklist: Type hints checklist
Loading practice…