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.
图形是 LangGraph 的核心抽象。每个 StateGraph 实现都用于创建图形工作流。编译后,您可以运行 CompiledGraph 来运行应用程序。
StateGraph¶
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
一个图形,其节点通过读取和写入共享状态进行通信。每个节点的签名是 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.
每个状态键都可以选择性地使用 reducer 函数进行注释,该函数将用于聚合从多个节点接收的该键的值。reducer 函数的签名是 (Value, Value) -> Value。
Parameters: 参数:
-
state_schema
(Type[Any]
, default:None
) –The schema class that defines the state.
state_schema
(类型[任意]
,默认值:没有
) –定义状态的架构类。
-
config_schema
(Optional[Type[Any]]
, default:None
) –The schema class that defines the configuration. Use this to expose configurable parameters in your API.
config_schema
(可选[类型[任意]]
,默认值:没有
) –定义配置的架构类。使用它来公开 API 中的可配置参数。
Examples: 例子:
>>> from langchain_core.runnables import RunnableConfig
>>> from typing_extensions import Annotated, TypedDict
>>> from langgraph.checkpoint 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
libs/langgraph/langgraph/graph/state.py
中的源代码
71 72 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 |
|
add_conditional_edges(source, path, path_map=None, then=None)
¶
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.
源
(str
) –起始节点。此条件边将在退出此节点时运行。
-
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
则应返回一个或多个节点。如果返回 END,则图形将停止执行。 -
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.path_map
(可选[dict[Hashable, str]]
,默认值:没有
) –可选的路径映射到节点名称。如果省略,
则 path
返回的路径应为节点名称。 -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.然后
(可选[str]
,默认值:没有
) –在
按路径
选择的节点之后要执行的节点的名称。
Returns: 返回:
-
None
–None
没有
–没有
Without typehints on the path
function's return value (e.g., -> Literal["foo", "__end__"]:
)
路径
函数的返回值上没有 typehints(例如,-> Literal[“foo”, “__end__”]:
)
or a path_map, the graph visualization assumes the edge could transition to any node in the graph.
或者path_map,图形可视化假定边缘可以过渡到图形中的任何节点。
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_entry_point(key)
¶
set_entry_point(键)
¶
Specifies the first node to be called in the graph.
指定要在关系图中调用的第一个节点。
Equivalent to calling add_edge(START, key)
.
等效于调用 add_edge(START, key)。
Parameters: 参数:
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_conditional_entry_point(path, path_map=None, then=None)
¶
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
则应返回一个或多个节点。如果返回 END,则图形将停止执行。 -
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.path_map
(可选[dict[str, str]]
,默认值:没有
) –可选的路径映射到节点名称。如果省略,
则 path
返回的路径应为节点名称。 -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.然后
(可选[str]
,默认值:没有
) –在
按路径
选择的节点之后要执行的节点的名称。
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_finish_point(key)
¶
set_finish_point(键)
¶
Marks a node as a finish point of the graph.
将节点标记为图形的完成点。
If the graph reaches this node, it will cease execution.
如果图形到达此节点,它将停止执行。
Parameters: 参数:
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
add_node(node, action=None, *, metadata=None, input=None, retry=None)
¶
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.
将采用函数的名称/runnable 作为节点名称。
Parameters: 参数:
-
node
(Union[str, RunnableLike)]
) –The function or runnable this node will run.
节点
(Union[str, RunnableLike)]
) –此节点将运行的函数或可运行设备。
-
action
(Optional[RunnableLike]
, default:None
) –The action associated with the node. (default: None)
行动
(可选[RunnableLike]
,默认值:没有
) –与节点关联的操作。(默认值:无)
-
metadata
(Optional[dict[str, Any]]
, default:None
) –The metadata associated with the node. (default: None)
元数据
(可选[dict[str, Any]]
,默认值:没有
) –与节点关联的元数据。(默认值:无)
-
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)
重试
(可选 [RetryPolicy]
,默认值:没有
) –重试节点的策略。(默认值:无)
Raises:
ValueError: If the key is already being used as a state key.
加薪:ValueError:如果键已被用作状态键。
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
libs/langgraph/langgraph/graph/state.py
中的源代码
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 |
|
add_edge(start_key, end_key)
¶
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.
如果图形过渡到start_key节点,则接下来将始终过渡到end_key节点。
Parameters: 参数:
-
start_key
(Union[str, list[str]]
) –The key(s) of the start node(s) of the edge.
start_key
(联合[str, list[str]]
) –Edge 的起始节点的键。
-
end_key
(str
) –The key of the end node of the edge.
end_key
(str
) –Edge 的终端节点的键。
Raises: 提高:
-
ValueError
–If the start key is 'END' or if the start key or end key is not present in the graph.
值错误
–如果开始键为“END”,或者图形中不存在开始键或结束键。
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/state.py
libs/langgraph/langgraph/graph/state.py
中的源代码
compile(checkpointer=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
compile(checkpointer=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
Compiles the state graph into a CompiledGraph
object.
将状态图编译为 CompiledGraph
对象。
The compiled graph implements the Runnable
interface and can be invoked,
streamed, batched, and run asynchronously.
编译后的图形实现了 Runnable
接口,可以异步调用、流式处理、批处理和运行。
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.
检查点
(可选 [BaseCheckpointSaver]
,默认值:没有
) –可选的检查点保护程序对象。这充当图形的完全版本控制的“内存”,允许图形暂停和恢复,并从任何点重放。
-
interrupt_before
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt before.
interrupt_before
(可选[Sequence[str]]
,默认值:没有
) –要在之前中断的节点名称的可选列表。
-
interrupt_after
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt after.
interrupt_after
(可选[Sequence[str]]
,默认值:没有
) –要中断的节点名称的可选列表。
-
debug
(bool
, default:False
) –A flag indicating whether to enable debug mode.
调试
(布尔值
,默认值:假
) –指示是否启用调试模式的标志。
Returns: 返回:
-
CompiledStateGraph
(CompiledStateGraph
) –The compiled state graph.
CompiledStateGraph
(CompiledStateGraph
) –编译的状态图。
Source code in libs/langgraph/langgraph/graph/state.py
libs/langgraph/langgraph/graph/state.py
中的源代码
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 |
|
handler: python 处理程序:Python
MessageGraph¶
MessageGraph(消息图)¶
Bases: StateGraph
基础:StateGraph
A StateGraph where every node receives a list of messages as input and returns one or more messages as output.
一个 StateGraph,其中每个节点都会接收一个消息列表作为输入,并返回一条或多条消息作为输出。
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.
MessageGraph 是 StateGraph 的一个子类,其整个状态是一个单独的、仅追加*的消息列表。MessageGraph 中的每个节点都采用消息列表作为输入,并返回零条或多条消息作为输出。add_messages
函数用于将每个节点的输出消息合并到图形状态中的现有消息列表中。
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
libs/langgraph/langgraph/graph/message.py
源代码
add_node(node, action=None, *, metadata=None, input=None, retry=None)
¶
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.
将采用函数的名称/runnable 作为节点名称。
Parameters: 参数:
-
node
(Union[str, RunnableLike)]
) –The function or runnable this node will run.
节点
(Union[str, RunnableLike)]
) –此节点将运行的函数或可运行设备。
-
action
(Optional[RunnableLike]
, default:None
) –The action associated with the node. (default: None)
行动
(可选[RunnableLike]
,默认值:没有
) –与节点关联的操作。(默认值:无)
-
metadata
(Optional[dict[str, Any]]
, default:None
) –The metadata associated with the node. (default: None)
元数据
(可选[dict[str, Any]]
,默认值:没有
) –与节点关联的元数据。(默认值:无)
-
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)
重试
(可选 [RetryPolicy]
,默认值:没有
) –重试节点的策略。(默认值:无)
Raises:
ValueError: If the key is already being used as a state key.
加薪:ValueError:如果键已被用作状态键。
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
libs/langgraph/langgraph/graph/state.py
源代码
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 |
|
add_edge(start_key, end_key)
¶
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.
如果图形过渡到start_key节点,则接下来将始终过渡到end_key节点。
Parameters: 参数:
-
start_key
(Union[str, list[str]]
) –The key(s) of the start node(s) of the edge.
start_key
(联合[str, list[str]]
) –Edge 的起始节点的键。
-
end_key
(str
) –The key of the end node of the edge.
end_key
(str
) –Edge 的终端节点的键。
Raises: 提高:
-
ValueError
–If the start key is 'END' or if the start key or end key is not present in the graph.
值错误
–如果开始键为“END”,或者图形中不存在开始键或结束键。
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/state.py
libs/langgraph/langgraph/graph/state.py
中的源代码
add_conditional_edges(source, path, path_map=None, then=None)
¶
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.
源
(str
) –起始节点。此条件边将在退出此节点时运行。
-
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
则应返回一个或多个节点。如果返回 END,则图形将停止执行。 -
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.path_map
(可选[dict[Hashable, str]]
,默认值:没有
) –可选的路径映射到节点名称。如果省略,
则 path
返回的路径应为节点名称。 -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.然后
(可选[str]
,默认值:没有
) –在
按路径
选择的节点之后要执行的节点的名称。
Returns: 返回:
-
None
–None
没有
–没有
Without typehints on the path
function's return value (e.g., -> Literal["foo", "__end__"]:
)
路径
函数的返回值上没有类型提示(例如,-> Literal[“foo”, “__end__”]:
)
or a path_map, the graph visualization assumes the edge could transition to any node in the graph.
或者path_map,图形可视化假定边缘可以过渡到图形中的任何节点。
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_entry_point(key)
¶
set_entry_point(键)
¶
Specifies the first node to be called in the graph.
指定要在关系图中调用的第一个节点。
Equivalent to calling add_edge(START, key)
.
等效于调用 add_edge(START, key)。
Parameters: 参数:
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_conditional_entry_point(path, path_map=None, then=None)
¶
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
则应返回一个或多个节点。如果返回 END,则图形将停止执行。 -
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.path_map
(可选[dict[str, str]]
,默认值:没有
) –可选的路径映射到节点名称。如果省略,
则 path
返回的路径应为节点名称。 -
then
(Optional[str]
, default:None
) –The name of a node to execute after the nodes selected by
path
.然后
(可选[str]
,默认值:没有
) –在
按路径
选择的节点之后要执行的节点的名称。
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
set_finish_point(key)
¶
set_finish_point(键)
¶
Marks a node as a finish point of the graph.
将节点标记为图形的完成点。
If the graph reaches this node, it will cease execution.
如果图形到达此节点,它将停止执行。
Parameters: 参数:
Returns: 返回:
-
None
–None
没有
–没有
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
compile(checkpointer=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
compile(checkpointer=None, interrupt_before=None, interrupt_after=None, debug=False)
¶
Compiles the state graph into a CompiledGraph
object.
将状态图编译为 CompiledGraph
对象。
The compiled graph implements the Runnable
interface and can be invoked,
streamed, batched, and run asynchronously.
编译后的图形实现了 Runnable
接口,可以异步调用、流式处理、批处理和运行。
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.
检查点
(可选 [BaseCheckpointSaver]
,默认值:没有
) –可选的检查点保护程序对象。这充当图形的完全版本控制的“内存”,允许图形暂停和恢复,并从任何点重放。
-
interrupt_before
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt before.
interrupt_before
(可选[Sequence[str]]
,默认值:没有
) –要在之前中断的节点名称的可选列表。
-
interrupt_after
(Optional[Sequence[str]]
, default:None
) –An optional list of node names to interrupt after.
interrupt_after
(可选[Sequence[str]]
,默认值:没有
) –要中断的节点名称的可选列表。
-
debug
(bool
, default:False
) –A flag indicating whether to enable debug mode.
调试
(布尔值
,默认值:假
) –指示是否启用调试模式的标志。
Returns: 返回:
-
CompiledStateGraph
(CompiledStateGraph
) –The compiled state graph.
CompiledStateGraph
(CompiledStateGraph
) –编译的状态图。
Source code in libs/langgraph/langgraph/graph/state.py
libs/langgraph/langgraph/graph/state.py
中的源代码
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 |
|
CompiledGraph¶
编译图¶
Bases: Pregel
基质:预凝胶
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
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 |
|
stream_mode: StreamMode = 'values'
class-attribute
instance-attribute
¶
stream_mode: StreamMode = 'values'
类-属性
instance-attribute
¶
Mode to stream output, defaults to 'values'.
流式传输输出的模式,默认为 'values'。
stream_channels: Optional[Union[str, Sequence[str]]] = None
class-attribute
instance-attribute
¶
stream_channels: Optional[Union[str, Sequence[str]]] = 无
类属性
instance-attribute
¶
Channels to stream, defaults to all channels not in reserved channels
要流式传输的频道,默认为不在预留频道中的所有频道
step_timeout: Optional[float] = None
class-attribute
instance-attribute
¶
step_timeout: Optional[float] = None
类-属性
instance-attribute
¶
Maximum time to wait for a step to complete, in seconds. Defaults to None.
等待步骤完成的最长时间(以秒为单位)。默认值为 None。
debug: bool = Field(default_factory=get_debug)
class-attribute
instance-attribute
¶
debug: bool = Field(default_factory=get_debug)
类-属性
instance-attribute
¶
Whether to print debug information during execution. Defaults to False.
是否在执行过程中打印调试信息。默认值为 False。
checkpointer: Optional[BaseCheckpointSaver] = None
class-attribute
instance-attribute
¶
checkpointer: Optional[BaseCheckpointSaver] = 无
类属性
instance-attribute
¶
Checkpointer used to save and load graph state. Defaults to None.
Checkpointer 用于保存和加载图形状态。默认值为 None。
retry_policy: Optional[RetryPolicy] = None
class-attribute
instance-attribute
¶
retry_policy: Optional[RetryPolicy] = None
类-属性
instance-attribute
¶
Retry policy to use when running tasks. Set to None to disable.
重试运行任务时使用的策略。设置为“无”可禁用。
is_lc_serializable()
classmethod
¶
is_lc_serializable()
类方法
¶
Return whether the graph can be serialized by Langchain.
返回图形是否可以被Langchain序列化。
get_state(config)
¶
get_state(配置)
¶
Get the current state of the graph.
获取图形的当前状态。
Source code in libs/langgraph/langgraph/pregel/__init__.py
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
aget_state(config)
async
¶
aget_state(config)
异步
¶
Get the current state of the graph.
获取图形的当前状态。
Source code in libs/langgraph/langgraph/pregel/__init__.py
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
get_state_history(config, *, filter=None, before=None, limit=None)
¶
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
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
aget_state_history(config, *, filter=None, before=None, limit=None)
async
¶
aget_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
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
update_state(config, values, as_node=None)
¶
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.
使用给定的值更新图形的状态,就好像它们来自节点 as_node
一样。如果未提供 as_node
,则将设置为更新状态的最后一个节点(如果不是不明确)。
Source code in libs/langgraph/langgraph/pregel/__init__.py
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
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 |
|
stream(input, config=None, *, stream_mode=None, output_keys=None, interrupt_before=None, interrupt_after=None, debug=None)
¶
stream(input, config=None, *, stream_mode=None, output_keys=None, interrupt_before=None, interrupt_after=None, debug=None)
¶
Stream graph steps for a single input.
单个输入的流图步长。
Parameters: 参数:
-
input
(Union[dict[str, Any], Any]
) –The input to the graph.
输入
(联合[dict[str, any], any]
) –图形的输入。
-
config
(Optional[RunnableConfig]
, default:None
) –The configuration to use for the run.
配置
(可选 [RunnableConfig]
,默认值:没有
) –要用于运行的配置。
-
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.
stream_mode
(可选 [Union[StreamMode, list[StreamMode]]]
,默认值:没有
) –流式传输输出的模式,默认为 self.stream_mode。选项包括“values”、“updates”和“debug”。values:发出每个步骤的状态当前值。updates:仅发出对每个步骤的状态的更新。输出是一个字典,节点名称作为键,更新的值作为值。debug:为每个步骤发出调试事件。
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –The keys to stream, defaults to all non-context channels.
output_keys
(可选[Union[str, Sequence[str]]]
,默认值:没有
) –要流式传输的键,默认为所有非上下文通道。
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt before, defaults to all nodes in the graph.
interrupt_before
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –之前要中断的节点,默认为图中的所有节点。
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt after, defaults to all nodes in the graph.
interrupt_after
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –要中断的节点,默认为图中的所有节点。
-
debug
(Optional[bool]
, default:None
) –Whether to print debug information during execution, defaults to False.
调试
(可选[bool]
,默认值:没有
) –执行过程中是否打印调试信息,默认为 False。
Yields: 收益 率:
-
Union[dict[str, Any], Any]
–The output of each step in the graph. The output shape depends on the stream_mode.
联合[dict[str, any], any]
–图中每个步骤的输出。输出形状取决于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()
使用 stream_mode=“values”:
>>> 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']}
使用 stream_mode=“updates”:
>>> for event in graph.stream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
使用 stream_mode=“debug”:
>>> 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
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
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 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 |
|
astream(input, config=None, *, stream_mode=None, output_keys=None, interrupt_before=None, interrupt_after=None, debug=None)
async
¶
astream(input, config=无, *, stream_mode=无, output_keys=无, interrupt_before=无, interrupt_after=None, debug=None)
异步
¶
Stream graph steps for a single input.
单个输入的流图步长。
Parameters: 参数:
-
input
(Union[dict[str, Any], Any]
) –The input to the graph.
输入
(联合[dict[str, any], any]
) –图形的输入。
-
config
(Optional[RunnableConfig]
, default:None
) –The configuration to use for the run.
配置
(可选 [RunnableConfig]
,默认值:没有
) –要用于运行的配置。
-
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.
stream_mode
(可选 [Union[StreamMode, list[StreamMode]]]
,默认值:没有
) –流式传输输出的模式,默认为 self.stream_mode。选项包括“values”、“updates”和“debug”。values:发出每个步骤的状态当前值。updates:仅发出对每个步骤的状态的更新。输出是一个字典,节点名称作为键,更新的值作为值。debug:为每个步骤发出调试事件。
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –The keys to stream, defaults to all non-context channels.
output_keys
(可选[Union[str, Sequence[str]]]
,默认值:没有
) –要流式传输的键,默认为所有非上下文通道。
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt before, defaults to all nodes in the graph.
interrupt_before
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –之前要中断的节点,默认为图中的所有节点。
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Nodes to interrupt after, defaults to all nodes in the graph.
interrupt_after
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –要中断的节点,默认为图中的所有节点。
-
debug
(Optional[bool]
, default:None
) –Whether to print debug information during execution, defaults to False.
调试
(可选[bool]
,默认值:没有
) –执行过程中是否打印调试信息,默认为 False。
Yields: 收益 率:
-
AsyncIterator[Union[dict[str, Any], Any]]
–The output of each step in the graph. The output shape depends on the stream_mode.
AsyncIterator[Union[dict[str, any], any]]
–图中每个步骤的输出。输出形状取决于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()
使用 stream_mode=“values”:
>>> 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']}
使用 stream_mode=“updates”:
>>> async for event in graph.astream({"alist": ['Ex for stream_mode="updates"']}, stream_mode="updates"):
... print(event)
{'a': {'another_list': ['hi']}}
{'b': {'alist': ['there']}}
使用 stream_mode=“debug”:
>>> 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
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
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 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 |
|
invoke(input, config=None, *, stream_mode='values', output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, **kwargs)
¶
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.
输入
(联合[dict[str, any], any]
) –图形的输入数据。它可以是字典或任何其他类型。
-
config
(Optional[RunnableConfig]
, default:None
) –Optional. The configuration for the graph run.
配置
(可选 [RunnableConfig]
,默认值:没有
) –自选。图形运行的配置。
-
stream_mode
(StreamMode
, default:'values'
) –Optional[str]. The stream mode for the graph run. Default is "values".
stream_mode
(StreamMode
,默认值:“值”
) –可选[str]。图形运行的流模式。默认值为“values”。
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional. The output keys to retrieve from the graph run.
output_keys
(可选[Union[str, Sequence[str]]]
,默认值:没有
) –自选。要从图形中检索的输出键将运行。
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt the graph run before.
interrupt_before
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –自选。中断图形的节点在运行之前。
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt the graph run after.
interrupt_after
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –自选。中断图形的节点在之后运行。
-
debug
(Optional[bool]
, default:None
) –Optional. Enable debug mode for the graph run.
调试
(可选[bool]
,默认值:没有
) –自选。为图形运行启用调试模式。
-
**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.
联合[dict[str, any], any]
–图形运行的输出。如果 stream_mode 是“values”,则返回最新的输出。
-
Union[dict[str, Any], Any]
–If stream_mode is not "values", it returns a list of output chunks.
联合[dict[str, any], any]
–如果 stream_mode 不是 “values”,则返回输出块的列表。
Source code in libs/langgraph/langgraph/pregel/__init__.py
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
¶
ainvoke(input, config=None, *, stream_mode='values', output_keys=None, interrupt_before=None, interrupt_after=None, debug=None, **kwargs)
异步
¶
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.
输入
(联合[dict[str, any], any]
) –用于计算的输入数据。它可以是字典或任何其他类型。
-
config
(Optional[RunnableConfig]
, default:None
) –Optional. The configuration for the computation.
配置
(可选 [RunnableConfig]
,默认值:没有
) –自选。计算的配置。
-
stream_mode
(StreamMode
, default:'values'
) –Optional. The stream mode for the computation. Default is "values".
stream_mode
(StreamMode
,默认值:“值”
) –自选。计算的流模式。默认值为“values”。
-
output_keys
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional. The output keys to include in the result. Default is None.
output_keys
(可选[Union[str, Sequence[str]]]
,默认值:没有
) –自选。要包含在结果中的输出键。默认值为 None。
-
interrupt_before
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt before. Default is None.
interrupt_before
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –自选。之前要中断的节点。默认值为 None。
-
interrupt_after
(Optional[Union[All, Sequence[str]]]
, default:None
) –Optional. The nodes to interrupt after. Default is None.
interrupt_after
(可选[Union[All, Sequence[str]]]
,默认值:没有
) –自选。之后要中断的节点。默认值为 None。
-
debug
(Optional[bool]
, default:None
) –Optional. Whether to enable debug mode. Default is None.
调试
(可选[bool]
,默认值:没有
) –自选。是否启用调试模式。默认值为 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.
联合[dict[str, any], any]
–计算的结果。如果 stream_mode 是 “values”,则返回最新的值。
-
Union[dict[str, Any], Any]
–If stream_mode is "chunks", it returns a list of chunks.
联合[dict[str, any], any]
–如果 stream_mode 是 “chunks”,则返回块列表。
Source code in libs/langgraph/langgraph/pregel/__init__.py
libs/langgraph/langgraph/pregel/__init__.py
中的源代码
get_graph(config=None, *, xray=False)
¶
get_graph(config=None, *, xray=False)
¶
Returns a drawable representation of the computation graph.
返回计算图的可绘制表示形式。
Source code in libs/langgraph/langgraph/graph/graph.py
libs/langgraph/langgraph/graph/graph.py
中的源代码
StreamMode¶
How the stream method should emit outputs.
流方法应如何发出输出。
- 'values': Emit all values of the state for each step.
“values”:为每个步骤发出状态的所有值。 - 'updates': Emit only the node name(s) and updates
that were returned by the node(s) after each step.
“updates”:仅发出节点名称和每个步骤后节点返回的更新。 - 'debug': Emit debug events for each step.
“debug”:为每个步骤发出调试事件。
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.
START 是一个字符串常量 (“__start__”
),用作图形中的“虚拟”节点。将 START
中的边(或条件边)添加到图形中的一个或多个节点,将指示图形在那里开始执行。
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.
END 是一个字符串常量 (“__end__”
),用作图形中的“虚拟”节点。将图中一个或多个节点的边(或条件边)添加到 END
“节点”将指示图在到达此点后立即停止执行。
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
route states to different nodes based on certain conditions. This enables
creating "map-reduce" like workflows, where a node can be invoked multiple times
in parallel on different states, and the results can be aggregated back into the
main graph's state.Send
类在 StateGraph
的条件边缘中使用,以根据特定条件动态地将状态路由到不同的节点。这样就可以创建类似“map-reduce”的工作流,其中可以在不同状态下并行多次调用节点,并且结果可以聚合回主图的状态。
Attributes: 属性:
-
node
(str
) –The name of the target node to send the message to.
节点
(str
) –要向其发送消息的目标节点的名称。
-
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()
>>> graph.invoke({"subjects": ["cats", "dogs"]})
{'subjects': ['cats', 'dogs'], 'jokes': ['Joke about cats', 'Joke about dogs']}
Source code in libs/langgraph/langgraph/constants.py
libs/langgraph/langgraph/constants.py
中的源代码
__init__(node, arg)
¶
__init__(node, arg)
¶
Initialize a new instance of the Send class.
初始化 Send 类的新实例。
Parameters: 参数:
-
node
(str
) –The name of the target node to send the message to.
节点
(str
) –要向其发送消息的目标节点的名称。
-
arg
(Any
) –The state or message to send to the target node.
精 氨 酸
(任何)
–要发送到目标节点的状态或消息。
Source code in libs/langgraph/langgraph/constants.py
libs/langgraph/langgraph/constants.py
中的源代码
RetryPolicy¶
重试策略¶
Bases: NamedTuple
基数:NamedTuple
Configuration for retrying nodes.
用于重试节点的配置。
Source code in libs/langgraph/langgraph/pregel/types.py
libs/langgraph/langgraph/pregel/types.py
中的源代码
initial_interval: float = 0.5
class-attribute
instance-attribute
¶
initial_interval: float = 0.5
类属性
instance-attribute
¶
Amount of time that must elapse before the first retry occurs. In seconds.
在第一次重试发生之前必须经过的时间量。在几秒钟内。
backoff_factor: float = 2.0
class-attribute
instance-attribute
¶
backoff_factor: float = 2.0
类属性
instance-attribute
¶
Multiplier by which the interval increases after each retry.
每次重试后间隔增加的乘数。
max_interval: float = 128.0
class-attribute
instance-attribute
¶
max_interval: float = 128.0
类-属性
instance-attribute
¶
Maximum amount of time that may elapse between retries. In seconds.
两次重试之间可能经过的最长时间。在几秒钟内。
max_attempts: int = 3
class-attribute
instance-attribute
¶
max_attempts: int = 3
类-属性
instance-attribute
¶
Maximum number of attempts to make before giving up, including the first.
放弃前的最大尝试次数,包括第一次。
jitter: bool = True
class-attribute
instance-attribute
¶
抖动: bool = 真正的
类-属性
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
¶
retry_on: Union[Type[Exception], tuple[Type[Exception], ...], callable[[Exception], bool]] = default_retry_on
类属性
instance-attribute
¶
List of exception classes that should trigger a retry, or a callable that returns True for exceptions that should trigger a retry.
应触发重试的异常类的列表,或对于应触发重试的异常返回 True 的可调用对象。