- Spec files
pypi-langgraph-sdk
Describes: pkg:pypi/langgraph-sdk@0.2.x
- Description
- Python SDK for interacting with the LangGraph Platform REST API to build and manage AI assistants and conversational workflows
- Author
- tessl
- Last updated
thread-management.md docs/
1# Thread Management23Manage conversation threads that maintain state across multiple interactions. Threads provide isolation for conversations and support state inspection, updates, and history tracking.45## Capabilities67### Thread CRUD Operations89Core operations for creating, reading, updating, and deleting conversation threads with metadata and configuration support.1011```python { .api }12from collections.abc import Mapping, Sequence13from typing import Any14from langgraph_sdk.schema import (15Thread, ThreadSelectField, Json, OnConflictBehavior, QueryParamTypes16)1718# Via client.threads19async def create(20*,21metadata: Json = None,22thread_id: str | None = None,23if_exists: OnConflictBehavior | None = None,24supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,25graph_id: str | None = None,26ttl: int | Mapping[str, Any] | None = None,27headers: Mapping[str, str] | None = None,28params: QueryParamTypes | None = None,29) -> Thread:30"""31Create a thread.3233Args:34metadata: Metadata to merge with the thread.35thread_id: ID of the thread. If None, ID will be a UUID.36if_exists: How to handle duplicate creates. Defaults to "create".37supersteps: Optional supersteps to apply to the thread.38graph_id: Optional graph_id to apply to the thread.39ttl: Metadata key-value pairs to be used to configure the thread's time-to-live.40headers: Optional custom headers to include with the request.41params: Optional query parameters to include with the request.4243Returns:44Thread: The created thread.45"""4647async def get(48thread_id: str,49*,50select: list[ThreadSelectField] | None = None,51headers: Mapping[str, str] | None = None,52params: QueryParamTypes | None = None,53) -> Thread:54"""55Get a thread by ID.5657Args:58thread_id: The ID of the thread to get.59select: Fields to include in the response.60headers: Optional custom headers to include with the request.61params: Optional query parameters to include with the request.6263Returns:64Thread: Thread object.65"""6667async def update(68thread_id: str,69*,70metadata: Mapping[str, Any],71ttl: int | Mapping[str, Any] | None = None,72headers: Mapping[str, str] | None = None,73params: QueryParamTypes | None = None,74) -> Thread:75"""76Update a thread.7778Args:79thread_id: ID of the thread to update.80metadata: Metadata to merge with the thread.81ttl: Time-to-live configuration for the thread.82headers: Optional custom headers to include with the request.83params: Optional query parameters to include with the request.8485Returns:86Thread: The updated thread.87"""8889async def delete(90thread_id: str,91*,92headers: Mapping[str, str] | None = None,93params: QueryParamTypes | None = None,94) -> None:95"""96Delete a thread.9798Args:99thread_id: The ID of the thread to delete.100headers: Optional custom headers to include with the request.101params: Optional query parameters to include with the request.102"""103```104105### Thread Discovery & Search106107Search and enumerate threads with filtering, pagination, and sorting capabilities.108109```python { .api }110from langgraph_sdk.schema import (111Thread, ThreadSelectField, ThreadSortBy, ThreadStatus, SortOrder,112Json, QueryParamTypes113)114115async def search(116*,117metadata: Json = None,118values: Json = None,119ids: Sequence[str] | None = None,120status: ThreadStatus | None = None,121limit: int = 10,122offset: int = 0,123sort_by: ThreadSortBy | None = None,124sort_order: SortOrder | None = None,125select: list[ThreadSelectField] | None = None,126headers: Mapping[str, str] | None = None,127params: QueryParamTypes | None = None,128) -> list[Thread]:129"""130Search for threads.131132Args:133metadata: Metadata to filter by. Exact match filter for each KV pair.134values: Values to filter by. Exact match filter for each KV pair.135ids: Thread IDs to filter by.136status: Status to filter by.137limit: Limit the number of threads to return.138offset: Offset to start from.139sort_by: Field to sort by.140sort_order: Order to sort by.141select: Fields to include in the response.142headers: Optional custom headers to include with the request.143params: Optional query parameters to include with the request.144145Returns:146list[Thread]: List of threads matching the query.147"""148149async def count(150*,151metadata: Json = None,152values: Json = None,153status: ThreadStatus | None = None,154headers: Mapping[str, str] | None = None,155params: QueryParamTypes | None = None,156) -> int:157"""158Count threads.159160Args:161metadata: Metadata to filter by. Exact match filter for each KV pair.162values: Values to filter by. Exact match filter for each KV pair.163status: Status to filter by.164headers: Optional custom headers to include with the request.165params: Optional query parameters to include with the request.166167Returns:168int: Number of threads that match the query.169"""170```171172### Thread Operations173174Advanced thread operations including copying, state management, and history tracking.175176```python { .api }177async def copy(178thread_id: str,179*,180headers: Mapping[str, str] | None = None,181params: QueryParamTypes | None = None,182) -> None:183"""184Copy a thread.185186Args:187thread_id: The ID of the thread to copy.188headers: Optional custom headers to include with the request.189params: Optional query parameters to include with the request.190"""191```192193### State Management194195Inspect and manipulate thread state, including current values, checkpoints, and state updates.196197```python { .api }198from langgraph_sdk.schema import (199ThreadState, ThreadUpdateStateResponse, Checkpoint, QueryParamTypes200)201202async def get_state(203thread_id: str,204*,205checkpoint: Checkpoint | None = None,206checkpoint_id: str | None = None, # deprecated207subgraphs: bool = False,208headers: Mapping[str, str] | None = None,209params: QueryParamTypes | None = None,210) -> ThreadState:211"""212Get state for a thread.213214Args:215thread_id: The ID of the thread to get the state for.216checkpoint: The checkpoint to get the state for.217checkpoint_id: Checkpoint to get the state for. Deprecated, use checkpoint instead.218subgraphs: Whether to include subgraphs.219headers: Optional custom headers to include with the request.220params: Optional query parameters to include with the request.221222Returns:223ThreadState: The thread of the state.224"""225226async def update_state(227thread_id: str,228values: dict[str, Any] | Sequence[dict] | None,229*,230as_node: str | None = None,231checkpoint: Checkpoint | None = None,232checkpoint_id: str | None = None, # deprecated233headers: Mapping[str, str] | None = None,234params: QueryParamTypes | None = None,235) -> ThreadUpdateStateResponse:236"""237Update state for a thread.238239Args:240thread_id: The ID of the thread to update.241values: The values to update the state with.242as_node: The node to update the state as.243checkpoint: The checkpoint to update the state for.244checkpoint_id: Checkpoint to update the state for. Deprecated, use checkpoint instead.245headers: Optional custom headers to include with the request.246params: Optional query parameters to include with the request.247248Returns:249ThreadUpdateStateResponse: The response from updating the thread state.250"""251252async def get_history(253thread_id: str,254*,255limit: int = 10,256before: str | Checkpoint | None = None,257metadata: Mapping[str, Any] | None = None,258checkpoint: Checkpoint | None = None,259headers: Mapping[str, str] | None = None,260params: QueryParamTypes | None = None,261) -> list[ThreadState]:262"""263Get the state history of a thread.264265Args:266thread_id: The ID of the thread to get the state history for.267checkpoint: Return states for this subgraph. If empty defaults to root.268before: Return states before this checkpoint.269limit: The number of states to return.270metadata: Metadata to filter by.271headers: Optional custom headers to include with the request.272params: Optional query parameters to include with the request.273274Returns:275list[ThreadState]: The state history for the thread.276"""277```278279### Thread Streaming280281Real-time streaming of thread events and state changes.282283```python { .api }284from collections.abc import AsyncIterator, Sequence285from langgraph_sdk.schema import StreamPart, ThreadStreamMode, QueryParamTypes286287async def join_stream(288thread_id: str,289*,290last_event_id: str | None = None,291stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",292headers: Mapping[str, str] | None = None,293params: QueryParamTypes | None = None,294) -> AsyncIterator[StreamPart]:295"""296Get a stream of events for a thread.297298Args:299thread_id: The ID of the thread to get the stream for.300last_event_id: The ID of the last event to get.301stream_mode: The mode of the stream.302headers: Optional custom headers to include with the request.303params: Optional query parameters to include with the request.304305Returns:306AsyncIterator[StreamPart]: A stream of events for the thread.307"""308```309310## Types311312```python { .api }313class Thread(TypedDict):314"""Thread definition and status."""315thread_id: str316created_at: str317updated_at: str318metadata: dict319status: ThreadStatus320config: Config321322class ThreadState(TypedDict):323"""Thread execution state."""324values: dict325next: list[str]326checkpoint: Checkpoint327metadata: dict328created_at: str329parent_checkpoint: Checkpoint330331class ThreadUpdateStateResponse(TypedDict):332"""Response from state update operation."""333checkpoint: Checkpoint334status: str335336class Checkpoint(TypedDict):337"""Execution checkpoint reference."""338thread_id: str339checkpoint_ns: str340checkpoint_id: str341342ThreadStatus = Literal["idle", "busy", "interrupted", "error"]343344ThreadStreamMode = Literal["run_modes", "lifecycle", "state_update"]345346ThreadSelectField = Literal[347"thread_id", "created_at", "updated_at", "metadata", "status", "config"348]349350ThreadSortBy = Literal["created_at", "updated_at", "thread_id"]351```352353## Usage Examples354355### Creating and Managing Threads356357```python358# Create a new thread with metadata359thread = await client.threads.create(360metadata={"user_id": "user-123", "session_type": "chat"}361)362363# Get thread details364thread = await client.threads.get("thread-456")365366# Update thread metadata367updated = await client.threads.update(368"thread-456",369metadata={"last_interaction": "2023-12-01T10:30:00Z"}370)371```372373### Thread Discovery374375```python376# Search threads by user377user_threads = await client.threads.search(378metadata={"user_id": "user-123"},379status="idle",380limit=20381)382383# Get active threads384active_threads = await client.threads.search(385status="busy",386sort_by="updated_at"387)388389# Count total threads390total = await client.threads.count()391```392393### State Management394395```python396# Get current thread state397state = await client.threads.get_state("thread-456")398print(f"Current state: {state['values']}")399400# Update thread state401response = await client.threads.update_state(402"thread-456",403values={"user_preferences": {"theme": "dark"}},404as_node="preference_manager"405)406407# Get thread execution history408history = await client.threads.get_history("thread-456", limit=50)409for checkpoint in history:410print(f"Checkpoint {checkpoint['checkpoint']['checkpoint_id']}: {checkpoint['values']}")411```412413### Thread Operations414415```python416# Copy a thread417copied = await client.threads.copy(418"thread-456",419metadata={"source_thread": "thread-456", "copy_reason": "backup"}420)421422# Stream thread events423async for event in client.threads.join_stream("thread-456", mode="state_update"):424print(f"Thread event: {event}")425```426427### Thread Lifecycle428429```python430# Create, use, and cleanup431thread = await client.threads.create(metadata={"purpose": "temp-calculation"})432433# ... perform operations ...434435# Delete when done436await client.threads.delete(thread["thread_id"])437```