langgraph-api 0.19.0.dev4__py3-none-any.whl → 0.19.0.dev6__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.
- langgraph_api/__init__.py +1 -1
- langgraph_api/api/a2a.py +90 -40
- langgraph_api/api/meta.py +20 -4
- langgraph_api/api/runs.py +217 -8
- langgraph_api/api/threads.py +38 -17
- langgraph_api/asgi_transport.py +5 -3
- langgraph_api/command.py +16 -1
- langgraph_api/config/__init__.py +26 -1
- langgraph_api/encryption/context.py +11 -4
- langgraph_api/errors.py +37 -0
- langgraph_api/event_streaming/capabilities.py +1 -1
- langgraph_api/event_streaming/service.py +12 -23
- langgraph_api/event_streaming/session.py +33 -2
- langgraph_api/executor/__main__.py +18 -4
- langgraph_api/feature_flags.py +5 -0
- langgraph_api/go_prometheus_metrics.py +52 -0
- langgraph_api/grpc/ops/__init__.py +3 -0
- langgraph_api/grpc/ops/runs.py +64 -28
- langgraph_api/grpc/ops/threads.py +60 -23
- langgraph_api/js/client.mts +45 -13
- langgraph_api/js/errors.py +9 -2
- langgraph_api/js/package.json +2 -2
- langgraph_api/js/remote.py +9 -1
- langgraph_api/js/src/lifecycle.mts +153 -0
- langgraph_api/js/src/utils/serde.mts +21 -0
- langgraph_api/js/yarn.lock +113 -113
- langgraph_api/lifecycle.py +276 -0
- langgraph_api/metadata.py +4 -11
- langgraph_api/metrics_collector.py +3 -1
- langgraph_api/metrics_otlp.py +13 -1
- langgraph_api/middleware/private_network.py +17 -15
- langgraph_api/models/run.py +1 -16
- langgraph_api/queue_entrypoint.py +5 -1
- langgraph_api/runtime/__init__.py +1 -0
- langgraph_api/runtime/lifespan.py +335 -0
- langgraph_api/runtime/metrics.py +26 -0
- langgraph_api/runtime/queue.py +457 -0
- langgraph_api/runtime/retry.py +87 -0
- langgraph_api/self_hosted_metrics.py +9 -3
- langgraph_api/serde.py +6 -2
- langgraph_api/server.py +14 -0
- langgraph_api/sse.py +45 -16
- langgraph_api/state.py +82 -5
- langgraph_api/stream.py +215 -43
- langgraph_api/utils/__init__.py +7 -3
- langgraph_api/validation.py +1 -0
- langgraph_api/web_identity.py +287 -0
- langgraph_api/worker.py +59 -11
- langgraph_api/worker_runtime.py +28 -0
- {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/METADATA +1 -1
- {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/RECORD +65 -56
- langgraph_grpc_common/checkpointer.py +7 -5
- langgraph_grpc_common/proto/checkpointer_pb2.py +18 -18
- langgraph_grpc_common/proto/checkpointer_pb2.pyi +9 -1
- langgraph_grpc_common/proto/core_api_pb2.py +150 -148
- langgraph_grpc_common/proto/core_api_pb2.pyi +75 -8
- langgraph_grpc_common/proto/core_api_pb2_grpc.py +44 -0
- langgraph_grpc_common/proto/core_api_pb2_grpc.pyi +12 -0
- langgraph_grpc_common/proto/orchestrator_pb2.py +4 -4
- langgraph_grpc_common/proto/orchestrator_pb2.pyi +5 -1
- langgraph_runtime/__init__.py +3 -0
- openapi.json +180 -14
- {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/WHEEL +0 -0
- {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/entry_points.txt +0 -0
- {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/licenses/LICENSE +0 -0
langgraph_api/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.19.0.
|
|
1
|
+
__version__ = "0.19.0.dev6"
|
langgraph_api/api/a2a.py
CHANGED
|
@@ -18,7 +18,7 @@ import os
|
|
|
18
18
|
import uuid
|
|
19
19
|
from dataclasses import dataclass, replace
|
|
20
20
|
from datetime import UTC, datetime
|
|
21
|
-
from typing import Any, Literal, NotRequired, Self, cast
|
|
21
|
+
from typing import TYPE_CHECKING, Any, Literal, NotRequired, Self, cast
|
|
22
22
|
|
|
23
23
|
import orjson
|
|
24
24
|
import structlog
|
|
@@ -42,6 +42,7 @@ from langgraph_api.config import (
|
|
|
42
42
|
A2A_A2UI_TOOL_CALL_RESULTS,
|
|
43
43
|
A2A_ALLOWED_TOOL_CALL_RESULTS,
|
|
44
44
|
)
|
|
45
|
+
from langgraph_api.errors import UserInterrupt, UserRollback
|
|
45
46
|
from langgraph_api.metadata import USER_API_URL
|
|
46
47
|
from langgraph_api.route import ApiRequest, ApiRoute
|
|
47
48
|
from langgraph_api.schema import RunCommand
|
|
@@ -50,6 +51,9 @@ from langgraph_api.sse import EventSourceResponse
|
|
|
50
51
|
from langgraph_api.utils.cache import LRUCache
|
|
51
52
|
from langgraph_api.utils.uuids import uuid7
|
|
52
53
|
|
|
54
|
+
if TYPE_CHECKING:
|
|
55
|
+
from langgraph_sdk.schema import RunCreateMetadata
|
|
56
|
+
|
|
53
57
|
logger = structlog.stdlib.get_logger(__name__)
|
|
54
58
|
|
|
55
59
|
# Cache for assistant schemas (assistant_id -> schemas dict)
|
|
@@ -553,6 +557,13 @@ def _lg_status_to_a2a_state(lg_status: str) -> str:
|
|
|
553
557
|
return mapping.get(lg_status, "TASK_STATE_SUBMITTED")
|
|
554
558
|
|
|
555
559
|
|
|
560
|
+
_CANCEL_ERROR_NAMES = frozenset({UserInterrupt.__name__, UserRollback.__name__})
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _is_cancel_error(error: object) -> bool:
|
|
564
|
+
return isinstance(error, dict) and error.get("error") in _CANCEL_ERROR_NAMES
|
|
565
|
+
|
|
566
|
+
|
|
556
567
|
def _task_state_for_run(
|
|
557
568
|
run: dict[str, Any], thread: dict[str, Any] | None = None
|
|
558
569
|
) -> str:
|
|
@@ -1716,7 +1727,12 @@ async def _create_task_response(
|
|
|
1716
1727
|
if history_length != 0:
|
|
1717
1728
|
base_task["history"] = thread_history
|
|
1718
1729
|
|
|
1719
|
-
if "__error__"
|
|
1730
|
+
if _is_cancel_error(result.get("__error__")):
|
|
1731
|
+
base_task["status"] = {
|
|
1732
|
+
"state": "TASK_STATE_CANCELED",
|
|
1733
|
+
"timestamp": datetime.now(UTC).isoformat(),
|
|
1734
|
+
}
|
|
1735
|
+
elif "__error__" in result:
|
|
1720
1736
|
base_task["status"] = {
|
|
1721
1737
|
"state": "TASK_STATE_FAILED",
|
|
1722
1738
|
"message": {
|
|
@@ -2296,32 +2312,37 @@ async def handle_message_send(
|
|
|
2296
2312
|
task_id=existing_task_id,
|
|
2297
2313
|
)
|
|
2298
2314
|
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
context=run_context,
|
|
2306
|
-
metadata=_a2a_run_metadata(
|
|
2307
|
-
assistant,
|
|
2308
|
-
a2ui,
|
|
2309
|
-
task_id=task_id,
|
|
2310
|
-
task_start_id=task_start_id,
|
|
2311
|
-
),
|
|
2312
|
-
if_not_exists="create",
|
|
2313
|
-
headers=request.headers,
|
|
2314
|
-
)
|
|
2315
|
-
except Exception as e:
|
|
2316
|
-
error_response = _map_runs_create_error_to_rpc(e, assistant_id, context_id)
|
|
2317
|
-
if error_response.get("error", {}).get("code") == ERROR_CODE_INTERNAL_ERROR:
|
|
2318
|
-
raise
|
|
2319
|
-
return error_response
|
|
2320
|
-
|
|
2321
|
-
context_id = str(run["thread_id"])
|
|
2322
|
-
if task_id is None:
|
|
2323
|
-
task_id = _make_task_id(context_id, str(run["run_id"]))
|
|
2315
|
+
run_metadata = _a2a_run_metadata(
|
|
2316
|
+
assistant,
|
|
2317
|
+
a2ui,
|
|
2318
|
+
task_id=task_id,
|
|
2319
|
+
task_start_id=task_start_id,
|
|
2320
|
+
)
|
|
2324
2321
|
if return_immediately:
|
|
2322
|
+
try:
|
|
2323
|
+
run = await client.runs.create(
|
|
2324
|
+
thread_id=context_id,
|
|
2325
|
+
assistant_id=assistant_id,
|
|
2326
|
+
input=input_content,
|
|
2327
|
+
command=command,
|
|
2328
|
+
context=run_context,
|
|
2329
|
+
metadata=run_metadata,
|
|
2330
|
+
if_not_exists="create",
|
|
2331
|
+
headers=request.headers,
|
|
2332
|
+
)
|
|
2333
|
+
except Exception as e:
|
|
2334
|
+
error_response = _map_runs_create_error_to_rpc(
|
|
2335
|
+
e, assistant_id, context_id
|
|
2336
|
+
)
|
|
2337
|
+
if (
|
|
2338
|
+
error_response.get("error", {}).get("code")
|
|
2339
|
+
== ERROR_CODE_INTERNAL_ERROR
|
|
2340
|
+
):
|
|
2341
|
+
raise
|
|
2342
|
+
return error_response
|
|
2343
|
+
context_id = str(run["thread_id"])
|
|
2344
|
+
if task_id is None:
|
|
2345
|
+
task_id = _make_task_id(context_id, str(run["run_id"]))
|
|
2325
2346
|
immediate_task: dict[str, Any] = {
|
|
2326
2347
|
"kind": "task",
|
|
2327
2348
|
"id": task_id,
|
|
@@ -2350,6 +2371,35 @@ async def handle_message_send(
|
|
|
2350
2371
|
)
|
|
2351
2372
|
return {"result": {"task": immediate_task}}
|
|
2352
2373
|
|
|
2374
|
+
# runs.wait subscribes to the run before creating it, so a cancel that lands
|
|
2375
|
+
# right after the run starts still reaches this call; a create followed by a
|
|
2376
|
+
# join starts listening too late and misses it.
|
|
2377
|
+
created: list[RunCreateMetadata] = []
|
|
2378
|
+
try:
|
|
2379
|
+
result = cast(
|
|
2380
|
+
"dict[str, Any]",
|
|
2381
|
+
await client.runs.wait(
|
|
2382
|
+
thread_id=context_id,
|
|
2383
|
+
assistant_id=assistant_id,
|
|
2384
|
+
input=input_content,
|
|
2385
|
+
command=command,
|
|
2386
|
+
context=run_context,
|
|
2387
|
+
metadata=run_metadata,
|
|
2388
|
+
if_not_exists="create",
|
|
2389
|
+
raise_error=False,
|
|
2390
|
+
on_run_created=created.append,
|
|
2391
|
+
headers=request.headers,
|
|
2392
|
+
),
|
|
2393
|
+
)
|
|
2394
|
+
except Exception as e:
|
|
2395
|
+
error_response = _map_runs_create_error_to_rpc(e, assistant_id, context_id)
|
|
2396
|
+
if error_response.get("error", {}).get("code") == ERROR_CODE_INTERNAL_ERROR:
|
|
2397
|
+
raise
|
|
2398
|
+
return error_response
|
|
2399
|
+
run_id = str(created[0]["run_id"])
|
|
2400
|
+
if task_id is None:
|
|
2401
|
+
task_id = _make_task_id(context_id, run_id)
|
|
2402
|
+
|
|
2353
2403
|
if existing_task_id is None:
|
|
2354
2404
|
try:
|
|
2355
2405
|
runs = await _list_context_runs(
|
|
@@ -2367,11 +2417,6 @@ async def handle_message_send(
|
|
|
2367
2417
|
if task_start_id:
|
|
2368
2418
|
task_ids_by_start_id.setdefault(task_start_id, task_id)
|
|
2369
2419
|
|
|
2370
|
-
result = await client.runs.join(
|
|
2371
|
-
thread_id=run["thread_id"],
|
|
2372
|
-
run_id=run["run_id"],
|
|
2373
|
-
headers=request.headers,
|
|
2374
|
-
)
|
|
2375
2420
|
data_only_input = command is None and "messages" not in input_content
|
|
2376
2421
|
turn = None
|
|
2377
2422
|
if data_only_input or (
|
|
@@ -2379,9 +2424,7 @@ async def handle_message_send(
|
|
|
2379
2424
|
and history_length != 0
|
|
2380
2425
|
and "messages" not in input_content
|
|
2381
2426
|
):
|
|
2382
|
-
run_messages = await _load_run_messages(
|
|
2383
|
-
context_id, str(run["run_id"]), request.headers
|
|
2384
|
-
)
|
|
2427
|
+
run_messages = await _load_run_messages(context_id, run_id, request.headers)
|
|
2385
2428
|
result = {**result, "messages": run_messages.stamped(task_id)}
|
|
2386
2429
|
if data_only_input:
|
|
2387
2430
|
turn = run_messages.added
|
|
@@ -3913,7 +3956,7 @@ async def handle_message_stream(
|
|
|
3913
3956
|
"result": update,
|
|
3914
3957
|
},
|
|
3915
3958
|
)
|
|
3916
|
-
|
|
3959
|
+
elif chunk.event != "end":
|
|
3917
3960
|
await logger.awarning(
|
|
3918
3961
|
"Ignoring unknown event type: " + chunk.event
|
|
3919
3962
|
)
|
|
@@ -3923,9 +3966,14 @@ async def handle_message_stream(
|
|
|
3923
3966
|
err = {"error": type(e).__name__, "message": str(e)}
|
|
3924
3967
|
continue
|
|
3925
3968
|
|
|
3926
|
-
#
|
|
3969
|
+
# The stream ended: report the final state from the last error or result.
|
|
3970
|
+
canceled = _is_cancel_error(err)
|
|
3927
3971
|
final_message = None
|
|
3928
|
-
if
|
|
3972
|
+
if (
|
|
3973
|
+
not canceled
|
|
3974
|
+
and isinstance(err, dict)
|
|
3975
|
+
and ("__error__" in err or "error" in err)
|
|
3976
|
+
):
|
|
3929
3977
|
msg = (
|
|
3930
3978
|
err.get("__error__", {}).get("error")
|
|
3931
3979
|
if isinstance(err.get("__error__"), dict)
|
|
@@ -3940,8 +3988,10 @@ async def handle_message_stream(
|
|
|
3940
3988
|
"taskId": task_id,
|
|
3941
3989
|
"contextId": context_id,
|
|
3942
3990
|
}
|
|
3943
|
-
# Determine final state: failed > input-required > completed
|
|
3944
|
-
if
|
|
3991
|
+
# Determine final state: canceled > failed > input-required > completed
|
|
3992
|
+
if canceled:
|
|
3993
|
+
fallback_state = "TASK_STATE_CANCELED"
|
|
3994
|
+
elif err:
|
|
3945
3995
|
fallback_state = "TASK_STATE_FAILED"
|
|
3946
3996
|
elif isinstance(result, dict) and "__interrupt__" in result:
|
|
3947
3997
|
fallback_state = "TASK_STATE_INPUT_REQUIRED"
|
langgraph_api/api/meta.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import langgraph._internal._constants as langgraph_constants
|
|
1
2
|
import langgraph.version
|
|
2
3
|
import structlog
|
|
3
4
|
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
|
@@ -6,6 +7,7 @@ from starlette.responses import JSONResponse, PlainTextResponse
|
|
|
6
7
|
from langgraph_api import __version__, config, metadata
|
|
7
8
|
from langgraph_api.api.mcp import MCP_SERVED
|
|
8
9
|
from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
|
|
10
|
+
from langgraph_api.go_prometheus_metrics import merge_go_prometheus_text
|
|
9
11
|
from langgraph_api.http_metrics import HTTP_METRICS_COLLECTOR
|
|
10
12
|
from langgraph_api.route import ApiRequest
|
|
11
13
|
from langgraph_api.schema import PoolStats, PostgresPoolStats, RedisPoolStats
|
|
@@ -13,6 +15,9 @@ from langgraph_api.tracing_session import ADDRESS_SUPPORT
|
|
|
13
15
|
from langgraph_runtime.database import connect, pool_stats
|
|
14
16
|
from langgraph_runtime.metrics import get_metrics
|
|
15
17
|
|
|
18
|
+
# A run's `strict_resume` works only on a langgraph that has the check.
|
|
19
|
+
STRICT_RESUME = hasattr(langgraph_constants, "CONFIG_KEY_STRICT_RESUME")
|
|
20
|
+
|
|
16
21
|
if IS_POSTGRES_OR_GRPC_BACKEND:
|
|
17
22
|
from langgraph_api.grpc.ops import Runs
|
|
18
23
|
else:
|
|
@@ -39,13 +44,18 @@ def _merge_pool_stats(local: PoolStats, remote: PoolStats) -> PoolStats:
|
|
|
39
44
|
if "redis" in local or "redis" in remote:
|
|
40
45
|
lr = local.get("redis") or {}
|
|
41
46
|
rr = remote.get("redis") or {}
|
|
42
|
-
|
|
47
|
+
redis_stats = RedisPoolStats(
|
|
43
48
|
idle_connections=lr.get("idle_connections", 0)
|
|
44
49
|
+ rr.get("idle_connections", 0),
|
|
45
50
|
in_use_connections=lr.get("in_use_connections", 0)
|
|
46
51
|
+ rr.get("in_use_connections", 0),
|
|
47
|
-
max_connections=lr.get("max_connections", 0) + rr.get("max_connections", 0),
|
|
48
52
|
)
|
|
53
|
+
# Cluster Go path omits max; only sum when at least one side reported it.
|
|
54
|
+
if "max_connections" in lr or "max_connections" in rr:
|
|
55
|
+
redis_stats["max_connections"] = lr.get("max_connections", 0) + rr.get(
|
|
56
|
+
"max_connections", 0
|
|
57
|
+
)
|
|
58
|
+
merged["redis"] = redis_stats
|
|
49
59
|
return merged
|
|
50
60
|
|
|
51
61
|
|
|
@@ -84,6 +94,9 @@ async def meta_info(request: ApiRequest):
|
|
|
84
94
|
"langsmith_tracing_session_on_runs": True,
|
|
85
95
|
"langsmith_tracing_address": ADDRESS_SUPPORT,
|
|
86
96
|
"mcp": MCP_SERVED,
|
|
97
|
+
"stream_namespaces": IS_POSTGRES_OR_GRPC_BACKEND,
|
|
98
|
+
"stream_lifecycle": True,
|
|
99
|
+
"strict_resume": STRICT_RESUME,
|
|
87
100
|
},
|
|
88
101
|
"host": {
|
|
89
102
|
"kind": metadata.HOST,
|
|
@@ -104,8 +117,11 @@ async def meta_metrics(request: ApiRequest):
|
|
|
104
117
|
|
|
105
118
|
if metrics_format == "prometheus":
|
|
106
119
|
# Served straight from the OTLP Prometheus client's registry (see
|
|
107
|
-
# metrics_otlp._LSDPrometheusReader).
|
|
108
|
-
|
|
120
|
+
# metrics_otlp._LSDPrometheusReader). In multi-process, Go owns queue
|
|
121
|
+
# depth / workers / run lifecycle — merge via Runs.PrometheusMetrics
|
|
122
|
+
# gRPC so scrapers (always hitting Python :8000/metrics) see them.
|
|
123
|
+
body = await merge_go_prometheus_text(generate_latest())
|
|
124
|
+
return PlainTextResponse(body, media_type=CONTENT_TYPE_LATEST)
|
|
109
125
|
|
|
110
126
|
# JSON: hand-built snapshot of workers, queue depth, HTTP, and pool stats.
|
|
111
127
|
worker_metrics = get_metrics()["workers"]
|
langgraph_api/api/runs.py
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
3
3
|
from typing import Any, Literal, cast
|
|
4
|
+
from urllib.parse import urlencode
|
|
4
5
|
from uuid import UUID
|
|
5
6
|
|
|
6
7
|
import orjson
|
|
7
8
|
import structlog
|
|
9
|
+
from starlette.datastructures import QueryParams
|
|
8
10
|
from starlette.exceptions import HTTPException
|
|
9
11
|
from starlette.responses import Response, StreamingResponse
|
|
10
12
|
|
|
11
13
|
from langgraph_api.asyncio import ValueEvent
|
|
14
|
+
from langgraph_api.errors import UserInterrupt
|
|
12
15
|
from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
|
|
13
16
|
from langgraph_api.graph import _validate_assistant_id
|
|
14
17
|
from langgraph_api.models.run import create_valid_run
|
|
@@ -16,6 +19,7 @@ from langgraph_api.route import ApiRequest, ApiResponse, ApiRoute
|
|
|
16
19
|
from langgraph_api.schema import (
|
|
17
20
|
CRON_FIELDS,
|
|
18
21
|
RUN_FIELDS,
|
|
22
|
+
Run,
|
|
19
23
|
)
|
|
20
24
|
from langgraph_api.serde import json_dumpb, json_loads
|
|
21
25
|
from langgraph_api.sse import EventSourceResponse
|
|
@@ -24,6 +28,7 @@ from langgraph_api.utils import (
|
|
|
24
28
|
get_pagination_headers,
|
|
25
29
|
uuid7,
|
|
26
30
|
validate_select_columns,
|
|
31
|
+
validate_stream_id,
|
|
27
32
|
validate_timezone,
|
|
28
33
|
validate_uuid,
|
|
29
34
|
)
|
|
@@ -75,6 +80,53 @@ def parse_stream_mode_param(stream_mode_param: str | None) -> list[str]:
|
|
|
75
80
|
return [stream_mode_param]
|
|
76
81
|
|
|
77
82
|
|
|
83
|
+
# 32 `tools:<uuid>` values keep the query near 1.8 KB, under the 8 KB many
|
|
84
|
+
# proxies allow, and the Go core's per-event check, which tries each value,
|
|
85
|
+
# under 100 ns.
|
|
86
|
+
MAX_STREAM_NAMESPACES = 32
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def parse_stream_namespaces(params: QueryParams) -> list[str]:
|
|
90
|
+
"""The ``namespace`` params: the conversations a run stream keeps.
|
|
91
|
+
|
|
92
|
+
Each is a "|"-joined namespace ("" is the root graph), kept without the
|
|
93
|
+
subagents it starts.
|
|
94
|
+
"""
|
|
95
|
+
namespaces = list(dict.fromkeys(params.getlist("namespace")))
|
|
96
|
+
if len(namespaces) > MAX_STREAM_NAMESPACES:
|
|
97
|
+
raise HTTPException(
|
|
98
|
+
status_code=422,
|
|
99
|
+
detail=f"At most {MAX_STREAM_NAMESPACES} namespace values are allowed",
|
|
100
|
+
)
|
|
101
|
+
if any(ns and "" in ns.split("|") for ns in namespaces):
|
|
102
|
+
raise HTTPException(
|
|
103
|
+
status_code=422, detail="Invalid namespace: it has an empty segment"
|
|
104
|
+
)
|
|
105
|
+
return namespaces
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def stream_namespace_query(params: QueryParams) -> str:
|
|
109
|
+
"""The ``namespace`` params as the query of a run stream's reconnect ``Location``.
|
|
110
|
+
|
|
111
|
+
A run-creating request ignores its other query params, so they must not
|
|
112
|
+
reach the join a reconnect makes.
|
|
113
|
+
"""
|
|
114
|
+
query = urlencode([("namespace", ns) for ns in params.getlist("namespace")])
|
|
115
|
+
return f"?{query}" if query else ""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def stream_namespace_kwargs(params: QueryParams) -> dict[str, list[str]]:
|
|
119
|
+
"""``Runs.Stream.join`` kwargs for the request's ``namespace`` params.
|
|
120
|
+
|
|
121
|
+
Every runtime rejects a bad value, but only the Go core filters by
|
|
122
|
+
namespace, so the Python in-memory runtime gets none and streams everything.
|
|
123
|
+
"""
|
|
124
|
+
namespaces = parse_stream_namespaces(params)
|
|
125
|
+
if not namespaces or not IS_POSTGRES_OR_GRPC_BACKEND:
|
|
126
|
+
return {}
|
|
127
|
+
return {"namespaces": namespaces}
|
|
128
|
+
|
|
129
|
+
|
|
78
130
|
# Type alias for stream handlers (GrpcStreamHandler or ContextQueue).
|
|
79
131
|
# Runs is selected at runtime, and the implementations have different
|
|
80
132
|
# type signatures, so we use Any for compatibility.
|
|
@@ -203,6 +255,102 @@ class _RunResult:
|
|
|
203
255
|
return self._interrupt_chunks[-1]
|
|
204
256
|
|
|
205
257
|
|
|
258
|
+
async def _read_ended_run(run_id: UUID, thread_id: UUID) -> Run | None:
|
|
259
|
+
async with connect() as conn:
|
|
260
|
+
try:
|
|
261
|
+
return await fetchone(
|
|
262
|
+
await Runs.get(
|
|
263
|
+
conn,
|
|
264
|
+
run_id,
|
|
265
|
+
thread_id=thread_id,
|
|
266
|
+
read_mask_paths=["status", "cancel_reason"],
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
except HTTPException as e:
|
|
270
|
+
# A rolled-back or deleted run has no ending left to report.
|
|
271
|
+
if e.status_code == 404:
|
|
272
|
+
return None
|
|
273
|
+
raise
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
async def _ended_run_error(run: Run) -> bytes | None:
|
|
277
|
+
# Only a cancel leaves a run interrupted: a graph interrupt ends the
|
|
278
|
+
# run as success and interrupts its thread instead.
|
|
279
|
+
if run["status"] == "interrupted":
|
|
280
|
+
reason = run.get("cancel_reason")
|
|
281
|
+
return json_dumpb(UserInterrupt(reason) if reason else UserInterrupt())
|
|
282
|
+
if run["status"] not in ("error", "timeout"):
|
|
283
|
+
return None
|
|
284
|
+
async with connect() as conn:
|
|
285
|
+
try:
|
|
286
|
+
# The run row has no error field, and the thread keeps only its latest
|
|
287
|
+
# failure: it's this run's only while no later run exists.
|
|
288
|
+
latest = await fetchone(
|
|
289
|
+
await Runs.search(conn, run["thread_id"], limit=1, select=["run_id"])
|
|
290
|
+
)
|
|
291
|
+
if latest["run_id"] != run["run_id"]:
|
|
292
|
+
return None
|
|
293
|
+
thread = await fetchone(
|
|
294
|
+
await Threads.get(
|
|
295
|
+
conn, run["thread_id"], read_mask_paths=["status", "error"]
|
|
296
|
+
)
|
|
297
|
+
)
|
|
298
|
+
except HTTPException as e:
|
|
299
|
+
# A deleted run has no ending left to report, and a user who may not
|
|
300
|
+
# list the thread's runs can't be told which failure is this run's.
|
|
301
|
+
if e.status_code in (403, 404):
|
|
302
|
+
return None
|
|
303
|
+
raise
|
|
304
|
+
if thread["status"] != "error":
|
|
305
|
+
return None
|
|
306
|
+
return json_dumpb(json_loads(thread["error"]))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
async def _join_with_outcome(
|
|
310
|
+
run_id: UUID, *, thread_id: UUID, end: bool = False, **join_kwargs: Any
|
|
311
|
+
) -> AsyncIterator[tuple[bytes, bytes, bytes | None]]:
|
|
312
|
+
"""`Runs.Stream.join`, ending with how the run ended when the join didn't say.
|
|
313
|
+
|
|
314
|
+
A join gets no events from a run cancelled before it started, or from a run
|
|
315
|
+
that ended before the join: without Last-Event-ID it replays nothing, and a
|
|
316
|
+
replay has nothing left once the run's events expire. Such a join ends with
|
|
317
|
+
the run's error. With `end`, a join also ends with an `end` event carrying
|
|
318
|
+
the run's final status whenever that status can be read.
|
|
319
|
+
"""
|
|
320
|
+
joined_any = ended = False
|
|
321
|
+
async for event in Runs.Stream.join(run_id, thread_id=thread_id, **join_kwargs):
|
|
322
|
+
if ended:
|
|
323
|
+
# A resume can replay `end` after the run's row is gone, and the
|
|
324
|
+
# core then reports the missing run. Keep reading instead of
|
|
325
|
+
# closing: closing early would cancel an on_disconnect=cancel run
|
|
326
|
+
# whose row still says running.
|
|
327
|
+
continue
|
|
328
|
+
ended = event[0] == b"end"
|
|
329
|
+
# `metadata` only starts an attempt and a `gap` only says events are missing,
|
|
330
|
+
# so a join that saw just those still needs the run's ending.
|
|
331
|
+
joined_any = joined_any or event[0] not in (b"metadata", b"gap")
|
|
332
|
+
yield event
|
|
333
|
+
if ended or (joined_any and not end):
|
|
334
|
+
return
|
|
335
|
+
try:
|
|
336
|
+
run = await _read_ended_run(run_id, thread_id)
|
|
337
|
+
error = None if joined_any or run is None else await _ended_run_error(run)
|
|
338
|
+
except Exception:
|
|
339
|
+
if not end:
|
|
340
|
+
raise
|
|
341
|
+
# Raising would end the stream with an error event, which reads as a
|
|
342
|
+
# failed run; without an ending, the client asks the run instead.
|
|
343
|
+
await logger.awarning(
|
|
344
|
+
"Could not read how a run ended", run_id=str(run_id), exc_info=True
|
|
345
|
+
)
|
|
346
|
+
return
|
|
347
|
+
if error:
|
|
348
|
+
yield b"error", error, None
|
|
349
|
+
if end and run is not None and run["status"] not in ("pending", "running"):
|
|
350
|
+
end_data = {"run_id": run["run_id"], "status": run["status"]}
|
|
351
|
+
yield b"end", json_dumpb(end_data), None
|
|
352
|
+
|
|
353
|
+
|
|
206
354
|
def _run_result_body(
|
|
207
355
|
*,
|
|
208
356
|
run_id: UUID,
|
|
@@ -218,7 +366,7 @@ def _run_result_body(
|
|
|
218
366
|
async def consume() -> None:
|
|
219
367
|
result = _RunResult(fallback)
|
|
220
368
|
try:
|
|
221
|
-
async for mode, chunk, _ in
|
|
369
|
+
async for mode, chunk, _ in _join_with_outcome(
|
|
222
370
|
run_id,
|
|
223
371
|
stream_channel=sub,
|
|
224
372
|
cancel_on_disconnect=cancel_on_disconnect,
|
|
@@ -327,6 +475,7 @@ async def stream_run(
|
|
|
327
475
|
"""Create a run."""
|
|
328
476
|
thread_id = request.path_params["thread_id"]
|
|
329
477
|
payload = await request.json(RunCreateStreamingStateful)
|
|
478
|
+
namespace_kwargs = stream_namespace_kwargs(request.query_params)
|
|
330
479
|
on_disconnect = payload.get("on_disconnect", "continue")
|
|
331
480
|
run_id = uuid7()
|
|
332
481
|
|
|
@@ -350,11 +499,13 @@ async def stream_run(
|
|
|
350
499
|
|
|
351
500
|
async def body():
|
|
352
501
|
try:
|
|
353
|
-
async for event, message, stream_id in
|
|
502
|
+
async for event, message, stream_id in _join_with_outcome(
|
|
354
503
|
run["run_id"],
|
|
355
504
|
thread_id=thread_id,
|
|
505
|
+
end=True,
|
|
356
506
|
cancel_on_disconnect=on_disconnect == "cancel",
|
|
357
507
|
stream_channel=cast("_StreamHandler", sub),
|
|
508
|
+
**namespace_kwargs,
|
|
358
509
|
):
|
|
359
510
|
yield event, message, stream_id
|
|
360
511
|
finally:
|
|
@@ -364,7 +515,8 @@ async def stream_run(
|
|
|
364
515
|
return EventSourceResponse(
|
|
365
516
|
body(),
|
|
366
517
|
headers={
|
|
367
|
-
"Location": f"/threads/{thread_id}/runs/{run['run_id']}/stream"
|
|
518
|
+
"Location": f"/threads/{thread_id}/runs/{run['run_id']}/stream"
|
|
519
|
+
+ stream_namespace_query(request.query_params),
|
|
368
520
|
"Content-Location": f"/threads/{thread_id}/runs/{run['run_id']}",
|
|
369
521
|
},
|
|
370
522
|
on_close=lambda: sub.__aexit__(None, None, None),
|
|
@@ -376,6 +528,7 @@ async def stream_run_stateless(
|
|
|
376
528
|
):
|
|
377
529
|
"""Create a stateless run."""
|
|
378
530
|
payload = await request.json(RunCreateStreamingStateless)
|
|
531
|
+
namespace_kwargs = stream_namespace_kwargs(request.query_params)
|
|
379
532
|
payload["if_not_exists"] = "create"
|
|
380
533
|
on_disconnect = payload.get("on_disconnect", "continue")
|
|
381
534
|
run_id = uuid7()
|
|
@@ -402,12 +555,14 @@ async def stream_run_stateless(
|
|
|
402
555
|
|
|
403
556
|
async def body():
|
|
404
557
|
try:
|
|
405
|
-
async for event, message, stream_id in
|
|
558
|
+
async for event, message, stream_id in _join_with_outcome(
|
|
406
559
|
run["run_id"],
|
|
407
560
|
thread_id=run["thread_id"],
|
|
561
|
+
end=True,
|
|
408
562
|
ignore_404=True,
|
|
409
563
|
cancel_on_disconnect=on_disconnect == "cancel",
|
|
410
564
|
stream_channel=cast("_StreamHandler", sub),
|
|
565
|
+
**namespace_kwargs,
|
|
411
566
|
):
|
|
412
567
|
yield event, message, stream_id
|
|
413
568
|
finally:
|
|
@@ -417,7 +572,8 @@ async def stream_run_stateless(
|
|
|
417
572
|
return EventSourceResponse(
|
|
418
573
|
body(),
|
|
419
574
|
headers={
|
|
420
|
-
"Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}/stream"
|
|
575
|
+
"Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}/stream"
|
|
576
|
+
+ stream_namespace_query(request.query_params),
|
|
421
577
|
"Content-Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}",
|
|
422
578
|
},
|
|
423
579
|
on_close=lambda: sub.__aexit__(None, None, None),
|
|
@@ -630,18 +786,44 @@ async def join_run_stream(request: ApiRequest):
|
|
|
630
786
|
for mode in parse_stream_mode_param(value)
|
|
631
787
|
]
|
|
632
788
|
|
|
633
|
-
|
|
789
|
+
join_kwargs: dict[str, Any] = dict(stream_namespace_kwargs(request.query_params))
|
|
790
|
+
last_event_id = validate_stream_id(
|
|
791
|
+
request.headers.get("last-event-id") or None,
|
|
792
|
+
"Invalid last-event-id: must be a valid Redis stream ID",
|
|
793
|
+
)
|
|
794
|
+
checkpoint_id = request.query_params.get("checkpoint_id")
|
|
795
|
+
# A real Last-Event-ID, sent on a reconnect, wins over checkpoint_id, which is then
|
|
796
|
+
# neither validated nor used.
|
|
797
|
+
if last_event_id not in (None, "-"):
|
|
798
|
+
checkpoint_id = None
|
|
799
|
+
elif checkpoint_id is not None:
|
|
800
|
+
checkpoint_id = validate_uuid(
|
|
801
|
+
checkpoint_id, "Invalid checkpoint_id: must be a UUID"
|
|
802
|
+
)
|
|
803
|
+
# A resume replays what the client missed from the stream's cache, which
|
|
804
|
+
# outlives a run deleted as it ends (a stateless run), so it skips this
|
|
805
|
+
# check; the join still applies the auth filters before it replays.
|
|
806
|
+
if last_event_id is None:
|
|
807
|
+
await Runs.Stream.check_run_stream_auth(run_id, thread_id)
|
|
808
|
+
if checkpoint_id:
|
|
809
|
+
# Where the checkpoint goes unused, on the in-memory runtime or a core that
|
|
810
|
+
# predates it, "-" replays the whole run instead of streaming only new events.
|
|
811
|
+
last_event_id = "-"
|
|
812
|
+
if IS_POSTGRES_OR_GRPC_BACKEND:
|
|
813
|
+
join_kwargs["checkpoint_id"] = str(checkpoint_id)
|
|
634
814
|
sub = await Runs.Stream.subscribe(run_id, thread_id)
|
|
635
815
|
|
|
636
816
|
async def body():
|
|
637
817
|
try:
|
|
638
|
-
async for event, message, stream_id in
|
|
818
|
+
async for event, message, stream_id in _join_with_outcome(
|
|
639
819
|
run_id,
|
|
640
820
|
thread_id=thread_id,
|
|
821
|
+
end=True,
|
|
641
822
|
cancel_on_disconnect=cancel_on_disconnect,
|
|
642
823
|
stream_channel=cast("_StreamHandler", sub),
|
|
643
824
|
stream_mode=stream_mode,
|
|
644
825
|
last_event_id=last_event_id,
|
|
826
|
+
**join_kwargs,
|
|
645
827
|
):
|
|
646
828
|
yield event, message, stream_id
|
|
647
829
|
finally:
|
|
@@ -662,6 +844,26 @@ async def join_run_stream(request: ApiRequest):
|
|
|
662
844
|
)
|
|
663
845
|
|
|
664
846
|
|
|
847
|
+
def _cancel_reason(
|
|
848
|
+
request: ApiRequest, action: Literal["interrupt", "rollback"]
|
|
849
|
+
) -> str:
|
|
850
|
+
path = "/threads/{thread_id}/runs/{run_id}/cancel"
|
|
851
|
+
reason = request.query_params.get("reason")
|
|
852
|
+
if reason is None:
|
|
853
|
+
return f"{action} requested via POST {path}"
|
|
854
|
+
if reason != "taken":
|
|
855
|
+
raise HTTPException(
|
|
856
|
+
status_code=422,
|
|
857
|
+
detail="Invalid cancellation reason: must be 'taken'",
|
|
858
|
+
)
|
|
859
|
+
if action != "interrupt":
|
|
860
|
+
raise HTTPException(
|
|
861
|
+
status_code=422,
|
|
862
|
+
detail="Cancellation reason 'taken' requires action 'interrupt'",
|
|
863
|
+
)
|
|
864
|
+
return f"taken: input absorbed for steering via POST {path}"
|
|
865
|
+
|
|
866
|
+
|
|
665
867
|
@retry_db
|
|
666
868
|
async def cancel_run(
|
|
667
869
|
request: ApiRequest,
|
|
@@ -679,6 +881,7 @@ async def cancel_run(
|
|
|
679
881
|
action_str if action_str in {"interrupt", "rollback"} else "interrupt",
|
|
680
882
|
)
|
|
681
883
|
|
|
884
|
+
reason = _cancel_reason(request, action)
|
|
682
885
|
sub = await Runs.Stream.subscribe(run_id, thread_id) if wait else None
|
|
683
886
|
try:
|
|
684
887
|
async with connect() as conn:
|
|
@@ -687,7 +890,7 @@ async def cancel_run(
|
|
|
687
890
|
[run_id],
|
|
688
891
|
action=action,
|
|
689
892
|
thread_id=thread_id,
|
|
690
|
-
reason=
|
|
893
|
+
reason=reason,
|
|
691
894
|
)
|
|
692
895
|
except Exception:
|
|
693
896
|
if sub is not None:
|
|
@@ -717,6 +920,12 @@ async def cancel_runs(
|
|
|
717
920
|
request: ApiRequest,
|
|
718
921
|
):
|
|
719
922
|
"""Cancel a run."""
|
|
923
|
+
if "reason" in request.query_params:
|
|
924
|
+
# A batch can partly fail without reporting which runs it cancelled.
|
|
925
|
+
raise HTTPException(
|
|
926
|
+
status_code=422,
|
|
927
|
+
detail="Cancellation reason is only supported when cancelling a single run",
|
|
928
|
+
)
|
|
720
929
|
body = await request.json(RunsCancel)
|
|
721
930
|
status = body.get("status")
|
|
722
931
|
if status:
|