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