Graph Definitions¶
Graphs are the core abstraction of LangGraph. Each StateGraph implementation is used to create graph workflows. Once compiled, you can run the CompiledGraph to run the application.
StateGraph¶
from langgraph.graph import StateGraph
from typing_extensions import TypedDict
class MyState(TypedDict)
...
graph = StateGraph(MyState)
Bases: Graph
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
(Type[Any]
, default:None
) –The schema class that defines the state.
-
config_schema
(Optional[Type[Any]]
, default: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) -> int:
... 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
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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 |
|
add_conditional_edges(source, path, path_map=None, then=None)
¶
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
(Optional[dict[Hashable, str]]
, default:None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
None
–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)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
set_conditional_entry_point(path, path_map=None, then=None)
¶
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
(Optional[dict[str, str]]
, default:None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
set_finish_point(key)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
add_node(node, action=None, *, metadata=None, input=None, retry=None)
¶
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
(Optional[RunnableLike]
, default:None
) –The action associated with the node. (default: None)
-
metadata
(Optional[dict[str, Any]]
, default:None
) –The metadata associated with the node. (default: None)
-
input
(Optional[Type[Any]]
, default:None
) –The input schema for the node. (default: the graph's input schema)
-
retry
(Optional[RetryPolicy]
, default: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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/state.py
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 |
|
add_edge(start_key, end_key)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/state.py
compile(checkpointer=None, *, store=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
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
(Optional[BaseCheckpointSaver]
, default:None
) –An optional checkpoint saver object. This serves as a fully versioned "memory" for the graph, allowing the graph to be paused and resumed, and replayed from any point.
-
interrupt_before
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt before.
-
interrupt_after
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt after.
-
debug
(bool
, default: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
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 |
|
handler: python
MessageGraph¶
Bases: StateGraph
A StateGraph where every node receives a list of messages as input and returns one or more messages as output.
MessageGraph is a subclass of StateGraph whose entire state is a single, append-only* list of messages.
Each node in a MessageGraph takes a list of messages as input and returns zero or more
messages as output. The add_messages
function is used to merge the output messages from each node
into the existing list of messages in the graph's state.
Examples:
>>> from langgraph.graph.message import MessageGraph
...
>>> builder = MessageGraph()
>>> builder.add_node("chatbot", lambda state: [("assistant", "Hello!")])
>>> builder.set_entry_point("chatbot")
>>> builder.set_finish_point("chatbot")
>>> builder.compile().invoke([("user", "Hi there.")])
[HumanMessage(content="Hi there.", id='...'), AIMessage(content="Hello!", id='...')]
>>> from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
>>> from langgraph.graph.message import MessageGraph
...
>>> builder = MessageGraph()
>>> builder.add_node(
... "chatbot",
... lambda state: [
... AIMessage(
... content="Hello!",
... tool_calls=[{"name": "search", "id": "123", "args": {"query": "X"}}],
... )
... ],
... )
>>> builder.add_node(
... "search", lambda state: [ToolMessage(content="Searching...", tool_call_id="123")]
... )
>>> builder.set_entry_point("chatbot")
>>> builder.add_edge("chatbot", "search")
>>> builder.set_finish_point("search")
>>> builder.compile().invoke([HumanMessage(content="Hi there. Can you search for X?")])
{'messages': [HumanMessage(content="Hi there. Can you search for X?", id='b8b7d8f4-7f4d-4f4d-9c1d-f8b8d8f4d9c1'),
AIMessage(content="Hello!", id='f4d9c1d8-8d8f-4d9c-b8b7-d8f4f4d9c1d8'),
ToolMessage(content="Searching...", id='d8f4f4d9-c1d8-4f4d-b8b7-d8f4f4d9c1d8', tool_call_id="123")]}
Source code in libs/langgraph/langgraph/graph/message.py
add_node(node, action=None, *, metadata=None, input=None, retry=None)
¶
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
(Optional[RunnableLike]
, default:None
) –The action associated with the node. (default: None)
-
metadata
(Optional[dict[str, Any]]
, default:None
) –The metadata associated with the node. (default: None)
-
input
(Optional[Type[Any]]
, default:None
) –The input schema for the node. (default: the graph's input schema)
-
retry
(Optional[RetryPolicy]
, default: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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/state.py
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 |
|
add_edge(start_key, end_key)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/state.py
add_conditional_edges(source, path, path_map=None, then=None)
¶
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
(Optional[dict[Hashable, str]]
, default:None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
None
–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)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
set_conditional_entry_point(path, path_map=None, then=None)
¶
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
(Optional[dict[str, str]]
, default:None
) –Optional mapping of paths to node names. If omitted the paths returned by
path
should be node names. -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.
Returns:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
set_finish_point(key)
¶
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:
-
None
–None
Source code in libs/langgraph/langgraph/graph/graph.py
compile(checkpointer=None, *, store=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
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
(Optional[BaseCheckpointSaver]
, default:None
) –An optional checkpoint saver object. This serves as a fully versioned "memory" for the graph, allowing the graph to be paused and resumed, and replayed from any point.
-
interrupt_before
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt before.
-
interrupt_after
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt after.
-
debug
(bool
, default: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
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 |
|
CompiledGraph¶
Bases: Pregel
Source code in libs/langgraph/langgraph/graph/graph.py
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 |
|
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: Optional[BaseCheckpointSaver] = 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, *, subgraphs=False)
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state(config, *, subgraphs=False)
async
¶
Get the current state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
get_state_history(config, *, filter=None, before=None, limit=None)
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
aget_state_history(config, *, filter=None, before=None, limit=None)
async
¶
Get the history of the state of the graph.
Source code in libs/langgraph/langgraph/pregel/__init__.py
update_state(config, values, as_node=None)
¶
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
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 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 |
|
stream(input, config=None, *, stream_mode=None, output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, subgraphs=False)
¶
Stream graph steps for a single input.
Parameters:
-
input
(Union[dict[str, Any], Any]
) –The input to the graph.
-
config
(Optional[RunnableConfig]
, default:None
) –The configuration to use for the run.
-
stream_mode
(Optional[Union[StreamMode, list[StreamMode]]]
, default: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
(Optional[Union[str, Sequence[str]]]
, default:None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(Optional[bool]
, default:None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(bool
, default: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
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 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 |
|
astream(input, config=None, *, stream_mode=None, output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, subgraphs=False)
async
¶
Stream graph steps for a single input.
Parameters:
-
input
(Union[dict[str, Any], Any]
) –The input to the graph.
-
config
(Optional[RunnableConfig]
, default:None
) –The configuration to use for the run.
-
stream_mode
(Optional[Union[StreamMode, list[StreamMode]]]
, default: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
(Optional[Union[str, Sequence[str]]]
, default:None
) –The keys to stream, defaults to all non-context channels.
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt before, defaults to all nodes in the graph.
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt after, defaults to all nodes in the graph.
-
debug
(Optional[bool]
, default:None
) –Whether to print debug information during execution, defaults to False.
-
subgraphs
(bool
, default: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
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 |
|
invoke(input, config=None, *, stream_mode='values', output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, **kwargs)
¶
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
(Optional[RunnableConfig]
, default:None
) –Optional. The configuration for the graph run.
-
stream_mode
(StreamMode
, default:'values'
) –Optional[str]. The stream mode for the graph run. Default is "values".
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional. The output keys to retrieve from the graph run.
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt the graph run before.
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt the graph run after.
-
debug
(Optional[bool]
, default:None
) –Optional. Enable debug mode for the graph run.
-
**kwargs
(Any
, default:{}
) –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, config=None, *, stream_mode='values', output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, **kwargs)
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
(Optional[RunnableConfig]
, default:None
) –Optional. The configuration for the computation.
-
stream_mode
(StreamMode
, default:'values'
) –Optional. The stream mode for the computation. Default is "values".
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional. The output keys to include in the result. Default is None.
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt before. Default is None.
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt after. Default is None.
-
debug
(Optional[bool]
, default:None
) –Optional. Whether to enable debug mode. Default is None.
-
**kwargs
(Any
, default:{}
) –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=None, *, xray=False)
¶
Returns a drawable representation of the computation graph.
Source code in libs/langgraph/langgraph/graph/graph.py
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 |
|
StreamMode¶
How the stream method should emit outputs.
- 'values': Emit all values of the state for each step.
- 'updates': Emit only the node name(s) and updates that were returned by the node(s) after each step.
- 'debug': Emit debug events for each step.
Constants¶
The following constants and classes are used to help control graph execution.
START¶
START is a string constant ("__start__"
) that serves as a "virtual" node in the graph.
Adding an edge (or conditional edges) from START
to node one or more nodes in your graph
will direct the graph to begin execution there.
from langgraph.graph import START
...
builder.add_edge(START, "my_node")
# Or to add a conditional starting point
builder.add_conditional_edges(START, my_condition)
END¶
END is a string constant ("__end__"
) that serves as a "virtual" node in the graph. Adding
an edge (or conditional edges) from one or more nodes in your graph to the END
"node" will
direct the graph to cease execution as soon as it reaches this point.
from langgraph.graph import END
...
builder.add_edge("my_node", END) # Stop any time my_node completes
# Or to conditionally terminate
def my_condition(state):
if state["should_stop"]:
return END
return "my_node"
builder.add_conditional_edges("my_node", my_condition)
Send¶
A message or packet to send to a specific node in the graph.
The Send
class is used within a StateGraph
's conditional edges to
dynamically invoke a node with a custom state at the next step.
Importantly, the sent state can differ from the core graph's state, allowing for flexible and dynamic workflow management.
One such example is a "map-reduce" workflow where your graph invokes the same node multiple times in parallel with different states, before aggregating the results back into the main graph's state.
Attributes:
-
node
(str
) –The name of the target node to send the message to.
-
arg
(Any
) –The state or message to send to the target node.
Examples:
>>> from typing import Annotated
>>> import operator
>>> class OverallState(TypedDict):
... subjects: list[str]
... jokes: Annotated[list[str], operator.add]
...
>>> from langgraph.constants import Send
>>> from langgraph.graph import END, START
>>> def continue_to_jokes(state: OverallState):
... return [Send("generate_joke", {"subject": s}) for s in state['subjects']]
...
>>> from langgraph.graph import StateGraph
>>> builder = StateGraph(OverallState)
>>> builder.add_node("generate_joke", lambda state: {"jokes": [f"Joke about {state['subject']}"]})
>>> builder.add_conditional_edges(START, continue_to_jokes)
>>> builder.add_edge("generate_joke", END)
>>> graph = builder.compile()
>>>
>>> # Invoking with two subjects results in a generated joke for each
>>> graph.invoke({"subjects": ["cats", "dogs"]})
{'subjects': ['cats', 'dogs'], 'jokes': ['Joke about cats', 'Joke about dogs']}
Source code in libs/langgraph/langgraph/constants.py
RetryPolicy¶
Bases: NamedTuple
Configuration for retrying nodes.
Source code in libs/langgraph/langgraph/pregel/types.py
initial_interval: float = 0.5
class-attribute
instance-attribute
¶
Amount of time that must elapse before the first retry occurs. In seconds.
backoff_factor: float = 2.0
class-attribute
instance-attribute
¶
Multiplier by which the interval increases after each retry.
max_interval: float = 128.0
class-attribute
instance-attribute
¶
Maximum amount of time that may elapse between retries. In seconds.
max_attempts: int = 3
class-attribute
instance-attribute
¶
Maximum number of attempts to make before giving up, including the first.
jitter: bool = True
class-attribute
instance-attribute
¶
Whether to add random jitter to the interval between retries.
retry_on: Union[Type[Exception], tuple[Type[Exception], ...], Callable[[Exception], bool]] = default_retry_on
class-attribute
instance-attribute
¶
List of exception classes that should trigger a retry, or a callable that returns True for exceptions that should trigger a retry.