codekingpro commited on
Commit
ccfb389
·
verified ·
1 Parent(s): 4c3ed59

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/user_packages/Python313/site-packages/langgraph_sdk-0.3.14.dist-info/licenses/LICENSE +21 -0
  2. python/user_packages/Python313/site-packages/langgraph_sdk/_async/__init__.py +20 -0
  3. python/user_packages/Python313/site-packages/langgraph_sdk/_async/assistants.py +733 -0
  4. python/user_packages/Python313/site-packages/langgraph_sdk/_async/client.py +178 -0
  5. python/user_packages/Python313/site-packages/langgraph_sdk/_async/cron.py +521 -0
  6. python/user_packages/Python313/site-packages/langgraph_sdk/_async/http.py +312 -0
  7. python/user_packages/Python313/site-packages/langgraph_sdk/_async/runs.py +1181 -0
  8. python/user_packages/Python313/site-packages/langgraph_sdk/_async/store.py +313 -0
  9. python/user_packages/Python313/site-packages/langgraph_sdk/_async/threads.py +773 -0
  10. python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__init__.py +1 -0
  11. python/user_packages/Python313/site-packages/langgraph_sdk/_shared/types.py +10 -0
  12. python/user_packages/Python313/site-packages/langgraph_sdk/_shared/utilities.py +217 -0
  13. python/user_packages/Python313/site-packages/langgraph_sdk/_sync/assistants.py +731 -0
  14. python/user_packages/Python313/site-packages/langgraph_sdk/auth/__init__.py +876 -0
  15. python/user_packages/Python313/site-packages/langgraph_sdk/auth/exceptions.py +59 -0
  16. python/user_packages/Python313/site-packages/langgraph_sdk/auth/types.py +1162 -0
  17. python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__init__.py +466 -0
  18. python/user_packages/Python313/site-packages/langgraph_sdk/encryption/types.py +147 -0
  19. python/user_packages/Python313/site-packages/langsmith/__pycache__/__init__.cpython-313.pyc +0 -0
  20. python/user_packages/Python313/site-packages/langsmith/__pycache__/_expect.cpython-313.pyc +0 -0
  21. python/user_packages/Python313/site-packages/langsmith/__pycache__/_runtime_overrides.cpython-313.pyc +0 -0
  22. python/user_packages/Python313/site-packages/langsmith/__pycache__/anonymizer.cpython-313.pyc +0 -0
  23. python/user_packages/Python313/site-packages/langsmith/__pycache__/middleware.cpython-313.pyc +0 -0
  24. python/user_packages/Python313/site-packages/langsmith/__pycache__/prompt_cache.cpython-313.pyc +0 -0
  25. python/user_packages/Python313/site-packages/langsmith/__pycache__/pytest_plugin.cpython-313.pyc +0 -0
  26. python/user_packages/Python313/site-packages/langsmith/__pycache__/run_helpers.cpython-313.pyc +0 -0
  27. python/user_packages/Python313/site-packages/langsmith/__pycache__/run_trees.cpython-313.pyc +0 -0
  28. python/user_packages/Python313/site-packages/langsmith/__pycache__/schemas.cpython-313.pyc +0 -0
  29. python/user_packages/Python313/site-packages/langsmith/__pycache__/utils.cpython-313.pyc +0 -0
  30. python/user_packages/Python313/site-packages/langsmith/__pycache__/uuid.cpython-313.pyc +0 -0
  31. python/user_packages/Python313/site-packages/langsmith/_internal/__init__.py +0 -0
  32. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/__init__.cpython-313.pyc +0 -0
  33. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_aiter.cpython-313.pyc +0 -0
  34. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_background_thread.cpython-313.pyc +0 -0
  35. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_beta_decorator.cpython-313.pyc +0 -0
  36. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_compressed_traces.cpython-313.pyc +0 -0
  37. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_constants.cpython-313.pyc +0 -0
  38. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_context.cpython-313.pyc +0 -0
  39. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_edit_distance.cpython-313.pyc +0 -0
  40. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_embedding_distance.cpython-313.pyc +0 -0
  41. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_hub.cpython-313.pyc +0 -0
  42. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_multipart.cpython-313.pyc +0 -0
  43. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_operations.cpython-313.pyc +0 -0
  44. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_orjson.cpython-313.pyc +0 -0
  45. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_otel_utils.cpython-313.pyc +0 -0
  46. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_patch.cpython-313.pyc +0 -0
  47. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_profiles.cpython-313.pyc +0 -0
  48. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_serde.cpython-313.pyc +0 -0
  49. python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_uuid.cpython-313.pyc +0 -0
  50. python/user_packages/Python313/site-packages/langsmith/_internal/_aiter.py +382 -0
