or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

assistants.mdauth.mdclient.mdcrons.mdindex.mdreact.mdruns.mdstore.mdthreads.md

threads.mddocs/

0

# Threads Management

1

2

The ThreadsClient provides comprehensive thread lifecycle management for conversation handling, state management, and history tracking in LangGraph applications. Threads represent conversation sessions that maintain state across multiple run executions, enabling persistent conversational experiences with full state management capabilities.

3

4

## Core Functionality

5

6

The ThreadsClient supports:

7

8

- **Thread Lifecycle**: Create, get, update, delete, and copy thread operations

9

- **State Management**: Get, update, and patch thread state with checkpoint support

10

- **History Tracking**: Access complete thread state history across all checkpoints

11

- **Search Operations**: Find threads using flexible search criteria

12

- **Type Safety**: Full TypeScript support with generic state types

13

14

## ThreadsClient API

15

16

```typescript { .api }

17

class ThreadsClient<TStateType = DefaultValues, TUpdateType = TStateType> extends BaseClient {

18

/**

19

* Get thread by ID with optional type parameter for state values

20

* @param threadId - Unique thread identifier

21

* @returns Promise resolving to thread with typed values

22

*/

23

get<ValuesType = TStateType>(threadId: string): Promise<Thread<ValuesType>>;

24

25

/**

26

* Create a new thread with optional configuration

27

* @param payload - Thread creation configuration

28

* @returns Promise resolving to newly created thread

29

*/

30

create(payload?: CreateThreadPayload): Promise<Thread<TStateType>>;

31

32

/**

33

* Copy an existing thread to create a new thread with same configuration

34

* @param threadId - Source thread ID to copy

35

* @returns Promise resolving to copied thread

36

*/

37

copy(threadId: string): Promise<Thread<TStateType>>;

38

39

/**

40

* Update thread metadata and configuration

41

* @param threadId - Thread ID to update

42

* @param payload - Update configuration

43

* @returns Promise resolving to updated thread

44

*/

45

update(threadId: string, payload?: UpdateThreadPayload): Promise<Thread>;

46

47

/**

48

* Delete thread permanently

49

* @param threadId - Thread ID to delete

50

* @returns Promise resolving when deletion completes

51

*/

52

delete(threadId: string): Promise<void>;

53

54

/**

55

* Search threads with flexible criteria and pagination

56

* @param query - Search parameters and filters

57

* @returns Promise resolving to array of matching threads

58

*/

59

search<ValuesType = TStateType>(query?: ThreadSearchQuery): Promise<Thread<ValuesType>[]>;

60

61

/**

62

* Get current thread state at specific checkpoint with optional subgraph data

63

* @param threadId - Thread ID

64

* @param checkpoint - Specific checkpoint ID or checkpoint object (optional)

65

* @param options - Additional options for subgraph inclusion

66

* @returns Promise resolving to thread state

67

*/

68

getState<ValuesType = TStateType>(

69

threadId: string,

70

checkpoint?: Checkpoint | string,

71

options?: { subgraphs?: boolean }

72

): Promise<ThreadState<ValuesType>>;

73

74

/**

75

* Update thread state with new values and configuration

76

* @param threadId - Thread ID to update

77

* @param options - State update configuration

78

* @returns Promise resolving to updated configuration

79

*/

80

updateState<ValuesType = TUpdateType>(

81

threadId: string,

82

options: UpdateStateOptions

83

): Promise<Pick<Config, "configurable">>;

84

85

/**

86

* Patch thread metadata without affecting state values

87

* @param threadIdOrConfig - Thread ID or full config object

88

* @param metadata - Metadata to patch

89

* @returns Promise resolving when patch completes

90

*/

91

patchState(threadIdOrConfig: string | Config, metadata: Metadata): Promise<void>;

92

93

/**

94

* Get complete thread state history across all checkpoints

95

* @param threadId - Thread ID

96

* @param options - History retrieval options

97

* @returns Promise resolving to array of historical states

98

*/

99

getHistory<ValuesType = TStateType>(

100

threadId: string,

101

options?: GetHistoryOptions

102

): Promise<ThreadState<ValuesType>[]>;

103

}

104

```

105

106

## Core Types

107

108

### Thread Interface

109

110

```typescript { .api }

111

interface Thread<ValuesType = DefaultValues> {

112

/** Unique thread identifier */

113

thread_id: string;

114

/** Thread creation timestamp */

115

created_at: string;

116

/** Thread last update timestamp */

117

updated_at: string;

118

/** Thread metadata for custom data */

119

metadata: Metadata;

120

/** Current thread status */

121

status: ThreadStatus;

122

/** Current thread state values */

123

values: ValuesType;

124

}

125

126

type ThreadStatus = "idle" | "busy" | "interrupted" | "error";

127

128

interface Metadata {

129

[key: string]: any;

130

}

131

```

