0
# Core Client API
1
2
The core Client API provides the foundation for all interactions with LangGraph API servers, including client configuration, authentication, and access to all resource-specific clients.
3
4
## Capabilities
5
6
### Client Class
7
8
The main Client class provides centralized access to all LangGraph resources and handles authentication, request management, and base configuration.
9
10
```typescript { .api }
11
/**
12
* Main LangGraph API client providing access to all LangGraph resources
13
* @template TStateType - Type of thread state values
14
* @template TUpdateType - Type of state updates
15
* @template TCustomEventType - Type of custom stream events
16
*/
17
class Client<
18
TStateType = DefaultValues,
19
TUpdateType = TStateType,
20
TCustomEventType = unknown
21
> {
22
/** Client for managing assistants */
23
assistants: AssistantsClient;
24
25
/** Client for managing threads */
26
threads: ThreadsClient<TStateType, TUpdateType>;
27
28
/** Client for managing runs */
29
runs: RunsClient<TStateType, TUpdateType, TCustomEventType>;
30
31
/** Client for managing scheduled cron jobs */
32
crons: CronsClient;
33
34
/** Client for key-value store operations */
35
store: StoreClient;
36
37
/**
38
* Create a new LangGraph client
39
* @param config - Optional client configuration
40
*/
41
constructor(config?: ClientConfig);
42
}
43
44
type DefaultValues = Record<string, any>;
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
import { Client } from "@langchain/langgraph-sdk";
51
52
// Basic client with default configuration
53
const client = new Client();
54
55
// Client with custom API endpoint and key
56
const client = new Client({
57
apiUrl: "https://api.langgraph.example.com",
58
apiKey: "your-api-key"
59
});
60
61
// Client with advanced configuration
62
const client = new Client({
63
apiUrl: "https://api.langgraph.example.com",
64
apiKey: "your-api-key",
65
timeoutMs: 30000,
66
defaultHeaders: {
67
"User-Agent": "MyApp/1.0"
68
},
69
callerOptions: {
70
maxRetries: 3,
71
maxConcurrency: 2
72
}
73
});
74
75
// Access resource clients
76
const assistant = await client.assistants.get("assistant-id");
77
const thread = await client.threads.create();
78
```
79
80
### Client Configuration
81
82
Configuration interface for customizing client behavior, authentication, and HTTP options.
83
84
```typescript { .api }
85
/**
86
* Configuration options for the LangGraph client
87
*/
88
interface ClientConfig {
89
/**
90
* API endpoint URL. Defaults to http://localhost:8123
91
* Remove trailing slash if present
92
*/
93
apiUrl?: string;
94
95
/**
96
* API authentication key. Can also be set via environment variables:
97
* LANGGRAPH_API_KEY, LANGSMITH_API_KEY, or LANGCHAIN_API_KEY
98
*/
99
apiKey?: string;
100
101
/** HTTP client configuration options */
102
callerOptions?: AsyncCallerParams;
103
104
/** Request timeout in milliseconds */
105
timeoutMs?: number;
106
107
/** Default headers to include with all requests */
108
defaultHeaders?: Record<string, string | undefined | null>;
109
110
/** Request interceptor function */
111
onRequest?: RequestHook;
112
}
113
114
/**
115
* Request interceptor hook for modifying requests before they are sent
116
* @param url - The request URL
117
* @param init - The request initialization options
118
* @returns Modified request initialization options
119
*/
120
type RequestHook = (url: URL, init: RequestInit) => Promise<RequestInit> | RequestInit;
121
122
/**
123
* HTTP client configuration options
124
*/
125
interface AsyncCallerParams {
126
/** Maximum number of retry attempts (default: 4) */
127
maxRetries?: number;
128
129
/** Maximum concurrent requests (default: 4) */
130
maxConcurrency?: number;
131
132
/** Custom fetch implementation */
133
fetch?: typeof fetch;
134
135
/** Callback for failed response handling */
136
onFailedResponseHook?: (response: Response, request: RequestInit) => void;
137
}
138
```
139
140
**Usage Examples:**
141
142
```typescript
143
import { Client } from "@langchain/langgraph-sdk";
144
145
// Client with request interceptor
146
const client = new Client({
147
apiUrl: "https://api.langgraph.example.com",
148
onRequest: async (url, init) => {
149
// Add custom headers or modify request
150
return {
151
...init,
152
headers: {
153
...init.headers,
154
"X-Request-ID": generateRequestId()
155
}
156
};
157
}
158
});
159
160
// Client with retry configuration
161
const client = new Client({
162
callerOptions: {
163
maxRetries: 5,
164
maxConcurrency: 10,
165
onFailedResponseHook: (response, request) => {
166
console.error(`Request failed: ${response.status}`);
167
}
168
}
169
});
170
```
171
172
### API Key Management
173
174
Utility function for resolving API keys from various sources with precedence order.
175
176
```typescript { .api }
177
/**
178
* Get the API key from environment variables with precedence order
179
* @param apiKey - Optional API key provided as an argument
180
* @returns The resolved API key or undefined if not found
181
*
182
* Precedence:
183
* 1. Explicit apiKey argument
184
* 2. LANGGRAPH_API_KEY environment variable
185
* 3. LANGSMITH_API_KEY environment variable
186
* 4. LANGCHAIN_API_KEY environment variable
187
*/
188
function getApiKey(apiKey?: string): string | undefined;
189
```
190
191
**Usage Examples:**
192
193
```typescript
194
import { getApiKey, Client } from "@langchain/langgraph-sdk";
195
196
// Explicitly check API key availability
197
const apiKey = getApiKey();
198
if (!apiKey) {
199
throw new Error("API key not found");
200
}
201
202
// Use with client
203
const client = new Client({ apiKey: getApiKey() });
204
205
// Let client handle API key resolution automatically
206
const client = new Client(); // Will use getApiKey() internally
207
```
208
209
### Fetch Override
210
211
Global fetch implementation override for custom HTTP handling or testing scenarios.
212
213
```typescript { .api }
214
/**
215
* Override the global fetch implementation used by the client
216
* @param fetchImpl - Custom fetch implementation to use
217
*/
218
function overrideFetchImplementation(fetchImpl: typeof fetch): void;
219
```
220
221
**Usage Examples:**
222
223
```typescript
224
import { overrideFetchImplementation } from "@langchain/langgraph-sdk";
225
import fetch from "node-fetch";
226
227
// Use node-fetch in Node.js environments
228
overrideFetchImplementation(fetch as any);
229
230
// Use custom fetch with logging
231
overrideFetchImplementation(async (url, init) => {
232
console.log(`Making request to ${url}`);
233
const response = await fetch(url, init);
234
console.log(`Response status: ${response.status}`);
235
return response;
236
});
237
```
238
239
## Error Handling
240
241
The client handles various error scenarios and provides detailed error information:
242
243
```typescript
244
import { Client } from "@langchain/langgraph-sdk";
245
246
try {
247
const client = new Client({
248
apiUrl: "https://api.langgraph.example.com",
249
apiKey: "invalid-key"
250
});
251
252
const assistant = await client.assistants.get("assistant-id");
253
} catch (error) {
254
if (error.status === 401) {
255
console.error("Authentication failed - check API key");
256
} else if (error.status === 404) {
257
console.error("Assistant not found");
258
} else {
259
console.error("Request failed:", error.message);
260
}
261
}
262
```
263
264
## Environment Configuration
265
266
The client respects various environment variables for configuration:
267
268
- `LANGGRAPH_API_KEY` - Primary API key environment variable
269
- `LANGSMITH_API_KEY` - Alternative API key environment variable
270
- `LANGCHAIN_API_KEY` - Fallback API key environment variable
271
272
```bash
273
# Set API key via environment
274
export LANGGRAPH_API_KEY="your-api-key"
275
276
# Client will automatically detect and use the key
277
const client = new Client({
278
apiUrl: "https://api.langgraph.example.com"
279
});
280
```
281
282
## Type Safety
283
284
The client supports full type safety with generic type parameters:
285
286
```typescript
287
interface MyState {
288
messages: Message[];
289
user_id: string;
290
}
291
292
interface MyUpdate {
293
new_message: Message;
294
}
295
296
// Typed client with custom state types
297
const client = new Client<MyState, MyUpdate>({
298
apiUrl: "https://api.langgraph.example.com",
299
apiKey: "your-api-key"
300
});
301
302
// Type-safe operations
303
const thread = await client.threads.create(); // Returns Thread<MyState>
304
const state = await client.threads.getState(thread.thread_id); // Returns ThreadState<MyState>
305
```