langgraph-api 0.19.0.dev4__py3-none-any.whl → 0.19.0.dev5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/api/a2a.py +90 -40
  3. langgraph_api/api/meta.py +9 -2
  4. langgraph_api/api/runs.py +197 -7
  5. langgraph_api/api/threads.py +28 -16
  6. langgraph_api/asgi_transport.py +5 -3
  7. langgraph_api/command.py +16 -1
  8. langgraph_api/config/__init__.py +1 -1
  9. langgraph_api/encryption/context.py +11 -4
  10. langgraph_api/errors.py +10 -0
  11. langgraph_api/event_streaming/capabilities.py +1 -1
  12. langgraph_api/event_streaming/service.py +3 -16
  13. langgraph_api/event_streaming/session.py +15 -1
  14. langgraph_api/feature_flags.py +5 -0
  15. langgraph_api/grpc/ops/__init__.py +3 -0
  16. langgraph_api/grpc/ops/runs.py +24 -3
  17. langgraph_api/grpc/ops/threads.py +21 -17
  18. langgraph_api/js/client.mts +28 -8
  19. langgraph_api/js/src/lifecycle.mts +153 -0
  20. langgraph_api/lifecycle.py +276 -0
  21. langgraph_api/metrics_collector.py +3 -1
  22. langgraph_api/middleware/private_network.py +17 -15
  23. langgraph_api/models/run.py +0 -16
  24. langgraph_api/self_hosted_metrics.py +5 -2
  25. langgraph_api/serde.py +3 -1
  26. langgraph_api/server.py +14 -0
  27. langgraph_api/sse.py +45 -16
  28. langgraph_api/state.py +82 -5
  29. langgraph_api/stream.py +154 -41
  30. langgraph_api/worker.py +31 -2
  31. langgraph_api/worker_runtime.py +7 -0
  32. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev5.dist-info}/METADATA +1 -1
  33. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev5.dist-info}/RECORD +42 -40
  34. langgraph_grpc_common/checkpointer.py +7 -5
  35. langgraph_grpc_common/proto/checkpointer_pb2.py +18 -18
  36. langgraph_grpc_common/proto/checkpointer_pb2.pyi +9 -1
  37. langgraph_grpc_common/proto/core_api_pb2.py +109 -109
  38. langgraph_grpc_common/proto/core_api_pb2.pyi +23 -4
  39. openapi.json +161 -12
  40. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev5.dist-info}/WHEEL +0 -0
  41. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev5.dist-info}/entry_points.txt +0 -0
  42. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev5.dist-info}/licenses/LICENSE +0 -0
