{ "cells": [ { "cell_type": "markdown", "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53", "metadata": {}, "source": [ "# How to use Pydantic model as state\n", "\n", "Every [StateGraph](https://langchain-ai.github.io/langgraph/reference/graphs/#langgraph.graph.StateGraph) is a state machine. When initializing, it accepts a `state_schema` that tells it the \"shape\" of its state and how to incorporate updates from the nodes into a shared representation of what work has been done.\n", "\n", "The `state_schema` can be any [type](https://docs.python.org/3/library/stdtypes.html#type-objects), though we typically use a python-native `TypedDict` in our examples (or in the case of [MessageGraph](https://langchain-ai.github.io/langgraph/reference/graphs/#messagegraph), a [list](https://docs.python.org/3/library/stdtypes.html#list)).\n", "\n", "If you want to apply additional validation on state updates, you could instead opt for a pydantic [BaseModel](https://docs.pydantic.dev/latest/api/base_model/).\n", "\n", "In this example, we will create a ReAct agent using a pydantic base model as the state object. This means all nodes receive an instance of the model as their first arg, and validation is run before each node executes." ] }, { "cell_type": "markdown", "id": "7cbd446a-808f-4394-be92-d45ab818953c", "metadata": {}, "source": [ "## Setup\n", "\n", "First we need to install the packages required" ] }, { "cell_type": "code", "execution_count": null, "id": "af4ce0ba-7596-4e5f-8bf8-0b0bd6e62833", "metadata": {}, "outputs": [], "source": [ "%%capture --no-stderr\n", "%pip install --quiet -U langgraph langchain_openai" ] }, { "cell_type": "markdown", "id": "0abe11f4-62ed-4dc4-8875-3db21e260d1d", "metadata": {}, "source": [ "Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)" ] }, { "cell_type": "code", "execution_count": 1, "id": "c903a1cf-2977-4e2d-ad7d-8b3946821d89", "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "OPENAI_API_KEY: ········\n" ] } ], "source": [ "import getpass\n", "import os\n", "\n", "\n", "def _set_env(var: str):\n", " if not os.environ.get(var):\n", " os.environ[var] = getpass.getpass(f\"{var}: \")\n", "\n", "\n", "_set_env(\"OPENAI_API_KEY\")" ] }, { "cell_type": "markdown", "id": "f0ed46a8-effe-4596-b0e1-a6a29ee16f5c", "metadata": {}, "source": [ "
Set up LangSmith for LangGraph development
\n", "\n", " Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started here. \n", "
\n", "