Skip to content

Python SDK Reference

The LangGraph client implementations connect to the LangGraph API.

This module provides both asynchronous (LangGraphClient) and synchronous (SyncLanggraphClient) clients to interacting with the LangGraph API's core resources such as Assistants, Threads, Runs, and Cron jobs, as well as its persistent document Store.

LangGraphClient

Top-level client for LangGraph API.

Attributes:

  • assistants

    Manages versioned configuration for your graphs.

  • threads

    Handles (potentially) multi-turn interactions, such as conversational threads.

  • runs

    Controls individual invocations of the graph.

  • crons

    Manages scheduled operations.

  • store

    Interfaces with persistent, shared data storage.

Source code in libs/sdk-py/langgraph_sdk/client.py
class LangGraphClient:
    """Top-level client for LangGraph API.

    Attributes:
        assistants: Manages versioned configuration for your graphs.
        threads: Handles (potentially) multi-turn interactions, such as conversational threads.
        runs: Controls individual invocations of the graph.
        crons: Manages scheduled operations.
        store: Interfaces with persistent, shared data storage.
    """

    def __init__(self, client: httpx.AsyncClient) -> None:
        self.http = HttpClient(client)
        self.assistants = AssistantsClient(self.http)
        self.threads = ThreadsClient(self.http)
        self.runs = RunsClient(self.http)
        self.crons = CronClient(self.http)
        self.store = StoreClient(self.http)

HttpClient

Hancle async requests to the LangGraph API.

Adds additional error messaging & content handling above the provided httpx client.

Attributes:

  • client (AsyncClient) –

    Underlying HTTPX async client.