python/user_packages/Python313/site-packages/langgraph_sdk-0.3.14.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 LangChain, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
python/user_packages/Python313/site-packages/langgraph_sdk/_async/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client exports."""
2
+
3
+ from langgraph_sdk._async.assistants import AssistantsClient
4
+ from langgraph_sdk._async.client import LangGraphClient, get_client
5
+ from langgraph_sdk._async.cron import CronClient
6
+ from langgraph_sdk._async.http import HttpClient
7
+ from langgraph_sdk._async.runs import RunsClient
8
+ from langgraph_sdk._async.store import StoreClient
9
+ from langgraph_sdk._async.threads import ThreadsClient
10
+
11
+ __all__ = [
12
+ "AssistantsClient",
13
+ "CronClient",
14
+ "HttpClient",
15
+ "LangGraphClient",
16
+ "RunsClient",
17
+ "StoreClient",
18
+ "ThreadsClient",
19
+ "get_client",
20
+ ]
python/user_packages/Python313/site-packages/langgraph_sdk/_async/assistants.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client for managing assistants in LangGraph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, Literal, cast, overload
7
+
8
+ import httpx
9
+
10
+ from langgraph_sdk._async.http import HttpClient
11
+ from langgraph_sdk.schema import (
12
+ Assistant,
13
+ AssistantSelectField,
14
+ AssistantSortBy,
15
+ AssistantsSearchResponse,
16
+ AssistantVersion,
17
+ Config,
18
+ Context,
19
+ GraphSchema,
20
+ Json,
21
+ OnConflictBehavior,
22
+ QueryParamTypes,
23
+ SortOrder,
24
+ Subgraphs,
25
+ )
26
+
27
+
28
+ class AssistantsClient:
29
+ """Client for managing assistants in LangGraph.
30
+
31
+ This class provides methods to interact with assistants,
32
+ which are versioned configurations of your graph.
33
+
34
+ ???+ example "Example"
35
+
36
+ ```python
37
+ client = get_client(url="http://localhost:2024")
38
+ assistant = await client.assistants.get("assistant_id_123")
39
+ ```
40
+ """
41
+
42
+ def __init__(self, http: HttpClient) -> None:
43
+ self.http = http
44
+
45
+ async def get(
46
+ self,
47
+ assistant_id: str,
48
+ *,
49
+ headers: Mapping[str, str] | None = None,
50
+ params: QueryParamTypes | None = None,
51
+ ) -> Assistant:
52
+ """Get an assistant by ID.
53
+
54
+ Args:
55
+ assistant_id: The ID of the assistant to get.
56
+ headers: Optional custom headers to include with the request.
57
+ params: Optional query parameters to include with the request.
58
+
59
+ Returns:
60
+ Assistant: Assistant Object.
61
+
62
+ ???+ example "Example Usage"
63
+
64
+ ```python
65
+ assistant = await client.assistants.get(
66
+ assistant_id="my_assistant_id"
67
+ )
68
+ print(assistant)
69
+ ```
70
+
71
+ ```shell
72
+ ----------------------------------------------------
73
+
74
+ {
75
+ 'assistant_id': 'my_assistant_id',
76
+ 'graph_id': 'agent',
77
+ 'created_at': '2024-06-25T17:10:33.109781+00:00',
78
+ 'updated_at': '2024-06-25T17:10:33.109781+00:00',
79
+ 'config': {},
80
+ 'metadata': {'created_by': 'system'},
81
+ 'version': 1,
82
+ 'name': 'my_assistant'
83
+ }
84
+ ```
85
+ """
86
+ return await self.http.get(
87
+ f"/assistants/{assistant_id}", headers=headers, params=params
88
+ )
89
+
90
+ async def get_graph(
91
+ self,
92
+ assistant_id: str,
93
+ *,
94
+ xray: int | bool = False,
95
+ headers: Mapping[str, str] | None = None,
96
+ params: QueryParamTypes | None = None,
97
+ ) -> dict[str, list[dict[str, Any]]]:
98
+ """Get the graph of an assistant by ID.
99
+
100
+ Args:
101
+ assistant_id: The ID of the assistant to get the graph of.
102
+ xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
103
+ headers: Optional custom headers to include with the request.
104
+ params: Optional query parameters to include with the request.
105
+
106
+ Returns:
107
+ Graph: The graph information for the assistant in JSON format.
108
+
109
+ ???+ example "Example Usage"
110
+
111
+ ```python
112
+ client = get_client(url="http://localhost:2024")
113
+ graph_info = await client.assistants.get_graph(
114
+ assistant_id="my_assistant_id"
115
+ )
116
+ print(graph_info)
117
+ ```
118
+
119
+ ```shell
120
+
121
+ --------------------------------------------------------------------------------------------------------------------------
122
+
123
+ {
124
+ 'nodes':
125
+ [
126
+ {'id': '__start__', 'type': 'schema', 'data': '__start__'},
127
+ {'id': '__end__', 'type': 'schema', 'data': '__end__'},
128
+ {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
129
+ ],
130
+ 'edges':
131
+ [
132
+ {'source': '__start__', 'target': 'agent'},
133
+ {'source': 'agent','target': '__end__'}
134
+ ]
135
+ }
136
+ ```
137
+
138
+
139
+ """
140
+ query_params = {"xray": xray}
141
+ if params:
142
+ query_params.update(params)
143
+
144
+ return await self.http.get(
145
+ f"/assistants/{assistant_id}/graph", params=query_params, headers=headers
146
+ )
147
+
148
+ async def get_schemas(
149
+ self,
150
+ assistant_id: str,
151
+ *,
152
+ headers: Mapping[str, str] | None = None,
153
+ params: QueryParamTypes | None = None,
154
+ ) -> GraphSchema:
155
+ """Get the schemas of an assistant by ID.
156
+
157
+ Args:
158
+ assistant_id: The ID of the assistant to get the schema of.
159
+ headers: Optional custom headers to include with the request.
160
+ params: Optional query parameters to include with the request.
161
+
162
+ Returns:
163
+ GraphSchema: The graph schema for the assistant.
164
+
165
+ ???+ example "Example Usage"
166
+
167
+ ```python
168
+ client = get_client(url="http://localhost:2024")
169
+ schema = await client.assistants.get_schemas(
170
+ assistant_id="my_assistant_id"
171
+ )
172
+ print(schema)
173
+ ```
174
+
175
+ ```shell
176
+
177
+ ----------------------------------------------------------------------------------------------------------------------------
178
+
179
+ {
180
+ 'graph_id': 'agent',
181
+ 'state_schema':
182
+ {
183
+ 'title': 'LangGraphInput',
184
+ '$ref': '#/definitions/AgentState',
185
+ 'definitions':
186
+ {
187
+ 'BaseMessage':
188
+ {
189
+ 'title': 'BaseMessage',
190
+ 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
191
+ 'type': 'object',
192
+ 'properties':
193
+ {
194
+ 'content':
195
+ {
196
+ 'title': 'Content',
197
+ 'anyOf': [
198
+ {'type': 'string'},
199
+ {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
200
+ ]
201
+ },
202
+ 'additional_kwargs':
203
+ {
204
+ 'title': 'Additional Kwargs',
205
+ 'type': 'object'
206
+ },
207
+ 'response_metadata':
208
+ {
209
+ 'title': 'Response Metadata',
210
+ 'type': 'object'
211
+ },
212
+ 'type':
213
+ {
214
+ 'title': 'Type',
215
+ 'type': 'string'
216
+ },
217
+ 'name':
218
+ {
219
+ 'title': 'Name',
220
+ 'type': 'string'
221
+ },
222
+ 'id':
223
+ {
224
+ 'title': 'Id',
225
+ 'type': 'string'
226
+ }
227
+ },
228
+ 'required': ['content', 'type']
229
+ },
230
+ 'AgentState':
231
+ {
232
+ 'title': 'AgentState',
233
+ 'type': 'object',
234
+ 'properties':
235
+ {
236
+ 'messages':
237
+ {
238
+ 'title': 'Messages',
239
+ 'type': 'array',
240
+ 'items': {'$ref': '#/definitions/BaseMessage'}
241
+ }
242
+ },
243
+ 'required': ['messages']
244
+ }
245
+ }
246
+ },
247
+ 'context_schema':
248
+ {
249
+ 'title': 'Context',
250
+ 'type': 'object',
251
+ 'properties':
252
+ {
253
+ 'model_name':
254
+ {
255
+ 'title': 'Model Name',
256
+ 'enum': ['anthropic', 'openai'],
257
+ 'type': 'string'
258
+ }
259
+ }
260
+ }
261
+ }
262
+ ```
263
+
264
+ """
265
+ return await self.http.get(
266
+ f"/assistants/{assistant_id}/schemas", headers=headers, params=params
267
+ )
268
+
269
+ async def get_subgraphs(
270
+ self,
271
+ assistant_id: str,
272
+ namespace: str | None = None,
273
+ recurse: bool = False,
274
+ *,
275
+ headers: Mapping[str, str] | None = None,
276
+ params: QueryParamTypes | None = None,
277
+ ) -> Subgraphs:
278
+ """Get the schemas of an assistant by ID.
279
+
280
+ Args:
281
+ assistant_id: The ID of the assistant to get the schema of.
282
+ namespace: Optional namespace to filter by.
283
+ recurse: Whether to recursively get subgraphs.
284
+ headers: Optional custom headers to include with the request.
285
+ params: Optional query parameters to include with the request.
286
+
287
+ Returns:
288
+ Subgraphs: The graph schema for the assistant.
289
+
290
+ """
291
+ get_params = {"recurse": recurse}
292
+ if params:
293
+ get_params = {**get_params, **dict(params)}
294
+ if namespace is not None:
295
+ return await self.http.get(
296
+ f"/assistants/{assistant_id}/subgraphs/{namespace}",
297
+ params=get_params,
298
+ headers=headers,
299
+ )
300
+ else:
301
+ return await self.http.get(
302
+ f"/assistants/{assistant_id}/subgraphs",
303
+ params=get_params,
304
+ headers=headers,
305
+ )
306
+
307
+ async def create(
308
+ self,
309
+ graph_id: str | None,
310
+ config: Config | None = None,
311
+ *,
312
+ context: Context | None = None,
313
+ metadata: Json = None,
314
+ assistant_id: str | None = None,
315
+ if_exists: OnConflictBehavior | None = None,
316
+ name: str | None = None,
317
+ headers: Mapping[str, str] | None = None,
318
+ description: str | None = None,
319
+ params: QueryParamTypes | None = None,
320
+ ) -> Assistant:
321
+ """Create a new assistant.
322
+
323
+ Useful when graph is configurable and you want to create different assistants based on different configurations.
324
+
325
+ Args:
326
+ graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
327
+ config: Configuration to use for the graph.
328
+ metadata: Metadata to add to assistant.
329
+ context: Static context to add to the assistant.
330
+ !!! version-added "Added in version 0.6.0"
331
+ assistant_id: Assistant ID to use, will default to a random UUID if not provided.
332
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
333
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
334
+ name: The name of the assistant. Defaults to 'Untitled' under the hood.
335
+ headers: Optional custom headers to include with the request.
336
+ description: Optional description of the assistant.
337
+ The description field is available for langgraph-api server version>=0.0.45
338
+ params: Optional query parameters to include with the request.
339
+
340
+ Returns:
341
+ Assistant: The created assistant.
342
+
343
+ ???+ example "Example Usage"
344
+
345
+ ```python
346
+ client = get_client(url="http://localhost:2024")
347
+ assistant = await client.assistants.create(
348
+ graph_id="agent",
349
+ context={"model_name": "openai"},
350
+ metadata={"number":1},
351
+ assistant_id="my-assistant-id",
352
+ if_exists="do_nothing",
353
+ name="my_name"
354
+ )
355
+ ```
356
+ """
357
+ payload: dict[str, Any] = {
358
+ "graph_id": graph_id,
359
+ }
360
+ if config:
361
+ payload["config"] = config
362
+ if context:
363
+ payload["context"] = context
364
+ if metadata:
365
+ payload["metadata"] = metadata
366
+ if assistant_id:
367
+ payload["assistant_id"] = assistant_id
368
+ if if_exists:
369
+ payload["if_exists"] = if_exists
370
+ if name:
371
+ payload["name"] = name
372
+ if description:
373
+ payload["description"] = description
374
+ return await self.http.post(
375
+ "/assistants", json=payload, headers=headers, params=params
376
+ )
377
+
378
+ async def update(
379
+ self,
380
+ assistant_id: str,
381
+ *,
382
+ graph_id: str | None = None,
383
+ config: Config | None = None,
384
+ context: Context | None = None,
385
+ metadata: Json = None,
386
+ name: str | None = None,
387
+ headers: Mapping[str, str] | None = None,
388
+ description: str | None = None,
389
+ params: QueryParamTypes | None = None,
390
+ ) -> Assistant:
391
+ """Update an assistant.
392
+
393
+ Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
394
+
395
+ Args:
396
+ assistant_id: Assistant to update.
397
+ graph_id: The ID of the graph the assistant should use.
398
+ The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
399
+ config: Configuration to use for the graph.
400
+ context: Static context to add to the assistant.
401
+ !!! version-added "Added in version 0.6.0"
402
+ metadata: Metadata to merge with existing assistant metadata.
403
+ name: The new name for the assistant.
404
+ headers: Optional custom headers to include with the request.
405
+ description: Optional description of the assistant.
406
+ The description field is available for langgraph-api server version>=0.0.45
407
+ params: Optional query parameters to include with the request.
408
+
409
+ Returns:
410
+ The updated assistant.
411
+
412
+ ???+ example "Example Usage"
413
+
414
+ ```python
415
+ client = get_client(url="http://localhost:2024")
416
+ assistant = await client.assistants.update(
417
+ assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
418
+ graph_id="other-graph",
419
+ context={"model_name": "anthropic"},
420
+ metadata={"number":2}
421
+ )
422
+ ```
423
+
424
+ """
425
+ payload: dict[str, Any] = {}
426
+ if graph_id:
427
+ payload["graph_id"] = graph_id
428
+ if config is not None:
429
+ payload["config"] = config
430
+ if context is not None:
431
+ payload["context"] = context
432
+ if metadata:
433
+ payload["metadata"] = metadata
434
+ if name:
435
+ payload["name"] = name
436
+ if description:
437
+ payload["description"] = description
438
+ return await self.http.patch(
439
+ f"/assistants/{assistant_id}",
440
+ json=payload,
441
+ headers=headers,
442
+ params=params,
443
+ )
444
+
445
+ async def delete(
446
+ self,
447
+ assistant_id: str,
448
+ *,
449
+ delete_threads: bool = False,
450
+ headers: Mapping[str, str] | None = None,
451
+ params: QueryParamTypes | None = None,
452
+ ) -> None:
453
+ """Delete an assistant.
454
+
455
+ Args:
456
+ assistant_id: The assistant ID to delete.
457
+ delete_threads: If true, delete all threads with `metadata.assistant_id`
458
+ matching this assistant, along with runs and checkpoints belonging to
459
+ those threads.
460
+ headers: Optional custom headers to include with the request.
461
+ params: Optional query parameters to include with the request.
462
+
463
+ Returns:
464
+ `None`
465
+
466
+ ???+ example "Example Usage"
467
+
468
+ ```python
469
+ client = get_client(url="http://localhost:2024")
470
+ await client.assistants.delete(
471
+ assistant_id="my_assistant_id"
472
+ )
473
+ ```
474
+
475
+ """
476
+ query_params: dict[str, Any] = {}
477
+ if delete_threads:
478
+ query_params["delete_threads"] = True
479
+ if params:
480
+ query_params.update(params)
481
+ await self.http.delete(
482
+ f"/assistants/{assistant_id}",
483
+ headers=headers,
484
+ params=query_params or None,
485
+ )
486
+
487
+ @overload
488
+ async def search(
489
+ self,
490
+ *,
491
+ metadata: Json = None,
492
+ graph_id: str | None = None,
493
+ name: str | None = None,
494
+ limit: int = 10,
495
+ offset: int = 0,
496
+ sort_by: AssistantSortBy | None = None,
497
+ sort_order: SortOrder | None = None,
498
+ select: list[AssistantSelectField] | None = None,
499
+ response_format: Literal["object"],
500
+ headers: Mapping[str, str] | None = None,
501
+ params: QueryParamTypes | None = None,
502
+ ) -> AssistantsSearchResponse: ...
503
+
504
+ @overload
505
+ async def search(
506
+ self,
507
+ *,
508
+ metadata: Json = None,
509
+ graph_id: str | None = None,
510
+ name: str | None = None,
511
+ limit: int = 10,
512
+ offset: int = 0,
513
+ sort_by: AssistantSortBy | None = None,
514
+ sort_order: SortOrder | None = None,
515
+ select: list[AssistantSelectField] | None = None,
516
+ response_format: Literal["array"] = "array",
517
+ headers: Mapping[str, str] | None = None,
518
+ params: QueryParamTypes | None = None,
519
+ ) -> list[Assistant]: ...
520
+
521
+ async def search(
522
+ self,
523
+ *,
524
+ metadata: Json = None,
525
+ graph_id: str | None = None,
526
+ name: str | None = None,
527
+ limit: int = 10,
528
+ offset: int = 0,
529
+ sort_by: AssistantSortBy | None = None,
530
+ sort_order: SortOrder | None = None,
531
+ select: list[AssistantSelectField] | None = None,
532
+ response_format: Literal["array", "object"] = "array",
533
+ headers: Mapping[str, str] | None = None,
534
+ params: QueryParamTypes | None = None,
535
+ ) -> AssistantsSearchResponse | list[Assistant]:
536
+ """Search for assistants.
537
+
538
+ Args:
539
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
540
+ graph_id: The ID of the graph to filter by.
541
+ The graph ID is normally set in your langgraph.json configuration.
542
+ name: The name of the assistant to filter by.
543
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
544
+ limit: The maximum number of results to return.
545
+ offset: The number of results to skip.
546
+ sort_by: The field to sort by.
547
+ sort_order: The order to sort by.
548
+ select: Specific assistant fields to include in the response.
549
+ response_format: Controls the response shape. Use `"array"` (default)
550
+ to return a bare list of assistants, or `"object"` to return
551
+ a mapping containing assistants plus pagination metadata.
552
+ Defaults to "array", though this default will be changed to "object" in a future release.
553
+ headers: Optional custom headers to include with the request.
554
+ params: Optional query parameters to include with the request.
555
+
556
+ Returns:
557
+ A list of assistants (when `response_format="array"`) or a mapping
558
+ with the assistants and the next pagination cursor (when
559
+ `response_format="object"`).
560
+
561
+ ???+ example "Example Usage"
562
+
563
+ ```python
564
+ client = get_client(url="http://localhost:2024")
565
+ response = await client.assistants.search(
566
+ metadata = {"name":"my_name"},
567
+ graph_id="my_graph_id",
568
+ limit=5,
569
+ offset=5,
570
+ response_format="object"
571
+ )
572
+ next_cursor = response["next"]
573
+ assistants = response["assistants"]
574
+ ```
575
+ """
576
+ if response_format not in ("array", "object"):
577
+ raise ValueError(
578
+ f"response_format must be 'array' or 'object', got {response_format!r}"
579
+ )
580
+ payload: dict[str, Any] = {
581
+ "limit": limit,
582
+ "offset": offset,
583
+ }
584
+ if metadata:
585
+ payload["metadata"] = metadata
586
+ if graph_id:
587
+ payload["graph_id"] = graph_id
588
+ if name:
589
+ payload["name"] = name
590
+ if sort_by:
591
+ payload["sort_by"] = sort_by
592
+ if sort_order:
593
+ payload["sort_order"] = sort_order
594
+ if select:
595
+ payload["select"] = select
596
+ next_cursor: str | None = None
597
+
598
+ def capture_pagination(response: httpx.Response) -> None:
599
+ nonlocal next_cursor
600
+ next_cursor = response.headers.get("X-Pagination-Next")
601
+
602
+ assistants = cast(
603
+ list[Assistant],
604
+ await self.http.post(
605
+ "/assistants/search",
606
+ json=payload,
607
+ headers=headers,
608
+ params=params,
609
+ on_response=capture_pagination if response_format == "object" else None,
610
+ ),
611
+ )
612
+ if response_format == "object":
613
+ return {"assistants": assistants, "next": next_cursor}
614
+ return assistants
615
+
616
+ async def count(
617
+ self,
618
+ *,
619
+ metadata: Json = None,
620
+ graph_id: str | None = None,
621
+ name: str | None = None,
622
+ headers: Mapping[str, str] | None = None,
623
+ params: QueryParamTypes | None = None,
624
+ ) -> int:
625
+ """Count assistants matching filters.
626
+
627
+ Args:
628
+ metadata: Metadata to filter by. Exact match for each key/value.
629
+ graph_id: Optional graph id to filter by.
630
+ name: Optional name to filter by.
631
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
632
+ headers: Optional custom headers to include with the request.
633
+ params: Optional query parameters to include with the request.
634
+
635
+ Returns:
636
+ int: Number of assistants matching the criteria.
637
+ """
638
+ payload: dict[str, Any] = {}
639
+ if metadata:
640
+ payload["metadata"] = metadata
641
+ if graph_id:
642
+ payload["graph_id"] = graph_id
643
+ if name:
644
+ payload["name"] = name
645
+ return await self.http.post(
646
+ "/assistants/count", json=payload, headers=headers, params=params
647
+ )
648
+
649
+ async def get_versions(
650
+ self,
651
+ assistant_id: str,
652
+ metadata: Json = None,
653
+ limit: int = 10,
654
+ offset: int = 0,
655
+ *,
656
+ headers: Mapping[str, str] | None = None,
657
+ params: QueryParamTypes | None = None,
658
+ ) -> list[AssistantVersion]:
659
+ """List all versions of an assistant.
660
+
661
+ Args:
662
+ assistant_id: The assistant ID to get versions for.
663
+ metadata: Metadata to filter versions by. Exact match filter for each KV pair.
664
+ limit: The maximum number of versions to return.
665
+ offset: The number of versions to skip.
666
+ headers: Optional custom headers to include with the request.
667
+ params: Optional query parameters to include with the request.
668
+
669
+ Returns:
670
+ A list of assistant versions.
671
+
672
+ ???+ example "Example Usage"
673
+
674
+ ```python
675
+ client = get_client(url="http://localhost:2024")
676
+ assistant_versions = await client.assistants.get_versions(
677
+ assistant_id="my_assistant_id"
678
+ )
679
+ ```
680
+ """
681
+
682
+ payload: dict[str, Any] = {
683
+ "limit": limit,
684
+ "offset": offset,
685
+ }
686
+ if metadata:
687
+ payload["metadata"] = metadata
688
+ return await self.http.post(
689
+ f"/assistants/{assistant_id}/versions",
690
+ json=payload,
691
+ headers=headers,
692
+ params=params,
693
+ )
694
+
695
+ async def set_latest(
696
+ self,
697
+ assistant_id: str,
698
+ version: int,
699
+ *,
700
+ headers: Mapping[str, str] | None = None,
701
+ params: QueryParamTypes | None = None,
702
+ ) -> Assistant:
703
+ """Change the version of an assistant.
704
+
705
+ Args:
706
+ assistant_id: The assistant ID to delete.
707
+ version: The version to change to.
708
+ headers: Optional custom headers to include with the request.
709
+ params: Optional query parameters to include with the request.
710
+
711
+ Returns:
712
+ Assistant Object.
713
+
714
+ ???+ example "Example Usage"
715
+
716
+ ```python
717
+ client = get_client(url="http://localhost:2024")
718
+ new_version_assistant = await client.assistants.set_latest(
719
+ assistant_id="my_assistant_id",
720
+ version=3
721
+ )
722
+ ```
723
+
724
+ """
725
+
726
+ payload: dict[str, Any] = {"version": version}
727
+
728
+ return await self.http.post(
729
+ f"/assistants/{assistant_id}/latest",
730
+ json=payload,
731
+ headers=headers,
732
+ params=params,
733
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_async/client.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async LangGraph client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from collections.abc import Mapping
8
+ from types import TracebackType
9
+
10
+ import httpx
11
+
12
+ from langgraph_sdk._async.assistants import AssistantsClient
13
+ from langgraph_sdk._async.cron import CronClient
14
+ from langgraph_sdk._async.http import HttpClient
15
+ from langgraph_sdk._async.runs import RunsClient
16
+ from langgraph_sdk._async.store import StoreClient
17
+ from langgraph_sdk._async.threads import ThreadsClient
18
+ from langgraph_sdk._shared.types import TimeoutTypes
19
+ from langgraph_sdk._shared.utilities import (
20
+ NOT_PROVIDED,
21
+ _get_headers,
22
+ _registered_transports,
23
+ get_asgi_transport,
24
+ )
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def get_client(
30
+ *,
31
+ url: str | None = None,
32
+ api_key: str | None = NOT_PROVIDED,
33
+ headers: Mapping[str, str] | None = None,
34
+ timeout: TimeoutTypes | None = None,
35
+ ) -> LangGraphClient:
36
+ """Create and configure a LangGraphClient.
37
+
38
+ The client provides programmatic access to LangSmith Deployment. It supports
39
+ both remote servers and local in-process connections (when running inside a LangGraph server).
40
+
41
+ Args:
42
+ url:
43
+ Base URL of the LangGraph API.
44
+ - If `None`, the client first attempts an in-process connection via ASGI transport.
45
+ If that fails, it defers registration until after app initialization. This
46
+ only works if the client is used from within the Agent server.
47
+ api_key:
48
+ API key for authentication. Can be:
49
+ - A string: use this exact API key
50
+ - `None`: explicitly skip loading from environment variables
51
+ - Not provided (default): auto-load from environment in this order:
52
+ 1. `LANGGRAPH_API_KEY`
53
+ 2. `LANGSMITH_API_KEY`
54
+ 3. `LANGCHAIN_API_KEY`
55
+ headers:
56
+ Additional HTTP headers to include in requests. Merged with authentication headers.
57
+ timeout:
58
+ HTTP timeout configuration. May be:
59
+ - `httpx.Timeout` instance
60
+ - float (total seconds)
61
+ - tuple `(connect, read, write, pool)` in seconds
62
+ Defaults: connect=5, read=300, write=300, pool=5.
63
+
64
+ Returns:
65
+ LangGraphClient:
66
+ A top-level client exposing sub-clients for assistants, threads,
67
+ runs, and cron operations.
68
+
69
+ ???+ example "Connect to a remote server:"
70
+
71
+ ```python
72
+ from langgraph_sdk import get_client
73
+
74
+ # get top-level LangGraphClient
75
+ client = get_client(url="http://localhost:8123")
76
+
77
+ # example usage: client.<model>.<method_name>()
78
+ assistants = await client.assistants.get(assistant_id="some_uuid")
79
+ ```
80
+
81
+ ???+ example "Connect in-process to a running LangGraph server:"
82
+
83
+ ```python
84
+ from langgraph_sdk import get_client
85
+
86
+ client = get_client(url=None)
87
+
88
+ async def my_node(...):
89
+ subagent_result = await client.runs.wait(
90
+ thread_id=None,
91
+ assistant_id="agent",
92
+ input={"messages": [{"role": "user", "content": "Foo"}]},
93
+ )
94
+ ```
95
+
96
+ ???+ example "Skip auto-loading API key from environment:"
97
+
98
+ ```python
99
+ from langgraph_sdk import get_client
100
+
101
+ # Don't load API key from environment variables
102
+ client = get_client(
103
+ url="http://localhost:8123",
104
+ api_key=None
105
+ )
106
+ ```
107
+ """
108
+
109
+ transport: httpx.AsyncBaseTransport | None = None
110
+ if url is None:
111
+ url = "http://api"
112
+ if os.environ.get("__LANGGRAPH_DEFER_LOOPBACK_TRANSPORT") == "true":
113
+ transport = get_asgi_transport()(app=None, root_path="/noauth") # type: ignore[invalid-argument-type]
114
+ _registered_transports.append(transport)
115
+ else:
116
+ try:
117
+ from langgraph_api.server import app # type: ignore
118
+
119
+ transport = get_asgi_transport()(app, root_path="/noauth")
120
+ except Exception:
121
+ logger.debug(
122
+ "Failed to connect to in-process LangGraph server. Deferring configuration.",
123
+ exc_info=True,
124
+ )
125
+ transport = get_asgi_transport()(app=None, root_path="/noauth") # type: ignore[invalid-argument-type]
126
+ _registered_transports.append(transport)
127
+
128
+ if transport is None:
129
+ transport = httpx.AsyncHTTPTransport(retries=5)
130
+ client = httpx.AsyncClient(
131
+ base_url=url,
132
+ transport=transport,
133
+ timeout=(
134
+ httpx.Timeout(timeout) # type: ignore[arg-type]
135
+ if timeout is not None
136
+ else httpx.Timeout(connect=5, read=300, write=300, pool=5)
137
+ ),
138
+ headers=_get_headers(api_key, headers),
139
+ )
140
+ return LangGraphClient(client)
141
+
142
+
143
+ class LangGraphClient:
144
+ """Top-level client for LangGraph API.
145
+
146
+ Attributes:
147
+ assistants: Manages versioned configuration for your graphs.
148
+ threads: Handles (potentially) multi-turn interactions, such as conversational threads.
149
+ runs: Controls individual invocations of the graph.
150
+ crons: Manages scheduled operations.
151
+ store: Interfaces with persistent, shared data storage.
152
+ """
153
+
154
+ def __init__(self, client: httpx.AsyncClient) -> None:
155
+ self.http = HttpClient(client)
156
+ self.assistants = AssistantsClient(self.http)
157
+ self.threads = ThreadsClient(self.http)
158
+ self.runs = RunsClient(self.http)
159
+ self.crons = CronClient(self.http)
160
+ self.store = StoreClient(self.http)
161
+
162
+ async def __aenter__(self) -> LangGraphClient:
163
+ """Enter the async context manager."""
164
+ return self
165
+
166
+ async def __aexit__(
167
+ self,
168
+ exc_type: type[BaseException] | None,
169
+ exc_val: BaseException | None,
170
+ exc_tb: TracebackType | None,
171
+ ) -> None:
172
+ """Exit the async context manager."""
173
+ await self.aclose()
174
+
175
+ async def aclose(self) -> None:
176
+ """Close the underlying HTTP client."""
177
+ if hasattr(self, "http"):
178
+ await self.http.client.aclose()
python/user_packages/Python313/site-packages/langgraph_sdk/_async/cron.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client for managing recurrent runs (cron jobs) in LangGraph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Mapping, Sequence
7
+ from datetime import datetime, tzinfo
8
+ from typing import Any
9
+
10
+ from langgraph_sdk._async.http import HttpClient
11
+ from langgraph_sdk._shared.utilities import _resolve_timezone
12
+ from langgraph_sdk.schema import (
13
+ All,
14
+ Config,
15
+ Context,
16
+ Cron,
17
+ CronSelectField,
18
+ CronSortBy,
19
+ Durability,
20
+ Input,
21
+ OnCompletionBehavior,
22
+ QueryParamTypes,
23
+ Run,
24
+ SortOrder,
25
+ StreamMode,
26
+ )
27
+
28
+
29
+ class CronClient:
30
+ """Client for managing recurrent runs (cron jobs) in LangGraph.
31
+
32
+ A run is a single invocation of an assistant with optional input, config, and context.
33
+ This client allows scheduling recurring runs to occur automatically.
34
+
35
+ ???+ example "Example Usage"
36
+
37
+ ```python
38
+ client = get_client(url="http://localhost:2024"))
39
+ cron_job = await client.crons.create_for_thread(
40
+ thread_id="thread_123",
41
+ assistant_id="asst_456",
42
+ schedule="0 9 * * *",
43
+ input={"message": "Daily update"}
44
+ )
45
+ ```
46
+
47
+ !!! note "Feature Availability"
48
+
49
+ The crons client functionality is not supported on all licenses.
50
+ Please check the relevant license documentation for the most up-to-date
51
+ details on feature availability.
52
+ """
53
+
54
+ def __init__(self, http_client: HttpClient) -> None:
55
+ self.http = http_client
56
+
57
+ async def create_for_thread(
58
+ self,
59
+ thread_id: str,
60
+ assistant_id: str,
61
+ *,
62
+ schedule: str,
63
+ input: Input | None = None,
64
+ metadata: Mapping[str, Any] | None = None,
65
+ config: Config | None = None,
66
+ context: Context | None = None,
67
+ checkpoint_during: bool | None = None, # deprecated
68
+ interrupt_before: All | list[str] | None = None,
69
+ interrupt_after: All | list[str] | None = None,
70
+ webhook: str | None = None,
71
+ multitask_strategy: str | None = None,
72
+ end_time: datetime | None = None,
73
+ enabled: bool | None = None,
74
+ timezone: str | tzinfo | None = None,
75
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
76
+ stream_subgraphs: bool | None = None,
77
+ stream_resumable: bool | None = None,
78
+ durability: Durability | None = None,
79
+ headers: Mapping[str, str] | None = None,
80
+ params: QueryParamTypes | None = None,
81
+ ) -> Run:
82
+ """Create a cron job for a thread.
83
+
84
+ Args:
85
+ thread_id: the thread ID to run the cron job on.
86
+ assistant_id: The assistant ID or graph name to use for the cron job.
87
+ If using graph name, will default to first assistant created from that graph.
88
+ schedule: The cron schedule to execute this job on.
89
+ Schedules are interpreted in UTC unless a timezone is specified.
90
+ input: The input to the graph.
91
+ metadata: Metadata to assign to the cron job runs.
92
+ config: The configuration for the assistant.
93
+ context: Static context to add to the assistant.
94
+ !!! version-added "Added in version 0.6.0"
95
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
96
+ interrupt_before: Nodes to interrupt immediately before they get executed.
97
+
98
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
99
+
100
+ webhook: Webhook to call after LangGraph API call is done.
101
+ multitask_strategy: Multitask strategy to use.
102
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
103
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
104
+ enabled: Whether the cron job is enabled or not.
105
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
106
+ stream_mode: The stream mode(s) to use.
107
+ stream_subgraphs: Whether to stream output from subgraphs.
108
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
109
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
110
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
111
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
112
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
113
+ headers: Optional custom headers to include with the request.
114
+ params: Optional query parameters to include with the request.
115
+
116
+ Returns:
117
+ The cron run.
118
+
119
+ ???+ example "Example Usage"
120
+
121
+ ```python
122
+ client = get_client(url="http://localhost:2024")
123
+ cron_run = await client.crons.create_for_thread(
124
+ thread_id="my-thread-id",
125
+ assistant_id="agent",
126
+ schedule="27 15 * * *",
127
+ input={"messages": [{"role": "user", "content": "hello!"}]},
128
+ metadata={"name":"my_run"},
129
+ context={"model_name": "openai"},
130
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
131
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
132
+ webhook="https://my.fake.webhook.com",
133
+ multitask_strategy="interrupt",
134
+ enabled=True,
135
+ )
136
+ ```
137
+ """
138
+ if checkpoint_during is not None:
139
+ warnings.warn(
140
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
141
+ DeprecationWarning,
142
+ stacklevel=2,
143
+ )
144
+
145
+ payload = {
146
+ "schedule": schedule,
147
+ "input": input,
148
+ "config": config,
149
+ "metadata": metadata,
150
+ "context": context,
151
+ "assistant_id": assistant_id,
152
+ "checkpoint_during": checkpoint_during,
153
+ "interrupt_before": interrupt_before,
154
+ "interrupt_after": interrupt_after,
155
+ "webhook": webhook,
156
+ "end_time": end_time.isoformat() if end_time else None,
157
+ "enabled": enabled,
158
+ "timezone": _resolve_timezone(timezone),
159
+ "stream_mode": stream_mode,
160
+ "stream_subgraphs": stream_subgraphs,
161
+ "stream_resumable": stream_resumable,
162
+ "durability": durability,
163
+ }
164
+ if multitask_strategy:
165
+ payload["multitask_strategy"] = multitask_strategy
166
+ payload = {k: v for k, v in payload.items() if v is not None}
167
+ return await self.http.post(
168
+ f"/threads/{thread_id}/runs/crons",
169
+ json=payload,
170
+ headers=headers,
171
+ params=params,
172
+ )
173
+
174
+ async def create(
175
+ self,
176
+ assistant_id: str,
177
+ *,
178
+ schedule: str,
179
+ input: Input | None = None,
180
+ metadata: Mapping[str, Any] | None = None,
181
+ config: Config | None = None,
182
+ context: Context | None = None,
183
+ checkpoint_during: bool | None = None, # deprecated
184
+ interrupt_before: All | list[str] | None = None,
185
+ interrupt_after: All | list[str] | None = None,
186
+ webhook: str | None = None,
187
+ on_run_completed: OnCompletionBehavior | None = None,
188
+ multitask_strategy: str | None = None,
189
+ end_time: datetime | None = None,
190
+ enabled: bool | None = None,
191
+ timezone: str | tzinfo | None = None,
192
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
193
+ stream_subgraphs: bool | None = None,
194
+ stream_resumable: bool | None = None,
195
+ durability: Durability | None = None,
196
+ headers: Mapping[str, str] | None = None,
197
+ params: QueryParamTypes | None = None,
198
+ ) -> Run:
199
+ """Create a cron run.
200
+
201
+ Args:
202
+ assistant_id: The assistant ID or graph name to use for the cron job.
203
+ If using graph name, will default to first assistant created from that graph.
204
+ schedule: The cron schedule to execute this job on.
205
+ Schedules are interpreted in UTC unless a timezone is specified.
206
+ input: The input to the graph.
207
+ metadata: Metadata to assign to the cron job runs.
208
+ config: The configuration for the assistant.
209
+ context: Static context to add to the assistant.
210
+ !!! version-added "Added in version 0.6.0"
211
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
212
+ interrupt_before: Nodes to interrupt immediately before they get executed.
213
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
214
+ webhook: Webhook to call after LangGraph API call is done.
215
+ on_run_completed: What to do with the thread after the run completes.
216
+ Must be one of 'delete' (default) or 'keep'. 'delete' removes the thread
217
+ after execution. 'keep' creates a new thread for each execution but does not
218
+ clean them up. Clients are responsible for cleaning up kept threads.
219
+ multitask_strategy: Multitask strategy to use.
220
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
221
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
222
+ enabled: Whether the cron job is enabled or not.
223
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
224
+ stream_mode: The stream mode(s) to use.
225
+ stream_subgraphs: Whether to stream output from subgraphs.
226
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
227
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
228
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
229
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
230
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
231
+ headers: Optional custom headers to include with the request.
232
+ params: Optional query parameters to include with the request.
233
+
234
+ Returns:
235
+ The cron run.
236
+
237
+ ???+ example "Example Usage"
238
+
239
+ ```python
240
+ client = get_client(url="http://localhost:2024")
241
+ cron_run = client.crons.create(
242
+ assistant_id="agent",
243
+ schedule="27 15 * * *",
244
+ input={"messages": [{"role": "user", "content": "hello!"}]},
245
+ metadata={"name":"my_run"},
246
+ context={"model_name": "openai"},
247
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
248
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
249
+ webhook="https://my.fake.webhook.com",
250
+ multitask_strategy="interrupt",
251
+ enabled=True,
252
+ )
253
+ ```
254
+
255
+ """
256
+ if checkpoint_during is not None:
257
+ warnings.warn(
258
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
259
+ DeprecationWarning,
260
+ stacklevel=2,
261
+ )
262
+
263
+ payload = {
264
+ "schedule": schedule,
265
+ "input": input,
266
+ "config": config,
267
+ "metadata": metadata,
268
+ "context": context,
269
+ "assistant_id": assistant_id,
270
+ "checkpoint_during": checkpoint_during,
271
+ "interrupt_before": interrupt_before,
272
+ "interrupt_after": interrupt_after,
273
+ "webhook": webhook,
274
+ "on_run_completed": on_run_completed,
275
+ "end_time": end_time.isoformat() if end_time else None,
276
+ "enabled": enabled,
277
+ "timezone": _resolve_timezone(timezone),
278
+ "stream_mode": stream_mode,
279
+ "stream_subgraphs": stream_subgraphs,
280
+ "stream_resumable": stream_resumable,
281
+ "durability": durability,
282
+ }
283
+ if multitask_strategy:
284
+ payload["multitask_strategy"] = multitask_strategy
285
+ payload = {k: v for k, v in payload.items() if v is not None}
286
+ return await self.http.post(
287
+ "/runs/crons", json=payload, headers=headers, params=params
288
+ )
289
+
290
+ async def delete(
291
+ self,
292
+ cron_id: str,
293
+ *,
294
+ headers: Mapping[str, str] | None = None,
295
+ params: QueryParamTypes | None = None,
296
+ ) -> None:
297
+ """Delete a cron.
298
+
299
+ Args:
300
+ cron_id: The cron ID to delete.
301
+ headers: Optional custom headers to include with the request.
302
+ params: Optional query parameters to include with the request.
303
+
304
+ Returns:
305
+ `None`
306
+
307
+ ???+ example "Example Usage"
308
+
309
+ ```python
310
+ client = get_client(url="http://localhost:2024")
311
+ await client.crons.delete(
312
+ cron_id="cron_to_delete"
313
+ )
314
+ ```
315
+
316
+ """
317
+ await self.http.delete(f"/runs/crons/{cron_id}", headers=headers, params=params)
318
+
319
+ async def update(
320
+ self,
321
+ cron_id: str,
322
+ *,
323
+ schedule: str | None = None,
324
+ end_time: datetime | None = None,
325
+ input: Input | None = None,
326
+ metadata: Mapping[str, Any] | None = None,
327
+ config: Config | None = None,
328
+ context: Context | None = None,
329
+ webhook: str | None = None,
330
+ interrupt_before: All | list[str] | None = None,
331
+ interrupt_after: All | list[str] | None = None,
332
+ on_run_completed: OnCompletionBehavior | None = None,
333
+ enabled: bool | None = None,
334
+ timezone: str | tzinfo | None = None,
335
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
336
+ stream_subgraphs: bool | None = None,
337
+ stream_resumable: bool | None = None,
338
+ durability: Durability | None = None,
339
+ headers: Mapping[str, str] | None = None,
340
+ params: QueryParamTypes | None = None,
341
+ ) -> Cron:
342
+ """Update a cron job by ID.
343
+
344
+ Args:
345
+ cron_id: The cron ID to update.
346
+ schedule: The cron schedule to execute this job on.
347
+ Schedules are interpreted in UTC unless a timezone is specified.
348
+ end_time: The end date to stop running the cron.
349
+ input: The input to the graph.
350
+ metadata: Metadata to assign to the cron job runs.
351
+ config: The configuration for the assistant.
352
+ context: Static context added to the assistant.
353
+ webhook: Webhook to call after LangGraph API call is done.
354
+ interrupt_before: Nodes to interrupt immediately before they get executed.
355
+ interrupt_after: Nodes to interrupt immediately after they get executed.
356
+ on_run_completed: What to do with the thread after the run completes.
357
+ Must be one of 'delete' or 'keep'. 'delete' removes the thread
358
+ after execution. 'keep' creates a new thread for each execution but does not
359
+ clean them up.
360
+ enabled: Enable or disable the cron job.
361
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
362
+ stream_mode: The stream mode(s) to use.
363
+ stream_subgraphs: Whether to stream output from subgraphs.
364
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
365
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
366
+ headers: Optional custom headers to include with the request.
367
+ params: Optional query parameters to include with the request.
368
+
369
+ Returns:
370
+ The updated cron job.
371
+
372
+ ???+ example "Example Usage"
373
+
374
+ ```python
375
+ client = get_client(url="http://localhost:2024")
376
+ updated_cron = await client.crons.update(
377
+ cron_id="1ef3cefa-4c09-6926-96d0-3dc97fd5e39b",
378
+ schedule="0 10 * * *",
379
+ enabled=False,
380
+ )
381
+ ```
382
+
383
+ """
384
+ payload = {
385
+ "schedule": schedule,
386
+ "end_time": end_time.isoformat() if end_time else None,
387
+ "input": input,
388
+ "metadata": metadata,
389
+ "config": config,
390
+ "context": context,
391
+ "webhook": webhook,
392
+ "interrupt_before": interrupt_before,
393
+ "interrupt_after": interrupt_after,
394
+ "on_run_completed": on_run_completed,
395
+ "enabled": enabled,
396
+ "timezone": _resolve_timezone(timezone),
397
+ "stream_mode": stream_mode,
398
+ "stream_subgraphs": stream_subgraphs,
399
+ "stream_resumable": stream_resumable,
400
+ "durability": durability,
401
+ }
402
+ payload = {k: v for k, v in payload.items() if v is not None}
403
+ return await self.http.patch(
404
+ f"/runs/crons/{cron_id}",
405
+ json=payload,
406
+ headers=headers,
407
+ params=params,
408
+ )
409
+
410
+ async def search(
411
+ self,
412
+ *,
413
+ assistant_id: str | None = None,
414
+ thread_id: str | None = None,
415
+ enabled: bool | None = None,
416
+ limit: int = 10,
417
+ offset: int = 0,
418
+ sort_by: CronSortBy | None = None,
419
+ sort_order: SortOrder | None = None,
420
+ select: list[CronSelectField] | None = None,
421
+ headers: Mapping[str, str] | None = None,
422
+ params: QueryParamTypes | None = None,
423
+ ) -> list[Cron]:
424
+ """Get a list of cron jobs.
425
+
426
+ Args:
427
+ assistant_id: The assistant ID or graph name to search for.
428
+ thread_id: the thread ID to search for.
429
+ enabled: The enabled status to search for.
430
+ limit: The maximum number of results to return.
431
+ offset: The number of results to skip.
432
+ headers: Optional custom headers to include with the request.
433
+ params: Optional query parameters to include with the request.
434
+
435
+ Returns:
436
+ The list of cron jobs returned by the search,
437
+
438
+ ???+ example "Example Usage"
439
+
440
+ ```python
441
+ client = get_client(url="http://localhost:2024")
442
+ cron_jobs = await client.crons.search(
443
+ assistant_id="my_assistant_id",
444
+ thread_id="my_thread_id",
445
+ enabled=True,
446
+ limit=5,
447
+ offset=5,
448
+ )
449
+ print(cron_jobs)
450
+ ```
451
+ ```shell
452
+
453
+ ----------------------------------------------------------
454
+
455
+ [
456
+ {
457
+ 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
458
+ 'assistant_id': 'my_assistant_id',
459
+ 'thread_id': 'my_thread_id',
460
+ 'user_id': None,
461
+ 'payload':
462
+ {
463
+ 'input': {'start_time': ''},
464
+ 'schedule': '4 * * * *',
465
+ 'assistant_id': 'my_assistant_id'
466
+ },
467
+ 'schedule': '4 * * * *',
468
+ 'next_run_date': '2024-07-25T17:04:00+00:00',
469
+ 'end_time': None,
470
+ 'created_at': '2024-07-08T06:02:23.073257+00:00',
471
+ 'updated_at': '2024-07-08T06:02:23.073257+00:00'
472
+ }
473
+ ]
474
+ ```
475
+
476
+ """
477
+ payload: dict[str, Any] = {
478
+ "assistant_id": assistant_id,
479
+ "thread_id": thread_id,
480
+ "enabled": enabled,
481
+ "limit": limit,
482
+ "offset": offset,
483
+ }
484
+ if sort_by:
485
+ payload["sort_by"] = sort_by
486
+ if sort_order:
487
+ payload["sort_order"] = sort_order
488
+ if select:
489
+ payload["select"] = select
490
+ payload = {k: v for k, v in payload.items() if v is not None}
491
+ return await self.http.post(
492
+ "/runs/crons/search", json=payload, headers=headers, params=params
493
+ )
494
+
495
+ async def count(
496
+ self,
497
+ *,
498
+ assistant_id: str | None = None,
499
+ thread_id: str | None = None,
500
+ headers: Mapping[str, str] | None = None,
501
+ params: QueryParamTypes | None = None,
502
+ ) -> int:
503
+ """Count cron jobs matching filters.
504
+
505
+ Args:
506
+ assistant_id: Assistant ID to filter by.
507
+ thread_id: Thread ID to filter by.
508
+ headers: Optional custom headers to include with the request.
509
+ params: Optional query parameters to include with the request.
510
+
511
+ Returns:
512
+ int: Number of crons matching the criteria.
513
+ """
514
+ payload: dict[str, Any] = {}
515
+ if assistant_id:
516
+ payload["assistant_id"] = assistant_id
517
+ if thread_id:
518
+ payload["thread_id"] = thread_id
519
+ return await self.http.post(
520
+ "/runs/crons/count", json=payload, headers=headers, params=params
521
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_async/http.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP client for async operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import sys
8
+ import warnings
9
+ from collections.abc import AsyncIterator, Callable, Mapping
10
+ from typing import Any, cast
11
+
12
+ import httpx
13
+ import orjson
14
+
15
+ from langgraph_sdk._shared.utilities import (
16
+ _orjson_default,
17
+ _validate_reconnect_location,
18
+ )
19
+ from langgraph_sdk.errors import _araise_for_status_typed
20
+ from langgraph_sdk.schema import QueryParamTypes, StreamPart
21
+ from langgraph_sdk.sse import SSEDecoder, aiter_lines_raw
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class HttpClient:
27
+ """Handle async requests to the LangGraph API.
28
+
29
+ Adds additional error messaging & content handling above the
30
+ provided httpx client.
31
+
32
+ Attributes:
33
+ client (httpx.AsyncClient): Underlying HTTPX async client.
34
+ """
35
+
36
+ def __init__(self, client: httpx.AsyncClient) -> None:
37
+ self.client = client
38
+
39
+ async def get(
40
+ self,
41
+ path: str,
42
+ *,
43
+ params: QueryParamTypes | None = None,
44
+ headers: Mapping[str, str] | None = None,
45
+ on_response: Callable[[httpx.Response], None] | None = None,
46
+ ) -> Any:
47
+ """Send a `GET` request."""
48
+ r = await self.client.get(path, params=params, headers=headers)
49
+ if on_response:
50
+ on_response(r)
51
+ await _araise_for_status_typed(r)
52
+ return await _adecode_json(r)
53
+
54
+ async def post(
55
+ self,
56
+ path: str,
57
+ *,
58
+ json: dict[str, Any] | list | None,
59
+ params: QueryParamTypes | None = None,
60
+ headers: Mapping[str, str] | None = None,
61
+ on_response: Callable[[httpx.Response], None] | None = None,
62
+ ) -> Any:
63
+ """Send a `POST` request."""
64
+ if json is not None:
65
+ request_headers, content = await _aencode_json(json)
66
+ else:
67
+ request_headers, content = {}, b""
68
+ # Merge headers, with runtime headers taking precedence
69
+ if headers:
70
+ request_headers.update(headers)
71
+ r = await self.client.post(
72
+ path, headers=request_headers, content=content, params=params
73
+ )
74
+ if on_response:
75
+ on_response(r)
76
+ await _araise_for_status_typed(r)
77
+ return await _adecode_json(r)
78
+
79
+ async def put(
80
+ self,
81
+ path: str,
82
+ *,
83
+ json: dict,
84
+ params: QueryParamTypes | None = None,
85
+ headers: Mapping[str, str] | None = None,
86
+ on_response: Callable[[httpx.Response], None] | None = None,
87
+ ) -> Any:
88
+ """Send a `PUT` request."""
89
+ request_headers, content = await _aencode_json(json)
90
+ if headers:
91
+ request_headers.update(headers)
92
+ r = await self.client.put(
93
+ path, headers=request_headers, content=content, params=params
94
+ )
95
+ if on_response:
96
+ on_response(r)
97
+ await _araise_for_status_typed(r)
98
+ return await _adecode_json(r)
99
+
100
+ async def patch(
101
+ self,
102
+ path: str,
103
+ *,
104
+ json: dict,
105
+ params: QueryParamTypes | None = None,
106
+ headers: Mapping[str, str] | None = None,
107
+ on_response: Callable[[httpx.Response], None] | None = None,
108
+ ) -> Any:
109
+ """Send a `PATCH` request."""
110
+ request_headers, content = await _aencode_json(json)
111
+ if headers:
112
+ request_headers.update(headers)
113
+ r = await self.client.patch(
114
+ path, headers=request_headers, content=content, params=params
115
+ )
116
+ if on_response:
117
+ on_response(r)
118
+ await _araise_for_status_typed(r)
119
+ return await _adecode_json(r)
120
+
121
+ async def delete(
122
+ self,
123
+ path: str,
124
+ *,
125
+ json: Any | None = None,
126
+ params: QueryParamTypes | None = None,
127
+ headers: Mapping[str, str] | None = None,
128
+ on_response: Callable[[httpx.Response], None] | None = None,
129
+ ) -> None:
130
+ """Send a `DELETE` request."""
131
+ r = await self.client.request(
132
+ "DELETE", path, json=json, params=params, headers=headers
133
+ )
134
+ if on_response:
135
+ on_response(r)
136
+ await _araise_for_status_typed(r)
137
+
138
+ async def request_reconnect(
139
+ self,
140
+ path: str,
141
+ method: str,
142
+ *,
143
+ json: dict[str, Any] | None = None,
144
+ params: QueryParamTypes | None = None,
145
+ headers: Mapping[str, str] | None = None,
146
+ on_response: Callable[[httpx.Response], None] | None = None,
147
+ reconnect_limit: int = 5,
148
+ ) -> Any:
149
+ """Send a request that automatically reconnects to Location header."""
150
+ request_headers, content = await _aencode_json(json)
151
+ if headers:
152
+ request_headers.update(headers)
153
+ async with self.client.stream(
154
+ method, path, headers=request_headers, content=content, params=params
155
+ ) as r:
156
+ if on_response:
157
+ on_response(r)
158
+ try:
159
+ r.raise_for_status()
160
+ except httpx.HTTPStatusError as e:
161
+ body = (await r.aread()).decode()
162
+ if sys.version_info >= (3, 11):
163
+ e.add_note(body)
164
+ else:
165
+ logger.error(f"Error from langgraph-api: {body}", exc_info=e)
166
+ raise e
167
+ loc = r.headers.get("location")
168
+ if reconnect_limit <= 0 or not loc:
169
+ return await _adecode_json(r)
170
+ _validate_reconnect_location(self.client.base_url, loc)
171
+ try:
172
+ return await _adecode_json(r)
173
+ except httpx.HTTPError:
174
+ warnings.warn(
175
+ f"Request failed, attempting reconnect to Location: {loc}",
176
+ stacklevel=2,
177
+ )
178
+ await r.aclose()
179
+ return await self.request_reconnect(
180
+ loc,
181
+ "GET",
182
+ headers=request_headers,
183
+ # don't pass on_response so it's only called once
184
+ reconnect_limit=reconnect_limit - 1,
185
+ )
186
+
187
+ async def stream(
188
+ self,
189
+ path: str,
190
+ method: str,
191
+ *,
192
+ json: dict[str, Any] | None = None,
193
+ params: QueryParamTypes | None = None,
194
+ headers: Mapping[str, str] | None = None,
195
+ on_response: Callable[[httpx.Response], None] | None = None,
196
+ ) -> AsyncIterator[StreamPart]:
197
+ """Stream results using SSE."""
198
+ request_headers, content = await _aencode_json(json)
199
+ request_headers["Accept"] = "text/event-stream"
200
+ request_headers["Cache-Control"] = "no-store"
201
+ # Add runtime headers with precedence
202
+ if headers:
203
+ request_headers.update(headers)
204
+
205
+ reconnect_headers = {
206
+ key: value
207
+ for key, value in request_headers.items()
208
+ if key.lower() not in {"content-length", "content-type"}
209
+ }
210
+
211
+ last_event_id: str | None = None
212
+ reconnect_path: str | None = None
213
+ reconnect_attempts = 0
214
+ max_reconnect_attempts = 5
215
+
216
+ while True:
217
+ current_headers = dict(
218
+ request_headers if reconnect_path is None else reconnect_headers
219
+ )
220
+ if last_event_id is not None:
221
+ current_headers["Last-Event-ID"] = last_event_id
222
+
223
+ current_method = method if reconnect_path is None else "GET"
224
+ current_content = content if reconnect_path is None else None
225
+ current_params = params if reconnect_path is None else None
226
+
227
+ retry = False
228
+ async with self.client.stream(
229
+ current_method,
230
+ reconnect_path or path,
231
+ headers=current_headers,
232
+ content=current_content,
233
+ params=current_params,
234
+ ) as res:
235
+ if reconnect_path is None and on_response:
236
+ on_response(res)
237
+ # check status
238
+ await _araise_for_status_typed(res)
239
+ # check content type
240
+ content_type = res.headers.get("content-type", "").partition(";")[0]
241
+ if "text/event-stream" not in content_type:
242
+ raise httpx.TransportError(
243
+ "Expected response header Content-Type to contain 'text/event-stream', "
244
+ f"got {content_type!r}"
245
+ )
246
+
247
+ reconnect_location = res.headers.get("location")
248
+ if reconnect_location:
249
+ _validate_reconnect_location(
250
+ self.client.base_url, reconnect_location
251
+ )
252
+ reconnect_path = reconnect_location
253
+
254
+ # parse SSE
255
+ decoder = SSEDecoder()
256
+ try:
257
+ async for line in aiter_lines_raw(res):
258
+ sse = decoder.decode(line=cast("bytes", line).rstrip(b"\n"))
259
+ if sse is not None:
260
+ if decoder.last_event_id is not None:
261
+ last_event_id = decoder.last_event_id
262
+ if sse.event or sse.data is not None:
263
+ yield sse
264
+ except httpx.HTTPError:
265
+ # httpx.TransportError inherits from HTTPError, so transient
266
+ # disconnects during streaming land here.
267
+ if reconnect_path is None:
268
+ raise
269
+ retry = True
270
+ else:
271
+ if sse := decoder.decode(b""):
272
+ if decoder.last_event_id is not None:
273
+ last_event_id = decoder.last_event_id
274
+ if sse.event or sse.data is not None:
275
+ # decoder.decode(b"") flushes the in-flight event and may
276
+ # return an empty placeholder when there is no pending
277
+ # message. Skip these no-op events so the stream doesn't
278
+ # emit a trailing blank item after reconnects.
279
+ yield sse
280
+ if retry:
281
+ reconnect_attempts += 1
282
+ if reconnect_attempts > max_reconnect_attempts:
283
+ raise httpx.TransportError(
284
+ "Exceeded maximum SSE reconnection attempts"
285
+ )
286
+ continue
287
+ break
288
+
289
+
290
+ async def _aencode_json(json: Any) -> tuple[dict[str, str], bytes | None]:
291
+ if json is None:
292
+ return {}, None
293
+ body = await asyncio.get_running_loop().run_in_executor(
294
+ None,
295
+ orjson.dumps,
296
+ json,
297
+ _orjson_default,
298
+ orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
299
+ )
300
+ content_length = str(len(body))
301
+ content_type = "application/json"
302
+ headers = {"Content-Length": content_length, "Content-Type": content_type}
303
+ return headers, body
304
+
305
+
306
+ async def _adecode_json(r: httpx.Response) -> Any:
307
+ body = await r.aread()
308
+ return (
309
+ await asyncio.get_running_loop().run_in_executor(None, orjson.loads, body)
310
+ if body
311
+ else None
312
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_async/runs.py ADDED
@@ -0,0 +1,1181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client for managing runs in LangGraph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ import warnings
7
+ from collections.abc import AsyncIterator, Callable, Mapping, Sequence
8
+ from typing import Any, Literal, overload
9
+
10
+ import httpx
11
+
12
+ from langgraph_sdk._async.http import HttpClient
13
+ from langgraph_sdk._shared.utilities import (
14
+ _get_run_metadata_from_response,
15
+ _sse_to_v2_dict,
16
+ )
17
+ from langgraph_sdk.schema import (
18
+ All,
19
+ BulkCancelRunsStatus,
20
+ CancelAction,
21
+ Checkpoint,
22
+ Command,
23
+ Config,
24
+ Context,
25
+ DisconnectMode,
26
+ Durability,
27
+ IfNotExists,
28
+ Input,
29
+ LangSmithTracing,
30
+ MultitaskStrategy,
31
+ OnCompletionBehavior,
32
+ QueryParamTypes,
33
+ Run,
34
+ RunCreate,
35
+ RunCreateMetadata,
36
+ RunSelectField,
37
+ RunStatus,
38
+ StreamMode,
39
+ StreamPart,
40
+ StreamPartV2,
41
+ StreamVersion,
42
+ )
43
+
44
+
45
+ async def _wrap_stream_v2(
46
+ raw: AsyncIterator[StreamPart],
47
+ ) -> AsyncIterator[StreamPartV2]:
48
+ """Wrap a raw SSE stream, converting each event to a v2 dict."""
49
+ async for part in raw:
50
+ v2 = _sse_to_v2_dict(part.event, part.data)
51
+ if v2 is not None:
52
+ yield v2
53
+
54
+
55
+ class RunsClient:
56
+ """Client for managing runs in LangGraph.
57
+
58
+ A run is a single assistant invocation with optional input, config, context, and metadata.
59
+ This client manages runs, which can be stateful (on threads) or stateless.
60
+
61
+ ???+ example "Example"
62
+
63
+ ```python
64
+ client = get_client(url="http://localhost:2024")
65
+ run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})
66
+ ```
67
+ """
68
+
69
+ def __init__(self, http: HttpClient) -> None:
70
+ self.http = http
71
+
72
+ @overload
73
+ def stream(
74
+ self,
75
+ thread_id: str,
76
+ assistant_id: str,
77
+ *,
78
+ input: Input | None = None,
79
+ command: Command | None = None,
80
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
81
+ stream_subgraphs: bool = False,
82
+ stream_resumable: bool = False,
83
+ metadata: Mapping[str, Any] | None = None,
84
+ config: Config | None = None,
85
+ context: Context | None = None,
86
+ checkpoint: Checkpoint | None = None,
87
+ checkpoint_id: str | None = None,
88
+ checkpoint_during: bool | None = None,
89
+ interrupt_before: All | Sequence[str] | None = None,
90
+ interrupt_after: All | Sequence[str] | None = None,
91
+ feedback_keys: Sequence[str] | None = None,
92
+ on_disconnect: DisconnectMode | None = None,
93
+ webhook: str | None = None,
94
+ multitask_strategy: MultitaskStrategy | None = None,
95
+ if_not_exists: IfNotExists | None = None,
96
+ after_seconds: int | None = None,
97
+ langsmith_tracing: LangSmithTracing | None = None,
98
+ headers: Mapping[str, str] | None = None,
99
+ params: QueryParamTypes | None = None,
100
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
101
+ version: Literal["v1"] = "v1",
102
+ ) -> AsyncIterator[StreamPart]: ...
103
+
104
+ @overload
105
+ def stream(
106
+ self,
107
+ thread_id: str,
108
+ assistant_id: str,
109
+ *,
110
+ input: Input | None = None,
111
+ command: Command | None = None,
112
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
113
+ stream_subgraphs: bool = False,
114
+ stream_resumable: bool = False,
115
+ metadata: Mapping[str, Any] | None = None,
116
+ config: Config | None = None,
117
+ context: Context | None = None,
118
+ checkpoint: Checkpoint | None = None,
119
+ checkpoint_id: str | None = None,
120
+ checkpoint_during: bool | None = None,
121
+ interrupt_before: All | Sequence[str] | None = None,
122
+ interrupt_after: All | Sequence[str] | None = None,
123
+ feedback_keys: Sequence[str] | None = None,
124
+ on_disconnect: DisconnectMode | None = None,
125
+ webhook: str | None = None,
126
+ multitask_strategy: MultitaskStrategy | None = None,
127
+ if_not_exists: IfNotExists | None = None,
128
+ after_seconds: int | None = None,
129
+ langsmith_tracing: LangSmithTracing | None = None,
130
+ headers: Mapping[str, str] | None = None,
131
+ params: QueryParamTypes | None = None,
132
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
133
+ version: Literal["v2"],
134
+ ) -> AsyncIterator[StreamPartV2]: ...
135
+
136
+ @overload
137
+ def stream(
138
+ self,
139
+ thread_id: None,
140
+ assistant_id: str,
141
+ *,
142
+ input: Input | None = None,
143
+ command: Command | None = None,
144
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
145
+ stream_subgraphs: bool = False,
146
+ stream_resumable: bool = False,
147
+ metadata: Mapping[str, Any] | None = None,
148
+ config: Config | None = None,
149
+ checkpoint_during: bool | None = None,
150
+ interrupt_before: All | Sequence[str] | None = None,
151
+ interrupt_after: All | Sequence[str] | None = None,
152
+ feedback_keys: Sequence[str] | None = None,
153
+ on_disconnect: DisconnectMode | None = None,
154
+ on_completion: OnCompletionBehavior | None = None,
155
+ if_not_exists: IfNotExists | None = None,
156
+ webhook: str | None = None,
157
+ after_seconds: int | None = None,
158
+ langsmith_tracing: LangSmithTracing | None = None,
159
+ headers: Mapping[str, str] | None = None,
160
+ params: QueryParamTypes | None = None,
161
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
162
+ version: Literal["v1"] = "v1",
163
+ ) -> AsyncIterator[StreamPart]: ...
164
+
165
+ @overload
166
+ def stream(
167
+ self,
168
+ thread_id: None,
169
+ assistant_id: str,
170
+ *,
171
+ input: Input | None = None,
172
+ command: Command | None = None,
173
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
174
+ stream_subgraphs: bool = False,
175
+ stream_resumable: bool = False,
176
+ metadata: Mapping[str, Any] | None = None,
177
+ config: Config | None = None,
178
+ checkpoint_during: bool | None = None,
179
+ interrupt_before: All | Sequence[str] | None = None,
180
+ interrupt_after: All | Sequence[str] | None = None,
181
+ feedback_keys: Sequence[str] | None = None,
182
+ on_disconnect: DisconnectMode | None = None,
183
+ on_completion: OnCompletionBehavior | None = None,
184
+ if_not_exists: IfNotExists | None = None,
185
+ webhook: str | None = None,
186
+ after_seconds: int | None = None,
187
+ langsmith_tracing: LangSmithTracing | None = None,
188
+ headers: Mapping[str, str] | None = None,
189
+ params: QueryParamTypes | None = None,
190
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
191
+ version: Literal["v2"],
192
+ ) -> AsyncIterator[StreamPartV2]: ...
193
+
194
+ def stream(
195
+ self,
196
+ thread_id: str | None,
197
+ assistant_id: str,
198
+ *,
199
+ input: Input | None = None,
200
+ command: Command | None = None,
201
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
202
+ stream_subgraphs: bool = False,
203
+ stream_resumable: bool = False,
204
+ metadata: Mapping[str, Any] | None = None,
205
+ config: Config | None = None,
206
+ context: Context | None = None,
207
+ checkpoint: Checkpoint | None = None,
208
+ checkpoint_id: str | None = None,
209
+ checkpoint_during: bool | None = None, # deprecated
210
+ interrupt_before: All | Sequence[str] | None = None,
211
+ interrupt_after: All | Sequence[str] | None = None,
212
+ feedback_keys: Sequence[str] | None = None,
213
+ on_disconnect: DisconnectMode | None = None,
214
+ on_completion: OnCompletionBehavior | None = None,
215
+ webhook: str | None = None,
216
+ multitask_strategy: MultitaskStrategy | None = None,
217
+ if_not_exists: IfNotExists | None = None,
218
+ after_seconds: int | None = None,
219
+ langsmith_tracing: LangSmithTracing | None = None,
220
+ headers: Mapping[str, str] | None = None,
221
+ params: QueryParamTypes | None = None,
222
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
223
+ durability: Durability | None = None,
224
+ version: StreamVersion = "v1",
225
+ ) -> AsyncIterator[StreamPart | StreamPartV2]:
226
+ """Create a run and stream the results.
227
+
228
+ Args:
229
+ thread_id: the thread ID to assign to the thread.
230
+ If `None` will create a stateless run.
231
+ assistant_id: The assistant ID or graph name to stream from.
232
+ If using graph name, will default to first assistant created from that graph.
233
+ input: The input to the graph.
234
+ command: A command to execute. Cannot be combined with input.
235
+ stream_mode: The stream mode(s) to use.
236
+ stream_subgraphs: Whether to stream output from subgraphs.
237
+ stream_resumable: Whether the stream is considered resumable.
238
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
239
+ metadata: Metadata to assign to the run.
240
+ config: The configuration for the assistant.
241
+ context: Static context to add to the assistant.
242
+ !!! version-added "Added in version 0.6.0"
243
+ checkpoint: The checkpoint to resume from.
244
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
245
+ interrupt_before: Nodes to interrupt immediately before they get executed.
246
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
247
+ feedback_keys: Feedback keys to assign to run.
248
+ on_disconnect: The disconnect mode to use.
249
+ Must be one of 'cancel' or 'continue'.
250
+ on_completion: Whether to delete or keep the thread created for a stateless run.
251
+ Must be one of 'delete' or 'keep'.
252
+ webhook: Webhook to call after LangGraph API call is done.
253
+ multitask_strategy: Multitask strategy to use.
254
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
255
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
256
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
257
+ after_seconds: The number of seconds to wait before starting the run.
258
+ Use to schedule future runs.
259
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
260
+ to a specific project or associating with a dataset example.
261
+ headers: Optional custom headers to include with the request.
262
+ params: Optional query parameters to include with the request.
263
+ on_run_created: Callback when a run is created.
264
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
265
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
266
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
267
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
268
+ version: Stream format version. "v1" (default) returns raw SSE StreamPart
269
+ NamedTuples. "v2" returns typed dicts with `type`, `ns`, and `data` keys.
270
+
271
+ Returns:
272
+ Asynchronous iterator of stream results.
273
+
274
+ ???+ example "Example Usage"
275
+
276
+ ```python
277
+ client = get_client(url="http://localhost:2024)
278
+ async for chunk in client.runs.stream(
279
+ thread_id=None,
280
+ assistant_id="agent",
281
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
282
+ stream_mode=["values","debug"],
283
+ metadata={"name":"my_run"},
284
+ context={"model_name": "anthropic"},
285
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
286
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
287
+ feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
288
+ webhook="https://my.fake.webhook.com",
289
+ multitask_strategy="interrupt"
290
+ ):
291
+ print(chunk)
292
+ ```
293
+
294
+ ```shell
295
+
296
+ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
297
+
298
+ StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
299
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
300
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
301
+ StreamPart(event='end', data=None)
302
+ ```
303
+
304
+ """
305
+ if checkpoint_during is not None:
306
+ warnings.warn(
307
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
308
+ DeprecationWarning,
309
+ stacklevel=2,
310
+ )
311
+
312
+ payload: dict[str, Any] = {
313
+ "input": input,
314
+ "command": (
315
+ {k: v for k, v in command.items() if v is not None} if command else None
316
+ ),
317
+ "config": config,
318
+ "context": context,
319
+ "metadata": metadata,
320
+ "stream_mode": stream_mode,
321
+ "stream_subgraphs": stream_subgraphs,
322
+ "stream_resumable": stream_resumable,
323
+ "assistant_id": assistant_id,
324
+ "interrupt_before": interrupt_before,
325
+ "interrupt_after": interrupt_after,
326
+ "feedback_keys": feedback_keys,
327
+ "webhook": webhook,
328
+ "checkpoint": checkpoint,
329
+ "checkpoint_id": checkpoint_id,
330
+ "checkpoint_during": checkpoint_during,
331
+ "multitask_strategy": multitask_strategy,
332
+ "if_not_exists": if_not_exists,
333
+ "on_disconnect": on_disconnect,
334
+ "on_completion": on_completion,
335
+ "after_seconds": after_seconds,
336
+ "durability": durability,
337
+ "langsmith_tracer": langsmith_tracing,
338
+ }
339
+ endpoint = (
340
+ f"/threads/{thread_id}/runs/stream"
341
+ if thread_id is not None
342
+ else "/runs/stream"
343
+ )
344
+
345
+ def on_response(res: httpx.Response):
346
+ """Callback function to handle the response."""
347
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
348
+ on_run_created(metadata)
349
+
350
+ raw = self.http.stream(
351
+ endpoint,
352
+ "POST",
353
+ json={k: v for k, v in payload.items() if v is not None},
354
+ params=params,
355
+ headers=headers,
356
+ on_response=on_response if on_run_created else None,
357
+ )
358
+ if version == "v2":
359
+ return _wrap_stream_v2(raw)
360
+ return raw
361
+
362
+ @overload
363
+ async def create(
364
+ self,
365
+ thread_id: None,
366
+ assistant_id: str,
367
+ *,
368
+ input: Input | None = None,
369
+ command: Command | None = None,
370
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
371
+ stream_subgraphs: bool = False,
372
+ stream_resumable: bool = False,
373
+ metadata: Mapping[str, Any] | None = None,
374
+ checkpoint_during: bool | None = None,
375
+ config: Config | None = None,
376
+ context: Context | None = None,
377
+ interrupt_before: All | Sequence[str] | None = None,
378
+ interrupt_after: All | Sequence[str] | None = None,
379
+ webhook: str | None = None,
380
+ on_completion: OnCompletionBehavior | None = None,
381
+ if_not_exists: IfNotExists | None = None,
382
+ after_seconds: int | None = None,
383
+ langsmith_tracing: LangSmithTracing | None = None,
384
+ headers: Mapping[str, str] | None = None,
385
+ params: QueryParamTypes | None = None,
386
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
387
+ ) -> Run: ...
388
+
389
+ @overload
390
+ async def create(
391
+ self,
392
+ thread_id: str,
393
+ assistant_id: str,
394
+ *,
395
+ input: Input | None = None,
396
+ command: Command | None = None,
397
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
398
+ stream_subgraphs: bool = False,
399
+ stream_resumable: bool = False,
400
+ metadata: Mapping[str, Any] | None = None,
401
+ config: Config | None = None,
402
+ context: Context | None = None,
403
+ checkpoint: Checkpoint | None = None,
404
+ checkpoint_id: str | None = None,
405
+ checkpoint_during: bool | None = None,
406
+ interrupt_before: All | Sequence[str] | None = None,
407
+ interrupt_after: All | Sequence[str] | None = None,
408
+ webhook: str | None = None,
409
+ multitask_strategy: MultitaskStrategy | None = None,
410
+ if_not_exists: IfNotExists | None = None,
411
+ after_seconds: int | None = None,
412
+ langsmith_tracing: LangSmithTracing | None = None,
413
+ headers: Mapping[str, str] | None = None,
414
+ params: QueryParamTypes | None = None,
415
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
416
+ ) -> Run: ...
417
+
418
+ async def create(
419
+ self,
420
+ thread_id: str | None,
421
+ assistant_id: str,
422
+ *,
423
+ input: Input | None = None,
424
+ command: Command | None = None,
425
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
426
+ stream_subgraphs: bool = False,
427
+ stream_resumable: bool = False,
428
+ metadata: Mapping[str, Any] | None = None,
429
+ config: Config | None = None,
430
+ context: Context | None = None,
431
+ checkpoint: Checkpoint | None = None,
432
+ checkpoint_id: str | None = None,
433
+ checkpoint_during: bool | None = None, # deprecated
434
+ interrupt_before: All | Sequence[str] | None = None,
435
+ interrupt_after: All | Sequence[str] | None = None,
436
+ webhook: str | None = None,
437
+ multitask_strategy: MultitaskStrategy | None = None,
438
+ if_not_exists: IfNotExists | None = None,
439
+ on_completion: OnCompletionBehavior | None = None,
440
+ after_seconds: int | None = None,
441
+ langsmith_tracing: LangSmithTracing | None = None,
442
+ headers: Mapping[str, str] | None = None,
443
+ params: QueryParamTypes | None = None,
444
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
445
+ durability: Durability | None = None,
446
+ ) -> Run:
447
+ """Create a background run.
448
+
449
+ Args:
450
+ thread_id: the thread ID to assign to the thread.
451
+ If `None` will create a stateless run.
452
+ assistant_id: The assistant ID or graph name to stream from.
453
+ If using graph name, will default to first assistant created from that graph.
454
+ input: The input to the graph.
455
+ command: A command to execute. Cannot be combined with input.
456
+ stream_mode: The stream mode(s) to use.
457
+ stream_subgraphs: Whether to stream output from subgraphs.
458
+ stream_resumable: Whether the stream is considered resumable.
459
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
460
+ metadata: Metadata to assign to the run.
461
+ config: The configuration for the assistant.
462
+ context: Static context to add to the assistant.
463
+ !!! version-added "Added in version 0.6.0"
464
+ checkpoint: The checkpoint to resume from.
465
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
466
+ interrupt_before: Nodes to interrupt immediately before they get executed.
467
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
468
+ webhook: Webhook to call after LangGraph API call is done.
469
+ multitask_strategy: Multitask strategy to use.
470
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
471
+ on_completion: Whether to delete or keep the thread created for a stateless run.
472
+ Must be one of 'delete' or 'keep'.
473
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
474
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
475
+ after_seconds: The number of seconds to wait before starting the run.
476
+ Use to schedule future runs.
477
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
478
+ to a specific project or associating with a dataset example.
479
+ headers: Optional custom headers to include with the request.
480
+ on_run_created: Optional callback to call when a run is created.
481
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
482
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
483
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
484
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
485
+
486
+ Returns:
487
+ The created background run.
488
+
489
+ ???+ example "Example Usage"
490
+
491
+ ```python
492
+
493
+ background_run = await client.runs.create(
494
+ thread_id="my_thread_id",
495
+ assistant_id="my_assistant_id",
496
+ input={"messages": [{"role": "user", "content": "hello!"}]},
497
+ metadata={"name":"my_run"},
498
+ context={"model_name": "openai"},
499
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
500
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
501
+ webhook="https://my.fake.webhook.com",
502
+ multitask_strategy="interrupt"
503
+ )
504
+ print(background_run)
505
+ ```
506
+
507
+ ```shell
508
+ --------------------------------------------------------------------------------
509
+
510
+ {
511
+ 'run_id': 'my_run_id',
512
+ 'thread_id': 'my_thread_id',
513
+ 'assistant_id': 'my_assistant_id',
514
+ 'created_at': '2024-07-25T15:35:42.598503+00:00',
515
+ 'updated_at': '2024-07-25T15:35:42.598503+00:00',
516
+ 'metadata': {},
517
+ 'status': 'pending',
518
+ 'kwargs':
519
+ {
520
+ 'input':
521
+ {
522
+ 'messages': [
523
+ {
524
+ 'role': 'user',
525
+ 'content': 'how are you?'
526
+ }
527
+ ]
528
+ },
529
+ 'config':
530
+ {
531
+ 'metadata':
532
+ {
533
+ 'created_by': 'system'
534
+ },
535
+ 'configurable':
536
+ {
537
+ 'run_id': 'my_run_id',
538
+ 'user_id': None,
539
+ 'graph_id': 'agent',
540
+ 'thread_id': 'my_thread_id',
541
+ 'checkpoint_id': None,
542
+ 'assistant_id': 'my_assistant_id'
543
+ },
544
+ },
545
+ 'context':
546
+ {
547
+ 'model_name': 'openai'
548
+ }
549
+ 'webhook': "https://my.fake.webhook.com",
550
+ 'temporary': False,
551
+ 'stream_mode': ['values'],
552
+ 'feedback_keys': None,
553
+ 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
554
+ 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
555
+ },
556
+ 'multitask_strategy': 'interrupt'
557
+ }
558
+ ```
559
+ """
560
+ if checkpoint_during is not None:
561
+ warnings.warn(
562
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
563
+ DeprecationWarning,
564
+ stacklevel=2,
565
+ )
566
+ payload = {
567
+ "input": input,
568
+ "command": (
569
+ {k: v for k, v in command.items() if v is not None} if command else None
570
+ ),
571
+ "stream_mode": stream_mode,
572
+ "stream_subgraphs": stream_subgraphs,
573
+ "stream_resumable": stream_resumable,
574
+ "config": config,
575
+ "context": context,
576
+ "metadata": metadata,
577
+ "assistant_id": assistant_id,
578
+ "interrupt_before": interrupt_before,
579
+ "interrupt_after": interrupt_after,
580
+ "webhook": webhook,
581
+ "checkpoint": checkpoint,
582
+ "checkpoint_id": checkpoint_id,
583
+ "checkpoint_during": checkpoint_during,
584
+ "multitask_strategy": multitask_strategy,
585
+ "if_not_exists": if_not_exists,
586
+ "on_completion": on_completion,
587
+ "after_seconds": after_seconds,
588
+ "durability": durability,
589
+ "langsmith_tracer": langsmith_tracing,
590
+ }
591
+ payload = {k: v for k, v in payload.items() if v is not None}
592
+
593
+ def on_response(res: httpx.Response):
594
+ """Callback function to handle the response."""
595
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
596
+ on_run_created(metadata)
597
+
598
+ return await self.http.post(
599
+ f"/threads/{thread_id}/runs" if thread_id else "/runs",
600
+ json=payload,
601
+ params=params,
602
+ headers=headers,
603
+ on_response=on_response if on_run_created else None,
604
+ )
605
+
606
+ async def create_batch(
607
+ self,
608
+ payloads: builtins.list[RunCreate],
609
+ *,
610
+ headers: Mapping[str, str] | None = None,
611
+ params: QueryParamTypes | None = None,
612
+ ) -> builtins.list[Run]:
613
+ """Create a batch of stateless background runs."""
614
+
615
+ def filter_payload(payload: RunCreate):
616
+ return {k: v for k, v in payload.items() if v is not None}
617
+
618
+ filtered = [filter_payload(payload) for payload in payloads]
619
+ return await self.http.post(
620
+ "/runs/batch", json=filtered, headers=headers, params=params
621
+ )
622
+
623
+ @overload
624
+ async def wait(
625
+ self,
626
+ thread_id: str,
627
+ assistant_id: str,
628
+ *,
629
+ input: Input | None = None,
630
+ command: Command | None = None,
631
+ metadata: Mapping[str, Any] | None = None,
632
+ config: Config | None = None,
633
+ context: Context | None = None,
634
+ checkpoint: Checkpoint | None = None,
635
+ checkpoint_id: str | None = None,
636
+ checkpoint_during: bool | None = None,
637
+ interrupt_before: All | Sequence[str] | None = None,
638
+ interrupt_after: All | Sequence[str] | None = None,
639
+ webhook: str | None = None,
640
+ on_disconnect: DisconnectMode | None = None,
641
+ multitask_strategy: MultitaskStrategy | None = None,
642
+ if_not_exists: IfNotExists | None = None,
643
+ after_seconds: int | None = None,
644
+ langsmith_tracing: LangSmithTracing | None = None,
645
+ raise_error: bool = True,
646
+ headers: Mapping[str, str] | None = None,
647
+ params: QueryParamTypes | None = None,
648
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
649
+ ) -> builtins.list[dict] | dict[str, Any]: ...
650
+
651
+ @overload
652
+ async def wait(
653
+ self,
654
+ thread_id: None,
655
+ assistant_id: str,
656
+ *,
657
+ input: Input | None = None,
658
+ command: Command | None = None,
659
+ metadata: Mapping[str, Any] | None = None,
660
+ config: Config | None = None,
661
+ context: Context | None = None,
662
+ checkpoint_during: bool | None = None,
663
+ interrupt_before: All | Sequence[str] | None = None,
664
+ interrupt_after: All | Sequence[str] | None = None,
665
+ webhook: str | None = None,
666
+ on_disconnect: DisconnectMode | None = None,
667
+ on_completion: OnCompletionBehavior | None = None,
668
+ if_not_exists: IfNotExists | None = None,
669
+ after_seconds: int | None = None,
670
+ langsmith_tracing: LangSmithTracing | None = None,
671
+ raise_error: bool = True,
672
+ headers: Mapping[str, str] | None = None,
673
+ params: QueryParamTypes | None = None,
674
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
675
+ ) -> builtins.list[dict] | dict[str, Any]: ...
676
+
677
+ async def wait(
678
+ self,
679
+ thread_id: str | None,
680
+ assistant_id: str,
681
+ *,
682
+ input: Input | None = None,
683
+ command: Command | None = None,
684
+ metadata: Mapping[str, Any] | None = None,
685
+ config: Config | None = None,
686
+ context: Context | None = None,
687
+ checkpoint: Checkpoint | None = None,
688
+ checkpoint_id: str | None = None,
689
+ checkpoint_during: bool | None = None, # deprecated
690
+ interrupt_before: All | Sequence[str] | None = None,
691
+ interrupt_after: All | Sequence[str] | None = None,
692
+ webhook: str | None = None,
693
+ on_disconnect: DisconnectMode | None = None,
694
+ on_completion: OnCompletionBehavior | None = None,
695
+ multitask_strategy: MultitaskStrategy | None = None,
696
+ if_not_exists: IfNotExists | None = None,
697
+ after_seconds: int | None = None,
698
+ langsmith_tracing: LangSmithTracing | None = None,
699
+ raise_error: bool = True,
700
+ headers: Mapping[str, str] | None = None,
701
+ params: QueryParamTypes | None = None,
702
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
703
+ durability: Durability | None = None,
704
+ ) -> builtins.list[dict] | dict[str, Any]:
705
+ """Create a run, wait until it finishes and return the final state.
706
+
707
+ Args:
708
+ thread_id: the thread ID to create the run on.
709
+ If `None` will create a stateless run.
710
+ assistant_id: The assistant ID or graph name to run.
711
+ If using graph name, will default to first assistant created from that graph.
712
+ input: The input to the graph.
713
+ command: A command to execute. Cannot be combined with input.
714
+ metadata: Metadata to assign to the run.
715
+ config: The configuration for the assistant.
716
+ context: Static context to add to the assistant.
717
+ !!! version-added "Added in version 0.6.0"
718
+ checkpoint: The checkpoint to resume from.
719
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
720
+ interrupt_before: Nodes to interrupt immediately before they get executed.
721
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
722
+ webhook: Webhook to call after LangGraph API call is done.
723
+ on_disconnect: The disconnect mode to use.
724
+ Must be one of 'cancel' or 'continue'.
725
+ on_completion: Whether to delete or keep the thread created for a stateless run.
726
+ Must be one of 'delete' or 'keep'.
727
+ multitask_strategy: Multitask strategy to use.
728
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
729
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
730
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
731
+ after_seconds: The number of seconds to wait before starting the run.
732
+ Use to schedule future runs.
733
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
734
+ to a specific project or associating with a dataset example.
735
+ headers: Optional custom headers to include with the request.
736
+ on_run_created: Optional callback to call when a run is created.
737
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
738
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
739
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
740
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
741
+
742
+ Returns:
743
+ The output of the run.
744
+
745
+ ???+ example "Example Usage"
746
+
747
+ ```python
748
+ client = get_client(url="http://localhost:2024")
749
+ final_state_of_run = await client.runs.wait(
750
+ thread_id=None,
751
+ assistant_id="agent",
752
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
753
+ metadata={"name":"my_run"},
754
+ context={"model_name": "anthropic"},
755
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
756
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
757
+ webhook="https://my.fake.webhook.com",
758
+ multitask_strategy="interrupt"
759
+ )
760
+ print(final_state_of_run)
761
+ ```
762
+
763
+ ```shell
764
+ -------------------------------------------------------------------------------------------------------------------------------------------
765
+
766
+ {
767
+ 'messages': [
768
+ {
769
+ 'content': 'how are you?',
770
+ 'additional_kwargs': {},
771
+ 'response_metadata': {},
772
+ 'type': 'human',
773
+ 'name': None,
774
+ 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
775
+ 'example': False
776
+ },
777
+ {
778
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
779
+ 'additional_kwargs': {},
780
+ 'response_metadata': {},
781
+ 'type': 'ai',
782
+ 'name': None,
783
+ 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
784
+ 'example': False,
785
+ 'tool_calls': [],
786
+ 'invalid_tool_calls': [],
787
+ 'usage_metadata': None
788
+ }
789
+ ]
790
+ }
791
+ ```
792
+
793
+ """
794
+ if checkpoint_during is not None:
795
+ warnings.warn(
796
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
797
+ DeprecationWarning,
798
+ stacklevel=2,
799
+ )
800
+ payload = {
801
+ "input": input,
802
+ "command": (
803
+ {k: v for k, v in command.items() if v is not None} if command else None
804
+ ),
805
+ "config": config,
806
+ "context": context,
807
+ "metadata": metadata,
808
+ "assistant_id": assistant_id,
809
+ "interrupt_before": interrupt_before,
810
+ "interrupt_after": interrupt_after,
811
+ "webhook": webhook,
812
+ "checkpoint": checkpoint,
813
+ "checkpoint_id": checkpoint_id,
814
+ "multitask_strategy": multitask_strategy,
815
+ "checkpoint_during": checkpoint_during,
816
+ "if_not_exists": if_not_exists,
817
+ "on_disconnect": on_disconnect,
818
+ "on_completion": on_completion,
819
+ "after_seconds": after_seconds,
820
+ "durability": durability,
821
+ "langsmith_tracer": langsmith_tracing,
822
+ }
823
+ endpoint = (
824
+ f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
825
+ )
826
+
827
+ def on_response(res: httpx.Response):
828
+ """Callback function to handle the response."""
829
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
830
+ on_run_created(metadata)
831
+
832
+ response = await self.http.request_reconnect(
833
+ endpoint,
834
+ "POST",
835
+ json={k: v for k, v in payload.items() if v is not None},
836
+ params=params,
837
+ headers=headers,
838
+ on_response=on_response if on_run_created else None,
839
+ )
840
+ if (
841
+ raise_error
842
+ and isinstance(response, dict)
843
+ and "__error__" in response
844
+ and isinstance(response["__error__"], dict)
845
+ ):
846
+ raise Exception(
847
+ f"{response['__error__'].get('error')}: {response['__error__'].get('message')}"
848
+ )
849
+ return response
850
+
851
+ async def list(
852
+ self,
853
+ thread_id: str,
854
+ *,
855
+ limit: int = 10,
856
+ offset: int = 0,
857
+ status: RunStatus | None = None,
858
+ select: builtins.list[RunSelectField] | None = None,
859
+ headers: Mapping[str, str] | None = None,
860
+ params: QueryParamTypes | None = None,
861
+ ) -> builtins.list[Run]:
862
+ """List runs.
863
+
864
+ Args:
865
+ thread_id: The thread ID to list runs for.
866
+ limit: The maximum number of results to return.
867
+ offset: The number of results to skip.
868
+ status: The status of the run to filter by.
869
+ headers: Optional custom headers to include with the request.
870
+ params: Optional query parameters to include with the request.
871
+
872
+ Returns:
873
+ The runs for the thread.
874
+
875
+ ???+ example "Example Usage"
876
+
877
+ ```python
878
+ client = get_client(url="http://localhost:2024")
879
+ await client.runs.list(
880
+ thread_id="thread_id",
881
+ limit=5,
882
+ offset=5,
883
+ )
884
+ ```
885
+
886
+ """
887
+ query_params: dict[str, Any] = {
888
+ "limit": limit,
889
+ "offset": offset,
890
+ }
891
+ if status is not None:
892
+ query_params["status"] = status
893
+ if select:
894
+ query_params["select"] = select
895
+ if params:
896
+ query_params.update(params)
897
+ return await self.http.get(
898
+ f"/threads/{thread_id}/runs", params=query_params, headers=headers
899
+ )
900
+
901
+ async def get(
902
+ self,
903
+ thread_id: str,
904
+ run_id: str,
905
+ *,
906
+ headers: Mapping[str, str] | None = None,
907
+ params: QueryParamTypes | None = None,
908
+ ) -> Run:
909
+ """Get a run.
910
+
911
+ Args:
912
+ thread_id: The thread ID to get.
913
+ run_id: The run ID to get.
914
+ headers: Optional custom headers to include with the request.
915
+ params: Optional query parameters to include with the request.
916
+
917
+ Returns:
918
+ `Run` object.
919
+
920
+ ???+ example "Example Usage"
921
+
922
+ ```python
923
+ client = get_client(url="http://localhost:2024")
924
+ run = await client.runs.get(
925
+ thread_id="thread_id_to_delete",
926
+ run_id="run_id_to_delete",
927
+ )
928
+ ```
929
+
930
+ """
931
+
932
+ return await self.http.get(
933
+ f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
934
+ )
935
+
936
+ async def cancel(
937
+ self,
938
+ thread_id: str,
939
+ run_id: str,
940
+ *,
941
+ wait: bool = False,
942
+ action: CancelAction = "interrupt",
943
+ headers: Mapping[str, str] | None = None,
944
+ params: QueryParamTypes | None = None,
945
+ ) -> None:
946
+ """Get a run.
947
+
948
+ Args:
949
+ thread_id: The thread ID to cancel.
950
+ run_id: The run ID to cancel.
951
+ wait: Whether to wait until run has completed.
952
+ action: Action to take when cancelling the run. Possible values
953
+ are `interrupt` or `rollback`. Default is `interrupt`.
954
+ headers: Optional custom headers to include with the request.
955
+ params: Optional query parameters to include with the request.
956
+
957
+ Returns:
958
+ `None`
959
+
960
+ ???+ example "Example Usage"
961
+
962
+ ```python
963
+ client = get_client(url="http://localhost:2024")
964
+ await client.runs.cancel(
965
+ thread_id="thread_id_to_cancel",
966
+ run_id="run_id_to_cancel",
967
+ wait=True,
968
+ action="interrupt"
969
+ )
970
+ ```
971
+
972
+ """
973
+ query_params = {
974
+ "wait": 1 if wait else 0,
975
+ "action": action,
976
+ }
977
+ if params:
978
+ query_params.update(params)
979
+ if wait:
980
+ return await self.http.request_reconnect(
981
+ f"/threads/{thread_id}/runs/{run_id}/cancel",
982
+ "POST",
983
+ params=query_params,
984
+ headers=headers,
985
+ )
986
+ else:
987
+ return await self.http.post(
988
+ f"/threads/{thread_id}/runs/{run_id}/cancel",
989
+ json=None,
990
+ params=query_params,
991
+ headers=headers,
992
+ )
993
+
994
+ async def cancel_many(
995
+ self,
996
+ *,
997
+ thread_id: str | None = None,
998
+ run_ids: Sequence[str] | None = None,
999
+ status: BulkCancelRunsStatus | None = None,
1000
+ action: CancelAction = "interrupt",
1001
+ headers: Mapping[str, str] | None = None,
1002
+ params: QueryParamTypes | None = None,
1003
+ ) -> None:
1004
+ """Cancel one or more runs.
1005
+
1006
+ Can cancel runs by thread ID and run IDs, or by status filter.
1007
+
1008
+ Args:
1009
+ thread_id: The ID of the thread containing runs to cancel.
1010
+ run_ids: List of run IDs to cancel.
1011
+ status: Filter runs by status to cancel. Must be one of
1012
+ `"pending"`, `"running"`, or `"all"`.
1013
+ action: Action to take when cancelling the run. Possible values
1014
+ are `"interrupt"` or `"rollback"`. Default is `"interrupt"`.
1015
+ headers: Optional custom headers to include with the request.
1016
+ params: Optional query parameters to include with the request.
1017
+
1018
+ Returns:
1019
+ `None`
1020
+
1021
+ ???+ example "Example Usage"
1022
+
1023
+ ```python
1024
+ client = get_client(url="http://localhost:2024")
1025
+ # Cancel all pending runs
1026
+ await client.runs.cancel_many(status="pending")
1027
+ # Cancel specific runs on a thread
1028
+ await client.runs.cancel_many(
1029
+ thread_id="my_thread_id",
1030
+ run_ids=["run_1", "run_2"],
1031
+ action="rollback",
1032
+ )
1033
+ ```
1034
+
1035
+ """
1036
+ payload: dict[str, Any] = {}
1037
+ if thread_id:
1038
+ payload["thread_id"] = thread_id
1039
+ if run_ids:
1040
+ payload["run_ids"] = run_ids
1041
+ if status:
1042
+ payload["status"] = status
1043
+ query_params: dict[str, Any] = {"action": action}
1044
+ if params:
1045
+ query_params.update(params)
1046
+ await self.http.post(
1047
+ "/runs/cancel",
1048
+ json=payload,
1049
+ headers=headers,
1050
+ params=query_params,
1051
+ )
1052
+
1053
+ async def join(
1054
+ self,
1055
+ thread_id: str,
1056
+ run_id: str,
1057
+ *,
1058
+ headers: Mapping[str, str] | None = None,
1059
+ params: QueryParamTypes | None = None,
1060
+ ) -> dict:
1061
+ """Block until a run is done. Returns the final state of the thread.
1062
+
1063
+ Args:
1064
+ thread_id: The thread ID to join.
1065
+ run_id: The run ID to join.
1066
+ headers: Optional custom headers to include with the request.
1067
+ params: Optional query parameters to include with the request.
1068
+
1069
+ Returns:
1070
+ `None`
1071
+
1072
+ ???+ example "Example Usage"
1073
+
1074
+ ```python
1075
+ client = get_client(url="http://localhost:2024")
1076
+ result =await client.runs.join(
1077
+ thread_id="thread_id_to_join",
1078
+ run_id="run_id_to_join"
1079
+ )
1080
+ ```
1081
+
1082
+ """
1083
+ return await self.http.request_reconnect(
1084
+ f"/threads/{thread_id}/runs/{run_id}/join",
1085
+ "GET",
1086
+ headers=headers,
1087
+ params=params,
1088
+ )
1089
+
1090
+ def join_stream(
1091
+ self,
1092
+ thread_id: str,
1093
+ run_id: str,
1094
+ *,
1095
+ cancel_on_disconnect: bool = False,
1096
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
1097
+ headers: Mapping[str, str] | None = None,
1098
+ params: QueryParamTypes | None = None,
1099
+ last_event_id: str | None = None,
1100
+ ) -> AsyncIterator[StreamPart]:
1101
+ """Stream output from a run in real-time, until the run is done.
1102
+ Output is not buffered, so any output produced before this call will
1103
+ not be received here.
1104
+
1105
+ Args:
1106
+ thread_id: The thread ID to join.
1107
+ run_id: The run ID to join.
1108
+ cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
1109
+ stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
1110
+ when creating the run. Background runs default to having the union of all
1111
+ stream modes.
1112
+ headers: Optional custom headers to include with the request.
1113
+ params: Optional query parameters to include with the request.
1114
+ last_event_id: The last event ID to use for the stream.
1115
+
1116
+ Returns:
1117
+ The stream of parts.
1118
+
1119
+ ???+ example "Example Usage"
1120
+
1121
+ ```python
1122
+ client = get_client(url="http://localhost:2024")
1123
+ async for part in client.runs.join_stream(
1124
+ thread_id="thread_id_to_join",
1125
+ run_id="run_id_to_join",
1126
+ stream_mode=["values", "debug"]
1127
+ ):
1128
+ print(part)
1129
+ ```
1130
+
1131
+ """
1132
+ query_params = {
1133
+ "cancel_on_disconnect": cancel_on_disconnect,
1134
+ "stream_mode": stream_mode,
1135
+ }
1136
+ if params:
1137
+ query_params.update(params)
1138
+ return self.http.stream(
1139
+ f"/threads/{thread_id}/runs/{run_id}/stream",
1140
+ "GET",
1141
+ params=query_params,
1142
+ headers={
1143
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
1144
+ **(headers or {}),
1145
+ }
1146
+ or None,
1147
+ )
1148
+
1149
+ async def delete(
1150
+ self,
1151
+ thread_id: str,
1152
+ run_id: str,
1153
+ *,
1154
+ headers: Mapping[str, str] | None = None,
1155
+ params: QueryParamTypes | None = None,
1156
+ ) -> None:
1157
+ """Delete a run.
1158
+
1159
+ Args:
1160
+ thread_id: The thread ID to delete.
1161
+ run_id: The run ID to delete.
1162
+ headers: Optional custom headers to include with the request.
1163
+ params: Optional query parameters to include with the request.
1164
+
1165
+ Returns:
1166
+ `None`
1167
+
1168
+ ???+ example "Example Usage"
1169
+
1170
+ ```python
1171
+ client = get_client(url="http://localhost:2024")
1172
+ await client.runs.delete(
1173
+ thread_id="thread_id_to_delete",
1174
+ run_id="run_id_to_delete"
1175
+ )
1176
+ ```
1177
+
1178
+ """
1179
+ await self.http.delete(
1180
+ f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
1181
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_async/store.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async Store client for LangGraph SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from typing import Any, Literal
7
+
8
+ from langgraph_sdk._async.http import HttpClient
9
+ from langgraph_sdk._shared.utilities import _provided_vals
10
+ from langgraph_sdk.schema import (
11
+ Item,
12
+ ListNamespaceResponse,
13
+ QueryParamTypes,
14
+ SearchItemsResponse,
15
+ )
16
+
17
+
18
+ class StoreClient:
19
+ """Client for interacting with the graph's shared storage.
20
+
21
+ The Store provides a key-value storage system for persisting data across graph executions,
22
+ allowing for stateful operations and data sharing across threads.
23
+
24
+ ???+ example "Example"
25
+
26
+ ```python
27
+ client = get_client(url="http://localhost:2024")
28
+ await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})
29
+ ```
30
+ """
31
+
32
+ def __init__(self, http: HttpClient) -> None:
33
+ self.http = http
34
+
35
+ async def put_item(
36
+ self,
37
+ namespace: Sequence[str],
38
+ /,
39
+ key: str,
40
+ value: Mapping[str, Any],
41
+ index: Literal[False] | list[str] | None = None,
42
+ ttl: int | None = None,
43
+ headers: Mapping[str, str] | None = None,
44
+ params: QueryParamTypes | None = None,
45
+ ) -> None:
46
+ """Store or update an item.
47
+
48
+ Args:
49
+ namespace: A list of strings representing the namespace path.
50
+ key: The unique identifier for the item within the namespace.
51
+ value: A dictionary containing the item's data.
52
+ index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
53
+ ttl: Optional time-to-live in minutes for the item, or None for no expiration.
54
+ headers: Optional custom headers to include with the request.
55
+ params: Optional query parameters to include with the request.
56
+
57
+ Returns:
58
+ `None`
59
+
60
+ ???+ example "Example Usage"
61
+
62
+ ```python
63
+ client = get_client(url="http://localhost:2024")
64
+ await client.store.put_item(
65
+ ["documents", "user123"],
66
+ key="item456",
67
+ value={"title": "My Document", "content": "Hello World"}
68
+ )
69
+ ```
70
+ """
71
+ for label in namespace:
72
+ if "." in label:
73
+ raise ValueError(
74
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
75
+ )
76
+ payload = {
77
+ "namespace": namespace,
78
+ "key": key,
79
+ "value": value,
80
+ "index": index,
81
+ "ttl": ttl,
82
+ }
83
+ await self.http.put(
84
+ "/store/items", json=_provided_vals(payload), headers=headers, params=params
85
+ )
86
+
87
+ async def get_item(
88
+ self,
89
+ namespace: Sequence[str],
90
+ /,
91
+ key: str,
92
+ *,
93
+ refresh_ttl: bool | None = None,
94
+ headers: Mapping[str, str] | None = None,
95
+ params: QueryParamTypes | None = None,
96
+ ) -> Item:
97
+ """Retrieve a single item.
98
+
99
+ Args:
100
+ key: The unique identifier for the item.
101
+ namespace: Optional list of strings representing the namespace path.
102
+ refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
103
+
104
+ Returns:
105
+ Item: The retrieved item.
106
+ headers: Optional custom headers to include with the request.
107
+ params: Optional query parameters to include with the request.
108
+
109
+ ???+ example "Example Usage"
110
+
111
+ ```python
112
+ client = get_client(url="http://localhost:2024")
113
+ item = await client.store.get_item(
114
+ ["documents", "user123"],
115
+ key="item456",
116
+ )
117
+ print(item)
118
+ ```
119
+ ```shell
120
+
121
+ ----------------------------------------------------------------
122
+
123
+ {
124
+ 'namespace': ['documents', 'user123'],
125
+ 'key': 'item456',
126
+ 'value': {'title': 'My Document', 'content': 'Hello World'},
127
+ 'created_at': '2024-07-30T12:00:00Z',
128
+ 'updated_at': '2024-07-30T12:00:00Z'
129
+ }
130
+ ```
131
+ """
132
+ for label in namespace:
133
+ if "." in label:
134
+ raise ValueError(
135
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
136
+ )
137
+ get_params: dict[str, Any] = {"namespace": ".".join(namespace), "key": key}
138
+ if refresh_ttl is not None:
139
+ get_params["refresh_ttl"] = refresh_ttl
140
+ if params:
141
+ get_params = {**get_params, **dict(params)}
142
+ return await self.http.get("/store/items", params=get_params, headers=headers)
143
+
144
+ async def delete_item(
145
+ self,
146
+ namespace: Sequence[str],
147
+ /,
148
+ key: str,
149
+ headers: Mapping[str, str] | None = None,
150
+ params: QueryParamTypes | None = None,
151
+ ) -> None:
152
+ """Delete an item.
153
+
154
+ Args:
155
+ key: The unique identifier for the item.
156
+ namespace: Optional list of strings representing the namespace path.
157
+ headers: Optional custom headers to include with the request.
158
+ params: Optional query parameters to include with the request.
159
+
160
+ Returns:
161
+ `None`
162
+
163
+ ???+ example "Example Usage"
164
+
165
+ ```python
166
+ client = get_client(url="http://localhost:2024")
167
+ await client.store.delete_item(
168
+ ["documents", "user123"],
169
+ key="item456",
170
+ )
171
+ ```
172
+ """
173
+ await self.http.delete(
174
+ "/store/items",
175
+ json={"namespace": namespace, "key": key},
176
+ headers=headers,
177
+ params=params,
178
+ )
179
+
180
+ async def search_items(
181
+ self,
182
+ namespace_prefix: Sequence[str],
183
+ /,
184
+ filter: Mapping[str, Any] | None = None,
185
+ limit: int = 10,
186
+ offset: int = 0,
187
+ query: str | None = None,
188
+ refresh_ttl: bool | None = None,
189
+ headers: Mapping[str, str] | None = None,
190
+ params: QueryParamTypes | None = None,
191
+ ) -> SearchItemsResponse:
192
+ """Search for items within a namespace prefix.
193
+
194
+ Args:
195
+ namespace_prefix: List of strings representing the namespace prefix.
196
+ filter: Optional dictionary of key-value pairs to filter results.
197
+ limit: Maximum number of items to return (default is 10).
198
+ offset: Number of items to skip before returning results (default is 0).
199
+ query: Optional query for natural language search.
200
+ refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
201
+ headers: Optional custom headers to include with the request.
202
+ params: Optional query parameters to include with the request.
203
+
204
+ Returns:
205
+ A list of items matching the search criteria.
206
+
207
+ ???+ example "Example Usage"
208
+
209
+ ```python
210
+ client = get_client(url="http://localhost:2024")
211
+ items = await client.store.search_items(
212
+ ["documents"],
213
+ filter={"author": "John Doe"},
214
+ limit=5,
215
+ offset=0
216
+ )
217
+ print(items)
218
+ ```
219
+ ```shell
220
+
221
+ ----------------------------------------------------------------
222
+
223
+ {
224
+ "items": [
225
+ {
226
+ "namespace": ["documents", "user123"],
227
+ "key": "item789",
228
+ "value": {
229
+ "title": "Another Document",
230
+ "author": "John Doe"
231
+ },
232
+ "created_at": "2024-07-30T12:00:00Z",
233
+ "updated_at": "2024-07-30T12:00:00Z"
234
+ },
235
+ # ... additional items ...
236
+ ]
237
+ }
238
+ ```
239
+ """
240
+ payload = {
241
+ "namespace_prefix": namespace_prefix,
242
+ "filter": filter,
243
+ "limit": limit,
244
+ "offset": offset,
245
+ "query": query,
246
+ "refresh_ttl": refresh_ttl,
247
+ }
248
+
249
+ return await self.http.post(
250
+ "/store/items/search",
251
+ json=_provided_vals(payload),
252
+ headers=headers,
253
+ params=params,
254
+ )
255
+
256
+ async def list_namespaces(
257
+ self,
258
+ prefix: list[str] | None = None,
259
+ suffix: list[str] | None = None,
260
+ max_depth: int | None = None,
261
+ limit: int = 100,
262
+ offset: int = 0,
263
+ headers: Mapping[str, str] | None = None,
264
+ params: QueryParamTypes | None = None,
265
+ ) -> ListNamespaceResponse:
266
+ """List namespaces with optional match conditions.
267
+
268
+ Args:
269
+ prefix: Optional list of strings representing the prefix to filter namespaces.
270
+ suffix: Optional list of strings representing the suffix to filter namespaces.
271
+ max_depth: Optional integer specifying the maximum depth of namespaces to return.
272
+ limit: Maximum number of namespaces to return (default is 100).
273
+ offset: Number of namespaces to skip before returning results (default is 0).
274
+ headers: Optional custom headers to include with the request.
275
+ params: Optional query parameters to include with the request.
276
+
277
+ Returns:
278
+ A list of namespaces matching the criteria.
279
+
280
+ ???+ example "Example Usage"
281
+
282
+ ```python
283
+ client = get_client(url="http://localhost:2024")
284
+ namespaces = await client.store.list_namespaces(
285
+ prefix=["documents"],
286
+ max_depth=3,
287
+ limit=10,
288
+ offset=0
289
+ )
290
+ print(namespaces)
291
+
292
+ ----------------------------------------------------------------
293
+
294
+ [
295
+ ["documents", "user123", "reports"],
296
+ ["documents", "user456", "invoices"],
297
+ ...
298
+ ]
299
+ ```
300
+ """
301
+ payload = {
302
+ "prefix": prefix,
303
+ "suffix": suffix,
304
+ "max_depth": max_depth,
305
+ "limit": limit,
306
+ "offset": offset,
307
+ }
308
+ return await self.http.post(
309
+ "/store/namespaces",
310
+ json=_provided_vals(payload),
311
+ headers=headers,
312
+ params=params,
313
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_async/threads.py ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client for managing threads in LangGraph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Mapping, Sequence
6
+ from typing import Any, Literal, overload
7
+
8
+ from langgraph_sdk._async.http import HttpClient
9
+ from langgraph_sdk.schema import (
10
+ Checkpoint,
11
+ Json,
12
+ OnConflictBehavior,
13
+ PruneStrategy,
14
+ QueryParamTypes,
15
+ SortOrder,
16
+ StreamPart,
17
+ Thread,
18
+ ThreadSelectField,
19
+ ThreadSortBy,
20
+ ThreadState,
21
+ ThreadStatus,
22
+ ThreadStreamMode,
23
+ ThreadUpdateStateResponse,
24
+ )
25
+
26
+
27
+ class ThreadsClient:
28
+ """Client for managing threads in LangGraph.
29
+
30
+ A thread maintains the state of a graph across multiple interactions/invocations (aka runs).
31
+ It accumulates and persists the graph's state, allowing for continuity between separate
32
+ invocations of the graph.
33
+
34
+ ???+ example "Example"
35
+
36
+ ```python
37
+ client = get_client(url="http://localhost:2024"))
38
+ new_thread = await client.threads.create(metadata={"user_id": "123"})
39
+ ```
40
+ """
41
+
42
+ def __init__(self, http: HttpClient) -> None:
43
+ self.http = http
44
+
45
+ async def get(
46
+ self,
47
+ thread_id: str,
48
+ *,
49
+ include: Sequence[str] | None = None,
50
+ headers: Mapping[str, str] | None = None,
51
+ params: QueryParamTypes | None = None,
52
+ ) -> Thread:
53
+ """Get a thread by ID.
54
+
55
+ Args:
56
+ thread_id: The ID of the thread to get.
57
+ include: Additional fields to include in the response.
58
+ Supported values: `"ttl"`.
59
+ headers: Optional custom headers to include with the request.
60
+ params: Optional query parameters to include with the request.
61
+
62
+ Returns:
63
+ Thread object.
64
+
65
+ ???+ example "Example Usage"
66
+
67
+ ```python
68
+ client = get_client(url="http://localhost:2024")
69
+ thread = await client.threads.get(
70
+ thread_id="my_thread_id"
71
+ )
72
+ print(thread)
73
+ ```
74
+
75
+ ```shell
76
+ -----------------------------------------------------
77
+
78
+ {
79
+ 'thread_id': 'my_thread_id',
80
+ 'created_at': '2024-07-18T18:35:15.540834+00:00',
81
+ 'updated_at': '2024-07-18T18:35:15.540834+00:00',
82
+ 'metadata': {'graph_id': 'agent'}
83
+ }
84
+ ```
85
+
86
+ """
87
+ query_params: dict[str, Any] = {}
88
+ if include:
89
+ query_params["include"] = ",".join(include)
90
+ if params:
91
+ query_params.update(params)
92
+ return await self.http.get(
93
+ f"/threads/{thread_id}",
94
+ headers=headers,
95
+ params=query_params or None,
96
+ )
97
+
98
+ async def create(
99
+ self,
100
+ *,
101
+ metadata: Json = None,
102
+ thread_id: str | None = None,
103
+ if_exists: OnConflictBehavior | None = None,
104
+ supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
105
+ graph_id: str | None = None,
106
+ ttl: int | Mapping[str, Any] | None = None,
107
+ headers: Mapping[str, str] | None = None,
108
+ params: QueryParamTypes | None = None,
109
+ ) -> Thread:
110
+ """Create a new thread.
111
+
112
+ Args:
113
+ metadata: Metadata to add to thread.
114
+ thread_id: ID of thread.
115
+ If `None`, ID will be a randomly generated UUID.
116
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
117
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
118
+ supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
119
+ Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
120
+ graph_id: Optional graph ID to associate with the thread.
121
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
122
+ integer (minutes) or a mapping with keys `ttl` and optional
123
+ `strategy` (defaults to "delete").
124
+ headers: Optional custom headers to include with the request.
125
+ params: Optional query parameters to include with the request.
126
+
127
+ Returns:
128
+ The created thread.
129
+
130
+ ???+ example "Example Usage"
131
+
132
+ ```python
133
+ client = get_client(url="http://localhost:2024")
134
+ thread = await client.threads.create(
135
+ metadata={"number":1},
136
+ thread_id="my-thread-id",
137
+ if_exists="raise"
138
+ )
139
+ ```
140
+ """
141
+ payload: dict[str, Any] = {}
142
+ if thread_id:
143
+ payload["thread_id"] = thread_id
144
+ if metadata or graph_id:
145
+ payload["metadata"] = {
146
+ **(metadata or {}),
147
+ **({"graph_id": graph_id} if graph_id else {}),
148
+ }
149
+ if if_exists:
150
+ payload["if_exists"] = if_exists
151
+ if supersteps:
152
+ payload["supersteps"] = [
153
+ {
154
+ "updates": [
155
+ {
156
+ "values": u["values"],
157
+ "command": u.get("command"),
158
+ "as_node": u["as_node"],
159
+ }
160
+ for u in s["updates"]
161
+ ]
162
+ }
163
+ for s in supersteps
164
+ ]
165
+ if ttl is not None:
166
+ if isinstance(ttl, (int, float)):
167
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
168
+ else:
169
+ payload["ttl"] = ttl
170
+
171
+ return await self.http.post(
172
+ "/threads", json=payload, headers=headers, params=params
173
+ )
174
+
175
+ @overload
176
+ async def update(
177
+ self,
178
+ thread_id: str,
179
+ *,
180
+ metadata: Mapping[str, Any],
181
+ ttl: int | Mapping[str, Any] | None = None,
182
+ return_minimal: Literal[False] = False,
183
+ headers: Mapping[str, str] | None = None,
184
+ params: QueryParamTypes | None = None,
185
+ ) -> Thread: ...
186
+
187
+ @overload
188
+ async def update(
189
+ self,
190
+ thread_id: str,
191
+ *,
192
+ metadata: Mapping[str, Any],
193
+ ttl: int | Mapping[str, Any] | None = None,
194
+ return_minimal: Literal[True],
195
+ headers: Mapping[str, str] | None = None,
196
+ params: QueryParamTypes | None = None,
197
+ ) -> None: ...
198
+
199
+ @overload
200
+ async def update(
201
+ self,
202
+ thread_id: str,
203
+ *,
204
+ metadata: Mapping[str, Any],
205
+ ttl: int | Mapping[str, Any] | None = None,
206
+ return_minimal: bool,
207
+ headers: Mapping[str, str] | None = None,
208
+ params: QueryParamTypes | None = None,
209
+ ) -> Thread | None: ...
210
+
211
+ async def update(
212
+ self,
213
+ thread_id: str,
214
+ *,
215
+ metadata: Mapping[str, Any],
216
+ ttl: int | Mapping[str, Any] | None = None,
217
+ return_minimal: bool = False,
218
+ headers: Mapping[str, str] | None = None,
219
+ params: QueryParamTypes | None = None,
220
+ ) -> Thread | None:
221
+ """Update a thread.
222
+
223
+ Args:
224
+ thread_id: ID of thread to update.
225
+ metadata: Metadata to merge with existing thread metadata.
226
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
227
+ integer (minutes) or a mapping with keys `ttl` and optional
228
+ `strategy` (defaults to "delete").
229
+ return_minimal: If `True`, request a 204 response with no body.
230
+ headers: Optional custom headers to include with the request.
231
+ params: Optional query parameters to include with the request.
232
+
233
+ Returns:
234
+ The updated thread, or `None` when `return_minimal=True`.
235
+
236
+ ???+ example "Example Usage"
237
+
238
+ ```python
239
+ client = get_client(url="http://localhost:2024")
240
+ thread = await client.threads.update(
241
+ thread_id="my-thread-id",
242
+ metadata={"number":1},
243
+ ttl=43_200,
244
+ )
245
+ ```
246
+ """
247
+ payload: dict[str, Any] = {"metadata": metadata}
248
+ if ttl is not None:
249
+ if isinstance(ttl, (int, float)):
250
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
251
+ else:
252
+ payload["ttl"] = ttl
253
+ request_headers = dict(headers or {})
254
+ if return_minimal:
255
+ request_headers["Prefer"] = "return=minimal"
256
+ return await self.http.patch(
257
+ f"/threads/{thread_id}",
258
+ json=payload,
259
+ headers=request_headers or None,
260
+ params=params,
261
+ )
262
+
263
+ async def delete(
264
+ self,
265
+ thread_id: str,
266
+ *,
267
+ headers: Mapping[str, str] | None = None,
268
+ params: QueryParamTypes | None = None,
269
+ ) -> None:
270
+ """Delete a thread.
271
+
272
+ Args:
273
+ thread_id: The ID of the thread to delete.
274
+ headers: Optional custom headers to include with the request.
275
+ params: Optional query parameters to include with the request.
276
+
277
+ Returns:
278
+ `None`
279
+
280
+ ???+ example "Example Usage"
281
+
282
+ ```python
283
+ client = get_client(url="http://localhost2024)
284
+ await client.threads.delete(
285
+ thread_id="my_thread_id"
286
+ )
287
+ ```
288
+
289
+ """
290
+ await self.http.delete(f"/threads/{thread_id}", headers=headers, params=params)
291
+
292
+ async def search(
293
+ self,
294
+ *,
295
+ metadata: Json = None,
296
+ values: Json = None,
297
+ ids: Sequence[str] | None = None,
298
+ status: ThreadStatus | None = None,
299
+ limit: int = 10,
300
+ offset: int = 0,
301
+ sort_by: ThreadSortBy | None = None,
302
+ sort_order: SortOrder | None = None,
303
+ select: list[ThreadSelectField] | None = None,
304
+ extract: dict[str, str] | None = None,
305
+ headers: Mapping[str, str] | None = None,
306
+ params: QueryParamTypes | None = None,
307
+ ) -> list[Thread]:
308
+ """Search for threads.
309
+
310
+ Args:
311
+ metadata: Thread metadata to filter on.
312
+ values: State values to filter on.
313
+ ids: List of thread IDs to filter by.
314
+ status: Thread status to filter on.
315
+ Must be one of 'idle', 'busy', 'interrupted' or 'error'.
316
+ limit: Limit on number of threads to return.
317
+ offset: Offset in threads table to start search from.
318
+ sort_by: Sort by field.
319
+ sort_order: Sort order.
320
+ select: List of fields to include in the response.
321
+ extract: Dictionary mapping aliases to JSONB paths to extract
322
+ from thread data. Paths use dot notation for nested keys and
323
+ bracket notation for array indices (e.g.,
324
+ `{"last_msg": "values.messages[-1]"}`). Extracted values are
325
+ returned in an `extracted` field on each thread. Maximum 10
326
+ paths per request.
327
+ headers: Optional custom headers to include with the request.
328
+ params: Optional query parameters to include with the request.
329
+
330
+ Returns:
331
+ List of the threads matching the search parameters.
332
+
333
+ ???+ example "Example Usage"
334
+
335
+ ```python
336
+ client = get_client(url="http://localhost:2024")
337
+ threads = await client.threads.search(
338
+ metadata={"number":1},
339
+ status="interrupted",
340
+ limit=15,
341
+ offset=5
342
+ )
343
+ ```
344
+
345
+ """
346
+ payload: dict[str, Any] = {
347
+ "limit": limit,
348
+ "offset": offset,
349
+ }
350
+ if metadata:
351
+ payload["metadata"] = metadata
352
+ if values:
353
+ payload["values"] = values
354
+ if ids:
355
+ payload["ids"] = ids
356
+ if status:
357
+ payload["status"] = status
358
+ if sort_by:
359
+ payload["sort_by"] = sort_by
360
+ if sort_order:
361
+ payload["sort_order"] = sort_order
362
+ if select:
363
+ payload["select"] = select
364
+ if extract:
365
+ payload["extract"] = extract
366
+ return await self.http.post(
367
+ "/threads/search",
368
+ json=payload,
369
+ headers=headers,
370
+ params=params,
371
+ )
372
+
373
+ async def count(
374
+ self,
375
+ *,
376
+ metadata: Json = None,
377
+ values: Json = None,
378
+ status: ThreadStatus | None = None,
379
+ headers: Mapping[str, str] | None = None,
380
+ params: QueryParamTypes | None = None,
381
+ ) -> int:
382
+ """Count threads matching filters.
383
+
384
+ Args:
385
+ metadata: Thread metadata to filter on.
386
+ values: State values to filter on.
387
+ status: Thread status to filter on.
388
+ headers: Optional custom headers to include with the request.
389
+ params: Optional query parameters to include with the request.
390
+
391
+ Returns:
392
+ int: Number of threads matching the criteria.
393
+ """
394
+ payload: dict[str, Any] = {}
395
+ if metadata:
396
+ payload["metadata"] = metadata
397
+ if values:
398
+ payload["values"] = values
399
+ if status:
400
+ payload["status"] = status
401
+ return await self.http.post(
402
+ "/threads/count", json=payload, headers=headers, params=params
403
+ )
404
+
405
+ async def copy(
406
+ self,
407
+ thread_id: str,
408
+ *,
409
+ headers: Mapping[str, str] | None = None,
410
+ params: QueryParamTypes | None = None,
411
+ ) -> None:
412
+ """Copy a thread.
413
+
414
+ Args:
415
+ thread_id: The ID of the thread to copy.
416
+ headers: Optional custom headers to include with the request.
417
+ params: Optional query parameters to include with the request.
418
+
419
+ Returns:
420
+ `None`
421
+
422
+ ???+ example "Example Usage"
423
+
424
+ ```python
425
+ client = get_client(url="http://localhost:2024)
426
+ await client.threads.copy(
427
+ thread_id="my_thread_id"
428
+ )
429
+ ```
430
+
431
+ """
432
+ return await self.http.post(
433
+ f"/threads/{thread_id}/copy", json=None, headers=headers, params=params
434
+ )
435
+
436
+ async def prune(
437
+ self,
438
+ thread_ids: Sequence[str],
439
+ *,
440
+ strategy: PruneStrategy = "delete",
441
+ headers: Mapping[str, str] | None = None,
442
+ params: QueryParamTypes | None = None,
443
+ ) -> dict[str, Any]:
444
+ """Prune threads by ID.
445
+
446
+ Args:
447
+ thread_ids: List of thread IDs to prune.
448
+ strategy: The prune strategy. `"delete"` removes threads entirely.
449
+ `"keep_latest"` prunes old checkpoints but keeps threads and their
450
+ latest state. Defaults to `"delete"`.
451
+ headers: Optional custom headers to include with the request.
452
+ params: Optional query parameters to include with the request.
453
+
454
+ Returns:
455
+ A dict containing `pruned_count` (number of threads pruned).
456
+
457
+ ???+ example "Example Usage"
458
+
459
+ ```python
460
+ client = get_client(url="http://localhost:2024")
461
+ result = await client.threads.prune(
462
+ thread_ids=["thread_1", "thread_2"],
463
+ )
464
+ print(result) # {'pruned_count': 2}
465
+ ```
466
+
467
+ """
468
+ payload: dict[str, Any] = {
469
+ "thread_ids": thread_ids,
470
+ }
471
+ if strategy != "delete":
472
+ payload["strategy"] = strategy
473
+ return await self.http.post(
474
+ "/threads/prune", json=payload, headers=headers, params=params
475
+ )
476
+
477
+ async def get_state(
478
+ self,
479
+ thread_id: str,
480
+ checkpoint: Checkpoint | None = None,
481
+ checkpoint_id: str | None = None, # deprecated
482
+ *,
483
+ subgraphs: bool = False,
484
+ headers: Mapping[str, str] | None = None,
485
+ params: QueryParamTypes | None = None,
486
+ ) -> ThreadState:
487
+ """Get the state of a thread.
488
+
489
+ Args:
490
+ thread_id: The ID of the thread to get the state of.
491
+ checkpoint: The checkpoint to get the state of.
492
+ checkpoint_id: (deprecated) The checkpoint ID to get the state of.
493
+ subgraphs: Include subgraphs states.
494
+ headers: Optional custom headers to include with the request.
495
+ params: Optional query parameters to include with the request.
496
+
497
+ Returns:
498
+ The thread of the state.
499
+
500
+ ???+ example "Example Usage"
501
+
502
+ ```python
503
+ client = get_client(url="http://localhost:2024)
504
+ thread_state = await client.threads.get_state(
505
+ thread_id="my_thread_id",
506
+ checkpoint_id="my_checkpoint_id"
507
+ )
508
+ print(thread_state)
509
+ ```
510
+
511
+ ```shell
512
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
513
+
514
+ {
515
+ 'values': {
516
+ 'messages': [
517
+ {
518
+ 'content': 'how are you?',
519
+ 'additional_kwargs': {},
520
+ 'response_metadata': {},
521
+ 'type': 'human',
522
+ 'name': None,
523
+ 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
524
+ 'example': False
525
+ },
526
+ {
527
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
528
+ 'additional_kwargs': {},
529
+ 'response_metadata': {},
530
+ 'type': 'ai',
531
+ 'name': None,
532
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
533
+ 'example': False,
534
+ 'tool_calls': [],
535
+ 'invalid_tool_calls': [],
536
+ 'usage_metadata': None
537
+ }
538
+ ]
539
+ },
540
+ 'next': [],
541
+ 'checkpoint':
542
+ {
543
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
544
+ 'checkpoint_ns': '',
545
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
546
+ }
547
+ 'metadata':
548
+ {
549
+ 'step': 1,
550
+ 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
551
+ 'source': 'loop',
552
+ 'writes':
553
+ {
554
+ 'agent':
555
+ {
556
+ 'messages': [
557
+ {
558
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
559
+ 'name': None,
560
+ 'type': 'ai',
561
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
562
+ 'example': False,
563
+ 'tool_calls': [],
564
+ 'usage_metadata': None,
565
+ 'additional_kwargs': {},
566
+ 'response_metadata': {},
567
+ 'invalid_tool_calls': []
568
+ }
569
+ ]
570
+ }
571
+ },
572
+ 'user_id': None,
573
+ 'graph_id': 'agent',
574
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
575
+ 'created_by': 'system',
576
+ 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
577
+ 'created_at': '2024-07-25T15:35:44.184703+00:00',
578
+ 'parent_config':
579
+ {
580
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
581
+ 'checkpoint_ns': '',
582
+ 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
583
+ }
584
+ }
585
+ ```
586
+ """
587
+ if checkpoint:
588
+ return await self.http.post(
589
+ f"/threads/{thread_id}/state/checkpoint",
590
+ json={"checkpoint": checkpoint, "subgraphs": subgraphs},
591
+ headers=headers,
592
+ params=params,
593
+ )
594
+ elif checkpoint_id:
595
+ get_params = {"subgraphs": subgraphs}
596
+ if params:
597
+ get_params = {**get_params, **dict(params)}
598
+ return await self.http.get(
599
+ f"/threads/{thread_id}/state/{checkpoint_id}",
600
+ params=get_params,
601
+ headers=headers,
602
+ )
603
+ else:
604
+ get_params = {"subgraphs": subgraphs}
605
+ if params:
606
+ get_params = {**get_params, **dict(params)}
607
+ return await self.http.get(
608
+ f"/threads/{thread_id}/state",
609
+ params=get_params,
610
+ headers=headers,
611
+ )
612
+
613
+ async def update_state(
614
+ self,
615
+ thread_id: str,
616
+ values: dict[str, Any] | Sequence[dict] | None,
617
+ *,
618
+ as_node: str | None = None,
619
+ checkpoint: Checkpoint | None = None,
620
+ checkpoint_id: str | None = None, # deprecated
621
+ headers: Mapping[str, str] | None = None,
622
+ params: QueryParamTypes | None = None,
623
+ ) -> ThreadUpdateStateResponse:
624
+ """Update the state of a thread.
625
+
626
+ Args:
627
+ thread_id: The ID of the thread to update.
628
+ values: The values to update the state with.
629
+ as_node: Update the state as if this node had just executed.
630
+ checkpoint: The checkpoint to update the state of.
631
+ checkpoint_id: (deprecated) The checkpoint ID to update the state of.
632
+ headers: Optional custom headers to include with the request.
633
+ params: Optional query parameters to include with the request.
634
+
635
+ Returns:
636
+ Response after updating a thread's state.
637
+
638
+ ???+ example "Example Usage"
639
+
640
+ ```python
641
+ client = get_client(url="http://localhost:2024)
642
+ response = await client.threads.update_state(
643
+ thread_id="my_thread_id",
644
+ values={"messages":[{"role": "user", "content": "hello!"}]},
645
+ as_node="my_node",
646
+ )
647
+ print(response)
648
+ ```
649
+ ```shell
650
+
651
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
652
+
653
+ {
654
+ 'checkpoint': {
655
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
656
+ 'checkpoint_ns': '',
657
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
658
+ 'checkpoint_map': {}
659
+ }
660
+ }
661
+ ```
662
+ """
663
+ payload: dict[str, Any] = {
664
+ "values": values,
665
+ }
666
+ if checkpoint_id:
667
+ payload["checkpoint_id"] = checkpoint_id
668
+ if checkpoint:
669
+ payload["checkpoint"] = checkpoint
670
+ if as_node:
671
+ payload["as_node"] = as_node
672
+ return await self.http.post(
673
+ f"/threads/{thread_id}/state", json=payload, headers=headers, params=params
674
+ )
675
+
676
+ async def get_history(
677
+ self,
678
+ thread_id: str,
679
+ *,
680
+ limit: int = 10,
681
+ before: str | Checkpoint | None = None,
682
+ metadata: Mapping[str, Any] | None = None,
683
+ checkpoint: Checkpoint | None = None,
684
+ headers: Mapping[str, str] | None = None,
685
+ params: QueryParamTypes | None = None,
686
+ ) -> list[ThreadState]:
687
+ """Get the state history of a thread.
688
+
689
+ Args:
690
+ thread_id: The ID of the thread to get the state history for.
691
+ checkpoint: Return states for this subgraph. If empty defaults to root.
692
+ limit: The maximum number of states to return.
693
+ before: Return states before this checkpoint.
694
+ metadata: Filter states by metadata key-value pairs.
695
+ headers: Optional custom headers to include with the request.
696
+ params: Optional query parameters to include with the request.
697
+
698
+ Returns:
699
+ The state history of the thread.
700
+
701
+ ???+ example "Example Usage"
702
+
703
+ ```python
704
+ client = get_client(url="http://localhost:2024)
705
+ thread_state = await client.threads.get_history(
706
+ thread_id="my_thread_id",
707
+ limit=5,
708
+ )
709
+ ```
710
+
711
+ """
712
+ payload: dict[str, Any] = {
713
+ "limit": limit,
714
+ }
715
+ if before:
716
+ payload["before"] = before
717
+ if metadata:
718
+ payload["metadata"] = metadata
719
+ if checkpoint:
720
+ payload["checkpoint"] = checkpoint
721
+ return await self.http.post(
722
+ f"/threads/{thread_id}/history",
723
+ json=payload,
724
+ headers=headers,
725
+ params=params,
726
+ )
727
+
728
+ async def join_stream(
729
+ self,
730
+ thread_id: str,
731
+ *,
732
+ last_event_id: str | None = None,
733
+ stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
734
+ headers: Mapping[str, str] | None = None,
735
+ params: QueryParamTypes | None = None,
736
+ ) -> AsyncIterator[StreamPart]:
737
+ """Get a stream of events for a thread.
738
+
739
+ Args:
740
+ thread_id: The ID of the thread to get the stream for.
741
+ last_event_id: The ID of the last event to get.
742
+ headers: Optional custom headers to include with the request.
743
+ params: Optional query parameters to include with the request.
744
+
745
+ Returns:
746
+ An iterator of stream parts.
747
+
748
+ ???+ example "Example Usage"
749
+
750
+ ```python
751
+
752
+ for chunk in client.threads.join_stream(
753
+ thread_id="my_thread_id",
754
+ last_event_id="my_event_id",
755
+ ):
756
+ print(chunk)
757
+ ```
758
+
759
+ """
760
+ query_params = {
761
+ "stream_mode": stream_mode,
762
+ }
763
+ if params:
764
+ query_params.update(params)
765
+ return self.http.stream(
766
+ f"/threads/{thread_id}/stream",
767
+ "GET",
768
+ headers={
769
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
770
+ **(headers or {}),
771
+ },
772
+ params=query_params,
773
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_shared/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Shared utilities for async and sync clients."""
python/user_packages/Python313/site-packages/langgraph_sdk/_shared/types.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Type aliases and constants."""
2
+
3
+ from __future__ import annotations
4
+
5
+ TimeoutTypes = (
6
+ None
7
+ | float
8
+ | tuple[float | None, float | None]
9
+ | tuple[float | None, float | None, float | None, float | None]
10
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/_shared/utilities.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared utility functions for async and sync clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import os
7
+ import re
8
+ from collections.abc import Mapping
9
+ from datetime import tzinfo
10
+ from typing import TYPE_CHECKING, Any, cast
11
+ from urllib.parse import urlparse
12
+
13
+ import httpx
14
+
15
+ import langgraph_sdk
16
+ from langgraph_sdk.schema import RunCreateMetadata
17
+
18
+ if TYPE_CHECKING:
19
+ from zoneinfo import ZoneInfo
20
+
21
+ RESERVED_HEADERS = ("x-api-key",)
22
+
23
+ NOT_PROVIDED = cast(None, object())
24
+
25
+
26
+ def _get_api_key(api_key: str | None = NOT_PROVIDED) -> str | None:
27
+ """Get the API key from the environment.
28
+ Precedence:
29
+ 1. explicit string argument
30
+ 2. LANGGRAPH_API_KEY (if api_key not provided)
31
+ 3. LANGSMITH_API_KEY (if api_key not provided)
32
+ 4. LANGCHAIN_API_KEY (if api_key not provided)
33
+
34
+ Args:
35
+ api_key: The API key to use. Can be:
36
+ - A string: use this exact API key
37
+ - None: explicitly skip loading from environment
38
+ - NOT_PROVIDED (default): auto-load from environment variables
39
+ """
40
+ if isinstance(api_key, str):
41
+ return api_key
42
+ if api_key is NOT_PROVIDED:
43
+ # api_key is not explicitly provided, try to load from environment
44
+ for prefix in ["LANGGRAPH", "LANGSMITH", "LANGCHAIN"]:
45
+ if env := os.getenv(f"{prefix}_API_KEY"):
46
+ return env.strip().strip('"').strip("'")
47
+ # api_key is explicitly None, don't load from environment
48
+ return None
49
+
50
+
51
+ def _get_headers(
52
+ api_key: str | None,
53
+ custom_headers: Mapping[str, str] | None,
54
+ ) -> dict[str, str]:
55
+ """Combine api_key and custom user-provided headers."""
56
+ custom_headers = custom_headers or {}
57
+ for header in RESERVED_HEADERS:
58
+ if header in custom_headers:
59
+ raise ValueError(f"Cannot set reserved header '{header}'")
60
+
61
+ headers = {
62
+ "User-Agent": f"langgraph-sdk-py/{langgraph_sdk.__version__}",
63
+ **custom_headers,
64
+ }
65
+ resolved_api_key = _get_api_key(api_key)
66
+ if resolved_api_key:
67
+ headers["x-api-key"] = resolved_api_key
68
+
69
+ return headers
70
+
71
+
72
+ def _orjson_default(obj: Any) -> Any:
73
+ is_class = isinstance(obj, type)
74
+ if hasattr(obj, "model_dump") and callable(obj.model_dump):
75
+ if is_class:
76
+ raise TypeError(
77
+ f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
78
+ f"\nReceived type: {obj!r}"
79
+ )
80
+ return obj.model_dump()
81
+ elif hasattr(obj, "dict") and callable(obj.dict):
82
+ if is_class:
83
+ raise TypeError(
84
+ f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
85
+ f"\nReceived type: {obj!r}"
86
+ )
87
+ return obj.dict()
88
+ elif isinstance(obj, (set, frozenset)):
89
+ return list(obj)
90
+ else:
91
+ raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
92
+
93
+
94
+ # Compiled regex pattern for extracting run metadata from Content-Location header
95
+ _RUN_METADATA_PATTERN = re.compile(
96
+ r"(\/threads\/(?P<thread_id>.+))?\/runs\/(?P<run_id>.+)"
97
+ )
98
+
99
+
100
+ def _get_run_metadata_from_response(
101
+ response: httpx.Response,
102
+ ) -> RunCreateMetadata | None:
103
+ """Extract run metadata from the response headers."""
104
+ if (content_location := response.headers.get("Content-Location")) and (
105
+ match := _RUN_METADATA_PATTERN.search(content_location)
106
+ ):
107
+ return RunCreateMetadata(
108
+ run_id=match.group("run_id"),
109
+ thread_id=match.group("thread_id") or None,
110
+ )
111
+
112
+ return None
113
+
114
+
115
+ def _sse_to_v2_dict(event: str, data: Any) -> dict[str, Any] | None:
116
+ """Convert an SSE event+data pair into a v2 stream part dict.
117
+
118
+ Returns None for ``end`` events (signals end of stream).
119
+ """
120
+ if event == "end":
121
+ return None
122
+ parts = event.split("|")
123
+ event_type = parts[0]
124
+ ns = parts[1:] if len(parts) > 1 else []
125
+ result: dict[str, Any] = {"type": event_type, "ns": ns, "data": data}
126
+ if event_type == "values" and isinstance(data, dict):
127
+ result["interrupts"] = data.pop("__interrupt__", [])
128
+ else:
129
+ result["interrupts"] = []
130
+ return result
131
+
132
+
133
+ def _resolve_timezone(tz: str | tzinfo | ZoneInfo | None) -> str | None:
134
+ """Convert a timezone argument to an IANA timezone string.
135
+
136
+ Accepts:
137
+ - A string (returned as-is, assumed to be an IANA timezone name)
138
+ - A ``datetime.tzinfo`` instance (e.g. ``zoneinfo.ZoneInfo("America/New_York")``,
139
+ ``datetime.timezone.utc``). The ``key`` attribute is used if available,
140
+ otherwise ``tzname(None)`` is used.
141
+ - ``None`` (returned as ``None``)
142
+ """
143
+ if tz is None or isinstance(tz, str):
144
+ return tz
145
+ if isinstance(tz, tzinfo):
146
+ # ZoneInfo objects have a .key attribute with the IANA name
147
+ if hasattr(tz, "key"):
148
+ return tz.key # type: ignore[union-attr]
149
+ # Fall back to tzname for fixed-offset timezones like datetime.timezone.utc
150
+ name = tz.tzname(None)
151
+ if name is not None:
152
+ return name
153
+ raise ValueError(
154
+ f"Cannot determine timezone name from {tz!r}. "
155
+ "Use a zoneinfo.ZoneInfo instance or pass a string like 'America/New_York'."
156
+ )
157
+ raise TypeError(
158
+ f"Expected str, datetime.tzinfo, or None for timezone, got {type(tz).__name__}"
159
+ )
160
+
161
+
162
+ def _default_port(scheme: str) -> int:
163
+ return 443 if scheme == "https" else 80
164
+
165
+
166
+ def _validate_reconnect_location(base_url: httpx.URL, location: str) -> str:
167
+ """Validate that a reconnect Location URL is same-origin as the base URL.
168
+
169
+ Raises ValueError if the Location header points to a different origin
170
+ (scheme + host + port), which would leak credentials to an external server.
171
+ """
172
+ parsed = urlparse(location)
173
+ # Relative URLs are safe — they resolve against the base
174
+ if not parsed.scheme and not parsed.netloc:
175
+ return location
176
+ # Compare origin components (normalize default ports to avoid mismatches)
177
+ base_scheme = str(base_url.scheme)
178
+ base_origin = (
179
+ base_scheme,
180
+ str(base_url.host),
181
+ base_url.port or _default_port(base_scheme),
182
+ )
183
+ loc_origin = (
184
+ parsed.scheme,
185
+ parsed.hostname or "",
186
+ parsed.port or _default_port(parsed.scheme),
187
+ )
188
+ if base_origin != loc_origin:
189
+ raise ValueError(
190
+ f"Refusing to follow cross-origin reconnect Location: {location!r} "
191
+ f"(origin {loc_origin}) does not match base URL origin {base_origin}"
192
+ )
193
+ return location
194
+
195
+
196
+ def _provided_vals(d: Mapping[str, Any]) -> dict[str, Any]:
197
+ return {k: v for k, v in d.items() if v is not None}
198
+
199
+
200
+ _registered_transports: list[httpx.ASGITransport] = []
201
+
202
+
203
+ # Do not move; this is used in the server.
204
+ def configure_loopback_transports(app: Any) -> None:
205
+ for transport in _registered_transports:
206
+ transport.app = app
207
+
208
+
209
+ @functools.lru_cache(maxsize=1)
210
+ def get_asgi_transport() -> type[httpx.ASGITransport]:
211
+ try:
212
+ from langgraph_api import asgi_transport # type: ignore[unresolved-import]
213
+
214
+ return asgi_transport.ASGITransport
215
+ except ImportError:
216
+ # Older versions of the server
217
+ return httpx.ASGITransport
python/user_packages/Python313/site-packages/langgraph_sdk/_sync/assistants.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synchronous client for managing assistants in LangGraph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, Literal, cast, overload
7
+
8
+ import httpx
9
+
10
+ from langgraph_sdk._sync.http import SyncHttpClient
11
+ from langgraph_sdk.schema import (
12
+ Assistant,
13
+ AssistantSelectField,
14
+ AssistantSortBy,
15
+ AssistantsSearchResponse,
16
+ AssistantVersion,
17
+ Config,
18
+ Context,
19
+ GraphSchema,
20
+ Json,
21
+ OnConflictBehavior,
22
+ QueryParamTypes,
23
+ SortOrder,
24
+ Subgraphs,
25
+ )
26
+
27
+
28
+ class SyncAssistantsClient:
29
+ """Client for managing assistants in LangGraph synchronously.
30
+
31
+ This class provides methods to interact with assistants, which are versioned configurations of your graph.
32
+
33
+ ???+ example "Example"
34
+
35
+ ```python
36
+ client = get_sync_client(url="http://localhost:2024")
37
+ assistant = client.assistants.get("assistant_id_123")
38
+ ```
39
+ """
40
+
41
+ def __init__(self, http: SyncHttpClient) -> None:
42
+ self.http = http
43
+
44
+ def get(
45
+ self,
46
+ assistant_id: str,
47
+ *,
48
+ headers: Mapping[str, str] | None = None,
49
+ params: QueryParamTypes | None = None,
50
+ ) -> Assistant:
51
+ """Get an assistant by ID.
52
+
53
+ Args:
54
+ assistant_id: The ID of the assistant to get OR the name of the graph (to use the default assistant).
55
+ headers: Optional custom headers to include with the request.
56
+ params: Optional query parameters to include with the request.
57
+
58
+ Returns:
59
+ `Assistant` Object.
60
+
61
+ ???+ example "Example Usage"
62
+
63
+ ```python
64
+ assistant = client.assistants.get(
65
+ assistant_id="my_assistant_id"
66
+ )
67
+ print(assistant)
68
+ ```
69
+
70
+ ```shell
71
+ ----------------------------------------------------
72
+
73
+ {
74
+ 'assistant_id': 'my_assistant_id',
75
+ 'graph_id': 'agent',
76
+ 'created_at': '2024-06-25T17:10:33.109781+00:00',
77
+ 'updated_at': '2024-06-25T17:10:33.109781+00:00',
78
+ 'config': {},
79
+ 'context': {},
80
+ 'metadata': {'created_by': 'system'}
81
+ }
82
+ ```
83
+
84
+ """
85
+ return self.http.get(
86
+ f"/assistants/{assistant_id}", headers=headers, params=params
87
+ )
88
+
89
+ def get_graph(
90
+ self,
91
+ assistant_id: str,
92
+ *,
93
+ xray: int | bool = False,
94
+ headers: Mapping[str, str] | None = None,
95
+ params: QueryParamTypes | None = None,
96
+ ) -> dict[str, list[dict[str, Any]]]:
97
+ """Get the graph of an assistant by ID.
98
+
99
+ Args:
100
+ assistant_id: The ID of the assistant to get the graph of.
101
+ xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
102
+ headers: Optional custom headers to include with the request.
103
+ params: Optional query parameters to include with the request.
104
+
105
+ Returns:
106
+ The graph information for the assistant in JSON format.
107
+
108
+ ???+ example "Example Usage"
109
+
110
+ ```python
111
+ client = get_sync_client(url="http://localhost:2024")
112
+ graph_info = client.assistants.get_graph(
113
+ assistant_id="my_assistant_id"
114
+ )
115
+ print(graph_info)
116
+
117
+ --------------------------------------------------------------------------------------------------------------------------
118
+
119
+ {
120
+ 'nodes':
121
+ [
122
+ {'id': '__start__', 'type': 'schema', 'data': '__start__'},
123
+ {'id': '__end__', 'type': 'schema', 'data': '__end__'},
124
+ {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
125
+ ],
126
+ 'edges':
127
+ [
128
+ {'source': '__start__', 'target': 'agent'},
129
+ {'source': 'agent','target': '__end__'}
130
+ ]
131
+ }
132
+ ```
133
+
134
+ """
135
+ query_params = {"xray": xray}
136
+ if params:
137
+ query_params.update(params)
138
+ return self.http.get(
139
+ f"/assistants/{assistant_id}/graph", params=query_params, headers=headers
140
+ )
141
+
142
+ def get_schemas(
143
+ self,
144
+ assistant_id: str,
145
+ *,
146
+ headers: Mapping[str, str] | None = None,
147
+ params: QueryParamTypes | None = None,
148
+ ) -> GraphSchema:
149
+ """Get the schemas of an assistant by ID.
150
+
151
+ Args:
152
+ assistant_id: The ID of the assistant to get the schema of.
153
+ headers: Optional custom headers to include with the request.
154
+ params: Optional query parameters to include with the request.
155
+
156
+ Returns:
157
+ GraphSchema: The graph schema for the assistant.
158
+
159
+ ???+ example "Example Usage"
160
+
161
+ ```python
162
+ client = get_sync_client(url="http://localhost:2024")
163
+ schema = client.assistants.get_schemas(
164
+ assistant_id="my_assistant_id"
165
+ )
166
+ print(schema)
167
+ ```
168
+ ```shell
169
+ ----------------------------------------------------------------------------------------------------------------------------
170
+
171
+ {
172
+ 'graph_id': 'agent',
173
+ 'state_schema':
174
+ {
175
+ 'title': 'LangGraphInput',
176
+ '$ref': '#/definitions/AgentState',
177
+ 'definitions':
178
+ {
179
+ 'BaseMessage':
180
+ {
181
+ 'title': 'BaseMessage',
182
+ 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
183
+ 'type': 'object',
184
+ 'properties':
185
+ {
186
+ 'content':
187
+ {
188
+ 'title': 'Content',
189
+ 'anyOf': [
190
+ {'type': 'string'},
191
+ {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
192
+ ]
193
+ },
194
+ 'additional_kwargs':
195
+ {
196
+ 'title': 'Additional Kwargs',
197
+ 'type': 'object'
198
+ },
199
+ 'response_metadata':
200
+ {
201
+ 'title': 'Response Metadata',
202
+ 'type': 'object'
203
+ },
204
+ 'type':
205
+ {
206
+ 'title': 'Type',
207
+ 'type': 'string'
208
+ },
209
+ 'name':
210
+ {
211
+ 'title': 'Name',
212
+ 'type': 'string'
213
+ },
214
+ 'id':
215
+ {
216
+ 'title': 'Id',
217
+ 'type': 'string'
218
+ }
219
+ },
220
+ 'required': ['content', 'type']
221
+ },
222
+ 'AgentState':
223
+ {
224
+ 'title': 'AgentState',
225
+ 'type': 'object',
226
+ 'properties':
227
+ {
228
+ 'messages':
229
+ {
230
+ 'title': 'Messages',
231
+ 'type': 'array',
232
+ 'items': {'$ref': '#/definitions/BaseMessage'}
233
+ }
234
+ },
235
+ 'required': ['messages']
236
+ }
237
+ }
238
+ },
239
+ 'config_schema':
240
+ {
241
+ 'title': 'Configurable',
242
+ 'type': 'object',
243
+ 'properties':
244
+ {
245
+ 'model_name':
246
+ {
247
+ 'title': 'Model Name',
248
+ 'enum': ['anthropic', 'openai'],
249
+ 'type': 'string'
250
+ }
251
+ }
252
+ },
253
+ 'context_schema':
254
+ {
255
+ 'title': 'Context',
256
+ 'type': 'object',
257
+ 'properties':
258
+ {
259
+ 'model_name':
260
+ {
261
+ 'title': 'Model Name',
262
+ 'enum': ['anthropic', 'openai'],
263
+ 'type': 'string'
264
+ }
265
+ }
266
+ }
267
+ }
268
+ ```
269
+
270
+ """
271
+ return self.http.get(
272
+ f"/assistants/{assistant_id}/schemas", headers=headers, params=params
273
+ )
274
+
275
+ def get_subgraphs(
276
+ self,
277
+ assistant_id: str,
278
+ namespace: str | None = None,
279
+ recurse: bool = False,
280
+ *,
281
+ headers: Mapping[str, str] | None = None,
282
+ params: QueryParamTypes | None = None,
283
+ ) -> Subgraphs:
284
+ """Get the schemas of an assistant by ID.
285
+
286
+ Args:
287
+ assistant_id: The ID of the assistant to get the schema of.
288
+ headers: Optional custom headers to include with the request.
289
+ params: Optional query parameters to include with the request.
290
+
291
+ Returns:
292
+ Subgraphs: The graph schema for the assistant.
293
+
294
+ """
295
+ get_params = {"recurse": recurse}
296
+ if params:
297
+ get_params = {**get_params, **dict(params)}
298
+ if namespace is not None:
299
+ return self.http.get(
300
+ f"/assistants/{assistant_id}/subgraphs/{namespace}",
301
+ params=get_params,
302
+ headers=headers,
303
+ )
304
+ else:
305
+ return self.http.get(
306
+ f"/assistants/{assistant_id}/subgraphs",
307
+ params=get_params,
308
+ headers=headers,
309
+ )
310
+
311
+ def create(
312
+ self,
313
+ graph_id: str | None,
314
+ config: Config | None = None,
315
+ *,
316
+ context: Context | None = None,
317
+ metadata: Json = None,
318
+ assistant_id: str | None = None,
319
+ if_exists: OnConflictBehavior | None = None,
320
+ name: str | None = None,
321
+ headers: Mapping[str, str] | None = None,
322
+ description: str | None = None,
323
+ params: QueryParamTypes | None = None,
324
+ ) -> Assistant:
325
+ """Create a new assistant.
326
+
327
+ Useful when graph is configurable and you want to create different assistants based on different configurations.
328
+
329
+ Args:
330
+ graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
331
+ config: Configuration to use for the graph.
332
+ context: Static context to add to the assistant.
333
+ !!! version-added "Added in version 0.6.0"
334
+ metadata: Metadata to add to assistant.
335
+ assistant_id: Assistant ID to use, will default to a random UUID if not provided.
336
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
337
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
338
+ name: The name of the assistant. Defaults to 'Untitled' under the hood.
339
+ headers: Optional custom headers to include with the request.
340
+ description: Optional description of the assistant.
341
+ The description field is available for langgraph-api server version>=0.0.45
342
+ params: Optional query parameters to include with the request.
343
+
344
+ Returns:
345
+ The created assistant.
346
+
347
+ ???+ example "Example Usage"
348
+
349
+ ```python
350
+ client = get_sync_client(url="http://localhost:2024")
351
+ assistant = client.assistants.create(
352
+ graph_id="agent",
353
+ context={"model_name": "openai"},
354
+ metadata={"number":1},
355
+ assistant_id="my-assistant-id",
356
+ if_exists="do_nothing",
357
+ name="my_name"
358
+ )
359
+ ```
360
+ """
361
+ payload: dict[str, Any] = {
362
+ "graph_id": graph_id,
363
+ }
364
+ if config:
365
+ payload["config"] = config
366
+ if context:
367
+ payload["context"] = context
368
+ if metadata:
369
+ payload["metadata"] = metadata
370
+ if assistant_id:
371
+ payload["assistant_id"] = assistant_id
372
+ if if_exists:
373
+ payload["if_exists"] = if_exists
374
+ if name:
375
+ payload["name"] = name
376
+ if description:
377
+ payload["description"] = description
378
+ return self.http.post(
379
+ "/assistants", json=payload, headers=headers, params=params
380
+ )
381
+
382
+ def update(
383
+ self,
384
+ assistant_id: str,
385
+ *,
386
+ graph_id: str | None = None,
387
+ config: Config | None = None,
388
+ context: Context | None = None,
389
+ metadata: Json = None,
390
+ name: str | None = None,
391
+ headers: Mapping[str, str] | None = None,
392
+ description: str | None = None,
393
+ params: QueryParamTypes | None = None,
394
+ ) -> Assistant:
395
+ """Update an assistant.
396
+
397
+ Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
398
+
399
+ Args:
400
+ assistant_id: Assistant to update.
401
+ graph_id: The ID of the graph the assistant should use.
402
+ The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
403
+ config: Configuration to use for the graph.
404
+ context: Static context to add to the assistant.
405
+ !!! version-added "Added in version 0.6.0"
406
+ metadata: Metadata to merge with existing assistant metadata.
407
+ name: The new name for the assistant.
408
+ headers: Optional custom headers to include with the request.
409
+ description: Optional description of the assistant.
410
+ The description field is available for langgraph-api server version>=0.0.45
411
+
412
+ Returns:
413
+ The updated assistant.
414
+
415
+ ???+ example "Example Usage"
416
+
417
+ ```python
418
+ client = get_sync_client(url="http://localhost:2024")
419
+ assistant = client.assistants.update(
420
+ assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
421
+ graph_id="other-graph",
422
+ context={"model_name": "anthropic"},
423
+ metadata={"number":2}
424
+ )
425
+ ```
426
+ """
427
+ payload: dict[str, Any] = {}
428
+ if graph_id:
429
+ payload["graph_id"] = graph_id
430
+ if config is not None:
431
+ payload["config"] = config
432
+ if context is not None:
433
+ payload["context"] = context
434
+ if metadata:
435
+ payload["metadata"] = metadata
436
+ if name:
437
+ payload["name"] = name
438
+ if description:
439
+ payload["description"] = description
440
+ return self.http.patch(
441
+ f"/assistants/{assistant_id}",
442
+ json=payload,
443
+ headers=headers,
444
+ params=params,
445
+ )
446
+
447
+ def delete(
448
+ self,
449
+ assistant_id: str,
450
+ *,
451
+ delete_threads: bool = False,
452
+ headers: Mapping[str, str] | None = None,
453
+ params: QueryParamTypes | None = None,
454
+ ) -> None:
455
+ """Delete an assistant.
456
+
457
+ Args:
458
+ assistant_id: The assistant ID to delete.
459
+ delete_threads: If true, delete all threads with `metadata.assistant_id`
460
+ matching this assistant, along with runs and checkpoints belonging to
461
+ those threads.
462
+ headers: Optional custom headers to include with the request.
463
+ params: Optional query parameters to include with the request.
464
+
465
+ Returns:
466
+ `None`
467
+
468
+ ???+ example "Example Usage"
469
+
470
+ ```python
471
+ client = get_sync_client(url="http://localhost:2024")
472
+ client.assistants.delete(
473
+ assistant_id="my_assistant_id"
474
+ )
475
+ ```
476
+
477
+ """
478
+ query_params: dict[str, Any] = {}
479
+ if delete_threads:
480
+ query_params["delete_threads"] = True
481
+ if params:
482
+ query_params.update(params)
483
+ self.http.delete(
484
+ f"/assistants/{assistant_id}",
485
+ headers=headers,
486
+ params=query_params or None,
487
+ )
488
+
489
+ @overload
490
+ def search(
491
+ self,
492
+ *,
493
+ metadata: Json = None,
494
+ graph_id: str | None = None,
495
+ name: str | None = None,
496
+ limit: int = 10,
497
+ offset: int = 0,
498
+ sort_by: AssistantSortBy | None = None,
499
+ sort_order: SortOrder | None = None,
500
+ select: list[AssistantSelectField] | None = None,
501
+ response_format: Literal["object"],
502
+ headers: Mapping[str, str] | None = None,
503
+ params: QueryParamTypes | None = None,
504
+ ) -> AssistantsSearchResponse: ...
505
+
506
+ @overload
507
+ def search(
508
+ self,
509
+ *,
510
+ metadata: Json = None,
511
+ graph_id: str | None = None,
512
+ name: str | None = None,
513
+ limit: int = 10,
514
+ offset: int = 0,
515
+ sort_by: AssistantSortBy | None = None,
516
+ sort_order: SortOrder | None = None,
517
+ select: list[AssistantSelectField] | None = None,
518
+ response_format: Literal["array"] = "array",
519
+ headers: Mapping[str, str] | None = None,
520
+ params: QueryParamTypes | None = None,
521
+ ) -> list[Assistant]: ...
522
+
523
+ def search(
524
+ self,
525
+ *,
526
+ metadata: Json = None,
527
+ graph_id: str | None = None,
528
+ name: str | None = None,
529
+ limit: int = 10,
530
+ offset: int = 0,
531
+ sort_by: AssistantSortBy | None = None,
532
+ sort_order: SortOrder | None = None,
533
+ select: list[AssistantSelectField] | None = None,
534
+ response_format: Literal["array", "object"] = "array",
535
+ headers: Mapping[str, str] | None = None,
536
+ params: QueryParamTypes | None = None,
537
+ ) -> AssistantsSearchResponse | list[Assistant]:
538
+ """Search for assistants.
539
+
540
+ Args:
541
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
542
+ graph_id: The ID of the graph to filter by.
543
+ The graph ID is normally set in your langgraph.json configuration.
544
+ name: The name of the assistant to filter by.
545
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
546
+ limit: The maximum number of results to return.
547
+ offset: The number of results to skip.
548
+ sort_by: The field to sort by.
549
+ sort_order: The order to sort by.
550
+ select: Specific assistant fields to include in the response.
551
+ response_format: Controls the response shape. Use `"array"` (default)
552
+ to return a bare list of assistants, or `"object"` to return
553
+ a mapping containing assistants plus pagination metadata.
554
+ Defaults to "array", though this default will be changed to "object" in a future release.
555
+ headers: Optional custom headers to include with the request.
556
+
557
+ Returns:
558
+ A list of assistants (when `response_format="array"`) or a mapping
559
+ with the assistants and the next pagination cursor (when
560
+ `response_format="object"`).
561
+
562
+ ???+ example "Example Usage"
563
+
564
+ ```python
565
+ client = get_sync_client(url="http://localhost:2024")
566
+ response = client.assistants.search(
567
+ metadata = {"name":"my_name"},
568
+ graph_id="my_graph_id",
569
+ limit=5,
570
+ offset=5,
571
+ response_format="object",
572
+ )
573
+ assistants = response["assistants"]
574
+ next_cursor = response["next"]
575
+ ```
576
+ """
577
+ if response_format not in ("array", "object"):
578
+ raise ValueError("response_format must be 'array' or 'object'")
579
+ payload: dict[str, Any] = {
580
+ "limit": limit,
581
+ "offset": offset,
582
+ }
583
+ if metadata:
584
+ payload["metadata"] = metadata
585
+ if graph_id:
586
+ payload["graph_id"] = graph_id
587
+ if name:
588
+ payload["name"] = name
589
+ if sort_by:
590
+ payload["sort_by"] = sort_by
591
+ if sort_order:
592
+ payload["sort_order"] = sort_order
593
+ if select:
594
+ payload["select"] = select
595
+ next_cursor: str | None = None
596
+
597
+ def capture_pagination(response: httpx.Response) -> None:
598
+ nonlocal next_cursor
599
+ next_cursor = response.headers.get("X-Pagination-Next")
600
+
601
+ assistants = cast(
602
+ list[Assistant],
603
+ self.http.post(
604
+ "/assistants/search",
605
+ json=payload,
606
+ headers=headers,
607
+ params=params,
608
+ on_response=capture_pagination if response_format == "object" else None,
609
+ ),
610
+ )
611
+ if response_format == "object":
612
+ return {"assistants": assistants, "next": next_cursor}
613
+ return assistants
614
+
615
+ def count(
616
+ self,
617
+ *,
618
+ metadata: Json = None,
619
+ graph_id: str | None = None,
620
+ name: str | None = None,
621
+ headers: Mapping[str, str] | None = None,
622
+ params: QueryParamTypes | None = None,
623
+ ) -> int:
624
+ """Count assistants matching filters.
625
+
626
+ Args:
627
+ metadata: Metadata to filter by. Exact match for each key/value.
628
+ graph_id: Optional graph id to filter by.
629
+ name: Optional name to filter by.
630
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
631
+ headers: Optional custom headers to include with the request.
632
+ params: Optional query parameters to include with the request.
633
+
634
+ Returns:
635
+ int: Number of assistants matching the criteria.
636
+ """
637
+ payload: dict[str, Any] = {}
638
+ if metadata:
639
+ payload["metadata"] = metadata
640
+ if graph_id:
641
+ payload["graph_id"] = graph_id
642
+ if name:
643
+ payload["name"] = name
644
+ return self.http.post(
645
+ "/assistants/count", json=payload, headers=headers, params=params
646
+ )
647
+
648
+ def get_versions(
649
+ self,
650
+ assistant_id: str,
651
+ metadata: Json = None,
652
+ limit: int = 10,
653
+ offset: int = 0,
654
+ *,
655
+ headers: Mapping[str, str] | None = None,
656
+ params: QueryParamTypes | None = None,
657
+ ) -> list[AssistantVersion]:
658
+ """List all versions of an assistant.
659
+
660
+ Args:
661
+ assistant_id: The assistant ID to get versions for.
662
+ metadata: Metadata to filter versions by. Exact match filter for each KV pair.
663
+ limit: The maximum number of versions to return.
664
+ offset: The number of versions to skip.
665
+ headers: Optional custom headers to include with the request.
666
+
667
+ Returns:
668
+ A list of assistants.
669
+
670
+ ???+ example "Example Usage"
671
+
672
+ ```python
673
+ client = get_sync_client(url="http://localhost:2024")
674
+ assistant_versions = client.assistants.get_versions(
675
+ assistant_id="my_assistant_id"
676
+ )
677
+ ```
678
+
679
+ """
680
+
681
+ payload: dict[str, Any] = {
682
+ "limit": limit,
683
+ "offset": offset,
684
+ }
685
+ if metadata:
686
+ payload["metadata"] = metadata
687
+ return self.http.post(
688
+ f"/assistants/{assistant_id}/versions",
689
+ json=payload,
690
+ headers=headers,
691
+ params=params,
692
+ )
693
+
694
+ def set_latest(
695
+ self,
696
+ assistant_id: str,
697
+ version: int,
698
+ *,
699
+ headers: Mapping[str, str] | None = None,
700
+ params: QueryParamTypes | None = None,
701
+ ) -> Assistant:
702
+ """Change the version of an assistant.
703
+
704
+ Args:
705
+ assistant_id: The assistant ID to delete.
706
+ version: The version to change to.
707
+ headers: Optional custom headers to include with the request.
708
+
709
+ Returns:
710
+ `Assistant` Object.
711
+
712
+ ???+ example "Example Usage"
713
+
714
+ ```python
715
+ client = get_sync_client(url="http://localhost:2024")
716
+ new_version_assistant = client.assistants.set_latest(
717
+ assistant_id="my_assistant_id",
718
+ version=3
719
+ )
720
+ ```
721
+
722
+ """
723
+
724
+ payload: dict[str, Any] = {"version": version}
725
+
726
+ return self.http.post(
727
+ f"/assistants/{assistant_id}/latest",
728
+ json=payload,
729
+ headers=headers,
730
+ params=params,
731
+ )
python/user_packages/Python313/site-packages/langgraph_sdk/auth/__init__.py ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import typing
5
+ from collections.abc import Callable, Sequence
6
+
7
+ from langgraph_sdk.auth import exceptions, types
8
+
9
+ TH = typing.TypeVar("TH", bound=types.Handler)
10
+ AH = typing.TypeVar("AH", bound=types.Authenticator)
11
+
12
+
13
+ class Auth:
14
+ """Add custom authentication and authorization management to your LangGraph application.
15
+
16
+ The Auth class provides a unified system for handling authentication and
17
+ authorization in LangGraph applications. It supports custom user authentication
18
+ protocols and fine-grained authorization rules for different resources and
19
+ actions.
20
+
21
+ To use, create a separate python file and add the path to the file to your
22
+ LangGraph API configuration file (`langgraph.json`). Within that file, create
23
+ an instance of the Auth class and register authentication and authorization
24
+ handlers as needed.
25
+
26
+ Example `langgraph.json` file:
27
+
28
+ ```json
29
+ {
30
+ "dependencies": ["."],
31
+ "graphs": {
32
+ "agent": "./my_agent/agent.py:graph"
33
+ },
34
+ "env": ".env",
35
+ "auth": {
36
+ "path": "./auth.py:my_auth"
37
+ }
38
+ ```
39
+
40
+ Then the LangGraph server will load your auth file and run it server-side whenever a request comes in.
41
+
42
+ ???+ example "Basic Usage"
43
+
44
+ ```python
45
+ from langgraph_sdk import Auth
46
+
47
+ my_auth = Auth()
48
+
49
+ @my_auth.authenticate
50
+ async def authenticate(authorization: str) -> Auth.types.MinimalUserDict:
51
+ user = await verify_token(authorization) # Your token verification logic
52
+ if not user:
53
+ raise Auth.exceptions.HTTPException(
54
+ status_code=401, detail="Unauthorized"
55
+ )
56
+ return {
57
+ "identity": user["id"],
58
+ "permissions": user.get("permissions", []),
59
+ }
60
+
61
+ # Default deny: reject all requests that don't have a specific handler
62
+ @my_auth.on
63
+ async def deny_all(ctx: Auth.types.AuthContext, value: Any) -> False:
64
+ return False
65
+
66
+ # Allow users to create threads with their own identity as owner
67
+ @my_auth.on.threads.create
68
+ async def allow_thread_create(
69
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.create.value
70
+ ):
71
+ metadata = value.setdefault("metadata", {})
72
+ metadata["owner"] = ctx.user.identity
73
+
74
+ # Allow users to read and search their own threads
75
+ @my_auth.on.threads.read
76
+ async def allow_thread_read(
77
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.read.value
78
+ ) -> Auth.types.FilterType:
79
+ return {"owner": ctx.user.identity}
80
+
81
+ @my_auth.on.threads.search
82
+ async def allow_thread_search(
83
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.search.value
84
+ ) -> Auth.types.FilterType:
85
+ return {"owner": ctx.user.identity}
86
+
87
+ # Scope all store operations to the user's namespace
88
+ @my_auth.on.store
89
+ async def scope_store(ctx: Auth.types.AuthContext, value: Auth.types.on.store.value):
90
+ namespace = tuple(value["namespace"]) if value.get("namespace") else ()
91
+ if not namespace or namespace[0] != ctx.user.identity:
92
+ namespace = (ctx.user.identity, *namespace)
93
+ value["namespace"] = namespace
94
+ ```
95
+
96
+ ???+ note "Request Processing Flow"
97
+
98
+ 1. Authentication (your `@auth.authenticate` handler) is performed first on **every request**
99
+ 2. For authorization, the most specific matching handler is called:
100
+ * If a handler exists for the exact resource and action, it is used (e.g., `@auth.on.threads.create`)
101
+ * Otherwise, if a handler exists for the resource with any action, it is used (e.g., `@auth.on.threads`)
102
+ * Finally, if no specific handlers match, the global handler is used (e.g., `@auth.on`)
103
+ * If no global handler is set, the request is accepted
104
+
105
+ This allows you to set default behavior with a global handler while
106
+ overriding specific routes as needed.
107
+ """
108
+
109
+ __slots__ = (
110
+ "_authenticate_handler",
111
+ "_global_handlers",
112
+ "_handler_cache",
113
+ "_handlers",
114
+ "on",
115
+ )
116
+ types = types
117
+ """Reference to auth type definitions.
118
+
119
+ Provides access to all type definitions used in the auth system,
120
+ like ThreadsCreate, AssistantsRead, etc."""
121
+
122
+ exceptions = exceptions
123
+ """Reference to auth exception definitions.
124
+
125
+ Provides access to all exception definitions used in the auth system,
126
+ like HTTPException, etc.
127
+ """
128
+
129
+ def __init__(self) -> None:
130
+ self.on = _On(self)
131
+ """Entry point for authorization handlers that control access to specific resources.
132
+
133
+ The on class provides a flexible way to define authorization rules for different
134
+ resources and actions in your application. It supports three main usage patterns:
135
+
136
+ 1. Global handlers that run for all resources and actions
137
+ 2. Resource-specific handlers that run for all actions on a resource
138
+ 3. Resource and action specific handlers for fine-grained control
139
+
140
+ Each handler must be an async function that accepts two parameters:
141
+ - ctx (AuthContext): Contains request context and authenticated user info
142
+ - value: The data being authorized (type varies by endpoint)
143
+
144
+ The handler should return one of:
145
+
146
+ - None or True: Accept the request
147
+ - False: Reject with 403 error
148
+ - FilterType: Apply filtering rules to the response
149
+
150
+ ???+ example "Examples"
151
+
152
+ Start by denying all requests by default, then add specific handlers
153
+ to allow access:
154
+
155
+ ```python
156
+ # Default deny: reject all unhandled requests
157
+ @auth.on
158
+ async def deny_all(ctx: AuthContext, value: Any) -> False:
159
+ return False
160
+ ```
161
+
162
+ Resource-specific handler. This takes precedence over the global handler
163
+ for all actions on the `threads` resource:
164
+
165
+ ```python
166
+ @auth.on.threads
167
+ async def allow_thread_access(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
168
+ # Only allow access to threads owned by the user
169
+ return {"owner": ctx.user.identity}
170
+ ```
171
+
172
+ Resource and action specific handler:
173
+
174
+ ```python
175
+ @auth.on.threads.delete
176
+ async def allow_admin_thread_deletion(ctx: AuthContext, value: Any) -> bool:
177
+ # Only admins can delete threads
178
+ return "admin" in ctx.user.permissions
179
+ ```
180
+
181
+ Multiple resources or actions:
182
+
183
+ ```python
184
+ @auth.on(resources=["threads", "assistants"], actions=["read", "search"])
185
+ async def allow_reads(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
186
+ # Allow read/search access to resources owned by the user
187
+ return {"owner": ctx.user.identity}
188
+ ```
189
+
190
+ Auth for the `store` resource is a bit different since its structure is developer defined.
191
+ You typically want to scope store operations by rewriting the namespace to include the user's identity.
192
+ The `value` dict is mutable — changes to `value["namespace"]` are used by the server for the actual operation.
193
+
194
+ ```python
195
+ @auth.on.store
196
+ async def scope_store(ctx: AuthContext, value: Auth.types.on.store.value):
197
+ # Allow store access but scope to user's namespace
198
+ namespace = tuple(value["namespace"]) if value.get("namespace") else ()
199
+ if not namespace or namespace[0] != ctx.user.identity:
200
+ namespace = (ctx.user.identity, *namespace)
201
+ value["namespace"] = namespace
202
+ ```
203
+
204
+ You can also register handlers for specific store actions:
205
+
206
+ ```python
207
+ @auth.on.store.put
208
+ async def allow_put(ctx: AuthContext, value: Auth.types.on.store.put.value):
209
+ # Allow puts, scoped to user's namespace
210
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
211
+
212
+ @auth.on.store.get
213
+ async def allow_get(ctx: AuthContext, value: Auth.types.on.store.get.value):
214
+ # Allow gets, scoped to user's namespace
215
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
216
+ ```
217
+ """
218
+ # These are accessed by the API. Changes to their names or types is
219
+ # will be considered a breaking change.
220
+ self._handlers: dict[tuple[str, str], list[types.Handler]] = {}
221
+ self._global_handlers: list[types.Handler] = []
222
+ self._authenticate_handler: types.Authenticator | None = None
223
+ self._handler_cache: dict[tuple[str, str], types.Handler] = {}
224
+
225
+ def authenticate(self, fn: AH) -> AH:
226
+ """Register an authentication handler function.
227
+
228
+ The authentication handler is responsible for verifying credentials
229
+ and returning user scopes. It can accept any of the following parameters
230
+ by name:
231
+
232
+ - request (Request): The raw ASGI request object
233
+ - path (str): The request path, e.g., "/threads/abcd-1234-abcd-1234/runs/abcd-1234-abcd-1234/stream"
234
+ - method (str): The HTTP method, e.g., "GET"
235
+ - path_params (dict[str, str]): URL path parameters, e.g., {"thread_id": "abcd-1234-abcd-1234", "run_id": "abcd-1234-abcd-1234"}
236
+ - query_params (dict[str, str]): URL query parameters, e.g., {"stream": "true"}
237
+ - headers (dict[bytes, bytes]): Request headers
238
+ - authorization (str | None): The Authorization header value (e.g., "Bearer <token>")
239
+
240
+ Args:
241
+ fn: The authentication handler function to register.
242
+ Must return a representation of the user. This could be a:
243
+ - string (the user id)
244
+ - dict containing {"identity": str, "permissions": list[str]}
245
+ - or an object with identity and permissions properties
246
+ Permissions can be optionally used by your handlers downstream.
247
+
248
+ Returns:
249
+ The registered handler function.
250
+
251
+ Raises:
252
+ ValueError: If an authentication handler is already registered.
253
+
254
+ ???+ example "Examples"
255
+
256
+ Basic token authentication:
257
+
258
+ ```python
259
+ @auth.authenticate
260
+ async def authenticate(authorization: str) -> str:
261
+ user_id = verify_token(authorization)
262
+ return user_id
263
+ ```
264
+
265
+ Accept the full request context:
266
+
267
+ ```python
268
+ @auth.authenticate
269
+ async def authenticate(
270
+ method: str,
271
+ path: str,
272
+ headers: dict[str, bytes]
273
+ ) -> str:
274
+ user = await verify_request(method, path, headers)
275
+ return user
276
+ ```
277
+
278
+ Return user name and permissions:
279
+
280
+ ```python
281
+ @auth.authenticate
282
+ async def authenticate(
283
+ method: str,
284
+ path: str,
285
+ headers: dict[str, bytes]
286
+ ) -> Auth.types.MinimalUserDict:
287
+ permissions, user = await verify_request(method, path, headers)
288
+ # Permissions could be things like ["runs:read", "runs:write", "threads:read", "threads:write"]
289
+ return {
290
+ "identity": user["id"],
291
+ "permissions": permissions,
292
+ "display_name": user["name"],
293
+ }
294
+ ```
295
+ """
296
+ if self._authenticate_handler is not None:
297
+ raise ValueError(
298
+ f"Authentication handler already set as {self._authenticate_handler}."
299
+ )
300
+ self._authenticate_handler = fn
301
+ return fn
302
+
303
+
304
+ ## Helper types & utilities
305
+
306
+ V = typing.TypeVar("V", contravariant=True)
307
+
308
+
309
+ class _ActionHandler(typing.Protocol[V]):
310
+ async def __call__(
311
+ self, *, ctx: types.AuthContext, value: V
312
+ ) -> types.HandlerResult: ...
313
+
314
+
315
+ T = typing.TypeVar("T", covariant=True)
316
+
317
+
318
+ class _ResourceActionOn(typing.Generic[T]):
319
+ def __init__(
320
+ self,
321
+ auth: Auth,
322
+ resource: typing.Literal["threads", "crons", "assistants"],
323
+ action: typing.Literal[
324
+ "create", "read", "update", "delete", "search", "create_run"
325
+ ],
326
+ value: type[T],
327
+ ) -> None:
328
+ self.auth = auth
329
+ self.resource = resource
330
+ self.action = action
331
+ self.value = value
332
+
333
+ def __call__(self, fn: _ActionHandler[T]) -> _ActionHandler[T]:
334
+ _validate_handler(fn)
335
+ _register_handler(self.auth, self.resource, self.action, fn)
336
+ return fn
337
+
338
+
339
+ VCreate = typing.TypeVar("VCreate", covariant=True)
340
+ VUpdate = typing.TypeVar("VUpdate", covariant=True)
341
+ VRead = typing.TypeVar("VRead", covariant=True)
342
+ VDelete = typing.TypeVar("VDelete", covariant=True)
343
+ VSearch = typing.TypeVar("VSearch", covariant=True)
344
+
345
+
346
+ class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
347
+ """
348
+ Generic base class for resource-specific handlers.
349
+ """
350
+
351
+ value: type[VCreate | VUpdate | VRead | VDelete | VSearch]
352
+
353
+ Create: type[VCreate]
354
+ Read: type[VRead]
355
+ Update: type[VUpdate]
356
+ Delete: type[VDelete]
357
+ Search: type[VSearch]
358
+
359
+ def __init__(
360
+ self,
361
+ auth: Auth,
362
+ resource: typing.Literal["threads", "crons", "assistants"],
363
+ ) -> None:
364
+ self.auth = auth
365
+ self.resource = resource
366
+ self.create: _ResourceActionOn[VCreate] = _ResourceActionOn(
367
+ auth, resource, "create", self.Create
368
+ )
369
+ self.read: _ResourceActionOn[VRead] = _ResourceActionOn(
370
+ auth, resource, "read", self.Read
371
+ )
372
+ self.update: _ResourceActionOn[VUpdate] = _ResourceActionOn(
373
+ auth, resource, "update", self.Update
374
+ )
375
+ self.delete: _ResourceActionOn[VDelete] = _ResourceActionOn(
376
+ auth, resource, "delete", self.Delete
377
+ )
378
+ self.search: _ResourceActionOn[VSearch] = _ResourceActionOn(
379
+ auth, resource, "search", self.Search
380
+ )
381
+
382
+ @typing.overload
383
+ def __call__(
384
+ self,
385
+ fn: (
386
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
387
+ | _ActionHandler[dict[str, typing.Any]]
388
+ ),
389
+ ) -> _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]: ...
390
+
391
+ @typing.overload
392
+ def __call__(
393
+ self,
394
+ *,
395
+ resources: str | Sequence[str],
396
+ actions: str | Sequence[str] | None = None,
397
+ ) -> Callable[
398
+ [_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]],
399
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
400
+ ]: ...
401
+
402
+ def __call__(
403
+ self,
404
+ fn: (
405
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
406
+ | _ActionHandler[dict[str, typing.Any]]
407
+ | None
408
+ ) = None,
409
+ *,
410
+ resources: str | Sequence[str] | None = None,
411
+ actions: str | Sequence[str] | None = None,
412
+ ) -> (
413
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
414
+ | Callable[
415
+ [_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]],
416
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
417
+ ]
418
+ ):
419
+ if fn is not None:
420
+ _validate_handler(fn)
421
+ return typing.cast(
422
+ "_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
423
+ _register_handler(self.auth, self.resource, "*", fn),
424
+ )
425
+
426
+ def decorator(
427
+ handler: _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
428
+ ) -> _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]:
429
+ _validate_handler(handler)
430
+ return typing.cast(
431
+ "_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
432
+ _register_handler(self.auth, self.resource, "*", handler),
433
+ )
434
+
435
+ # Accept keyword-only parameters for future filtering behavior; referenced to satisfy linters.
436
+ _ = resources, actions
437
+ return decorator
438
+
439
+
440
+ class _AssistantsOn(
441
+ _ResourceOn[
442
+ types.AssistantsCreate,
443
+ types.AssistantsRead,
444
+ types.AssistantsUpdate,
445
+ types.AssistantsDelete,
446
+ types.AssistantsSearch,
447
+ ]
448
+ ):
449
+ value = (
450
+ types.AssistantsCreate
451
+ | types.AssistantsRead
452
+ | types.AssistantsUpdate
453
+ | types.AssistantsDelete
454
+ | types.AssistantsSearch
455
+ )
456
+ Create = types.AssistantsCreate
457
+ Read = types.AssistantsRead
458
+ Update = types.AssistantsUpdate
459
+ Delete = types.AssistantsDelete
460
+ Search = types.AssistantsSearch
461
+
462
+
463
+ class _ThreadsOn(
464
+ _ResourceOn[
465
+ types.ThreadsCreate,
466
+ types.ThreadsRead,
467
+ types.ThreadsUpdate,
468
+ types.ThreadsDelete,
469
+ types.ThreadsSearch,
470
+ ]
471
+ ):
472
+ value = (
473
+ types.ThreadsCreate
474
+ | types.ThreadsRead
475
+ | types.ThreadsUpdate
476
+ | types.ThreadsDelete
477
+ | types.ThreadsSearch
478
+ | types.RunsCreate
479
+ )
480
+ Create = types.ThreadsCreate
481
+ Read = types.ThreadsRead
482
+ Update = types.ThreadsUpdate
483
+ Delete = types.ThreadsDelete
484
+ Search = types.ThreadsSearch
485
+ CreateRun = types.RunsCreate
486
+
487
+ def __init__(
488
+ self,
489
+ auth: Auth,
490
+ resource: typing.Literal["threads", "crons", "assistants"],
491
+ ) -> None:
492
+ super().__init__(auth, resource)
493
+ self.create_run: _ResourceActionOn[types.RunsCreate] = _ResourceActionOn(
494
+ auth, resource, "create_run", self.CreateRun
495
+ )
496
+
497
+
498
+ class _CronsOn(
499
+ _ResourceOn[
500
+ types.CronsCreate,
501
+ types.CronsRead,
502
+ types.CronsUpdate,
503
+ types.CronsDelete,
504
+ types.CronsSearch,
505
+ ]
506
+ ):
507
+ value = type[
508
+ types.CronsCreate
509
+ | types.CronsRead
510
+ | types.CronsUpdate
511
+ | types.CronsDelete
512
+ | types.CronsSearch
513
+ ]
514
+
515
+ Create = types.CronsCreate
516
+ Read = types.CronsRead
517
+ Update = types.CronsUpdate
518
+ Delete = types.CronsDelete
519
+ Search = types.CronsSearch
520
+
521
+
522
+ class _StoreActionOn(typing.Generic[T]):
523
+ """Decorator for registering a handler for a specific store action."""
524
+
525
+ def __init__(
526
+ self,
527
+ auth: Auth,
528
+ action: typing.Literal["put", "get", "search", "delete", "list_namespaces"],
529
+ value: type[T],
530
+ ) -> None:
531
+ self.auth = auth
532
+ self.action = action
533
+ self.value = value
534
+
535
+ def __call__(self, fn: _ActionHandler[T]) -> _ActionHandler[T]:
536
+ _validate_handler(fn)
537
+ _register_handler(self.auth, "store", self.action, fn)
538
+ return fn
539
+
540
+
541
+ class _StoreOn:
542
+ def __init__(self, auth: Auth) -> None:
543
+ self._auth = auth
544
+ self.put = _StoreActionOn(auth, "put", types.StorePut)
545
+ """Register a handler for store put operations.
546
+
547
+ ???+ example "Example"
548
+ If using `@auth.on` to deny by default, register this handler to allow
549
+ put operations (scoped to the user's namespace):
550
+
551
+ ```python
552
+ @auth.on.store.put
553
+ async def allow_store_put(ctx: Auth.types.AuthContext, value: Auth.types.on.store.put.value):
554
+ # Allow puts, scoped to user's namespace
555
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
556
+ ```
557
+ """
558
+ self.get = _StoreActionOn(auth, "get", types.StoreGet)
559
+ """Register a handler for store get operations.
560
+
561
+ ???+ example "Example"
562
+ If using `@auth.on` to deny by default, register this handler to allow
563
+ get operations (scoped to the user's namespace):
564
+
565
+ ```python
566
+ @auth.on.store.get
567
+ async def allow_store_get(ctx: Auth.types.AuthContext, value: Auth.types.on.store.get.value):
568
+ # Allow gets, scoped to user's namespace
569
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
570
+ ```
571
+ """
572
+ self.search = _StoreActionOn(auth, "search", types.StoreSearch)
573
+ """Register a handler for store search operations.
574
+
575
+ ???+ example "Example"
576
+ If using `@auth.on` to deny by default, register this handler to allow
577
+ search operations (scoped to the user's namespace):
578
+
579
+ ```python
580
+ @auth.on.store.search
581
+ async def allow_store_search(ctx: Auth.types.AuthContext, value: Auth.types.on.store.search.value):
582
+ # Allow searches, scoped to user's namespace
583
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
584
+ ```
585
+ """
586
+ self.delete = _StoreActionOn(auth, "delete", types.StoreDelete)
587
+ """Register a handler for store delete operations.
588
+
589
+ ???+ example "Example"
590
+ If using `@auth.on` to deny by default, register this handler to allow
591
+ delete operations (scoped to the user's namespace):
592
+
593
+ ```python
594
+ @auth.on.store.delete
595
+ async def allow_store_delete(ctx: Auth.types.AuthContext, value: Auth.types.on.store.delete.value):
596
+ # Allow deletes, scoped to user's namespace
597
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
598
+ ```
599
+ """
600
+ self.list_namespaces = _StoreActionOn(
601
+ auth, "list_namespaces", types.StoreListNamespaces
602
+ )
603
+ """Register a handler for store list_namespaces operations.
604
+
605
+ ???+ example "Example"
606
+ If using `@auth.on` to deny by default, register this handler to allow
607
+ namespace listing (scoped to the user's prefix):
608
+
609
+ ```python
610
+ @auth.on.store.list_namespaces
611
+ async def allow_list_ns(ctx: Auth.types.AuthContext, value: Auth.types.on.store.list_namespaces.value):
612
+ # Allow listing, scoped to user's namespace prefix
613
+ value["namespace"] = (ctx.user.identity,)
614
+ ```
615
+ """
616
+
617
+ @typing.overload
618
+ def __call__(
619
+ self,
620
+ *,
621
+ actions: (
622
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
623
+ | Sequence[
624
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
625
+ ]
626
+ | None
627
+ ) = None,
628
+ ) -> Callable[[AHO], AHO]: ...
629
+
630
+ @typing.overload
631
+ def __call__(self, fn: AHO) -> AHO: ...
632
+
633
+ def __call__(
634
+ self,
635
+ fn: AHO | None = None,
636
+ *,
637
+ actions: (
638
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
639
+ | Sequence[
640
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
641
+ ]
642
+ | None
643
+ ) = None,
644
+ ) -> AHO | Callable[[AHO], AHO]:
645
+ """Register a handler for specific resources and actions.
646
+
647
+ Can be used as a decorator or with explicit resource/action parameters:
648
+
649
+ @auth.on.store
650
+ async def handler(): ... # Handle all store ops
651
+
652
+ @auth.on.store(actions=("put", "get", "search", "delete"))
653
+ async def handler(): ... # Handle specific store ops
654
+
655
+ @auth.on.store.put
656
+ async def handler(): ... # Handle store.put ops
657
+ """
658
+ if fn is not None:
659
+ # Used as a plain decorator
660
+ _register_handler(self._auth, "store", None, fn)
661
+ return fn
662
+
663
+ # Used with parameters, return a decorator
664
+ def decorator(
665
+ handler: AHO,
666
+ ) -> AHO:
667
+ if isinstance(actions, str):
668
+ action_list = [actions]
669
+ else:
670
+ action_list = list(actions) if actions is not None else ["*"]
671
+ for action in action_list:
672
+ _register_handler(self._auth, "store", action, handler)
673
+ return handler
674
+
675
+ return decorator
676
+
677
+
678
+ AHO = typing.TypeVar("AHO", bound=_ActionHandler[dict[str, typing.Any]])
679
+
680
+
681
+ class _On:
682
+ """Entry point for authorization handlers that control access to specific resources.
683
+
684
+ The _On class provides a flexible way to define authorization rules for different resources
685
+ and actions in your application. It supports three main usage patterns:
686
+
687
+ 1. Global handlers that run for all resources and actions
688
+ 2. Resource-specific handlers that run for all actions on a resource
689
+ 3. Resource and action specific handlers for fine-grained control
690
+
691
+ Each handler must be an async function that accepts two parameters:
692
+ - ctx (AuthContext): Contains request context and authenticated user info
693
+ - value: The data being authorized (type varies by endpoint)
694
+
695
+ The handler should return one of:
696
+ - None or True: Accept the request
697
+ - False: Reject with 403 error
698
+ - FilterType: Apply filtering rules to the response
699
+
700
+ ???+ example "Examples"
701
+
702
+ Start by denying all requests by default with a global handler,
703
+ then add specific handlers to allow access:
704
+
705
+ ```python
706
+ # Default deny: reject all requests without a specific handler
707
+ @auth.on
708
+ async def deny_all(ctx: AuthContext, value: Any) -> False:
709
+ return False
710
+ ```
711
+
712
+ Resource-specific handler to allow access (takes precedence
713
+ over the global deny handler):
714
+
715
+ ```python
716
+ @auth.on.threads
717
+ async def allow_thread_access(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
718
+ # Allow access only to threads owned by the user
719
+ return {"owner": ctx.user.identity}
720
+ ```
721
+
722
+ Resource and action specific handler:
723
+
724
+ ```python
725
+ @auth.on.threads.create
726
+ async def allow_thread_create(ctx: AuthContext, value: Any) -> None:
727
+ # Allow thread creation, stamping the owner
728
+ value.setdefault("metadata", {})["owner"] = ctx.user.identity
729
+ ```
730
+
731
+ Multiple resources or actions:
732
+
733
+ ```python
734
+ @auth.on(resources=["threads", "assistants"], actions=["read", "search"])
735
+ async def allow_reads(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
736
+ # Allow read/search, scoped to user's resources
737
+ return {"owner": ctx.user.identity}
738
+ ```
739
+ """
740
+
741
+ __slots__ = (
742
+ "_auth",
743
+ "assistants",
744
+ "crons",
745
+ "runs",
746
+ "store",
747
+ "threads",
748
+ "value",
749
+ )
750
+
751
+ def __init__(self, auth: Auth) -> None:
752
+ self._auth = auth
753
+ self.assistants = _AssistantsOn(auth, "assistants")
754
+ self.threads = _ThreadsOn(auth, "threads")
755
+ self.crons = _CronsOn(auth, "crons")
756
+ self.store = _StoreOn(auth)
757
+ self.value = dict[str, typing.Any]
758
+
759
+ @typing.overload
760
+ def __call__(
761
+ self,
762
+ *,
763
+ resources: str | Sequence[str],
764
+ actions: str | Sequence[str] | None = None,
765
+ ) -> Callable[[AHO], AHO]: ...
766
+
767
+ @typing.overload
768
+ def __call__(self, fn: AHO) -> AHO: ...
769
+
770
+ def __call__(
771
+ self,
772
+ fn: AHO | None = None,
773
+ *,
774
+ resources: str | Sequence[str] | None = None,
775
+ actions: str | Sequence[str] | None = None,
776
+ ) -> AHO | Callable[[AHO], AHO]:
777
+ """Register a handler for specific resources and actions.
778
+
779
+ Can be used as a decorator or with explicit resource/action parameters:
780
+
781
+ @auth.on
782
+ async def handler(): ... # Global handler
783
+
784
+ @auth.on(resources="threads")
785
+ async def handler(): ... # types.Handler for all thread actions
786
+
787
+ @auth.on(resources="threads", actions="create")
788
+ async def handler(): ... # types.Handler for thread creation
789
+ """
790
+ if fn is not None:
791
+ # Used as a plain decorator
792
+ _register_handler(self._auth, None, None, fn)
793
+ return fn
794
+
795
+ # Used with parameters, return a decorator
796
+ def decorator(
797
+ handler: AHO,
798
+ ) -> AHO:
799
+ if isinstance(resources, str):
800
+ resource_list = [resources]
801
+ else:
802
+ resource_list = list(resources) if resources is not None else ["*"]
803
+
804
+ if isinstance(actions, str):
805
+ action_list = [actions]
806
+ else:
807
+ action_list = list(actions) if actions is not None else ["*"]
808
+ for resource in resource_list:
809
+ for action in action_list:
810
+ _register_handler(self._auth, resource, action, handler)
811
+ return handler
812
+
813
+ return decorator
814
+
815
+
816
+ def _register_handler(
817
+ auth: Auth,
818
+ resource: str | None,
819
+ action: str | None,
820
+ fn: types.Handler,
821
+ ) -> types.Handler:
822
+ _validate_handler(fn)
823
+ resource = resource or "*"
824
+ action = action or "*"
825
+ if resource == "*" and action == "*":
826
+ if auth._global_handlers:
827
+ raise ValueError("Global handler already set.")
828
+ auth._global_handlers.append(fn)
829
+ else:
830
+ r = resource if resource is not None else "*"
831
+ a = action if action is not None else "*"
832
+ if (r, a) in auth._handlers:
833
+ raise ValueError(f"types.Handler already set for {r}, {a}.")
834
+ auth._handlers[(r, a)] = [fn]
835
+ return fn
836
+
837
+
838
+ def _validate_handler(fn: Callable[..., typing.Any]) -> None:
839
+ """Validates that an auth handler function meets the required signature.
840
+
841
+ Auth handlers must:
842
+ 1. Be async functions
843
+ 2. Accept a ctx parameter of type AuthContext
844
+ 3. Accept a value parameter for the data being authorized
845
+ """
846
+ if not inspect.iscoroutinefunction(fn):
847
+ raise ValueError(
848
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must be an async function. "
849
+ "Add 'async' before 'def' to make it asynchronous and ensure"
850
+ " any IO operations are non-blocking."
851
+ )
852
+
853
+ sig = inspect.signature(fn)
854
+ if "ctx" not in sig.parameters:
855
+ raise ValueError(
856
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must have a 'ctx: AuthContext' parameter. "
857
+ "Update the function signature to include this required parameter."
858
+ )
859
+ if "value" not in sig.parameters:
860
+ raise ValueError(
861
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must have a 'value' parameter. "
862
+ " The value contains the mutable data being sent to the endpoint."
863
+ "Update the function signature to include this required parameter."
864
+ )
865
+
866
+
867
+ def is_studio_user(
868
+ user: types.MinimalUser | types.BaseUser | types.MinimalUserDict,
869
+ ) -> bool:
870
+ return (
871
+ isinstance(user, types.StudioUser)
872
+ or (isinstance(user, dict) and user.get("kind") == "StudioUser") # ty: ignore[invalid-argument-type]
873
+ )
874
+
875
+
876
+ __all__ = ["Auth", "exceptions", "types"]
python/user_packages/Python313/site-packages/langgraph_sdk/auth/exceptions.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exceptions used in the auth system."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http
6
+ from collections.abc import Mapping
7
+
8
+
9
+ class HTTPException(Exception):
10
+ """HTTP exception that you can raise to return a specific HTTP error response.
11
+
12
+ Since this is defined in the auth module, we default to a 401 status code.
13
+
14
+ Args:
15
+ status_code: HTTP status code for the error. Defaults to 401 "Unauthorized".
16
+ detail: Detailed error message. If `None`, uses a default
17
+ message based on the status code.
18
+ headers: Additional HTTP headers to include in the error response.
19
+
20
+ Example:
21
+ Default:
22
+ ```python
23
+ raise HTTPException()
24
+ # HTTPException(status_code=401, detail='Unauthorized')
25
+ ```
26
+
27
+ Add headers:
28
+ ```python
29
+ raise HTTPException(headers={"X-Custom-Header": "Custom Value"})
30
+ # HTTPException(status_code=401, detail='Unauthorized', headers={"WWW-Authenticate": "Bearer"})
31
+ ```
32
+
33
+ Custom error:
34
+ ```python
35
+ raise HTTPException(status_code=404, detail="Not found")
36
+ ```
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ status_code: int = 401,
42
+ detail: str | None = None,
43
+ headers: Mapping[str, str] | None = None,
44
+ ) -> None:
45
+ if detail is None:
46
+ detail = http.HTTPStatus(status_code).phrase
47
+ self.status_code = status_code
48
+ self.detail = detail
49
+ self.headers = headers
50
+
51
+ def __str__(self) -> str:
52
+ return f"{self.status_code}: {self.detail}"
53
+
54
+ def __repr__(self) -> str:
55
+ class_name = self.__class__.__name__
56
+ return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
57
+
58
+
59
+ __all__ = ["HTTPException"]
python/user_packages/Python313/site-packages/langgraph_sdk/auth/types.py ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authentication and authorization types for LangGraph.
2
+
3
+ This module defines the core types used for authentication, authorization, and
4
+ request handling in LangGraph. It includes user protocols, authentication contexts,
5
+ and typed dictionaries for various API operations.
6
+
7
+ Note:
8
+ All typing.TypedDict classes use total=False to make all fields typing.Optional by default.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import typing
14
+ from collections.abc import Awaitable, Callable, Sequence
15
+ from dataclasses import dataclass
16
+ from datetime import datetime
17
+ from uuid import UUID
18
+
19
+ import typing_extensions
20
+
21
+ RunStatus = typing.Literal["pending", "error", "success", "timeout", "interrupted"]
22
+ """Status of a run execution.
23
+
24
+ Values:
25
+ - pending: Run is queued or in progress
26
+ - error: Run failed with an error
27
+ - success: Run completed successfully
28
+ - timeout: Run exceeded time limit
29
+ - interrupted: Run was manually interrupted
30
+ """
31
+
32
+ MultitaskStrategy = typing.Literal["reject", "rollback", "interrupt", "enqueue"]
33
+ """Strategy for handling multiple concurrent tasks.
34
+
35
+ Values:
36
+ - reject: Reject new tasks while one is in progress
37
+ - rollback: Cancel current task and start new one
38
+ - interrupt: Interrupt current task and start new one
39
+ - enqueue: Queue new tasks to run after current one
40
+ """
41
+
42
+ OnConflictBehavior = typing.Literal["raise", "do_nothing"]
43
+ """Behavior when encountering conflicts.
44
+
45
+ Values:
46
+ - raise: Raise an exception on conflict
47
+ - do_nothing: Silently ignore conflicts
48
+ """
49
+
50
+ IfNotExists = typing.Literal["create", "reject"]
51
+ """Behavior when an entity doesn't exist.
52
+
53
+ Values:
54
+ - create: Create the entity
55
+ - reject: Reject the operation
56
+ """
57
+
58
+ FilterType = (
59
+ dict[
60
+ str,
61
+ str
62
+ | dict[typing.Literal["$eq", "$contains"], str]
63
+ | dict[typing.Literal["$contains"], list[str]],
64
+ ]
65
+ | dict[str, str]
66
+ )
67
+ """Response type for authorization handlers.
68
+
69
+ Supports exact matches and operators:
70
+ - Exact match shorthand: {"field": "value"}
71
+ - Exact match: {"field": {"$eq": "value"}}
72
+ - Contains (membership): {"field": {"$contains": "value"}}
73
+ - Contains (subset containment): {"field": {"$contains": ["value1", "value2"]}}
74
+
75
+ Subset containment is only supported by newer versions of the LangGraph dev server;
76
+ install langgraph-runtime-inmem >= 0.14.1 to use this filter variant.
77
+
78
+ ???+ example "Examples"
79
+
80
+ Simple exact match filter for the resource owner:
81
+
82
+ ```python
83
+ filter = {"owner": "user-abcd123"}
84
+ ```
85
+
86
+ Explicit version of the exact match filter:
87
+
88
+ ```python
89
+ filter = {"owner": {"$eq": "user-abcd123"}}
90
+ ```
91
+
92
+ Containment (membership of a single element):
93
+
94
+ ```python
95
+ filter = {"participants": {"$contains": "user-abcd123"}}
96
+ ```
97
+
98
+ Containment (subset containment; all values must be present, but order doesn't matter):
99
+
100
+ ```python
101
+ filter = {"participants": {"$contains": ["user-abcd123", "user-efgh456"]}}
102
+ ```
103
+
104
+ Combining filters (treated as a logical `AND`):
105
+
106
+ ```python
107
+ filter = {"owner": "user-abcd123", "participants": {"$contains": "user-efgh456"}}
108
+ ```
109
+ """
110
+
111
+ ThreadStatus = typing.Literal["idle", "busy", "interrupted", "error"]
112
+ """Status of a thread.
113
+
114
+ Values:
115
+ - idle: Thread is available for work
116
+ - busy: Thread is currently processing
117
+ - interrupted: Thread was interrupted
118
+ - error: Thread encountered an error
119
+ """
120
+
121
+ MetadataInput = dict[str, typing.Any]
122
+ """Type for arbitrary metadata attached to entities.
123
+
124
+ Allows storing custom key-value pairs with any entity.
125
+ Keys must be strings, values can be any JSON-serializable type.
126
+
127
+ ???+ example "Examples"
128
+
129
+ ```python
130
+ metadata = {
131
+ "created_by": "user123",
132
+ "priority": 1,
133
+ "tags": ["important", "urgent"]
134
+ }
135
+ ```
136
+ """
137
+
138
+ HandlerResult = None | bool | FilterType
139
+ """The result of a handler can be:
140
+ * None | True: accept the request.
141
+ * False: reject the request with a 403 error
142
+ * FilterType: filter to apply
143
+ """
144
+
145
+ Handler = Callable[..., Awaitable[HandlerResult]]
146
+
147
+ T = typing.TypeVar("T")
148
+
149
+
150
+ @typing.runtime_checkable
151
+ class MinimalUser(typing.Protocol):
152
+ """User objects must at least expose the identity property."""
153
+
154
+ @property
155
+ def identity(self) -> str:
156
+ """The unique identifier for the user.
157
+
158
+ This could be a username, email, or any other unique identifier used
159
+ to distinguish between different users in the system.
160
+ """
161
+ ...
162
+
163
+
164
+ class MinimalUserDict(typing.TypedDict, total=False):
165
+ """The dictionary representation of a user."""
166
+
167
+ identity: typing_extensions.Required[str]
168
+ """The required unique identifier for the user."""
169
+ display_name: str
170
+ """The typing.Optional display name for the user."""
171
+ is_authenticated: bool
172
+ """Whether the user is authenticated. Defaults to True."""
173
+ permissions: Sequence[str]
174
+ """A list of permissions associated with the user.
175
+
176
+ You can use these in your `@auth.on` authorization logic to determine
177
+ access permissions to different resources.
178
+ """
179
+
180
+
181
+ @typing.runtime_checkable
182
+ class BaseUser(typing.Protocol):
183
+ """The base ASGI user protocol"""
184
+
185
+ @property
186
+ def is_authenticated(self) -> bool:
187
+ """Whether the user is authenticated."""
188
+ ...
189
+
190
+ @property
191
+ def display_name(self) -> str:
192
+ """The display name of the user."""
193
+ ...
194
+
195
+ @property
196
+ def identity(self) -> str:
197
+ """The unique identifier for the user."""
198
+ ...
199
+
200
+ @property
201
+ def permissions(self) -> Sequence[str]:
202
+ """The permissions associated with the user."""
203
+ ...
204
+
205
+ def __getitem__(self, key):
206
+ """Get a key from your minimal user dict."""
207
+ ...
208
+
209
+ def __contains__(self, key):
210
+ """Check if a property exists."""
211
+ ...
212
+
213
+ def __iter__(self):
214
+ """Iterate over the keys of the user."""
215
+ ...
216
+
217
+
218
+ class StudioUser:
219
+ """A user object that's populated from authenticated requests from the LangGraph studio.
220
+
221
+ Note: Studio auth can be disabled in your `langgraph.json` config.
222
+
223
+ ```json
224
+ {
225
+ "auth": {
226
+ "disable_studio_auth": true
227
+ }
228
+ }
229
+ ```
230
+
231
+ You can use `isinstance` checks in your authorization handlers (`@auth.on`) to control access specifically
232
+ for developers accessing the instance from the LangGraph Studio UI.
233
+
234
+ ???+ example "Examples"
235
+
236
+ Use `@auth.on` to deny by default, but allow Studio users through:
237
+
238
+ ```python
239
+ @auth.on
240
+ async def deny_all_except_studio(ctx: Auth.types.AuthContext, value: Any) -> bool:
241
+ # Allow Studio users, deny everyone else by default
242
+ if isinstance(ctx.user, Auth.types.StudioUser):
243
+ return True
244
+ return False
245
+
246
+ # Then add specific handlers to allow access for non-Studio users
247
+ @auth.on.threads
248
+ async def allow_thread_access(ctx: Auth.types.AuthContext, value: Any) -> Auth.types.FilterType:
249
+ return {"owner": ctx.user.identity}
250
+ ```
251
+ """
252
+
253
+ __slots__ = ("_is_authenticated", "_permissions", "username")
254
+
255
+ def __init__(self, username: str, is_authenticated: bool = False) -> None:
256
+ self.username = username
257
+ self._is_authenticated = is_authenticated
258
+ self._permissions = ["authenticated"] if is_authenticated else []
259
+
260
+ @property
261
+ def is_authenticated(self) -> bool:
262
+ return self._is_authenticated
263
+
264
+ @property
265
+ def display_name(self) -> str:
266
+ return self.username
267
+
268
+ @property
269
+ def identity(self) -> str:
270
+ return self.username
271
+
272
+ @property
273
+ def permissions(self) -> Sequence[str]:
274
+ return self._permissions
275
+
276
+
277
+ Authenticator = Callable[
278
+ ...,
279
+ Awaitable[
280
+ MinimalUser
281
+ | str
282
+ | BaseUser
283
+ | MinimalUserDict
284
+ | typing.Mapping[str, typing.Any],
285
+ ],
286
+ ]
287
+ """Type for authentication functions.
288
+
289
+ An authenticator can return either:
290
+ 1. A string (user_id)
291
+ 2. A dict containing {"identity": str, "permissions": list[str]}
292
+ 3. An object with identity and permissions properties
293
+
294
+ Permissions can be used downstream by your authorization logic to determine
295
+ access permissions to different resources.
296
+
297
+ The authenticate decorator will automatically inject any of the following parameters
298
+ by name if they are included in your function signature:
299
+
300
+ Parameters:
301
+ request (Request): The raw ASGI request object
302
+ body (dict): The parsed request body
303
+ path (str): The request path
304
+ method (str): The HTTP method (GET, POST, etc.)
305
+ path_params (dict[str, str] | None): URL path parameters
306
+ query_params (dict[str, str] | None): URL query parameters
307
+ headers (dict[str, bytes] | None): Request headers
308
+ authorization (str | None): The Authorization header value (e.g. "Bearer <token>")
309
+
310
+ ???+ example "Examples"
311
+
312
+ Basic authentication with token:
313
+
314
+ ```python
315
+ from langgraph_sdk import Auth
316
+
317
+ auth = Auth()
318
+
319
+ @auth.authenticate
320
+ async def authenticate1(authorization: str) -> Auth.types.MinimalUserDict:
321
+ return await get_user(authorization)
322
+ ```
323
+
324
+ Authentication with multiple parameters:
325
+
326
+ ```
327
+ @auth.authenticate
328
+ async def authenticate2(
329
+ method: str,
330
+ path: str,
331
+ headers: dict[str, bytes]
332
+ ) -> Auth.types.MinimalUserDict:
333
+ # Custom auth logic using method, path and headers
334
+ user = verify_request(method, path, headers)
335
+ return user
336
+ ```
337
+
338
+ Accepting the raw ASGI request:
339
+
340
+ ```python
341
+ MY_SECRET = "my-secret-key"
342
+ @auth.authenticate
343
+ async def get_current_user(request: Request) -> Auth.types.MinimalUserDict:
344
+ try:
345
+ token = (request.headers.get("authorization") or "").split(" ", 1)[1]
346
+ payload = jwt.decode(token, MY_SECRET, algorithms=["HS256"])
347
+ except (IndexError, InvalidTokenError):
348
+ raise HTTPException(
349
+ status_code=401,
350
+ detail="Invalid token",
351
+ headers={"WWW-Authenticate": "Bearer"},
352
+ )
353
+
354
+ async with httpx.AsyncClient() as client:
355
+ response = await client.get(
356
+ f"https://api.myauth-provider.com/auth/v1/user",
357
+ headers={"Authorization": f"Bearer {MY_SECRET}"}
358
+ )
359
+ if response.status_code != 200:
360
+ raise HTTPException(status_code=401, detail="User not found")
361
+
362
+ user_data = response.json()
363
+ return {
364
+ "identity": user_data["id"],
365
+ "display_name": user_data.get("name"),
366
+ "permissions": user_data.get("permissions", []),
367
+ "is_authenticated": True,
368
+ }
369
+ ```
370
+ """
371
+
372
+
373
+ @dataclass(slots=True)
374
+ class BaseAuthContext:
375
+ """Base class for authentication context.
376
+
377
+ Provides the fundamental authentication information needed for
378
+ authorization decisions.
379
+ """
380
+
381
+ permissions: Sequence[str]
382
+ """The permissions granted to the authenticated user."""
383
+
384
+ user: BaseUser
385
+ """The authenticated user."""
386
+
387
+
388
+ @typing.final
389
+ @dataclass(slots=True)
390
+ class AuthContext(BaseAuthContext):
391
+ """Complete authentication context with resource and action information.
392
+
393
+ Extends BaseAuthContext with specific resource and action being accessed,
394
+ allowing for fine-grained access control decisions.
395
+ """
396
+
397
+ resource: typing.Literal["runs", "threads", "crons", "assistants", "store"]
398
+ """The resource being accessed."""
399
+
400
+ action: typing.Literal[
401
+ "create",
402
+ "read",
403
+ "update",
404
+ "delete",
405
+ "search",
406
+ "create_run",
407
+ "put",
408
+ "get",
409
+ "list_namespaces",
410
+ ]
411
+ """The action being performed on the resource.
412
+
413
+ Most resources support the following actions:
414
+ - create: Create a new resource
415
+ - read: Read information about a resource
416
+ - update: Update an existing resource
417
+ - delete: Delete a resource
418
+ - search: Search for resources
419
+
420
+ The store supports the following actions:
421
+ - put: Add or update an item in the store
422
+ - get: Get an item from the store
423
+ - search: Search for items within a namespace prefix
424
+ - delete: Delete an item from the store
425
+ - list_namespaces: List the namespaces in the store
426
+ """
427
+
428
+
429
+ class ThreadTTL(typing.TypedDict, total=False):
430
+ """Time-to-live configuration for a thread.
431
+
432
+ Matches the OpenAPI schema where TTL is represented as an object with
433
+ an optional strategy and a time value in minutes.
434
+ """
435
+
436
+ strategy: typing.Literal["delete"]
437
+ """TTL strategy. Currently only 'delete' is supported."""
438
+
439
+ ttl: int
440
+ """Time-to-live in minutes from now until the thread should be swept."""
441
+
442
+
443
+ class ThreadsCreate(typing.TypedDict, total=False):
444
+ """Parameters for creating a new thread.
445
+
446
+ ???+ example "Examples"
447
+
448
+ ```python
449
+ create_params = {
450
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
451
+ "metadata": {"owner": "user123"},
452
+ "if_exists": "do_nothing"
453
+ }
454
+ ```
455
+ """
456
+
457
+ thread_id: UUID
458
+ """Unique identifier for the thread."""
459
+
460
+ metadata: MetadataInput
461
+ """typing.Optional metadata to attach to the thread."""
462
+
463
+ if_exists: OnConflictBehavior
464
+ """Behavior when a thread with the same ID already exists."""
465
+
466
+ ttl: ThreadTTL
467
+ """Optional TTL configuration for the thread."""
468
+
469
+
470
+ class ThreadsRead(typing.TypedDict, total=False):
471
+ """Parameters for reading thread state or run information.
472
+
473
+ This type is used in three contexts:
474
+ 1. Reading thread, thread version, or thread state information: Only thread_id is provided
475
+ 2. Reading run information: Both thread_id and run_id are provided
476
+ """
477
+
478
+ thread_id: UUID
479
+ """Unique identifier for the thread."""
480
+
481
+ run_id: UUID | None
482
+ """Run ID to filter by. Only used when reading run information within a thread."""
483
+
484
+
485
+ class ThreadsUpdate(typing.TypedDict, total=False):
486
+ """Parameters for updating a thread or run.
487
+
488
+ Called for updates to a thread, thread version, or run
489
+ cancellation.
490
+ """
491
+
492
+ thread_id: UUID
493
+ """Unique identifier for the thread."""
494
+
495
+ metadata: MetadataInput
496
+ """typing.Optional metadata to update."""
497
+
498
+ action: typing.Literal["interrupt", "rollback"] | None
499
+ """typing.Optional action to perform on the thread."""
500
+
501
+
502
+ class ThreadsDelete(typing.TypedDict, total=False):
503
+ """Parameters for deleting a thread.
504
+
505
+ Called for deletes to a thread, thread version, or run
506
+ """
507
+
508
+ thread_id: UUID
509
+ """Unique identifier for the thread."""
510
+
511
+ run_id: UUID | None
512
+ """typing.Optional run ID to filter by."""
513
+
514
+
515
+ class ThreadsSearch(typing.TypedDict, total=False):
516
+ """Parameters for searching threads.
517
+
518
+ Called for searches to threads or runs.
519
+ """
520
+
521
+ metadata: MetadataInput
522
+ """typing.Optional metadata to filter by."""
523
+
524
+ values: MetadataInput
525
+ """typing.Optional values to filter by."""
526
+
527
+ status: ThreadStatus | None
528
+ """typing.Optional status to filter by."""
529
+
530
+ limit: int
531
+ """Maximum number of results to return."""
532
+
533
+ offset: int
534
+ """Offset for pagination."""
535
+
536
+ ids: Sequence[UUID] | None
537
+ """typing.Optional list of thread IDs to filter by."""
538
+
539
+ thread_id: UUID | None
540
+ """typing.Optional thread ID to filter by."""
541
+
542
+
543
+ class RunsCreate(typing.TypedDict, total=False):
544
+ """Payload for creating a run.
545
+
546
+ ???+ example "Examples"
547
+
548
+ ```python
549
+ create_params = {
550
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
551
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
552
+ "run_id": UUID("123e4567-e89b-12d3-a456-426614174002"),
553
+ "status": "pending",
554
+ "metadata": {"owner": "user123"},
555
+ "prevent_insert_if_inflight": True,
556
+ "multitask_strategy": "reject",
557
+ "if_not_exists": "create",
558
+ "after_seconds": 10,
559
+ "kwargs": {"key": "value"},
560
+ "action": "interrupt"
561
+ }
562
+ ```
563
+ """
564
+
565
+ assistant_id: UUID | None
566
+ """typing.Optional assistant ID to use for this run."""
567
+
568
+ thread_id: UUID | None
569
+ """typing.Optional thread ID to use for this run."""
570
+
571
+ run_id: UUID | None
572
+ """typing.Optional run ID to use for this run."""
573
+
574
+ status: RunStatus | None
575
+ """typing.Optional status for this run."""
576
+
577
+ metadata: MetadataInput
578
+ """typing.Optional metadata for the run."""
579
+
580
+ prevent_insert_if_inflight: bool
581
+ """Prevent inserting a new run if one is already in flight."""
582
+
583
+ multitask_strategy: MultitaskStrategy
584
+ """Multitask strategy for this run."""
585
+
586
+ if_not_exists: IfNotExists
587
+ """IfNotExists for this run."""
588
+
589
+ after_seconds: int
590
+ """Number of seconds to wait before creating the run."""
591
+
592
+ kwargs: dict[str, typing.Any]
593
+ """Keyword arguments to pass to the run."""
594
+
595
+ action: typing.Literal["interrupt", "rollback"] | None
596
+ """Action to take if updating an existing run."""
597
+
598
+
599
+ class AssistantsCreate(typing.TypedDict, total=False):
600
+ """Payload for creating an assistant.
601
+
602
+ ???+ example "Examples"
603
+
604
+ ```python
605
+ create_params = {
606
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
607
+ "graph_id": "graph123",
608
+ "config": {"tags": ["tag1", "tag2"]},
609
+ "context": {"key": "value"},
610
+ "metadata": {"owner": "user123"},
611
+ "if_exists": "do_nothing",
612
+ "name": "Assistant 1"
613
+ }
614
+ ```
615
+ """
616
+
617
+ assistant_id: UUID
618
+ """Unique identifier for the assistant."""
619
+
620
+ graph_id: str
621
+ """Graph ID to use for this assistant."""
622
+
623
+ config: dict[str, typing.Any]
624
+ """typing.Optional configuration for the assistant."""
625
+
626
+ context: dict[str, typing.Any]
627
+
628
+ metadata: MetadataInput
629
+ """typing.Optional metadata to attach to the assistant."""
630
+
631
+ if_exists: OnConflictBehavior
632
+ """Behavior when an assistant with the same ID already exists."""
633
+
634
+ name: str
635
+ """Name of the assistant."""
636
+
637
+
638
+ class AssistantsRead(typing.TypedDict, total=False):
639
+ """Payload for reading an assistant.
640
+
641
+ ???+ example "Examples"
642
+
643
+ ```python
644
+ read_params = {
645
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
646
+ "metadata": {"owner": "user123"}
647
+ }
648
+ ```
649
+ """
650
+
651
+ assistant_id: UUID
652
+ """Unique identifier for the assistant."""
653
+
654
+ metadata: MetadataInput
655
+ """typing.Optional metadata to filter by."""
656
+
657
+
658
+ class AssistantsUpdate(typing.TypedDict, total=False):
659
+ """Payload for updating an assistant.
660
+
661
+ ???+ example "Examples"
662
+
663
+ ```python
664
+ update_params = {
665
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
666
+ "graph_id": "graph123",
667
+ "config": {"tags": ["tag1", "tag2"]},
668
+ "context": {"key": "value"},
669
+ "metadata": {"owner": "user123"},
670
+ "name": "Assistant 1",
671
+ "version": 1
672
+ }
673
+ ```
674
+ """
675
+
676
+ assistant_id: UUID
677
+ """Unique identifier for the assistant."""
678
+
679
+ graph_id: str | None
680
+ """typing.Optional graph ID to update."""
681
+
682
+ config: dict[str, typing.Any]
683
+ """typing.Optional configuration to update."""
684
+
685
+ context: dict[str, typing.Any]
686
+ """The static context of the assistant."""
687
+
688
+ metadata: MetadataInput
689
+ """typing.Optional metadata to update."""
690
+
691
+ name: str | None
692
+ """typing.Optional name to update."""
693
+
694
+ version: int | None
695
+ """typing.Optional version to update."""
696
+
697
+
698
+ class AssistantsDelete(typing.TypedDict):
699
+ """Payload for deleting an assistant.
700
+
701
+ ???+ example "Examples"
702
+
703
+ ```python
704
+ delete_params = {
705
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000")
706
+ }
707
+ ```
708
+ """
709
+
710
+ assistant_id: UUID
711
+ """Unique identifier for the assistant."""
712
+
713
+
714
+ class AssistantsSearch(typing.TypedDict):
715
+ """Payload for searching assistants.
716
+
717
+ ???+ example "Examples"
718
+
719
+ ```python
720
+ search_params = {
721
+ "graph_id": "graph123",
722
+ "metadata": {"owner": "user123"},
723
+ "limit": 10,
724
+ "offset": 0
725
+ }
726
+ ```
727
+ """
728
+
729
+ graph_id: str | None
730
+ """typing.Optional graph ID to filter by."""
731
+
732
+ metadata: MetadataInput
733
+ """typing.Optional metadata to filter by."""
734
+
735
+ limit: int
736
+ """Maximum number of results to return."""
737
+
738
+ offset: int
739
+ """Offset for pagination."""
740
+
741
+
742
+ class CronsCreate(typing.TypedDict, total=False):
743
+ """Payload for creating a cron job.
744
+
745
+ ???+ example "Examples"
746
+
747
+ ```python
748
+ create_params = {
749
+ "payload": {"key": "value"},
750
+ "schedule": "0 0 * * *",
751
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
752
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
753
+ "user_id": "user123",
754
+ "end_time": datetime(2024, 3, 16, 10, 0, 0)
755
+ }
756
+ ```
757
+ """
758
+
759
+ payload: dict[str, typing.Any]
760
+ """Payload for the cron job."""
761
+
762
+ schedule: str
763
+ """Schedule for the cron job."""
764
+
765
+ cron_id: UUID | None
766
+ """typing.Optional unique identifier for the cron job."""
767
+
768
+ thread_id: UUID | None
769
+ """typing.Optional thread ID to use for this cron job."""
770
+
771
+ user_id: str | None
772
+ """typing.Optional user ID to use for this cron job."""
773
+
774
+ end_time: datetime | None
775
+ """typing.Optional end time for the cron job."""
776
+
777
+
778
+ class CronsDelete(typing.TypedDict):
779
+ """Payload for deleting a cron job.
780
+
781
+ ???+ example "Examples"
782
+
783
+ ```python
784
+ delete_params = {
785
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
786
+ }
787
+ ```
788
+ """
789
+
790
+ cron_id: UUID
791
+ """Unique identifier for the cron job."""
792
+
793
+
794
+ class CronsRead(typing.TypedDict):
795
+ """Payload for reading a cron job.
796
+
797
+ ???+ example "Examples"
798
+
799
+ ```python
800
+ read_params = {
801
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
802
+ }
803
+ ```
804
+ """
805
+
806
+ cron_id: UUID
807
+ """Unique identifier for the cron job."""
808
+
809
+
810
+ class CronsUpdate(typing.TypedDict, total=False):
811
+ """Payload for updating a cron job.
812
+
813
+ ???+ example "Examples"
814
+
815
+ ```python
816
+ update_params = {
817
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
818
+ "payload": {"key": "value"},
819
+ "schedule": "0 0 * * *"
820
+ }
821
+ ```
822
+ """
823
+
824
+ cron_id: UUID
825
+ """Unique identifier for the cron job."""
826
+
827
+ payload: dict[str, typing.Any] | None
828
+ """typing.Optional payload to update."""
829
+
830
+ schedule: str | None
831
+ """typing.Optional schedule to update."""
832
+
833
+
834
+ class CronsSearch(typing.TypedDict, total=False):
835
+ """Payload for searching cron jobs.
836
+
837
+ ???+ example "Examples"
838
+
839
+ ```python
840
+ search_params = {
841
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
842
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
843
+ "limit": 10,
844
+ "offset": 0
845
+ }
846
+ ```
847
+ """
848
+
849
+ assistant_id: UUID | None
850
+ """typing.Optional assistant ID to filter by."""
851
+
852
+ thread_id: UUID | None
853
+ """typing.Optional thread ID to filter by."""
854
+
855
+ limit: int
856
+ """Maximum number of results to return."""
857
+
858
+ offset: int
859
+ """Offset for pagination."""
860
+
861
+
862
+ class StoreGet(typing.TypedDict):
863
+ """Operation to retrieve a specific item by its namespace and key.
864
+
865
+ This dict is mutable — auth handlers can modify `namespace` to enforce
866
+ access scoping (e.g., prepending the user's identity).
867
+ """
868
+
869
+ namespace: tuple[str, ...]
870
+ """Hierarchical path that uniquely identifies the item's location.
871
+
872
+ Auth handlers can modify this to enforce per-user scoping.
873
+ """
874
+
875
+ key: str
876
+ """Unique identifier for the item within its specific namespace."""
877
+
878
+
879
+ class StoreSearch(typing.TypedDict):
880
+ """Operation to search for items within a specified namespace hierarchy.
881
+
882
+ This dict is mutable — auth handlers can modify `namespace` to enforce
883
+ access scoping (e.g., prepending the user's identity).
884
+ """
885
+
886
+ namespace: tuple[str, ...]
887
+ """Prefix filter for defining the search scope.
888
+
889
+ Auth handlers can modify this to enforce per-user scoping.
890
+ """
891
+
892
+ filter: dict[str, typing.Any] | None
893
+ """Key-value pairs for filtering results based on exact matches or comparison operators."""
894
+
895
+ limit: int
896
+ """Maximum number of items to return in the search results."""
897
+
898
+ offset: int
899
+ """Number of matching items to skip for pagination."""
900
+
901
+ query: str | None
902
+ """Natural language search query for semantic search capabilities."""
903
+
904
+
905
+ class StoreListNamespaces(typing.TypedDict):
906
+ """Operation to list and filter namespaces in the store.
907
+
908
+ This dict is mutable — auth handlers can modify `namespace` (the prefix)
909
+ to enforce access scoping (e.g., prepending the user's identity).
910
+ """
911
+
912
+ namespace: tuple[str, ...] | None
913
+ """Prefix filter for namespaces. Can be `None` if no prefix was provided.
914
+
915
+ Auth handlers can modify this to enforce per-user scoping. When `None`,
916
+ handlers should set it to `(user_id,)` to scope listing to the user's namespaces.
917
+ """
918
+
919
+ suffix: tuple[str, ...] | None
920
+ """Optional conditions for filtering namespaces."""
921
+
922
+ max_depth: int | None
923
+ """Maximum depth of namespace hierarchy to return.
924
+
925
+ Note:
926
+ Namespaces deeper than this level will be truncated.
927
+ """
928
+
929
+ limit: int
930
+ """Maximum number of namespaces to return."""
931
+
932
+ offset: int
933
+ """Number of namespaces to skip for pagination."""
934
+
935
+
936
+ class StorePut(typing.TypedDict):
937
+ """Operation to store, update, or delete an item in the store.
938
+
939
+ This dict is mutable — auth handlers can modify `namespace` to enforce
940
+ access scoping (e.g., prepending the user's identity).
941
+ """
942
+
943
+ namespace: tuple[str, ...]
944
+ """Hierarchical path that identifies the location of the item.
945
+
946
+ Auth handlers can modify this to enforce per-user scoping.
947
+ """
948
+
949
+ key: str
950
+ """Unique identifier for the item within its namespace."""
951
+
952
+ value: dict[str, typing.Any] | None
953
+ """The data to store, or `None` to mark the item for deletion."""
954
+
955
+ index: typing.Literal[False] | list[str] | None
956
+ """Optional index configuration for full-text search."""
957
+
958
+
959
+ class StoreDelete(typing.TypedDict):
960
+ """Operation to delete an item from the store.
961
+
962
+ This dict is mutable — auth handlers can modify `namespace` to enforce
963
+ access scoping (e.g., prepending the user's identity).
964
+ """
965
+
966
+ namespace: tuple[str, ...]
967
+ """Hierarchical path that uniquely identifies the item's location.
968
+
969
+ Auth handlers can modify this to enforce per-user scoping.
970
+ """
971
+
972
+ key: str
973
+ """Unique identifier for the item within its specific namespace."""
974
+
975
+
976
+ class on:
977
+ """Namespace for type definitions of different API operations.
978
+
979
+ This class organizes type definitions for create, read, update, delete,
980
+ and search operations across different resources (threads, assistants, crons).
981
+
982
+ ???+ note "Usage"
983
+ Start by denying all requests by default, then add handlers to allow access:
984
+
985
+ ```python
986
+ from langgraph_sdk import Auth
987
+
988
+ auth = Auth()
989
+
990
+ # Default deny: reject all requests without a specific handler
991
+ @auth.on
992
+ async def deny_all(ctx: Auth.types.AuthContext, value: Auth.on.value):
993
+ return False
994
+
995
+ # Allow thread creation, stamping the owner
996
+ @auth.on.threads.create
997
+ async def allow_thread_create(ctx: Auth.types.AuthContext, value: Auth.on.threads.create.value):
998
+ value.setdefault("metadata", {})["owner"] = ctx.user.identity
999
+
1000
+ # Allow assistant search, scoped to user's resources
1001
+ @auth.on.assistants.search
1002
+ async def allow_assistant_search(ctx: Auth.types.AuthContext, value: Auth.on.assistants.search.value):
1003
+ return {"owner": ctx.user.identity}
1004
+ ```
1005
+ """
1006
+
1007
+ value = dict[str, typing.Any]
1008
+
1009
+ class threads:
1010
+ """Types for thread-related operations."""
1011
+
1012
+ value = (
1013
+ ThreadsCreate | ThreadsRead | ThreadsUpdate | ThreadsDelete | ThreadsSearch
1014
+ )
1015
+
1016
+ class create:
1017
+ """Type for thread creation parameters."""
1018
+
1019
+ value = ThreadsCreate
1020
+
1021
+ class create_run:
1022
+ """Type for creating or streaming a run."""
1023
+
1024
+ value = RunsCreate
1025
+
1026
+ class read:
1027
+ """Type for thread read parameters."""
1028
+
1029
+ value = ThreadsRead
1030
+
1031
+ class update:
1032
+ """Type for thread update parameters."""
1033
+
1034
+ value = ThreadsUpdate
1035
+
1036
+ class delete:
1037
+ """Type for thread deletion parameters."""
1038
+
1039
+ value = ThreadsDelete
1040
+
1041
+ class search:
1042
+ """Type for thread search parameters."""
1043
+
1044
+ value = ThreadsSearch
1045
+
1046
+ class assistants:
1047
+ """Types for assistant-related operations."""
1048
+
1049
+ value = (
1050
+ AssistantsCreate
1051
+ | AssistantsRead
1052
+ | AssistantsUpdate
1053
+ | AssistantsDelete
1054
+ | AssistantsSearch
1055
+ )
1056
+
1057
+ class create:
1058
+ """Type for assistant creation parameters."""
1059
+
1060
+ value = AssistantsCreate
1061
+
1062
+ class read:
1063
+ """Type for assistant read parameters."""
1064
+
1065
+ value = AssistantsRead
1066
+
1067
+ class update:
1068
+ """Type for assistant update parameters."""
1069
+
1070
+ value = AssistantsUpdate
1071
+
1072
+ class delete:
1073
+ """Type for assistant deletion parameters."""
1074
+
1075
+ value = AssistantsDelete
1076
+
1077
+ class search:
1078
+ """Type for assistant search parameters."""
1079
+
1080
+ value = AssistantsSearch
1081
+
1082
+ class crons:
1083
+ """Types for cron-related operations."""
1084
+
1085
+ value = CronsCreate | CronsRead | CronsUpdate | CronsDelete | CronsSearch
1086
+
1087
+ class create:
1088
+ """Type for cron creation parameters."""
1089
+
1090
+ value = CronsCreate
1091
+
1092
+ class read:
1093
+ """Type for cron read parameters."""
1094
+
1095
+ value = CronsRead
1096
+
1097
+ class update:
1098
+ """Type for cron update parameters."""
1099
+
1100
+ value = CronsUpdate
1101
+
1102
+ class delete:
1103
+ """Type for cron deletion parameters."""
1104
+
1105
+ value = CronsDelete
1106
+
1107
+ class search:
1108
+ """Type for cron search parameters."""
1109
+
1110
+ value = CronsSearch
1111
+
1112
+ class store:
1113
+ """Types for store-related operations."""
1114
+
1115
+ value = StoreGet | StoreSearch | StoreListNamespaces | StorePut | StoreDelete
1116
+
1117
+ class put:
1118
+ """Type for store put parameters."""
1119
+
1120
+ value = StorePut
1121
+
1122
+ class get:
1123
+ """Type for store get parameters."""
1124
+
1125
+ value = StoreGet
1126
+
1127
+ class search:
1128
+ """Type for store search parameters."""
1129
+
1130
+ value = StoreSearch
1131
+
1132
+ class delete:
1133
+ """Type for store delete parameters."""
1134
+
1135
+ value = StoreDelete
1136
+
1137
+ class list_namespaces:
1138
+ """Type for store list namespaces parameters."""
1139
+
1140
+ value = StoreListNamespaces
1141
+
1142
+
1143
+ __all__ = [
1144
+ "AssistantsCreate",
1145
+ "AssistantsDelete",
1146
+ "AssistantsRead",
1147
+ "AssistantsSearch",
1148
+ "AssistantsUpdate",
1149
+ "MetadataInput",
1150
+ "RunsCreate",
1151
+ "StoreDelete",
1152
+ "StoreGet",
1153
+ "StoreListNamespaces",
1154
+ "StorePut",
1155
+ "StoreSearch",
1156
+ "ThreadsCreate",
1157
+ "ThreadsDelete",
1158
+ "ThreadsRead",
1159
+ "ThreadsSearch",
1160
+ "ThreadsUpdate",
1161
+ "on",
1162
+ ]
python/user_packages/Python313/site-packages/langgraph_sdk/encryption/__init__.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom encryption support for LangGraph.
2
+
3
+ .. warning::
4
+ This API is in beta and may change in future versions.
5
+
6
+ This module provides a framework for implementing custom at-rest encryption
7
+ in LangGraph applications. Similar to the Auth system, it allows developers
8
+ to define custom encryption and decryption handlers that are executed
9
+ server-side.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import inspect
16
+ import typing
17
+ import warnings
18
+
19
+ from langgraph_sdk.encryption import types
20
+
21
+
22
+ class LangGraphBetaWarning(UserWarning):
23
+ """Warning for beta features in LangGraph SDK."""
24
+
25
+
26
+ @functools.lru_cache(maxsize=1)
27
+ def _warn_encryption_beta() -> None:
28
+ warnings.warn(
29
+ "The Encryption API is in beta and may change in future versions.",
30
+ LangGraphBetaWarning,
31
+ stacklevel=4,
32
+ )
33
+
34
+
35
+ class DuplicateHandlerError(Exception):
36
+ """Raised when attempting to register a duplicate encryption/decryption handler."""
37
+
38
+ pass
39
+
40
+
41
+ def _validate_handler(fn: typing.Callable, handler_type: str) -> None:
42
+ """Validate that a handler function has the correct signature.
43
+
44
+ Args:
45
+ fn: The handler function to validate
46
+ handler_type: Description of the handler for error messages
47
+
48
+ Raises:
49
+ TypeError: If the handler is not an async function or has wrong parameter count
50
+ """
51
+ if not inspect.iscoroutinefunction(fn):
52
+ raise TypeError(f"{handler_type} must be an async function, got {type(fn)}")
53
+
54
+ sig = inspect.signature(fn)
55
+ params = [
56
+ p
57
+ for p in sig.parameters.values()
58
+ if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
59
+ ]
60
+ if len(params) != 2:
61
+ raise TypeError(
62
+ f"{handler_type} must accept exactly 2 parameters "
63
+ f"(ctx, data), got {len(params)}"
64
+ )
65
+
66
+
67
+ class _EncryptDecorators:
68
+ """Decorators for encryption handlers.
69
+
70
+ Provides @encryption.encrypt.blob and @encryption.encrypt.json decorators for
71
+ registering encryption functions.
72
+ """
73
+
74
+ def __init__(self, parent: Encryption):
75
+ self._parent = parent
76
+
77
+ def blob(self, fn: types.BlobEncryptor) -> types.BlobEncryptor:
78
+ """Register a blob encryption handler.
79
+
80
+ The handler will be called to encrypt opaque data like checkpoint blobs.
81
+
82
+ Example:
83
+ ```python
84
+ @encryption.encrypt.blob
85
+ async def encrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
86
+ # Encrypt the blob using your encryption service
87
+ return encrypted_blob
88
+ ```
89
+
90
+ Args:
91
+ fn: The encryption handler function
92
+
93
+ Returns:
94
+ The registered handler function
95
+
96
+ Raises:
97
+ DuplicateHandlerError: If blob encryptor already registered
98
+ TypeError: If handler has invalid signature
99
+ """
100
+ if self._parent._blob_encryptor is not None:
101
+ raise DuplicateHandlerError("Blob encryptor already registered")
102
+ _validate_handler(fn, "Blob encryptor")
103
+ self._parent._blob_encryptor = fn
104
+ return fn
105
+
106
+ def json(self, fn: types.JsonEncryptor) -> types.JsonEncryptor:
107
+ """Register the JSON encryption handler.
108
+
109
+ Example:
110
+ ```python
111
+ @encryption.encrypt.json
112
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
113
+ # Encrypt the data
114
+ return encrypt_data(data)
115
+ ```
116
+
117
+ Args:
118
+ fn: The encryption handler function
119
+
120
+ Returns:
121
+ The registered handler function
122
+
123
+ Raises:
124
+ DuplicateHandlerError: If JSON encryptor already registered
125
+ TypeError: If handler has invalid signature
126
+ """
127
+ if self._parent._json_encryptor is not None:
128
+ raise DuplicateHandlerError("JSON encryptor already registered")
129
+ _validate_handler(fn, "JSON encryptor")
130
+ self._parent._json_encryptor = fn
131
+ return fn
132
+
133
+
134
+ class _DecryptDecorators:
135
+ """Decorators for decryption handlers.
136
+
137
+ Provides @encryption.decrypt.blob and @encryption.decrypt.json decorators for
138
+ registering decryption functions.
139
+ """
140
+
141
+ def __init__(self, parent: Encryption):
142
+ self._parent = parent
143
+
144
+ def blob(self, fn: types.BlobDecryptor) -> types.BlobDecryptor:
145
+ """Register a blob decryption handler.
146
+
147
+ The handler will be called to decrypt opaque data like checkpoint blobs.
148
+
149
+ Example:
150
+ ```python
151
+ @encryption.decrypt.blob
152
+ async def decrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
153
+ # Decrypt the blob using your encryption service
154
+ return decrypted_blob
155
+ ```
156
+
157
+ Args:
158
+ fn: The decryption handler function
159
+
160
+ Returns:
161
+ The registered handler function
162
+
163
+ Raises:
164
+ DuplicateHandlerError: If blob decryptor already registered
165
+ TypeError: If handler has invalid signature
166
+ """
167
+ if self._parent._blob_decryptor is not None:
168
+ raise DuplicateHandlerError("Blob decryptor already registered")
169
+ _validate_handler(fn, "Blob decryptor")
170
+ self._parent._blob_decryptor = fn
171
+ return fn
172
+
173
+ def json(self, fn: types.JsonDecryptor) -> types.JsonDecryptor:
174
+ """Register the JSON decryption handler.
175
+
176
+ Example:
177
+ ```python
178
+ @encryption.decrypt.json
179
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
180
+ # Decrypt the data
181
+ return decrypt_data(data)
182
+ ```
183
+
184
+ Args:
185
+ fn: The decryption handler function
186
+
187
+ Returns:
188
+ The registered handler function
189
+
190
+ Raises:
191
+ DuplicateHandlerError: If JSON decryptor already registered
192
+ TypeError: If handler has invalid signature
193
+ """
194
+ if self._parent._json_decryptor is not None:
195
+ raise DuplicateHandlerError("JSON decryptor already registered")
196
+ _validate_handler(fn, "JSON decryptor")
197
+ self._parent._json_decryptor = fn
198
+ return fn
199
+
200
+
201
+ class Encryption:
202
+ """Add custom at-rest encryption to your LangGraph application.
203
+
204
+ .. warning::
205
+ This API is in beta and may change in future versions.
206
+
207
+ The Encryption class provides a system for implementing custom encryption
208
+ of data at rest in LangGraph applications. It supports encryption of
209
+ both opaque blobs (like checkpoints) and structured JSON data (like
210
+ metadata, context, kwargs, values, etc.).
211
+
212
+ To use, create a separate Python file and add the path to the file to your
213
+ LangGraph API configuration file (`langgraph.json`). Within that file, create
214
+ an instance of the Encryption class and register encryption and decryption
215
+ handlers as needed.
216
+
217
+ Example `langgraph.json` file:
218
+
219
+ ```json
220
+ {
221
+ "dependencies": ["."],
222
+ "graphs": {
223
+ "agent": "./my_agent/agent.py:graph"
224
+ },
225
+ "env": ".env",
226
+ "encryption": {
227
+ "path": "./encryption.py:my_encryption"
228
+ }
229
+ }
230
+ ```
231
+
232
+ Then the LangGraph server will load your encryption file and use it to
233
+ encrypt/decrypt data at rest.
234
+
235
+ !!! warning "JSON Encryptors Must Preserve Keys"
236
+
237
+ JSON encryptors **must not add or remove keys** from the input dict.
238
+ Only values may be transformed. This constraint is **enforced at runtime
239
+ by the server** and exists because SQL JSONB merge operations (used for
240
+ partial updates) work at the key level.
241
+
242
+ **Correct (per-key encryption):**
243
+ ```python
244
+ # Input: {"secret": "value", "plain": "x"}
245
+ # Output: {"secret": "<encrypted>", "plain": "x"} ✓ Keys preserved
246
+ ```
247
+
248
+ **Incorrect (key consolidation):**
249
+ ```python
250
+ # Input: {"secret": "value", "plain": "x"}
251
+ # Output: {"__encrypted__": "<blob>", "plain": "x"} ✗ Key changed
252
+ ```
253
+
254
+ If your encryptor needs to store auxiliary data (DEK, IV, etc.), embed it
255
+ within the encrypted value itself, not as separate keys.
256
+
257
+ ???+ example "Basic Usage"
258
+
259
+ ```python
260
+ from langgraph_sdk import Encryption, EncryptionContext
261
+
262
+ my_encryption = Encryption()
263
+
264
+ SKIP_FIELDS = {"tenant_id", "owner", "thread_id", "assistant_id"}
265
+ ENCRYPTED_PREFIX = "encrypted:"
266
+
267
+ @my_encryption.encrypt.blob
268
+ async def encrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
269
+ return your_encrypt_bytes(blob)
270
+
271
+ @my_encryption.decrypt.blob
272
+ async def decrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
273
+ return your_decrypt_bytes(blob)
274
+
275
+ @my_encryption.encrypt.json
276
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
277
+ result = {}
278
+ for k, v in data.items():
279
+ if k in SKIP_FIELDS or v is None:
280
+ result[k] = v
281
+ else:
282
+ result[k] = ENCRYPTED_PREFIX + your_encrypt_string(v)
283
+ return result
284
+
285
+ @my_encryption.decrypt.json
286
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
287
+ result = {}
288
+ for k, v in data.items():
289
+ if isinstance(v, str) and v.startswith(ENCRYPTED_PREFIX):
290
+ result[k] = your_decrypt_string(v[len(ENCRYPTED_PREFIX):])
291
+ else:
292
+ result[k] = v
293
+ return result
294
+ ```
295
+
296
+ ???+ example "Field-Specific Logic"
297
+
298
+ The `ctx.model` and `ctx.field` attributes tell you which model type and
299
+ specific field is being encrypted, allowing different logic:
300
+
301
+ ```python
302
+ @my_encryption.encrypt.json
303
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
304
+ if ctx.field == "metadata":
305
+ # Metadata - standard encryption
306
+ return encrypt_standard(data)
307
+ elif ctx.field == "values":
308
+ # Thread values - more sensitive, use stronger encryption
309
+ return encrypt_sensitive(data)
310
+ else:
311
+ return encrypt_standard(data)
312
+ ```
313
+
314
+ !!! warning "Model/Field May Differ Between Encrypt and Decrypt"
315
+
316
+ Data encrypted with one `(model, field)` pair is **not guaranteed**
317
+ to be decrypted with the same pair. The server performs SQL JSONB
318
+ merges that can move encrypted values between models (e.g., cron
319
+ metadata → run metadata). Your decryption logic must handle data
320
+ regardless of the `ctx.model` or `ctx.field` values at decrypt time.
321
+
322
+ **Safe:** Use `ctx.model`/`ctx.field` for logging or metrics only.
323
+
324
+ **Safe:** Encrypt different keys based on `ctx.field`, but use a
325
+ single decrypt handler that decrypts any value with the encrypted
326
+ prefix (and passes through plaintext unchanged):
327
+
328
+ ```python
329
+ ENCRYPTED_PREFIX = "enc:"
330
+
331
+ @my_encryption.encrypt.json
332
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
333
+ # Encrypt different keys depending on the field
334
+ if ctx.field == "context":
335
+ keys_to_encrypt = {"api_key", "secret_token"}
336
+ else:
337
+ keys_to_encrypt = {"email", "ssn"}
338
+ return {
339
+ k: ENCRYPTED_PREFIX + encrypt(v) if k in keys_to_encrypt else v
340
+ for k, v in data.items()
341
+ }
342
+
343
+ @my_encryption.decrypt.json
344
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
345
+ # Decrypt ANY value with the prefix, regardless of model/field
346
+ return {
347
+ k: decrypt(v[len(ENCRYPTED_PREFIX):])
348
+ if isinstance(v, str) and v.startswith(ENCRYPTED_PREFIX)
349
+ else v
350
+ for k, v in data.items()
351
+ }
352
+ ```
353
+
354
+ **Unsafe:** Using different encryption keys or algorithms based on
355
+ `ctx.model`/`ctx.field` will cause decryption failures.
356
+ """
357
+
358
+ __slots__ = (
359
+ "_blob_decryptor",
360
+ "_blob_encryptor",
361
+ "_context_handler",
362
+ "_json_decryptor",
363
+ "_json_encryptor",
364
+ "decrypt",
365
+ "encrypt",
366
+ )
367
+
368
+ types = types
369
+ """Reference to encryption type definitions.
370
+
371
+ Provides access to all type definitions used in the encryption system,
372
+ including EncryptionContext, BlobEncryptor, BlobDecryptor,
373
+ JsonEncryptor, and JsonDecryptor.
374
+ """
375
+
376
+ def __init__(self) -> None:
377
+ """Initialize the Encryption instance."""
378
+ _warn_encryption_beta()
379
+ self.encrypt = _EncryptDecorators(self)
380
+ self.decrypt = _DecryptDecorators(self)
381
+ self._blob_encryptor: types.BlobEncryptor | None = None
382
+ self._blob_decryptor: types.BlobDecryptor | None = None
383
+ self._json_encryptor: types.JsonEncryptor | None = None
384
+ self._json_decryptor: types.JsonDecryptor | None = None
385
+ self._context_handler: types.ContextHandler | None = None
386
+
387
+ def context(self, fn: types.ContextHandler) -> types.ContextHandler:
388
+ """Register a context handler to derive encryption context from auth.
389
+
390
+ The handler receives the authenticated user and current EncryptionContext,
391
+ and returns a dict that becomes ctx.metadata for encrypt/decrypt handlers.
392
+
393
+ This allows encryption context to be derived from JWT claims or other
394
+ auth-derived data instead of requiring a separate X-Encryption-Context header.
395
+
396
+ Note: The context handler is called once per request in middleware,
397
+ so ctx.model and ctx.field will be None in the handler.
398
+
399
+ Example:
400
+ ```python
401
+ from langgraph_sdk import Encryption, EncryptionContext
402
+ from starlette.authentication import BaseUser
403
+
404
+ encryption = Encryption()
405
+
406
+ @encryption.context
407
+ async def get_context(user: BaseUser, ctx: EncryptionContext) -> dict:
408
+ # Derive encryption context from authenticated user
409
+ return {
410
+ **ctx.metadata, # preserve X-Encryption-Context header if present
411
+ "tenant_id": user.tenant_id,
412
+ }
413
+ ```
414
+
415
+ Args:
416
+ fn: The context handler function
417
+
418
+ Returns:
419
+ The registered handler function
420
+ """
421
+ self._context_handler = fn
422
+ return fn
423
+
424
+ def get_json_encryptor(
425
+ self,
426
+ _model: str | None = None, # kept for langgraph-api compat
427
+ ) -> types.JsonEncryptor | None:
428
+ """Get the JSON encryptor.
429
+
430
+ Args:
431
+ _model: Ignored. Kept for backwards compatibility with langgraph-api
432
+ which passes model_type to this method.
433
+
434
+ Returns:
435
+ The JSON encryptor, or None if not registered.
436
+ """
437
+ return self._json_encryptor
438
+
439
+ def get_json_decryptor(
440
+ self,
441
+ _model: str | None = None, # kept for langgraph-api compat
442
+ ) -> types.JsonDecryptor | None:
443
+ """Get the JSON decryptor.
444
+
445
+ Args:
446
+ _model: Ignored. Kept for backwards compatibility with langgraph-api
447
+ which passes model_type to this method.
448
+
449
+ Returns:
450
+ The JSON decryptor, or None if not registered.
451
+ """
452
+ return self._json_decryptor
453
+
454
+ def __repr__(self) -> str:
455
+ handlers = []
456
+ if self._blob_encryptor:
457
+ handlers.append("blob_encryptor")
458
+ if self._blob_decryptor:
459
+ handlers.append("blob_decryptor")
460
+ if self._json_encryptor:
461
+ handlers.append("json_encryptor")
462
+ if self._json_decryptor:
463
+ handlers.append("json_decryptor")
464
+ if self._context_handler:
465
+ handlers.append("context_handler")
466
+ return f"Encryption(handlers=[{', '.join(handlers)}])"
python/user_packages/Python313/site-packages/langgraph_sdk/encryption/types.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Encryption and decryption types for LangGraph.
2
+
3
+ This module defines the core types used for custom at-rest encryption
4
+ in LangGraph. It includes context types and typed dictionaries for
5
+ encryption operations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import typing
11
+ from collections.abc import Awaitable, Callable
12
+
13
+ Json = dict[str, typing.Any]
14
+ """JSON-serializable dictionary type for structured data encryption."""
15
+
16
+
17
+ class EncryptionContext:
18
+ """Context passed to encryption/decryption handlers.
19
+
20
+ Contains arbitrary non-secret key-values that will be stored on encrypt.
21
+ These key-values are intended to be sent to an external service that
22
+ manages keys and handles the actual encryption and decryption of data.
23
+
24
+ Attributes:
25
+ model: The model type being encrypted (e.g., "assistant", "thread", "run", "checkpoint")
26
+ field: The specific field being encrypted (e.g., "metadata", "context", "kwargs", "values")
27
+ metadata: Additional context metadata that can be used for encryption decisions
28
+ """
29
+
30
+ __slots__ = ("field", "metadata", "model")
31
+
32
+ def __init__(
33
+ self,
34
+ model: str | None = None,
35
+ metadata: dict[str, typing.Any] | None = None,
36
+ field: str | None = None,
37
+ ):
38
+ self.model = model
39
+ self.field = field
40
+ self.metadata = metadata or {}
41
+
42
+ def __repr__(self) -> str:
43
+ return f"EncryptionContext(model={self.model!r}, field={self.field!r}, metadata={self.metadata!r})"
44
+
45
+
46
+ BlobEncryptor = Callable[[EncryptionContext, bytes], Awaitable[bytes]]
47
+ """Handler for encrypting opaque blob data like checkpoints.
48
+
49
+ Note: Must be an async function. Encryption typically involves I/O operations
50
+ (calling external KMS services), which should be async.
51
+
52
+ Args:
53
+ ctx: Encryption context with model type and metadata
54
+ blob: The raw bytes to encrypt
55
+
56
+ Returns:
57
+ Awaitable that resolves to encrypted bytes
58
+ """
59
+
60
+ BlobDecryptor = Callable[[EncryptionContext, bytes], Awaitable[bytes]]
61
+ """Handler for decrypting opaque blob data like checkpoints.
62
+
63
+ Note: Must be an async function. Decryption typically involves I/O operations
64
+ (calling external KMS services), which should be async.
65
+
66
+ Args:
67
+ ctx: Encryption context with model type and metadata
68
+ blob: The encrypted bytes to decrypt
69
+
70
+ Returns:
71
+ Awaitable that resolves to decrypted bytes
72
+ """
73
+
74
+ JsonEncryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
75
+ """Handler for encrypting structured JSON data.
76
+
77
+ Note: Must be an async function. Encryption typically involves I/O operations
78
+ (calling external KMS services), which should be async.
79
+
80
+ Used for encrypting structured data like metadata, context, kwargs, values,
81
+ and other JSON-serializable fields across different model types.
82
+
83
+ Maps plaintext fields to encrypted fields. A practical approach:
84
+ - Keep "owner" field unencrypted for search/filtering
85
+ - Encrypt VALUES (not keys) for fields with specific prefix (e.g., "my.customer.org/")
86
+ - Pass through all other fields unencrypted
87
+
88
+ Example:
89
+ Input: {"owner": "user123", "my.customer.org/email": "john@example.com", "tenant_id": "t-456"}
90
+ Output: {"owner": "user123", "my.customer.org/email": "ENCRYPTED", "tenant_id": "t-456"}
91
+
92
+ Note: Encrypted field VALUES cannot be reliably searched, as most real-world
93
+ encryption implementations use nonces (non-deterministic encryption).
94
+ Only unencrypted fields can be used in search queries.
95
+
96
+ Args:
97
+ ctx: Encryption context with model type, field name, and metadata
98
+ data: The plaintext JSON dictionary
99
+
100
+ Returns:
101
+ Awaitable that resolves to encrypted JSON dictionary
102
+ """
103
+
104
+ JsonDecryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
105
+ """Handler for decrypting structured JSON data.
106
+
107
+ Note: Must be an async function. Decryption typically involves I/O operations
108
+ (calling external KMS services), which should be async.
109
+
110
+ Inverse of JsonEncryptor. Must be able to decrypt data that
111
+ was encrypted by the corresponding encryptor.
112
+
113
+ Args:
114
+ ctx: Encryption context with model type, field name, and metadata
115
+ data: The encrypted JSON dictionary
116
+
117
+ Returns:
118
+ Awaitable that resolves to decrypted JSON dictionary
119
+ """
120
+
121
+ if typing.TYPE_CHECKING:
122
+ from starlette.authentication import BaseUser
123
+
124
+ ContextHandler = Callable[
125
+ ["BaseUser", EncryptionContext], Awaitable[dict[str, typing.Any]]
126
+ ]
127
+ """Handler for deriving encryption context from authenticated user info.
128
+
129
+ Note: Must be an async function as it may involve I/O operations.
130
+
131
+ The context handler is called once per request in middleware (after auth),
132
+ allowing encryption context to be derived from JWT claims, user properties,
133
+ or other auth-derived data instead of requiring a separate X-Encryption-Context header.
134
+
135
+ The return value becomes ctx.metadata for subsequent encrypt/decrypt operations
136
+ and is persisted with encrypted data for later decryption.
137
+
138
+ Note: ctx.model and ctx.field will be None in context handlers since
139
+ the handler runs once per request before any specific model/field is known.
140
+
141
+ Args:
142
+ user: The authenticated user (from Starlette's AuthenticationMiddleware)
143
+ ctx: Current encryption context with metadata from X-Encryption-Context header
144
+
145
+ Returns:
146
+ Awaitable that resolves to dict that becomes the new ctx.metadata
147
+ """
python/user_packages/Python313/site-packages/langsmith/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (4.05 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/_expect.cpython-313.pyc ADDED
Binary file (18.1 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/_runtime_overrides.cpython-313.pyc ADDED
Binary file (4.98 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/anonymizer.cpython-313.pyc ADDED
Binary file (8.27 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/middleware.cpython-313.pyc ADDED
Binary file (2.33 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/prompt_cache.cpython-313.pyc ADDED
Binary file (28.9 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/pytest_plugin.cpython-313.pyc ADDED
Binary file (18.2 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/run_helpers.cpython-313.pyc ADDED
Binary file (88.9 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/run_trees.cpython-313.pyc ADDED
Binary file (53.7 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/schemas.cpython-313.pyc ADDED
Binary file (60.1 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/utils.cpython-313.pyc ADDED
Binary file (40.6 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/__pycache__/uuid.cpython-313.pyc ADDED
Binary file (1.42 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__init__.py ADDED
File without changes
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (195 Bytes). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_aiter.cpython-313.pyc ADDED
Binary file (18 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_background_thread.cpython-313.pyc ADDED
Binary file (34.9 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_beta_decorator.cpython-313.pyc ADDED
Binary file (1.53 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_compressed_traces.cpython-313.pyc ADDED
Binary file (2.78 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_constants.cpython-313.pyc ADDED
Binary file (556 Bytes). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_context.cpython-313.pyc ADDED
Binary file (2.04 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_edit_distance.cpython-313.pyc ADDED
Binary file (2.82 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_embedding_distance.cpython-313.pyc ADDED
Binary file (9.05 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_hub.cpython-313.pyc ADDED
Binary file (1.67 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_multipart.cpython-313.pyc ADDED
Binary file (1.69 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_operations.cpython-313.pyc ADDED
Binary file (17.6 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_orjson.cpython-313.pyc ADDED
Binary file (3.82 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_otel_utils.cpython-313.pyc ADDED
Binary file (1.15 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_patch.cpython-313.pyc ADDED
Binary file (3.96 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_profiles.cpython-313.pyc ADDED
Binary file (18.5 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_serde.cpython-313.pyc ADDED
Binary file (7.3 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/__pycache__/_uuid.cpython-313.pyc ADDED
Binary file (4.55 kB). View file
 
python/user_packages/Python313/site-packages/langsmith/_internal/_aiter.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapted.
2
+
3
+ Original source:
4
+ https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
5
+ MIT License
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextvars
12
+ import functools
13
+ import inspect
14
+ from collections import deque
15
+ from collections.abc import (
16
+ AsyncGenerator,
17
+ AsyncIterable,
18
+ AsyncIterator,
19
+ Awaitable,
20
+ Coroutine,
21
+ Iterable,
22
+ Iterator,
23
+ )
24
+ from contextlib import AbstractAsyncContextManager
25
+ from typing import (
26
+ Any,
27
+ Callable,
28
+ Generic,
29
+ Optional,
30
+ TypeVar,
31
+ Union,
32
+ cast,
33
+ overload,
34
+ )
35
+
36
+ from langsmith._runtime_overrides import get_runtime_overrides
37
+
38
+ T = TypeVar("T")
39
+
40
+ _no_default = object()
41
+
42
+
43
+ # https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
44
+ # before 3.10, the builtin anext() was not available
45
+ def py_anext(
46
+ iterator: AsyncIterator[T], default: Union[T, Any] = _no_default
47
+ ) -> Awaitable[Union[T, None, Any]]:
48
+ """Pure-Python implementation of anext() for testing purposes.
49
+
50
+ Closely matches the builtin anext() C implementation.
51
+ Can be used to compare the built-in implementation of the inner
52
+ coroutines machinery to C-implementation of __anext__() and send()
53
+ or throw() on the returned generator.
54
+ """
55
+ try:
56
+ __anext__ = cast(
57
+ Callable[[AsyncIterator[T]], Awaitable[T]], type(iterator).__anext__
58
+ )
59
+ except AttributeError:
60
+ raise TypeError(f"{iterator!r} is not an async iterator")
61
+
62
+ if default is _no_default:
63
+ return __anext__(iterator)
64
+
65
+ async def anext_impl() -> Union[T, Any]:
66
+ try:
67
+ # The C code is way more low-level than this, as it implements
68
+ # all methods of the iterator protocol. In this implementation
69
+ # we're relying on higher-level coroutine concepts, but that's
70
+ # exactly what we want -- crosstest pure-Python high-level
71
+ # implementation and low-level C anext() iterators.
72
+ return await __anext__(iterator)
73
+ except StopAsyncIteration:
74
+ return default
75
+
76
+ return anext_impl()
77
+
78
+
79
+ class NoLock:
80
+ """Dummy lock that provides the proper interface but no protection."""
81
+
82
+ async def __aenter__(self) -> None:
83
+ pass
84
+
85
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
86
+ return False
87
+
88
+
89
+ async def tee_peer(
90
+ iterator: AsyncIterator[T],
91
+ # the buffer specific to this peer
92
+ buffer: deque[T],
93
+ # the buffers of all peers, including our own
94
+ peers: list[deque[T]],
95
+ lock: AbstractAsyncContextManager[Any],
96
+ ) -> AsyncGenerator[T, None]:
97
+ """Iterate over :py:func:`~.tee`."""
98
+ try:
99
+ while True:
100
+ if not buffer:
101
+ async with lock:
102
+ # Another peer produced an item while we were waiting for the lock.
103
+ # Proceed with the next loop iteration to yield the item.
104
+ if buffer:
105
+ continue
106
+ try:
107
+ item = await iterator.__anext__()
108
+ except StopAsyncIteration:
109
+ break
110
+ else:
111
+ # Append to all buffers, including our own. We'll fetch our
112
+ # item from the buffer again, instead of yielding it directly.
113
+ # This ensures the proper item ordering if any of our peers
114
+ # are fetching items concurrently. They may have buffered their
115
+ # item already.
116
+ for peer_buffer in peers:
117
+ peer_buffer.append(item)
118
+ yield buffer.popleft()
119
+ finally:
120
+ async with lock:
121
+ # this peer is done – remove its buffer
122
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
123
+ if peer_buffer is buffer:
124
+ peers.pop(idx)
125
+ break
126
+ # if we are the last peer, try and close the iterator
127
+ if not peers and hasattr(iterator, "aclose"):
128
+ await iterator.aclose()
129
+
130
+
131
+ class Tee(Generic[T]):
132
+ """Create ``n`` separate asynchronous iterators over ``iterable``.
133
+
134
+ This splits a single ``iterable`` into multiple iterators, each providing
135
+ the same items in the same order.
136
+ All child iterators may advance separately but pare the same items
137
+ from ``iterable`` -- when the most advanced iterator retrieves an item,
138
+ it is buffered until the least advanced iterator has yielded it as well.
139
+ A ``tee`` works lazily and can handle an infinite ``iterable``, provided
140
+ that all iterators advance.
141
+
142
+ ```python
143
+ async def derivative(sensor_data):
144
+ previous, current = a.tee(sensor_data, n=2)
145
+ await a.anext(previous) # advance one iterator
146
+ return a.map(operator.sub, previous, current)
147
+ ```
148
+
149
+ Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead
150
+ of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked
151
+ to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
152
+ immediately closes all children, and it can be used in an ``async with`` context
153
+ for the same effect.
154
+
155
+ If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
156
+ provide these items. Also, ``tee`` must internally buffer each item until the
157
+ last iterator has yielded it; if the most and least advanced iterator differ
158
+ by most data, using a :py:class:`list` is more efficient (but not lazy).
159
+
160
+ If the underlying iterable is concurrency safe (``anext`` may be awaited
161
+ concurrently) the resulting iterators are concurrency safe as well. Otherwise,
162
+ the iterators are safe if there is only ever one single "most advanced" iterator.
163
+ To enforce sequential use of ``anext``, provide a ``lock``
164
+ - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
165
+ and access is automatically synchronised.
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ iterable: AsyncIterator[T],
171
+ n: int = 2,
172
+ *,
173
+ lock: Optional[AbstractAsyncContextManager[Any]] = None,
174
+ ):
175
+ self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist
176
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
177
+ self._children = tuple(
178
+ tee_peer(
179
+ iterator=self._iterator,
180
+ buffer=buffer,
181
+ peers=self._buffers,
182
+ lock=lock if lock is not None else NoLock(),
183
+ )
184
+ for buffer in self._buffers
185
+ )
186
+
187
+ def __len__(self) -> int:
188
+ return len(self._children)
189
+
190
+ @overload
191
+ def __getitem__(self, item: int) -> AsyncIterator[T]: ...
192
+
193
+ @overload
194
+ def __getitem__(self, item: slice) -> tuple[AsyncIterator[T], ...]: ...
195
+
196
+ def __getitem__(
197
+ self, item: Union[int, slice]
198
+ ) -> Union[AsyncIterator[T], tuple[AsyncIterator[T], ...]]:
199
+ return self._children[item]
200
+
201
+ def __iter__(self) -> Iterator[AsyncIterator[T]]:
202
+ yield from self._children
203
+
204
+ async def __aenter__(self) -> Tee[T]:
205
+ return self
206
+
207
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
208
+ await self.aclose()
209
+ return False
210
+
211
+ async def aclose(self) -> None:
212
+ for child in self._children:
213
+ await child.aclose()
214
+
215
+
216
+ atee = Tee
217
+
218
+
219
+ async def async_zip(*async_iterables):
220
+ """Async version of zip."""
221
+ # Before Python 3.10, aiter() was not available
222
+ iterators = [iterable.__aiter__() for iterable in async_iterables]
223
+ while True:
224
+ try:
225
+ items = await asyncio.gather(
226
+ *(py_anext(iterator) for iterator in iterators)
227
+ )
228
+ yield tuple(items)
229
+ except StopAsyncIteration:
230
+ break
231
+
232
+
233
+ def ensure_async_iterator(
234
+ iterable: Union[Iterable, AsyncIterable],
235
+ ) -> AsyncIterator:
236
+ if hasattr(iterable, "__anext__"):
237
+ return cast(AsyncIterator, iterable)
238
+ elif hasattr(iterable, "__aiter__"):
239
+ return cast(AsyncIterator, iterable.__aiter__())
240
+ else:
241
+
242
+ class AsyncIteratorWrapper:
243
+ def __init__(self, iterable: Iterable):
244
+ self._iterator = iter(iterable)
245
+
246
+ async def __anext__(self):
247
+ try:
248
+ return next(self._iterator)
249
+ except StopIteration:
250
+ raise StopAsyncIteration
251
+
252
+ def __aiter__(self):
253
+ return self
254
+
255
+ return AsyncIteratorWrapper(iterable)
256
+
257
+
258
+ def aiter_with_concurrency(
259
+ n: Optional[int],
260
+ generator: AsyncIterator[Coroutine[None, None, T]],
261
+ *,
262
+ _eager_consumption_timeout: float = 0,
263
+ ) -> AsyncGenerator[T, None]:
264
+ """Process async generator with max parallelism.
265
+
266
+ Args:
267
+ n: The number of tasks to run concurrently.
268
+ generator: The async generator to process.
269
+ _eager_consumption_timeout: If set, check for completed tasks after
270
+ each iteration and yield their results. This can be used to
271
+ consume the generator eagerly while still respecting the concurrency
272
+ limit.
273
+
274
+ Yields:
275
+ The processed items yielded by the async generator.
276
+ """
277
+ if n == 0:
278
+
279
+ async def consume():
280
+ async for item in generator:
281
+ yield await item
282
+
283
+ return consume()
284
+ semaphore = cast(
285
+ asyncio.Semaphore, asyncio.Semaphore(n) if n is not None else NoLock()
286
+ )
287
+
288
+ async def process_item(ix: int, item):
289
+ async with semaphore:
290
+ res = await item
291
+ return (ix, res)
292
+
293
+ async def process_generator():
294
+ tasks = {}
295
+ accepts_context = asyncio_accepts_context()
296
+ ix = 0
297
+ async for item in generator:
298
+ if accepts_context:
299
+ context = contextvars.copy_context()
300
+ task = asyncio.create_task(process_item(ix, item), context=context)
301
+ else:
302
+ task = asyncio.create_task(process_item(ix, item))
303
+ tasks[ix] = task
304
+ ix += 1
305
+ if _eager_consumption_timeout > 0:
306
+ try:
307
+ for _fut in asyncio.as_completed(
308
+ tasks.values(),
309
+ timeout=_eager_consumption_timeout,
310
+ ):
311
+ task_idx, res = await _fut
312
+ yield res
313
+ del tasks[task_idx]
314
+ except asyncio.TimeoutError:
315
+ pass
316
+ if n is not None and len(tasks) >= n:
317
+ done, _ = await asyncio.wait(
318
+ tasks.values(), return_when=asyncio.FIRST_COMPLETED
319
+ )
320
+ for task in done:
321
+ task_idx, res = task.result()
322
+ yield res
323
+ del tasks[task_idx]
324
+
325
+ for task in asyncio.as_completed(tasks.values()):
326
+ _, res = await task
327
+ yield res
328
+
329
+ return process_generator()
330
+
331
+
332
+ def accepts_context(callable: Callable[..., Any]) -> bool:
333
+ """Check if a callable accepts a context argument."""
334
+ try:
335
+ return inspect.signature(callable).parameters.get("context") is not None
336
+ except ValueError:
337
+ return False
338
+
339
+
340
+ # Ported from Python 3.9+ to support Python 3.8
341
+ async def aio_to_thread(
342
+ ctx: contextvars.Context,
343
+ func,
344
+ /,
345
+ *args,
346
+ **kwargs,
347
+ ):
348
+ """Run ``func`` in a separate thread, inside ``ctx``.
349
+
350
+ ``ctx`` is the :class:`~contextvars.Context` in which ``func`` is invoked.
351
+ Callers that want default isolation should pass
352
+ ``contextvars.copy_context()``; callers with a specific Context
353
+ (e.g. :func:`trace`) pass it directly so subsequent reads from that
354
+ Context see the mutations.
355
+
356
+ Return a coroutine that can be awaited to get the eventual result of ``func``.
357
+ """
358
+ overrides = get_runtime_overrides()
359
+ if overrides.aio_to_thread is not None:
360
+ return await overrides.aio_to_thread(
361
+ _default_aio_to_thread, ctx, func, *args, **kwargs
362
+ )
363
+ return await _default_aio_to_thread(ctx, func, *args, **kwargs)
364
+
365
+
366
+ async def _default_aio_to_thread(
367
+ ctx: contextvars.Context,
368
+ func,
369
+ /,
370
+ *args,
371
+ **kwargs,
372
+ ):
373
+ """Default implementation of aio_to_thread using run_in_executor."""
374
+ loop = asyncio.get_running_loop()
375
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
376
+ return await loop.run_in_executor(None, func_call)
377
+
378
+
379
+ @functools.lru_cache(maxsize=1)
380
+ def asyncio_accepts_context():
381
+ """Check if the current asyncio event loop accepts a context argument."""
382
+ return accepts_context(asyncio.create_task)