schema.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. """Data models for interacting with the LangGraph API."""
  2. from __future__ import annotations
  3. from collections.abc import Mapping, Sequence
  4. from dataclasses import Field
  5. from datetime import datetime
  6. from typing import (
  7. Any,
  8. ClassVar,
  9. Literal,
  10. NamedTuple,
  11. Protocol,
  12. TypeAlias,
  13. Union,
  14. )
  15. from typing_extensions import TypedDict
  16. Json = dict[str, Any] | None
  17. """Represents a JSON-like structure, which can be None or a dictionary with string keys and any values."""
  18. RunStatus = Literal["pending", "running", "error", "success", "timeout", "interrupted"]
  19. """
  20. Represents the status of a run:
  21. - "pending": The run is waiting to start.
  22. - "running": The run is currently executing.
  23. - "error": The run encountered an error and stopped.
  24. - "success": The run completed successfully.
  25. - "timeout": The run exceeded its time limit.
  26. - "interrupted": The run was manually stopped or interrupted.
  27. """
  28. ThreadStatus = Literal["idle", "busy", "interrupted", "error"]
  29. """
  30. Represents the status of a thread:
  31. - "idle": The thread is not currently processing any task.
  32. - "busy": The thread is actively processing a task.
  33. - "interrupted": The thread's execution was interrupted.
  34. - "error": An exception occurred during task processing.
  35. """
  36. ThreadStreamMode = Literal["run_modes", "lifecycle", "state_update"]
  37. """
  38. Defines the mode of streaming:
  39. - "run_modes": Stream the same events as the runs on thread, as well as run_done events.
  40. - "lifecycle": Stream only run start/end events.
  41. - "state_update": Stream state updates on the thread.
  42. """
  43. StreamMode = Literal[
  44. "values",
  45. "messages",
  46. "updates",
  47. "events",
  48. "tasks",
  49. "checkpoints",
  50. "debug",
  51. "custom",
  52. "messages-tuple",
  53. ]
  54. """
  55. Defines the mode of streaming:
  56. - "values": Stream only the values.
  57. - "messages": Stream complete messages.
  58. - "updates": Stream updates to the state.
  59. - "events": Stream events occurring during execution.
  60. - "checkpoints": Stream checkpoints as they are created.
  61. - "tasks": Stream task start and finish events.
  62. - "debug": Stream detailed debug information.
  63. - "custom": Stream custom events.
  64. """
  65. DisconnectMode = Literal["cancel", "continue"]
  66. """
  67. Specifies behavior on disconnection:
  68. - "cancel": Cancel the operation on disconnection.
  69. - "continue": Continue the operation even if disconnected.
  70. """
  71. MultitaskStrategy = Literal["reject", "interrupt", "rollback", "enqueue"]
  72. """
  73. Defines how to handle multiple tasks:
  74. - "reject": Reject new tasks when busy.
  75. - "interrupt": Interrupt current task for new ones.
  76. - "rollback": Roll back current task and start new one.
  77. - "enqueue": Queue new tasks for later execution.
  78. """
  79. OnConflictBehavior = Literal["raise", "do_nothing"]
  80. """
  81. Specifies behavior on conflict:
  82. - "raise": Raise an exception when a conflict occurs.
  83. - "do_nothing": Ignore conflicts and proceed.
  84. """
  85. OnCompletionBehavior = Literal["delete", "keep"]
  86. """
  87. Defines action after completion:
  88. - "delete": Delete resources after completion.
  89. - "keep": Retain resources after completion.
  90. """
  91. Durability = Literal["sync", "async", "exit"]
  92. """Durability mode for the graph execution.
  93. - `"sync"`: Changes are persisted synchronously before the next step starts.
  94. - `"async"`: Changes are persisted asynchronously while the next step executes.
  95. - `"exit"`: Changes are persisted only when the graph exits."""
  96. All = Literal["*"]
  97. """Represents a wildcard or 'all' selector."""
  98. IfNotExists = Literal["create", "reject"]
  99. """
  100. Specifies behavior if the thread doesn't exist:
  101. - "create": Create a new thread if it doesn't exist.
  102. - "reject": Reject the operation if the thread doesn't exist.
  103. """
  104. CancelAction = Literal["interrupt", "rollback"]
  105. """
  106. Action to take when cancelling the run.
  107. - "interrupt": Simply cancel the run.
  108. - "rollback": Cancel the run. Then delete the run and associated checkpoints.
  109. """
  110. AssistantSortBy = Literal[
  111. "assistant_id", "graph_id", "name", "created_at", "updated_at"
  112. ]
  113. """
  114. The field to sort by.
  115. """
  116. ThreadSortBy = Literal["thread_id", "status", "created_at", "updated_at"]
  117. """
  118. The field to sort by.
  119. """
  120. CronSortBy = Literal[
  121. "cron_id", "assistant_id", "thread_id", "created_at", "updated_at", "next_run_date"
  122. ]
  123. """
  124. The field to sort by.
  125. """
  126. SortOrder = Literal["asc", "desc"]
  127. """
  128. The order to sort by.
  129. """
  130. class Config(TypedDict, total=False):
  131. """Configuration options for a call."""
  132. tags: list[str]
  133. """
  134. Tags for this call and any sub-calls (eg. a Chain calling an LLM).
  135. You can use these to filter calls.
  136. """
  137. recursion_limit: int
  138. """
  139. Maximum number of times a call can recurse. If not provided, defaults to 25.
  140. """
  141. configurable: dict[str, Any]
  142. """
  143. Runtime values for attributes previously made configurable on this Runnable,
  144. or sub-Runnables, through .configurable_fields() or .configurable_alternatives().
  145. Check .output_schema() for a description of the attributes that have been made
  146. configurable.
  147. """
  148. class Checkpoint(TypedDict):
  149. """Represents a checkpoint in the execution process."""
  150. thread_id: str
  151. """Unique identifier for the thread associated with this checkpoint."""
  152. checkpoint_ns: str
  153. """Namespace for the checkpoint; used internally to manage subgraph state."""
  154. checkpoint_id: str | None
  155. """Optional unique identifier for the checkpoint itself."""
  156. checkpoint_map: dict[str, Any] | None
  157. """Optional dictionary containing checkpoint-specific data."""
  158. class GraphSchema(TypedDict):
  159. """Defines the structure and properties of a graph."""
  160. graph_id: str
  161. """The ID of the graph."""
  162. input_schema: dict | None
  163. """The schema for the graph input.
  164. Missing if unable to generate JSON schema from graph."""
  165. output_schema: dict | None
  166. """The schema for the graph output.
  167. Missing if unable to generate JSON schema from graph."""
  168. state_schema: dict | None
  169. """The schema for the graph state.
  170. Missing if unable to generate JSON schema from graph."""
  171. config_schema: dict | None
  172. """The schema for the graph config.
  173. Missing if unable to generate JSON schema from graph."""
  174. context_schema: dict | None
  175. """The schema for the graph context.
  176. Missing if unable to generate JSON schema from graph."""
  177. Subgraphs = dict[str, GraphSchema]
  178. class AssistantBase(TypedDict):
  179. """Base model for an assistant."""
  180. assistant_id: str
  181. """The ID of the assistant."""
  182. graph_id: str
  183. """The ID of the graph."""
  184. config: Config
  185. """The assistant config."""
  186. context: Context
  187. """The static context of the assistant."""
  188. created_at: datetime
  189. """The time the assistant was created."""
  190. metadata: Json
  191. """The assistant metadata."""
  192. version: int
  193. """The version of the assistant"""
  194. name: str
  195. """The name of the assistant"""
  196. description: str | None
  197. """The description of the assistant"""
  198. class AssistantVersion(AssistantBase):
  199. """Represents a specific version of an assistant."""
  200. pass
  201. class Assistant(AssistantBase):
  202. """Represents an assistant with additional properties."""
  203. updated_at: datetime
  204. """The last time the assistant was updated."""
  205. class AssistantsSearchResponse(TypedDict):
  206. """Paginated response for assistant search results."""
  207. assistants: list[Assistant]
  208. """The assistants returned for the current search page."""
  209. next: str | None
  210. """Pagination cursor from the ``X-Pagination-Next`` response header."""
  211. class Interrupt(TypedDict):
  212. """Represents an interruption in the execution flow."""
  213. value: Any
  214. """The value associated with the interrupt."""
  215. id: str
  216. """The ID of the interrupt. Can be used to resume the interrupt."""
  217. class Thread(TypedDict):
  218. """Represents a conversation thread."""
  219. thread_id: str
  220. """The ID of the thread."""
  221. created_at: datetime
  222. """The time the thread was created."""
  223. updated_at: datetime
  224. """The last time the thread was updated."""
  225. metadata: Json
  226. """The thread metadata."""
  227. status: ThreadStatus
  228. """The status of the thread, one of 'idle', 'busy', 'interrupted'."""
  229. values: Json
  230. """The current state of the thread."""
  231. interrupts: dict[str, list[Interrupt]]
  232. """Mapping of task ids to interrupts that were raised in that task."""
  233. class ThreadTask(TypedDict):
  234. """Represents a task within a thread."""
  235. id: str
  236. name: str
  237. error: str | None
  238. interrupts: list[Interrupt]
  239. checkpoint: Checkpoint | None
  240. state: ThreadState | None
  241. result: dict[str, Any] | None
  242. class ThreadState(TypedDict):
  243. """Represents the state of a thread."""
  244. values: list[dict] | dict[str, Any]
  245. """The state values."""
  246. next: Sequence[str]
  247. """The next nodes to execute. If empty, the thread is done until new input is
  248. received."""
  249. checkpoint: Checkpoint
  250. """The ID of the checkpoint."""
  251. metadata: Json
  252. """Metadata for this state"""
  253. created_at: str | None
  254. """Timestamp of state creation"""
  255. parent_checkpoint: Checkpoint | None
  256. """The ID of the parent checkpoint. If missing, this is the root checkpoint."""
  257. tasks: Sequence[ThreadTask]
  258. """Tasks to execute in this step. If already attempted, may contain an error."""
  259. interrupts: list[Interrupt]
  260. """Interrupts which were thrown in this thread."""
  261. class ThreadUpdateStateResponse(TypedDict):
  262. """Represents the response from updating a thread's state."""
  263. checkpoint: Checkpoint
  264. """Checkpoint of the latest state."""
  265. class Run(TypedDict):
  266. """Represents a single execution run."""
  267. run_id: str
  268. """The ID of the run."""
  269. thread_id: str
  270. """The ID of the thread."""
  271. assistant_id: str
  272. """The assistant that was used for this run."""
  273. created_at: datetime
  274. """The time the run was created."""
  275. updated_at: datetime
  276. """The last time the run was updated."""
  277. status: RunStatus
  278. """The status of the run. One of 'pending', 'running', "error", 'success', "timeout", "interrupted"."""
  279. metadata: Json
  280. """The run metadata."""
  281. multitask_strategy: MultitaskStrategy
  282. """Strategy to handle concurrent runs on the same thread."""
  283. class Cron(TypedDict):
  284. """Represents a scheduled task."""
  285. cron_id: str
  286. """The ID of the cron."""
  287. assistant_id: str
  288. """The ID of the assistant."""
  289. thread_id: str | None
  290. """The ID of the thread."""
  291. end_time: datetime | None
  292. """The end date to stop running the cron."""
  293. schedule: str
  294. """The schedule to run, cron format."""
  295. created_at: datetime
  296. """The time the cron was created."""
  297. updated_at: datetime
  298. """The last time the cron was updated."""
  299. payload: dict
  300. """The run payload to use for creating new run."""
  301. user_id: str | None
  302. """The user ID of the cron."""
  303. next_run_date: datetime | None
  304. """The next run date of the cron."""
  305. metadata: dict
  306. """The metadata of the cron."""
  307. # Select field aliases for client-side typing of `select` parameters.
  308. # These mirror the server's allowed field sets.
  309. AssistantSelectField = Literal[
  310. "assistant_id",
  311. "graph_id",
  312. "name",
  313. "description",
  314. "config",
  315. "context",
  316. "created_at",
  317. "updated_at",
  318. "metadata",
  319. "version",
  320. ]
  321. ThreadSelectField = Literal[
  322. "thread_id",
  323. "created_at",
  324. "updated_at",
  325. "metadata",
  326. "config",
  327. "context",
  328. "status",
  329. "values",
  330. "interrupts",
  331. ]
  332. RunSelectField = Literal[
  333. "run_id",
  334. "thread_id",
  335. "assistant_id",
  336. "created_at",
  337. "updated_at",
  338. "status",
  339. "metadata",
  340. "kwargs",
  341. "multitask_strategy",
  342. ]
  343. CronSelectField = Literal[
  344. "cron_id",
  345. "assistant_id",
  346. "thread_id",
  347. "end_time",
  348. "schedule",
  349. "created_at",
  350. "updated_at",
  351. "user_id",
  352. "payload",
  353. "next_run_date",
  354. "metadata",
  355. "now",
  356. "on_run_completed",
  357. ]
  358. PrimitiveData = str | int | float | bool | None
  359. QueryParamTypes = (
  360. Mapping[str, PrimitiveData | Sequence[PrimitiveData]]
  361. | list[tuple[str, PrimitiveData]]
  362. | tuple[tuple[str, PrimitiveData], ...]
  363. | str
  364. | bytes
  365. )
  366. class RunCreate(TypedDict):
  367. """Defines the parameters for initiating a background run."""
  368. thread_id: str | None
  369. """The identifier of the thread to run. If not provided, the run is stateless."""
  370. assistant_id: str
  371. """The identifier of the assistant to use for this run."""
  372. input: dict | None
  373. """Initial input data for the run."""
  374. metadata: dict | None
  375. """Additional metadata to associate with the run."""
  376. config: Config | None
  377. """Configuration options for the run."""
  378. context: Context | None
  379. """The static context of the run."""
  380. checkpoint_id: str | None
  381. """The identifier of a checkpoint to resume from."""
  382. interrupt_before: list[str] | None
  383. """List of node names to interrupt execution before."""
  384. interrupt_after: list[str] | None
  385. """List of node names to interrupt execution after."""
  386. webhook: str | None
  387. """URL to send webhook notifications about the run's progress."""
  388. multitask_strategy: MultitaskStrategy | None
  389. """Strategy for handling concurrent runs on the same thread."""
  390. class Item(TypedDict):
  391. """Represents a single document or data entry in the graph's Store.
  392. Items are used to store cross-thread memories.
  393. """
  394. namespace: list[str]
  395. """The namespace of the item. A namespace is analogous to a document's directory."""
  396. key: str
  397. """The unique identifier of the item within its namespace.
  398. In general, keys needn't be globally unique.
  399. """
  400. value: dict[str, Any]
  401. """The value stored in the item. This is the document itself."""
  402. created_at: datetime
  403. """The timestamp when the item was created."""
  404. updated_at: datetime
  405. """The timestamp when the item was last updated."""
  406. class ListNamespaceResponse(TypedDict):
  407. """Response structure for listing namespaces."""
  408. namespaces: list[list[str]]
  409. """A list of namespace paths, where each path is a list of strings."""
  410. class SearchItem(Item, total=False):
  411. """Item with an optional relevance score from search operations.
  412. Attributes:
  413. score (Optional[float]): Relevance/similarity score. Included when
  414. searching a compatible store with a natural language query.
  415. """
  416. score: float | None
  417. class SearchItemsResponse(TypedDict):
  418. """Response structure for searching items."""
  419. items: list[SearchItem]
  420. """A list of items matching the search criteria."""
  421. class StreamPart(NamedTuple):
  422. """Represents a part of a stream response."""
  423. event: str
  424. """The type of event for this stream part."""
  425. data: dict
  426. """The data payload associated with the event."""
  427. id: str | None = None
  428. """The ID of the event."""
  429. class Send(TypedDict):
  430. """Represents a message to be sent to a specific node in the graph.
  431. This type is used to explicitly send messages to nodes in the graph, typically
  432. used within Command objects to control graph execution flow.
  433. """
  434. node: str
  435. """The name of the target node to send the message to."""
  436. input: dict[str, Any] | None
  437. """Optional dictionary containing the input data to be passed to the node.
  438. If None, the node will be called with no input."""
  439. class Command(TypedDict, total=False):
  440. """Represents one or more commands to control graph execution flow and state.
  441. This type defines the control commands that can be returned by nodes to influence
  442. graph execution. It lets you navigate to other nodes, update graph state,
  443. and resume from interruptions.
  444. """
  445. goto: Send | str | Sequence[Send | str]
  446. """Specifies where execution should continue. Can be:
  447. - A string node name to navigate to
  448. - A Send object to execute a node with specific input
  449. - A sequence of node names or Send objects to execute in order
  450. """
  451. update: dict[str, Any] | Sequence[tuple[str, Any]]
  452. """Updates to apply to the graph's state. Can be:
  453. - A dictionary of state updates to merge
  454. - A sequence of (key, value) tuples for ordered updates
  455. """
  456. resume: Any
  457. """Value to resume execution with after an interruption.
  458. Used in conjunction with interrupt() to implement control flow.
  459. """
  460. class RunCreateMetadata(TypedDict):
  461. """Metadata for a run creation request."""
  462. run_id: str
  463. """The ID of the run."""
  464. thread_id: str | None
  465. """The ID of the thread."""
  466. class _TypedDictLikeV1(Protocol):
  467. """Protocol to represent types that behave like TypedDicts
  468. Version 1: using `ClassVar` for keys."""
  469. __required_keys__: ClassVar[frozenset[str]]
  470. __optional_keys__: ClassVar[frozenset[str]]
  471. class _TypedDictLikeV2(Protocol):
  472. """Protocol to represent types that behave like TypedDicts
  473. Version 2: not using `ClassVar` for keys."""
  474. __required_keys__: frozenset[str]
  475. __optional_keys__: frozenset[str]
  476. class _DataclassLike(Protocol):
  477. """Protocol to represent types that behave like dataclasses.
  478. Inspired by the private _DataclassT from dataclasses that uses a similar protocol as a bound.
  479. """
  480. __dataclass_fields__: ClassVar[dict[str, Field[Any]]]
  481. class _BaseModelLike(Protocol):
  482. """Protocol to represent types that behave like Pydantic `BaseModel`."""
  483. model_config: ClassVar[dict[str, Any]]
  484. __pydantic_core_schema__: ClassVar[Any]
  485. def model_dump(
  486. self,
  487. **kwargs: Any,
  488. ) -> dict[str, Any]: ...
  489. _JSONLike: TypeAlias = None | str | int | float | bool
  490. _JSONMap: TypeAlias = Mapping[
  491. str, Union[_JSONLike, list[_JSONLike], "_JSONMap", list["_JSONMap"]]
  492. ]
  493. Input: TypeAlias = (
  494. _TypedDictLikeV1 | _TypedDictLikeV2 | _DataclassLike | _BaseModelLike | _JSONMap
  495. )
  496. Context: TypeAlias = Input