Graph Definitions¶
Graph
¶
Source code in libs/langgraph/langgraph/graph/graph.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
|
add_conditional_edges(source: str, path: Union[Callable[..., Union[Hashable, list[Hashable]]], Callable[..., Awaitable[Union[Hashable, list[Hashable]]]], Runnable[Any, Union[Hashable, list[Hashable]]]], path_map: Optional[Union[dict[Hashable, str], list[str]]] = None, then: Optional[str] = None) -> Self
¶
Add a conditional edge from the starting node to any number of destination nodes.
Parameters:
-
source
(
) –str The starting node. This conditional edge will run when exiting this node.
-
path
(
) –Union [Callable ,Runnable ]The callable that determines the next node or nodes. If not specifying
path_map
it should return one or more nodes. If it returns END, the graph will stop execution. -
path_map
(
, default:Optional [dict [Hashable ,str ]]None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(
, default:Optional [str ]None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
–Self None
Without typehints on the path
function's return value (e.g., -> Literal["foo", "__end__"]:
)
or a path_map, the graph visualization assumes the edge could transition to any node in the graph.
Source code in libs/langgraph/langgraph/graph/graph.py
set_entry_point(key: str) -> Self
¶
Specifies the first node to be called in the graph.
Equivalent to calling add_edge(START, key)
.
Parameters:
-
key
(
) –str The key of the node to set as the entry point.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
set_conditional_entry_point(path: Union[Callable[..., Union[Hashable, list[Hashable]]], Callable[..., Awaitable[Union[Hashable, list[Hashable]]]], Runnable[Any, Union[Hashable, list[Hashable]]]], path_map: Optional[Union[dict[Hashable, str], list[str]]] = None, then: Optional[str] = None) -> Self
¶
Sets a conditional entry point in the graph.
Parameters:
-
path
(
) –Union [Callable ,Runnable ]The callable that determines the next node or nodes. If not specifying
path_map
it should return one or more nodes. If it returns END, the graph will stop execution. -
path_map
(
, default:Optional [dict [str ,str ]]None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(
, default:Optional [str ]None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
set_finish_point(key: str) -> Self
¶
Marks a node as a finish point of the graph.
If the graph reaches this node, it will cease execution.
Parameters:
-
key
(
) –str The key of the node to set as the finish point.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
CompiledGraph
¶
Bases:
Source code in libs/langgraph/langgraph/graph/graph.py
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 |
|
stream_mode: StreamMode = stream_mode
class-attribute
instance-attribute
¶
Mode to stream output, defaults to 'values'.
stream_channels: Optional[Union[str, Sequence[str]]] = stream_channels
class-attribute
instance-attribute
¶
Channels to stream, defaults to all channels not in reserved channels
step_timeout: Optional[float] = step_timeout
class-attribute
instance-attribute
¶
Maximum time to wait for a step to complete, in seconds. Defaults to None.
debug: bool = debug if debug is not None else get_debug()
instance-attribute
¶
Whether to print debug information during execution. Defaults to False.
checkpointer: Checkpointer = checkpointer
class-attribute
instance-attribute
¶
Checkpointer used to save and load graph state. Defaults to None.
store: Optional[BaseStore] = store
class-attribute
instance-attribute
¶
Memory store to use for SharedValues. Defaults to None.
retry_policy: Optional[RetryPolicy] = retry_policy
class-attribute
instance-attribute
¶
Retry policy to use when running tasks. Set to None to disable.
get_state(config: RunnableConfig, *, subgraphs: bool = False) -> StateSnapshot
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state(config: RunnableConfig, *, subgraphs: bool = False) -> StateSnapshot
async
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
get_state_history(config: RunnableConfig, *, filter: Optional[Dict[str, Any]] = None, before: Optional[RunnableConfig] = None, limit: Optional[int] = None) -> Iterator[StateSnapshot]
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state_history(config: RunnableConfig, *, filter: Optional[Dict[str, Any]] = None, before: Optional[RunnableConfig] = None, limit: Optional[int] = None) -> AsyncIterator[StateSnapshot]
async
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
update_state(config: RunnableConfig, values: Optional[Union[dict[str, Any], Any]], as_node: Optional[str] = None) -> RunnableConfig
¶
Update the state of the graph with the given values, as if they came from
node as_node
. If as_node
is not provided, it will be set to the last node
that updated the state, if not ambiguous.
Source code in libs/langgraph/langgraph/pregel/__init__.py
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 |
|
stream(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: Optional[Union[StreamMode, list[StreamMode]]] = None, output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, subgraphs: bool = False) -> Iterator[Union[dict[str, Any], Any]]
¶
Stream graph steps for a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input to the graph.
-
config
(
, default:Optional [RunnableConfig ]None
) –The configuration to use for the run.
-
stream_mode
(
, default:Optional [Union [StreamMode ,list [StreamMode ]]]None
) –The mode to stream output, defaults to self.stream_mode. Options are 'values', 'updates', and 'debug'. values: Emit the current values of the state for each step. updates: Emit only the updates to the state for each step. Output is a dict with the node name as key and the updated values as value. debug: Emit debug events for each step.
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(
, default:Optional [bool ]None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(
, default:bool False
) –Whether to stream subgraphs, defaults to False.
Yields:
-
–Union [dict [str ,Any ],Any ]The output of each step in the graph. The output shape depends on the stream_mode.
Examples:
Using different stream modes with a graph:
>>> import operator
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.graph import StateGraph
>>> from langgraph.constants import START
...
>>> class State(TypedDict):
... alist: Annotated[list, operator.add]
... another_list: Annotated[list, operator.add]
...
>>> builder = StateGraph(State)
>>> builder.add_node("a", lambda _state: {"another_list": ["hi"]})
>>> builder.add_node("b", lambda _state: {"alist": ["there"]})
>>> builder.add_edge("a", "b")
>>> builder.add_edge(START, "a")
>>> graph = builder.compile()
>>> for event in graph.stream({"alist": ['Ex for stream_mode="values"']}, stream_mode="values"):
... print(event)
{'alist': ['Ex for stream_mode="values"'], 'another_list': []}
{'alist': ['Ex for stream_mode="values"'], 'another_list': ['hi']}
{'alist': ['Ex for stream_mode="values"', 'there'], 'another_list': ['hi']}
>>> for event in graph.stream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
>>> for event in graph.stream({"alist": ['Ex for stream_mode="debug"']}, stream_mode="debug"):
... print(event)
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': []}, 'triggers': ['start:a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'result': [('another_list', ['hi'])]}}
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': ['hi']}, 'triggers': ['a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'result': [('alist', ['there'])]}}
Source code in libs/langgraph/langgraph/pregel/__init__.py
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 |
|
astream(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: Optional[Union[StreamMode, list[StreamMode]]] = None, output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, subgraphs: bool = False) -> AsyncIterator[Union[dict[str, Any], Any]]
async
¶
Stream graph steps for a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input to the graph.
-
config
(
, default:Optional [RunnableConfig ]None
) –The configuration to use for the run.
-
stream_mode
(
, default:Optional [Union [StreamMode ,list [StreamMode ]]]None
) –The mode to stream output, defaults to self.stream_mode. Options are 'values', 'updates', and 'debug'. values: Emit the current values of the state for each step. updates: Emit only the updates to the state for each step. Output is a dict with the node name as key and the updated values as value. debug: Emit debug events for each step.
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(
, default:Optional [bool ]None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(
, default:bool False
) –Whether to stream subgraphs, defaults to False.
Yields:
-
–AsyncIterator [Union [dict [str ,Any ],Any ]]The output of each step in the graph. The output shape depends on the stream_mode.
Examples:
Using different stream modes with a graph:
>>> import operator
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.graph import StateGraph
>>> from langgraph.constants import START
...
>>> class State(TypedDict):
... alist: Annotated[list, operator.add]
... another_list: Annotated[list, operator.add]
...
>>> builder = StateGraph(State)
>>> builder.add_node("a", lambda _state: {"another_list": ["hi"]})
>>> builder.add_node("b", lambda _state: {"alist": ["there"]})
>>> builder.add_edge("a", "b")
>>> builder.add_edge(START, "a")
>>> graph = builder.compile()
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="values"']}, stream_mode="values"):
... print(event)
{'alist': ['Ex for stream_mode="values"'], 'another_list': []}
{'alist': ['Ex for stream_mode="values"'], 'another_list': ['hi']}
{'alist': ['Ex for stream_mode="values"', 'there'], 'another_list': ['hi']}
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="debug"']}, stream_mode="debug"):
... print(event)
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': []}, 'triggers': ['start:a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'result': [('another_list', ['hi'])]}}
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': ['hi']}, 'triggers': ['a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'result': [('alist', ['there'])]}}
Source code in libs/langgraph/langgraph/pregel/__init__.py
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 |
|
invoke(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: StreamMode = 'values', output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, **kwargs: Any) -> Union[dict[str, Any], Any]
¶
Run the graph with a single input and config.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input data for the graph. It can be a dictionary or any other type.
-
config
(
, default:Optional [RunnableConfig ]None
) –Optional. The configuration for the graph run.
-
stream_mode
(
, default:StreamMode 'values'
) –Optional[str]. The stream mode for the graph run. Default is "values".
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –Optional. The output keys to retrieve from the graph run.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt the graph run before.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt the graph run after.
-
debug
(
, default:Optional [bool ]None
) –Optional. Enable debug mode for the graph run.
-
**kwargs
(
, default:Any {}
) –Additional keyword arguments to pass to the graph run.
Returns:
-
–Union [dict [str ,Any ],Any ]The output of the graph run. If stream_mode is "values", it returns the latest output.
-
–Union [dict [str ,Any ],Any ]If stream_mode is not "values", it returns a list of output chunks.
Source code in libs/langgraph/langgraph/pregel/__init__.py
ainvoke(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: StreamMode = 'values', output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, **kwargs: Any) -> Union[dict[str, Any], Any]
async
¶
Asynchronously invoke the graph on a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input data for the computation. It can be a dictionary or any other type.
-
config
(
, default:Optional [RunnableConfig ]None
) –Optional. The configuration for the computation.
-
stream_mode
(
, default:StreamMode 'values'
) –Optional. The stream mode for the computation. Default is "values".
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –Optional. The output keys to include in the result. Default is None.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt before. Default is None.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt after. Default is None.
-
debug
(
, default:Optional [bool ]None
) –Optional. Whether to enable debug mode. Default is None.
-
**kwargs
(
, default:Any {}
) –Additional keyword arguments.
Returns:
-
–Union [dict [str ,Any ],Any ]The result of the computation. If stream_mode is "values", it returns the latest value.
-
–Union [dict [str ,Any ],Any ]If stream_mode is "chunks", it returns a list of chunks.
Source code in libs/langgraph/langgraph/pregel/__init__.py
get_graph(config: Optional[RunnableConfig] = None, *, xray: Union[int, bool] = False) -> DrawableGraph
¶
Returns a drawable representation of the computation graph.
Source code in libs/langgraph/langgraph/graph/graph.py
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 |
|
StateGraph
¶
Bases:
A graph whose nodes communicate by reading and writing to a shared state.
The signature of each node is State -> Partial
Each state key can optionally be annotated with a reducer function that will be used to aggregate the values of that key received from multiple nodes. The signature of a reducer function is (Value, Value) -> Value.
Parameters:
-
state_schema
(
, default:Type [Any ]None
) –The schema class that defines the state.
-
config_schema
(
, default:Optional [Type [Any ]]None
) –The schema class that defines the configuration. Use this to expose configurable parameters in your API.
Examples:
>>> from langchain_core.runnables import RunnableConfig
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.checkpoint.memory import MemorySaver
>>> from langgraph.graph import StateGraph
>>>
>>> def reducer(a: list, b: int | None) -> list:
... if b is not None:
... return a + [b]
... return a
>>>
>>> class State(TypedDict):
... x: Annotated[list, reducer]
>>>
>>> class ConfigSchema(TypedDict):
... r: float
>>>
>>> graph = StateGraph(State, config_schema=ConfigSchema)
>>>
>>> def node(state: State, config: RunnableConfig) -> dict:
... r = config["configurable"].get("r", 1.0)
... x = state["x"][-1]
... next_value = x * r * (1 - x)
... return {"x": next_value}
>>>
>>> graph.add_node("A", node)
>>> graph.set_entry_point("A")
>>> graph.set_finish_point("A")
>>> compiled = graph.compile()
>>>
>>> print(compiled.config_specs)
[ConfigurableFieldSpec(id='r', annotation=<class 'float'>, name=None, description=None, default=None, is_shared=False, dependencies=None)]
>>>
>>> step1 = compiled.invoke({"x": 0.5}, {"configurable": {"r": 3.0}})
>>> print(step1)
{'x': [0.5, 0.75]}
Source code in libs/langgraph/langgraph/graph/state.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
|
add_conditional_edges(source: str, path: Union[Callable[..., Union[Hashable, list[Hashable]]], Callable[..., Awaitable[Union[Hashable, list[Hashable]]]], Runnable[Any, Union[Hashable, list[Hashable]]]], path_map: Optional[Union[dict[Hashable, str], list[str]]] = None, then: Optional[str] = None) -> Self
¶
Add a conditional edge from the starting node to any number of destination nodes.
Parameters:
-
source
(
) –str The starting node. This conditional edge will run when exiting this node.
-
path
(
) –Union [Callable ,Runnable ]The callable that determines the next node or nodes. If not specifying
path_map
it should return one or more nodes. If it returns END, the graph will stop execution. -
path_map
(
, default:Optional [dict [Hashable ,str ]]None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(
, default:Optional [str ]None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
–Self None
Without typehints on the path
function's return value (e.g., -> Literal["foo", "__end__"]:
)
or a path_map, the graph visualization assumes the edge could transition to any node in the graph.
Source code in libs/langgraph/langgraph/graph/graph.py
set_entry_point(key: str) -> Self
¶
Specifies the first node to be called in the graph.
Equivalent to calling add_edge(START, key)
.
Parameters:
-
key
(
) –str The key of the node to set as the entry point.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
set_conditional_entry_point(path: Union[Callable[..., Union[Hashable, list[Hashable]]], Callable[..., Awaitable[Union[Hashable, list[Hashable]]]], Runnable[Any, Union[Hashable, list[Hashable]]]], path_map: Optional[Union[dict[Hashable, str], list[str]]] = None, then: Optional[str] = None) -> Self
¶
Sets a conditional entry point in the graph.
Parameters:
-
path
(
) –Union [Callable ,Runnable ]The callable that determines the next node or nodes. If not specifying
path_map
it should return one or more nodes. If it returns END, the graph will stop execution. -
path_map
(
, default:Optional [dict [str ,str ]]None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(
, default:Optional [str ]None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
set_finish_point(key: str) -> Self
¶
Marks a node as a finish point of the graph.
If the graph reaches this node, it will cease execution.
Parameters:
-
key
(
) –str The key of the node to set as the finish point.
Returns:
-
–Self None
Source code in libs/langgraph/langgraph/graph/graph.py
add_node(node: Union[str, RunnableLike], action: Optional[RunnableLike] = None, *, metadata: Optional[dict[str, Any]] = None, input: Optional[Type[Any]] = None, retry: Optional[RetryPolicy] = None) -> Self
¶
Adds a new node to the state graph.
Will take the name of the function/runnable as the node name.
Parameters:
-
node
(Union[str, RunnableLike)]
) –The function or runnable this node will run.
-
action
(
, default:Optional [RunnableLike ]None
) –The action associated with the node. (default: None)
-
metadata
(
, default:Optional [dict [str ,Any ]]None
) –The metadata associated with the node. (default: None)
-
input
(
, default:Optional [Type [Any ]]None
) –The input schema for the node. (default: the graph's input schema)
-
retry
(
, default:Optional [RetryPolicy ]None
) –The policy for retrying the node. (default: None)
Raises: ValueError: If the key is already being used as a state key.
Examples:
>>> from langgraph.graph import START, StateGraph
...
>>> def my_node(state, config):
... return {"x": state["x"] + 1}
...
>>> builder = StateGraph(dict)
>>> builder.add_node(my_node) # node name will be 'my_node'
>>> builder.add_edge(START, "my_node")
>>> graph = builder.compile()
>>> graph.invoke({"x": 1})
{'x': 2}
>>> builder = StateGraph(dict)
>>> builder.add_node("my_fair_node", my_node)
>>> builder.add_edge(START, "my_fair_node")
>>> graph = builder.compile()
>>> graph.invoke({"x": 1})
{'x': 2}
Returns:
-
–Self StateGraph
Source code in libs/langgraph/langgraph/graph/state.py
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
|
add_edge(start_key: Union[str, list[str]], end_key: str) -> Self
¶
Adds a directed edge from the start node to the end node.
If the graph transitions to the start_key node, it will always transition to the end_key node next.
Parameters:
-
start_key
(
) –Union [str ,list [str ]]The key(s) of the start node(s) of the edge.
-
end_key
(
) –str The key of the end node of the edge.
Raises:
-
–ValueError If the start key is 'END' or if the start key or end key is not present in the graph.
Returns:
-
–Self StateGraph
Source code in libs/langgraph/langgraph/graph/state.py
add_sequence(nodes: Sequence[Union[RunnableLike, tuple[str, RunnableLike]]]) -> Self
¶
Add a sequence of nodes that will be executed in the provided order.
Parameters:
-
nodes
(
) –Sequence [Union [RunnableLike ,tuple [str ,RunnableLike ]]]A sequence of RunnableLike objects (e.g. a LangChain Runnable or a callable) or (name, RunnableLike) tuples. If no names are provided, the name will be inferred from the node object (e.g. a runnable or a callable name). Each node will be executed in the order provided.
Raises:
-
–ValueError if the sequence is empty.
-
–ValueError if the sequence contains duplicate node names.
Returns:
-
–Self StateGraph
Source code in libs/langgraph/langgraph/graph/state.py
compile(checkpointer: Checkpointer = None, *, store: Optional[BaseStore] = None, interrupt_before: Optional[Union[All, list[str]]] = None, interrupt_after: Optional[Union[All, list[str]]] = None, debug: bool = False) -> CompiledStateGraph
¶
Compiles the state graph into a CompiledGraph
object.
The compiled graph implements the Runnable
interface and can be invoked,
streamed, batched, and run asynchronously.
Parameters:
-
checkpointer
(
, default:Optional [Union [Checkpointer ,Literal [False]]]None
) –A checkpoint saver object or flag. If provided, this Checkpointer serves as a fully versioned "short-term memory" for the graph, allowing it to be paused, resumed, and replayed from any point. If None, it may inherit the parent graph's checkpointer when used as a subgraph. If False, it will not use or inherit any checkpointer.
-
interrupt_before
(
, default:Optional [Sequence [str ]]None
) –An optional list of node names to interrupt before.
-
interrupt_after
(
, default:Optional [Sequence [str ]]None
) –An optional list of node names to interrupt after.
-
debug
(
, default:bool False
) –A flag indicating whether to enable debug mode.
Returns:
-
CompiledStateGraph
(
) –CompiledStateGraph The compiled state graph.
Source code in libs/langgraph/langgraph/graph/state.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
|
CompiledStateGraph
¶
Bases:
Source code in libs/langgraph/langgraph/graph/state.py
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 |
|
stream_mode: StreamMode = stream_mode
class-attribute
instance-attribute
¶
Mode to stream output, defaults to 'values'.
stream_channels: Optional[Union[str, Sequence[str]]] = stream_channels
class-attribute
instance-attribute
¶
Channels to stream, defaults to all channels not in reserved channels
step_timeout: Optional[float] = step_timeout
class-attribute
instance-attribute
¶
Maximum time to wait for a step to complete, in seconds. Defaults to None.
debug: bool = debug if debug is not None else get_debug()
instance-attribute
¶
Whether to print debug information during execution. Defaults to False.
checkpointer: Checkpointer = checkpointer
class-attribute
instance-attribute
¶
Checkpointer used to save and load graph state. Defaults to None.
store: Optional[BaseStore] = store
class-attribute
instance-attribute
¶
Memory store to use for SharedValues. Defaults to None.
retry_policy: Optional[RetryPolicy] = retry_policy
class-attribute
instance-attribute
¶
Retry policy to use when running tasks. Set to None to disable.
get_graph(config: Optional[RunnableConfig] = None, *, xray: Union[int, bool] = False) -> DrawableGraph
¶
Returns a drawable representation of the computation graph.
Source code in libs/langgraph/langgraph/graph/graph.py
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 |
|
get_state(config: RunnableConfig, *, subgraphs: bool = False) -> StateSnapshot
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state(config: RunnableConfig, *, subgraphs: bool = False) -> StateSnapshot
async
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
get_state_history(config: RunnableConfig, *, filter: Optional[Dict[str, Any]] = None, before: Optional[RunnableConfig] = None, limit: Optional[int] = None) -> Iterator[StateSnapshot]
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state_history(config: RunnableConfig, *, filter: Optional[Dict[str, Any]] = None, before: Optional[RunnableConfig] = None, limit: Optional[int] = None) -> AsyncIterator[StateSnapshot]
async
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
update_state(config: RunnableConfig, values: Optional[Union[dict[str, Any], Any]], as_node: Optional[str] = None) -> RunnableConfig
¶
Update the state of the graph with the given values, as if they came from
node as_node
. If as_node
is not provided, it will be set to the last node
that updated the state, if not ambiguous.
Source code in libs/langgraph/langgraph/pregel/__init__.py
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 |
|
stream(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: Optional[Union[StreamMode, list[StreamMode]]] = None, output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, subgraphs: bool = False) -> Iterator[Union[dict[str, Any], Any]]
¶
Stream graph steps for a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input to the graph.
-
config
(
, default:Optional [RunnableConfig ]None
) –The configuration to use for the run.
-
stream_mode
(
, default:Optional [Union [StreamMode ,list [StreamMode ]]]None
) –The mode to stream output, defaults to self.stream_mode. Options are 'values', 'updates', and 'debug'. values: Emit the current values of the state for each step. updates: Emit only the updates to the state for each step. Output is a dict with the node name as key and the updated values as value. debug: Emit debug events for each step.
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(
, default:Optional [bool ]None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(
, default:bool False
) –Whether to stream subgraphs, defaults to False.
Yields:
-
–Union [dict [str ,Any ],Any ]The output of each step in the graph. The output shape depends on the stream_mode.
Examples:
Using different stream modes with a graph:
>>> import operator
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.graph import StateGraph
>>> from langgraph.constants import START
...
>>> class State(TypedDict):
... alist: Annotated[list, operator.add]
... another_list: Annotated[list, operator.add]
...
>>> builder = StateGraph(State)
>>> builder.add_node("a", lambda _state: {"another_list": ["hi"]})
>>> builder.add_node("b", lambda _state: {"alist": ["there"]})
>>> builder.add_edge("a", "b")
>>> builder.add_edge(START, "a")
>>> graph = builder.compile()
>>> for event in graph.stream({"alist": ['Ex for stream_mode="values"']}, stream_mode="values"):
... print(event)
{'alist': ['Ex for stream_mode="values"'], 'another_list': []}
{'alist': ['Ex for stream_mode="values"'], 'another_list': ['hi']}
{'alist': ['Ex for stream_mode="values"', 'there'], 'another_list': ['hi']}
>>> for event in graph.stream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
>>> for event in graph.stream({"alist": ['Ex for stream_mode="debug"']}, stream_mode="debug"):
... print(event)
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': []}, 'triggers': ['start:a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'result': [('another_list', ['hi'])]}}
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': ['hi']}, 'triggers': ['a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'result': [('alist', ['there'])]}}
Source code in libs/langgraph/langgraph/pregel/__init__.py
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 |
|
astream(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: Optional[Union[StreamMode, list[StreamMode]]] = None, output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, subgraphs: bool = False) -> AsyncIterator[Union[dict[str, Any], Any]]
async
¶
Stream graph steps for a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input to the graph.
-
config
(
, default:Optional [RunnableConfig ]None
) –The configuration to use for the run.
-
stream_mode
(
, default:Optional [Union [StreamMode ,list [StreamMode ]]]None
) –The mode to stream output, defaults to self.stream_mode. Options are 'values', 'updates', and 'debug'. values: Emit the current values of the state for each step. updates: Emit only the updates to the state for each step. Output is a dict with the node name as key and the updated values as value. debug: Emit debug events for each step.
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(
, default:Optional [bool ]None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(
, default:bool False
) –Whether to stream subgraphs, defaults to False.
Yields:
-
–AsyncIterator [Union [dict [str ,Any ],Any ]]The output of each step in the graph. The output shape depends on the stream_mode.
Examples:
Using different stream modes with a graph:
>>> import operator
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.graph import StateGraph
>>> from langgraph.constants import START
...
>>> class State(TypedDict):
... alist: Annotated[list, operator.add]
... another_list: Annotated[list, operator.add]
...
>>> builder = StateGraph(State)
>>> builder.add_node("a", lambda _state: {"another_list": ["hi"]})
>>> builder.add_node("b", lambda _state: {"alist": ["there"]})
>>> builder.add_edge("a", "b")
>>> builder.add_edge(START, "a")
>>> graph = builder.compile()
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="values"']}, stream_mode="values"):
... print(event)
{'alist': ['Ex for stream_mode="values"'], 'another_list': []}
{'alist': ['Ex for stream_mode="values"'], 'another_list': ['hi']}
{'alist': ['Ex for stream_mode="values"', 'there'], 'another_list': ['hi']}
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="debug"']}, stream_mode="debug"):
... print(event)
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': []}, 'triggers': ['start:a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 1, 'payload': {'id': '...', 'name': 'a', 'result': [('another_list', ['hi'])]}}
{'type': 'task', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'input': {'alist': ['Ex for stream_mode="debug"'], 'another_list': ['hi']}, 'triggers': ['a']}}
{'type': 'task_result', 'timestamp': '2024-06-23T...+00:00', 'step': 2, 'payload': {'id': '...', 'name': 'b', 'result': [('alist', ['there'])]}}
Source code in libs/langgraph/langgraph/pregel/__init__.py
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 |
|
invoke(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: StreamMode = 'values', output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, **kwargs: Any) -> Union[dict[str, Any], Any]
¶
Run the graph with a single input and config.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input data for the graph. It can be a dictionary or any other type.
-
config
(
, default:Optional [RunnableConfig ]None
) –Optional. The configuration for the graph run.
-
stream_mode
(
, default:StreamMode 'values'
) –Optional[str]. The stream mode for the graph run. Default is "values".
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –Optional. The output keys to retrieve from the graph run.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt the graph run before.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt the graph run after.
-
debug
(
, default:Optional [bool ]None
) –Optional. Enable debug mode for the graph run.
-
**kwargs
(
, default:Any {}
) –Additional keyword arguments to pass to the graph run.
Returns:
-
–Union [dict [str ,Any ],Any ]The output of the graph run. If stream_mode is "values", it returns the latest output.
-
–Union [dict [str ,Any ],Any ]If stream_mode is not "values", it returns a list of output chunks.
Source code in libs/langgraph/langgraph/pregel/__init__.py
ainvoke(input: Union[dict[str, Any], Any], config: Optional[RunnableConfig] = None, *, stream_mode: StreamMode = 'values', output_keys: Optional[Union[str, Sequence[str]]] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, debug: Optional[bool] = None, **kwargs: Any) -> Union[dict[str, Any], Any]
async
¶
Asynchronously invoke the graph on a single input.
Parameters:
-
input
(
) –Union [dict [str ,Any ],Any ]The input data for the computation. It can be a dictionary or any other type.
-
config
(
, default:Optional [RunnableConfig ]None
) –Optional. The configuration for the computation.
-
stream_mode
(
, default:StreamMode 'values'
) –Optional. The stream mode for the computation. Default is "values".
-
output_keys
(
, default:Optional [Union [str ,Sequence [str ]]]None
) –Optional. The output keys to include in the result. Default is None.
-
interrupt_before
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt before. Default is None.
-
interrupt_after
(
, default:Optional [Union [All ,Sequence [str ]]]None
) –Optional. The nodes to interrupt after. Default is None.
-
debug
(
, default:Optional [bool ]None
) –Optional. Whether to enable debug mode. Default is None.
-
**kwargs
(
, default:Any {}
) –Additional keyword arguments.
Returns:
-
–Union [dict [str ,Any ],Any ]The result of the computation. If stream_mode is "values", it returns the latest value.
-
–Union [dict [str ,Any ],Any ]If stream_mode is "chunks", it returns a list of chunks.
Source code in libs/langgraph/langgraph/pregel/__init__.py
add_messages(left: Messages, right: Messages) -> Messages
¶
Merges two lists of messages, updating existing messages by ID.
By default, this ensures the state is "append-only", unless the new message has the same ID as an existing message.
Parameters:
-
left
(
) –Messages The base list of messages.
-
right
(
) –Messages The list of messages (or single message) to merge into the base list.
Returns:
-
–Messages A new list of messages with the messages from
right
merged intoleft
. -
–Messages If a message in
right
has the same ID as a message inleft
, the -
–Messages message from
right
will replace the message fromleft
.
Examples:
>>> from langchain_core.messages import AIMessage, HumanMessage
>>> msgs1 = [HumanMessage(content="Hello", id="1")]
>>> msgs2 = [AIMessage(content="Hi there!", id="2")]
>>> add_messages(msgs1, msgs2)
[HumanMessage(content='Hello', id='1'), AIMessage(content='Hi there!', id='2')]
>>> msgs1 = [HumanMessage(content="Hello", id="1")]
>>> msgs2 = [HumanMessage(content="Hello again", id="1")]
>>> add_messages(msgs1, msgs2)
[HumanMessage(content='Hello again', id='1')]
>>> from typing import Annotated
>>> from typing_extensions import TypedDict
>>> from langgraph.graph import StateGraph
>>>
>>> class State(TypedDict):
... messages: Annotated[list, add_messages]
...
>>> builder = StateGraph(State)
>>> builder.add_node("chatbot", lambda state: {"messages": [("assistant", "Hello")]})
>>> builder.set_entry_point("chatbot")
>>> builder.set_finish_point("chatbot")
>>> graph = builder.compile()
>>> graph.invoke({})
{'messages': [AIMessage(content='Hello', id=...)]}