132

133

### Thread State

134

135

```typescript { .api }

136

interface ThreadState<ValuesType = DefaultValues> {

137

/** Thread state values */

138

values: ValuesType;

139

/** Associated checkpoint information */

140

checkpoint: Checkpoint;

141

/** Thread metadata */

142

metadata: Metadata;

143

/** Thread creation timestamp */

144

created_at: string;

145

/** Parent checkpoint ID if applicable */

146

parent_checkpoint?: string | null;

147

/** Current thread tasks */

148

tasks: ThreadTask[];

149

}

150

151

interface Checkpoint {

152

/** Unique checkpoint identifier */

153

checkpoint_id: string;

154

/** Checkpoint thread ID */

155

thread_id: string;

156

/** Parent checkpoint ID */

157

parent_checkpoint_id?: string | null;

158

/** Checkpoint type */

159

type: "checkpoint";

160

/** Checkpoint metadata */

161

checkpoint: {

162

ts: string;

163

id: string;

164

version: number;

165

};

166

}

167

168

interface ThreadTask {

169

/** Task ID */

170

id: string;

171

/** Task name */

172

name: string;

173

/** Task path in execution graph */

174

path: string[];

175

/** Task error information if failed */

176

error?: string;

177

/** Task interrupts */

178

interrupts: Interrupt[];

179

}

180

```

181

182

## Payload Types

183

184

### Creation and Updates

185

186

```typescript { .api }

187

interface CreateThreadPayload {

188

/** Optional thread metadata */

189

metadata?: Metadata;

190

/** Initial thread state values */

191

values?: Record<string, any>;

192

/** If true, create as a copy of another thread */

193

if_exists?: "raise" | "do_nothing";

194

}

195

196

interface UpdateThreadPayload {

197

/** Updated thread metadata */

198

metadata?: Metadata;

199

/** Updated thread values */

200

values?: Record<string, any>;

201

}

202

203

interface UpdateStateOptions {

204

/** New state values to set */

205

values?: Record<string, any>;

206

/** Update configuration */

207

config?: Config;

208

/** Update mode configuration */

209

as_node?: string;

210

/** Interrupt configuration */

211

interrupt_after?: string[];

212

/** Interrupt before configuration */

213

interrupt_before?: string[];

214

}

215

```

216

217

### Search and History

218

219

```typescript { .api }

220

interface ThreadSearchQuery {

221

/** Metadata filters for search */

222

metadata?: Record<string, any>;

223

/** Thread status filter */

224

status?: ThreadStatus;

225

/** Pagination limit */

226

limit?: number;

227

/** Pagination offset */

228

offset?: number;

229

/** Created after timestamp filter */

230

created_after?: string;

231

/** Created before timestamp filter */

232

created_before?: string;

233

}

234

235

interface GetHistoryOptions {

236

/** Maximum number of historical states to return */

237

limit?: number;

238

/** Include checkpoint data */

239

checkpoints?: boolean;

240

/** Metadata filters */

241

metadata?: Record<string, any>;

242

/** Get history before specific checkpoint */

243

before?: Checkpoint | string;

244

/** Get history after specific checkpoint */

245

after?: Checkpoint | string;

246

}

247

```

248

249

## Usage Examples

250

251

### Basic Thread Operations

252

253

```typescript

254

import { Client } from "@langchain/langgraph-sdk";

255

256

const client = new Client({

257

apiUrl: "https://api.langgraph.example.com",

258

apiKey: "your-api-key"

259

});

260

261

// Create a new thread

262

const thread = await client.threads.create({

263

metadata: {

264

user_id: "user123",

265

conversation_type: "support"

266

},

267

values: {

268

messages: [],

269

context: "customer support session"

270

}

271

});

272

273

console.log("Created thread:", thread.thread_id);

274

275

// Get thread information

276

const retrievedThread = await client.threads.get(thread.thread_id);

277

console.log("Thread status:", retrievedThread.status);

278

console.log("Thread values:", retrievedThread.values);

279

280

// Update thread metadata

281

const updatedThread = await client.threads.update(thread.thread_id, {

282

metadata: {

283

...retrievedThread.metadata,

284

priority: "high",

285

last_activity: new Date().toISOString()

286

}

287

});

288

289

// Copy thread to create a duplicate

290

const copiedThread = await client.threads.copy(thread.thread_id);

291

console.log("Copied thread ID:", copiedThread.thread_id);

292

```