Source code in libs/sdk-py/langgraph_sdk/client.py
class HttpClient:
    """Hancle async requests to the LangGraph API.

    Adds additional error messaging & content handling above the
    provided httpx client.

    Attributes:
        client (httpx.AsyncClient): Underlying HTTPX async client.
    """

    def __init__(self, client: httpx.AsyncClient) -> None:
        self.client = client

    async def get(self, path: str, *, params: Optional[QueryParamTypes] = None) -> Any:
        """Send a GET request."""
        r = await self.client.get(path, params=params)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await r.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return await adecode_json(r)

    async def post(self, path: str, *, json: Optional[dict]) -> Any:
        """Send a POST request."""
        if json is not None:
            headers, content = await aencode_json(json)
        else:
            headers, content = {}, b""
        r = await self.client.post(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await r.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return await adecode_json(r)

    async def put(self, path: str, *, json: dict) -> Any:
        """Send a PUT request."""
        headers, content = await aencode_json(json)
        r = await self.client.put(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await r.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return await adecode_json(r)

    async def patch(self, path: str, *, json: dict) -> Any:
        """Send a PATCH request."""
        headers, content = await aencode_json(json)
        r = await self.client.patch(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await r.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return await adecode_json(r)

    async def delete(self, path: str, *, json: Optional[Any] = None) -> None:
        """Send a DELETE request."""
        r = await self.client.request("DELETE", path, json=json)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await r.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e

    async def stream(
        self, path: str, method: str, *, json: Optional[dict] = None
    ) -> AsyncIterator[StreamPart]:
        """Stream results using SSE."""
        headers, content = await aencode_json(json)
        async with httpx_sse.aconnect_sse(
            self.client, method, path, headers=headers, content=content
        ) as sse:
            try:
                sse.response.raise_for_status()
            except httpx.HTTPStatusError as e:
                body = (await sse.response.aread()).decode()
                if sys.version_info >= (3, 11):
                    e.add_note(body)
                else:
                    logger.error(f"Error from langgraph-api: {body}", exc_info=e)
                raise e
            async for event in sse.aiter_sse():
                yield StreamPart(
                    event.event, orjson.loads(event.data) if event.data else None
                )

get(path: str, *, params: Optional[QueryParamTypes] = None) -> Any async

Send a GET request.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def get(self, path: str, *, params: Optional[QueryParamTypes] = None) -> Any:
    """Send a GET request."""
    r = await self.client.get(path, params=params)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = (await r.aread()).decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return await adecode_json(r)

post(path: str, *, json: Optional[dict]) -> Any async

Send a POST request.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def post(self, path: str, *, json: Optional[dict]) -> Any:
    """Send a POST request."""
    if json is not None:
        headers, content = await aencode_json(json)
    else:
        headers, content = {}, b""
    r = await self.client.post(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = (await r.aread()).decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return await adecode_json(r)

put(path: str, *, json: dict) -> Any async

Send a PUT request.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def put(self, path: str, *, json: dict) -> Any:
    """Send a PUT request."""
    headers, content = await aencode_json(json)
    r = await self.client.put(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = (await r.aread()).decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return await adecode_json(r)

patch(path: str, *, json: dict) -> Any async

Send a PATCH request.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def patch(self, path: str, *, json: dict) -> Any:
    """Send a PATCH request."""
    headers, content = await aencode_json(json)
    r = await self.client.patch(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = (await r.aread()).decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return await adecode_json(r)

delete(path: str, *, json: Optional[Any] = None) -> None async

Send a DELETE request.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete(self, path: str, *, json: Optional[Any] = None) -> None:
    """Send a DELETE request."""
    r = await self.client.request("DELETE", path, json=json)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = (await r.aread()).decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e

stream(path: str, method: str, *, json: Optional[dict] = None) -> AsyncIterator[StreamPart] async

Stream results using SSE.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def stream(
    self, path: str, method: str, *, json: Optional[dict] = None
) -> AsyncIterator[StreamPart]:
    """Stream results using SSE."""
    headers, content = await aencode_json(json)
    async with httpx_sse.aconnect_sse(
        self.client, method, path, headers=headers, content=content
    ) as sse:
        try:
            sse.response.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = (await sse.response.aread()).decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        async for event in sse.aiter_sse():
            yield StreamPart(
                event.event, orjson.loads(event.data) if event.data else None
            )

AssistantsClient

Client for managing assistants in LangGraph.

This class provides methods to interact with assistants, which are versioned configurations of your graph.

Example:

client = get_client()
assistant = await client.assistants.get("assistant_id_123")
Source code in libs/sdk-py/langgraph_sdk/client.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
class AssistantsClient:
    """Client for managing assistants in LangGraph.

    This class provides methods to interact with assistants,
    which are versioned configurations of your graph.

    Example:

        client = get_client()
        assistant = await client.assistants.get("assistant_id_123")
    """

    def __init__(self, http: HttpClient) -> None:
        self.http = http

    async def get(self, assistant_id: str) -> Assistant:
        """Get an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get.

        Returns:
            Assistant: Assistant Object.

        Example Usage:

            assistant = await client.assistants.get(
                assistant_id="my_assistant_id"
            )
            print(assistant)

            ----------------------------------------------------

            {
                'assistant_id': 'my_assistant_id',
                'graph_id': 'agent',
                'created_at': '2024-06-25T17:10:33.109781+00:00',
                'updated_at': '2024-06-25T17:10:33.109781+00:00',
                'config': {},
                'metadata': {'created_by': 'system'}
            }

        """  # noqa: E501
        return await self.http.get(f"/assistants/{assistant_id}")

    async def get_graph(
        self, assistant_id: str, *, xray: Union[int, bool] = False
    ) -> dict[str, list[dict[str, Any]]]:
        """Get the graph of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the graph of.
            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.

        Returns:
            Graph: The graph information for the assistant in JSON format.

        Example Usage:

            graph_info = await client.assistants.get_graph(
                assistant_id="my_assistant_id"
            )
            print(graph_info)

            --------------------------------------------------------------------------------------------------------------------------

            {
                'nodes':
                    [
                        {'id': '__start__', 'type': 'schema', 'data': '__start__'},
                        {'id': '__end__', 'type': 'schema', 'data': '__end__'},
                        {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
                    ],
                'edges':
                    [
                        {'source': '__start__', 'target': 'agent'},
                        {'source': 'agent','target': '__end__'}
                    ]
            }


        """  # noqa: E501
        return await self.http.get(
            f"/assistants/{assistant_id}/graph", params={"xray": xray}
        )

    async def get_schemas(self, assistant_id: str) -> GraphSchema:
        """Get the schemas of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the schema of.

        Returns:
            GraphSchema: The graph schema for the assistant.

        Example Usage:

            schema = await client.assistants.get_schemas(
                assistant_id="my_assistant_id"
            )
            print(schema)

            ----------------------------------------------------------------------------------------------------------------------------

            {
                'graph_id': 'agent',
                'state_schema':
                    {
                        'title': 'LangGraphInput',
                        '$ref': '#/definitions/AgentState',
                        'definitions':
                            {
                                'BaseMessage':
                                    {
                                        'title': 'BaseMessage',
                                        'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                                        'type': 'object',
                                        'properties':
                                            {
                                             'content':
                                                {
                                                    'title': 'Content',
                                                    'anyOf': [
                                                        {'type': 'string'},
                                                        {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                                    ]
                                                },
                                            'additional_kwargs':
                                                {
                                                    'title': 'Additional Kwargs',
                                                    'type': 'object'
                                                },
                                            'response_metadata':
                                                {
                                                    'title': 'Response Metadata',
                                                    'type': 'object'
                                                },
                                            'type':
                                                {
                                                    'title': 'Type',
                                                    'type': 'string'
                                                },
                                            'name':
                                                {
                                                    'title': 'Name',
                                                    'type': 'string'
                                                },
                                            'id':
                                                {
                                                    'title': 'Id',
                                                    'type': 'string'
                                                }
                                            },
                                        'required': ['content', 'type']
                                    },
                                'AgentState':
                                    {
                                        'title': 'AgentState',
                                        'type': 'object',
                                        'properties':
                                            {
                                                'messages':
                                                    {
                                                        'title': 'Messages',
                                                        'type': 'array',
                                                        'items': {'$ref': '#/definitions/BaseMessage'}
                                                    }
                                            },
                                        'required': ['messages']
                                    }
                            }
                    },
                'config_schema':
                    {
                        'title': 'Configurable',
                        'type': 'object',
                        'properties':
                            {
                                'model_name':
                                    {
                                        'title': 'Model Name',
                                        'enum': ['anthropic', 'openai'],
                                        'type': 'string'
                                    }
                            }
                    }
            }

        """  # noqa: E501
        return await self.http.get(f"/assistants/{assistant_id}/schemas")

    async def get_subgraphs(
        self, assistant_id: str, namespace: Optional[str] = None, recurse: bool = False
    ) -> Subgraphs:
        """Get the schemas of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the schema of.

        Returns:
            Subgraphs: The graph schema for the assistant.

        """  # noqa: E501
        if namespace is not None:
            return await self.http.get(
                f"/assistants/{assistant_id}/subgraphs/{namespace}",
                params={"recurse": recurse},
            )
        else:
            return await self.http.get(
                f"/assistants/{assistant_id}/subgraphs",
                params={"recurse": recurse},
            )

    async def create(
        self,
        graph_id: Optional[str],
        config: Optional[Config] = None,
        *,
        metadata: Json = None,
        assistant_id: Optional[str] = None,
        if_exists: Optional[OnConflictBehavior] = None,
        name: Optional[str] = None,
    ) -> Assistant:
        """Create a new assistant.

        Useful when graph is configurable and you want to create different assistants based on different configurations.

        Args:
            graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
            config: Configuration to use for the graph.
            metadata: Metadata to add to assistant.
            assistant_id: Assistant ID to use, will default to a random UUID if not provided.
            if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
                Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
            name: The name of the assistant. Defaults to 'Untitled' under the hood.

        Returns:
            Assistant: The created assistant.

        Example Usage:

            assistant = await client.assistants.create(
                graph_id="agent",
                config={"configurable": {"model_name": "openai"}},
                metadata={"number":1},
                assistant_id="my-assistant-id",
                if_exists="do_nothing",
                name="my_name"
            )
        """  # noqa: E501
        payload: Dict[str, Any] = {
            "graph_id": graph_id,
        }
        if config:
            payload["config"] = config
        if metadata:
            payload["metadata"] = metadata
        if assistant_id:
            payload["assistant_id"] = assistant_id
        if if_exists:
            payload["if_exists"] = if_exists
        if name:
            payload["name"] = name
        return await self.http.post("/assistants", json=payload)

    async def update(
        self,
        assistant_id: str,
        *,
        graph_id: Optional[str] = None,
        config: Optional[Config] = None,
        metadata: Json = None,
        name: Optional[str] = None,
    ) -> Assistant:
        """Update an assistant.

        Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

        Args:
            assistant_id: Assistant to update.
            graph_id: The ID of the graph the assistant should use.
                The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.
            config: Configuration to use for the graph.
            metadata: Metadata to merge with existing assistant metadata.
            name: The new name for the assistant.

        Returns:
            Assistant: The updated assistant.

        Example Usage:

            assistant = await client.assistants.update(
                assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
                graph_id="other-graph",
                config={"configurable": {"model_name": "anthropic"}},
                metadata={"number":2}
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {}
        if graph_id:
            payload["graph_id"] = graph_id
        if config:
            payload["config"] = config
        if metadata:
            payload["metadata"] = metadata
        if name:
            payload["name"] = name
        return await self.http.patch(
            f"/assistants/{assistant_id}",
            json=payload,
        )

    async def delete(
        self,
        assistant_id: str,
    ) -> None:
        """Delete an assistant.

        Args:
            assistant_id: The assistant ID to delete.

        Returns:
            None

        Example Usage:

            await client.assistants.delete(
                assistant_id="my_assistant_id"
            )

        """  # noqa: E501
        await self.http.delete(f"/assistants/{assistant_id}")

    async def search(
        self,
        *,
        metadata: Json = None,
        graph_id: Optional[str] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Assistant]:
        """Search for assistants.

        Args:
            metadata: Metadata to filter by. Exact match filter for each KV pair.
            graph_id: The ID of the graph to filter by.
                The graph ID is normally set in your langgraph.json configuration.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            list[Assistant]: A list of assistants.

        Example Usage:

            assistants = await client.assistants.search(
                metadata = {"name":"my_name"},
                graph_id="my_graph_id",
                limit=5,
                offset=5
            )
        """
        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        if graph_id:
            payload["graph_id"] = graph_id
        return await self.http.post(
            "/assistants/search",
            json=payload,
        )

    async def get_versions(
        self,
        assistant_id: str,
        metadata: Json = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[AssistantVersion]:
        """List all versions of an assistant.

        Args:
            assistant_id: The assistant ID to get versions for.
            metadata: Metadata to filter versions by. Exact match filter for each KV pair.
            limit: The maximum number of versions to return.
            offset: The number of versions to skip.

        Returns:
            list[Assistant]: A list of assistants.

        Example Usage:

            assistant_versions = await client.assistants.get_versions(
                assistant_id="my_assistant_id"
            )

        """  # noqa: E501

        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        return await self.http.post(
            f"/assistants/{assistant_id}/versions", json=payload
        )

    async def set_latest(self, assistant_id: str, version: int) -> Assistant:
        """Change the version of an assistant.

        Args:
            assistant_id: The assistant ID to delete.
            version: The version to change to.

        Returns:
            Assistant: Assistant Object.

        Example Usage:

            new_version_assistant = await client.assistants.set_latest(
                assistant_id="my_assistant_id",
                version=3
            )

        """  # noqa: E501

        payload: Dict[str, Any] = {"version": version}

        return await self.http.post(f"/assistants/{assistant_id}/latest", json=payload)

get(assistant_id: str) -> Assistant async

Get an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get.

Returns:

  • Assistant ( Assistant ) –

    Assistant Object.

Example Usage:

assistant = await client.assistants.get(
    assistant_id="my_assistant_id"
)
print(assistant)

----------------------------------------------------

{
    'assistant_id': 'my_assistant_id',
    'graph_id': 'agent',
    'created_at': '2024-06-25T17:10:33.109781+00:00',
    'updated_at': '2024-06-25T17:10:33.109781+00:00',
    'config': {},
    'metadata': {'created_by': 'system'}
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get(self, assistant_id: str) -> Assistant:
    """Get an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get.

    Returns:
        Assistant: Assistant Object.

    Example Usage:

        assistant = await client.assistants.get(
            assistant_id="my_assistant_id"
        )
        print(assistant)

        ----------------------------------------------------

        {
            'assistant_id': 'my_assistant_id',
            'graph_id': 'agent',
            'created_at': '2024-06-25T17:10:33.109781+00:00',
            'updated_at': '2024-06-25T17:10:33.109781+00:00',
            'config': {},
            'metadata': {'created_by': 'system'}
        }

    """  # noqa: E501
    return await self.http.get(f"/assistants/{assistant_id}")

get_graph(assistant_id: str, *, xray: Union[int, bool] = False) -> dict[str, list[dict[str, Any]]] async

Get the graph of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the graph of.

  • xray (Union[int, bool], default: False ) –

    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.

Returns:

  • Graph ( dict[str, list[dict[str, Any]]] ) –

    The graph information for the assistant in JSON format.

Example Usage:

graph_info = await client.assistants.get_graph(
    assistant_id="my_assistant_id"
)
print(graph_info)

--------------------------------------------------------------------------------------------------------------------------

{
    'nodes':
        [
            {'id': '__start__', 'type': 'schema', 'data': '__start__'},
            {'id': '__end__', 'type': 'schema', 'data': '__end__'},
            {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
        ],
    'edges':
        [
            {'source': '__start__', 'target': 'agent'},
            {'source': 'agent','target': '__end__'}
        ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_graph(
    self, assistant_id: str, *, xray: Union[int, bool] = False
) -> dict[str, list[dict[str, Any]]]:
    """Get the graph of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the graph of.
        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.

    Returns:
        Graph: The graph information for the assistant in JSON format.

    Example Usage:

        graph_info = await client.assistants.get_graph(
            assistant_id="my_assistant_id"
        )
        print(graph_info)

        --------------------------------------------------------------------------------------------------------------------------

        {
            'nodes':
                [
                    {'id': '__start__', 'type': 'schema', 'data': '__start__'},
                    {'id': '__end__', 'type': 'schema', 'data': '__end__'},
                    {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
                ],
            'edges':
                [
                    {'source': '__start__', 'target': 'agent'},
                    {'source': 'agent','target': '__end__'}
                ]
        }


    """  # noqa: E501
    return await self.http.get(
        f"/assistants/{assistant_id}/graph", params={"xray": xray}
    )

get_schemas(assistant_id: str) -> GraphSchema async

Get the schemas of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the schema of.

Returns:

  • GraphSchema ( GraphSchema ) –

    The graph schema for the assistant.

Example Usage:

schema = await client.assistants.get_schemas(
    assistant_id="my_assistant_id"
)
print(schema)

----------------------------------------------------------------------------------------------------------------------------

{
    'graph_id': 'agent',
    'state_schema':
        {
            'title': 'LangGraphInput',
            '$ref': '#/definitions/AgentState',
            'definitions':
                {
                    'BaseMessage':
                        {
                            'title': 'BaseMessage',
                            'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                            'type': 'object',
                            'properties':
                                {
                                 'content':
                                    {
                                        'title': 'Content',
                                        'anyOf': [
                                            {'type': 'string'},
                                            {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                        ]
                                    },
                                'additional_kwargs':
                                    {
                                        'title': 'Additional Kwargs',
                                        'type': 'object'
                                    },
                                'response_metadata':
                                    {
                                        'title': 'Response Metadata',
                                        'type': 'object'
                                    },
                                'type':
                                    {
                                        'title': 'Type',
                                        'type': 'string'
                                    },
                                'name':
                                    {
                                        'title': 'Name',
                                        'type': 'string'
                                    },
                                'id':
                                    {
                                        'title': 'Id',
                                        'type': 'string'
                                    }
                                },
                            'required': ['content', 'type']
                        },
                    'AgentState':
                        {
                            'title': 'AgentState',
                            'type': 'object',
                            'properties':
                                {
                                    'messages':
                                        {
                                            'title': 'Messages',
                                            'type': 'array',
                                            'items': {'$ref': '#/definitions/BaseMessage'}
                                        }
                                },
                            'required': ['messages']
                        }
                }
        },
    'config_schema':
        {
            'title': 'Configurable',
            'type': 'object',
            'properties':
                {
                    'model_name':
                        {
                            'title': 'Model Name',
                            'enum': ['anthropic', 'openai'],
                            'type': 'string'
                        }
                }
        }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_schemas(self, assistant_id: str) -> GraphSchema:
    """Get the schemas of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the schema of.

    Returns:
        GraphSchema: The graph schema for the assistant.

    Example Usage:

        schema = await client.assistants.get_schemas(
            assistant_id="my_assistant_id"
        )
        print(schema)

        ----------------------------------------------------------------------------------------------------------------------------

        {
            'graph_id': 'agent',
            'state_schema':
                {
                    'title': 'LangGraphInput',
                    '$ref': '#/definitions/AgentState',
                    'definitions':
                        {
                            'BaseMessage':
                                {
                                    'title': 'BaseMessage',
                                    'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                                    'type': 'object',
                                    'properties':
                                        {
                                         'content':
                                            {
                                                'title': 'Content',
                                                'anyOf': [
                                                    {'type': 'string'},
                                                    {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                                ]
                                            },
                                        'additional_kwargs':
                                            {
                                                'title': 'Additional Kwargs',
                                                'type': 'object'
                                            },
                                        'response_metadata':
                                            {
                                                'title': 'Response Metadata',
                                                'type': 'object'
                                            },
                                        'type':
                                            {
                                                'title': 'Type',
                                                'type': 'string'
                                            },
                                        'name':
                                            {
                                                'title': 'Name',
                                                'type': 'string'
                                            },
                                        'id':
                                            {
                                                'title': 'Id',
                                                'type': 'string'
                                            }
                                        },
                                    'required': ['content', 'type']
                                },
                            'AgentState':
                                {
                                    'title': 'AgentState',
                                    'type': 'object',
                                    'properties':
                                        {
                                            'messages':
                                                {
                                                    'title': 'Messages',
                                                    'type': 'array',
                                                    'items': {'$ref': '#/definitions/BaseMessage'}
                                                }
                                        },
                                    'required': ['messages']
                                }
                        }
                },
            'config_schema':
                {
                    'title': 'Configurable',
                    'type': 'object',
                    'properties':
                        {
                            'model_name':
                                {
                                    'title': 'Model Name',
                                    'enum': ['anthropic', 'openai'],
                                    'type': 'string'
                                }
                        }
                }
        }

    """  # noqa: E501
    return await self.http.get(f"/assistants/{assistant_id}/schemas")

get_subgraphs(assistant_id: str, namespace: Optional[str] = None, recurse: bool = False) -> Subgraphs async

Get the schemas of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the schema of.

Returns:

  • Subgraphs ( Subgraphs ) –

    The graph schema for the assistant.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_subgraphs(
    self, assistant_id: str, namespace: Optional[str] = None, recurse: bool = False
) -> Subgraphs:
    """Get the schemas of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the schema of.

    Returns:
        Subgraphs: The graph schema for the assistant.

    """  # noqa: E501
    if namespace is not None:
        return await self.http.get(
            f"/assistants/{assistant_id}/subgraphs/{namespace}",
            params={"recurse": recurse},
        )
    else:
        return await self.http.get(
            f"/assistants/{assistant_id}/subgraphs",
            params={"recurse": recurse},
        )

create(graph_id: Optional[str], config: Optional[Config] = None, *, metadata: Json = None, assistant_id: Optional[str] = None, if_exists: Optional[OnConflictBehavior] = None, name: Optional[str] = None) -> Assistant async

Create a new assistant.

Useful when graph is configurable and you want to create different assistants based on different configurations.

Parameters:

  • graph_id (Optional[str]) –

    The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.

  • config (Optional[Config], default: None ) –

    Configuration to use for the graph.

  • metadata (Json, default: None ) –

    Metadata to add to assistant.

  • assistant_id (Optional[str], default: None ) –

    Assistant ID to use, will default to a random UUID if not provided.

  • if_exists (Optional[OnConflictBehavior], default: None ) –

    How to handle duplicate creation. Defaults to 'raise' under the hood. Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).

  • name (Optional[str], default: None ) –

    The name of the assistant. Defaults to 'Untitled' under the hood.

Returns:

  • Assistant ( Assistant ) –

    The created assistant.

Example Usage:

assistant = await client.assistants.create(
    graph_id="agent",
    config={"configurable": {"model_name": "openai"}},
    metadata={"number":1},
    assistant_id="my-assistant-id",
    if_exists="do_nothing",
    name="my_name"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def create(
    self,
    graph_id: Optional[str],
    config: Optional[Config] = None,
    *,
    metadata: Json = None,
    assistant_id: Optional[str] = None,
    if_exists: Optional[OnConflictBehavior] = None,
    name: Optional[str] = None,
) -> Assistant:
    """Create a new assistant.

    Useful when graph is configurable and you want to create different assistants based on different configurations.

    Args:
        graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
        config: Configuration to use for the graph.
        metadata: Metadata to add to assistant.
        assistant_id: Assistant ID to use, will default to a random UUID if not provided.
        if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
            Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
        name: The name of the assistant. Defaults to 'Untitled' under the hood.

    Returns:
        Assistant: The created assistant.

    Example Usage:

        assistant = await client.assistants.create(
            graph_id="agent",
            config={"configurable": {"model_name": "openai"}},
            metadata={"number":1},
            assistant_id="my-assistant-id",
            if_exists="do_nothing",
            name="my_name"
        )
    """  # noqa: E501
    payload: Dict[str, Any] = {
        "graph_id": graph_id,
    }
    if config:
        payload["config"] = config
    if metadata:
        payload["metadata"] = metadata
    if assistant_id:
        payload["assistant_id"] = assistant_id
    if if_exists:
        payload["if_exists"] = if_exists
    if name:
        payload["name"] = name
    return await self.http.post("/assistants", json=payload)

update(assistant_id: str, *, graph_id: Optional[str] = None, config: Optional[Config] = None, metadata: Json = None, name: Optional[str] = None) -> Assistant async

Update an assistant.

Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

Parameters:

  • assistant_id (str) –

    Assistant to update.

  • graph_id (Optional[str], default: None ) –

    The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.

  • config (Optional[Config], default: None ) –

    Configuration to use for the graph.

  • metadata (Json, default: None ) –

    Metadata to merge with existing assistant metadata.

  • name (Optional[str], default: None ) –

    The new name for the assistant.

Returns:

  • Assistant ( Assistant ) –

    The updated assistant.

Example Usage:

assistant = await client.assistants.update(
    assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
    graph_id="other-graph",
    config={"configurable": {"model_name": "anthropic"}},
    metadata={"number":2}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def update(
    self,
    assistant_id: str,
    *,
    graph_id: Optional[str] = None,
    config: Optional[Config] = None,
    metadata: Json = None,
    name: Optional[str] = None,
) -> Assistant:
    """Update an assistant.

    Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

    Args:
        assistant_id: Assistant to update.
        graph_id: The ID of the graph the assistant should use.
            The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.
        config: Configuration to use for the graph.
        metadata: Metadata to merge with existing assistant metadata.
        name: The new name for the assistant.

    Returns:
        Assistant: The updated assistant.

    Example Usage:

        assistant = await client.assistants.update(
            assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
            graph_id="other-graph",
            config={"configurable": {"model_name": "anthropic"}},
            metadata={"number":2}
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {}
    if graph_id:
        payload["graph_id"] = graph_id
    if config:
        payload["config"] = config
    if metadata:
        payload["metadata"] = metadata
    if name:
        payload["name"] = name
    return await self.http.patch(
        f"/assistants/{assistant_id}",
        json=payload,
    )

delete(assistant_id: str) -> None async

Delete an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to delete.

Returns:

  • None

    None

Example Usage:

await client.assistants.delete(
    assistant_id="my_assistant_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete(
    self,
    assistant_id: str,
) -> None:
    """Delete an assistant.

    Args:
        assistant_id: The assistant ID to delete.

    Returns:
        None

    Example Usage:

        await client.assistants.delete(
            assistant_id="my_assistant_id"
        )

    """  # noqa: E501
    await self.http.delete(f"/assistants/{assistant_id}")

search(*, metadata: Json = None, graph_id: Optional[str] = None, limit: int = 10, offset: int = 0) -> list[Assistant] async

Search for assistants.

Parameters:

  • metadata (Json, default: None ) –

    Metadata to filter by. Exact match filter for each KV pair.

  • graph_id (Optional[str], default: None ) –

    The ID of the graph to filter by. The graph ID is normally set in your langgraph.json configuration.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • list[Assistant]

    list[Assistant]: A list of assistants.

Example Usage:

assistants = await client.assistants.search(
    metadata = {"name":"my_name"},
    graph_id="my_graph_id",
    limit=5,
    offset=5
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def search(
    self,
    *,
    metadata: Json = None,
    graph_id: Optional[str] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Assistant]:
    """Search for assistants.

    Args:
        metadata: Metadata to filter by. Exact match filter for each KV pair.
        graph_id: The ID of the graph to filter by.
            The graph ID is normally set in your langgraph.json configuration.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        list[Assistant]: A list of assistants.

    Example Usage:

        assistants = await client.assistants.search(
            metadata = {"name":"my_name"},
            graph_id="my_graph_id",
            limit=5,
            offset=5
        )
    """
    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    if graph_id:
        payload["graph_id"] = graph_id
    return await self.http.post(
        "/assistants/search",
        json=payload,
    )

get_versions(assistant_id: str, metadata: Json = None, limit: int = 10, offset: int = 0) -> list[AssistantVersion] async

List all versions of an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to get versions for.

  • metadata (Json, default: None ) –

    Metadata to filter versions by. Exact match filter for each KV pair.

  • limit (int, default: 10 ) –

    The maximum number of versions to return.

  • offset (int, default: 0 ) –

    The number of versions to skip.

Returns:

  • list[AssistantVersion]

    list[Assistant]: A list of assistants.

Example Usage:

assistant_versions = await client.assistants.get_versions(
    assistant_id="my_assistant_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_versions(
    self,
    assistant_id: str,
    metadata: Json = None,
    limit: int = 10,
    offset: int = 0,
) -> list[AssistantVersion]:
    """List all versions of an assistant.

    Args:
        assistant_id: The assistant ID to get versions for.
        metadata: Metadata to filter versions by. Exact match filter for each KV pair.
        limit: The maximum number of versions to return.
        offset: The number of versions to skip.

    Returns:
        list[Assistant]: A list of assistants.

    Example Usage:

        assistant_versions = await client.assistants.get_versions(
            assistant_id="my_assistant_id"
        )

    """  # noqa: E501

    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    return await self.http.post(
        f"/assistants/{assistant_id}/versions", json=payload
    )

set_latest(assistant_id: str, version: int) -> Assistant async

Change the version of an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to delete.

  • version (int) –

    The version to change to.

Returns:

  • Assistant ( Assistant ) –

    Assistant Object.

Example Usage:

new_version_assistant = await client.assistants.set_latest(
    assistant_id="my_assistant_id",
    version=3
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def set_latest(self, assistant_id: str, version: int) -> Assistant:
    """Change the version of an assistant.

    Args:
        assistant_id: The assistant ID to delete.
        version: The version to change to.

    Returns:
        Assistant: Assistant Object.

    Example Usage:

        new_version_assistant = await client.assistants.set_latest(
            assistant_id="my_assistant_id",
            version=3
        )

    """  # noqa: E501

    payload: Dict[str, Any] = {"version": version}

    return await self.http.post(f"/assistants/{assistant_id}/latest", json=payload)

ThreadsClient

Client for managing threads in LangGraph.

A thread maintains the state of a graph across multiple interactions/invocations (aka runs). It accumulates and persists the graph's state, allowing for continuity between separate invocations of the graph.

Example:

client = get_client()
new_thread = await client.threads.create(metadata={"user_id": "123"})
Source code in libs/sdk-py/langgraph_sdk/client.py
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
class ThreadsClient:
    """Client for managing threads in LangGraph.

    A thread maintains the state of a graph across multiple interactions/invocations (aka runs).
    It accumulates and persists the graph's state, allowing for continuity between separate
    invocations of the graph.

    Example:

        client = get_client()
        new_thread = await client.threads.create(metadata={"user_id": "123"})
    """

    def __init__(self, http: HttpClient) -> None:
        self.http = http

    async def get(self, thread_id: str) -> Thread:
        """Get a thread by ID.

        Args:
            thread_id: The ID of the thread to get.

        Returns:
            Thread: Thread object.

        Example Usage:

            thread = await client.threads.get(
                thread_id="my_thread_id"
            )
            print(thread)

            -----------------------------------------------------

            {
                'thread_id': 'my_thread_id',
                'created_at': '2024-07-18T18:35:15.540834+00:00',
                'updated_at': '2024-07-18T18:35:15.540834+00:00',
                'metadata': {'graph_id': 'agent'}
            }

        """  # noqa: E501

        return await self.http.get(f"/threads/{thread_id}")

    async def create(
        self,
        *,
        metadata: Json = None,
        thread_id: Optional[str] = None,
        if_exists: Optional[OnConflictBehavior] = None,
    ) -> Thread:
        """Create a new thread.

        Args:
            metadata: Metadata to add to thread.
            thread_id: ID of thread.
                If None, ID will be a randomly generated UUID.
            if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
                Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

        Returns:
            Thread: The created thread.

        Example Usage:

            thread = await client.threads.create(
                metadata={"number":1},
                thread_id="my-thread-id",
                if_exists="raise"
            )
        """  # noqa: E501
        payload: Dict[str, Any] = {}
        if thread_id:
            payload["thread_id"] = thread_id
        if metadata:
            payload["metadata"] = metadata
        if if_exists:
            payload["if_exists"] = if_exists
        return await self.http.post("/threads", json=payload)

    async def update(self, thread_id: str, *, metadata: dict[str, Any]) -> Thread:
        """Update a thread.

        Args:
            thread_id: ID of thread to update.
            metadata: Metadata to merge with existing thread metadata.

        Returns:
            Thread: The created thread.

        Example Usage:

            thread = await client.threads.update(
                thread_id="my-thread-id",
                metadata={"number":1},
            )
        """  # noqa: E501
        return await self.http.patch(
            f"/threads/{thread_id}", json={"metadata": metadata}
        )

    async def delete(self, thread_id: str) -> None:
        """Delete a thread.

        Args:
            thread_id: The ID of the thread to delete.

        Returns:
            None

        Example Usage:

            await client.threads.delete(
                thread_id="my_thread_id"
            )

        """  # noqa: E501
        await self.http.delete(f"/threads/{thread_id}")

    async def search(
        self,
        *,
        metadata: Json = None,
        values: Json = None,
        status: Optional[ThreadStatus] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Thread]:
        """Search for threads.

        Args:
            metadata: Thread metadata to filter on.
            values: State values to filter on.
            status: Thread status to filter on.
                Must be one of 'idle', 'busy', 'interrupted' or 'error'.
            limit: Limit on number of threads to return.
            offset: Offset in threads table to start search from.

        Returns:
            list[Thread]: List of the threads matching the search parameters.

        Example Usage:

            threads = await client.threads.search(
                metadata={"number":1},
                status="interrupted",
                limit=15,
                offset=5
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        if values:
            payload["values"] = values
        if status:
            payload["status"] = status
        return await self.http.post(
            "/threads/search",
            json=payload,
        )

    async def copy(self, thread_id: str) -> None:
        """Copy a thread.

        Args:
            thread_id: The ID of the thread to copy.

        Returns:
            None

        Example Usage:

            await client.threads.copy(
                thread_id="my_thread_id"
            )

        """  # noqa: E501
        return await self.http.post(f"/threads/{thread_id}/copy", json=None)

    async def get_state(
        self,
        thread_id: str,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,  # deprecated
        *,
        subgraphs: bool = False,
    ) -> ThreadState:
        """Get the state of a thread.

        Args:
            thread_id: The ID of the thread to get the state of.
            checkpoint: The checkpoint to get the state of.
            subgraphs: Include subgraphs states.

        Returns:
            ThreadState: the thread of the state.

        Example Usage:

            thread_state = await client.threads.get_state(
                thread_id="my_thread_id",
                checkpoint_id="my_checkpoint_id"
            )
            print(thread_state)

            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'values': {
                    '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
                        }
                    ]
                },
                'next': [],
                'checkpoint':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
                    }
                'metadata':
                    {
                        'step': 1,
                        'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
                        'source': 'loop',
                        'writes':
                            {
                                'agent':
                                    {
                                        'messages': [
                                            {
                                                'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                                'name': None,
                                                'type': 'ai',
                                                'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                                'example': False,
                                                'tool_calls': [],
                                                'usage_metadata': None,
                                                'additional_kwargs': {},
                                                'response_metadata': {},
                                                'invalid_tool_calls': []
                                            }
                                        ]
                                    }
                            },
                'user_id': None,
                'graph_id': 'agent',
                'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                'created_by': 'system',
                'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
                'created_at': '2024-07-25T15:35:44.184703+00:00',
                'parent_config':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
                    }
            }

        """  # noqa: E501
        if checkpoint:
            return await self.http.post(
                f"/threads/{thread_id}/state/checkpoint",
                json={"checkpoint": checkpoint, "subgraphs": subgraphs},
            )
        elif checkpoint_id:
            return await self.http.get(
                f"/threads/{thread_id}/state/{checkpoint_id}",
                params={"subgraphs": subgraphs},
            )
        else:
            return await self.http.get(
                f"/threads/{thread_id}/state",
                params={"subgraphs": subgraphs},
            )

    async def update_state(
        self,
        thread_id: str,
        values: Optional[Union[dict, Sequence[dict]]],
        *,
        as_node: Optional[str] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,  # deprecated
    ) -> ThreadUpdateStateResponse:
        """Update the state of a thread.

        Args:
            thread_id: The ID of the thread to update.
            values: The values to update the state with.
            as_node: Update the state as if this node had just executed.
            checkpoint: The checkpoint to update the state of.

        Returns:
            ThreadUpdateStateResponse: Response after updating a thread's state.

        Example Usage:

            response = await client.threads.update_state(
                thread_id="my_thread_id",
                values={"messages":[{"role": "user", "content": "hello!"}]},
                as_node="my_node",
            )
            print(response)

            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'checkpoint': {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
                    'checkpoint_map': {}
                }
            }

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "values": values,
        }
        if checkpoint_id:
            payload["checkpoint_id"] = checkpoint_id
        if checkpoint:
            payload["checkpoint"] = checkpoint
        if as_node:
            payload["as_node"] = as_node
        return await self.http.post(f"/threads/{thread_id}/state", json=payload)

    async def get_history(
        self,
        thread_id: str,
        *,
        limit: int = 10,
        before: Optional[str | Checkpoint] = None,
        metadata: Optional[dict] = None,
        checkpoint: Optional[Checkpoint] = None,
    ) -> list[ThreadState]:
        """Get the state history of a thread.

        Args:
            thread_id: The ID of the thread to get the state history for.
            checkpoint: Return states for this subgraph. If empty defaults to root.
            limit: The maximum number of states to return.
            before: Return states before this checkpoint.
            metadata: Filter states by metadata key-value pairs.

        Returns:
            list[ThreadState]: the state history of the thread.

        Example Usage:

            thread_state = await client.threads.get_history(
                thread_id="my_thread_id",
                limit=5,
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "limit": limit,
        }
        if before:
            payload["before"] = before
        if metadata:
            payload["metadata"] = metadata
        if checkpoint:
            payload["checkpoint"] = checkpoint
        return await self.http.post(f"/threads/{thread_id}/history", json=payload)

get(thread_id: str) -> Thread async

Get a thread by ID.

Parameters:

  • thread_id (str) –

    The ID of the thread to get.

Returns:

  • Thread ( Thread ) –

    Thread object.

Example Usage:

thread = await client.threads.get(
    thread_id="my_thread_id"
)
print(thread)

-----------------------------------------------------

{
    'thread_id': 'my_thread_id',
    'created_at': '2024-07-18T18:35:15.540834+00:00',
    'updated_at': '2024-07-18T18:35:15.540834+00:00',
    'metadata': {'graph_id': 'agent'}
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get(self, thread_id: str) -> Thread:
    """Get a thread by ID.

    Args:
        thread_id: The ID of the thread to get.

    Returns:
        Thread: Thread object.

    Example Usage:

        thread = await client.threads.get(
            thread_id="my_thread_id"
        )
        print(thread)

        -----------------------------------------------------

        {
            'thread_id': 'my_thread_id',
            'created_at': '2024-07-18T18:35:15.540834+00:00',
            'updated_at': '2024-07-18T18:35:15.540834+00:00',
            'metadata': {'graph_id': 'agent'}
        }

    """  # noqa: E501

    return await self.http.get(f"/threads/{thread_id}")

create(*, metadata: Json = None, thread_id: Optional[str] = None, if_exists: Optional[OnConflictBehavior] = None) -> Thread async

Create a new thread.

Parameters:

  • metadata (Json, default: None ) –

    Metadata to add to thread.

  • thread_id (Optional[str], default: None ) –

    ID of thread. If None, ID will be a randomly generated UUID.

  • if_exists (Optional[OnConflictBehavior], default: None ) –

    How to handle duplicate creation. Defaults to 'raise' under the hood. Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

Returns:

  • Thread ( Thread ) –

    The created thread.

Example Usage:

thread = await client.threads.create(
    metadata={"number":1},
    thread_id="my-thread-id",
    if_exists="raise"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def create(
    self,
    *,
    metadata: Json = None,
    thread_id: Optional[str] = None,
    if_exists: Optional[OnConflictBehavior] = None,
) -> Thread:
    """Create a new thread.

    Args:
        metadata: Metadata to add to thread.
        thread_id: ID of thread.
            If None, ID will be a randomly generated UUID.
        if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
            Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

    Returns:
        Thread: The created thread.

    Example Usage:

        thread = await client.threads.create(
            metadata={"number":1},
            thread_id="my-thread-id",
            if_exists="raise"
        )
    """  # noqa: E501
    payload: Dict[str, Any] = {}
    if thread_id:
        payload["thread_id"] = thread_id
    if metadata:
        payload["metadata"] = metadata
    if if_exists:
        payload["if_exists"] = if_exists
    return await self.http.post("/threads", json=payload)

update(thread_id: str, *, metadata: dict[str, Any]) -> Thread async

Update a thread.

Parameters:

  • thread_id (str) –

    ID of thread to update.

  • metadata (dict[str, Any]) –

    Metadata to merge with existing thread metadata.

Returns:

  • Thread ( Thread ) –

    The created thread.

Example Usage:

thread = await client.threads.update(
    thread_id="my-thread-id",
    metadata={"number":1},
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def update(self, thread_id: str, *, metadata: dict[str, Any]) -> Thread:
    """Update a thread.

    Args:
        thread_id: ID of thread to update.
        metadata: Metadata to merge with existing thread metadata.

    Returns:
        Thread: The created thread.

    Example Usage:

        thread = await client.threads.update(
            thread_id="my-thread-id",
            metadata={"number":1},
        )
    """  # noqa: E501
    return await self.http.patch(
        f"/threads/{thread_id}", json={"metadata": metadata}
    )

delete(thread_id: str) -> None async

Delete a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to delete.

Returns:

  • None

    None

Example Usage:

await client.threads.delete(
    thread_id="my_thread_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete(self, thread_id: str) -> None:
    """Delete a thread.

    Args:
        thread_id: The ID of the thread to delete.

    Returns:
        None

    Example Usage:

        await client.threads.delete(
            thread_id="my_thread_id"
        )

    """  # noqa: E501
    await self.http.delete(f"/threads/{thread_id}")

search(*, metadata: Json = None, values: Json = None, status: Optional[ThreadStatus] = None, limit: int = 10, offset: int = 0) -> list[Thread] async

Search for threads.

Parameters:

  • metadata (Json, default: None ) –

    Thread metadata to filter on.

  • values (Json, default: None ) –

    State values to filter on.

  • status (Optional[ThreadStatus], default: None ) –

    Thread status to filter on. Must be one of 'idle', 'busy', 'interrupted' or 'error'.

  • limit (int, default: 10 ) –

    Limit on number of threads to return.

  • offset (int, default: 0 ) –

    Offset in threads table to start search from.

Returns:

  • list[Thread]

    list[Thread]: List of the threads matching the search parameters.

Example Usage:

threads = await client.threads.search(
    metadata={"number":1},
    status="interrupted",
    limit=15,
    offset=5
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def search(
    self,
    *,
    metadata: Json = None,
    values: Json = None,
    status: Optional[ThreadStatus] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Thread]:
    """Search for threads.

    Args:
        metadata: Thread metadata to filter on.
        values: State values to filter on.
        status: Thread status to filter on.
            Must be one of 'idle', 'busy', 'interrupted' or 'error'.
        limit: Limit on number of threads to return.
        offset: Offset in threads table to start search from.

    Returns:
        list[Thread]: List of the threads matching the search parameters.

    Example Usage:

        threads = await client.threads.search(
            metadata={"number":1},
            status="interrupted",
            limit=15,
            offset=5
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    if values:
        payload["values"] = values
    if status:
        payload["status"] = status
    return await self.http.post(
        "/threads/search",
        json=payload,
    )

copy(thread_id: str) -> None async

Copy a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to copy.

Returns:

  • None

    None

Example Usage:

await client.threads.copy(
    thread_id="my_thread_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def copy(self, thread_id: str) -> None:
    """Copy a thread.

    Args:
        thread_id: The ID of the thread to copy.

    Returns:
        None

    Example Usage:

        await client.threads.copy(
            thread_id="my_thread_id"
        )

    """  # noqa: E501
    return await self.http.post(f"/threads/{thread_id}/copy", json=None)

get_state(thread_id: str, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, *, subgraphs: bool = False) -> ThreadState async

Get the state of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to get the state of.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to get the state of.

  • subgraphs (bool, default: False ) –

    Include subgraphs states.

Returns:

  • ThreadState ( ThreadState ) –

    the thread of the state.

Example Usage:

thread_state = await client.threads.get_state(
    thread_id="my_thread_id",
    checkpoint_id="my_checkpoint_id"
)
print(thread_state)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'values': {
        '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
            }
        ]
    },
    'next': [],
    'checkpoint':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
        }
    'metadata':
        {
            'step': 1,
            'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
            'source': 'loop',
            'writes':
                {
                    'agent':
                        {
                            'messages': [
                                {
                                    'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                    'name': None,
                                    'type': 'ai',
                                    'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                    'example': False,
                                    'tool_calls': [],
                                    'usage_metadata': None,
                                    'additional_kwargs': {},
                                    'response_metadata': {},
                                    'invalid_tool_calls': []
                                }
                            ]
                        }
                },
    'user_id': None,
    'graph_id': 'agent',
    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
    'created_by': 'system',
    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
    'created_at': '2024-07-25T15:35:44.184703+00:00',
    'parent_config':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
        }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_state(
    self,
    thread_id: str,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,  # deprecated
    *,
    subgraphs: bool = False,
) -> ThreadState:
    """Get the state of a thread.

    Args:
        thread_id: The ID of the thread to get the state of.
        checkpoint: The checkpoint to get the state of.
        subgraphs: Include subgraphs states.

    Returns:
        ThreadState: the thread of the state.

    Example Usage:

        thread_state = await client.threads.get_state(
            thread_id="my_thread_id",
            checkpoint_id="my_checkpoint_id"
        )
        print(thread_state)

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

        {
            'values': {
                '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
                    }
                ]
            },
            'next': [],
            'checkpoint':
                {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
                }
            'metadata':
                {
                    'step': 1,
                    'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
                    'source': 'loop',
                    'writes':
                        {
                            'agent':
                                {
                                    'messages': [
                                        {
                                            'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                            'name': None,
                                            'type': 'ai',
                                            'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                            'example': False,
                                            'tool_calls': [],
                                            'usage_metadata': None,
                                            'additional_kwargs': {},
                                            'response_metadata': {},
                                            'invalid_tool_calls': []
                                        }
                                    ]
                                }
                        },
            'user_id': None,
            'graph_id': 'agent',
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'created_by': 'system',
            'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
            'created_at': '2024-07-25T15:35:44.184703+00:00',
            'parent_config':
                {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
                }
        }

    """  # noqa: E501
    if checkpoint:
        return await self.http.post(
            f"/threads/{thread_id}/state/checkpoint",
            json={"checkpoint": checkpoint, "subgraphs": subgraphs},
        )
    elif checkpoint_id:
        return await self.http.get(
            f"/threads/{thread_id}/state/{checkpoint_id}",
            params={"subgraphs": subgraphs},
        )
    else:
        return await self.http.get(
            f"/threads/{thread_id}/state",
            params={"subgraphs": subgraphs},
        )

update_state(thread_id: str, values: Optional[Union[dict, Sequence[dict]]], *, as_node: Optional[str] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None) -> ThreadUpdateStateResponse async

Update the state of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to update.

  • values (Optional[Union[dict, Sequence[dict]]]) –

    The values to update the state with.

  • as_node (Optional[str], default: None ) –

    Update the state as if this node had just executed.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to update the state of.

Returns:

  • ThreadUpdateStateResponse ( ThreadUpdateStateResponse ) –

    Response after updating a thread's state.

Example Usage:

response = await client.threads.update_state(
    thread_id="my_thread_id",
    values={"messages":[{"role": "user", "content": "hello!"}]},
    as_node="my_node",
)
print(response)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'checkpoint': {
        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
        'checkpoint_ns': '',
        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
        'checkpoint_map': {}
    }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def update_state(
    self,
    thread_id: str,
    values: Optional[Union[dict, Sequence[dict]]],
    *,
    as_node: Optional[str] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,  # deprecated
) -> ThreadUpdateStateResponse:
    """Update the state of a thread.

    Args:
        thread_id: The ID of the thread to update.
        values: The values to update the state with.
        as_node: Update the state as if this node had just executed.
        checkpoint: The checkpoint to update the state of.

    Returns:
        ThreadUpdateStateResponse: Response after updating a thread's state.

    Example Usage:

        response = await client.threads.update_state(
            thread_id="my_thread_id",
            values={"messages":[{"role": "user", "content": "hello!"}]},
            as_node="my_node",
        )
        print(response)

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

        {
            'checkpoint': {
                'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                'checkpoint_ns': '',
                'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
                'checkpoint_map': {}
            }
        }

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "values": values,
    }
    if checkpoint_id:
        payload["checkpoint_id"] = checkpoint_id
    if checkpoint:
        payload["checkpoint"] = checkpoint
    if as_node:
        payload["as_node"] = as_node
    return await self.http.post(f"/threads/{thread_id}/state", json=payload)

get_history(thread_id: str, *, limit: int = 10, before: Optional[str | Checkpoint] = None, metadata: Optional[dict] = None, checkpoint: Optional[Checkpoint] = None) -> list[ThreadState] async

Get the state history of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to get the state history for.

  • checkpoint (Optional[Checkpoint], default: None ) –

    Return states for this subgraph. If empty defaults to root.

  • limit (int, default: 10 ) –

    The maximum number of states to return.

  • before (Optional[str | Checkpoint], default: None ) –

    Return states before this checkpoint.

  • metadata (Optional[dict], default: None ) –

    Filter states by metadata key-value pairs.

Returns:

  • list[ThreadState]

    list[ThreadState]: the state history of the thread.

Example Usage:

thread_state = await client.threads.get_history(
    thread_id="my_thread_id",
    limit=5,
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_history(
    self,
    thread_id: str,
    *,
    limit: int = 10,
    before: Optional[str | Checkpoint] = None,
    metadata: Optional[dict] = None,
    checkpoint: Optional[Checkpoint] = None,
) -> list[ThreadState]:
    """Get the state history of a thread.

    Args:
        thread_id: The ID of the thread to get the state history for.
        checkpoint: Return states for this subgraph. If empty defaults to root.
        limit: The maximum number of states to return.
        before: Return states before this checkpoint.
        metadata: Filter states by metadata key-value pairs.

    Returns:
        list[ThreadState]: the state history of the thread.

    Example Usage:

        thread_state = await client.threads.get_history(
            thread_id="my_thread_id",
            limit=5,
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "limit": limit,
    }
    if before:
        payload["before"] = before
    if metadata:
        payload["metadata"] = metadata
    if checkpoint:
        payload["checkpoint"] = checkpoint
    return await self.http.post(f"/threads/{thread_id}/history", json=payload)

RunsClient

Client for managing runs in LangGraph.

A run is a single assistant invocation with optional input, config, and metadata. This client manages runs, which can be stateful (on threads) or stateless.

Example:

client = get_client()
run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})
Source code in libs/sdk-py/langgraph_sdk/client.py
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
class RunsClient:
    """Client for managing runs in LangGraph.

    A run is a single assistant invocation with optional input, config, and metadata.
    This client manages runs, which can be stateful (on threads) or stateless.

    Example:

        client = get_client()
        run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})
    """

    def __init__(self, http: HttpClient) -> None:
        self.http = http

    @overload
    def stream(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> AsyncIterator[StreamPart]: ...

    @overload
    def stream(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        webhook: Optional[str] = None,
        after_seconds: Optional[int] = None,
    ) -> AsyncIterator[StreamPart]: ...

    def stream(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> AsyncIterator[StreamPart]:
        """Create a run and stream the results.

        Args:
            thread_id: the thread ID to assign to the thread.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to stream from.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            command: A command to execute. Cannot be combined with input.
            stream_mode: The stream mode(s) to use.
            stream_subgraphs: Whether to stream output from subgraphs.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            feedback_keys: Feedback keys to assign to run.
            on_disconnect: The disconnect mode to use.
                Must be one of 'cancel' or 'continue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            AsyncIterator[StreamPart]: Asynchronous iterator of stream results.

        Example Usage:

            async for chunk in client.runs.stream(
                thread_id=None,
                assistant_id="agent",
                input={"messages": [{"role": "user", "content": "how are you?"}]},
                stream_mode=["values","debug"],
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "anthropic"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            ):
                print(chunk)

            ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

            StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
            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}]})
            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}]})
            StreamPart(event='end', data=None)

        """  # noqa: E501
        payload = {
            "input": input,
            "command": command,
            "config": config,
            "metadata": metadata,
            "stream_mode": stream_mode,
            "stream_subgraphs": stream_subgraphs,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "feedback_keys": feedback_keys,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_disconnect": on_disconnect,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        endpoint = (
            f"/threads/{thread_id}/runs/stream"
            if thread_id is not None
            else "/runs/stream"
        )
        return self.http.stream(
            endpoint, "POST", json={k: v for k, v in payload.items() if v is not None}
        )

    @overload
    async def create(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Run: ...

    @overload
    async def create(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Run: ...

    async def create(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        after_seconds: Optional[int] = None,
    ) -> Run:
        """Create a background run.

        Args:
            thread_id: the thread ID to assign to the thread.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to stream from.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            command: A command to execute. Cannot be combined with input.
            stream_mode: The stream mode(s) to use.
            stream_subgraphs: Whether to stream output from subgraphs.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            Run: The created background run.

        Example Usage:

            background_run = await client.runs.create(
                thread_id="my_thread_id",
                assistant_id="my_assistant_id",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )
            print(background_run)

            --------------------------------------------------------------------------------

            {
                'run_id': 'my_run_id',
                'thread_id': 'my_thread_id',
                'assistant_id': 'my_assistant_id',
                'created_at': '2024-07-25T15:35:42.598503+00:00',
                'updated_at': '2024-07-25T15:35:42.598503+00:00',
                'metadata': {},
                'status': 'pending',
                'kwargs':
                    {
                        'input':
                            {
                                'messages': [
                                    {
                                        'role': 'user',
                                        'content': 'how are you?'
                                    }
                                ]
                            },
                        'config':
                            {
                                'metadata':
                                    {
                                        'created_by': 'system'
                                    },
                                'configurable':
                                    {
                                        'run_id': 'my_run_id',
                                        'user_id': None,
                                        'graph_id': 'agent',
                                        'thread_id': 'my_thread_id',
                                        'checkpoint_id': None,
                                        'model_name': "openai",
                                        'assistant_id': 'my_assistant_id'
                                    }
                            },
                        'webhook': "https://my.fake.webhook.com",
                        'temporary': False,
                        'stream_mode': ['values'],
                        'feedback_keys': None,
                        'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
                        'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
                    },
                'multitask_strategy': 'interrupt'
            }

        """  # noqa: E501
        payload = {
            "input": input,
            "command": command,
            "stream_mode": stream_mode,
            "stream_subgraphs": stream_subgraphs,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        payload = {k: v for k, v in payload.items() if v is not None}
        if thread_id:
            return await self.http.post(f"/threads/{thread_id}/runs", json=payload)
        else:
            return await self.http.post("/runs", json=payload)

    async def create_batch(self, payloads: list[RunCreate]) -> list[Run]:
        """Create a batch of stateless background runs."""

        def filter_payload(payload: RunCreate):
            return {k: v for k, v in payload.items() if v is not None}

        payloads = [filter_payload(payload) for payload in payloads]
        return await self.http.post("/runs/batch", json=payloads)

    @overload
    async def wait(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
        raise_error: bool = True,
    ) -> Union[list[dict], dict[str, Any]]: ...

    @overload
    async def wait(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
        raise_error: bool = True,
    ) -> Union[list[dict], dict[str, Any]]: ...

    async def wait(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        command: Optional[Command] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
        raise_error: bool = True,
    ) -> Union[list[dict], dict[str, Any]]:
        """Create a run, wait until it finishes and return the final state.

        Args:
            thread_id: the thread ID to create the run on.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to run.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            command: A command to execute. Cannot be combined with input.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            on_disconnect: The disconnect mode to use.
                Must be one of 'cancel' or 'continue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            Union[list[dict], dict[str, Any]]: The output of the run.

        Example Usage:

            final_state_of_run = await client.runs.wait(
                thread_id=None,
                assistant_id="agent",
                input={"messages": [{"role": "user", "content": "how are you?"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "anthropic"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )
            print(final_state_of_run)

            -------------------------------------------------------------------------------------------------------------------------------------------

            {
                'messages': [
                    {
                        'content': 'how are you?',
                        'additional_kwargs': {},
                        'response_metadata': {},
                        'type': 'human',
                        'name': None,
                        'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
                        '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
                        'example': False,
                        'tool_calls': [],
                        'invalid_tool_calls': [],
                        'usage_metadata': None
                    }
                ]
            }

        """  # noqa: E501
        payload = {
            "input": input,
            "command": command,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_disconnect": on_disconnect,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        endpoint = (
            f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
        )
        response = await self.http.post(
            endpoint, json={k: v for k, v in payload.items() if v is not None}
        )
        if (
            raise_error
            and isinstance(response, dict)
            and "__error__" in response
            and isinstance(response["__error__"], dict)
        ):
            raise Exception(
                f"{response['__error__'].get('error')}: {response['__error__'].get('message')}"
            )
        return response

    async def list(
        self, thread_id: str, *, limit: int = 10, offset: int = 0
    ) -> List[Run]:
        """List runs.

        Args:
            thread_id: The thread ID to list runs for.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            List[Run]: The runs for the thread.

        Example Usage:

            await client.runs.delete(
                thread_id="thread_id_to_delete",
                limit=5,
                offset=5,
            )

        """  # noqa: E501
        return await self.http.get(
            f"/threads/{thread_id}/runs?limit={limit}&offset={offset}"
        )

    async def get(self, thread_id: str, run_id: str) -> Run:
        """Get a run.

        Args:
            thread_id: The thread ID to get.
            run_id: The run ID to get.

        Returns:
            Run: Run object.

        Example Usage:

            run = await client.runs.get(
                thread_id="thread_id_to_delete",
                run_id="run_id_to_delete",
            )

        """  # noqa: E501

        return await self.http.get(f"/threads/{thread_id}/runs/{run_id}")

    async def cancel(
        self,
        thread_id: str,
        run_id: str,
        *,
        wait: bool = False,
        action: CancelAction = "interrupt",
    ) -> None:
        """Get a run.

        Args:
            thread_id: The thread ID to cancel.
            run_id: The run ID to cancek.
            wait: Whether to wait until run has completed.
            action: Action to take when cancelling the run. Possible values
                are `interrupt` or `rollback`. Default is `interrupt`.

        Returns:
            None

        Example Usage:

            await client.runs.cancel(
                thread_id="thread_id_to_cancel",
                run_id="run_id_to_cancel",
                wait=True,
                action="interrupt"
            )

        """  # noqa: E501
        return await self.http.post(
            f"/threads/{thread_id}/runs/{run_id}/cancel?wait={1 if wait else 0}&action={action}",
            json=None,
        )

    async def join(self, thread_id: str, run_id: str) -> dict:
        """Block until a run is done. Returns the final state of the thread.

        Args:
            thread_id: The thread ID to join.
            run_id: The run ID to join.

        Returns:
            None

        Example Usage:

            result =await client.runs.join(
                thread_id="thread_id_to_join",
                run_id="run_id_to_join"
            )

        """  # noqa: E501
        return await self.http.get(f"/threads/{thread_id}/runs/{run_id}/join")

    def join_stream(self, thread_id: str, run_id: str) -> AsyncIterator[StreamPart]:
        """Stream output from a run in real-time, until the run is done.
        Output is not buffered, so any output produced before this call will
        not be received here.

        Args:
            thread_id: The thread ID to join.
            run_id: The run ID to join.

        Returns:
            None

        Example Usage:

            await client.runs.join_stream(
                thread_id="thread_id_to_join",
                run_id="run_id_to_join"
            )

        """  # noqa: E501
        return self.http.stream(f"/threads/{thread_id}/runs/{run_id}/stream", "GET")

    async def delete(self, thread_id: str, run_id: str) -> None:
        """Delete a run.

        Args:
            thread_id: The thread ID to delete.
            run_id: The run ID to delete.

        Returns:
            None

        Example Usage:

            await client.runs.delete(
                thread_id="thread_id_to_delete",
                run_id="run_id_to_delete"
            )

        """  # noqa: E501
        await self.http.delete(f"/threads/{thread_id}/runs/{run_id}")

stream(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, command: Optional[Command] = None, stream_mode: Union[StreamMode, Sequence[StreamMode]] = 'values', stream_subgraphs: bool = False, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, feedback_keys: Optional[Sequence[str]] = None, on_disconnect: Optional[DisconnectMode] = None, on_completion: Optional[OnCompletionBehavior] = None, webhook: Optional[str] = None, multitask_strategy: Optional[MultitaskStrategy] = None, if_not_exists: Optional[IfNotExists] = None, after_seconds: Optional[int] = None) -> AsyncIterator[StreamPart]

Create a run and stream the results.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to assign to the thread. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to stream from. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • command (Optional[Command], default: None ) –

    A command to execute. Cannot be combined with input.

  • stream_mode (Union[StreamMode, Sequence[StreamMode]], default: 'values' ) –

    The stream mode(s) to use.

  • stream_subgraphs (bool, default: False ) –

    Whether to stream output from subgraphs.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • feedback_keys (Optional[Sequence[str]], default: None ) –

    Feedback keys to assign to run.

  • on_disconnect (Optional[DisconnectMode], default: None ) –

    The disconnect mode to use. Must be one of 'cancel' or 'continue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • AsyncIterator[StreamPart]

    AsyncIterator[StreamPart]: Asynchronous iterator of stream results.

Example Usage:

async for chunk in client.runs.stream(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    stream_mode=["values","debug"],
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
):
    print(chunk)

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
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}]})
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}]})
StreamPart(event='end', data=None)
Source code in libs/sdk-py/langgraph_sdk/client.py
def stream(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    command: Optional[Command] = None,
    stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
    stream_subgraphs: bool = False,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    feedback_keys: Optional[Sequence[str]] = None,
    on_disconnect: Optional[DisconnectMode] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    if_not_exists: Optional[IfNotExists] = None,
    after_seconds: Optional[int] = None,
) -> AsyncIterator[StreamPart]:
    """Create a run and stream the results.

    Args:
        thread_id: the thread ID to assign to the thread.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to stream from.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        command: A command to execute. Cannot be combined with input.
        stream_mode: The stream mode(s) to use.
        stream_subgraphs: Whether to stream output from subgraphs.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        feedback_keys: Feedback keys to assign to run.
        on_disconnect: The disconnect mode to use.
            Must be one of 'cancel' or 'continue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        AsyncIterator[StreamPart]: Asynchronous iterator of stream results.

    Example Usage:

        async for chunk in client.runs.stream(
            thread_id=None,
            assistant_id="agent",
            input={"messages": [{"role": "user", "content": "how are you?"}]},
            stream_mode=["values","debug"],
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "anthropic"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        ):
            print(chunk)

        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
        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}]})
        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}]})
        StreamPart(event='end', data=None)

    """  # noqa: E501
    payload = {
        "input": input,
        "command": command,
        "config": config,
        "metadata": metadata,
        "stream_mode": stream_mode,
        "stream_subgraphs": stream_subgraphs,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "feedback_keys": feedback_keys,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_disconnect": on_disconnect,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    endpoint = (
        f"/threads/{thread_id}/runs/stream"
        if thread_id is not None
        else "/runs/stream"
    )
    return self.http.stream(
        endpoint, "POST", json={k: v for k, v in payload.items() if v is not None}
    )

