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

@@ -0,0 +1,657 @@
1
+ import asyncio
2
+ import os
3
+ import shutil
4
+ from collections.abc import AsyncIterator
5
+ from typing import Any, Literal
6
+
7
+ import httpx
8
+ import orjson
9
+ import structlog
10
+ import uvicorn
11
+ from langchain_core.runnables.config import RunnableConfig
12
+ from langchain_core.runnables.graph import Edge, Node
13
+ from langchain_core.runnables.graph import Graph as DrawableGraph
14
+ from langchain_core.runnables.schema import (
15
+ CustomStreamEvent,
16
+ StandardStreamEvent,
17
+ StreamEvent,
18
+ )
19
+ from langgraph.checkpoint.serde.base import SerializerProtocol
20
+ from langgraph.pregel.types import PregelTask, StateSnapshot
21
+ from langgraph.store.base import GetOp, Item, ListNamespacesOp, PutOp, SearchOp
22
+ from langgraph.types import Command, Interrupt
23
+ from pydantic import BaseModel
24
+ from starlette.applications import Starlette
25
+ from starlette.requests import Request
26
+ from starlette.routing import Route
27
+
28
+ from langgraph_api.js.base import BaseRemotePregel
29
+ from langgraph_api.js.errors import RemoteException
30
+ from langgraph_api.js.server_sent_events import aconnect_sse
31
+ from langgraph_api.route import ApiResponse
32
+ from langgraph_api.serde import json_dumpb
33
+ from langgraph_api.utils import AsyncConnectionProto
34
+
35
+ logger = structlog.stdlib.get_logger(__name__)
36
+
37
+ GRAPH_SOCKET = "./graph.sock"
38
+ REMOTE_SOCKET = "./checkpointer.sock"
39
+
40
+
41
+ async def _client_stream(method: str, data: dict[str, Any]):
42
+ body = data.copy()
43
+ graph_id = body.get("graph_id")
44
+
45
+ # Shim for the Pregel API. Will connect to GRAPH_SOCKET
46
+ # UNIX socket to communicate with the JS process.
47
+ _async_client = httpx.AsyncClient(
48
+ base_url="http://graph",
49
+ timeout=httpx.Timeout(None),
50
+ limits=httpx.Limits(),
51
+ transport=httpx.AsyncHTTPTransport(uds=GRAPH_SOCKET),
52
+ )
53
+
54
+ async with aconnect_sse(
55
+ _async_client,
56
+ "POST",
57
+ f"/{graph_id}/{method}",
58
+ headers={"Content-Type": "application/json"},
59
+ data=orjson.dumps(body),
60
+ ) as event_source:
61
+ async for sse in event_source.aiter_sse():
62
+ event = orjson.loads(sse["data"])
63
+ if sse["event"] == "error":
64
+ raise RemoteException(event["error"], event["message"])
65
+ yield event
66
+
67
+
68
+ async def _client_invoke(method: str, data: dict[str, Any]):
69
+ body = data.copy()
70
+ graph_id = body.get("graph_id")
71
+
72
+ # Shim for the Pregel API. Will connect to GRAPH_SOCKET
73
+ # UNIX socket to communicate with the JS process.
74
+ _async_client = httpx.AsyncClient(
75
+ base_url="http://graph",
76
+ timeout=httpx.Timeout(None),
77
+ limits=httpx.Limits(),
78
+ transport=httpx.AsyncHTTPTransport(uds=GRAPH_SOCKET),
79
+ )
80
+
81
+ res = await _async_client.post(
82
+ f"/{graph_id}/{method}",
83
+ headers={"Content-Type": "application/json"},
84
+ data=orjson.dumps(body),
85
+ )
86
+ return res.json()
87
+
88
+
89
+ class RemotePregel(BaseRemotePregel):
90
+ @staticmethod
91
+ def load(graph_id: str):
92
+ model = RemotePregel()
93
+ model.graph_id = graph_id
94
+ return model
95
+
96
+ async def astream_events(
97
+ self,
98
+ input: Any,
99
+ config: RunnableConfig | None = None,
100
+ *,
101
+ version: Literal["v1", "v2"],
102
+ **kwargs: Any,
103
+ ) -> AsyncIterator[StreamEvent]:
104
+ if version != "v2":
105
+ raise ValueError("Only v2 of astream_events is supported")
106
+
107
+ data = {
108
+ "graph_id": self.graph_id,
109
+ "command" if isinstance(input, Command) else "input": input,
110
+ "config": config,
111
+ **kwargs,
112
+ }
113
+
114
+ async for event in _client_stream("streamEvents", data):
115
+ if event["event"] == "on_custom_event":
116
+ yield CustomStreamEvent(**event)
117
+ else:
118
+ yield StandardStreamEvent(**event)
119
+
120
+ async def fetch_state_schema(self):
121
+ return await _client_invoke("getSchema", {"graph_id": self.graph_id})
122
+
123
+ async def fetch_graph(
124
+ self,
125
+ config: RunnableConfig | None = None,
126
+ *,
127
+ xray: int | bool = False,
128
+ ) -> DrawableGraph:
129
+ response = await _client_invoke(
130
+ "getGraph", {"graph_id": self.graph_id, "config": config, "xray": xray}
131
+ )
132
+ print(response)
133
+
134
+ nodes: list[Any] = response.pop("nodes")
135
+ edges: list[Any] = response.pop("edges")
136
+
137
+ class NoopModel(BaseModel):
138
+ pass
139
+
140
+ return DrawableGraph(
141
+ {
142
+ data["id"]: Node(
143
+ data["id"], data["id"], NoopModel(), data.get("metadata")
144
+ )
145
+ for data in nodes
146
+ },
147
+ {
148
+ Edge(
149
+ data["source"],
150
+ data["target"],
151
+ data.get("data"),
152
+ data.get("conditional", False),
153
+ )
154
+ for data in edges
155
+ },
156
+ )
157
+
158
+ async def fetch_subgraphs(
159
+ self, *, namespace: str | None = None, recurse: bool = False
160
+ ) -> dict[str, dict]:
161
+ return await _client_invoke(
162
+ "getSubgraphs",
163
+ {"graph_id": self.graph_id, "namespace": namespace, "recurse": recurse},
164
+ )
165
+
166
+ def _convert_state_snapshot(self, item: dict) -> StateSnapshot:
167
+ def _convert_tasks(tasks: list[dict]) -> tuple[PregelTask, ...]:
168
+ result: list[PregelTask] = []
169
+ for task in tasks:
170
+ state = task.get("state")
171
+
172
+ if state and isinstance(state, dict) and "config" in state:
173
+ state = self._convert_state_snapshot(state)
174
+
175
+ result.append(
176
+ PregelTask(
177
+ task["id"],
178
+ task["name"],
179
+ tuple(task["path"]) if task.get("path") else tuple(),
180
+ # TODO: figure out how to properly deserialise errors
181
+ task.get("error"),
182
+ (
183
+ tuple(
184
+ Interrupt(
185
+ value=interrupt["value"],
186
+ when=interrupt["when"],
187
+ resumable=interrupt.get("resumable", True),
188
+ ns=interrupt.get("ns"),
189
+ )
190
+ for interrupt in task.get("interrupts")
191
+ )
192
+ if task.get("interrupts")
193
+ else []
194
+ ),
195
+ state,
196
+ )
197
+ )
198
+ return tuple(result)
199
+
200
+ return StateSnapshot(
201
+ item.get("values"),
202
+ item.get("next"),
203
+ item.get("config"),
204
+ item.get("metadata"),
205
+ item.get("createdAt"),
206
+ item.get("parentConfig"),
207
+ _convert_tasks(item.get("tasks", [])),
208
+ )
209
+
210
+ async def aget_state(
211
+ self, config: RunnableConfig, *, subgraphs: bool = False
212
+ ) -> StateSnapshot:
213
+ return self._convert_state_snapshot(
214
+ await _client_invoke(
215
+ "getState",
216
+ {"graph_id": self.graph_id, "config": config, "subgraphs": subgraphs},
217
+ )
218
+ )
219
+
220
+ async def aupdate_state(
221
+ self,
222
+ config: RunnableConfig,
223
+ values: dict[str, Any] | Any,
224
+ as_node: str | None = None,
225
+ ) -> RunnableConfig:
226
+ response = await _client_invoke(
227
+ "updateState",
228
+ {
229
+ "graph_id": self.graph_id,
230
+ "config": config,
231
+ "values": values,
232
+ "as_node": as_node,
233
+ },
234
+ )
235
+ return RunnableConfig(**response)
236
+
237
+ async def aget_state_history(
238
+ self,
239
+ config: RunnableConfig,
240
+ *,
241
+ filter: dict[str, Any] | None = None,
242
+ before: RunnableConfig | None = None,
243
+ limit: int | None = None,
244
+ ) -> AsyncIterator[StateSnapshot]:
245
+ async for event in _client_stream(
246
+ "getStateHistory",
247
+ {
248
+ "graph_id": self.graph_id,
249
+ "config": config,
250
+ "limit": limit,
251
+ "filter": filter,
252
+ "before": before,
253
+ },
254
+ ):
255
+ yield self._convert_state_snapshot(event)
256
+
257
+ def get_graph(
258
+ self,
259
+ config: RunnableConfig | None = None,
260
+ *,
261
+ xray: int | bool = False,
262
+ ) -> dict[str, Any]:
263
+ raise Exception("Not implemented")
264
+
265
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
266
+ raise Exception("Not implemented")
267
+
268
+ def get_output_schema(
269
+ self, config: RunnableConfig | None = None
270
+ ) -> type[BaseModel]:
271
+ raise Exception("Not implemented")
272
+
273
+ def config_schema(self) -> type[BaseModel]:
274
+ raise Exception("Not implemented")
275
+
276
+ async def invoke(self, input: Any, config: RunnableConfig | None = None):
277
+ raise Exception("Not implemented")
278
+
279
+
280
+ async def run_js_process(paths_str: str, watch: bool = False):
281
+ # check if tsx is available
282
+ tsx_path = shutil.which("tsx")
283
+ if tsx_path is None:
284
+ raise FileNotFoundError("tsx not found in PATH")
285
+ attempt = 0
286
+ while not asyncio.current_task().cancelled():
287
+ client_file = os.path.join(os.path.dirname(__file__), "client.mts")
288
+ args = ("tsx", client_file)
289
+ if watch:
290
+ args = ("tsx", "watch", client_file, "--skip-schema-cache")
291
+ try:
292
+ process = await asyncio.create_subprocess_exec(
293
+ *args,
294
+ env={
295
+ "LANGSERVE_GRAPHS": paths_str,
296
+ "LANGCHAIN_CALLBACKS_BACKGROUND": "true",
297
+ "CHOKIDAR_USEPOLLING": "true",
298
+ **os.environ,
299
+ },
300
+ )
301
+ code = await process.wait()
302
+ raise Exception(f"JS process exited with code {code}")
303
+ except asyncio.CancelledError:
304
+ logger.info("Terminating JS graphs process")
305
+ try:
306
+ process.terminate()
307
+ await process.wait()
308
+ except (UnboundLocalError, ProcessLookupError):
309
+ pass
310
+ raise
311
+ except Exception:
312
+ if attempt >= 3:
313
+ raise
314
+ else:
315
+ logger.warning(f"Retrying JS process {3 - attempt} more times...")
316
+ attempt += 1
317
+
318
+
319
+ def _get_passthrough_checkpointer(conn: AsyncConnectionProto):
320
+ from langgraph_storage.checkpoint import Checkpointer
321
+
322
+ class PassthroughSerialiser(SerializerProtocol):
323
+ def dumps(self, obj: Any) -> bytes:
324
+ return json_dumpb(obj)
325
+
326
+ def dumps_typed(self, obj: Any) -> tuple[str, bytes]:
327
+ return "json", json_dumpb(obj)
328
+
329
+ def loads(self, data: bytes) -> Any:
330
+ return orjson.loads(data)
331
+
332
+ def loads_typed(self, data: tuple[str, bytes]) -> Any:
333
+ type, payload = data
334
+ if type != "json":
335
+ raise ValueError(f"Unsupported type {type}")
336
+ return orjson.loads(payload)
337
+
338
+ checkpointer = Checkpointer(conn)
339
+
340
+ # This checkpointer does not attempt to revive LC-objects.
341
+ # Instead, it will pass through the JSON values as-is.
342
+ checkpointer.serde = PassthroughSerialiser()
343
+
344
+ return checkpointer
345
+
346
+
347
+ def _get_passthrough_store():
348
+ from langgraph_storage.store import Store
349
+
350
+ return Store()
351
+
352
+
353
+ # Setup a HTTP server on top of CHECKPOINTER_SOCKET unix socket
354
+ # used by `client.mts` to communicate with the Python checkpointer
355
+ async def run_remote_checkpointer():
356
+ from langgraph_storage.database import connect
357
+
358
+ async def checkpointer_list(payload: dict):
359
+ """Search checkpoints"""
360
+
361
+ result = []
362
+ async with connect() as conn:
363
+ checkpointer = _get_passthrough_checkpointer(conn)
364
+ async for item in checkpointer.alist(
365
+ config=payload.get("config"),
366
+ limit=payload.get("limit"),
367
+ before=payload.get("before"),
368
+ filter=payload.get("filter"),
369
+ ):
370
+ result.append(item)
371
+
372
+ return result
373
+
374
+ async def checkpointer_put(payload: dict):
375
+ """Put the new checkpoint metadata"""
376
+
377
+ async with connect() as conn:
378
+ checkpointer = _get_passthrough_checkpointer(conn)
379
+ return await checkpointer.aput(
380
+ payload["config"],
381
+ payload["checkpoint"],
382
+ payload["metadata"],
383
+ payload.get("new_versions", {}),
384
+ )
385
+
386
+ async def checkpointer_get_tuple(payload: dict):
387
+ """Get actual checkpoint values (reads)"""
388
+
389
+ async with connect() as conn:
390
+ checkpointer = _get_passthrough_checkpointer(conn)
391
+ return await checkpointer.aget_tuple(config=payload["config"])
392
+
393
+ async def checkpointer_put_writes(payload: dict):
394
+ """Put actual checkpoint values (writes)"""
395
+
396
+ async with connect() as conn:
397
+ checkpointer = _get_passthrough_checkpointer(conn)
398
+ return await checkpointer.aput_writes(
399
+ payload["config"],
400
+ payload["writes"],
401
+ payload["taskId"],
402
+ )
403
+
404
+ async def store_batch(payload: dict):
405
+ """Batch operations on the store"""
406
+ operations = payload.get("operations", [])
407
+
408
+ if not operations:
409
+ raise ValueError("No operations provided")
410
+
411
+ # Convert raw operations to proper objects
412
+ processed_operations = []
413
+ for op in operations:
414
+ if "value" in op:
415
+ processed_operations.append(
416
+ PutOp(
417
+ namespace=tuple(op["namespace"]),
418
+ key=op["key"],
419
+ value=op["value"],
420
+ )
421
+ )
422
+ elif "namespace_prefix" in op:
423
+ processed_operations.append(
424
+ SearchOp(
425
+ namespace_prefix=tuple(op["namespace_prefix"]),
426
+ filter=op.get("filter"),
427
+ limit=op.get("limit", 10),
428
+ offset=op.get("offset", 0),
429
+ )
430
+ )
431
+
432
+ elif "namespace" in op and "key" in op:
433
+ processed_operations.append(
434
+ GetOp(namespace=tuple(op["namespace"]), key=op["key"])
435
+ )
436
+ elif "match_conditions" in op:
437
+ processed_operations.append(
438
+ ListNamespacesOp(
439
+ match_conditions=tuple(op["match_conditions"]),
440
+ max_depth=op.get("max_depth"),
441
+ limit=op.get("limit", 100),
442
+ offset=op.get("offset", 0),
443
+ )
444
+ )
445
+ else:
446
+ raise ValueError(f"Unknown operation type: {op}")
447
+
448
+ store = _get_passthrough_store()
449
+ results = await store.abatch(processed_operations)
450
+
451
+ # Handle potentially undefined or non-dict results
452
+ processed_results = []
453
+ # Result is of type: Union[Item, list[Item], list[tuple[str, ...]], None]
454
+ for result in results:
455
+ if isinstance(result, Item):
456
+ processed_results.append(result.dict())
457
+ elif isinstance(result, dict):
458
+ processed_results.append(result)
459
+ elif isinstance(result, list):
460
+ coerced = []
461
+ for res in result:
462
+ if isinstance(res, Item):
463
+ coerced.append(res.dict())
464
+ elif isinstance(res, tuple):
465
+ coerced.append(list(res))
466
+ elif res is None:
467
+ coerced.append(res)
468
+ else:
469
+ coerced.append(str(res))
470
+ processed_results.append(coerced)
471
+ elif result is None:
472
+ processed_results.append(None)
473
+ else:
474
+ processed_results.append(str(result))
475
+ return processed_results
476
+
477
+ async def store_get(payload: dict):
478
+ """Get store data"""
479
+ namespaces_str = payload.get("namespace")
480
+ key = payload.get("key")
481
+
482
+ if not namespaces_str or not key:
483
+ raise ValueError("Both namespaces and key are required")
484
+
485
+ namespaces = namespaces_str.split(".")
486
+
487
+ store = _get_passthrough_store()
488
+ result = await store.aget(namespaces, key)
489
+
490
+ return result
491
+
492
+ async def store_put(payload: dict):
493
+ """Put the new store data"""
494
+
495
+ namespace = tuple(payload["namespace"].split("."))
496
+ key = payload["key"]
497
+ value = payload["value"]
498
+ index = payload.get("index")
499
+
500
+ store = _get_passthrough_store()
501
+ await store.aput(namespace, key, value, index=index)
502
+
503
+ return {"success": True}
504
+
505
+ async def store_search(payload: dict):
506
+ """Search stores"""
507
+ namespace_prefix = tuple(payload["namespace_prefix"])
508
+ filter = payload.get("filter")
509
+ limit = payload.get("limit", 10)
510
+ offset = payload.get("offset", 0)
511
+ query = payload.get("query")
512
+
513
+ store = _get_passthrough_store()
514
+ result = await store.asearch(
515
+ namespace_prefix, filter=filter, limit=limit, offset=offset, query=query
516
+ )
517
+
518
+ return [item.dict() for item in result]
519
+
520
+ async def store_delete(payload: dict):
521
+ """Delete store data"""
522
+
523
+ namespace = tuple(payload["namespace"])
524
+ key = payload["key"]
525
+
526
+ store = _get_passthrough_store()
527
+ await store.adelete(namespace, key)
528
+
529
+ return {"success": True}
530
+
531
+ async def store_list_namespaces(payload: dict):
532
+ """List all namespaces"""
533
+ prefix = tuple(payload.get("prefix", [])) or None
534
+ suffix = tuple(payload.get("suffix", [])) or None
535
+ max_depth = payload.get("max_depth")
536
+ limit = payload.get("limit", 100)
537
+ offset = payload.get("offset", 0)
538
+
539
+ store = _get_passthrough_store()
540
+ result = await store.alist_namespaces(
541
+ prefix=prefix,
542
+ suffix=suffix,
543
+ max_depth=max_depth,
544
+ limit=limit,
545
+ offset=offset,
546
+ )
547
+
548
+ return [list(ns) for ns in result]
549
+
550
+ def wrap_handler(cb):
551
+ async def wrapped(request: Request):
552
+ try:
553
+ payload = orjson.loads(await request.body())
554
+ return ApiResponse(await cb(payload))
555
+ except ValueError as exc:
556
+ return ApiResponse({"error": str(exc)}, status_code=400)
557
+
558
+ return wrapped
559
+
560
+ remote = Starlette(
561
+ routes=[
562
+ Route(
563
+ "/checkpointer_get_tuple",
564
+ wrap_handler(checkpointer_get_tuple),
565
+ methods=["POST"],
566
+ ),
567
+ Route(
568
+ "/checkpointer_list", wrap_handler(checkpointer_list), methods=["POST"]
569
+ ),
570
+ Route(
571
+ "/checkpointer_put", wrap_handler(checkpointer_put), methods=["POST"]
572
+ ),
573
+ Route(
574
+ "/checkpointer_put_writes",
575
+ wrap_handler(checkpointer_put_writes),
576
+ methods=["POST"],
577
+ ),
578
+ Route("/store_get", wrap_handler(store_get), methods=["POST"]),
579
+ Route("/store_put", wrap_handler(store_put), methods=["POST"]),
580
+ Route("/store_delete", wrap_handler(store_delete), methods=["POST"]),
581
+ Route("/store_search", wrap_handler(store_search), methods=["POST"]),
582
+ Route(
583
+ "/store_list_namespaces",
584
+ wrap_handler(store_list_namespaces),
585
+ methods=["POST"],
586
+ ),
587
+ Route("/store_batch", wrap_handler(store_batch), methods=["POST"]),
588
+ Route("/ok", lambda _: ApiResponse({"ok": True}), methods=["GET"]),
589
+ ]
590
+ )
591
+
592
+ server = uvicorn.Server(
593
+ uvicorn.Config(
594
+ remote,
595
+ uds=REMOTE_SOCKET,
596
+ # We need to _explicitly_ set these values in order
597
+ # to avoid reinitialising the logger, which removes
598
+ # the structlog logger setup before.
599
+ # See: https://github.com/encode/uvicorn/blob/8f4c8a7f34914c16650ebd026127b96560425fde/uvicorn/config.py#L357-L393
600
+ log_config=None,
601
+ log_level=None,
602
+ access_log=True,
603
+ )
604
+ )
605
+ await server.serve()
606
+
607
+
608
+ async def wait_until_js_ready():
609
+ async with (
610
+ httpx.AsyncClient(
611
+ base_url="http://graph",
612
+ transport=httpx.AsyncHTTPTransport(uds=GRAPH_SOCKET),
613
+ limits=httpx.Limits(),
614
+ ) as graph_client,
615
+ httpx.AsyncClient(
616
+ base_url="http://checkpointer",
617
+ transport=httpx.AsyncHTTPTransport(uds=REMOTE_SOCKET),
618
+ limits=httpx.Limits(),
619
+ ) as checkpointer_client,
620
+ ):
621
+ attempt = 0
622
+ while not asyncio.current_task().cancelled():
623
+ try:
624
+ res = await graph_client.get("/ok")
625
+ res.raise_for_status()
626
+ res = await checkpointer_client.get("/ok")
627
+ res.raise_for_status()
628
+ return
629
+ except httpx.HTTPError:
630
+ if attempt > 240:
631
+ raise
632
+ else:
633
+ attempt += 1
634
+ await asyncio.sleep(0.5)
635
+
636
+
637
+ async def js_healthcheck():
638
+ async with (
639
+ httpx.AsyncClient(
640
+ base_url="http://graph",
641
+ transport=httpx.AsyncHTTPTransport(uds=GRAPH_SOCKET),
642
+ limits=httpx.Limits(),
643
+ ) as graph_client,
644
+ httpx.AsyncClient(
645
+ base_url="http://checkpointer",
646
+ transport=httpx.AsyncHTTPTransport(uds=REMOTE_SOCKET),
647
+ limits=httpx.Limits(),
648
+ ) as checkpointer_client,
649
+ ):
650
+ try:
651
+ res = await graph_client.get("/ok")
652
+ res.raise_for_status()
653
+ res = await checkpointer_client.get("/ok")
654
+ res.raise_for_status()
655
+ return True
656
+ except httpx.HTTPError:
657
+ return False
@@ -0,0 +1,29 @@
1
+ from typing import Any, TypedDict
2
+
3
+
4
+ class RequestPayload(TypedDict):
5
+ method: str
6
+ id: str
7
+ data: dict
8
+
9
+
10
+ class ResponsePayload(TypedDict):
11
+ method: str
12
+ id: str
13
+ success: bool | None
14
+ data: Any | None
15
+
16
+
17
+ class StreamPingData(TypedDict):
18
+ method: str
19
+ id: str
20
+
21
+
22
+ class StreamData(TypedDict):
23
+ done: bool
24
+ value: Any
25
+
26
+
27
+ class ErrorData(TypedDict):
28
+ error: str
29
+ message: str
@@ -19,3 +19,10 @@ export const serialiseAsDict = (obj: unknown) => {
19
19
  2
20
20
  );
21
21
  };
22
+
23
+ export const serializeError = (error: unknown) => {
24
+ if (error instanceof Error) {
25
+ return { error: error.name, message: error.message };
26
+ }
27
+ return { error: "Error", message: JSON.stringify(error) };
28
+ };