@@ -215,6 +215,7 @@ async def get_thread_state(
215
215
  thread_id = request.path_params["thread_id"]
216
216
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
217
217
  subgraphs = request.query_params.get("subgraphs") in ("true", "True")
218
+ select = _validate_history_select(request.query_params.getlist("select"))
218
219
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
219
220
  config = {
220
221
  "configurable": {
@@ -222,9 +223,7 @@ async def get_thread_state(
222
223
  "thread_id": thread_id,
223
224
  }
224
225
  }
225
- state = state_snapshot_to_thread_state(
226
- await Threads.State.get(conn, config=config, subgraphs=subgraphs)
227
- )
226
+ state = await _thread_state(conn, select, config=config, subgraphs=subgraphs)
228
227
  return ApiResponse(state)
229
228
 
230
229
 
@@ -236,6 +235,7 @@ async def get_thread_state_at_checkpoint(
236
235
  thread_id = request.path_params["thread_id"]
237
236
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
238
237
  checkpoint_id = request.path_params["checkpoint_id"]
238
+ select = _validate_history_select(request.query_params.getlist("select"))
239
239
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
240
240
  config = {
241
241
  "configurable": {
@@ -244,12 +244,11 @@ async def get_thread_state_at_checkpoint(
244
244
  "checkpoint_id": checkpoint_id,
245
245
  }
246
246
  }
247
- state = state_snapshot_to_thread_state(
248
- await Threads.State.get(
249
- conn,
250
- config=config,
251
- subgraphs=request.query_params.get("subgraphs") in ("true", "True"),
252
- )
247
+ state = await _thread_state(
248
+ conn,
249
+ select,
250
+ config=config,
251
+ subgraphs=request.query_params.get("subgraphs") in ("true", "True"),
253
252
  )
254
253
  return ApiResponse(state)
255
254
 
@@ -262,6 +261,7 @@ async def get_thread_state_at_checkpoint_post(
262
261
  thread_id = request.path_params["thread_id"]
263
262
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
264
263
  payload = await request.json(ThreadStateCheckpointRequest)
264
+ select = _validate_history_select(payload.get("select"))
265
265
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
266
266
  config = {
267
267
  "configurable": {
@@ -270,16 +270,25 @@ async def get_thread_state_at_checkpoint_post(
270
270
  "thread_id": thread_id,
271
271
  }
272
272
  }
273
- state = state_snapshot_to_thread_state(
274
- await Threads.State.get(
275
- conn,
276
- config=config,
277
- subgraphs=payload.get("subgraphs", False),
278
- )
273
+ state = await _thread_state(
274
+ conn,
275
+ select,
276
+ config=config,
277
+ subgraphs=payload.get("subgraphs", False),
279
278
  )
280
279
  return ApiResponse(state)
281
280
 
282
281
 
282
+ async def _thread_state(
283
+ conn: Any, select: list[str] | None, **kwargs: Any
284
+ ) -> "Mapping[str, Any]":
285
+ value_keys = _selected_value_keys(select)
286
+ if value_keys is not None:
287
+ kwargs["channels"] = value_keys
288
+ state = state_snapshot_to_thread_state(await Threads.State.get(conn, **kwargs))
289
+ return _project_thread_state(state, select, value_keys) if select else state
290
+
291
+
283
292
  @retry_db
284
293
  async def update_thread_state(
285
294
  request: ApiRequest,
@@ -407,7 +416,7 @@ def _validate_history_select(select: list[str] | None) -> list[str] | None:
407
416
 
408
417
 
409
418
  def _selected_value_keys(select: list[str] | None) -> list[str] | None:
410
- """State keys history entries return, or None when they return all of them."""
419
+ """State keys a state or history read returns, or None when it returns all."""
411
420
  if not select or "values" in select:
412
421
  return None
413
422
  return [f.removeprefix("values.") for f in select if f.startswith("values.")]
@@ -611,12 +620,15 @@ async def join_thread_stream(request: ApiRequest):
611
620
  if mode not in get_args(ThreadStreamMode):
612
621
  raise HTTPException(status_code=422, detail=f"Invalid stream mode: {mode}")
613
622
 
623
+ # Clients reconnect to Location as-is, so it keeps the request's query.
624
+ query = f"?{request.url.query}" if request.url.query else ""
614
625
  return EventSourceResponse(
615
626
  Threads.Stream.join(
616
627
  thread_id,
617
628
  last_event_id=last_event_id,
618
629
  stream_modes=stream_modes,
619
630
  ),
631
+ headers={"Location": f"/threads/{thread_id}/stream{query}"},
620
632
  )
621
633
 
622
634
 
@@ -9,7 +9,7 @@ import asyncio
9
9
  import typing
10
10
 
11
11
  from httpx import ASGITransport as ASGITransportBase
12
- from httpx import AsyncByteStream, Request, Response
12
+ from httpx import AsyncByteStream, RemoteProtocolError, Request, Response
13
13
 
14
14
  if typing.TYPE_CHECKING: # pragma: no cover
15
15
  import trio # type: ignore[unresolved-import]
@@ -272,10 +272,12 @@ class ASGITransport(ASGITransportBase):
272
272
  # The consumer drains queued chunks then sees the
273
273
  # error. Bound unconditionally — this is an ASGI
274
274
  # protocol error, not an app error, so it's not
275
- # gated on raise_app_exceptions.
275
+ # gated on raise_app_exceptions. A socket raises
276
+ # RemoteProtocolError for a truncated body, and the SDK
277
+ # reconnects a stream only on httpx errors.
276
278
  if not app_complete.done():
277
279
  app_complete.set_exception(
278
- RuntimeError("Response not complete")
280
+ RemoteProtocolError("Response not complete")
279
281
  )
280
282
  else:
281
283
  # 3. Clean completion (send saw more_body=False).
langgraph_api/command.py CHANGED
@@ -1,9 +1,24 @@
1
- from typing import cast
1
+ import re
2
+ from typing import Any, cast
2
3
 
3
4
  from langgraph.types import Command, Send
4
5
 
5
6
  from langgraph_api.schema import RunCommand
6
7
 
8
+ # langgraph resumes interrupts by id only when every key of the resume map has
9
+ # this shape; any other key turns the whole map into one value for whichever
10
+ # interrupt is pending.
11
+ INTERRUPT_ID_RE = re.compile(r"[0-9a-f]{32}")
12
+
13
+
14
+ def keyed_by_interrupt_id(value: Any) -> bool:
15
+ """Whether langgraph resumes ``value`` per interrupt rather than as one answer."""
16
+ return (
17
+ isinstance(value, dict)
18
+ and bool(value)
19
+ and all(INTERRUPT_ID_RE.fullmatch(key) for key in value)
20
+ )
21
+
7
22
 
8
23
  def map_cmd(cmd: RunCommand) -> Command:
9
24
  goto = cmd.get("goto")
@@ -205,7 +205,7 @@ LANGGRAPH_CLOUD_LICENSE_KEY = env("LANGGRAPH_CLOUD_LICENSE_KEY", cast=str, defau
205
205
 
206
206
  # When true, the Go core-server owns Postgres schema setup (DB migrations +
207
207
  # vector index)
208
- DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=False)
208
+ DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=True)
209
209
 
210
210
  # redis
211
211
  # Not in public docs: infrastructure, set by platform
@@ -7,8 +7,8 @@ from typing import Any
7
7
  import orjson
8
8
  import structlog
9
9
  from starlette.exceptions import HTTPException
10
- from starlette.middleware.base import BaseHTTPMiddleware
11
10
  from starlette.requests import Request
11
+ from starlette.types import ASGIApp, Receive, Scope, Send
12
12
 
13
13
  from langgraph_api.config import LANGGRAPH_ENCRYPTION
14
14
  from langgraph_api.encryption.custom import get_custom_encryption_instance
@@ -68,10 +68,17 @@ def extract_encryption_context(request: Request) -> dict[str, Any]:
68
68
  ) from e
69
69
 
70
70
 
71
- class EncryptionContextMiddleware(BaseHTTPMiddleware):
71
+ class EncryptionContextMiddleware:
72
72
  """Set request encryption context from headers and the configured handler."""
73
73
 
74
- async def dispatch(self, request: Request, call_next):
74
+ def __init__(self, app: ASGIApp) -> None:
75
+ self.app = app
76
+
77
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
78
+ if scope["type"] != "http":
79
+ await self.app(scope, receive, send)
80
+ return
81
+ request = Request(scope)
75
82
  context_dict = extract_encryption_context(request)
76
83
 
77
84
  encryption_instance = get_custom_encryption_instance()
@@ -92,4 +99,4 @@ class EncryptionContextMiddleware(BaseHTTPMiddleware):
92
99
 
93
100
  set_encryption_context(context_dict)
94
101
  request.state.encryption_context = context_dict
95
- return await call_next(request)
102
+ await self.app(scope, receive, send)
langgraph_api/errors.py CHANGED
@@ -93,3 +93,13 @@ class UserTimeout(Exception):
93
93
  def __init__(self, timeout_error: TimeoutError):
94
94
  super().__init__(timeout_error)
95
95
  self.timeout_error = timeout_error
96
+
97
+
98
+ class StreamCutError(Exception):
99
+ """The event stream behind a response ended before its run did.
100
+
101
+ The SSE response aborts instead of sending an ``error`` event, so the SDKs
102
+ reconnect run and thread streams with ``Last-Event-ID``. Behind a custom
103
+ ``BaseHTTPMiddleware``, which would end an aborted response cleanly, the
104
+ response sends an ``error`` event instead.
105
+ """
@@ -37,7 +37,7 @@ the runtime cannot emit native protocol-shaped message events.
37
37
  ``messages/partial`` events, which v2 no longer supports.
38
38
 
39
39
  Remote (JS) pregels bypass every code path that needs these symbols
40
- (``stream.py`` drops ``tools`` / ``lifecycle`` and skips the
40
+ (on protocol v2 runs ``stream.py`` drops ``tools`` / ``lifecycle`` and skips the
41
41
  content-block dispatch for remote graphs), so a ``BaseRemotePregel``-only
42
42
  deployment could in theory run on an older Python ``langgraph``. The
43
43
  probe is still applied — the DX of a clear "upgrade your dependencies"
@@ -21,7 +21,6 @@ from __future__ import annotations
21
21
  import asyncio
22
22
  import contextlib
23
23
  import inspect
24
- import re
25
24
  import time
26
25
  from collections.abc import Awaitable, Callable, Mapping
27
26
  from typing import Any, cast, get_args
@@ -30,6 +29,7 @@ from uuid import UUID, uuid4
30
29
  import orjson
31
30
  import structlog
32
31
 
32
+ from langgraph_api.command import INTERRUPT_ID_RE, keyed_by_interrupt_id
33
33
  from langgraph_api.event_streaming.capabilities import (
34
34
  ProtocolV2Capabilities,
35
35
  ProtocolV2UnsupportedError,
@@ -152,25 +152,12 @@ EventSink = Callable[[dict[str, Any]], Awaitable[None] | None]
152
152
  _IN_FLIGHT_THREAD_STATUS = "busy"
153
153
  _INTERRUPT_SETTLE_TIMEOUT_SECONDS = 5.0
154
154
  _INTERRUPT_SETTLE_POLL_INTERVAL_SECONDS = 0.05
155
- # langgraph resumes interrupts by id only when every key of the resume map has
156
- # this shape; any other key turns the whole map into one value for whichever
157
- # interrupt is pending.
158
- _INTERRUPT_ID_RE = re.compile(r"[0-9a-f]{32}")
159
155
 
160
156
 
161
157
  class _AmbiguousResumeError(Exception):
162
158
  """``run.start`` input would resume several pending interrupts at once."""
163
159
 
164
160
 
165
- def _keyed_by_interrupt_id(value: Any) -> bool:
166
- """Whether langgraph resumes ``value`` per interrupt rather than as one answer."""
167
- return (
168
- _is_record(value)
169
- and bool(value)
170
- and all(_INTERRUPT_ID_RE.fullmatch(key) for key in value)
171
- )
172
-
173
-
174
161
  # Protocol v2 commands this server implements. Anything outside this
175
162
  # set returns ``unknown_command`` up front from ``handle_command`` so
176
163
  # pre-session dispatch does not mislabel typos (or removed methods
@@ -709,7 +696,7 @@ class ThreadRunManager:
709
696
  # open for any id shaped like an interrupt id: the resume below is
710
697
  # authoritative, so neither must masquerade as a missing interrupt.
711
698
  if thread_state_ids is None:
712
- rejected = not _INTERRUPT_ID_RE.fullmatch(interrupt_id)
699
+ rejected = not INTERRUPT_ID_RE.fullmatch(interrupt_id)
713
700
  else:
714
701
  rejected = interrupt_id not in thread_state_ids
715
702
  if rejected:
@@ -816,7 +803,7 @@ class ThreadRunManager:
816
803
  has_interrupts = False
817
804
  if params.get("input") is not None and not force_resume:
818
805
  has_interrupts = await self._has_pending_interrupts()
819
- if has_interrupts and not _keyed_by_interrupt_id(params["input"]):
806
+ if has_interrupts and not keyed_by_interrupt_id(params["input"]):
820
807
  # One answer can't say which of several pending interrupts it is
821
808
  # for: langgraph fails the run, or picks one when they share a
822
809
  # subgraph task. Only a paused thread's row is current, so a run in
@@ -567,6 +567,10 @@ class EventStreamingSession:
567
567
  scope cleanly wraps every push triggered by this source event.
568
568
  """
569
569
 
570
+ if method == "interrupts":
571
+ await self._emit_input_answered(data)
572
+ return
573
+
570
574
  # Core ``langgraph.stream`` already emits canonical ProtocolEvent
571
575
  # objects. Re-envelope them with this session's seq/event_id so
572
576
  # transport replay remains API-owned.
@@ -1118,7 +1122,7 @@ class EventStreamingSession:
1118
1122
  self, subscription: Subscription, event: dict[str, Any]
1119
1123
  ) -> bool:
1120
1124
  raw_method = event.get("method", "")
1121
- channel = "input" if raw_method == "input.requested" else raw_method
1125
+ channel = "input" if raw_method.startswith("input.") else raw_method
1122
1126
  if not _is_supported_channel(channel):
1123
1127
  return False
1124
1128
  if channel == "custom":
@@ -1576,6 +1580,16 @@ class EventStreamingSession:
1576
1580
  """
1577
1581
  return self._pending_interrupts.get(interrupt_id)
1578
1582
 
1583
+ async def _emit_input_answered(self, data: Any) -> None:
1584
+ answered = data.get("answered") if _is_record(data) else None
1585
+ if not isinstance(answered, list) or not answered:
1586
+ return
1587
+ for interrupt_id in answered:
1588
+ self.clear_pending_interrupt(interrupt_id)
1589
+ await self._push_event(
1590
+ self._create_event("input.answered", [], {"interrupt_ids": answered})
1591
+ )
1592
+
1579
1593
  def clear_pending_interrupt(self, interrupt_id: str) -> None:
1580
1594
  """Remove *interrupt_id* from the pending set after a successful resume."""
1581
1595
  self._pending_interrupts.pop(interrupt_id, None)
@@ -91,3 +91,8 @@ DELTA_CHANNEL_SUPPORT = LANGGRAPH_PY_MINOR >= (1, 2)
91
91
  # (langchain-ai/langgraph#9281). Earlier versions drain in front of a
92
92
  # breakpoint, and the resume then runs past it.
93
93
  DRAIN_RESUME_SUPPORT = LANGGRAPH_PY_PATCH >= (1, 2, 15)
94
+
95
+ # v1 runs stream `tools` events from langgraph 1.2.19. Before it, a tool that
96
+ # pauses on `interrupt()` is reported as failed, and an awaited `@task` in a
97
+ # subgraph returns None while the tools handler runs.
98
+ TOOLS_STREAM_SUPPORT = LANGGRAPH_PY_PATCH >= (1, 2, 19)
@@ -21,6 +21,7 @@ from starlette.exceptions import HTTPException
21
21
  from langgraph_api.auth.custom import handle_event as auth_handle_event
22
22
  from langgraph_api.encryption.context import get_encryption_context
23
23
  from langgraph_api.encryption.shared import using_encryption
24
+ from langgraph_api.errors import StreamCutError
24
25
  from langgraph_api.serde import json_dumpb
25
26
  from langgraph_api.utils import get_auth_ctx
26
27
 
@@ -186,6 +187,8 @@ def _handle_grpc_error(error: AioRpcError) -> None:
186
187
  - A string. This we can return verbatim.
187
188
  Always return detail as a string here.
188
189
  """
190
+ if error.code() == StatusCode.ABORTED:
191
+ raise StreamCutError(error.details()) from error
189
192
  error_details = error.details()
190
193
  retry_after_seconds = None
191
194
  if error_details is not None:
@@ -282,6 +282,7 @@ class GrpcStreamHandler:
282
282
  ignore_run_not_found: bool = False,
283
283
  cancel_on_disconnect: bool = False,
284
284
  last_event_id: str | None = None,
285
+ namespaces: list[str] | None = None,
285
286
  ):
286
287
  """Send JoinRunRequest and yield events.
287
288
 
@@ -301,6 +302,8 @@ class GrpcStreamHandler:
301
302
  join_kwargs["stream_modes"] = stream_modes
302
303
  if last_event_id is not None:
303
304
  join_kwargs["last_event_id"] = last_event_id
305
+ if namespaces:
306
+ join_kwargs["namespaces"] = namespaces
304
307
 
305
308
  # Send JoinRunRequest
306
309
  join_msg = pb.StreamRunClientMessage(join=pb.JoinRunRequest(**join_kwargs))
@@ -677,18 +680,31 @@ class Runs(Authenticated):
677
680
  *,
678
681
  thread_id: UUID,
679
682
  ctx: Any = None,
683
+ read_mask_paths: list[str] | None = None,
680
684
  ) -> AsyncIterator[Run]:
681
- """Get a run by ID."""
685
+ """Get a run by ID.
686
+
687
+ Args:
688
+ read_mask_paths: When set, "metadata" and "kwargs" are read only if
689
+ listed, and every other field always is; omitting "kwargs" skips
690
+ the run's input. None reads every field.
691
+ """
682
692
  auth_filters = await Runs.handle_event(
683
693
  ctx,
684
694
  "read",
685
695
  Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id),
686
696
  )
687
697
 
698
+ read_mask = (
699
+ field_mask_pb2.FieldMask(paths=read_mask_paths)
700
+ if read_mask_paths is not None
701
+ else None
702
+ )
688
703
  request = pb.GetRunRequest(
689
704
  run_id=pb.UUID(value=str(run_id)),
690
705
  thread_id=pb.UUID(value=str(thread_id)),
691
706
  filters=auth_filters,
707
+ read_mask=read_mask,
692
708
  )
693
709
 
694
710
  client = await get_shared_client()
@@ -1020,11 +1036,14 @@ class Runs(Authenticated):
1020
1036
  }
1021
1037
  if response.HasField("redis"):
1022
1038
  r = response.redis
1023
- out["redis"] = {
1039
+ redis_stats: dict[str, int] = {
1024
1040
  "idle_connections": r.idle_connections,
1025
1041
  "in_use_connections": r.in_use_connections,
1026
- "max_connections": r.max_connections,
1027
1042
  }
1043
+ # Cluster omits max — proto3 zero is indistinguishable from unset.
1044
+ if r.max_connections:
1045
+ redis_stats["max_connections"] = r.max_connections
1046
+ out["redis"] = redis_stats
1028
1047
  return out
1029
1048
 
1030
1049
  @staticmethod
@@ -1159,6 +1178,7 @@ class Runs(Authenticated):
1159
1178
  cancel_on_disconnect: bool = False,
1160
1179
  stream_mode: list[str] | None = None,
1161
1180
  last_event_id: str | None = None,
1181
+ namespaces: list[str] | None = None,
1162
1182
  ctx: Any = None,
1163
1183
  ):
1164
1184
  """Join the run stream and start receiving events.
@@ -1183,6 +1203,7 @@ class Runs(Authenticated):
1183
1203
  ignore_run_not_found=ignore_404,
1184
1204
  cancel_on_disconnect=cancel_on_disconnect,
1185
1205
  last_event_id=last_event_id,
1206
+ namespaces=namespaces,
1186
1207
  ):
1187
1208
  yield (event_bytes, message_bytes, stream_id_bytes)
1188
1209
  except AioRpcError as e:
@@ -47,9 +47,9 @@ from langgraph_api.grpc.ops.runs import Runs, forget_deleted_thread
47
47
  from langgraph_api.schema import ThreadUpdateResponse
48
48
  from langgraph_api.serde import json_dumpb, json_dumpb_optional, json_loads
49
49
  from langgraph_api.state import (
50
- iter_state_history,
51
- narrow_history_reads,
52
50
  patch_interrupt,
51
+ read_state,
52
+ read_state_history,
53
53
  state_snapshot_to_thread_state,
54
54
  )
55
55
  from langgraph_api.utils import fetchone
@@ -1108,8 +1108,15 @@ class Threads(Authenticated):
1108
1108
  config: dict[str, Any],
1109
1109
  subgraphs: bool,
1110
1110
  ctx: Any = None,
1111
+ channels: Sequence[str] | None = None,
1111
1112
  ) -> StateSnapshot:
1112
- """Get state snapshot for a thread (*internal only*, no auth)."""
1113
+ """Get state snapshot for a thread (*internal only*, no auth).
1114
+
1115
+ ``channels`` names the state keys the caller needs; the rest of
1116
+ the checkpoint's stored state is left unread when the checkpointer
1117
+ supports it. None loads everything, as do reads with ``subgraphs``,
1118
+ since subgraph states are read with the same checkpointer.
1119
+ """
1113
1120
  checkpointer = await api_checkpointer.get_checkpointer(
1114
1121
  conn=conn, unpack_hook=_msgpack_ext_hook_to_json
1115
1122
  )
@@ -1150,7 +1157,9 @@ class Threads(Authenticated):
1150
1157
  store=(await api_store.get_store()),
1151
1158
  access_context="threads.read",
1152
1159
  ) as graph:
1153
- return await graph.aget_state(config, subgraphs=subgraphs)
1160
+ if subgraphs:
1161
+ return await graph.aget_state(config, subgraphs=True)
1162
+ return await read_state(graph, config, channels)
1154
1163
  else:
1155
1164
  _kwargs: dict[str, Any] = {
1156
1165
  "values": {},
@@ -1422,24 +1431,19 @@ class Threads(Authenticated):
1422
1431
  store=(await api_store.get_store()),
1423
1432
  access_context="threads.read",
1424
1433
  ) as graph:
1425
- graph = narrow_history_reads(graph, config, channels)
1426
1434
  before_config = (
1427
1435
  {"configurable": {"checkpoint_id": before}}
1428
1436
  if isinstance(before, str)
1429
1437
  else before
1430
1438
  )
1431
- history = (
1432
- iter_state_history(
1433
- graph,
1434
- config,
1435
- limit=limit,
1436
- filter=metadata,
1437
- before=before_config,
1438
- )
1439
- if incremental
1440
- else graph.aget_state_history(
1441
- config, limit=limit, filter=metadata, before=before_config
1442
- )
1439
+ history = read_state_history(
1440
+ graph,
1441
+ config,
1442
+ channels,
1443
+ limit=limit,
1444
+ filter=metadata,
1445
+ before=before_config,
1446
+ incremental=incremental,
1443
1447
  )
1444
1448
  async with aclosing(history) as states:
1445
1449
  async for c in states:
@@ -32,6 +32,7 @@ import * as path from "node:path";
32
32
  import { serialiseAsDict, serializeError } from "./src/utils/serde.mjs";
33
33
  import * as importMap from "./src/utils/importMap.mjs";
34
34
  import { buildExperimentReplicas } from "./src/utils/experiment-tracing.mjs";
35
+ import { ChainLifecycle } from "./src/lifecycle.mjs";
35
36
 
36
37
  import { createLogger, format, transports } from "winston";
37
38
 
@@ -147,6 +148,15 @@ const version = await (async () => {
147
148
  return undefined;
148
149
  })();
149
150
 
151
+ // Before 1.6.0 a tool that pauses on `interrupt()` is reported as failed.
152
+ const TOOLS_STREAM_SUPPORT = (() => {
153
+ if (typeof version !== "string") return false;
154
+ const parts = version.split(".").map((part) => parseInt(part, 10));
155
+ if (parts.length < 3 || parts.some(Number.isNaN)) return false;
156
+ const [major, minor] = parts;
157
+ return major > 1 || (major === 1 && minor >= 6);
158
+ })();
159
+
150
160
  const GRAPH_RESOLVED: Record<
151
161
  string,
152
162
  CompiledGraph<string> | CompiledGraphFactory<string>
@@ -700,6 +710,7 @@ const StreamEventsPayload = z.object({
700
710
  interrupt_before: z.union([z.array(z.string()), z.literal("*")]).nullish(),
701
711
  interrupt_after: z.union([z.array(z.string()), z.literal("*")]).nullish(),
702
712
  subgraphs: z.boolean().optional(),
713
+ lifecycle: z.boolean().optional(),
703
714
  durability: DurabilitySchema.optional(),
704
715
  // Selects the wire shape the worker expects back. ``"v3"`` is only sent
705
716
  // by the Protocol v2 event-streaming endpoints and switches this handler
@@ -771,7 +782,7 @@ async function* streamEventsRequest(
771
782
  graphStreamMode.add("values");
772
783
  } else if (mode === "messages-tuple") {
773
784
  graphStreamMode.add("messages");
774
- } else {
785
+ } else if (mode !== "tools" || TOOLS_STREAM_SUPPORT) {
775
786
  graphStreamMode.add(mode);
776
787
  }
777
788
  }
@@ -807,9 +818,17 @@ async function* streamEventsRequest(
807
818
  // when one with name "langchain_tracer" is already present in
808
819
  // config.callbacks (see @langchain/core callbacks/manager.js).
809
820
  const replicas = buildExperimentReplicas(config.configurable);
810
- const callbacks: BaseCallbackHandler[] | undefined = replicas
811
- ? [new LangChainTracer({ replicas })]
812
- : undefined;
821
+ const lifecycle = payload.lifecycle ? new ChainLifecycle() : undefined;
822
+ const handlers: BaseCallbackHandler[] = [
823
+ ...(replicas ? [new LangChainTracer({ replicas })] : []),
824
+ ...(lifecycle ? [lifecycle] : []),
825
+ ];
826
+ const callbacks = handlers.length > 0 ? handlers : undefined;
827
+
828
+ const outputKeys =
829
+ payload.output_keys === undefined
830
+ ? graph.outputChannels
831
+ : (payload.output_keys ?? undefined);
813
832
 
814
833
  // Protocol v2 event-streaming runs request ``stream_protocol: "v3"``.
815
834
  // Drive the run through LangGraphJS's native v3 stream so its
@@ -837,10 +856,7 @@ async function* streamEventsRequest(
837
856
  ...config,
838
857
  signal,
839
858
  version: "v3",
840
- outputKeys:
841
- payload.output_keys === undefined
842
- ? graph.outputChannels
843
- : (payload.output_keys ?? undefined),
859
+ outputKeys,
844
860
  interruptBefore,
845
861
  interruptAfter,
846
862
  ...(callbacks ? { callbacks } : {}),
@@ -860,6 +876,7 @@ async function* streamEventsRequest(
860
876
  signal,
861
877
  version: "v2",
862
878
  streamMode,
879
+ outputKeys,
863
880
  subgraphs: payload.subgraphs,
864
881
  interruptBefore,
865
882
  interruptAfter,
@@ -879,6 +896,7 @@ async function* streamEventsRequest(
879
896
  }
880
897
  }
881
898
 
899
+ if (lifecycle) yield* lifecycle.events.splice(0);
882
900
  yield data;
883
901
 
884
902
  if (userStreamMode.includes("messages")) {
@@ -946,6 +964,8 @@ async function* streamEventsRequest(
946
964
  }
947
965
  }
948
966
  }
967
+
968
+ if (lifecycle) yield* lifecycle.events.splice(0);
949
969
  }
950
970
 
951
971
  const GetGraphPayload = z.object({