create(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, command: Optional[Command] = None, stream_mode: Union[StreamMode, Sequence[StreamMode]] = 'values', stream_subgraphs: bool = False, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[MultitaskStrategy] = None, if_not_exists: Optional[IfNotExists] = None, on_completion: Optional[OnCompletionBehavior] = None, after_seconds: Optional[int] = None) -> Run async

Create a background run.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to assign to the thread. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to stream from. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • command (Optional[Command], default: None ) –

    A command to execute. Cannot be combined with input.

  • stream_mode (Union[StreamMode, Sequence[StreamMode]], default: 'values' ) –

    The stream mode(s) to use.

  • stream_subgraphs (bool, default: False ) –

    Whether to stream output from subgraphs.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • Run ( Run ) –

    The created background run.

Example Usage:

background_run = await client.runs.create(
    thread_id="my_thread_id",
    assistant_id="my_assistant_id",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(background_run)

--------------------------------------------------------------------------------

{
    'run_id': 'my_run_id',
    'thread_id': 'my_thread_id',
    'assistant_id': 'my_assistant_id',
    'created_at': '2024-07-25T15:35:42.598503+00:00',
    'updated_at': '2024-07-25T15:35:42.598503+00:00',
    'metadata': {},
    'status': 'pending',
    'kwargs':
        {
            'input':
                {
                    'messages': [
                        {
                            'role': 'user',
                            'content': 'how are you?'
                        }
                    ]
                },
            'config':
                {
                    'metadata':
                        {
                            'created_by': 'system'
                        },
                    'configurable':
                        {
                            'run_id': 'my_run_id',
                            'user_id': None,
                            'graph_id': 'agent',
                            'thread_id': 'my_thread_id',
                            'checkpoint_id': None,
                            'model_name': "openai",
                            'assistant_id': 'my_assistant_id'
                        }
                },
            'webhook': "https://my.fake.webhook.com",
            'temporary': False,
            'stream_mode': ['values'],
            'feedback_keys': None,
            'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
            'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
        },
    'multitask_strategy': 'interrupt'
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def create(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    command: Optional[Command] = None,
    stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
    stream_subgraphs: bool = False,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    if_not_exists: Optional[IfNotExists] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    after_seconds: Optional[int] = None,
) -> Run:
    """Create a background run.

    Args:
        thread_id: the thread ID to assign to the thread.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to stream from.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        command: A command to execute. Cannot be combined with input.
        stream_mode: The stream mode(s) to use.
        stream_subgraphs: Whether to stream output from subgraphs.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        Run: The created background run.

    Example Usage:

        background_run = await client.runs.create(
            thread_id="my_thread_id",
            assistant_id="my_assistant_id",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )
        print(background_run)

        --------------------------------------------------------------------------------

        {
            'run_id': 'my_run_id',
            'thread_id': 'my_thread_id',
            'assistant_id': 'my_assistant_id',
            'created_at': '2024-07-25T15:35:42.598503+00:00',
            'updated_at': '2024-07-25T15:35:42.598503+00:00',
            'metadata': {},
            'status': 'pending',
            'kwargs':
                {
                    'input':
                        {
                            'messages': [
                                {
                                    'role': 'user',
                                    'content': 'how are you?'
                                }
                            ]
                        },
                    'config':
                        {
                            'metadata':
                                {
                                    'created_by': 'system'
                                },
                            'configurable':
                                {
                                    'run_id': 'my_run_id',
                                    'user_id': None,
                                    'graph_id': 'agent',
                                    'thread_id': 'my_thread_id',
                                    'checkpoint_id': None,
                                    'model_name': "openai",
                                    'assistant_id': 'my_assistant_id'
                                }
                        },
                    'webhook': "https://my.fake.webhook.com",
                    'temporary': False,
                    'stream_mode': ['values'],
                    'feedback_keys': None,
                    'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
                    'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
                },
            'multitask_strategy': 'interrupt'
        }

    """  # noqa: E501
    payload = {
        "input": input,
        "command": command,
        "stream_mode": stream_mode,
        "stream_subgraphs": stream_subgraphs,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    payload = {k: v for k, v in payload.items() if v is not None}
    if thread_id:
        return await self.http.post(f"/threads/{thread_id}/runs", json=payload)
    else:
        return await self.http.post("/runs", json=payload)

create_batch(payloads: list[RunCreate]) -> list[Run] async

Create a batch of stateless background runs.

Source code in libs/sdk-py/langgraph_sdk/client.py
async def create_batch(self, payloads: list[RunCreate]) -> list[Run]:
    """Create a batch of stateless background runs."""

    def filter_payload(payload: RunCreate):
        return {k: v for k, v in payload.items() if v is not None}

    payloads = [filter_payload(payload) for payload in payloads]
    return await self.http.post("/runs/batch", json=payloads)

wait(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, command: Optional[Command] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, webhook: Optional[str] = None, on_disconnect: Optional[DisconnectMode] = None, on_completion: Optional[OnCompletionBehavior] = None, multitask_strategy: Optional[MultitaskStrategy] = None, if_not_exists: Optional[IfNotExists] = None, after_seconds: Optional[int] = None, raise_error: bool = True) -> Union[list[dict], dict[str, Any]] async

Create a run, wait until it finishes and return the final state.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to create the run on. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to run. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • command (Optional[Command], default: None ) –

    A command to execute. Cannot be combined with input.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • on_disconnect (Optional[DisconnectMode], default: None ) –

    The disconnect mode to use. Must be one of 'cancel' or 'continue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • Union[list[dict], dict[str, Any]]

    Union[list[dict], dict[str, Any]]: The output of the run.

Example Usage:

final_state_of_run = await client.runs.wait(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(final_state_of_run)

-------------------------------------------------------------------------------------------------------------------------------------------

{
    'messages': [
        {
            'content': 'how are you?',
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'human',
            'name': None,
            'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
            '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
            'example': False,
            'tool_calls': [],
            'invalid_tool_calls': [],
            'usage_metadata': None
        }
    ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def wait(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    command: Optional[Command] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    webhook: Optional[str] = None,
    on_disconnect: Optional[DisconnectMode] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    if_not_exists: Optional[IfNotExists] = None,
    after_seconds: Optional[int] = None,
    raise_error: bool = True,
) -> Union[list[dict], dict[str, Any]]:
    """Create a run, wait until it finishes and return the final state.

    Args:
        thread_id: the thread ID to create the run on.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to run.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        command: A command to execute. Cannot be combined with input.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        on_disconnect: The disconnect mode to use.
            Must be one of 'cancel' or 'continue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        Union[list[dict], dict[str, Any]]: The output of the run.

    Example Usage:

        final_state_of_run = await client.runs.wait(
            thread_id=None,
            assistant_id="agent",
            input={"messages": [{"role": "user", "content": "how are you?"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "anthropic"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )
        print(final_state_of_run)

        -------------------------------------------------------------------------------------------------------------------------------------------

        {
            'messages': [
                {
                    'content': 'how are you?',
                    'additional_kwargs': {},
                    'response_metadata': {},
                    'type': 'human',
                    'name': None,
                    'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
                    '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
                    'example': False,
                    'tool_calls': [],
                    'invalid_tool_calls': [],
                    'usage_metadata': None
                }
            ]
        }

    """  # noqa: E501
    payload = {
        "input": input,
        "command": command,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_disconnect": on_disconnect,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    endpoint = (
        f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
    )
    response = await self.http.post(
        endpoint, json={k: v for k, v in payload.items() if v is not None}
    )
    if (
        raise_error
        and isinstance(response, dict)
        and "__error__" in response
        and isinstance(response["__error__"], dict)
    ):
        raise Exception(
            f"{response['__error__'].get('error')}: {response['__error__'].get('message')}"
        )
    return response

list(thread_id: str, *, limit: int = 10, offset: int = 0) -> List[Run] async

List runs.

Parameters:

  • thread_id (str) –

    The thread ID to list runs for.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • List[Run]

    List[Run]: The runs for the thread.

Example Usage:

await client.runs.delete(
    thread_id="thread_id_to_delete",
    limit=5,
    offset=5,
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def list(
    self, thread_id: str, *, limit: int = 10, offset: int = 0
) -> List[Run]:
    """List runs.

    Args:
        thread_id: The thread ID to list runs for.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        List[Run]: The runs for the thread.

    Example Usage:

        await client.runs.delete(
            thread_id="thread_id_to_delete",
            limit=5,
            offset=5,
        )

    """  # noqa: E501
    return await self.http.get(
        f"/threads/{thread_id}/runs?limit={limit}&offset={offset}"
    )

get(thread_id: str, run_id: str) -> Run async

Get a run.

Parameters:

  • thread_id (str) –

    The thread ID to get.

  • run_id (str) –

    The run ID to get.

Returns:

  • Run ( Run ) –

    Run object.

Example Usage:

run = await client.runs.get(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete",
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get(self, thread_id: str, run_id: str) -> Run:
    """Get a run.

    Args:
        thread_id: The thread ID to get.
        run_id: The run ID to get.

    Returns:
        Run: Run object.

    Example Usage:

        run = await client.runs.get(
            thread_id="thread_id_to_delete",
            run_id="run_id_to_delete",
        )

    """  # noqa: E501

    return await self.http.get(f"/threads/{thread_id}/runs/{run_id}")

cancel(thread_id: str, run_id: str, *, wait: bool = False, action: CancelAction = 'interrupt') -> None async

Get a run.

Parameters:

  • thread_id (str) –

    The thread ID to cancel.

  • run_id (str) –

    The run ID to cancek.

  • wait (bool, default: False ) –

    Whether to wait until run has completed.

  • action (CancelAction, default: 'interrupt' ) –

    Action to take when cancelling the run. Possible values are interrupt or rollback. Default is interrupt.

Returns:

  • None

    None

Example Usage:

await client.runs.cancel(
    thread_id="thread_id_to_cancel",
    run_id="run_id_to_cancel",
    wait=True,
    action="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def cancel(
    self,
    thread_id: str,
    run_id: str,
    *,
    wait: bool = False,
    action: CancelAction = "interrupt",
) -> None:
    """Get a run.

    Args:
        thread_id: The thread ID to cancel.
        run_id: The run ID to cancek.
        wait: Whether to wait until run has completed.
        action: Action to take when cancelling the run. Possible values
            are `interrupt` or `rollback`. Default is `interrupt`.

    Returns:
        None

    Example Usage:

        await client.runs.cancel(
            thread_id="thread_id_to_cancel",
            run_id="run_id_to_cancel",
            wait=True,
            action="interrupt"
        )

    """  # noqa: E501
    return await self.http.post(
        f"/threads/{thread_id}/runs/{run_id}/cancel?wait={1 if wait else 0}&action={action}",
        json=None,
    )

join(thread_id: str, run_id: str) -> dict async

Block until a run is done. Returns the final state of the thread.

Parameters:

  • thread_id (str) –

    The thread ID to join.

  • run_id (str) –

    The run ID to join.

Returns:

  • dict

    None

Example Usage:

result =await client.runs.join(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def join(self, thread_id: str, run_id: str) -> dict:
    """Block until a run is done. Returns the final state of the thread.

    Args:
        thread_id: The thread ID to join.
        run_id: The run ID to join.

    Returns:
        None

    Example Usage:

        result =await client.runs.join(
            thread_id="thread_id_to_join",
            run_id="run_id_to_join"
        )

    """  # noqa: E501
    return await self.http.get(f"/threads/{thread_id}/runs/{run_id}/join")

join_stream(thread_id: str, run_id: str) -> AsyncIterator[StreamPart]

Stream output from a run in real-time, until the run is done. Output is not buffered, so any output produced before this call will not be received here.

Parameters:

  • thread_id (str) –

    The thread ID to join.

  • run_id (str) –

    The run ID to join.

Returns:

  • AsyncIterator[StreamPart]

    None

Example Usage:

await client.runs.join_stream(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def join_stream(self, thread_id: str, run_id: str) -> AsyncIterator[StreamPart]:
    """Stream output from a run in real-time, until the run is done.
    Output is not buffered, so any output produced before this call will
    not be received here.

    Args:
        thread_id: The thread ID to join.
        run_id: The run ID to join.

    Returns:
        None

    Example Usage:

        await client.runs.join_stream(
            thread_id="thread_id_to_join",
            run_id="run_id_to_join"
        )

    """  # noqa: E501
    return self.http.stream(f"/threads/{thread_id}/runs/{run_id}/stream", "GET")

delete(thread_id: str, run_id: str) -> None async

Delete a run.

Parameters:

  • thread_id (str) –

    The thread ID to delete.

  • run_id (str) –

    The run ID to delete.

Returns:

  • None

    None

Example Usage:

await client.runs.delete(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete(self, thread_id: str, run_id: str) -> None:
    """Delete a run.

    Args:
        thread_id: The thread ID to delete.
        run_id: The run ID to delete.

    Returns:
        None

    Example Usage:

        await client.runs.delete(
            thread_id="thread_id_to_delete",
            run_id="run_id_to_delete"
        )

    """  # noqa: E501
    await self.http.delete(f"/threads/{thread_id}/runs/{run_id}")

CronClient

Client for managing recurrent runs (cron jobs) in LangGraph.

A run is a single invocation of an assistant with optional input and config. This client allows scheduling recurring runs to occur automatically.

Example:

client = get_client()
cron_job = await client.crons.create_for_thread(
    thread_id="thread_123",
    assistant_id="asst_456",
    schedule="0 9 * * *",
    input={"message": "Daily update"}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
class CronClient:
    """Client for managing recurrent runs (cron jobs) in LangGraph.

    A run is a single invocation of an assistant with optional input and config.
    This client allows scheduling recurring runs to occur automatically.

    Example:

        client = get_client()
        cron_job = await client.crons.create_for_thread(
            thread_id="thread_123",
            assistant_id="asst_456",
            schedule="0 9 * * *",
            input={"message": "Daily update"}
        )
    """

    def __init__(self, http_client: HttpClient) -> None:
        self.http = http_client

    async def create_for_thread(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        schedule: str,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, list[str]]] = None,
        interrupt_after: Optional[Union[All, list[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[str] = None,
    ) -> Run:
        """Create a cron job for a thread.

        Args:
            thread_id: the thread ID to run the cron job on.
            assistant_id: The assistant ID or graph name to use for the cron job.
                If using graph name, will default to first assistant created from that graph.
            schedule: The cron schedule to execute this job on.
            input: The input to the graph.
            metadata: Metadata to assign to the cron job runs.
            config: The configuration for the assistant.
            interrupt_before: Nodes to interrupt immediately before they get executed.

            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.

            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

        Returns:
            Run: The cron run.

        Example Usage:

            cron_run = await client.crons.create_for_thread(
                thread_id="my-thread-id",
                assistant_id="agent",
                schedule="27 15 * * *",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )

        """  # noqa: E501
        payload = {
            "schedule": schedule,
            "input": input,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
        }
        if multitask_strategy:
            payload["multitask_strategy"] = multitask_strategy
        payload = {k: v for k, v in payload.items() if v is not None}
        return await self.http.post(f"/threads/{thread_id}/runs/crons", json=payload)

    async def create(
        self,
        assistant_id: str,
        *,
        schedule: str,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, list[str]]] = None,
        interrupt_after: Optional[Union[All, list[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[str] = None,
    ) -> Run:
        """Create a cron run.

        Args:
            assistant_id: The assistant ID or graph name to use for the cron job.
                If using graph name, will default to first assistant created from that graph.
            schedule: The cron schedule to execute this job on.
            input: The input to the graph.
            metadata: Metadata to assign to the cron job runs.
            config: The configuration for the assistant.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

        Returns:
            Run: The cron run.

        Example Usage:

            cron_run = await client.crons.create(
                assistant_id="agent",
                schedule="27 15 * * *",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )

        """  # noqa: E501
        payload = {
            "schedule": schedule,
            "input": input,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
        }
        if multitask_strategy:
            payload["multitask_strategy"] = multitask_strategy
        payload = {k: v for k, v in payload.items() if v is not None}
        return await self.http.post("/runs/crons", json=payload)

    async def delete(self, cron_id: str) -> None:
        """Delete a cron.

        Args:
            cron_id: The cron ID to delete.

        Returns:
            None

        Example Usage:

            await client.crons.delete(
                cron_id="cron_to_delete"
            )

        """  # noqa: E501
        await self.http.delete(f"/runs/crons/{cron_id}")

    async def search(
        self,
        *,
        assistant_id: Optional[str] = None,
        thread_id: Optional[str] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Cron]:
        """Get a list of cron jobs.

        Args:
            assistant_id: The assistant ID or graph name to search for.
            thread_id: the thread ID to search for.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            list[Cron]: The list of cron jobs returned by the search,

        Example Usage:

            cron_jobs = await client.crons.search(
                assistant_id="my_assistant_id",
                thread_id="my_thread_id",
                limit=5,
                offset=5,
            )
            print(cron_jobs)

            ----------------------------------------------------------

            [
                {
                    'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
                    'assistant_id': 'my_assistant_id',
                    'thread_id': 'my_thread_id',
                    'user_id': None,
                    'payload':
                        {
                            'input': {'start_time': ''},
                            'schedule': '4 * * * *',
                            'assistant_id': 'my_assistant_id'
                        },
                    'schedule': '4 * * * *',
                    'next_run_date': '2024-07-25T17:04:00+00:00',
                    'end_time': None,
                    'created_at': '2024-07-08T06:02:23.073257+00:00',
                    'updated_at': '2024-07-08T06:02:23.073257+00:00'
                }
            ]

        """  # noqa: E501
        payload = {
            "assistant_id": assistant_id,
            "thread_id": thread_id,
            "limit": limit,
            "offset": offset,
        }
        payload = {k: v for k, v in payload.items() if v is not None}
        return await self.http.post("/runs/crons/search", json=payload)

create_for_thread(thread_id: str, assistant_id: str, *, schedule: str, input: Optional[dict] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, interrupt_before: Optional[Union[All, list[str]]] = None, interrupt_after: Optional[Union[All, list[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[str] = None) -> Run async

Create a cron job for a thread.

Parameters:

  • thread_id (str) –

    the thread ID to run the cron job on.

  • assistant_id (str) –

    The assistant ID or graph name to use for the cron job. If using graph name, will default to first assistant created from that graph.

  • schedule (str) –

    The cron schedule to execute this job on.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the cron job runs.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • interrupt_before (Optional[Union[All, list[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, list[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[str], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

Returns:

  • Run ( Run ) –

    The cron run.

Example Usage:

cron_run = await client.crons.create_for_thread(
    thread_id="my-thread-id",
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def create_for_thread(
    self,
    thread_id: str,
    assistant_id: str,
    *,
    schedule: str,
    input: Optional[dict] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    interrupt_before: Optional[Union[All, list[str]]] = None,
    interrupt_after: Optional[Union[All, list[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[str] = None,
) -> Run:
    """Create a cron job for a thread.

    Args:
        thread_id: the thread ID to run the cron job on.
        assistant_id: The assistant ID or graph name to use for the cron job.
            If using graph name, will default to first assistant created from that graph.
        schedule: The cron schedule to execute this job on.
        input: The input to the graph.
        metadata: Metadata to assign to the cron job runs.
        config: The configuration for the assistant.
        interrupt_before: Nodes to interrupt immediately before they get executed.

        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.

        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

    Returns:
        Run: The cron run.

    Example Usage:

        cron_run = await client.crons.create_for_thread(
            thread_id="my-thread-id",
            assistant_id="agent",
            schedule="27 15 * * *",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )

    """  # noqa: E501
    payload = {
        "schedule": schedule,
        "input": input,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
    }
    if multitask_strategy:
        payload["multitask_strategy"] = multitask_strategy
    payload = {k: v for k, v in payload.items() if v is not None}
    return await self.http.post(f"/threads/{thread_id}/runs/crons", json=payload)

create(assistant_id: str, *, schedule: str, input: Optional[dict] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, interrupt_before: Optional[Union[All, list[str]]] = None, interrupt_after: Optional[Union[All, list[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[str] = None) -> Run async

Create a cron run.

Parameters:

  • assistant_id (str) –

    The assistant ID or graph name to use for the cron job. If using graph name, will default to first assistant created from that graph.

  • schedule (str) –

    The cron schedule to execute this job on.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the cron job runs.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • interrupt_before (Optional[Union[All, list[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, list[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[str], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

Returns:

  • Run ( Run ) –

    The cron run.

Example Usage:

cron_run = await client.crons.create(
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def create(
    self,
    assistant_id: str,
    *,
    schedule: str,
    input: Optional[dict] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    interrupt_before: Optional[Union[All, list[str]]] = None,
    interrupt_after: Optional[Union[All, list[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[str] = None,
) -> Run:
    """Create a cron run.

    Args:
        assistant_id: The assistant ID or graph name to use for the cron job.
            If using graph name, will default to first assistant created from that graph.
        schedule: The cron schedule to execute this job on.
        input: The input to the graph.
        metadata: Metadata to assign to the cron job runs.
        config: The configuration for the assistant.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

    Returns:
        Run: The cron run.

    Example Usage:

        cron_run = await client.crons.create(
            assistant_id="agent",
            schedule="27 15 * * *",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )

    """  # noqa: E501
    payload = {
        "schedule": schedule,
        "input": input,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
    }
    if multitask_strategy:
        payload["multitask_strategy"] = multitask_strategy
    payload = {k: v for k, v in payload.items() if v is not None}
    return await self.http.post("/runs/crons", json=payload)

delete(cron_id: str) -> None async

Delete a cron.

Parameters:

  • cron_id (str) –

    The cron ID to delete.

Returns:

  • None

    None

Example Usage:

await client.crons.delete(
    cron_id="cron_to_delete"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete(self, cron_id: str) -> None:
    """Delete a cron.

    Args:
        cron_id: The cron ID to delete.

    Returns:
        None

    Example Usage:

        await client.crons.delete(
            cron_id="cron_to_delete"
        )

    """  # noqa: E501
    await self.http.delete(f"/runs/crons/{cron_id}")

search(*, assistant_id: Optional[str] = None, thread_id: Optional[str] = None, limit: int = 10, offset: int = 0) -> list[Cron] async

Get a list of cron jobs.

Parameters:

  • assistant_id (Optional[str], default: None ) –

    The assistant ID or graph name to search for.

  • thread_id (Optional[str], default: None ) –

    the thread ID to search for.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • list[Cron]

    list[Cron]: The list of cron jobs returned by the search,

Example Usage:

cron_jobs = await client.crons.search(
    assistant_id="my_assistant_id",
    thread_id="my_thread_id",
    limit=5,
    offset=5,
)
print(cron_jobs)

----------------------------------------------------------

[
    {
        'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
        'assistant_id': 'my_assistant_id',
        'thread_id': 'my_thread_id',
        'user_id': None,
        'payload':
            {
                'input': {'start_time': ''},
                'schedule': '4 * * * *',
                'assistant_id': 'my_assistant_id'
            },
        'schedule': '4 * * * *',
        'next_run_date': '2024-07-25T17:04:00+00:00',
        'end_time': None,
        'created_at': '2024-07-08T06:02:23.073257+00:00',
        'updated_at': '2024-07-08T06:02:23.073257+00:00'
    }
]
Source code in libs/sdk-py/langgraph_sdk/client.py
async def search(
    self,
    *,
    assistant_id: Optional[str] = None,
    thread_id: Optional[str] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Cron]:
    """Get a list of cron jobs.

    Args:
        assistant_id: The assistant ID or graph name to search for.
        thread_id: the thread ID to search for.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        list[Cron]: The list of cron jobs returned by the search,

    Example Usage:

        cron_jobs = await client.crons.search(
            assistant_id="my_assistant_id",
            thread_id="my_thread_id",
            limit=5,
            offset=5,
        )
        print(cron_jobs)

        ----------------------------------------------------------

        [
            {
                'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
                'assistant_id': 'my_assistant_id',
                'thread_id': 'my_thread_id',
                'user_id': None,
                'payload':
                    {
                        'input': {'start_time': ''},
                        'schedule': '4 * * * *',
                        'assistant_id': 'my_assistant_id'
                    },
                'schedule': '4 * * * *',
                'next_run_date': '2024-07-25T17:04:00+00:00',
                'end_time': None,
                'created_at': '2024-07-08T06:02:23.073257+00:00',
                'updated_at': '2024-07-08T06:02:23.073257+00:00'
            }
        ]

    """  # noqa: E501
    payload = {
        "assistant_id": assistant_id,
        "thread_id": thread_id,
        "limit": limit,
        "offset": offset,
    }
    payload = {k: v for k, v in payload.items() if v is not None}
    return await self.http.post("/runs/crons/search", json=payload)

StoreClient

Client for interacting with the graph's shared storage.

The Store provides a key-value storage system for persisting data across graph executions, allowing for stateful operations and data sharing across threads.

Example:

client = get_client()
await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})
Source code in libs/sdk-py/langgraph_sdk/client.py
class StoreClient:
    """Client for interacting with the graph's shared storage.

    The Store provides a key-value storage system for persisting data across graph executions,
    allowing for stateful operations and data sharing across threads.

    Example:

        client = get_client()
        await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})
    """

    def __init__(self, http: HttpClient) -> None:
        self.http = http

    async def put_item(
        self, namespace: Sequence[str], /, key: str, value: dict[str, Any]
    ) -> None:
        """Store or update an item.

        Args:
            namespace: A list of strings representing the namespace path.
            key: The unique identifier for the item within the namespace.
            value: A dictionary containing the item's data.

        Returns:
            None

        Example Usage:

            await client.store.put_item(
                ["documents", "user123"],
                key="item456",
                value={"title": "My Document", "content": "Hello World"}
            )
        """
        for label in namespace:
            if "." in label:
                raise ValueError(
                    f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
                )
        payload = {
            "namespace": namespace,
            "key": key,
            "value": value,
        }
        await self.http.put("/store/items", json=payload)

    async def get_item(self, namespace: Sequence[str], /, key: str) -> Item:
        """Retrieve a single item.

        Args:
            key: The unique identifier for the item.
            namespace: Optional list of strings representing the namespace path.

        Returns:
            Item: The retrieved item.

        Example Usage:

            item = await client.store.get_item(
                ["documents", "user123"],
                key="item456",
            )
            print(item)

            ----------------------------------------------------------------

            {
                'namespace': ['documents', 'user123'],
                'key': 'item456',
                'value': {'title': 'My Document', 'content': 'Hello World'},
                'created_at': '2024-07-30T12:00:00Z',
                'updated_at': '2024-07-30T12:00:00Z'
            }
        """
        for label in namespace:
            if "." in label:
                raise ValueError(
                    f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
                )
        return await self.http.get(
            "/store/items", params={"namespace": ".".join(namespace), "key": key}
        )

    async def delete_item(self, namespace: Sequence[str], /, key: str) -> None:
        """Delete an item.

        Args:
            key: The unique identifier for the item.
            namespace: Optional list of strings representing the namespace path.

        Returns:
            None

        Example Usage:

            await client.store.delete_item(
                ["documents", "user123"],
                key="item456",
            )
        """
        await self.http.delete(
            "/store/items", json={"namespace": namespace, "key": key}
        )

    async def search_items(
        self,
        namespace_prefix: Sequence[str],
        /,
        filter: Optional[dict[str, Any]] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> SearchItemsResponse:
        """Search for items within a namespace prefix.

        Args:
            namespace_prefix: List of strings representing the namespace prefix.
            filter: Optional dictionary of key-value pairs to filter results.
            limit: Maximum number of items to return (default is 10).
            offset: Number of items to skip before returning results (default is 0).

        Returns:
            List[Item]: A list of items matching the search criteria.

        Example Usage:

            items = await client.store.search_items(
                ["documents"],
                filter={"author": "John Doe"},
                limit=5,
                offset=0
            )
            print(items)

            ----------------------------------------------------------------

            {
                "items": [
                    {
                        "namespace": ["documents", "user123"],
                        "key": "item789",
                        "value": {
                            "title": "Another Document",
                            "author": "John Doe"
                        },
                        "created_at": "2024-07-30T12:00:00Z",
                        "updated_at": "2024-07-30T12:00:00Z"
                    },
                    # ... additional items ...
                ]
            }
        """
        payload = {
            "namespace_prefix": namespace_prefix,
            "filter": filter,
            "limit": limit,
            "offset": offset,
        }

        return await self.http.post("/store/items/search", json=_provided_vals(payload))

    async def list_namespaces(
        self,
        prefix: Optional[List[str]] = None,
        suffix: Optional[List[str]] = None,
        max_depth: Optional[int] = None,
        limit: int = 100,
        offset: int = 0,
    ) -> ListNamespaceResponse:
        """List namespaces with optional match conditions.

        Args:
            prefix: Optional list of strings representing the prefix to filter namespaces.
            suffix: Optional list of strings representing the suffix to filter namespaces.
            max_depth: Optional integer specifying the maximum depth of namespaces to return.
            limit: Maximum number of namespaces to return (default is 100).
            offset: Number of namespaces to skip before returning results (default is 0).

        Returns:
            List[List[str]]: A list of namespaces matching the criteria.

        Example Usage:

            namespaces = await client.store.list_namespaces(
                prefix=["documents"],
                max_depth=3,
                limit=10,
                offset=0
            )
            print(namespaces)

            ----------------------------------------------------------------

            [
                ["documents", "user123", "reports"],
                ["documents", "user456", "invoices"],
                ...
            ]
        """
        payload = {
            "prefix": prefix,
            "suffix": suffix,
            "max_depth": max_depth,
            "limit": limit,
            "offset": offset,
        }
        return await self.http.post("/store/namespaces", json=_provided_vals(payload))

put_item(namespace: Sequence[str], /, key: str, value: dict[str, Any]) -> None async

Store or update an item.

Parameters:

  • namespace (Sequence[str]) –

    A list of strings representing the namespace path.

  • key (str) –

    The unique identifier for the item within the namespace.

  • value (dict[str, Any]) –

    A dictionary containing the item's data.

Returns:

  • None

    None

Example Usage:

await client.store.put_item(
    ["documents", "user123"],
    key="item456",
    value={"title": "My Document", "content": "Hello World"}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def put_item(
    self, namespace: Sequence[str], /, key: str, value: dict[str, Any]
) -> None:
    """Store or update an item.

    Args:
        namespace: A list of strings representing the namespace path.
        key: The unique identifier for the item within the namespace.
        value: A dictionary containing the item's data.

    Returns:
        None

    Example Usage:

        await client.store.put_item(
            ["documents", "user123"],
            key="item456",
            value={"title": "My Document", "content": "Hello World"}
        )
    """
    for label in namespace:
        if "." in label:
            raise ValueError(
                f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
            )
    payload = {
        "namespace": namespace,
        "key": key,
        "value": value,
    }
    await self.http.put("/store/items", json=payload)

get_item(namespace: Sequence[str], /, key: str) -> Item async

Retrieve a single item.

Parameters:

  • key (str) –

    The unique identifier for the item.

  • namespace (Sequence[str]) –

    Optional list of strings representing the namespace path.

Returns:

  • Item ( Item ) –

    The retrieved item.

Example Usage:

item = await client.store.get_item(
    ["documents", "user123"],
    key="item456",
)
print(item)

----------------------------------------------------------------

{
    'namespace': ['documents', 'user123'],
    'key': 'item456',
    'value': {'title': 'My Document', 'content': 'Hello World'},
    'created_at': '2024-07-30T12:00:00Z',
    'updated_at': '2024-07-30T12:00:00Z'
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def get_item(self, namespace: Sequence[str], /, key: str) -> Item:
    """Retrieve a single item.

    Args:
        key: The unique identifier for the item.
        namespace: Optional list of strings representing the namespace path.

    Returns:
        Item: The retrieved item.

    Example Usage:

        item = await client.store.get_item(
            ["documents", "user123"],
            key="item456",
        )
        print(item)

        ----------------------------------------------------------------

        {
            'namespace': ['documents', 'user123'],
            'key': 'item456',
            'value': {'title': 'My Document', 'content': 'Hello World'},
            'created_at': '2024-07-30T12:00:00Z',
            'updated_at': '2024-07-30T12:00:00Z'
        }
    """
    for label in namespace:
        if "." in label:
            raise ValueError(
                f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
            )
    return await self.http.get(
        "/store/items", params={"namespace": ".".join(namespace), "key": key}
    )

delete_item(namespace: Sequence[str], /, key: str) -> None async

Delete an item.

Parameters:

  • key (str) –

    The unique identifier for the item.

  • namespace (Sequence[str]) –

    Optional list of strings representing the namespace path.

Returns:

  • None

    None

Example Usage:

await client.store.delete_item(
    ["documents", "user123"],
    key="item456",
)
Source code in libs/sdk-py/langgraph_sdk/client.py
async def delete_item(self, namespace: Sequence[str], /, key: str) -> None:
    """Delete an item.

    Args:
        key: The unique identifier for the item.
        namespace: Optional list of strings representing the namespace path.

    Returns:
        None

    Example Usage:

        await client.store.delete_item(
            ["documents", "user123"],
            key="item456",
        )
    """
    await self.http.delete(
        "/store/items", json={"namespace": namespace, "key": key}
    )

search_items(namespace_prefix: Sequence[str], /, filter: Optional[dict[str, Any]] = None, limit: int = 10, offset: int = 0) -> SearchItemsResponse async

Search for items within a namespace prefix.

Parameters:

  • namespace_prefix (Sequence[str]) –

    List of strings representing the namespace prefix.

  • filter (Optional[dict[str, Any]], default: None ) –

    Optional dictionary of key-value pairs to filter results.

  • limit (int, default: 10 ) –

    Maximum number of items to return (default is 10).

  • offset (int, default: 0 ) –

    Number of items to skip before returning results (default is 0).

Returns:

  • SearchItemsResponse

    List[Item]: A list of items matching the search criteria.

Example Usage:

items = await client.store.search_items(
    ["documents"],
    filter={"author": "John Doe"},
    limit=5,
    offset=0
)
print(items)

----------------------------------------------------------------

{
    "items": [
        {
            "namespace": ["documents", "user123"],
            "key": "item789",
            "value": {
                "title": "Another Document",
                "author": "John Doe"
            },
            "created_at": "2024-07-30T12:00:00Z",
            "updated_at": "2024-07-30T12:00:00Z"
        },
        # ... additional items ...
    ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
async def search_items(
    self,
    namespace_prefix: Sequence[str],
    /,
    filter: Optional[dict[str, Any]] = None,
    limit: int = 10,
    offset: int = 0,
) -> SearchItemsResponse:
    """Search for items within a namespace prefix.

    Args:
        namespace_prefix: List of strings representing the namespace prefix.
        filter: Optional dictionary of key-value pairs to filter results.
        limit: Maximum number of items to return (default is 10).
        offset: Number of items to skip before returning results (default is 0).

    Returns:
        List[Item]: A list of items matching the search criteria.

    Example Usage:

        items = await client.store.search_items(
            ["documents"],
            filter={"author": "John Doe"},
            limit=5,
            offset=0
        )
        print(items)

        ----------------------------------------------------------------

        {
            "items": [
                {
                    "namespace": ["documents", "user123"],
                    "key": "item789",
                    "value": {
                        "title": "Another Document",
                        "author": "John Doe"
                    },
                    "created_at": "2024-07-30T12:00:00Z",
                    "updated_at": "2024-07-30T12:00:00Z"
                },
                # ... additional items ...
            ]
        }
    """
    payload = {
        "namespace_prefix": namespace_prefix,
        "filter": filter,
        "limit": limit,
        "offset": offset,
    }

    return await self.http.post("/store/items/search", json=_provided_vals(payload))

list_namespaces(prefix: Optional[List[str]] = None, suffix: Optional[List[str]] = None, max_depth: Optional[int] = None, limit: int = 100, offset: int = 0) -> ListNamespaceResponse async

List namespaces with optional match conditions.

Parameters:

  • prefix (Optional[List[str]], default: None ) –

    Optional list of strings representing the prefix to filter namespaces.

  • suffix (Optional[List[str]], default: None ) –

    Optional list of strings representing the suffix to filter namespaces.

  • max_depth (Optional[int], default: None ) –

    Optional integer specifying the maximum depth of namespaces to return.

  • limit (int, default: 100 ) –

    Maximum number of namespaces to return (default is 100).

  • offset (int, default: 0 ) –

    Number of namespaces to skip before returning results (default is 0).

Returns:

  • ListNamespaceResponse

    List[List[str]]: A list of namespaces matching the criteria.

Example Usage:

namespaces = await client.store.list_namespaces(
    prefix=["documents"],
    max_depth=3,
    limit=10,
    offset=0
)
print(namespaces)

----------------------------------------------------------------

[
    ["documents", "user123", "reports"],
    ["documents", "user456", "invoices"],
    ...
]
Source code in libs/sdk-py/langgraph_sdk/client.py
async def list_namespaces(
    self,
    prefix: Optional[List[str]] = None,
    suffix: Optional[List[str]] = None,
    max_depth: Optional[int] = None,
    limit: int = 100,
    offset: int = 0,
) -> ListNamespaceResponse:
    """List namespaces with optional match conditions.

    Args:
        prefix: Optional list of strings representing the prefix to filter namespaces.
        suffix: Optional list of strings representing the suffix to filter namespaces.
        max_depth: Optional integer specifying the maximum depth of namespaces to return.
        limit: Maximum number of namespaces to return (default is 100).
        offset: Number of namespaces to skip before returning results (default is 0).

    Returns:
        List[List[str]]: A list of namespaces matching the criteria.

    Example Usage:

        namespaces = await client.store.list_namespaces(
            prefix=["documents"],
            max_depth=3,
            limit=10,
            offset=0
        )
        print(namespaces)

        ----------------------------------------------------------------

        [
            ["documents", "user123", "reports"],
            ["documents", "user456", "invoices"],
            ...
        ]
    """
    payload = {
        "prefix": prefix,
        "suffix": suffix,
        "max_depth": max_depth,
        "limit": limit,
        "offset": offset,
    }
    return await self.http.post("/store/namespaces", json=_provided_vals(payload))

SyncLangGraphClient

Synchronous client for interacting with the LangGraph API.

This class provides synchronous access to LangGraph API endpoints for managing assistants, threads, runs, cron jobs, and data storage.

Example:

client = get_sync_client()
assistant = client.assistants.get("asst_123")
Source code in libs/sdk-py/langgraph_sdk/client.py
class SyncLangGraphClient:
    """Synchronous client for interacting with the LangGraph API.

    This class provides synchronous access to LangGraph API endpoints for managing
    assistants, threads, runs, cron jobs, and data storage.

    Example:

        client = get_sync_client()
        assistant = client.assistants.get("asst_123")
    """

    def __init__(self, client: httpx.Client) -> None:
        self.http = SyncHttpClient(client)
        self.assistants = SyncAssistantsClient(self.http)
        self.threads = SyncThreadsClient(self.http)
        self.runs = SyncRunsClient(self.http)
        self.crons = SyncCronClient(self.http)
        self.store = SyncStoreClient(self.http)

SyncHttpClient

Source code in libs/sdk-py/langgraph_sdk/client.py
class SyncHttpClient:
    def __init__(self, client: httpx.Client) -> None:
        self.client = client

    def get(self, path: str, *, params: Optional[QueryParamTypes] = None) -> Any:
        """Send a GET request."""
        r = self.client.get(path, params=params)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = r.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return decode_json(r)

    def post(self, path: str, *, json: Optional[dict]) -> Any:
        """Send a POST request."""
        if json is not None:
            headers, content = encode_json(json)
        else:
            headers, content = {}, b""
        r = self.client.post(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = r.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return decode_json(r)

    def put(self, path: str, *, json: dict) -> Any:
        """Send a PUT request."""
        headers, content = encode_json(json)
        r = self.client.put(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = r.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return decode_json(r)

    def patch(self, path: str, *, json: dict) -> Any:
        """Send a PATCH request."""
        headers, content = encode_json(json)
        r = self.client.patch(path, headers=headers, content=content)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = r.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        return decode_json(r)

    def delete(self, path: str, *, json: Optional[Any] = None) -> None:
        """Send a DELETE request."""
        r = self.client.request("DELETE", path, json=json)
        try:
            r.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = r.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e

    def stream(
        self, path: str, method: str, *, json: Optional[dict] = None
    ) -> Iterator[StreamPart]:
        """Stream the results of a request using SSE."""
        headers, content = encode_json(json)
        with httpx_sse.connect_sse(
            self.client, method, path, headers=headers, content=content
        ) as sse:
            try:
                sse.response.raise_for_status()
            except httpx.HTTPStatusError as e:
                body = sse.response.read().decode()
                if sys.version_info >= (3, 11):
                    e.add_note(body)
                else:
                    logger.error(f"Error from langgraph-api: {body}", exc_info=e)
                raise e
            for event in sse.iter_sse():
                yield StreamPart(
                    event.event, orjson.loads(event.data) if event.data else None
                )

get(path: str, *, params: Optional[QueryParamTypes] = None) -> Any

Send a GET request.

Source code in libs/sdk-py/langgraph_sdk/client.py
def get(self, path: str, *, params: Optional[QueryParamTypes] = None) -> Any:
    """Send a GET request."""
    r = self.client.get(path, params=params)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = r.read().decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return decode_json(r)

post(path: str, *, json: Optional[dict]) -> Any

Send a POST request.

Source code in libs/sdk-py/langgraph_sdk/client.py
def post(self, path: str, *, json: Optional[dict]) -> Any:
    """Send a POST request."""
    if json is not None:
        headers, content = encode_json(json)
    else:
        headers, content = {}, b""
    r = self.client.post(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = r.read().decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return decode_json(r)

put(path: str, *, json: dict) -> Any

Send a PUT request.

Source code in libs/sdk-py/langgraph_sdk/client.py
def put(self, path: str, *, json: dict) -> Any:
    """Send a PUT request."""
    headers, content = encode_json(json)
    r = self.client.put(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = r.read().decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return decode_json(r)

patch(path: str, *, json: dict) -> Any

Send a PATCH request.

Source code in libs/sdk-py/langgraph_sdk/client.py
def patch(self, path: str, *, json: dict) -> Any:
    """Send a PATCH request."""
    headers, content = encode_json(json)
    r = self.client.patch(path, headers=headers, content=content)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = r.read().decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e
    return decode_json(r)

delete(path: str, *, json: Optional[Any] = None) -> None

Send a DELETE request.

Source code in libs/sdk-py/langgraph_sdk/client.py
def delete(self, path: str, *, json: Optional[Any] = None) -> None:
    """Send a DELETE request."""
    r = self.client.request("DELETE", path, json=json)
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        body = r.read().decode()
        if sys.version_info >= (3, 11):
            e.add_note(body)
        else:
            logger.error(f"Error from langgraph-api: {body}", exc_info=e)
        raise e

stream(path: str, method: str, *, json: Optional[dict] = None) -> Iterator[StreamPart]

Stream the results of a request using SSE.

Source code in libs/sdk-py/langgraph_sdk/client.py
def stream(
    self, path: str, method: str, *, json: Optional[dict] = None
) -> Iterator[StreamPart]:
    """Stream the results of a request using SSE."""
    headers, content = encode_json(json)
    with httpx_sse.connect_sse(
        self.client, method, path, headers=headers, content=content
    ) as sse:
        try:
            sse.response.raise_for_status()
        except httpx.HTTPStatusError as e:
            body = sse.response.read().decode()
            if sys.version_info >= (3, 11):
                e.add_note(body)
            else:
                logger.error(f"Error from langgraph-api: {body}", exc_info=e)
            raise e
        for event in sse.iter_sse():
            yield StreamPart(
                event.event, orjson.loads(event.data) if event.data else None
            )

SyncAssistantsClient

Client for managing assistants in LangGraph synchronously.

This class provides methods to interact with assistants, which are versioned configurations of your graph.

Example:

client = get_client()
assistant = client.assistants.get("assistant_id_123")
Source code in libs/sdk-py/langgraph_sdk/client.py
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
class SyncAssistantsClient:
    """Client for managing assistants in LangGraph synchronously.

    This class provides methods to interact with assistants, which are versioned configurations of your graph.

    Example:

        client = get_client()
        assistant = client.assistants.get("assistant_id_123")
    """

    def __init__(self, http: SyncHttpClient) -> None:
        self.http = http

    def get(self, assistant_id: str) -> Assistant:
        """Get an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get.

        Returns:
            Assistant: Assistant Object.

        Example Usage:

            assistant = client.assistants.get(
                assistant_id="my_assistant_id"
            )
            print(assistant)

            ----------------------------------------------------

            {
                'assistant_id': 'my_assistant_id',
                'graph_id': 'agent',
                'created_at': '2024-06-25T17:10:33.109781+00:00',
                'updated_at': '2024-06-25T17:10:33.109781+00:00',
                'config': {},
                'metadata': {'created_by': 'system'}
            }

        """  # noqa: E501
        return self.http.get(f"/assistants/{assistant_id}")

    def get_graph(
        self, assistant_id: str, *, xray: Union[int, bool] = False
    ) -> dict[str, list[dict[str, Any]]]:
        """Get the graph of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the graph of.
            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.

        Returns:
            Graph: The graph information for the assistant in JSON format.

        Example Usage:

            graph_info = client.assistants.get_graph(
                assistant_id="my_assistant_id"
            )
            print(graph_info)

            --------------------------------------------------------------------------------------------------------------------------

            {
                'nodes':
                    [
                        {'id': '__start__', 'type': 'schema', 'data': '__start__'},
                        {'id': '__end__', 'type': 'schema', 'data': '__end__'},
                        {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
                    ],
                'edges':
                    [
                        {'source': '__start__', 'target': 'agent'},
                        {'source': 'agent','target': '__end__'}
                    ]
            }


        """  # noqa: E501
        return self.http.get(f"/assistants/{assistant_id}/graph", params={"xray": xray})

    def get_schemas(self, assistant_id: str) -> GraphSchema:
        """Get the schemas of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the schema of.

        Returns:
            GraphSchema: The graph schema for the assistant.

        Example Usage:

            schema = client.assistants.get_schemas(
                assistant_id="my_assistant_id"
            )
            print(schema)

            ----------------------------------------------------------------------------------------------------------------------------

            {
                'graph_id': 'agent',
                'state_schema':
                    {
                        'title': 'LangGraphInput',
                        '$ref': '#/definitions/AgentState',
                        'definitions':
                            {
                                'BaseMessage':
                                    {
                                        'title': 'BaseMessage',
                                        'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                                        'type': 'object',
                                        'properties':
                                            {
                                             'content':
                                                {
                                                    'title': 'Content',
                                                    'anyOf': [
                                                        {'type': 'string'},
                                                        {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                                    ]
                                                },
                                            'additional_kwargs':
                                                {
                                                    'title': 'Additional Kwargs',
                                                    'type': 'object'
                                                },
                                            'response_metadata':
                                                {
                                                    'title': 'Response Metadata',
                                                    'type': 'object'
                                                },
                                            'type':
                                                {
                                                    'title': 'Type',
                                                    'type': 'string'
                                                },
                                            'name':
                                                {
                                                    'title': 'Name',
                                                    'type': 'string'
                                                },
                                            'id':
                                                {
                                                    'title': 'Id',
                                                    'type': 'string'
                                                }
                                            },
                                        'required': ['content', 'type']
                                    },
                                'AgentState':
                                    {
                                        'title': 'AgentState',
                                        'type': 'object',
                                        'properties':
                                            {
                                                'messages':
                                                    {
                                                        'title': 'Messages',
                                                        'type': 'array',
                                                        'items': {'$ref': '#/definitions/BaseMessage'}
                                                    }
                                            },
                                        'required': ['messages']
                                    }
                            }
                    },
                'config_schema':
                    {
                        'title': 'Configurable',
                        'type': 'object',
                        'properties':
                            {
                                'model_name':
                                    {
                                        'title': 'Model Name',
                                        'enum': ['anthropic', 'openai'],
                                        'type': 'string'
                                    }
                            }
                    }
            }

        """  # noqa: E501
        return self.http.get(f"/assistants/{assistant_id}/schemas")

    def get_subgraphs(
        self, assistant_id: str, namespace: Optional[str] = None, recurse: bool = False
    ) -> Subgraphs:
        """Get the schemas of an assistant by ID.

        Args:
            assistant_id: The ID of the assistant to get the schema of.

        Returns:
            Subgraphs: The graph schema for the assistant.

        """  # noqa: E501
        if namespace is not None:
            return self.http.get(
                f"/assistants/{assistant_id}/subgraphs/{namespace}",
                params={"recurse": recurse},
            )
        else:
            return self.http.get(
                f"/assistants/{assistant_id}/subgraphs",
                params={"recurse": recurse},
            )

    def create(
        self,
        graph_id: Optional[str],
        config: Optional[Config] = None,
        *,
        metadata: Json = None,
        assistant_id: Optional[str] = None,
        if_exists: Optional[OnConflictBehavior] = None,
        name: Optional[str] = None,
    ) -> Assistant:
        """Create a new assistant.

        Useful when graph is configurable and you want to create different assistants based on different configurations.

        Args:
            graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
            config: Configuration to use for the graph.
            metadata: Metadata to add to assistant.
            assistant_id: Assistant ID to use, will default to a random UUID if not provided.
            if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
                Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
            name: The name of the assistant. Defaults to 'Untitled' under the hood.

        Returns:
            Assistant: The created assistant.

        Example Usage:

            assistant = client.assistants.create(
                graph_id="agent",
                config={"configurable": {"model_name": "openai"}},
                metadata={"number":1},
                assistant_id="my-assistant-id",
                if_exists="do_nothing",
                name="my_name"
            )
        """  # noqa: E501
        payload: Dict[str, Any] = {
            "graph_id": graph_id,
        }
        if config:
            payload["config"] = config
        if metadata:
            payload["metadata"] = metadata
        if assistant_id:
            payload["assistant_id"] = assistant_id
        if if_exists:
            payload["if_exists"] = if_exists
        if name:
            payload["name"] = name
        return self.http.post("/assistants", json=payload)

    def update(
        self,
        assistant_id: str,
        *,
        graph_id: Optional[str] = None,
        config: Optional[Config] = None,
        metadata: Json = None,
        name: Optional[str] = None,
    ) -> Assistant:
        """Update an assistant.

        Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

        Args:
            assistant_id: Assistant to update.
            graph_id: The ID of the graph the assistant should use.
                The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.
            config: Configuration to use for the graph.
            metadata: Metadata to merge with existing assistant metadata.
            name: The new name for the assistant.

        Returns:
            Assistant: The updated assistant.

        Example Usage:

            assistant = client.assistants.update(
                assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
                graph_id="other-graph",
                config={"configurable": {"model_name": "anthropic"}},
                metadata={"number":2}
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {}
        if graph_id:
            payload["graph_id"] = graph_id
        if config:
            payload["config"] = config
        if metadata:
            payload["metadata"] = metadata
        if name:
            payload["name"] = name
        return self.http.patch(
            f"/assistants/{assistant_id}",
            json=payload,
        )

    def delete(
        self,
        assistant_id: str,
    ) -> None:
        """Delete an assistant.

        Args:
            assistant_id: The assistant ID to delete.

        Returns:
            None

        Example Usage:

            client.assistants.delete(
                assistant_id="my_assistant_id"
            )

        """  # noqa: E501
        self.http.delete(f"/assistants/{assistant_id}")

    def search(
        self,
        *,
        metadata: Json = None,
        graph_id: Optional[str] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Assistant]:
        """Search for assistants.

        Args:
            metadata: Metadata to filter by. Exact match filter for each KV pair.
            graph_id: The ID of the graph to filter by.
                The graph ID is normally set in your langgraph.json configuration.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            list[Assistant]: A list of assistants.

        Example Usage:

            assistants = client.assistants.search(
                metadata = {"name":"my_name"},
                graph_id="my_graph_id",
                limit=5,
                offset=5
            )
        """
        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        if graph_id:
            payload["graph_id"] = graph_id
        return self.http.post(
            "/assistants/search",
            json=payload,
        )

    def get_versions(
        self,
        assistant_id: str,
        metadata: Json = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[AssistantVersion]:
        """List all versions of an assistant.

        Args:
            assistant_id: The assistant ID to get versions for.
            metadata: Metadata to filter versions by. Exact match filter for each KV pair.
            limit: The maximum number of versions to return.
            offset: The number of versions to skip.

        Returns:
            list[Assistant]: A list of assistants.

        Example Usage:

            assistant_versions = await client.assistants.get_versions(
                assistant_id="my_assistant_id"
            )

        """  # noqa: E501

        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        return self.http.post(f"/assistants/{assistant_id}/versions", json=payload)

    def set_latest(self, assistant_id: str, version: int) -> Assistant:
        """Change the version of an assistant.

        Args:
            assistant_id: The assistant ID to delete.
            version: The version to change to.

        Returns:
            Assistant: Assistant Object.

        Example Usage:

            new_version_assistant = await client.assistants.set_latest(
                assistant_id="my_assistant_id",
                version=3
            )

        """  # noqa: E501

        payload: Dict[str, Any] = {"version": version}

        return self.http.post(f"/assistants/{assistant_id}/latest", json=payload)

get(assistant_id: str) -> Assistant

Get an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get.

Returns:

  • Assistant ( Assistant ) –

    Assistant Object.

Example Usage:

assistant = client.assistants.get(
    assistant_id="my_assistant_id"
)
print(assistant)

----------------------------------------------------

{
    'assistant_id': 'my_assistant_id',
    'graph_id': 'agent',
    'created_at': '2024-06-25T17:10:33.109781+00:00',
    'updated_at': '2024-06-25T17:10:33.109781+00:00',
    'config': {},
    'metadata': {'created_by': 'system'}
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get(self, assistant_id: str) -> Assistant:
    """Get an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get.

    Returns:
        Assistant: Assistant Object.

    Example Usage:

        assistant = client.assistants.get(
            assistant_id="my_assistant_id"
        )
        print(assistant)

        ----------------------------------------------------

        {
            'assistant_id': 'my_assistant_id',
            'graph_id': 'agent',
            'created_at': '2024-06-25T17:10:33.109781+00:00',
            'updated_at': '2024-06-25T17:10:33.109781+00:00',
            'config': {},
            'metadata': {'created_by': 'system'}
        }

    """  # noqa: E501
    return self.http.get(f"/assistants/{assistant_id}")

get_graph(assistant_id: str, *, xray: Union[int, bool] = False) -> dict[str, list[dict[str, Any]]]

Get the graph of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the graph of.

  • xray (Union[int, bool], default: False ) –

    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.

Returns:

  • Graph ( dict[str, list[dict[str, Any]]] ) –

    The graph information for the assistant in JSON format.

Example Usage:

graph_info = client.assistants.get_graph(
    assistant_id="my_assistant_id"
)
print(graph_info)

--------------------------------------------------------------------------------------------------------------------------

{
    'nodes':
        [
            {'id': '__start__', 'type': 'schema', 'data': '__start__'},
            {'id': '__end__', 'type': 'schema', 'data': '__end__'},
            {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
        ],
    'edges':
        [
            {'source': '__start__', 'target': 'agent'},
            {'source': 'agent','target': '__end__'}
        ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_graph(
    self, assistant_id: str, *, xray: Union[int, bool] = False
) -> dict[str, list[dict[str, Any]]]:
    """Get the graph of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the graph of.
        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.

    Returns:
        Graph: The graph information for the assistant in JSON format.

    Example Usage:

        graph_info = client.assistants.get_graph(
            assistant_id="my_assistant_id"
        )
        print(graph_info)

        --------------------------------------------------------------------------------------------------------------------------

        {
            'nodes':
                [
                    {'id': '__start__', 'type': 'schema', 'data': '__start__'},
                    {'id': '__end__', 'type': 'schema', 'data': '__end__'},
                    {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
                ],
            'edges':
                [
                    {'source': '__start__', 'target': 'agent'},
                    {'source': 'agent','target': '__end__'}
                ]
        }


    """  # noqa: E501
    return self.http.get(f"/assistants/{assistant_id}/graph", params={"xray": xray})

get_schemas(assistant_id: str) -> GraphSchema

Get the schemas of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the schema of.

Returns:

  • GraphSchema ( GraphSchema ) –

    The graph schema for the assistant.

Example Usage:

schema = client.assistants.get_schemas(
    assistant_id="my_assistant_id"
)
print(schema)

----------------------------------------------------------------------------------------------------------------------------

{
    'graph_id': 'agent',
    'state_schema':
        {
            'title': 'LangGraphInput',
            '$ref': '#/definitions/AgentState',
            'definitions':
                {
                    'BaseMessage':
                        {
                            'title': 'BaseMessage',
                            'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                            'type': 'object',
                            'properties':
                                {
                                 'content':
                                    {
                                        'title': 'Content',
                                        'anyOf': [
                                            {'type': 'string'},
                                            {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                        ]
                                    },
                                'additional_kwargs':
                                    {
                                        'title': 'Additional Kwargs',
                                        'type': 'object'
                                    },
                                'response_metadata':
                                    {
                                        'title': 'Response Metadata',
                                        'type': 'object'
                                    },
                                'type':
                                    {
                                        'title': 'Type',
                                        'type': 'string'
                                    },
                                'name':
                                    {
                                        'title': 'Name',
                                        'type': 'string'
                                    },
                                'id':
                                    {
                                        'title': 'Id',
                                        'type': 'string'
                                    }
                                },
                            'required': ['content', 'type']
                        },
                    'AgentState':
                        {
                            'title': 'AgentState',
                            'type': 'object',
                            'properties':
                                {
                                    'messages':
                                        {
                                            'title': 'Messages',
                                            'type': 'array',
                                            'items': {'$ref': '#/definitions/BaseMessage'}
                                        }
                                },
                            'required': ['messages']
                        }
                }
        },
    'config_schema':
        {
            'title': 'Configurable',
            'type': 'object',
            'properties':
                {
                    'model_name':
                        {
                            'title': 'Model Name',
                            'enum': ['anthropic', 'openai'],
                            'type': 'string'
                        }
                }
        }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_schemas(self, assistant_id: str) -> GraphSchema:
    """Get the schemas of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the schema of.

    Returns:
        GraphSchema: The graph schema for the assistant.

    Example Usage:

        schema = client.assistants.get_schemas(
            assistant_id="my_assistant_id"
        )
        print(schema)

        ----------------------------------------------------------------------------------------------------------------------------

        {
            'graph_id': 'agent',
            'state_schema':
                {
                    'title': 'LangGraphInput',
                    '$ref': '#/definitions/AgentState',
                    'definitions':
                        {
                            'BaseMessage':
                                {
                                    'title': 'BaseMessage',
                                    'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                                    'type': 'object',
                                    'properties':
                                        {
                                         'content':
                                            {
                                                'title': 'Content',
                                                'anyOf': [
                                                    {'type': 'string'},
                                                    {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                                ]
                                            },
                                        'additional_kwargs':
                                            {
                                                'title': 'Additional Kwargs',
                                                'type': 'object'
                                            },
                                        'response_metadata':
                                            {
                                                'title': 'Response Metadata',
                                                'type': 'object'
                                            },
                                        'type':
                                            {
                                                'title': 'Type',
                                                'type': 'string'
                                            },
                                        'name':
                                            {
                                                'title': 'Name',
                                                'type': 'string'
                                            },
                                        'id':
                                            {
                                                'title': 'Id',
                                                'type': 'string'
                                            }
                                        },
                                    'required': ['content', 'type']
                                },
                            'AgentState':
                                {
                                    'title': 'AgentState',
                                    'type': 'object',
                                    'properties':
                                        {
                                            'messages':
                                                {
                                                    'title': 'Messages',
                                                    'type': 'array',
                                                    'items': {'$ref': '#/definitions/BaseMessage'}
                                                }
                                        },
                                    'required': ['messages']
                                }
                        }
                },
            'config_schema':
                {
                    'title': 'Configurable',
                    'type': 'object',
                    'properties':
                        {
                            'model_name':
                                {
                                    'title': 'Model Name',
                                    'enum': ['anthropic', 'openai'],
                                    'type': 'string'
                                }
                        }
                }
        }

    """  # noqa: E501
    return self.http.get(f"/assistants/{assistant_id}/schemas")

get_subgraphs(assistant_id: str, namespace: Optional[str] = None, recurse: bool = False) -> Subgraphs

Get the schemas of an assistant by ID.

Parameters:

  • assistant_id (str) –

    The ID of the assistant to get the schema of.

Returns:

  • Subgraphs ( Subgraphs ) –

    The graph schema for the assistant.

Source code in libs/sdk-py/langgraph_sdk/client.py
def get_subgraphs(
    self, assistant_id: str, namespace: Optional[str] = None, recurse: bool = False
) -> Subgraphs:
    """Get the schemas of an assistant by ID.

    Args:
        assistant_id: The ID of the assistant to get the schema of.

    Returns:
        Subgraphs: The graph schema for the assistant.

    """  # noqa: E501
    if namespace is not None:
        return self.http.get(
            f"/assistants/{assistant_id}/subgraphs/{namespace}",
            params={"recurse": recurse},
        )
    else:
        return self.http.get(
            f"/assistants/{assistant_id}/subgraphs",
            params={"recurse": recurse},
        )

create(graph_id: Optional[str], config: Optional[Config] = None, *, metadata: Json = None, assistant_id: Optional[str] = None, if_exists: Optional[OnConflictBehavior] = None, name: Optional[str] = None) -> Assistant

Create a new assistant.

Useful when graph is configurable and you want to create different assistants based on different configurations.

Parameters:

  • graph_id (Optional[str]) –

    The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.

  • config (Optional[Config], default: None ) –

    Configuration to use for the graph.

  • metadata (Json, default: None ) –

    Metadata to add to assistant.

  • assistant_id (Optional[str], default: None ) –

    Assistant ID to use, will default to a random UUID if not provided.

  • if_exists (Optional[OnConflictBehavior], default: None ) –

    How to handle duplicate creation. Defaults to 'raise' under the hood. Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).

  • name (Optional[str], default: None ) –

    The name of the assistant. Defaults to 'Untitled' under the hood.

Returns:

  • Assistant ( Assistant ) –

    The created assistant.

Example Usage:

assistant = client.assistants.create(
    graph_id="agent",
    config={"configurable": {"model_name": "openai"}},
    metadata={"number":1},
    assistant_id="my-assistant-id",
    if_exists="do_nothing",
    name="my_name"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def create(
    self,
    graph_id: Optional[str],
    config: Optional[Config] = None,
    *,
    metadata: Json = None,
    assistant_id: Optional[str] = None,
    if_exists: Optional[OnConflictBehavior] = None,
    name: Optional[str] = None,
) -> Assistant:
    """Create a new assistant.

    Useful when graph is configurable and you want to create different assistants based on different configurations.

    Args:
        graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
        config: Configuration to use for the graph.
        metadata: Metadata to add to assistant.
        assistant_id: Assistant ID to use, will default to a random UUID if not provided.
        if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
            Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
        name: The name of the assistant. Defaults to 'Untitled' under the hood.

    Returns:
        Assistant: The created assistant.

    Example Usage:

        assistant = client.assistants.create(
            graph_id="agent",
            config={"configurable": {"model_name": "openai"}},
            metadata={"number":1},
            assistant_id="my-assistant-id",
            if_exists="do_nothing",
            name="my_name"
        )
    """  # noqa: E501
    payload: Dict[str, Any] = {
        "graph_id": graph_id,
    }
    if config:
        payload["config"] = config
    if metadata:
        payload["metadata"] = metadata
    if assistant_id:
        payload["assistant_id"] = assistant_id
    if if_exists:
        payload["if_exists"] = if_exists
    if name:
        payload["name"] = name
    return self.http.post("/assistants", json=payload)

update(assistant_id: str, *, graph_id: Optional[str] = None, config: Optional[Config] = None, metadata: Json = None, name: Optional[str] = None) -> Assistant

Update an assistant.

Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

Parameters:

  • assistant_id (str) –

    Assistant to update.

  • graph_id (Optional[str], default: None ) –

    The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.

  • config (Optional[Config], default: None ) –

    Configuration to use for the graph.

  • metadata (Json, default: None ) –

    Metadata to merge with existing assistant metadata.

  • name (Optional[str], default: None ) –

    The new name for the assistant.

Returns:

  • Assistant ( Assistant ) –

    The updated assistant.

Example Usage:

assistant = client.assistants.update(
    assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
    graph_id="other-graph",
    config={"configurable": {"model_name": "anthropic"}},
    metadata={"number":2}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def update(
    self,
    assistant_id: str,
    *,
    graph_id: Optional[str] = None,
    config: Optional[Config] = None,
    metadata: Json = None,
    name: Optional[str] = None,
) -> Assistant:
    """Update an assistant.

    Use this to point to a different graph, update the configuration, or change the metadata of an assistant.

    Args:
        assistant_id: Assistant to update.
        graph_id: The ID of the graph the assistant should use.
            The graph ID is normally set in your langgraph.json configuration. If None, assistant will keep pointing to same graph.
        config: Configuration to use for the graph.
        metadata: Metadata to merge with existing assistant metadata.
        name: The new name for the assistant.

    Returns:
        Assistant: The updated assistant.

    Example Usage:

        assistant = client.assistants.update(
            assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
            graph_id="other-graph",
            config={"configurable": {"model_name": "anthropic"}},
            metadata={"number":2}
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {}
    if graph_id:
        payload["graph_id"] = graph_id
    if config:
        payload["config"] = config
    if metadata:
        payload["metadata"] = metadata
    if name:
        payload["name"] = name
    return self.http.patch(
        f"/assistants/{assistant_id}",
        json=payload,
    )

delete(assistant_id: str) -> None

Delete an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to delete.

Returns:

  • None

    None

Example Usage:

client.assistants.delete(
    assistant_id="my_assistant_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def delete(
    self,
    assistant_id: str,
) -> None:
    """Delete an assistant.

    Args:
        assistant_id: The assistant ID to delete.

    Returns:
        None

    Example Usage:

        client.assistants.delete(
            assistant_id="my_assistant_id"
        )

    """  # noqa: E501
    self.http.delete(f"/assistants/{assistant_id}")

search(*, metadata: Json = None, graph_id: Optional[str] = None, limit: int = 10, offset: int = 0) -> list[Assistant]

Search for assistants.

Parameters:

  • metadata (Json, default: None ) –

    Metadata to filter by. Exact match filter for each KV pair.

  • graph_id (Optional[str], default: None ) –

    The ID of the graph to filter by. The graph ID is normally set in your langgraph.json configuration.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • list[Assistant]

    list[Assistant]: A list of assistants.

Example Usage:

assistants = client.assistants.search(
    metadata = {"name":"my_name"},
    graph_id="my_graph_id",
    limit=5,
    offset=5
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def search(
    self,
    *,
    metadata: Json = None,
    graph_id: Optional[str] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Assistant]:
    """Search for assistants.

    Args:
        metadata: Metadata to filter by. Exact match filter for each KV pair.
        graph_id: The ID of the graph to filter by.
            The graph ID is normally set in your langgraph.json configuration.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        list[Assistant]: A list of assistants.

    Example Usage:

        assistants = client.assistants.search(
            metadata = {"name":"my_name"},
            graph_id="my_graph_id",
            limit=5,
            offset=5
        )
    """
    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    if graph_id:
        payload["graph_id"] = graph_id
    return self.http.post(
        "/assistants/search",
        json=payload,
    )

get_versions(assistant_id: str, metadata: Json = None, limit: int = 10, offset: int = 0) -> list[AssistantVersion]

List all versions of an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to get versions for.

  • metadata (Json, default: None ) –

    Metadata to filter versions by. Exact match filter for each KV pair.

  • limit (int, default: 10 ) –

    The maximum number of versions to return.

  • offset (int, default: 0 ) –

    The number of versions to skip.

Returns:

  • list[AssistantVersion]

    list[Assistant]: A list of assistants.

Example Usage:

assistant_versions = await client.assistants.get_versions(
    assistant_id="my_assistant_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_versions(
    self,
    assistant_id: str,
    metadata: Json = None,
    limit: int = 10,
    offset: int = 0,
) -> list[AssistantVersion]:
    """List all versions of an assistant.

    Args:
        assistant_id: The assistant ID to get versions for.
        metadata: Metadata to filter versions by. Exact match filter for each KV pair.
        limit: The maximum number of versions to return.
        offset: The number of versions to skip.

    Returns:
        list[Assistant]: A list of assistants.

    Example Usage:

        assistant_versions = await client.assistants.get_versions(
            assistant_id="my_assistant_id"
        )

    """  # noqa: E501

    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    return self.http.post(f"/assistants/{assistant_id}/versions", json=payload)

set_latest(assistant_id: str, version: int) -> Assistant

Change the version of an assistant.

Parameters:

  • assistant_id (str) –

    The assistant ID to delete.

  • version (int) –

    The version to change to.

Returns:

  • Assistant ( Assistant ) –

    Assistant Object.

Example Usage:

new_version_assistant = await client.assistants.set_latest(
    assistant_id="my_assistant_id",
    version=3
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def set_latest(self, assistant_id: str, version: int) -> Assistant:
    """Change the version of an assistant.

    Args:
        assistant_id: The assistant ID to delete.
        version: The version to change to.

    Returns:
        Assistant: Assistant Object.

    Example Usage:

        new_version_assistant = await client.assistants.set_latest(
            assistant_id="my_assistant_id",
            version=3
        )

    """  # noqa: E501

    payload: Dict[str, Any] = {"version": version}

    return self.http.post(f"/assistants/{assistant_id}/latest", json=payload)

SyncThreadsClient

Synchronous client for managing threads in LangGraph.

This class provides methods to create, retrieve, and manage threads, which represent conversations or stateful interactions.

Example:

client = get_sync_client()
thread = client.threads.create(metadata={"user_id": "123"})
Source code in libs/sdk-py/langgraph_sdk/client.py
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
class SyncThreadsClient:
    """Synchronous client for managing threads in LangGraph.

    This class provides methods to create, retrieve, and manage threads,
    which represent conversations or stateful interactions.

    Example:

        client = get_sync_client()
        thread = client.threads.create(metadata={"user_id": "123"})
    """

    def __init__(self, http: SyncHttpClient) -> None:
        self.http = http

    def get(self, thread_id: str) -> Thread:
        """Get a thread by ID.

        Args:
            thread_id: The ID of the thread to get.

        Returns:
            Thread: Thread object.

        Example Usage:

            thread = client.threads.get(
                thread_id="my_thread_id"
            )
            print(thread)

            -----------------------------------------------------

            {
                'thread_id': 'my_thread_id',
                'created_at': '2024-07-18T18:35:15.540834+00:00',
                'updated_at': '2024-07-18T18:35:15.540834+00:00',
                'metadata': {'graph_id': 'agent'}
            }

        """  # noqa: E501

        return self.http.get(f"/threads/{thread_id}")

    def create(
        self,
        *,
        metadata: Json = None,
        thread_id: Optional[str] = None,
        if_exists: Optional[OnConflictBehavior] = None,
    ) -> Thread:
        """Create a new thread.

        Args:
            metadata: Metadata to add to thread.
            thread_id: ID of thread.
                If None, ID will be a randomly generated UUID.
            if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
                Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

        Returns:
            Thread: The created thread.

        Example Usage:

            thread = client.threads.create(
                metadata={"number":1},
                thread_id="my-thread-id",
                if_exists="raise"
            )
        """  # noqa: E501
        payload: Dict[str, Any] = {}
        if thread_id:
            payload["thread_id"] = thread_id
        if metadata:
            payload["metadata"] = metadata
        if if_exists:
            payload["if_exists"] = if_exists
        return self.http.post("/threads", json=payload)

    def update(self, thread_id: str, *, metadata: dict[str, Any]) -> Thread:
        """Update a thread.

        Args:
            thread_id: ID of thread to update.
            metadata: Metadata to merge with existing thread metadata.

        Returns:
            Thread: The created thread.

        Example Usage:

            thread = client.threads.update(
                thread_id="my-thread-id",
                metadata={"number":1},
            )
        """  # noqa: E501
        return self.http.patch(f"/threads/{thread_id}", json={"metadata": metadata})

    def delete(self, thread_id: str) -> None:
        """Delete a thread.

        Args:
            thread_id: The ID of the thread to delete.

        Returns:
            None

        Example Usage:

            client.threads.delete(
                thread_id="my_thread_id"
            )

        """  # noqa: E501
        self.http.delete(f"/threads/{thread_id}")

    def search(
        self,
        *,
        metadata: Json = None,
        values: Json = None,
        status: Optional[ThreadStatus] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Thread]:
        """Search for threads.

        Args:
            metadata: Thread metadata to filter on.
            values: State values to filter on.
            status: Thread status to filter on.
                Must be one of 'idle', 'busy', 'interrupted' or 'error'.
            limit: Limit on number of threads to return.
            offset: Offset in threads table to start search from.

        Returns:
            list[Thread]: List of the threads matching the search parameters.

        Example Usage:

            threads = client.threads.search(
                metadata={"number":1},
                status="interrupted",
                limit=15,
                offset=5
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        if metadata:
            payload["metadata"] = metadata
        if values:
            payload["values"] = values
        if status:
            payload["status"] = status
        return self.http.post(
            "/threads/search",
            json=payload,
        )

    def copy(self, thread_id: str) -> None:
        """Copy a thread.

        Args:
            thread_id: The ID of the thread to copy.

        Returns:
            None

        Example Usage:

            client.threads.copy(
                thread_id="my_thread_id"
            )

        """  # noqa: E501
        return self.http.post(f"/threads/{thread_id}/copy", json=None)

    def get_state(
        self,
        thread_id: str,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,  # deprecated
        *,
        subgraphs: bool = False,
    ) -> ThreadState:
        """Get the state of a thread.

        Args:
            thread_id: The ID of the thread to get the state of.
            checkpoint: The checkpoint to get the state of.
            subgraphs: Include subgraphs states.

        Returns:
            ThreadState: the thread of the state.

        Example Usage:

            thread_state = client.threads.get_state(
                thread_id="my_thread_id",
                checkpoint_id="my_checkpoint_id"
            )
            print(thread_state)

            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'values': {
                    '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
                        }
                    ]
                },
                'next': [],
                'checkpoint':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
                    }
                'metadata':
                    {
                        'step': 1,
                        'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
                        'source': 'loop',
                        'writes':
                            {
                                'agent':
                                    {
                                        'messages': [
                                            {
                                                'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                                'name': None,
                                                'type': 'ai',
                                                'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                                'example': False,
                                                'tool_calls': [],
                                                'usage_metadata': None,
                                                'additional_kwargs': {},
                                                'response_metadata': {},
                                                'invalid_tool_calls': []
                                            }
                                        ]
                                    }
                            },
                'user_id': None,
                'graph_id': 'agent',
                'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                'created_by': 'system',
                'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
                'created_at': '2024-07-25T15:35:44.184703+00:00',
                'parent_config':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
                    }
            }

        """  # noqa: E501
        if checkpoint:
            return self.http.post(
                f"/threads/{thread_id}/state/checkpoint",
                json={"checkpoint": checkpoint, "subgraphs": subgraphs},
            )
        elif checkpoint_id:
            return self.http.get(
                f"/threads/{thread_id}/state/{checkpoint_id}",
                params={"subgraphs": subgraphs},
            )
        else:
            return self.http.get(
                f"/threads/{thread_id}/state",
                params={"subgraphs": subgraphs},
            )

    def update_state(
        self,
        thread_id: str,
        values: Optional[Union[dict, Sequence[dict]]],
        *,
        as_node: Optional[str] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,  # deprecated
    ) -> ThreadUpdateStateResponse:
        """Update the state of a thread.

        Args:
            thread_id: The ID of the thread to update.
            values: The values to update the state with.
            as_node: Update the state as if this node had just executed.
            checkpoint: The checkpoint to update the state of.

        Returns:
            ThreadUpdateStateResponse: Response after updating a thread's state.

        Example Usage:

            response = client.threads.update_state(
                thread_id="my_thread_id",
                values={"messages":[{"role": "user", "content": "hello!"}]},
                as_node="my_node",
            )
            print(response)

            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'checkpoint': {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
                    'checkpoint_map': {}
                }
            }

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "values": values,
        }
        if checkpoint_id:
            payload["checkpoint_id"] = checkpoint_id
        if checkpoint:
            payload["checkpoint"] = checkpoint
        if as_node:
            payload["as_node"] = as_node
        return self.http.post(f"/threads/{thread_id}/state", json=payload)

    def get_history(
        self,
        thread_id: str,
        *,
        limit: int = 10,
        before: Optional[str | Checkpoint] = None,
        metadata: Optional[dict] = None,
        checkpoint: Optional[Checkpoint] = None,
    ) -> list[ThreadState]:
        """Get the state history of a thread.

        Args:
            thread_id: The ID of the thread to get the state history for.
            checkpoint: Return states for this subgraph. If empty defaults to root.
            limit: The maximum number of states to return.
            before: Return states before this checkpoint.
            metadata: Filter states by metadata key-value pairs.

        Returns:
            list[ThreadState]: the state history of the thread.

        Example Usage:

            thread_state = client.threads.get_history(
                thread_id="my_thread_id",
                limit=5,
                before="my_timestamp",
                metadata={"name":"my_name"}
            )

        """  # noqa: E501
        payload: Dict[str, Any] = {
            "limit": limit,
        }
        if before:
            payload["before"] = before
        if metadata:
            payload["metadata"] = metadata
        if checkpoint:
            payload["checkpoint"] = checkpoint
        return self.http.post(f"/threads/{thread_id}/history", json=payload)

get(thread_id: str) -> Thread

Get a thread by ID.

Parameters:

  • thread_id (str) –

    The ID of the thread to get.

Returns:

  • Thread ( Thread ) –

    Thread object.

Example Usage:

thread = client.threads.get(
    thread_id="my_thread_id"
)
print(thread)

-----------------------------------------------------

{
    'thread_id': 'my_thread_id',
    'created_at': '2024-07-18T18:35:15.540834+00:00',
    'updated_at': '2024-07-18T18:35:15.540834+00:00',
    'metadata': {'graph_id': 'agent'}
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get(self, thread_id: str) -> Thread:
    """Get a thread by ID.

    Args:
        thread_id: The ID of the thread to get.

    Returns:
        Thread: Thread object.

    Example Usage:

        thread = client.threads.get(
            thread_id="my_thread_id"
        )
        print(thread)

        -----------------------------------------------------

        {
            'thread_id': 'my_thread_id',
            'created_at': '2024-07-18T18:35:15.540834+00:00',
            'updated_at': '2024-07-18T18:35:15.540834+00:00',
            'metadata': {'graph_id': 'agent'}
        }

    """  # noqa: E501

    return self.http.get(f"/threads/{thread_id}")

create(*, metadata: Json = None, thread_id: Optional[str] = None, if_exists: Optional[OnConflictBehavior] = None) -> Thread

Create a new thread.

Parameters:

  • metadata (Json, default: None ) –

    Metadata to add to thread.

  • thread_id (Optional[str], default: None ) –

    ID of thread. If None, ID will be a randomly generated UUID.

  • if_exists (Optional[OnConflictBehavior], default: None ) –

    How to handle duplicate creation. Defaults to 'raise' under the hood. Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

Returns:

  • Thread ( Thread ) –

    The created thread.

Example Usage:

thread = client.threads.create(
    metadata={"number":1},
    thread_id="my-thread-id",
    if_exists="raise"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def create(
    self,
    *,
    metadata: Json = None,
    thread_id: Optional[str] = None,
    if_exists: Optional[OnConflictBehavior] = None,
) -> Thread:
    """Create a new thread.

    Args:
        metadata: Metadata to add to thread.
        thread_id: ID of thread.
            If None, ID will be a randomly generated UUID.
        if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
            Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).

    Returns:
        Thread: The created thread.

    Example Usage:

        thread = client.threads.create(
            metadata={"number":1},
            thread_id="my-thread-id",
            if_exists="raise"
        )
    """  # noqa: E501
    payload: Dict[str, Any] = {}
    if thread_id:
        payload["thread_id"] = thread_id
    if metadata:
        payload["metadata"] = metadata
    if if_exists:
        payload["if_exists"] = if_exists
    return self.http.post("/threads", json=payload)

update(thread_id: str, *, metadata: dict[str, Any]) -> Thread

Update a thread.

Parameters:

  • thread_id (str) –

    ID of thread to update.

  • metadata (dict[str, Any]) –

    Metadata to merge with existing thread metadata.

Returns:

  • Thread ( Thread ) –

    The created thread.

Example Usage:

thread = client.threads.update(
    thread_id="my-thread-id",
    metadata={"number":1},
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def update(self, thread_id: str, *, metadata: dict[str, Any]) -> Thread:
    """Update a thread.

    Args:
        thread_id: ID of thread to update.
        metadata: Metadata to merge with existing thread metadata.

    Returns:
        Thread: The created thread.

    Example Usage:

        thread = client.threads.update(
            thread_id="my-thread-id",
            metadata={"number":1},
        )
    """  # noqa: E501
    return self.http.patch(f"/threads/{thread_id}", json={"metadata": metadata})

delete(thread_id: str) -> None

Delete a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to delete.

Returns:

  • None

    None

Example Usage:

client.threads.delete(
    thread_id="my_thread_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def delete(self, thread_id: str) -> None:
    """Delete a thread.

    Args:
        thread_id: The ID of the thread to delete.

    Returns:
        None

    Example Usage:

        client.threads.delete(
            thread_id="my_thread_id"
        )

    """  # noqa: E501
    self.http.delete(f"/threads/{thread_id}")

search(*, metadata: Json = None, values: Json = None, status: Optional[ThreadStatus] = None, limit: int = 10, offset: int = 0) -> list[Thread]

Search for threads.

Parameters:

  • metadata (Json, default: None ) –

    Thread metadata to filter on.

  • values (Json, default: None ) –

    State values to filter on.

  • status (Optional[ThreadStatus], default: None ) –

    Thread status to filter on. Must be one of 'idle', 'busy', 'interrupted' or 'error'.

  • limit (int, default: 10 ) –

    Limit on number of threads to return.

  • offset (int, default: 0 ) –

    Offset in threads table to start search from.

Returns:

  • list[Thread]

    list[Thread]: List of the threads matching the search parameters.

Example Usage:

threads = client.threads.search(
    metadata={"number":1},
    status="interrupted",
    limit=15,
    offset=5
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def search(
    self,
    *,
    metadata: Json = None,
    values: Json = None,
    status: Optional[ThreadStatus] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Thread]:
    """Search for threads.

    Args:
        metadata: Thread metadata to filter on.
        values: State values to filter on.
        status: Thread status to filter on.
            Must be one of 'idle', 'busy', 'interrupted' or 'error'.
        limit: Limit on number of threads to return.
        offset: Offset in threads table to start search from.

    Returns:
        list[Thread]: List of the threads matching the search parameters.

    Example Usage:

        threads = client.threads.search(
            metadata={"number":1},
            status="interrupted",
            limit=15,
            offset=5
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "limit": limit,
        "offset": offset,
    }
    if metadata:
        payload["metadata"] = metadata
    if values:
        payload["values"] = values
    if status:
        payload["status"] = status
    return self.http.post(
        "/threads/search",
        json=payload,
    )

copy(thread_id: str) -> None

Copy a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to copy.

Returns:

  • None

    None

Example Usage:

client.threads.copy(
    thread_id="my_thread_id"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def copy(self, thread_id: str) -> None:
    """Copy a thread.

    Args:
        thread_id: The ID of the thread to copy.

    Returns:
        None

    Example Usage:

        client.threads.copy(
            thread_id="my_thread_id"
        )

    """  # noqa: E501
    return self.http.post(f"/threads/{thread_id}/copy", json=None)

get_state(thread_id: str, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, *, subgraphs: bool = False) -> ThreadState

Get the state of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to get the state of.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to get the state of.

  • subgraphs (bool, default: False ) –

    Include subgraphs states.

Returns:

  • ThreadState ( ThreadState ) –

    the thread of the state.

Example Usage:

thread_state = client.threads.get_state(
    thread_id="my_thread_id",
    checkpoint_id="my_checkpoint_id"
)
print(thread_state)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'values': {
        '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
            }
        ]
    },
    'next': [],
    'checkpoint':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
        }
    'metadata':
        {
            'step': 1,
            'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
            'source': 'loop',
            'writes':
                {
                    'agent':
                        {
                            'messages': [
                                {
                                    'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                    'name': None,
                                    'type': 'ai',
                                    'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                    'example': False,
                                    'tool_calls': [],
                                    'usage_metadata': None,
                                    'additional_kwargs': {},
                                    'response_metadata': {},
                                    'invalid_tool_calls': []
                                }
                            ]
                        }
                },
    'user_id': None,
    'graph_id': 'agent',
    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
    'created_by': 'system',
    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
    'created_at': '2024-07-25T15:35:44.184703+00:00',
    'parent_config':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
        }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_state(
    self,
    thread_id: str,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,  # deprecated
    *,
    subgraphs: bool = False,
) -> ThreadState:
    """Get the state of a thread.

    Args:
        thread_id: The ID of the thread to get the state of.
        checkpoint: The checkpoint to get the state of.
        subgraphs: Include subgraphs states.

    Returns:
        ThreadState: the thread of the state.

    Example Usage:

        thread_state = client.threads.get_state(
            thread_id="my_thread_id",
            checkpoint_id="my_checkpoint_id"
        )
        print(thread_state)

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

        {
            'values': {
                '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
                    }
                ]
            },
            'next': [],
            'checkpoint':
                {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
                }
            'metadata':
                {
                    'step': 1,
                    'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
                    'source': 'loop',
                    'writes':
                        {
                            'agent':
                                {
                                    'messages': [
                                        {
                                            'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                            'name': None,
                                            'type': 'ai',
                                            'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                            'example': False,
                                            'tool_calls': [],
                                            'usage_metadata': None,
                                            'additional_kwargs': {},
                                            'response_metadata': {},
                                            'invalid_tool_calls': []
                                        }
                                    ]
                                }
                        },
            'user_id': None,
            'graph_id': 'agent',
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'created_by': 'system',
            'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
            'created_at': '2024-07-25T15:35:44.184703+00:00',
            'parent_config':
                {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
                }
        }

    """  # noqa: E501
    if checkpoint:
        return self.http.post(
            f"/threads/{thread_id}/state/checkpoint",
            json={"checkpoint": checkpoint, "subgraphs": subgraphs},
        )
    elif checkpoint_id:
        return self.http.get(
            f"/threads/{thread_id}/state/{checkpoint_id}",
            params={"subgraphs": subgraphs},
        )
    else:
        return self.http.get(
            f"/threads/{thread_id}/state",
            params={"subgraphs": subgraphs},
        )

update_state(thread_id: str, values: Optional[Union[dict, Sequence[dict]]], *, as_node: Optional[str] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None) -> ThreadUpdateStateResponse

Update the state of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to update.

  • values (Optional[Union[dict, Sequence[dict]]]) –

    The values to update the state with.

  • as_node (Optional[str], default: None ) –

    Update the state as if this node had just executed.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to update the state of.

Returns:

  • ThreadUpdateStateResponse ( ThreadUpdateStateResponse ) –

    Response after updating a thread's state.

Example Usage:

response = client.threads.update_state(
    thread_id="my_thread_id",
    values={"messages":[{"role": "user", "content": "hello!"}]},
    as_node="my_node",
)
print(response)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'checkpoint': {
        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
        'checkpoint_ns': '',
        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
        'checkpoint_map': {}
    }
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def update_state(
    self,
    thread_id: str,
    values: Optional[Union[dict, Sequence[dict]]],
    *,
    as_node: Optional[str] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,  # deprecated
) -> ThreadUpdateStateResponse:
    """Update the state of a thread.

    Args:
        thread_id: The ID of the thread to update.
        values: The values to update the state with.
        as_node: Update the state as if this node had just executed.
        checkpoint: The checkpoint to update the state of.

    Returns:
        ThreadUpdateStateResponse: Response after updating a thread's state.

    Example Usage:

        response = client.threads.update_state(
            thread_id="my_thread_id",
            values={"messages":[{"role": "user", "content": "hello!"}]},
            as_node="my_node",
        )
        print(response)

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

        {
            'checkpoint': {
                'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                'checkpoint_ns': '',
                'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
                'checkpoint_map': {}
            }
        }

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "values": values,
    }
    if checkpoint_id:
        payload["checkpoint_id"] = checkpoint_id
    if checkpoint:
        payload["checkpoint"] = checkpoint
    if as_node:
        payload["as_node"] = as_node
    return self.http.post(f"/threads/{thread_id}/state", json=payload)

get_history(thread_id: str, *, limit: int = 10, before: Optional[str | Checkpoint] = None, metadata: Optional[dict] = None, checkpoint: Optional[Checkpoint] = None) -> list[ThreadState]

Get the state history of a thread.

Parameters:

  • thread_id (str) –

    The ID of the thread to get the state history for.

  • checkpoint (Optional[Checkpoint], default: None ) –

    Return states for this subgraph. If empty defaults to root.

  • limit (int, default: 10 ) –

    The maximum number of states to return.

  • before (Optional[str | Checkpoint], default: None ) –

    Return states before this checkpoint.

  • metadata (Optional[dict], default: None ) –

    Filter states by metadata key-value pairs.

Returns:

  • list[ThreadState]

    list[ThreadState]: the state history of the thread.

Example Usage:

thread_state = client.threads.get_history(
    thread_id="my_thread_id",
    limit=5,
    before="my_timestamp",
    metadata={"name":"my_name"}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_history(
    self,
    thread_id: str,
    *,
    limit: int = 10,
    before: Optional[str | Checkpoint] = None,
    metadata: Optional[dict] = None,
    checkpoint: Optional[Checkpoint] = None,
) -> list[ThreadState]:
    """Get the state history of a thread.

    Args:
        thread_id: The ID of the thread to get the state history for.
        checkpoint: Return states for this subgraph. If empty defaults to root.
        limit: The maximum number of states to return.
        before: Return states before this checkpoint.
        metadata: Filter states by metadata key-value pairs.

    Returns:
        list[ThreadState]: the state history of the thread.

    Example Usage:

        thread_state = client.threads.get_history(
            thread_id="my_thread_id",
            limit=5,
            before="my_timestamp",
            metadata={"name":"my_name"}
        )

    """  # noqa: E501
    payload: Dict[str, Any] = {
        "limit": limit,
    }
    if before:
        payload["before"] = before
    if metadata:
        payload["metadata"] = metadata
    if checkpoint:
        payload["checkpoint"] = checkpoint
    return self.http.post(f"/threads/{thread_id}/history", json=payload)

SyncRunsClient

Synchronous client for managing runs in LangGraph.

This class provides methods to create, retrieve, and manage runs, which represent individual executions of graphs.

Example:

client = get_sync_client()
run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")
Source code in libs/sdk-py/langgraph_sdk/client.py
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
class SyncRunsClient:
    """Synchronous client for managing runs in LangGraph.

    This class provides methods to create, retrieve, and manage runs, which represent
    individual executions of graphs.

    Example:

        client = get_sync_client()
        run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")
    """

    def __init__(self, http: SyncHttpClient) -> None:
        self.http = http

    @overload
    def stream(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Iterator[StreamPart]: ...

    @overload
    def stream(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        webhook: Optional[str] = None,
        after_seconds: Optional[int] = None,
    ) -> Iterator[StreamPart]: ...

    def stream(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        feedback_keys: Optional[Sequence[str]] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Iterator[StreamPart]:
        """Create a run and stream the results.

        Args:
            thread_id: the thread ID to assign to the thread.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to stream from.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            stream_mode: The stream mode(s) to use.
            stream_subgraphs: Whether to stream output from subgraphs.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            feedback_keys: Feedback keys to assign to run.
            on_disconnect: The disconnect mode to use.
                Must be one of 'cancel' or 'continue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            Iterator[StreamPart]: Iterator of stream results.

        Example Usage:

            async for chunk in client.runs.stream(
                thread_id=None,
                assistant_id="agent",
                input={"messages": [{"role": "user", "content": "how are you?"}]},
                stream_mode=["values","debug"],
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "anthropic"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            ):
                print(chunk)

            ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

            StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
            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}]})
            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}]})
            StreamPart(event='end', data=None)

        """  # noqa: E501
        payload = {
            "input": input,
            "config": config,
            "metadata": metadata,
            "stream_mode": stream_mode,
            "stream_subgraphs": stream_subgraphs,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "feedback_keys": feedback_keys,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_disconnect": on_disconnect,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        endpoint = (
            f"/threads/{thread_id}/runs/stream"
            if thread_id is not None
            else "/runs/stream"
        )
        return self.http.stream(
            endpoint, "POST", json={k: v for k, v in payload.items() if v is not None}
        )

    @overload
    def create(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Run: ...

    @overload
    def create(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Run: ...

    def create(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
        stream_subgraphs: bool = False,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Run:
        """Create a background run.

        Args:
            thread_id: the thread ID to assign to the thread.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to stream from.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            stream_mode: The stream mode(s) to use.
            stream_subgraphs: Whether to stream output from subgraphs.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            Run: The created background run.

        Example Usage:

            background_run = client.runs.create(
                thread_id="my_thread_id",
                assistant_id="my_assistant_id",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )
            print(background_run)

            --------------------------------------------------------------------------------

            {
                'run_id': 'my_run_id',
                'thread_id': 'my_thread_id',
                'assistant_id': 'my_assistant_id',
                'created_at': '2024-07-25T15:35:42.598503+00:00',
                'updated_at': '2024-07-25T15:35:42.598503+00:00',
                'metadata': {},
                'status': 'pending',
                'kwargs':
                    {
                        'input':
                            {
                                'messages': [
                                    {
                                        'role': 'user',
                                        'content': 'how are you?'
                                    }
                                ]
                            },
                        'config':
                            {
                                'metadata':
                                    {
                                        'created_by': 'system'
                                    },
                                'configurable':
                                    {
                                        'run_id': 'my_run_id',
                                        'user_id': None,
                                        'graph_id': 'agent',
                                        'thread_id': 'my_thread_id',
                                        'checkpoint_id': None,
                                        'model_name': "openai",
                                        'assistant_id': 'my_assistant_id'
                                    }
                            },
                        'webhook': "https://my.fake.webhook.com",
                        'temporary': False,
                        'stream_mode': ['values'],
                        'feedback_keys': None,
                        'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
                        'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
                    },
                'multitask_strategy': 'interrupt'
            }

        """  # noqa: E501
        payload = {
            "input": input,
            "stream_mode": stream_mode,
            "stream_subgraphs": stream_subgraphs,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        payload = {k: v for k, v in payload.items() if v is not None}
        if thread_id:
            return self.http.post(f"/threads/{thread_id}/runs", json=payload)
        else:
            return self.http.post("/runs", json=payload)

    def create_batch(self, payloads: list[RunCreate]) -> list[Run]:
        """Create a batch of stateless background runs."""

        def filter_payload(payload: RunCreate):
            return {k: v for k, v in payload.items() if v is not None}

        payloads = [filter_payload(payload) for payload in payloads]
        return self.http.post("/runs/batch", json=payloads)

    @overload
    def wait(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Union[list[dict], dict[str, Any]]: ...

    @overload
    def wait(
        self,
        thread_id: None,
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Union[list[dict], dict[str, Any]]: ...

    def wait(
        self,
        thread_id: Optional[str],
        assistant_id: str,
        *,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        checkpoint: Optional[Checkpoint] = None,
        checkpoint_id: Optional[str] = None,
        interrupt_before: Optional[Union[All, Sequence[str]]] = None,
        interrupt_after: Optional[Union[All, Sequence[str]]] = None,
        webhook: Optional[str] = None,
        on_disconnect: Optional[DisconnectMode] = None,
        on_completion: Optional[OnCompletionBehavior] = None,
        multitask_strategy: Optional[MultitaskStrategy] = None,
        if_not_exists: Optional[IfNotExists] = None,
        after_seconds: Optional[int] = None,
    ) -> Union[list[dict], dict[str, Any]]:
        """Create a run, wait until it finishes and return the final state.

        Args:
            thread_id: the thread ID to create the run on.
                If None will create a stateless run.
            assistant_id: The assistant ID or graph name to run.
                If using graph name, will default to first assistant created from that graph.
            input: The input to the graph.
            metadata: Metadata to assign to the run.
            config: The configuration for the assistant.
            checkpoint: The checkpoint to resume from.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            on_disconnect: The disconnect mode to use.
                Must be one of 'cancel' or 'continue'.
            on_completion: Whether to delete or keep the thread created for a stateless run.
                Must be one of 'delete' or 'keep'.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
            if_not_exists: How to handle missing thread. Defaults to 'reject'.
                Must be either 'reject' (raise error if missing), or 'create' (create new thread).
            after_seconds: The number of seconds to wait before starting the run.
                Use to schedule future runs.

        Returns:
            Union[list[dict], dict[str, Any]]: The output of the run.

        Example Usage:

            final_state_of_run = client.runs.wait(
                thread_id=None,
                assistant_id="agent",
                input={"messages": [{"role": "user", "content": "how are you?"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "anthropic"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )
            print(final_state_of_run)

            -------------------------------------------------------------------------------------------------------------------------------------------

            {
                'messages': [
                    {
                        'content': 'how are you?',
                        'additional_kwargs': {},
                        'response_metadata': {},
                        'type': 'human',
                        'name': None,
                        'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
                        '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
                        'example': False,
                        'tool_calls': [],
                        'invalid_tool_calls': [],
                        'usage_metadata': None
                    }
                ]
            }

        """  # noqa: E501
        payload = {
            "input": input,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
            "checkpoint": checkpoint,
            "checkpoint_id": checkpoint_id,
            "multitask_strategy": multitask_strategy,
            "if_not_exists": if_not_exists,
            "on_disconnect": on_disconnect,
            "on_completion": on_completion,
            "after_seconds": after_seconds,
        }
        endpoint = (
            f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
        )
        return self.http.post(
            endpoint, json={k: v for k, v in payload.items() if v is not None}
        )

    def list(self, thread_id: str, *, limit: int = 10, offset: int = 0) -> List[Run]:
        """List runs.

        Args:
            thread_id: The thread ID to list runs for.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            List[Run]: The runs for the thread.

        Example Usage:

            client.runs.delete(
                thread_id="thread_id_to_delete",
                limit=5,
                offset=5,
            )

        """  # noqa: E501
        return self.http.get(f"/threads/{thread_id}/runs?limit={limit}&offset={offset}")

    def get(self, thread_id: str, run_id: str) -> Run:
        """Get a run.

        Args:
            thread_id: The thread ID to get.
            run_id: The run ID to get.

        Returns:
            Run: Run object.

        Example Usage:

            run = client.runs.get(
                thread_id="thread_id_to_delete",
                run_id="run_id_to_delete",
            )

        """  # noqa: E501

        return self.http.get(f"/threads/{thread_id}/runs/{run_id}")

    def cancel(
        self,
        thread_id: str,
        run_id: str,
        *,
        wait: bool = False,
        action: CancelAction = "interrupt",
    ) -> None:
        """Get a run.

        Args:
            thread_id: The thread ID to cancel.
            run_id: The run ID to cancek.
            wait: Whether to wait until run has completed.
            action: Action to take when cancelling the run. Possible values
                are `interrupt` or `rollback`. Default is `interrupt`.

        Returns:
            None

        Example Usage:

            client.runs.cancel(
                thread_id="thread_id_to_cancel",
                run_id="run_id_to_cancel",
                wait=True,
                action="interrupt"
            )

        """  # noqa: E501
        return self.http.post(
            f"/threads/{thread_id}/runs/{run_id}/cancel?wait={1 if wait else 0}&action={action}",
            json=None,
        )

    def join(self, thread_id: str, run_id: str) -> dict:
        """Block until a run is done. Returns the final state of the thread.

        Args:
            thread_id: The thread ID to join.
            run_id: The run ID to join.

        Returns:
            None

        Example Usage:

            client.runs.join(
                thread_id="thread_id_to_join",
                run_id="run_id_to_join"
            )

        """  # noqa: E501
        return self.http.get(f"/threads/{thread_id}/runs/{run_id}/join")

    def join_stream(self, thread_id: str, run_id: str) -> Iterator[StreamPart]:
        """Stream output from a run in real-time, until the run is done.
        Output is not buffered, so any output produced before this call will
        not be received here.

        Args:
            thread_id: The thread ID to join.
            run_id: The run ID to join.

        Returns:
            None

        Example Usage:

            client.runs.join_stream(
                thread_id="thread_id_to_join",
                run_id="run_id_to_join"
            )

        """  # noqa: E501
        return self.http.stream(f"/threads/{thread_id}/runs/{run_id}/stream", "GET")

    def delete(self, thread_id: str, run_id: str) -> None:
        """Delete a run.

        Args:
            thread_id: The thread ID to delete.
            run_id: The run ID to delete.

        Returns:
            None

        Example Usage:

            client.runs.delete(
                thread_id="thread_id_to_delete",
                run_id="run_id_to_delete"
            )

        """  # noqa: E501
        self.http.delete(f"/threads/{thread_id}/runs/{run_id}")

stream(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, stream_mode: Union[StreamMode, Sequence[StreamMode]] = 'values', stream_subgraphs: bool = False, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, feedback_keys: Optional[Sequence[str]] = None, on_disconnect: Optional[DisconnectMode] = None, on_completion: Optional[OnCompletionBehavior] = None, webhook: Optional[str] = None, multitask_strategy: Optional[MultitaskStrategy] = None, if_not_exists: Optional[IfNotExists] = None, after_seconds: Optional[int] = None) -> Iterator[StreamPart]

Create a run and stream the results.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to assign to the thread. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to stream from. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • stream_mode (Union[StreamMode, Sequence[StreamMode]], default: 'values' ) –

    The stream mode(s) to use.

  • stream_subgraphs (bool, default: False ) –

    Whether to stream output from subgraphs.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • feedback_keys (Optional[Sequence[str]], default: None ) –

    Feedback keys to assign to run.

  • on_disconnect (Optional[DisconnectMode], default: None ) –

    The disconnect mode to use. Must be one of 'cancel' or 'continue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • Iterator[StreamPart]

    Iterator[StreamPart]: Iterator of stream results.

Example Usage:

async for chunk in client.runs.stream(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    stream_mode=["values","debug"],
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
):
    print(chunk)

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
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}]})
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}]})
StreamPart(event='end', data=None)
Source code in libs/sdk-py/langgraph_sdk/client.py
def stream(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
    stream_subgraphs: bool = False,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    feedback_keys: Optional[Sequence[str]] = None,
    on_disconnect: Optional[DisconnectMode] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    if_not_exists: Optional[IfNotExists] = None,
    after_seconds: Optional[int] = None,
) -> Iterator[StreamPart]:
    """Create a run and stream the results.

    Args:
        thread_id: the thread ID to assign to the thread.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to stream from.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        stream_mode: The stream mode(s) to use.
        stream_subgraphs: Whether to stream output from subgraphs.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        feedback_keys: Feedback keys to assign to run.
        on_disconnect: The disconnect mode to use.
            Must be one of 'cancel' or 'continue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        Iterator[StreamPart]: Iterator of stream results.

    Example Usage:

        async for chunk in client.runs.stream(
            thread_id=None,
            assistant_id="agent",
            input={"messages": [{"role": "user", "content": "how are you?"}]},
            stream_mode=["values","debug"],
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "anthropic"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        ):
            print(chunk)

        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
        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}]})
        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}]})
        StreamPart(event='end', data=None)

    """  # noqa: E501
    payload = {
        "input": input,
        "config": config,
        "metadata": metadata,
        "stream_mode": stream_mode,
        "stream_subgraphs": stream_subgraphs,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "feedback_keys": feedback_keys,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_disconnect": on_disconnect,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    endpoint = (
        f"/threads/{thread_id}/runs/stream"
        if thread_id is not None
        else "/runs/stream"
    )
    return self.http.stream(
        endpoint, "POST", json={k: v for k, v in payload.items() if v is not None}
    )

create(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, stream_mode: Union[StreamMode, Sequence[StreamMode]] = 'values', stream_subgraphs: bool = False, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[MultitaskStrategy] = None, on_completion: Optional[OnCompletionBehavior] = None, if_not_exists: Optional[IfNotExists] = None, after_seconds: Optional[int] = None) -> Run

Create a background run.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to assign to the thread. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to stream from. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • stream_mode (Union[StreamMode, Sequence[StreamMode]], default: 'values' ) –

    The stream mode(s) to use.

  • stream_subgraphs (bool, default: False ) –

    Whether to stream output from subgraphs.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • Run ( Run ) –

    The created background run.

Example Usage:

background_run = client.runs.create(
    thread_id="my_thread_id",
    assistant_id="my_assistant_id",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(background_run)

--------------------------------------------------------------------------------

{
    'run_id': 'my_run_id',
    'thread_id': 'my_thread_id',
    'assistant_id': 'my_assistant_id',
    'created_at': '2024-07-25T15:35:42.598503+00:00',
    'updated_at': '2024-07-25T15:35:42.598503+00:00',
    'metadata': {},
    'status': 'pending',
    'kwargs':
        {
            'input':
                {
                    'messages': [
                        {
                            'role': 'user',
                            'content': 'how are you?'
                        }
                    ]
                },
            'config':
                {
                    'metadata':
                        {
                            'created_by': 'system'
                        },
                    'configurable':
                        {
                            'run_id': 'my_run_id',
                            'user_id': None,
                            'graph_id': 'agent',
                            'thread_id': 'my_thread_id',
                            'checkpoint_id': None,
                            'model_name': "openai",
                            'assistant_id': 'my_assistant_id'
                        }
                },
            'webhook': "https://my.fake.webhook.com",
            'temporary': False,
            'stream_mode': ['values'],
            'feedback_keys': None,
            'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
            'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
        },
    'multitask_strategy': 'interrupt'
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def create(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    stream_mode: Union[StreamMode, Sequence[StreamMode]] = "values",
    stream_subgraphs: bool = False,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    if_not_exists: Optional[IfNotExists] = None,
    after_seconds: Optional[int] = None,
) -> Run:
    """Create a background run.

    Args:
        thread_id: the thread ID to assign to the thread.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to stream from.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        stream_mode: The stream mode(s) to use.
        stream_subgraphs: Whether to stream output from subgraphs.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        Run: The created background run.

    Example Usage:

        background_run = client.runs.create(
            thread_id="my_thread_id",
            assistant_id="my_assistant_id",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )
        print(background_run)

        --------------------------------------------------------------------------------

        {
            'run_id': 'my_run_id',
            'thread_id': 'my_thread_id',
            'assistant_id': 'my_assistant_id',
            'created_at': '2024-07-25T15:35:42.598503+00:00',
            'updated_at': '2024-07-25T15:35:42.598503+00:00',
            'metadata': {},
            'status': 'pending',
            'kwargs':
                {
                    'input':
                        {
                            'messages': [
                                {
                                    'role': 'user',
                                    'content': 'how are you?'
                                }
                            ]
                        },
                    'config':
                        {
                            'metadata':
                                {
                                    'created_by': 'system'
                                },
                            'configurable':
                                {
                                    'run_id': 'my_run_id',
                                    'user_id': None,
                                    'graph_id': 'agent',
                                    'thread_id': 'my_thread_id',
                                    'checkpoint_id': None,
                                    'model_name': "openai",
                                    'assistant_id': 'my_assistant_id'
                                }
                        },
                    'webhook': "https://my.fake.webhook.com",
                    'temporary': False,
                    'stream_mode': ['values'],
                    'feedback_keys': None,
                    'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
                    'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
                },
            'multitask_strategy': 'interrupt'
        }

    """  # noqa: E501
    payload = {
        "input": input,
        "stream_mode": stream_mode,
        "stream_subgraphs": stream_subgraphs,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    payload = {k: v for k, v in payload.items() if v is not None}
    if thread_id:
        return self.http.post(f"/threads/{thread_id}/runs", json=payload)
    else:
        return self.http.post("/runs", json=payload)

create_batch(payloads: list[RunCreate]) -> list[Run]

Create a batch of stateless background runs.

Source code in libs/sdk-py/langgraph_sdk/client.py
def create_batch(self, payloads: list[RunCreate]) -> list[Run]:
    """Create a batch of stateless background runs."""

    def filter_payload(payload: RunCreate):
        return {k: v for k, v in payload.items() if v is not None}

    payloads = [filter_payload(payload) for payload in payloads]
    return self.http.post("/runs/batch", json=payloads)

wait(thread_id: Optional[str], assistant_id: str, *, input: Optional[dict] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, checkpoint: Optional[Checkpoint] = None, checkpoint_id: Optional[str] = None, interrupt_before: Optional[Union[All, Sequence[str]]] = None, interrupt_after: Optional[Union[All, Sequence[str]]] = None, webhook: Optional[str] = None, on_disconnect: Optional[DisconnectMode] = None, on_completion: Optional[OnCompletionBehavior] = None, multitask_strategy: Optional[MultitaskStrategy] = None, if_not_exists: Optional[IfNotExists] = None, after_seconds: Optional[int] = None) -> Union[list[dict], dict[str, Any]]

Create a run, wait until it finishes and return the final state.

Parameters:

  • thread_id (Optional[str]) –

    the thread ID to create the run on. If None will create a stateless run.

  • assistant_id (str) –

    The assistant ID or graph name to run. If using graph name, will default to first assistant created from that graph.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the run.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • checkpoint (Optional[Checkpoint], default: None ) –

    The checkpoint to resume from.

  • interrupt_before (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, Sequence[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • on_disconnect (Optional[DisconnectMode], default: None ) –

    The disconnect mode to use. Must be one of 'cancel' or 'continue'.

  • on_completion (Optional[OnCompletionBehavior], default: None ) –

    Whether to delete or keep the thread created for a stateless run. Must be one of 'delete' or 'keep'.

  • multitask_strategy (Optional[MultitaskStrategy], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

  • if_not_exists (Optional[IfNotExists], default: None ) –

    How to handle missing thread. Defaults to 'reject'. Must be either 'reject' (raise error if missing), or 'create' (create new thread).

  • after_seconds (Optional[int], default: None ) –

    The number of seconds to wait before starting the run. Use to schedule future runs.

Returns:

  • Union[list[dict], dict[str, Any]]

    Union[list[dict], dict[str, Any]]: The output of the run.

Example Usage:

final_state_of_run = client.runs.wait(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(final_state_of_run)

-------------------------------------------------------------------------------------------------------------------------------------------

{
    'messages': [
        {
            'content': 'how are you?',
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'human',
            'name': None,
            'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
            '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
            'example': False,
            'tool_calls': [],
            'invalid_tool_calls': [],
            'usage_metadata': None
        }
    ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def wait(
    self,
    thread_id: Optional[str],
    assistant_id: str,
    *,
    input: Optional[dict] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    checkpoint: Optional[Checkpoint] = None,
    checkpoint_id: Optional[str] = None,
    interrupt_before: Optional[Union[All, Sequence[str]]] = None,
    interrupt_after: Optional[Union[All, Sequence[str]]] = None,
    webhook: Optional[str] = None,
    on_disconnect: Optional[DisconnectMode] = None,
    on_completion: Optional[OnCompletionBehavior] = None,
    multitask_strategy: Optional[MultitaskStrategy] = None,
    if_not_exists: Optional[IfNotExists] = None,
    after_seconds: Optional[int] = None,
) -> Union[list[dict], dict[str, Any]]:
    """Create a run, wait until it finishes and return the final state.

    Args:
        thread_id: the thread ID to create the run on.
            If None will create a stateless run.
        assistant_id: The assistant ID or graph name to run.
            If using graph name, will default to first assistant created from that graph.
        input: The input to the graph.
        metadata: Metadata to assign to the run.
        config: The configuration for the assistant.
        checkpoint: The checkpoint to resume from.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        on_disconnect: The disconnect mode to use.
            Must be one of 'cancel' or 'continue'.
        on_completion: Whether to delete or keep the thread created for a stateless run.
            Must be one of 'delete' or 'keep'.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
        if_not_exists: How to handle missing thread. Defaults to 'reject'.
            Must be either 'reject' (raise error if missing), or 'create' (create new thread).
        after_seconds: The number of seconds to wait before starting the run.
            Use to schedule future runs.

    Returns:
        Union[list[dict], dict[str, Any]]: The output of the run.

    Example Usage:

        final_state_of_run = client.runs.wait(
            thread_id=None,
            assistant_id="agent",
            input={"messages": [{"role": "user", "content": "how are you?"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "anthropic"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )
        print(final_state_of_run)

        -------------------------------------------------------------------------------------------------------------------------------------------

        {
            'messages': [
                {
                    'content': 'how are you?',
                    'additional_kwargs': {},
                    'response_metadata': {},
                    'type': 'human',
                    'name': None,
                    'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
                    '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-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
                    'example': False,
                    'tool_calls': [],
                    'invalid_tool_calls': [],
                    'usage_metadata': None
                }
            ]
        }

    """  # noqa: E501
    payload = {
        "input": input,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
        "checkpoint": checkpoint,
        "checkpoint_id": checkpoint_id,
        "multitask_strategy": multitask_strategy,
        "if_not_exists": if_not_exists,
        "on_disconnect": on_disconnect,
        "on_completion": on_completion,
        "after_seconds": after_seconds,
    }
    endpoint = (
        f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
    )
    return self.http.post(
        endpoint, json={k: v for k, v in payload.items() if v is not None}
    )

list(thread_id: str, *, limit: int = 10, offset: int = 0) -> List[Run]

List runs.

Parameters:

  • thread_id (str) –

    The thread ID to list runs for.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • List[Run]

    List[Run]: The runs for the thread.

Example Usage:

client.runs.delete(
    thread_id="thread_id_to_delete",
    limit=5,
    offset=5,
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def list(self, thread_id: str, *, limit: int = 10, offset: int = 0) -> List[Run]:
    """List runs.

    Args:
        thread_id: The thread ID to list runs for.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        List[Run]: The runs for the thread.

    Example Usage:

        client.runs.delete(
            thread_id="thread_id_to_delete",
            limit=5,
            offset=5,
        )

    """  # noqa: E501
    return self.http.get(f"/threads/{thread_id}/runs?limit={limit}&offset={offset}")

get(thread_id: str, run_id: str) -> Run

Get a run.

Parameters:

  • thread_id (str) –

    The thread ID to get.

  • run_id (str) –

    The run ID to get.

Returns:

  • Run ( Run ) –

    Run object.

Example Usage:

run = client.runs.get(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete",
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def get(self, thread_id: str, run_id: str) -> Run:
    """Get a run.

    Args:
        thread_id: The thread ID to get.
        run_id: The run ID to get.

    Returns:
        Run: Run object.

    Example Usage:

        run = client.runs.get(
            thread_id="thread_id_to_delete",
            run_id="run_id_to_delete",
        )

    """  # noqa: E501

    return self.http.get(f"/threads/{thread_id}/runs/{run_id}")

cancel(thread_id: str, run_id: str, *, wait: bool = False, action: CancelAction = 'interrupt') -> None

Get a run.

Parameters:

  • thread_id (str) –

    The thread ID to cancel.

  • run_id (str) –

    The run ID to cancek.

  • wait (bool, default: False ) –

    Whether to wait until run has completed.

  • action (CancelAction, default: 'interrupt' ) –

    Action to take when cancelling the run. Possible values are interrupt or rollback. Default is interrupt.

Returns:

  • None

    None

Example Usage:

client.runs.cancel(
    thread_id="thread_id_to_cancel",
    run_id="run_id_to_cancel",
    wait=True,
    action="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def cancel(
    self,
    thread_id: str,
    run_id: str,
    *,
    wait: bool = False,
    action: CancelAction = "interrupt",
) -> None:
    """Get a run.

    Args:
        thread_id: The thread ID to cancel.
        run_id: The run ID to cancek.
        wait: Whether to wait until run has completed.
        action: Action to take when cancelling the run. Possible values
            are `interrupt` or `rollback`. Default is `interrupt`.

    Returns:
        None

    Example Usage:

        client.runs.cancel(
            thread_id="thread_id_to_cancel",
            run_id="run_id_to_cancel",
            wait=True,
            action="interrupt"
        )

    """  # noqa: E501
    return self.http.post(
        f"/threads/{thread_id}/runs/{run_id}/cancel?wait={1 if wait else 0}&action={action}",
        json=None,
    )

join(thread_id: str, run_id: str) -> dict

Block until a run is done. Returns the final state of the thread.

Parameters:

  • thread_id (str) –

    The thread ID to join.

  • run_id (str) –

    The run ID to join.

Returns:

  • dict

    None

Example Usage:

client.runs.join(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def join(self, thread_id: str, run_id: str) -> dict:
    """Block until a run is done. Returns the final state of the thread.

    Args:
        thread_id: The thread ID to join.
        run_id: The run ID to join.

    Returns:
        None

    Example Usage:

        client.runs.join(
            thread_id="thread_id_to_join",
            run_id="run_id_to_join"
        )

    """  # noqa: E501
    return self.http.get(f"/threads/{thread_id}/runs/{run_id}/join")

join_stream(thread_id: str, run_id: str) -> Iterator[StreamPart]

Stream output from a run in real-time, until the run is done. Output is not buffered, so any output produced before this call will not be received here.

Parameters:

  • thread_id (str) –

    The thread ID to join.

  • run_id (str) –

    The run ID to join.

Returns:

  • Iterator[StreamPart]

    None

Example Usage:

client.runs.join_stream(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def join_stream(self, thread_id: str, run_id: str) -> Iterator[StreamPart]:
    """Stream output from a run in real-time, until the run is done.
    Output is not buffered, so any output produced before this call will
    not be received here.

    Args:
        thread_id: The thread ID to join.
        run_id: The run ID to join.

    Returns:
        None

    Example Usage:

        client.runs.join_stream(
            thread_id="thread_id_to_join",
            run_id="run_id_to_join"
        )

    """  # noqa: E501
    return self.http.stream(f"/threads/{thread_id}/runs/{run_id}/stream", "GET")

delete(thread_id: str, run_id: str) -> None

Delete a run.

Parameters:

  • thread_id (str) –

    The thread ID to delete.

  • run_id (str) –

    The run ID to delete.

Returns:

  • None

    None

Example Usage:

client.runs.delete(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def delete(self, thread_id: str, run_id: str) -> None:
    """Delete a run.

    Args:
        thread_id: The thread ID to delete.
        run_id: The run ID to delete.

    Returns:
        None

    Example Usage:

        client.runs.delete(
            thread_id="thread_id_to_delete",
            run_id="run_id_to_delete"
        )

    """  # noqa: E501
    self.http.delete(f"/threads/{thread_id}/runs/{run_id}")

SyncCronClient

Synchronous client for managing cron jobs in LangGraph.

This class provides methods to create and manage scheduled tasks (cron jobs) for automated graph executions.

Example:

client = get_sync_client()
cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")
Source code in libs/sdk-py/langgraph_sdk/client.py
class SyncCronClient:
    """Synchronous client for managing cron jobs in LangGraph.

    This class provides methods to create and manage scheduled tasks (cron jobs) for automated graph executions.

    Example:

        client = get_sync_client()
        cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")
    """

    def __init__(self, http_client: SyncHttpClient) -> None:
        self.http = http_client

    def create_for_thread(
        self,
        thread_id: str,
        assistant_id: str,
        *,
        schedule: str,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, list[str]]] = None,
        interrupt_after: Optional[Union[All, list[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[str] = None,
    ) -> Run:
        """Create a cron job for a thread.

        Args:
            thread_id: the thread ID to run the cron job on.
            assistant_id: The assistant ID or graph name to use for the cron job.
                If using graph name, will default to first assistant created from that graph.
            schedule: The cron schedule to execute this job on.
            input: The input to the graph.
            metadata: Metadata to assign to the cron job runs.
            config: The configuration for the assistant.
            interrupt_before: Nodes to interrupt immediately before they get executed.

            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.

            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

        Returns:
            Run: The cron run.

        Example Usage:

            cron_run = client.crons.create_for_thread(
                thread_id="my-thread-id",
                assistant_id="agent",
                schedule="27 15 * * *",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )

        """  # noqa: E501
        payload = {
            "schedule": schedule,
            "input": input,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
        }
        if multitask_strategy:
            payload["multitask_strategy"] = multitask_strategy
        payload = {k: v for k, v in payload.items() if v is not None}
        return self.http.post(f"/threads/{thread_id}/runs/crons", json=payload)

    def create(
        self,
        assistant_id: str,
        *,
        schedule: str,
        input: Optional[dict] = None,
        metadata: Optional[dict] = None,
        config: Optional[Config] = None,
        interrupt_before: Optional[Union[All, list[str]]] = None,
        interrupt_after: Optional[Union[All, list[str]]] = None,
        webhook: Optional[str] = None,
        multitask_strategy: Optional[str] = None,
    ) -> Run:
        """Create a cron run.

        Args:
            assistant_id: The assistant ID or graph name to use for the cron job.
                If using graph name, will default to first assistant created from that graph.
            schedule: The cron schedule to execute this job on.
            input: The input to the graph.
            metadata: Metadata to assign to the cron job runs.
            config: The configuration for the assistant.
            interrupt_before: Nodes to interrupt immediately before they get executed.
            interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
            webhook: Webhook to call after LangGraph API call is done.
            multitask_strategy: Multitask strategy to use.
                Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

        Returns:
            Run: The cron run.

        Example Usage:

            cron_run = client.crons.create(
                assistant_id="agent",
                schedule="27 15 * * *",
                input={"messages": [{"role": "user", "content": "hello!"}]},
                metadata={"name":"my_run"},
                config={"configurable": {"model_name": "openai"}},
                interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
                interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
                webhook="https://my.fake.webhook.com",
                multitask_strategy="interrupt"
            )

        """  # noqa: E501
        payload = {
            "schedule": schedule,
            "input": input,
            "config": config,
            "metadata": metadata,
            "assistant_id": assistant_id,
            "interrupt_before": interrupt_before,
            "interrupt_after": interrupt_after,
            "webhook": webhook,
        }
        if multitask_strategy:
            payload["multitask_strategy"] = multitask_strategy
        payload = {k: v for k, v in payload.items() if v is not None}
        return self.http.post("/runs/crons", json=payload)

    def delete(self, cron_id: str) -> None:
        """Delete a cron.

        Args:
            cron_id: The cron ID to delete.

        Returns:
            None

        Example Usage:

            client.crons.delete(
                cron_id="cron_to_delete"
            )

        """  # noqa: E501
        self.http.delete(f"/runs/crons/{cron_id}")

    def search(
        self,
        *,
        assistant_id: Optional[str] = None,
        thread_id: Optional[str] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> list[Cron]:
        """Get a list of cron jobs.

        Args:
            assistant_id: The assistant ID or graph name to search for.
            thread_id: the thread ID to search for.
            limit: The maximum number of results to return.
            offset: The number of results to skip.

        Returns:
            list[Cron]: The list of cron jobs returned by the search,

        Example Usage:

            cron_jobs = client.crons.search(
                assistant_id="my_assistant_id",
                thread_id="my_thread_id",
                limit=5,
                offset=5,
            )
            print(cron_jobs)

            ----------------------------------------------------------

            [
                {
                    'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
                    'assistant_id': 'my_assistant_id',
                    'thread_id': 'my_thread_id',
                    'user_id': None,
                    'payload':
                        {
                            'input': {'start_time': ''},
                            'schedule': '4 * * * *',
                            'assistant_id': 'my_assistant_id'
                        },
                    'schedule': '4 * * * *',
                    'next_run_date': '2024-07-25T17:04:00+00:00',
                    'end_time': None,
                    'created_at': '2024-07-08T06:02:23.073257+00:00',
                    'updated_at': '2024-07-08T06:02:23.073257+00:00'
                }
            ]

        """  # noqa: E501
        payload = {
            "assistant_id": assistant_id,
            "thread_id": thread_id,
            "limit": limit,
            "offset": offset,
        }
        payload = {k: v for k, v in payload.items() if v is not None}
        return self.http.post("/runs/crons/search", json=payload)

create_for_thread(thread_id: str, assistant_id: str, *, schedule: str, input: Optional[dict] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, interrupt_before: Optional[Union[All, list[str]]] = None, interrupt_after: Optional[Union[All, list[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[str] = None) -> Run

Create a cron job for a thread.

Parameters:

  • thread_id (str) –

    the thread ID to run the cron job on.

  • assistant_id (str) –

    The assistant ID or graph name to use for the cron job. If using graph name, will default to first assistant created from that graph.

  • schedule (str) –

    The cron schedule to execute this job on.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the cron job runs.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • interrupt_before (Optional[Union[All, list[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, list[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[str], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

Returns:

  • Run ( Run ) –

    The cron run.

Example Usage:

cron_run = client.crons.create_for_thread(
    thread_id="my-thread-id",
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def create_for_thread(
    self,
    thread_id: str,
    assistant_id: str,
    *,
    schedule: str,
    input: Optional[dict] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    interrupt_before: Optional[Union[All, list[str]]] = None,
    interrupt_after: Optional[Union[All, list[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[str] = None,
) -> Run:
    """Create a cron job for a thread.

    Args:
        thread_id: the thread ID to run the cron job on.
        assistant_id: The assistant ID or graph name to use for the cron job.
            If using graph name, will default to first assistant created from that graph.
        schedule: The cron schedule to execute this job on.
        input: The input to the graph.
        metadata: Metadata to assign to the cron job runs.
        config: The configuration for the assistant.
        interrupt_before: Nodes to interrupt immediately before they get executed.

        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.

        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

    Returns:
        Run: The cron run.

    Example Usage:

        cron_run = client.crons.create_for_thread(
            thread_id="my-thread-id",
            assistant_id="agent",
            schedule="27 15 * * *",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )

    """  # noqa: E501
    payload = {
        "schedule": schedule,
        "input": input,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
    }
    if multitask_strategy:
        payload["multitask_strategy"] = multitask_strategy
    payload = {k: v for k, v in payload.items() if v is not None}
    return self.http.post(f"/threads/{thread_id}/runs/crons", json=payload)

create(assistant_id: str, *, schedule: str, input: Optional[dict] = None, metadata: Optional[dict] = None, config: Optional[Config] = None, interrupt_before: Optional[Union[All, list[str]]] = None, interrupt_after: Optional[Union[All, list[str]]] = None, webhook: Optional[str] = None, multitask_strategy: Optional[str] = None) -> Run

Create a cron run.

Parameters:

  • assistant_id (str) –

    The assistant ID or graph name to use for the cron job. If using graph name, will default to first assistant created from that graph.

  • schedule (str) –

    The cron schedule to execute this job on.

  • input (Optional[dict], default: None ) –

    The input to the graph.

  • metadata (Optional[dict], default: None ) –

    Metadata to assign to the cron job runs.

  • config (Optional[Config], default: None ) –

    The configuration for the assistant.

  • interrupt_before (Optional[Union[All, list[str]]], default: None ) –

    Nodes to interrupt immediately before they get executed.

  • interrupt_after (Optional[Union[All, list[str]]], default: None ) –

    Nodes to Nodes to interrupt immediately after they get executed.

  • webhook (Optional[str], default: None ) –

    Webhook to call after LangGraph API call is done.

  • multitask_strategy (Optional[str], default: None ) –

    Multitask strategy to use. Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

Returns:

  • Run ( Run ) –

    The cron run.

Example Usage:

cron_run = client.crons.create(
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def create(
    self,
    assistant_id: str,
    *,
    schedule: str,
    input: Optional[dict] = None,
    metadata: Optional[dict] = None,
    config: Optional[Config] = None,
    interrupt_before: Optional[Union[All, list[str]]] = None,
    interrupt_after: Optional[Union[All, list[str]]] = None,
    webhook: Optional[str] = None,
    multitask_strategy: Optional[str] = None,
) -> Run:
    """Create a cron run.

    Args:
        assistant_id: The assistant ID or graph name to use for the cron job.
            If using graph name, will default to first assistant created from that graph.
        schedule: The cron schedule to execute this job on.
        input: The input to the graph.
        metadata: Metadata to assign to the cron job runs.
        config: The configuration for the assistant.
        interrupt_before: Nodes to interrupt immediately before they get executed.
        interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
        webhook: Webhook to call after LangGraph API call is done.
        multitask_strategy: Multitask strategy to use.
            Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.

    Returns:
        Run: The cron run.

    Example Usage:

        cron_run = client.crons.create(
            assistant_id="agent",
            schedule="27 15 * * *",
            input={"messages": [{"role": "user", "content": "hello!"}]},
            metadata={"name":"my_run"},
            config={"configurable": {"model_name": "openai"}},
            interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
            interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
            webhook="https://my.fake.webhook.com",
            multitask_strategy="interrupt"
        )

    """  # noqa: E501
    payload = {
        "schedule": schedule,
        "input": input,
        "config": config,
        "metadata": metadata,
        "assistant_id": assistant_id,
        "interrupt_before": interrupt_before,
        "interrupt_after": interrupt_after,
        "webhook": webhook,
    }
    if multitask_strategy:
        payload["multitask_strategy"] = multitask_strategy
    payload = {k: v for k, v in payload.items() if v is not None}
    return self.http.post("/runs/crons", json=payload)

delete(cron_id: str) -> None

Delete a cron.

Parameters:

  • cron_id (str) –

    The cron ID to delete.

Returns:

  • None

    None

Example Usage:

client.crons.delete(
    cron_id="cron_to_delete"
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def delete(self, cron_id: str) -> None:
    """Delete a cron.

    Args:
        cron_id: The cron ID to delete.

    Returns:
        None

    Example Usage:

        client.crons.delete(
            cron_id="cron_to_delete"
        )

    """  # noqa: E501
    self.http.delete(f"/runs/crons/{cron_id}")

search(*, assistant_id: Optional[str] = None, thread_id: Optional[str] = None, limit: int = 10, offset: int = 0) -> list[Cron]

Get a list of cron jobs.

Parameters:

  • assistant_id (Optional[str], default: None ) –

    The assistant ID or graph name to search for.

  • thread_id (Optional[str], default: None ) –

    the thread ID to search for.

  • limit (int, default: 10 ) –

    The maximum number of results to return.

  • offset (int, default: 0 ) –

    The number of results to skip.

Returns:

  • list[Cron]

    list[Cron]: The list of cron jobs returned by the search,

Example Usage:

cron_jobs = client.crons.search(
    assistant_id="my_assistant_id",
    thread_id="my_thread_id",
    limit=5,
    offset=5,
)
print(cron_jobs)

----------------------------------------------------------

[
    {
        'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
        'assistant_id': 'my_assistant_id',
        'thread_id': 'my_thread_id',
        'user_id': None,
        'payload':
            {
                'input': {'start_time': ''},
                'schedule': '4 * * * *',
                'assistant_id': 'my_assistant_id'
            },
        'schedule': '4 * * * *',
        'next_run_date': '2024-07-25T17:04:00+00:00',
        'end_time': None,
        'created_at': '2024-07-08T06:02:23.073257+00:00',
        'updated_at': '2024-07-08T06:02:23.073257+00:00'
    }
]
Source code in libs/sdk-py/langgraph_sdk/client.py
def search(
    self,
    *,
    assistant_id: Optional[str] = None,
    thread_id: Optional[str] = None,
    limit: int = 10,
    offset: int = 0,
) -> list[Cron]:
    """Get a list of cron jobs.

    Args:
        assistant_id: The assistant ID or graph name to search for.
        thread_id: the thread ID to search for.
        limit: The maximum number of results to return.
        offset: The number of results to skip.

    Returns:
        list[Cron]: The list of cron jobs returned by the search,

    Example Usage:

        cron_jobs = client.crons.search(
            assistant_id="my_assistant_id",
            thread_id="my_thread_id",
            limit=5,
            offset=5,
        )
        print(cron_jobs)

        ----------------------------------------------------------

        [
            {
                'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
                'assistant_id': 'my_assistant_id',
                'thread_id': 'my_thread_id',
                'user_id': None,
                'payload':
                    {
                        'input': {'start_time': ''},
                        'schedule': '4 * * * *',
                        'assistant_id': 'my_assistant_id'
                    },
                'schedule': '4 * * * *',
                'next_run_date': '2024-07-25T17:04:00+00:00',
                'end_time': None,
                'created_at': '2024-07-08T06:02:23.073257+00:00',
                'updated_at': '2024-07-08T06:02:23.073257+00:00'
            }
        ]

    """  # noqa: E501
    payload = {
        "assistant_id": assistant_id,
        "thread_id": thread_id,
        "limit": limit,
        "offset": offset,
    }
    payload = {k: v for k, v in payload.items() if v is not None}
    return self.http.post("/runs/crons/search", json=payload)

SyncStoreClient

A client for synchronous operations on a key-value store.

Provides methods to interact with a remote key-value store, allowing storage and retrieval of items within namespaced hierarchies.

Example:

client = get_sync_client()
client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})
Source code in libs/sdk-py/langgraph_sdk/client.py
class SyncStoreClient:
    """A client for synchronous operations on a key-value store.

    Provides methods to interact with a remote key-value store, allowing
    storage and retrieval of items within namespaced hierarchies.

    Example:

        client = get_sync_client()
        client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})
    """

    def __init__(self, http: SyncHttpClient) -> None:
        self.http = http

    def put_item(
        self, namespace: Sequence[str], /, key: str, value: dict[str, Any]
    ) -> None:
        """Store or update an item.

        Args:
            namespace: A list of strings representing the namespace path.
            key: The unique identifier for the item within the namespace.
            value: A dictionary containing the item's data.

        Returns:
            None

        Example Usage:

            client.store.put_item(
                ["documents", "user123"],
                key="item456",
                value={"title": "My Document", "content": "Hello World"}
            )
        """
        for label in namespace:
            if "." in label:
                raise ValueError(
                    f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
                )
        payload = {
            "namespace": namespace,
            "key": key,
            "value": value,
        }
        self.http.put("/store/items", json=payload)

    def get_item(self, namespace: Sequence[str], /, key: str) -> Item:
        """Retrieve a single item.

        Args:
            key: The unique identifier for the item.
            namespace: Optional list of strings representing the namespace path.

        Returns:
            Item: The retrieved item.

        Example Usage:

            item = client.store.get_item(
                ["documents", "user123"],
                key="item456",
            )
            print(item)

            ----------------------------------------------------------------

            {
                'namespace': ['documents', 'user123'],
                'key': 'item456',
                'value': {'title': 'My Document', 'content': 'Hello World'},
                'created_at': '2024-07-30T12:00:00Z',
                'updated_at': '2024-07-30T12:00:00Z'
            }
        """
        for label in namespace:
            if "." in label:
                raise ValueError(
                    f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
                )

        return self.http.get(
            "/store/items", params={"key": key, "namespace": ".".join(namespace)}
        )

    def delete_item(self, namespace: Sequence[str], /, key: str) -> None:
        """Delete an item.

        Args:
            key: The unique identifier for the item.
            namespace: Optional list of strings representing the namespace path.

        Returns:
            None

        Example Usage:

            client.store.delete_item(
                ["documents", "user123"],
                key="item456",
            )
        """
        self.http.delete("/store/items", json={"key": key, "namespace": namespace})

    def search_items(
        self,
        namespace_prefix: Sequence[str],
        /,
        filter: Optional[dict[str, Any]] = None,
        limit: int = 10,
        offset: int = 0,
    ) -> SearchItemsResponse:
        """Search for items within a namespace prefix.

        Args:
            namespace_prefix: List of strings representing the namespace prefix.
            filter: Optional dictionary of key-value pairs to filter results.
            limit: Maximum number of items to return (default is 10).
            offset: Number of items to skip before returning results (default is 0).

        Returns:
            List[Item]: A list of items matching the search criteria.

        Example Usage:

            items = client.store.search_items(
                ["documents"],
                filter={"author": "John Doe"},
                limit=5,
                offset=0
            )
            print(items)

            ----------------------------------------------------------------

            {
                "items": [
                    {
                        "namespace": ["documents", "user123"],
                        "key": "item789",
                        "value": {
                            "title": "Another Document",
                            "author": "John Doe"
                        },
                        "created_at": "2024-07-30T12:00:00Z",
                        "updated_at": "2024-07-30T12:00:00Z"
                    },
                    # ... additional items ...
                ]
            }
        """
        payload = {
            "namespace_prefix": namespace_prefix,
            "filter": filter,
            "limit": limit,
            "offset": offset,
        }
        return self.http.post("/store/items/search", json=_provided_vals(payload))

    def list_namespaces(
        self,
        prefix: Optional[List[str]] = None,
        suffix: Optional[List[str]] = None,
        max_depth: Optional[int] = None,
        limit: int = 100,
        offset: int = 0,
    ) -> ListNamespaceResponse:
        """List namespaces with optional match conditions.

        Args:
            prefix: Optional list of strings representing the prefix to filter namespaces.
            suffix: Optional list of strings representing the suffix to filter namespaces.
            max_depth: Optional integer specifying the maximum depth of namespaces to return.
            limit: Maximum number of namespaces to return (default is 100).
            offset: Number of namespaces to skip before returning results (default is 0).

        Returns:
            List[List[str]]: A list of namespaces matching the criteria.

        Example Usage:

            namespaces = client.store.list_namespaces(
                prefix=["documents"],
                max_depth=3,
                limit=10,
                offset=0
            )
            print(namespaces)

            ----------------------------------------------------------------

            [
                ["documents", "user123", "reports"],
                ["documents", "user456", "invoices"],
                ...
            ]
        """
        payload = {
            "prefix": prefix,
            "suffix": suffix,
            "max_depth": max_depth,
            "limit": limit,
            "offset": offset,
        }
        return self.http.post("/store/namespaces", json=_provided_vals(payload))

put_item(namespace: Sequence[str], /, key: str, value: dict[str, Any]) -> None

Store or update an item.

Parameters:

  • namespace (Sequence[str]) –

    A list of strings representing the namespace path.

  • key (str) –

    The unique identifier for the item within the namespace.

  • value (dict[str, Any]) –

    A dictionary containing the item's data.

Returns:

  • None

    None

Example Usage:

client.store.put_item(
    ["documents", "user123"],
    key="item456",
    value={"title": "My Document", "content": "Hello World"}
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def put_item(
    self, namespace: Sequence[str], /, key: str, value: dict[str, Any]
) -> None:
    """Store or update an item.

    Args:
        namespace: A list of strings representing the namespace path.
        key: The unique identifier for the item within the namespace.
        value: A dictionary containing the item's data.

    Returns:
        None

    Example Usage:

        client.store.put_item(
            ["documents", "user123"],
            key="item456",
            value={"title": "My Document", "content": "Hello World"}
        )
    """
    for label in namespace:
        if "." in label:
            raise ValueError(
                f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
            )
    payload = {
        "namespace": namespace,
        "key": key,
        "value": value,
    }
    self.http.put("/store/items", json=payload)

get_item(namespace: Sequence[str], /, key: str) -> Item

Retrieve a single item.

Parameters:

  • key (str) –

    The unique identifier for the item.

  • namespace (Sequence[str]) –

    Optional list of strings representing the namespace path.

Returns:

  • Item ( Item ) –

    The retrieved item.

Example Usage:

item = client.store.get_item(
    ["documents", "user123"],
    key="item456",
)
print(item)

----------------------------------------------------------------

{
    'namespace': ['documents', 'user123'],
    'key': 'item456',
    'value': {'title': 'My Document', 'content': 'Hello World'},
    'created_at': '2024-07-30T12:00:00Z',
    'updated_at': '2024-07-30T12:00:00Z'
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_item(self, namespace: Sequence[str], /, key: str) -> Item:
    """Retrieve a single item.

    Args:
        key: The unique identifier for the item.
        namespace: Optional list of strings representing the namespace path.

    Returns:
        Item: The retrieved item.

    Example Usage:

        item = client.store.get_item(
            ["documents", "user123"],
            key="item456",
        )
        print(item)

        ----------------------------------------------------------------

        {
            'namespace': ['documents', 'user123'],
            'key': 'item456',
            'value': {'title': 'My Document', 'content': 'Hello World'},
            'created_at': '2024-07-30T12:00:00Z',
            'updated_at': '2024-07-30T12:00:00Z'
        }
    """
    for label in namespace:
        if "." in label:
            raise ValueError(
                f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
            )

    return self.http.get(
        "/store/items", params={"key": key, "namespace": ".".join(namespace)}
    )

delete_item(namespace: Sequence[str], /, key: str) -> None

Delete an item.

Parameters:

  • key (str) –

    The unique identifier for the item.

  • namespace (Sequence[str]) –

    Optional list of strings representing the namespace path.

Returns:

  • None

    None

Example Usage:

client.store.delete_item(
    ["documents", "user123"],
    key="item456",
)
Source code in libs/sdk-py/langgraph_sdk/client.py
def delete_item(self, namespace: Sequence[str], /, key: str) -> None:
    """Delete an item.

    Args:
        key: The unique identifier for the item.
        namespace: Optional list of strings representing the namespace path.

    Returns:
        None

    Example Usage:

        client.store.delete_item(
            ["documents", "user123"],
            key="item456",
        )
    """
    self.http.delete("/store/items", json={"key": key, "namespace": namespace})

search_items(namespace_prefix: Sequence[str], /, filter: Optional[dict[str, Any]] = None, limit: int = 10, offset: int = 0) -> SearchItemsResponse

Search for items within a namespace prefix.

Parameters:

  • namespace_prefix (Sequence[str]) –

    List of strings representing the namespace prefix.

  • filter (Optional[dict[str, Any]], default: None ) –

    Optional dictionary of key-value pairs to filter results.

  • limit (int, default: 10 ) –

    Maximum number of items to return (default is 10).

  • offset (int, default: 0 ) –

    Number of items to skip before returning results (default is 0).

Returns:

  • SearchItemsResponse

    List[Item]: A list of items matching the search criteria.

Example Usage:

items = client.store.search_items(
    ["documents"],
    filter={"author": "John Doe"},
    limit=5,
    offset=0
)
print(items)

----------------------------------------------------------------

{
    "items": [
        {
            "namespace": ["documents", "user123"],
            "key": "item789",
            "value": {
                "title": "Another Document",
                "author": "John Doe"
            },
            "created_at": "2024-07-30T12:00:00Z",
            "updated_at": "2024-07-30T12:00:00Z"
        },
        # ... additional items ...
    ]
}
Source code in libs/sdk-py/langgraph_sdk/client.py
def search_items(
    self,
    namespace_prefix: Sequence[str],
    /,
    filter: Optional[dict[str, Any]] = None,
    limit: int = 10,
    offset: int = 0,
) -> SearchItemsResponse:
    """Search for items within a namespace prefix.

    Args:
        namespace_prefix: List of strings representing the namespace prefix.
        filter: Optional dictionary of key-value pairs to filter results.
        limit: Maximum number of items to return (default is 10).
        offset: Number of items to skip before returning results (default is 0).

    Returns:
        List[Item]: A list of items matching the search criteria.

    Example Usage:

        items = client.store.search_items(
            ["documents"],
            filter={"author": "John Doe"},
            limit=5,
            offset=0
        )
        print(items)

        ----------------------------------------------------------------

        {
            "items": [
                {
                    "namespace": ["documents", "user123"],
                    "key": "item789",
                    "value": {
                        "title": "Another Document",
                        "author": "John Doe"
                    },
                    "created_at": "2024-07-30T12:00:00Z",
                    "updated_at": "2024-07-30T12:00:00Z"
                },
                # ... additional items ...
            ]
        }
    """
    payload = {
        "namespace_prefix": namespace_prefix,
        "filter": filter,
        "limit": limit,
        "offset": offset,
    }
    return self.http.post("/store/items/search", json=_provided_vals(payload))

list_namespaces(prefix: Optional[List[str]] = None, suffix: Optional[List[str]] = None, max_depth: Optional[int] = None, limit: int = 100, offset: int = 0) -> ListNamespaceResponse

List namespaces with optional match conditions.

Parameters:

  • prefix (Optional[List[str]], default: None ) –

    Optional list of strings representing the prefix to filter namespaces.

  • suffix (Optional[List[str]], default: None ) –

    Optional list of strings representing the suffix to filter namespaces.

  • max_depth (Optional[int], default: None ) –

    Optional integer specifying the maximum depth of namespaces to return.

  • limit (int, default: 100 ) –

    Maximum number of namespaces to return (default is 100).

  • offset (int, default: 0 ) –

    Number of namespaces to skip before returning results (default is 0).

Returns:

  • ListNamespaceResponse

    List[List[str]]: A list of namespaces matching the criteria.

Example Usage:

namespaces = client.store.list_namespaces(
    prefix=["documents"],
    max_depth=3,
    limit=10,
    offset=0
)
print(namespaces)

----------------------------------------------------------------

[
    ["documents", "user123", "reports"],
    ["documents", "user456", "invoices"],
    ...
]
Source code in libs/sdk-py/langgraph_sdk/client.py
def list_namespaces(
    self,
    prefix: Optional[List[str]] = None,
    suffix: Optional[List[str]] = None,
    max_depth: Optional[int] = None,
    limit: int = 100,
    offset: int = 0,
) -> ListNamespaceResponse:
    """List namespaces with optional match conditions.

    Args:
        prefix: Optional list of strings representing the prefix to filter namespaces.
        suffix: Optional list of strings representing the suffix to filter namespaces.
        max_depth: Optional integer specifying the maximum depth of namespaces to return.
        limit: Maximum number of namespaces to return (default is 100).
        offset: Number of namespaces to skip before returning results (default is 0).

    Returns:
        List[List[str]]: A list of namespaces matching the criteria.

    Example Usage:

        namespaces = client.store.list_namespaces(
            prefix=["documents"],
            max_depth=3,
            limit=10,
            offset=0
        )
        print(namespaces)

        ----------------------------------------------------------------

        [
            ["documents", "user123", "reports"],
            ["documents", "user456", "invoices"],
            ...
        ]
    """
    payload = {
        "prefix": prefix,
        "suffix": suffix,
        "max_depth": max_depth,
        "limit": limit,
        "offset": offset,
    }
    return self.http.post("/store/namespaces", json=_provided_vals(payload))

get_headers(api_key: Optional[str], custom_headers: Optional[dict[str, str]]) -> dict[str, str]

Combine api_key and custom user-provided headers.

Source code in libs/sdk-py/langgraph_sdk/client.py
def get_headers(
    api_key: Optional[str], custom_headers: Optional[dict[str, str]]
) -> dict[str, str]:
    """Combine api_key and custom user-provided headers."""
    custom_headers = custom_headers or {}
    for header in RESERVED_HEADERS:
        if header in custom_headers:
            raise ValueError(f"Cannot set reserved header '{header}'")

    headers = {
        "User-Agent": f"langgraph-sdk-py/{langgraph_sdk.__version__}",
        **custom_headers,
    }
    api_key = _get_api_key(api_key)
    if api_key:
        headers["x-api-key"] = api_key

    return headers

get_client(*, url: Optional[str] = None, api_key: Optional[str] = None, headers: Optional[dict[str, str]] = None) -> LangGraphClient

Get a LangGraphClient instance.

Parameters:

  • url (Optional[str], default: None ) –

    The URL of the LangGraph API.

  • api_key (Optional[str], default: None ) –

    The API key. If not provided, it will be read from the environment. Precedence: 1. explicit argument 2. LANGGRAPH_API_KEY 3. LANGSMITH_API_KEY 4. LANGCHAIN_API_KEY

  • headers (Optional[dict[str, str]], default: None ) –

    Optional custom headers

Returns:

  • LangGraphClient ( LangGraphClient ) –

    The top-level client for accessing AssistantsClient,

  • LangGraphClient

    ThreadsClient, RunsClient, and CronClient.

Example:

from langgraph_sdk import get_client

# get top-level LangGraphClient
client = get_client(url="http://localhost:8123")

# example usage: client.<model>.<method_name>()
assistants = await client.assistants.get(assistant_id="some_uuid")
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_client(
    *,
    url: Optional[str] = None,
    api_key: Optional[str] = None,
    headers: Optional[dict[str, str]] = None,
) -> LangGraphClient:
    """Get a LangGraphClient instance.

    Args:
        url: The URL of the LangGraph API.
        api_key: The API key. If not provided, it will be read from the environment.
            Precedence:
                1. explicit argument
                2. LANGGRAPH_API_KEY
                3. LANGSMITH_API_KEY
                4. LANGCHAIN_API_KEY
        headers: Optional custom headers

    Returns:
        LangGraphClient: The top-level client for accessing AssistantsClient,
        ThreadsClient, RunsClient, and CronClient.

    Example:

        from langgraph_sdk import get_client

        # get top-level LangGraphClient
        client = get_client(url="http://localhost:8123")

        # example usage: client.<model>.<method_name>()
        assistants = await client.assistants.get(assistant_id="some_uuid")
    """
    transport: Optional[httpx.AsyncBaseTransport] = None
    if url is None:
        try:
            from langgraph_api.server import app  # type: ignore

            url = "http://api"
            transport = httpx.ASGITransport(app, root_path="/noauth")
        except Exception:
            url = "http://localhost:8123"

    if transport is None:
        transport = httpx.AsyncHTTPTransport(retries=5)

    client = httpx.AsyncClient(
        base_url=url,
        transport=transport,
        timeout=httpx.Timeout(connect=5, read=300, write=300, pool=5),
        headers=get_headers(api_key, headers),
    )
    return LangGraphClient(client)

get_sync_client(*, url: Optional[str] = None, api_key: Optional[str] = None, headers: Optional[dict[str, str]] = None) -> SyncLangGraphClient

Get a synchronous LangGraphClient instance.

Parameters:

  • url (Optional[str], default: None ) –

    The URL of the LangGraph API.

  • api_key (Optional[str], default: None ) –

    The API key. If not provided, it will be read from the environment. Precedence: 1. explicit argument 2. LANGGRAPH_API_KEY 3. LANGSMITH_API_KEY 4. LANGCHAIN_API_KEY

  • headers (Optional[dict[str, str]], default: None ) –

    Optional custom headers

Returns: SyncLangGraphClient: The top-level synchronous client for accessing AssistantsClient, ThreadsClient, RunsClient, and CronClient.

Example:

from langgraph_sdk import get_sync_client

# get top-level synchronous LangGraphClient
client = get_sync_client(url="http://localhost:8123")

# example usage: client.<model>.<method_name>()
assistant = client.assistants.get(assistant_id="some_uuid")
Source code in libs/sdk-py/langgraph_sdk/client.py
def get_sync_client(
    *,
    url: Optional[str] = None,
    api_key: Optional[str] = None,
    headers: Optional[dict[str, str]] = None,
) -> SyncLangGraphClient:
    """Get a synchronous LangGraphClient instance.

    Args:
        url: The URL of the LangGraph API.
        api_key: The API key. If not provided, it will be read from the environment.
            Precedence:
                1. explicit argument
                2. LANGGRAPH_API_KEY
                3. LANGSMITH_API_KEY
                4. LANGCHAIN_API_KEY
        headers: Optional custom headers
    Returns:
        SyncLangGraphClient: The top-level synchronous client for accessing AssistantsClient,
        ThreadsClient, RunsClient, and CronClient.

    Example:

        from langgraph_sdk import get_sync_client

        # get top-level synchronous LangGraphClient
        client = get_sync_client(url="http://localhost:8123")

        # example usage: client.<model>.<method_name>()
        assistant = client.assistants.get(assistant_id="some_uuid")
    """

    if url is None:
        url = "http://localhost:8123"

    transport = httpx.HTTPTransport(retries=5)
    client = httpx.Client(
        base_url=url,
        transport=transport,
        timeout=httpx.Timeout(connect=5, read=300, write=300, pool=5),
        headers=get_headers(api_key, headers),
    )
    return SyncLangGraphClient(client)

Data models for interacting with the LangGraph API.

Json = Optional[dict[str, Any]] module-attribute

Represents a JSON-like structure, which can be None or a dictionary with string keys and any values.

RunStatus = Literal['pending', 'error', 'success', 'timeout', 'interrupted'] module-attribute

Represents the status of a run: - "pending": The run is waiting to start. - "error": The run encountered an error and stopped. - "success": The run completed successfully. - "timeout": The run exceeded its time limit. - "interrupted": The run was manually stopped or interrupted.

ThreadStatus = Literal['idle', 'busy', 'interrupted', 'error'] module-attribute

Represents the status of a thread: - "idle": The thread is not currently processing any task. - "busy": The thread is actively processing a task. - "interrupted": The thread's execution was interrupted. - "error": An exception occurred during task processing.

StreamMode = Literal['values', 'messages', 'updates', 'events', 'debug', 'custom', 'messages-tuple'] module-attribute

Defines the mode of streaming: - "values": Stream only the values. - "messages": Stream complete messages. - "updates": Stream updates to the state. - "events": Stream events occurring during execution. - "debug": Stream detailed debug information. - "custom": Stream custom events.

DisconnectMode = Literal['cancel', 'continue'] module-attribute

Specifies behavior on disconnection: - "cancel": Cancel the operation on disconnection. - "continue": Continue the operation even if disconnected.

MultitaskStrategy = Literal['reject', 'interrupt', 'rollback', 'enqueue'] module-attribute

Defines how to handle multiple tasks: - "reject": Reject new tasks when busy. - "interrupt": Interrupt current task for new ones. - "rollback": Roll back current task and start new one. - "enqueue": Queue new tasks for later execution.

OnConflictBehavior = Literal['raise', 'do_nothing'] module-attribute

Specifies behavior on conflict: - "raise": Raise an exception when a conflict occurs. - "do_nothing": Ignore conflicts and proceed.

OnCompletionBehavior = Literal['delete', 'keep'] module-attribute

Defines action after completion: - "delete": Delete resources after completion. - "keep": Retain resources after completion.

All = Literal['*'] module-attribute

Represents a wildcard or 'all' selector.

IfNotExists = Literal['create', 'reject'] module-attribute

Specifies behavior if the thread doesn't exist: - "create": Create a new thread if it doesn't exist. - "reject": Reject the operation if the thread doesn't exist.

CancelAction = Literal['interrupt', 'rollback'] module-attribute

Action to take when cancelling the run. - "interrupt": Simply cancel the run. - "rollback": Cancel the run. Then delete the run and associated checkpoints.

Config

Bases: TypedDict

Configuration options for a call.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Config(TypedDict, total=False):
    """Configuration options for a call."""

    tags: list[str]
    """
    Tags for this call and any sub-calls (eg. a Chain calling an LLM).
    You can use these to filter calls.
    """

    recursion_limit: int
    """
    Maximum number of times a call can recurse. If not provided, defaults to 25.
    """

    configurable: dict[str, Any]
    """
    Runtime values for attributes previously made configurable on this Runnable,
    or sub-Runnables, through .configurable_fields() or .configurable_alternatives().
    Check .output_schema() for a description of the attributes that have been made 
    configurable.
    """

tags: list[str] instance-attribute

Tags for this call and any sub-calls (eg. a Chain calling an LLM). You can use these to filter calls.

recursion_limit: int instance-attribute

Maximum number of times a call can recurse. If not provided, defaults to 25.

configurable: dict[str, Any] instance-attribute

Runtime values for attributes previously made configurable on this Runnable, or sub-Runnables, through .configurable_fields() or .configurable_alternatives(). Check .output_schema() for a description of the attributes that have been made configurable.

Checkpoint

Bases: TypedDict

Represents a checkpoint in the execution process.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Checkpoint(TypedDict):
    """Represents a checkpoint in the execution process."""

    thread_id: str
    """Unique identifier for the thread associated with this checkpoint."""
    checkpoint_ns: str
    """Namespace for the checkpoint, used for organization and retrieval."""
    checkpoint_id: Optional[str]
    """Optional unique identifier for the checkpoint itself."""
    checkpoint_map: Optional[dict[str, Any]]
    """Optional dictionary containing checkpoint-specific data."""

thread_id: str instance-attribute

Unique identifier for the thread associated with this checkpoint.

checkpoint_ns: str instance-attribute

Namespace for the checkpoint, used for organization and retrieval.

checkpoint_id: Optional[str] instance-attribute

Optional unique identifier for the checkpoint itself.

checkpoint_map: Optional[dict[str, Any]] instance-attribute

Optional dictionary containing checkpoint-specific data.

GraphSchema

Bases: TypedDict

Defines the structure and properties of a graph.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class GraphSchema(TypedDict):
    """Defines the structure and properties of a graph."""

    graph_id: str
    """The ID of the graph."""
    input_schema: Optional[dict]
    """The schema for the graph input.
    Missing if unable to generate JSON schema from graph."""
    output_schema: Optional[dict]
    """The schema for the graph output.
    Missing if unable to generate JSON schema from graph."""
    state_schema: Optional[dict]
    """The schema for the graph state.
    Missing if unable to generate JSON schema from graph."""
    config_schema: Optional[dict]
    """The schema for the graph config.
    Missing if unable to generate JSON schema from graph."""

graph_id: str instance-attribute

The ID of the graph.

input_schema: Optional[dict] instance-attribute

The schema for the graph input. Missing if unable to generate JSON schema from graph.

output_schema: Optional[dict] instance-attribute

The schema for the graph output. Missing if unable to generate JSON schema from graph.

state_schema: Optional[dict] instance-attribute

The schema for the graph state. Missing if unable to generate JSON schema from graph.

config_schema: Optional[dict] instance-attribute

The schema for the graph config. Missing if unable to generate JSON schema from graph.

AssistantBase

Bases: TypedDict

Base model for an assistant.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class AssistantBase(TypedDict):
    """Base model for an assistant."""

    assistant_id: str
    """The ID of the assistant."""
    graph_id: str
    """The ID of the graph."""
    config: Config
    """The assistant config."""
    created_at: datetime
    """The time the assistant was created."""
    metadata: Json
    """The assistant metadata."""
    version: int
    """The version of the assistant"""

assistant_id: str instance-attribute

The ID of the assistant.

graph_id: str instance-attribute

The ID of the graph.

config: Config instance-attribute

The assistant config.

created_at: datetime instance-attribute

The time the assistant was created.

metadata: Json instance-attribute

The assistant metadata.

version: int instance-attribute

The version of the assistant

AssistantVersion

Bases: AssistantBase

Represents a specific version of an assistant.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class AssistantVersion(AssistantBase):
    """Represents a specific version of an assistant."""

    pass

assistant_id: str instance-attribute

The ID of the assistant.

graph_id: str instance-attribute

The ID of the graph.

config: Config instance-attribute

The assistant config.

created_at: datetime instance-attribute

The time the assistant was created.

metadata: Json instance-attribute

The assistant metadata.

version: int instance-attribute

The version of the assistant

Assistant

Bases: AssistantBase

Represents an assistant with additional properties.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Assistant(AssistantBase):
    """Represents an assistant with additional properties."""

    updated_at: datetime
    """The last time the assistant was updated."""
    name: str
    """The name of the assistant"""

assistant_id: str instance-attribute

The ID of the assistant.

graph_id: str instance-attribute

The ID of the graph.

config: Config instance-attribute

The assistant config.

created_at: datetime instance-attribute

The time the assistant was created.

metadata: Json instance-attribute

The assistant metadata.

version: int instance-attribute

The version of the assistant

updated_at: datetime instance-attribute

The last time the assistant was updated.

name: str instance-attribute

The name of the assistant

Thread

Bases: TypedDict

Represents a conversation thread.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Thread(TypedDict):
    """Represents a conversation thread."""

    thread_id: str
    """The ID of the thread."""
    created_at: datetime
    """The time the thread was created."""
    updated_at: datetime
    """The last time the thread was updated."""
    metadata: Json
    """The thread metadata."""
    status: ThreadStatus
    """The status of the thread, one of 'idle', 'busy', 'interrupted'."""
    values: Json
    """The current state of the thread."""

thread_id: str instance-attribute

The ID of the thread.

created_at: datetime instance-attribute

The time the thread was created.

updated_at: datetime instance-attribute

The last time the thread was updated.

metadata: Json instance-attribute

The thread metadata.

status: ThreadStatus instance-attribute

The status of the thread, one of 'idle', 'busy', 'interrupted'.

values: Json instance-attribute

The current state of the thread.

ThreadTask

Bases: TypedDict

Represents a task within a thread.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class ThreadTask(TypedDict):
    """Represents a task within a thread."""

    id: str
    name: str
    error: Optional[str]
    interrupts: list[dict]
    checkpoint: Optional[Checkpoint]
    state: Optional["ThreadState"]
    result: Optional[dict[str, Any]]

ThreadState

Bases: TypedDict

Represents the state of a thread.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class ThreadState(TypedDict):
    """Represents the state of a thread."""

    values: Union[list[dict], dict[str, Any]]
    """The state values."""
    next: Sequence[str]
    """The next nodes to execute. If empty, the thread is done until new input is 
    received."""
    checkpoint: Checkpoint
    """The ID of the checkpoint."""
    metadata: Json
    """Metadata for this state"""
    created_at: Optional[str]
    """Timestamp of state creation"""
    parent_checkpoint: Optional[Checkpoint]
    """The ID of the parent checkpoint. If missing, this is the root checkpoint."""
    tasks: Sequence[ThreadTask]
    """Tasks to execute in this step. If already attempted, may contain an error."""

values: Union[list[dict], dict[str, Any]] instance-attribute

The state values.

next: Sequence[str] instance-attribute

The next nodes to execute. If empty, the thread is done until new input is received.

checkpoint: Checkpoint instance-attribute

The ID of the checkpoint.

metadata: Json instance-attribute

Metadata for this state

created_at: Optional[str] instance-attribute

Timestamp of state creation

parent_checkpoint: Optional[Checkpoint] instance-attribute

The ID of the parent checkpoint. If missing, this is the root checkpoint.

tasks: Sequence[ThreadTask] instance-attribute

Tasks to execute in this step. If already attempted, may contain an error.

ThreadUpdateStateResponse

Bases: TypedDict

Represents the response from updating a thread's state.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class ThreadUpdateStateResponse(TypedDict):
    """Represents the response from updating a thread's state."""

    checkpoint: Checkpoint
    """Checkpoint of the latest state."""

checkpoint: Checkpoint instance-attribute

Checkpoint of the latest state.

Run

Bases: TypedDict

Represents a single execution run.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Run(TypedDict):
    """Represents a single execution run."""

    run_id: str
    """The ID of the run."""
    thread_id: str
    """The ID of the thread."""
    assistant_id: str
    """The assistant that was used for this run."""
    created_at: datetime
    """The time the run was created."""
    updated_at: datetime
    """The last time the run was updated."""
    status: RunStatus
    """The status of the run. One of 'pending', 'running', "error", 'success', "timeout", "interrupted"."""
    metadata: Json
    """The run metadata."""
    multitask_strategy: MultitaskStrategy
    """Strategy to handle concurrent runs on the same thread."""

run_id: str instance-attribute

The ID of the run.

thread_id: str instance-attribute

The ID of the thread.

assistant_id: str instance-attribute

The assistant that was used for this run.

created_at: datetime instance-attribute

The time the run was created.

updated_at: datetime instance-attribute

The last time the run was updated.

status: RunStatus instance-attribute

The status of the run. One of 'pending', 'running', "error", 'success', "timeout", "interrupted".

metadata: Json instance-attribute

The run metadata.

multitask_strategy: MultitaskStrategy instance-attribute

Strategy to handle concurrent runs on the same thread.

Cron

Bases: TypedDict

Represents a scheduled task.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Cron(TypedDict):
    """Represents a scheduled task."""

    cron_id: str
    """The ID of the cron."""
    thread_id: Optional[str]
    """The ID of the thread."""
    end_time: Optional[datetime]
    """The end date to stop running the cron."""
    schedule: str
    """The schedule to run, cron format."""
    created_at: datetime
    """The time the cron was created."""
    updated_at: datetime
    """The last time the cron was updated."""
    payload: dict
    """The run payload to use for creating new run."""

cron_id: str instance-attribute

The ID of the cron.

thread_id: Optional[str] instance-attribute

The ID of the thread.

end_time: Optional[datetime] instance-attribute

The end date to stop running the cron.

schedule: str instance-attribute

The schedule to run, cron format.

created_at: datetime instance-attribute

The time the cron was created.

updated_at: datetime instance-attribute

The last time the cron was updated.

payload: dict instance-attribute

The run payload to use for creating new run.

RunCreate

Bases: TypedDict

Defines the parameters for initiating a background run.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class RunCreate(TypedDict):
    """Defines the parameters for initiating a background run."""

    thread_id: Optional[str]
    """The identifier of the thread to run. If not provided, the run is stateless."""
    assistant_id: str
    """The identifier of the assistant to use for this run."""
    input: Optional[dict]
    """Initial input data for the run."""
    metadata: Optional[dict]
    """Additional metadata to associate with the run."""
    config: Optional[Config]
    """Configuration options for the run."""
    checkpoint_id: Optional[str]
    """The identifier of a checkpoint to resume from."""
    interrupt_before: Optional[list[str]]
    """List of node names to interrupt execution before."""
    interrupt_after: Optional[list[str]]
    """List of node names to interrupt execution after."""
    webhook: Optional[str]
    """URL to send webhook notifications about the run's progress."""
    multitask_strategy: Optional[MultitaskStrategy]
    """Strategy for handling concurrent runs on the same thread."""

thread_id: Optional[str] instance-attribute

The identifier of the thread to run. If not provided, the run is stateless.

assistant_id: str instance-attribute

The identifier of the assistant to use for this run.

input: Optional[dict] instance-attribute

Initial input data for the run.

metadata: Optional[dict] instance-attribute

Additional metadata to associate with the run.

config: Optional[Config] instance-attribute

Configuration options for the run.

checkpoint_id: Optional[str] instance-attribute

The identifier of a checkpoint to resume from.

interrupt_before: Optional[list[str]] instance-attribute

List of node names to interrupt execution before.

interrupt_after: Optional[list[str]] instance-attribute

List of node names to interrupt execution after.

webhook: Optional[str] instance-attribute

URL to send webhook notifications about the run's progress.

multitask_strategy: Optional[MultitaskStrategy] instance-attribute

Strategy for handling concurrent runs on the same thread.

Item

Bases: TypedDict

Represents a single document or data entry in the graph's Store.

Items are used to store cross-thread memories.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class Item(TypedDict):
    """Represents a single document or data entry in the graph's Store.

    Items are used to store cross-thread memories.
    """

    namespace: list[str]
    """The namespace of the item. A namespace is analogous to a document's directory."""
    key: str
    """The unique identifier of the item within its namespace.

    In general, keys needn't be globally unique.
    """
    value: dict[str, Any]
    """The value stored in the item. This is the document itself."""
    created_at: datetime
    """The timestamp when the item was created."""
    updated_at: datetime
    """The timestamp when the item was last updated."""

namespace: list[str] instance-attribute

The namespace of the item. A namespace is analogous to a document's directory.

key: str instance-attribute

The unique identifier of the item within its namespace.

In general, keys needn't be globally unique.

value: dict[str, Any] instance-attribute

The value stored in the item. This is the document itself.

created_at: datetime instance-attribute

The timestamp when the item was created.

updated_at: datetime instance-attribute

The timestamp when the item was last updated.

ListNamespaceResponse

Bases: TypedDict

Response structure for listing namespaces.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class ListNamespaceResponse(TypedDict):
    """Response structure for listing namespaces."""

    namespaces: list[list[str]]
    """A list of namespace paths, where each path is a list of strings."""

namespaces: list[list[str]] instance-attribute

A list of namespace paths, where each path is a list of strings.

SearchItemsResponse

Bases: TypedDict

Response structure for searching items.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class SearchItemsResponse(TypedDict):
    """Response structure for searching items."""

    items: list[Item]
    """A list of items matching the search criteria."""

items: list[Item] instance-attribute

A list of items matching the search criteria.

StreamPart

Bases: NamedTuple

Represents a part of a stream response.

Source code in libs/sdk-py/langgraph_sdk/schema.py
class StreamPart(NamedTuple):
    """Represents a part of a stream response."""

    event: str
    """The type of event for this stream part."""
    data: dict
    """The data payload associated with the event."""

event: str instance-attribute

The type of event for this stream part.

data: dict instance-attribute

The data payload associated with the event.

Comments