0
# Sessions
1
2
The Sessions API provides retrieval of sessions and their associated traces. Sessions group related traces together, typically representing a conversation or workflow that spans multiple interactions.
3
4
## Capabilities
5
6
### SessionsClient
7
8
Client for retrieving sessions and their traces.
9
10
```java { .api }
11
/**
12
* List sessions with filters and pagination
13
*
14
* @param request Optional filters (date range, environment, pagination)
15
* @param requestOptions Optional request configuration
16
*/
17
PaginatedSessions list();
18
PaginatedSessions list(GetSessionsRequest request);
19
PaginatedSessions list(GetSessionsRequest request, RequestOptions requestOptions);
20
21
/**
22
* Get a session with all its traces
23
* Note: Traces on this endpoint are not paginated
24
*
25
* @param sessionId Session ID
26
* @param requestOptions Optional request configuration
27
*/
28
SessionWithTraces get(String sessionId);
29
SessionWithTraces get(String sessionId, RequestOptions requestOptions);
30
```
31
32
**Usage Examples:**
33
34
```java
35
import com.langfuse.client.LangfuseClient;
36
import com.langfuse.client.resources.sessions.requests.GetSessionsRequest;
37
import com.langfuse.client.resources.sessions.types.PaginatedSessions;
38
import com.langfuse.client.resources.commons.types.*;
39
40
LangfuseClient client = LangfuseClient.builder()
41
.url("https://cloud.langfuse.com")
42
.credentials("pk-lf-...", "sk-lf-...")
43
.build();
44
45
// List all sessions
46
PaginatedSessions sessions = client.sessions().list();
47
for (Session session : sessions.getData()) {
48
System.out.println("Session: " + session.getId());
49
System.out.println(" Created: " + session.getCreatedAt());
50
System.out.println(" Environment: " + session.getEnvironment().orElse("none"));
51
}
52
53
// Filter by date range
54
GetSessionsRequest request = GetSessionsRequest.builder()
55
.fromTimestamp(OffsetDateTime.parse("2025-10-01T00:00:00Z"))
56
.toTimestamp(OffsetDateTime.parse("2025-10-14T23:59:59Z"))
57
.limit(50)
58
.build();
59
60
PaginatedSessions recentSessions = client.sessions().list(request);
61
62
// Filter by environment
63
GetSessionsRequest prodRequest = GetSessionsRequest.builder()
64
.environment("production")
65
.build();
66
67
PaginatedSessions prodSessions = client.sessions().list(prodRequest);
68
69
// Get a specific session with all traces
70
SessionWithTraces session = client.sessions().get("session-123");
71
System.out.println("Session: " + session.getId());
72
System.out.println("Traces: " + session.getTraces().size());
73
74
for (Trace trace : session.getTraces()) {
75
System.out.println(" - " + trace.getName().orElse("unnamed"));
76
System.out.println(" Timestamp: " + trace.getTimestamp());
77
}
78
```
79
80
## Request Types
81
82
### GetSessionsRequest
83
84
```java { .api }
85
import java.time.OffsetDateTime;
86
87
/**
88
* Request parameters for listing sessions
89
*/
90
public final class GetSessionsRequest {
91
Optional<Integer> getPage(); // Page number (default: 1)
92
Optional<Integer> getLimit(); // Items per page (default: 50)
93
Optional<OffsetDateTime> getFromTimestamp(); // Filter from this datetime
94
Optional<OffsetDateTime> getToTimestamp(); // Filter until this datetime
95
Optional<String> getEnvironment(); // Filter by environment
96
97
static Builder builder();
98
}
99
```
100
101
## Response Types
102
103
### Session
104
105
```java { .api }
106
import java.time.OffsetDateTime;
107
108
/**
109
* Session object
110
*/
111
public final class Session {
112
String getId(); // Session ID
113
OffsetDateTime getCreatedAt(); // Creation timestamp
114
String getProjectId(); // Project ID
115
Optional<String> getEnvironment(); // Environment
116
117
static Builder builder();
118
}
119
```
120
121
### PaginatedSessions
122
123
```java { .api }
124
/**
125
* Paginated list of sessions
126
*/
127
public final class PaginatedSessions {
128
List<Session> getData();
129
MetaResponse getMeta(); // Pagination metadata
130
131
static Builder builder();
132
}
133
```
134
135
### SessionWithTraces
136
137
```java { .api }
138
import java.time.OffsetDateTime;
139
140
/**
141
* Session with all its traces
142
* Note: Traces are not paginated
143
*/
144
public final class SessionWithTraces {
145
String getId();
146
OffsetDateTime getCreatedAt(); // Creation timestamp
147
String getProjectId(); // Project ID
148
Optional<String> getEnvironment(); // Environment
149
List<Trace> getTraces(); // All traces in session
150
151
static Builder builder();
152
}
153
```
154
155
## Complete Session Analysis Example
156
157
```java
158
import com.langfuse.client.LangfuseClient;
159
import com.langfuse.client.resources.sessions.requests.GetSessionsRequest;
160
import com.langfuse.client.resources.sessions.types.PaginatedSessions;
161
import com.langfuse.client.resources.commons.types.*;
162
import java.time.OffsetDateTime;
163
import java.util.Map;
164
import java.util.HashMap;
165
166
public class SessionAnalysisExample {
167
public static void main(String[] args) {
168
LangfuseClient client = LangfuseClient.builder()
169
.url("https://cloud.langfuse.com")
170
.credentials("pk-lf-...", "sk-lf-...")
171
.build();
172
173
// 1. List recent sessions
174
GetSessionsRequest request = GetSessionsRequest.builder()
175
.fromTimestamp(OffsetDateTime.parse("2025-10-14T00:00:00Z"))
176
.environment("production")
177
.limit(20)
178
.build();
179
180
PaginatedSessions sessions = client.sessions().list(request);
181
182
System.out.println("Found " + sessions.getMeta().getTotalItems() + " sessions");
183
184
// 2. Analyze each session
185
for (Session session : sessions.getData()) {
186
System.out.println("\nSession: " + session.getId());
187
System.out.println(" Created: " + session.getCreatedAt());
188
System.out.println(" Environment: " + session.getEnvironment().orElse("none"));
189
190
// Get detailed session data
191
SessionWithTraces fullSession = client.sessions().get(session.getId());
192
193
// Analyze traces in session
194
System.out.println(" Trace count: " + fullSession.getTraces().size());
195
for (Trace trace : fullSession.getTraces()) {
196
System.out.println(" - " + trace.getName().orElse("unnamed"));
197
System.out.println(" Time: " + trace.getTimestamp());
198
}
199
200
// Calculate session metrics
201
long durationMs = 0;
202
if (!fullSession.getTraces().isEmpty()) {
203
// Calculate session duration from first to last trace
204
String firstTime = fullSession.getTraces().get(0).getTimestamp();
205
String lastTime = fullSession.getTraces()
206
.get(fullSession.getTraces().size() - 1).getTimestamp();
207
208
System.out.println(" First trace: " + firstTime);
209
System.out.println(" Last trace: " + lastTime);
210
}
211
}
212
213
// 3. Group by environment
214
Map<String, Integer> envCount = new HashMap<>();
215
for (Session session : sessions.getData()) {
216
String env = session.getEnvironment().orElse("unknown");
217
envCount.merge(env, 1, Integer::sum);
218
}
219
220
System.out.println("\nSessions by environment:");
221
envCount.forEach((env, count) -> {
222
System.out.println(" " + env + ": " + count + " sessions");
223
});
224
}
225
}
226
```
227
228
## Query Patterns
229
230
### Finding Sessions by Time Range
231
232
```java
233
import java.time.OffsetDateTime;
234
235
GetSessionsRequest timeRangeRequest = GetSessionsRequest.builder()
236
.fromTimestamp(OffsetDateTime.parse("2025-10-01T00:00:00Z"))
237
.toTimestamp(OffsetDateTime.parse("2025-10-31T23:59:59Z"))
238
.build();
239
240
PaginatedSessions monthlySessions = client.sessions().list(timeRangeRequest);
241
```
242
243
### Paginating Through Sessions
244
245
```java
246
int page = 1;
247
boolean hasMore = true;
248
249
while (hasMore) {
250
GetSessionsRequest pageRequest = GetSessionsRequest.builder()
251
.page(page)
252
.limit(100)
253
.build();
254
255
PaginatedSessions sessions = client.sessions().list(pageRequest);
256
257
// Process sessions
258
for (Session session : sessions.getData()) {
259
System.out.println("Session: " + session.getId());
260
}
261
262
// Check if more pages exist
263
hasMore = page < sessions.getMeta().getTotalPages();
264
page++;
265
}
266
```
267
268
### Filtering by Environment
269
270
```java
271
GetSessionsRequest prodRequest = GetSessionsRequest.builder()
272
.environment("production")
273
.limit(50)
274
.build();
275
276
PaginatedSessions prodSessions = client.sessions().list(prodRequest);
277
```
278
279
## Best Practices
280
281
1. **Use Session IDs**: Group related traces with a consistent sessionId
282
2. **Track Conversations**: Use sessions to represent multi-turn conversations
283
3. **Environment Separation**: Filter by environment to separate prod/dev data
284
4. **Pagination**: Use pagination for large result sets
285
5. **Time-Based Queries**: Filter by date range for performance
286
6. **Analyze Trace Details**: Use SessionWithTraces to get full trace information
287
7. **Monitor Creation Timestamps**: Track session creation times for temporal analysis
288
289
## Use Cases
290
291
### Conversation Analysis
292
293
Sessions are ideal for analyzing multi-turn conversations:
294
295
```java
296
SessionWithTraces chatSession = client.sessions().get("session-123");
297
298
System.out.println("Session: " + chatSession.getId());
299
System.out.println("Number of traces: " + chatSession.getTraces().size());
300
System.out.println("Environment: " + chatSession.getEnvironment().orElse("none"));
301
302
for (int i = 0; i < chatSession.getTraces().size(); i++) {
303
Trace turn = chatSession.getTraces().get(i);
304
System.out.println("Trace " + (i + 1) + ": " + turn.getName().orElse(""));
305
}
306
```
307
308
### Environment-based Analysis
309
310
Analyze sessions by environment:
311
312
```java
313
import java.time.OffsetDateTime;
314
315
GetSessionsRequest request = GetSessionsRequest.builder()
316
.fromTimestamp(OffsetDateTime.parse("2025-10-01T00:00:00Z"))
317
.environment("production")
318
.build();
319
320
PaginatedSessions sessions = client.sessions().list(request);
321
322
System.out.println("Production sessions: " + sessions.getMeta().getTotalItems());
323
```
324
325
### Trace Analysis within Sessions
326
327
Analyze traces within a session:
328
329
```java
330
SessionWithTraces session = client.sessions().get("session-123");
331
332
System.out.println("Session: " + session.getId());
333
System.out.println("Total traces: " + session.getTraces().size());
334
335
// Analyze each trace
336
for (Trace trace : session.getTraces()) {
337
System.out.println("Trace: " + trace.getId());
338
System.out.println(" Name: " + trace.getName().orElse("unnamed"));
339
System.out.println(" Timestamp: " + trace.getTimestamp());
340
}
341
```
342
343
## Related Documentation
344
345
- [Traces and Observations](./traces-observations.md) - Traces within sessions
346
- [Ingestion API](./ingestion.md) - Creating traces with session IDs
347
- [Common Types](./common-types.md) - Session type definitions
348
- [Pagination](./pagination.md) - Pagination utilities
349