293

294

### State Management

295

296

```typescript

297

// Get current thread state

298

const state = await client.threads.getState(thread.thread_id);

299

console.log("Current values:", state.values);

300

console.log("Checkpoint:", state.checkpoint.checkpoint_id);

301

302

// Get state at specific checkpoint

303

const historicalState = await client.threads.getState(

304

thread.thread_id,

305

"checkpoint_abc123"

306

);

307

308

// Update thread state

309

await client.threads.updateState(thread.thread_id, {

310

values: {

311

messages: [

312

...state.values.messages,

313

{ role: "user", content: "Hello!" }

314

]

315

},

316

config: {

317

configurable: {

318

temperature: 0.7

319

}

320

}

321

});

322

323

// Patch thread metadata only

324

await client.threads.patchState(thread.thread_id, {

325

session_duration: "45m",

326

interaction_count: 12

327

});

328

```

329

330

### Search and History

331

332

```typescript

333

// Search threads with filters

334

const threads = await client.threads.search({

335

metadata: { user_id: "user123" },

336

status: "idle",

337

limit: 50,

338

created_after: "2024-01-01T00:00:00Z"

339

});

340

341

console.log(`Found ${threads.length} matching threads`);

342

343

// Get complete thread history

344

const history = await client.threads.getHistory(thread.thread_id, {

345

limit: 100,

346

checkpoints: true

347

});

348

349

console.log("Thread history:");

350

history.forEach((state, index) => {

351

console.log(`${index + 1}. Checkpoint: ${state.checkpoint.checkpoint_id}`);

352

console.log(` Created: ${state.created_at}`);

353

console.log(` Values: ${JSON.stringify(state.values, null, 2)}`);

354

});

355

356

// Get history within date range

357

const recentHistory = await client.threads.getHistory(thread.thread_id, {

358

limit: 20,

359

metadata: { interaction_type: "chat" },

360

after: "checkpoint_start123"

361

});

362

```

363

364

### Advanced State Operations

365

366

```typescript

367

interface CustomState {

368

messages: Array<{

369

role: string;

370

content: string;

371

timestamp: string;

372

}>;

373

user_context: {

374

preferences: Record<string, any>;

375

history: string[];

376

};

377

session_data: {

378

start_time: string;

379

activity_count: number;

380

};

381

}

382

383

// Create typed thread

384

const typedThread = await client.threads.create({

385

metadata: { type: "conversation" },

386

values: {

387

messages: [],

388

user_context: {

389

preferences: { theme: "dark", language: "en" },

390

history: []

391

},

392

session_data: {

393

start_time: new Date().toISOString(),

394

activity_count: 0

395

}

396

} as CustomState

397

});

398

399

// Get typed state

400

const typedState = await client.threads.getState<CustomState>(

401

typedThread.thread_id

402

);

403

404

// Update with type safety

405

await client.threads.updateState<CustomState>(typedThread.thread_id, {

406

values: {

407

messages: [

408

...typedState.values.messages,

409

{

410

role: "user",

411

content: "Hello!",

412

timestamp: new Date().toISOString()

413

}

414

],

415

session_data: {

416

...typedState.values.session_data,

417

activity_count: typedState.values.session_data.activity_count + 1

418

}

419

}

420

});

421

```

422

423

### Error Handling and Cleanup

424

425

```typescript

426

try {

427

// Attempt thread operations with error handling

428

const thread = await client.threads.create({

429

metadata: { user_id: "user456" },

430

if_exists: "raise" // Fail if thread already exists

431

});

432

433

// Perform operations...

434

const state = await client.threads.getState(thread.thread_id);

435

436

// Update state with validation

437

await client.threads.updateState(thread.thread_id, {

438

values: {

439

validated_data: true,

440

last_update: new Date().toISOString()

441

},

442

config: {

443

tags: ["validated", "active"]

444

}

445

});

446

447

} catch (error) {

448

console.error("Thread operation failed:", error);

449

450

// Handle specific error types

451

if (error.status === 404) {

452

console.log("Thread not found");

453

} else if (error.status === 409) {

454

console.log("Thread already exists");

455

}

456

} finally {

457

// Cleanup if needed

458

if (thread && thread.thread_id) {

459

// Optional: Delete thread after use

460

// await client.threads.delete(thread.thread_id);

461

}

462

}

463

```

464

465

The ThreadsClient provides complete thread management capabilities with type safety, comprehensive state handling, and flexible search operations, making it ideal for building conversational applications with persistent state management.