langgraph-api 0.3.4__py3-none-any.whl → 0.4.0__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.

Potentially problematic release.


This version of langgraph-api might be problematic. Click here for more details.

langgraph_api/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.3.4"
1
+ __version__ = "0.4.0"
langgraph_api/api/runs.py CHANGED
@@ -1,6 +1,7 @@
1
1
  import asyncio
2
2
  from collections.abc import AsyncIterator
3
3
  from typing import Literal, cast
4
+ from uuid import uuid4
4
5
 
5
6
  import orjson
6
7
  from starlette.exceptions import HTTPException
@@ -100,7 +101,7 @@ async def stream_run(
100
101
  payload = await request.json(RunCreateStateful)
101
102
  on_disconnect = payload.get("on_disconnect", "continue")
102
103
  run_id = uuid7()
103
- sub = asyncio.create_task(Runs.Stream.subscribe(run_id))
104
+ sub = asyncio.create_task(Runs.Stream.subscribe(run_id, thread_id))
104
105
 
105
106
  try:
106
107
  async with connect() as conn:
@@ -138,19 +139,21 @@ async def stream_run_stateless(
138
139
  ):
139
140
  """Create a stateless run."""
140
141
  payload = await request.json(RunCreateStateless)
142
+ payload["if_not_exists"] = "create"
141
143
  on_disconnect = payload.get("on_disconnect", "continue")
142
144
  run_id = uuid7()
143
- sub = asyncio.create_task(Runs.Stream.subscribe(run_id))
144
-
145
+ thread_id = uuid4()
146
+ sub = asyncio.create_task(Runs.Stream.subscribe(run_id, thread_id))
145
147
  try:
146
148
  async with connect() as conn:
147
149
  run = await create_valid_run(
148
150
  conn,
149
- None,
151
+ str(thread_id),
150
152
  payload,
151
153
  request.headers,
152
154
  run_id=run_id,
153
155
  request_start_time=request.scope.get("request_start_time_ms"),
156
+ temporary=True,
154
157
  )
155
158
  except Exception:
156
159
  if not sub.cancelled():
@@ -181,7 +184,7 @@ async def wait_run(request: ApiRequest):
181
184
  payload = await request.json(RunCreateStateful)
182
185
  on_disconnect = payload.get("on_disconnect", "continue")
183
186
  run_id = uuid7()
184
- sub = asyncio.create_task(Runs.Stream.subscribe(run_id))
187
+ sub = asyncio.create_task(Runs.Stream.subscribe(run_id, thread_id))
185
188
 
186
189
  try:
187
190
  async with connect() as conn:
@@ -263,26 +266,28 @@ async def wait_run(request: ApiRequest):
263
266
  async def wait_run_stateless(request: ApiRequest):
264
267
  """Create a stateless run, wait for the output."""
265
268
  payload = await request.json(RunCreateStateless)
269
+ payload["if_not_exists"] = "create"
266
270
  on_disconnect = payload.get("on_disconnect", "continue")
267
271
  run_id = uuid7()
268
- sub = asyncio.create_task(Runs.Stream.subscribe(run_id))
272
+ thread_id = uuid4()
273
+ sub = asyncio.create_task(Runs.Stream.subscribe(run_id, thread_id))
269
274
 
270
275
  try:
271
276
  async with connect() as conn:
272
277
  run = await create_valid_run(
273
278
  conn,
274
- None,
279
+ str(thread_id),
275
280
  payload,
276
281
  request.headers,
277
282
  run_id=run_id,
278
283
  request_start_time=request.scope.get("request_start_time_ms"),
284
+ temporary=True,
279
285
  )
280
286
  except Exception:
281
287
  if not sub.cancelled():
282
288
  handle = await sub
283
289
  await handle.__aexit__(None, None, None)
284
290
  raise
285
-
286
291
  last_chunk = ValueEvent()
287
292
 
288
293
  async def consume():
@@ -6,11 +6,13 @@ from starlette.routing import BaseRoute
6
6
 
7
7
  from langgraph_api.route import ApiRequest, ApiResponse, ApiRoute
8
8
  from langgraph_api.schema import THREAD_FIELDS
9
+ from langgraph_api.sse import EventSourceResponse
9
10
  from langgraph_api.state import state_snapshot_to_thread_state
10
11
  from langgraph_api.utils import (
11
12
  fetchone,
12
13
  get_pagination_headers,
13
14
  validate_select_columns,
15
+ validate_stream_id,
14
16
  validate_uuid,
15
17
  )
16
18
  from langgraph_api.validation import (
@@ -282,6 +284,23 @@ async def copy_thread(request: ApiRequest):
282
284
  return ApiResponse(await fetchone(iter, not_found_code=409))
283
285
 
284
286
 
287
+ @retry_db
288
+ async def join_thread_stream(request: ApiRequest):
289
+ """Join a thread stream."""
290
+ thread_id = request.path_params["thread_id"]
291
+ validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
292
+ last_event_id = request.headers.get("last-event-id") or None
293
+ validate_stream_id(
294
+ last_event_id, "Invalid last-event-id: must be a valid Redis stream ID"
295
+ )
296
+ return EventSourceResponse(
297
+ Threads.Stream.join(
298
+ thread_id,
299
+ last_event_id=last_event_id,
300
+ ),
301
+ )
302
+
303
+
285
304
  threads_routes: list[BaseRoute] = [
286
305
  ApiRoute("/threads", endpoint=create_thread, methods=["POST"]),
287
306
  ApiRoute("/threads/search", endpoint=search_threads, methods=["POST"]),
@@ -312,4 +331,9 @@ threads_routes: list[BaseRoute] = [
312
331
  endpoint=get_thread_state_at_checkpoint_post,
313
332
  methods=["POST"],
314
333
  ),
334
+ ApiRoute(
335
+ "/threads/{thread_id}/stream",
336
+ endpoint=join_thread_stream,
337
+ methods=["GET"],
338
+ ),
315
339
  ]
@@ -249,6 +249,7 @@ async def create_valid_run(
249
249
  barrier: asyncio.Barrier | None = None,
250
250
  run_id: UUID | None = None,
251
251
  request_start_time: float | None = None,
252
+ temporary: bool = False,
252
253
  ) -> Run:
253
254
  request_id = headers.get("x-request-id") # Will be null in the crons scheduler.
254
255
  (
@@ -262,7 +263,7 @@ async def create_valid_run(
262
263
  run_id=run_id,
263
264
  )
264
265
  if (
265
- thread_id_ is None
266
+ (thread_id_ is None or temporary)
266
267
  and (command := payload.get("command"))
267
268
  and command.get("resume")
268
269
  ):
@@ -270,9 +271,9 @@ async def create_valid_run(
270
271
  status_code=400,
271
272
  detail="You must provide a thread_id when resuming.",
272
273
  )
273
- temporary = (
274
- thread_id_ is None and payload.get("on_completion", "delete") == "delete"
275
- )
274
+ temporary = (temporary or thread_id_ is None) and payload.get(
275
+ "on_completion", "delete"
276
+ ) == "delete"
276
277
  stream_resumable = payload.get("stream_resumable", False)
277
278
  stream_mode, multitask_strategy, prevent_insert_if_inflight = assign_defaults(
278
279
  payload
langgraph_api/stream.py CHANGED
@@ -2,7 +2,7 @@ import uuid
2
2
  from collections.abc import AsyncIterator, Callable
3
3
  from contextlib import AsyncExitStack, aclosing, asynccontextmanager
4
4
  from functools import lru_cache
5
- from typing import Any, Literal, cast
5
+ from typing import Any, cast
6
6
 
7
7
  import langgraph.version
8
8
  import langsmith
@@ -423,7 +423,9 @@ async def consume(
423
423
  stream: AnyStream,
424
424
  run_id: str | uuid.UUID,
425
425
  resumable: bool = False,
426
- stream_modes: set[StreamMode | Literal["metadata"]] | None = None,
426
+ stream_modes: set[StreamMode] | None = None,
427
+ *,
428
+ thread_id: str | uuid.UUID | None = None,
427
429
  ) -> None:
428
430
  stream_modes = stream_modes or set()
429
431
  if "messages-tuple" in stream_modes:
@@ -437,6 +439,7 @@ async def consume(
437
439
  run_id,
438
440
  mode,
439
441
  await run_in_executor(None, json_dumpb, payload),
442
+ thread_id=thread_id,
440
443
  resumable=resumable and mode.split("|")[0] in stream_modes,
441
444
  )
442
445
  except Exception as e:
@@ -446,6 +449,7 @@ async def consume(
446
449
  run_id,
447
450
  "error",
448
451
  await run_in_executor(None, json_dumpb, e),
452
+ thread_id=thread_id,
449
453
  )
450
454
  raise e
451
455
 
@@ -1,4 +1,5 @@
1
1
  import contextvars
2
+ import re
2
3
  import uuid
3
4
  from collections.abc import AsyncIterator
4
5
  from contextlib import asynccontextmanager
@@ -22,6 +23,7 @@ Row: TypeAlias = dict[str, Any]
22
23
  AuthContext = contextvars.ContextVar[Auth.types.BaseAuthContext | None](
23
24
  "AuthContext", default=None
24
25
  )
26
+ STREAM_ID_PATTERN = re.compile(r"^\d+(-(\d+|\*))?$")
25
27
 
26
28
 
27
29
  @asynccontextmanager
@@ -101,6 +103,23 @@ def validate_uuid(uuid_str: str, invalid_uuid_detail: str | None) -> uuid.UUID:
101
103
  raise HTTPException(status_code=422, detail=invalid_uuid_detail) from None
102
104
 
103
105
 
106
+ def validate_stream_id(stream_id: str | None, invalid_stream_id_detail: str | None):
107
+ """
108
+ Validate Redis stream ID format.
109
+ Valid formats:
110
+ - timestamp-sequence (e.g., "1724342400000-0")
111
+ - timestamp-* (e.g., "1724342400000-*")
112
+ - timestamp only (e.g., "1724342400000")
113
+ - "-" (special case, represents the beginning of the stream, use if you want to replay all events)
114
+ """
115
+ if not stream_id or stream_id == "-":
116
+ return stream_id
117
+
118
+ if STREAM_ID_PATTERN.match(stream_id):
119
+ return stream_id
120
+ raise HTTPException(status_code=422, detail=invalid_stream_id_detail)
121
+
122
+
104
123
  def next_cron_date(schedule: str, base_time: datetime) -> datetime:
105
124
  import croniter # type: ignore[unresolved-import]
106
125
 
langgraph_api/worker.py CHANGED
@@ -139,7 +139,9 @@ async def worker(
139
139
  stream_modes: set[StreamMode],
140
140
  ):
141
141
  try:
142
- await consume(stream, run_id, resumable, stream_modes)
142
+ await consume(
143
+ stream, run_id, resumable, stream_modes, thread_id=run["thread_id"]
144
+ )
143
145
  except Exception as e:
144
146
  if not isinstance(e, UserRollback | UserInterrupt):
145
147
  logger.exception(
@@ -151,7 +153,7 @@ async def worker(
151
153
  raise UserTimeout(e) from e
152
154
  raise
153
155
 
154
- async with Runs.enter(run_id, main_loop) as done:
156
+ async with Runs.enter(run_id, run["thread_id"], main_loop) as done:
155
157
  # attempt the run
156
158
  try:
157
159
  if attempt > BG_JOB_MAX_RETRIES:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: langgraph-api
3
- Version: 0.3.4
3
+ Version: 0.4.0
4
4
  Author-email: Nuno Campos <nuno@langchain.dev>, Will Fu-Hinthorn <will@langchain.dev>
5
5
  License: Elastic-2.0
6
6
  License-File: LICENSE
@@ -1,4 +1,4 @@
1
- langgraph_api/__init__.py,sha256=oYLGMpySamd16KLiaBTfRyrAS7_oyp-TOEHmzmeumwg,22
1
+ langgraph_api/__init__.py,sha256=42STGor_9nKYXumfeV5tiyD_M8VdcddX7CEexmibPBk,22
2
2
  langgraph_api/asgi_transport.py,sha256=XtiLOu4WWsd-xizagBLzT5xUkxc9ZG9YqwvETBPjBFE,5161
3
3
  langgraph_api/asyncio.py,sha256=mZ7G32JjrGxrlH4OMy7AKlBQo5bZt4Sm2rlrBcU-Vj8,9483
4
4
  langgraph_api/cli.py,sha256=-ruIeKi1imvS6GriOfRDZY-waV4SbWiJ0BEFAciPVYI,16330
@@ -22,21 +22,21 @@ langgraph_api/server.py,sha256=uCAqPgCLJ6ckslLs0i_dacSR8mzuR0Y6PkkJYk0O3bE,7196
22
22
  langgraph_api/sse.py,sha256=SLdtZmTdh5D8fbWrQjuY9HYLd2dg8Rmi6ZMmFMVc2iE,4204
23
23
  langgraph_api/state.py,sha256=5RTOShiFVnkx-o6t99_x63CGwXw_8Eb-dSTpYirP8ro,4683
24
24
  langgraph_api/store.py,sha256=NIoNZojs6NbtG3VLBPQEFNttvp7XPkHAfjbQ3gY7aLY,4701
25
- langgraph_api/stream.py,sha256=iRF4Hu6A1n-KvDR4ki1BeOvOnOxGoV2NV8tiBHUWZOs,18428
25
+ langgraph_api/stream.py,sha256=IpGW9vpknI_wWteEmZfQKqCYqbaJAzOpq0FgdFJP60s,18528
26
26
  langgraph_api/thread_ttl.py,sha256=7H3gFlWcUiODPoaEzcwB0LR61uvcuyjD0ew_4BztB7k,1902
27
27
  langgraph_api/traceblock.py,sha256=Qq5CUdefnMDaRDnyvBSWGBClEj-f3oO7NbH6fedxOSE,630
28
28
  langgraph_api/utils.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
29
  langgraph_api/validation.py,sha256=86jftgOsMa7tkeshBw6imYe7zyUXPoVuf5Voh6dFiR8,5285
30
30
  langgraph_api/webhook.py,sha256=SvSM1rdnNtiH4q3JQYmAqJUk2Sable5xAcwOLuRhtlo,1723
31
- langgraph_api/worker.py,sha256=HVGyGVEYcXG-iKVgoBdFgANGxPjSs57JRl5OB4ra4nw,15267
31
+ langgraph_api/worker.py,sha256=M9WQdxEzVGDZqdjz3LHEHhM1g6isPcf3k1V4PEkcSY8,15343
32
32
  langgraph_api/api/__init__.py,sha256=WHy6oNLWtH1K7AxmmsU9RD-Vm6WP-Ov16xS8Ey9YCmQ,6090
33
33
  langgraph_api/api/assistants.py,sha256=5gVvU58Y1-EftBhCHGbEaOi_7cqGMKWhOt_GVfBC0Gg,16836
34
34
  langgraph_api/api/mcp.py,sha256=qe10ZRMN3f-Hli-9TI8nbQyWvMeBb72YB1PZVbyqBQw,14418
35
35
  langgraph_api/api/meta.py,sha256=dFD9ZgykbKARLdVSaJD9vO3CShvEyBmGpkjE8tqii0c,4448
36
36
  langgraph_api/api/openapi.py,sha256=If-z1ckXt-Yu5bwQytK1LWyX_T7G46UtLfixgEP8hwc,11959
37
- langgraph_api/api/runs.py,sha256=AiohGTFLjWCb-oTXoNDvPMod4v6RS_ivlieoiqDmtQM,21812
37
+ langgraph_api/api/runs.py,sha256=1RlD4WA8auCNugFjJSgaM9WPnwEHeWsJLEuKpwSRqcU,22089
38
38
  langgraph_api/api/store.py,sha256=xGcPFx4v-VxlK6HRU9uCjzCQ0v66cvc3o_PB5_g7n0Q,5550
39
- langgraph_api/api/threads.py,sha256=Ap5zUcYqK5GJqwEc-q4QY6qCkmbLxfMmEvQZm0MCFxk,10427
39
+ langgraph_api/api/threads.py,sha256=xjeA6eUp4r19YYvqkfe8c3b_u4yIg6jvjq-EmlGu1kI,11150
40
40
  langgraph_api/api/ui.py,sha256=_genglTUy5BMHlL0lkQypX524yFv6Z5fraIvnrxp7yE,2639
41
41
  langgraph_api/auth/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
42
42
  langgraph_api/auth/custom.py,sha256=psETw_GpLWClBbd_ESVPRLUz9GLQ0_XNsuUDSVbtZy0,22522
@@ -75,9 +75,9 @@ langgraph_api/middleware/http_logger.py,sha256=2LABfhzTAUtqT8nf1ACy8cYXteatkwraB
75
75
  langgraph_api/middleware/private_network.py,sha256=eYgdyU8AzU2XJu362i1L8aSFoQRiV7_aLBPw7_EgeqI,2111
76
76
  langgraph_api/middleware/request_id.py,sha256=SDj3Yi3WvTbFQ2ewrPQBjAV8sYReOJGeIiuoHeZpR9g,1242
77
77
  langgraph_api/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
78
- langgraph_api/models/run.py,sha256=q99y57RqUgZgw5kNkUeezo5E9yazg-4-uxKhJR2agag,15479
78
+ langgraph_api/models/run.py,sha256=jPGWcW9fd1KFoXZTSXMMvc0IiXDXk3yoZ5kjdqxZ1mg,15536
79
79
  langgraph_api/tunneling/cloudflare.py,sha256=iKb6tj-VWPlDchHFjuQyep2Dpb-w2NGfJKt-WJG9LH0,3650
80
- langgraph_api/utils/__init__.py,sha256=kj3uCnO2Md9EEhabm331Tg4Jx9qXcxbACMh2T2P-FYw,5028
80
+ langgraph_api/utils/__init__.py,sha256=yCMq7pOMlmeNmi2Fh8U7KLiljBdOMcF0L2SfpobnKKE,5703
81
81
  langgraph_api/utils/cache.py,sha256=SrtIWYibbrNeZzLXLUGBFhJPkMVNQnVxR5giiYGHEfI,1810
82
82
  langgraph_api/utils/config.py,sha256=Tbp4tKDSLKXQJ44EKr885wAQupY-9VWNJ6rgUU2oLOY,4162
83
83
  langgraph_api/utils/future.py,sha256=lXsRQPhJwY7JUbFFZrK-94JjgsToLu-EWU896hvbUxE,7289
@@ -96,9 +96,9 @@ langgraph_runtime/retry.py,sha256=V0duD01fO7GUQ_btQkp1aoXcEOFhXooGVP6q4yMfuyY,11
96
96
  langgraph_runtime/store.py,sha256=7mowndlsIroGHv3NpTSOZDJR0lCuaYMBoTnTrewjslw,114
97
97
  LICENSE,sha256=ZPwVR73Biwm3sK6vR54djCrhaRiM4cAD2zvOQZV8Xis,3859
98
98
  logging.json,sha256=3RNjSADZmDq38eHePMm1CbP6qZ71AmpBtLwCmKU9Zgo,379
99
- openapi.json,sha256=h1LbSeGqr2Oor6vO8d3m67XJ1lHhVYVyt2ULvyhf_Ks,160215
100
- langgraph_api-0.3.4.dist-info/METADATA,sha256=L5VNuwfF9vgK-Pq3KK1AOz1E2_45tosXJlbigcHVd0Q,3890
101
- langgraph_api-0.3.4.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
102
- langgraph_api-0.3.4.dist-info/entry_points.txt,sha256=hGedv8n7cgi41PypMfinwS_HfCwA7xJIfS0jAp8htV8,78
103
- langgraph_api-0.3.4.dist-info/licenses/LICENSE,sha256=ZPwVR73Biwm3sK6vR54djCrhaRiM4cAD2zvOQZV8Xis,3859
104
- langgraph_api-0.3.4.dist-info/RECORD,,
99
+ openapi.json,sha256=kT_Xi6PAI64jLUalbdh0TtIRy1PfqQBxSu-rbyo_ZyA,162474
100
+ langgraph_api-0.4.0.dist-info/METADATA,sha256=dzjz3DMGzJSLbRmjGY7YJeL336DdeNe1_Cgcy9IYcmg,3890
101
+ langgraph_api-0.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
102
+ langgraph_api-0.4.0.dist-info/entry_points.txt,sha256=hGedv8n7cgi41PypMfinwS_HfCwA7xJIfS0jAp8htV8,78
103
+ langgraph_api-0.4.0.dist-info/licenses/LICENSE,sha256=ZPwVR73Biwm3sK6vR54djCrhaRiM4cAD2zvOQZV8Xis,3859
104
+ langgraph_api-0.4.0.dist-info/RECORD,,
openapi.json CHANGED
@@ -1520,6 +1520,73 @@
1520
1520
  }
1521
1521
  }
1522
1522
  },
1523
+ "/threads/{thread_id}/stream": {
1524
+ "get": {
1525
+ "tags": [
1526
+ "Threads"
1527
+ ],
1528
+ "summary": "Join Thread Stream",
1529
+ "description": "This endpoint streams output in real-time from a thread. The stream will include the output of each run executed sequentially on the thread and will remain open indefinitely. It is the responsibility of the calling client to close the connection.",
1530
+ "operationId": "join_thread_stream_threads__thread_id__stream_get",
1531
+ "parameters": [
1532
+ {
1533
+ "description": "The ID of the thread.",
1534
+ "required": true,
1535
+ "schema": {
1536
+ "type": "string",
1537
+ "format": "uuid",
1538
+ "title": "Thread Id",
1539
+ "description": "The ID of the thread."
1540
+ },
1541
+ "name": "thread_id",
1542
+ "in": "path"
1543
+ },
1544
+ {
1545
+ "required": false,
1546
+ "schema": {
1547
+ "type": "string",
1548
+ "title": "Last Event ID",
1549
+ "description": "The ID of the last event received. Used to resume streaming from a specific point. Pass '-' to resume from the beginning."
1550
+ },
1551
+ "name": "Last-Event-ID",
1552
+ "in": "header"
1553
+ }
1554
+ ],
1555
+ "responses": {
1556
+ "200": {
1557
+ "description": "Success",
1558
+ "content": {
1559
+ "text/event-stream": {
1560
+ "schema": {
1561
+ "type": "string",
1562
+ "description": "The server will send a stream of events in SSE format.\n\n**Example event**:\n\nid: 1\n\nevent: message\n\ndata: {}"
1563
+ }
1564
+ }
1565
+ }
1566
+ },
1567
+ "404": {
1568
+ "description": "Not Found",
1569
+ "content": {
1570
+ "application/json": {
1571
+ "schema": {
1572
+ "$ref": "#/components/schemas/ErrorResponse"
1573
+ }
1574
+ }
1575
+ }
1576
+ },
1577
+ "422": {
1578
+ "description": "Validation Error",
1579
+ "content": {
1580
+ "application/json": {
1581
+ "schema": {
1582
+ "$ref": "#/components/schemas/ErrorResponse"
1583
+ }
1584
+ }
1585
+ }
1586
+ }
1587
+ }
1588
+ }
1589
+ },
1523
1590
  "/threads/{thread_id}/runs": {
1524
1591
  "get": {
1525
1592
  "tags": [