Skip to content

guidellm.schemas

Pydantic schema models for GuideLLM operations.

Provides standardized data models and type definitions for generation requests, responses, timing measurements, and statistics aggregation. These schemas ensure type safety and consistent data handling across the benchmarking pipeline, from request submission through backend processing to results compilation.

DistributionSummary

Bases: StandardBaseModel

Comprehensive statistical summary of a probability distribution.

Captures central tendency (mean, median, mode), spread (variance, std_dev), extrema (min, max), and percentile information with optional probability density function. Supports creation from raw values, PDFs, or time-based event data for rate and concurrency analysis in benchmark metrics.

Source code in src/guidellm/schemas/statistics.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
class DistributionSummary(StandardBaseModel):
    """
    Comprehensive statistical summary of a probability distribution.

    Captures central tendency (mean, median, mode), spread (variance, std_dev),
    extrema (min, max), and percentile information with optional probability density
    function. Supports creation from raw values, PDFs, or time-based event data for
    rate and concurrency analysis in benchmark metrics.
    """

    mean: float = Field(description="Mean/average value")
    median: float = Field(description="Median (50th percentile) value")
    mode: float = Field(description="Mode (most probable) value")
    variance: float = Field(description="Variance of the distribution")
    std_dev: float = Field(description="Standard deviation")
    min: float = Field(description="Minimum value")
    max: float = Field(description="Maximum value")
    count: int = Field(description="Number of observations")
    total_sum: float = Field(description="Sum of all values")
    percentiles: Percentiles = Field(description="Standard percentile values")
    pdf: list[tuple[float, float]] | None = Field(
        description="Probability density function as (value, probability) pairs",
        default=None,
    )

    @classmethod
    def from_pdf(
        cls,
        pdf: np.ndarray,
        count: int | None = None,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
        validate: bool = True,
    ) -> DistributionSummary:
        """
        Create distribution summary from a probability density function.

        :param pdf: 2D array (N, 2) with values in column 0 and probabilities in
            column 1
        :param count: Number of original observations; defaults to PDF length
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :param validate: Whether to validate probabilities sum to 1 and are non-negative
        :return: Complete distribution summary with statistics
        :raises ValueError: If PDF shape is invalid or probabilities are invalid
        """
        expected_shape = (None, 2)

        if len(pdf.shape) != len(expected_shape) or pdf.shape[1] != expected_shape[1]:
            raise ValueError(
                "PDF must be a 2D array of shape (N, 2) where first column is values "
                f"and second column is probabilities. Got {pdf.shape} instead."
            )

        if pdf.shape[0] == 0:
            return DistributionSummary(
                mean=0.0,
                median=0.0,
                mode=0.0,
                variance=0.0,
                std_dev=0.0,
                min=0.0,
                max=0.0,
                count=0 if count is None else count,
                total_sum=0.0,
                percentiles=Percentiles.from_pdf(pdf, epsilon=epsilon),
                pdf=None if include_pdf is False else [],
            )

        # Calculate stats
        values = pdf[:, 0]
        probabilities = pdf[:, 1]

        if validate:
            # Fail if probabilities don't sum to 1 or are negative
            if np.any(probabilities < 0):
                raise ValueError("Probabilities must be non-negative.")

            prob_sum = np.sum(probabilities)
            if not np.isclose(prob_sum, 1.0, atol=epsilon):
                raise ValueError(f"Probabilities must sum to 1.0 (sum={prob_sum}).")

            # Fail if values are not sorted
            if not np.all(values[:-1] <= values[1:]):
                raise ValueError("Values in PDF must be sorted in ascending order.")

        percentiles = Percentiles.from_pdf(pdf, epsilon=epsilon, validate=False)
        median = percentiles.p50
        mean = np.sum(values * probabilities).item()
        mode = values[np.argmax(probabilities)].item()
        variance = np.sum((values - mean) ** 2 * probabilities).item()
        std_dev = math.sqrt(variance)
        minimum = values[0].item()
        maximum = values[-1].item()

        if count is None:
            count = len(pdf)

        total_sum = mean * count
        sampled_pdf = cls._sample_pdf(pdf, include_pdf)

        return DistributionSummary(
            mean=mean,
            median=median,
            mode=mode,
            variance=variance,
            std_dev=std_dev,
            min=minimum,
            max=maximum,
            count=count,
            total_sum=total_sum,
            percentiles=percentiles,
            pdf=sampled_pdf,
        )

    @classmethod
    def _sample_pdf(
        cls, pdf: np.ndarray, include_pdf: bool | int
    ) -> list[tuple[float, float]] | None:
        """
        Sample PDF based on include_pdf parameter.

        :param pdf: PDF array to sample
        :param include_pdf: False for None, True for full, int for sampled size
        :return: Sampled PDF as list of tuples or None
        """
        if include_pdf is False:
            return None
        if include_pdf is True:
            return pdf.tolist()
        if isinstance(include_pdf, int) and include_pdf > 0:
            if len(pdf) <= include_pdf:
                return pdf.tolist()
            sample_indices = np.linspace(0, len(pdf) - 1, include_pdf, dtype=int)
            return pdf[sample_indices].tolist()
        return []

    @classmethod
    def from_values(
        cls,
        values: Sequence[float | tuple[float, float]] | np.ndarray,
        count: int | None = None,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> DistributionSummary:
        """
        Create distribution summary from raw values with optional weights.

        :param values: Values or (value, weight) tuples, or numpy array
        :param count: Number of original observations; defaults to sum of weights
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Distribution summary computed from the values
        :raises ValueError: If total weight is zero or invalid
        """
        np_values = cls._to_weighted_ndarray(values, num_values_per_item=2)

        if np_values.shape[0] == 0:
            return DistributionSummary.from_pdf(
                pdf=np.empty((0, 2)), count=0, include_pdf=include_pdf, epsilon=epsilon
            )

        if count is None:
            count = round(np.sum(np_values[:, 1]).item())

        # Sort values and weights by values
        sort_ind = np.argsort(np_values[:, 0])
        sorted_values = np_values[sort_ind, 0]
        sorted_weights = np_values[sort_ind, 1]

        # Combine any duplicate values by summing their weights
        unique_values, inverse_indices = np.unique(sorted_values, return_inverse=True)
        combined_weights = np.zeros_like(unique_values, dtype=float)
        np.add.at(combined_weights, inverse_indices, sorted_weights)

        # Remove any values with zero weight
        nonzero_mask = combined_weights > 0
        final_values = unique_values[nonzero_mask]
        final_weights = combined_weights[nonzero_mask]

        # Create PDF by normalizing weights and stacking
        total_weight = np.sum(final_weights)
        if total_weight <= epsilon:
            # No valid weights to create PDF, overwrite to uniform distribution
            final_weights = np.ones_like(final_values)
            total_weight = np.sum(final_weights)

        probabilities = final_weights / total_weight
        pdf = np.column_stack((final_values, probabilities))

        return DistributionSummary.from_pdf(
            pdf=pdf,
            count=count,
            include_pdf=include_pdf,
            epsilon=epsilon,
            validate=False,
        )

    @classmethod
    def rate_distribution_from_timings(
        cls,
        event_times: Sequence[float | tuple[float, float]] | np.ndarray,
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,  # 1/10th of a millisecond
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> DistributionSummary:
        """
        Create rate distribution from event timestamps.

        Computes event rates over time intervals weighted by interval duration for
        analyzing request throughput patterns.

        :param event_times: Event timestamps or (timestamp, weight) tuples
        :param start_time: Analysis window start; filters earlier events
        :param end_time: Analysis window end; filters later events
        :param threshold: Time threshold for merging nearby events; 1/10th millisecond
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Distribution summary of event rates over time
        """
        weighted_times = cls._to_weighted_ndarray(event_times, num_values_per_item=2)

        if start_time is not None:
            # Filter out any times before start, insert start time with 0 weight
            weighted_times = np.insert(
                weighted_times[weighted_times[:, 0] >= start_time],
                0,
                [start_time, 0.0],
                axis=0,
            )

        if end_time is not None:
            # Filter out any times after end, insert end time with 0 weight
            weighted_times = np.append(
                weighted_times[weighted_times[:, 0] <= end_time],
                [[end_time, 0.0]],
                axis=0,
            )

        # Sort by time for merging, merge any times within threshold
        sort_ind = np.argsort(weighted_times[:, 0])
        weighted_times = weighted_times[sort_ind]
        weighted_times = cls._merge_sorted_times_with_weights(weighted_times, threshold)

        if len(weighted_times) <= 1:
            # No data to calculate rates from (need at least two times)
            return cls.from_values(
                [],
                count=len(weighted_times),
                include_pdf=include_pdf,
                epsilon=epsilon,
            )

        times = weighted_times[:, 0]
        occurrences = weighted_times[:, 1]

        # Calculate local duration for each event: ((times[i+1] - times[i-1])) / 2
        midpoints = (times[1:] + times[:-1]) / 2
        durations = np.empty_like(times)
        durations[0] = midpoints[0] - times[0]
        durations[1:-1] = midpoints[1:] - midpoints[:-1]
        durations[-1] = np.clip(times[-1] - midpoints[-1], epsilon, None)

        # Calculate rate at each interval: occurences[i] / duration[i]
        rates = occurrences / durations
        count = round(np.sum(occurrences).item())

        return cls.from_values(
            np.column_stack((rates, durations)),
            count=count,
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    @classmethod
    def concurrency_distribution_from_timings(
        cls,
        event_intervals: (
            Sequence[tuple[float, float] | tuple[float, float, float]] | np.ndarray
        ),
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,  # 1/10th of a millisecond
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> DistributionSummary:
        """
        Create concurrency distribution from event time intervals.

        Tracks overlapping events to compute concurrency levels over time for analyzing
        request processing patterns and resource utilization.

        :param event_intervals: Event (start, end) or (start, end, weight) tuples
        :param start_time: Analysis window start
        :param end_time: Analysis window end
        :param threshold: Time threshold for merging nearby transitions;
            1/10th millisecond
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Distribution summary of concurrency levels over time
        """
        weighted_intervals = cls._to_weighted_ndarray(
            event_intervals, num_values_per_item=3
        )

        # If start_time, filter any intervals that end before start_time
        if start_time is not None:
            keep_mask = weighted_intervals[:, 1] >= start_time
            weighted_intervals = weighted_intervals[keep_mask]

        # If end_time, filter any intervals that start after end_time
        if end_time is not None:
            keep_mask = weighted_intervals[:, 0] <= end_time
            weighted_intervals = weighted_intervals[keep_mask]

        count = len(weighted_intervals)

        # Convert to concurrency changes at each time
        add_occurences = (
            np.stack(
                (
                    weighted_intervals[:, 0],
                    weighted_intervals[:, 2],
                ),
                axis=1,
            )
            if len(weighted_intervals) > 0
            else np.empty((0, 2))
        )
        remove_occurences = (
            np.stack(
                (
                    weighted_intervals[:, 1],
                    -1 * weighted_intervals[:, 2],
                ),
                axis=1,
            )
            if len(weighted_intervals) > 0
            else np.empty((0, 2))
        )

        # Combine add and remove occurences into weighted times
        weighted_times = np.vstack((add_occurences, remove_occurences))

        # Sort by the times and merge any times within threshold
        weighted_times = weighted_times[np.argsort(weighted_times[:, 0])]
        weighted_times = cls._merge_sorted_times_with_weights(weighted_times, threshold)

        # If start_time, ensure included (if any before, add final concurrency at start)
        if start_time is not None and len(weighted_times) > 0:
            start_ind = np.searchsorted(weighted_times[:, 0], start_time, side="left")
            prior_delta = (
                np.sum(weighted_times[:start_ind, 1]) if start_ind > 0 else 0.0
            )
            weighted_times = np.insert(
                weighted_times[start_ind:], 0, [start_time, prior_delta], axis=0
            )

        # If end_time, ensure included (if any after, filter out)
        if end_time is not None and len(weighted_times) > 0:
            end_ind = np.searchsorted(weighted_times[:, 0], end_time, side="right")
            weighted_times = np.append(
                weighted_times[:end_ind], [[end_time, 0.0]], axis=0
            )

        # Calculate concurrency from cumulative sum of changes over time
        concurrencies = np.clip(np.cumsum(weighted_times[:, 1]), 0, None)

        if len(concurrencies) <= 1:
            # No data to calculate concurrency from
            return cls.from_values(
                [] if count == 0 else [concurrencies[0].item()],
                include_pdf=include_pdf,
                epsilon=epsilon,
            )

        # Calculate durations equal to times[i+1] - times[i]
        # The last concurrency level is not used since no following time point
        durations = np.clip(np.diff(weighted_times[:, 0]), 0, None)
        values = np.column_stack((concurrencies[:-1], durations))

        return (
            cls.from_values(
                values,
                count=count,
                include_pdf=include_pdf,
                epsilon=epsilon,
            )
            if np.any(durations > 0)
            else cls.from_values(
                [],
                count=count,
                include_pdf=include_pdf,
                epsilon=epsilon,
            )
        )

    @classmethod
    def _to_weighted_ndarray(
        cls,
        inputs: (
            Sequence[float | tuple[float, float] | tuple[float, float, float]]
            | np.ndarray
        ),
        num_values_per_item: Literal[2, 3],
    ) -> np.ndarray:
        if not isinstance(inputs, np.ndarray):
            # Convert list to structured numpy array with dims (N, num_dimensions)
            # Fill in missing weights with 1.0
            return cls._sequence_to_weighted_ndarray(inputs, num_values_per_item)

        if len(inputs.shape) == 1:
            # 1D array: reshape to (N, 1) and add weights column
            inputs = inputs.reshape(-1, 1)
            weights = np.ones((inputs.shape[0], 1), dtype=float)

            return (
                np.hstack((inputs, weights))
                if num_values_per_item == 2  # noqa: PLR2004
                else np.hstack((inputs, inputs, weights))
            )

        if len(inputs.shape) == 2 and inputs.shape[1] == num_values_per_item - 1:  # noqa: PLR2004
            # Add weights column of 1.0
            weights = np.ones((inputs.shape[0], 1), dtype=float)

            return np.hstack((inputs, weights))

        if len(inputs.shape) == 2 and inputs.shape[1] == num_values_per_item:  # noqa: PLR2004
            return inputs

        raise ValueError(
            "inputs must be a numpy array of shape (N,), "
            f"(N, {num_values_per_item - 1}), or (N, {num_values_per_item}). "
            f"Got shape {inputs.shape}."
        )

    @classmethod
    def _sequence_to_weighted_ndarray(
        cls,
        inputs: Sequence[float | tuple[float, float] | tuple[float, float, float]],
        num_values_per_item: Literal[2, 3],
    ) -> np.ndarray:
        ndarray = np.empty((len(inputs), num_values_per_item), dtype=float)
        scalar_types: tuple[type, ...] = (int, float, np.integer, np.floating)

        for ind, val in enumerate(inputs):
            if isinstance(val, scalar_types):
                ndarray[ind, :] = (
                    (val, 1.0) if num_values_per_item == 2 else (val, val, 1.0)  # noqa: PLR2004
                )
            elif isinstance(val, tuple) and len(val) == num_values_per_item:
                ndarray[ind, :] = val
            elif isinstance(val, tuple) and len(val) == num_values_per_item - 1:
                ndarray[ind, :] = (
                    (val[0], 1.0) if num_values_per_item == 2 else (val[0], val[1], 1.0)  # noqa: PLR2004
                )
            else:
                raise ValueError(
                    "Each item must be a float or a tuple of "
                    f"{num_values_per_item} or {num_values_per_item - 1} "
                    "elements."
                )

        return ndarray

    @classmethod
    def _merge_sorted_times_with_weights(
        cls, weighted_times: np.ndarray, threshold: float | None
    ) -> np.ndarray:
        # First remove any exact duplicate times and sum their weights
        unique_times, inverse = np.unique(weighted_times[:, 0], return_inverse=True)
        unique_weights = np.zeros_like(unique_times, dtype=float)
        np.add.at(unique_weights, inverse, weighted_times[:, 1])
        weighted_times = np.column_stack((unique_times, unique_weights))

        if threshold is None or threshold <= 0.0:
            return weighted_times

        # Loop to merge times within threshold until no more merges possible
        # (loop due to possible overlapping merge groups)
        while weighted_times.shape[0] > 1:
            times = weighted_times[:, 0]
            weights = weighted_times[:, 1]

            # Find diffs between consecutive times, create mask for within-threshold
            diffs = np.diff(times)
            within = diffs <= threshold
            if not np.any(within):
                break

            # Start indices are marked by the transition from 0 to 1 in the mask
            # End indices found by searching for last time within threshold from start
            starts = np.where(np.diff(np.insert(within.astype(int), 0, 0)) == 1)[0]
            start_end_times = times[starts] + threshold
            ends = np.searchsorted(times, start_end_times, side="right") - 1

            # Collapse overlapping or chained merge groups
            if len(starts) > 1:
                valid_mask = np.concatenate([[True], starts[1:] > ends[:-1]])
                starts, ends = starts[valid_mask], ends[valid_mask]

            # Update weights at start indices to sum of merged weights
            cumsum = np.concatenate(([0.0], np.cumsum(weights)))
            weighted_times[starts, 1] = cumsum[ends + 1] - cumsum[starts]

            # Calculate vectorized mask for removing merged entries
            merged_events = np.zeros(len(weighted_times) + 1, dtype=int)
            np.add.at(merged_events, starts, 1)
            np.add.at(merged_events, ends + 1, -1)
            remove_mask = np.cumsum(merged_events[:-1]) > 0
            remove_mask[starts] = False  # Keep start indices

            # Remove merged entries, update weighted_times
            weights = weights[~remove_mask]
            times = times[~remove_mask]
            weighted_times = np.column_stack((times, weights))

        return weighted_times

concurrency_distribution_from_timings(event_intervals, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create concurrency distribution from event time intervals.

Tracks overlapping events to compute concurrency levels over time for analyzing request processing patterns and resource utilization.

Parameters:

Name Type Description Default
event_intervals Sequence[tuple[float, float] | tuple[float, float, float]] | ndarray

Event (start, end) or (start, end, weight) tuples

required
start_time float | None

Analysis window start

None
end_time float | None

Analysis window end

None
threshold float | None

Time threshold for merging nearby transitions; 1/10th millisecond

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
DistributionSummary

Distribution summary of concurrency levels over time

Source code in src/guidellm/schemas/statistics.py
@classmethod
def concurrency_distribution_from_timings(
    cls,
    event_intervals: (
        Sequence[tuple[float, float] | tuple[float, float, float]] | np.ndarray
    ),
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,  # 1/10th of a millisecond
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> DistributionSummary:
    """
    Create concurrency distribution from event time intervals.

    Tracks overlapping events to compute concurrency levels over time for analyzing
    request processing patterns and resource utilization.

    :param event_intervals: Event (start, end) or (start, end, weight) tuples
    :param start_time: Analysis window start
    :param end_time: Analysis window end
    :param threshold: Time threshold for merging nearby transitions;
        1/10th millisecond
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Distribution summary of concurrency levels over time
    """
    weighted_intervals = cls._to_weighted_ndarray(
        event_intervals, num_values_per_item=3
    )

    # If start_time, filter any intervals that end before start_time
    if start_time is not None:
        keep_mask = weighted_intervals[:, 1] >= start_time
        weighted_intervals = weighted_intervals[keep_mask]

    # If end_time, filter any intervals that start after end_time
    if end_time is not None:
        keep_mask = weighted_intervals[:, 0] <= end_time
        weighted_intervals = weighted_intervals[keep_mask]

    count = len(weighted_intervals)

    # Convert to concurrency changes at each time
    add_occurences = (
        np.stack(
            (
                weighted_intervals[:, 0],
                weighted_intervals[:, 2],
            ),
            axis=1,
        )
        if len(weighted_intervals) > 0
        else np.empty((0, 2))
    )
    remove_occurences = (
        np.stack(
            (
                weighted_intervals[:, 1],
                -1 * weighted_intervals[:, 2],
            ),
            axis=1,
        )
        if len(weighted_intervals) > 0
        else np.empty((0, 2))
    )

    # Combine add and remove occurences into weighted times
    weighted_times = np.vstack((add_occurences, remove_occurences))

    # Sort by the times and merge any times within threshold
    weighted_times = weighted_times[np.argsort(weighted_times[:, 0])]
    weighted_times = cls._merge_sorted_times_with_weights(weighted_times, threshold)

    # If start_time, ensure included (if any before, add final concurrency at start)
    if start_time is not None and len(weighted_times) > 0:
        start_ind = np.searchsorted(weighted_times[:, 0], start_time, side="left")
        prior_delta = (
            np.sum(weighted_times[:start_ind, 1]) if start_ind > 0 else 0.0
        )
        weighted_times = np.insert(
            weighted_times[start_ind:], 0, [start_time, prior_delta], axis=0
        )

    # If end_time, ensure included (if any after, filter out)
    if end_time is not None and len(weighted_times) > 0:
        end_ind = np.searchsorted(weighted_times[:, 0], end_time, side="right")
        weighted_times = np.append(
            weighted_times[:end_ind], [[end_time, 0.0]], axis=0
        )

    # Calculate concurrency from cumulative sum of changes over time
    concurrencies = np.clip(np.cumsum(weighted_times[:, 1]), 0, None)

    if len(concurrencies) <= 1:
        # No data to calculate concurrency from
        return cls.from_values(
            [] if count == 0 else [concurrencies[0].item()],
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    # Calculate durations equal to times[i+1] - times[i]
    # The last concurrency level is not used since no following time point
    durations = np.clip(np.diff(weighted_times[:, 0]), 0, None)
    values = np.column_stack((concurrencies[:-1], durations))

    return (
        cls.from_values(
            values,
            count=count,
            include_pdf=include_pdf,
            epsilon=epsilon,
        )
        if np.any(durations > 0)
        else cls.from_values(
            [],
            count=count,
            include_pdf=include_pdf,
            epsilon=epsilon,
        )
    )

from_pdf(pdf, count=None, include_pdf=False, epsilon=1e-06, validate=True) classmethod

Create distribution summary from a probability density function.

Parameters:

Name Type Description Default
pdf ndarray

2D array (N, 2) with values in column 0 and probabilities in column 1

required
count int | None

Number of original observations; defaults to PDF length

None
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06
validate bool

Whether to validate probabilities sum to 1 and are non-negative

True

Returns:

Type Description
DistributionSummary

Complete distribution summary with statistics

Raises:

Type Description
ValueError

If PDF shape is invalid or probabilities are invalid

Source code in src/guidellm/schemas/statistics.py
@classmethod
def from_pdf(
    cls,
    pdf: np.ndarray,
    count: int | None = None,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
    validate: bool = True,
) -> DistributionSummary:
    """
    Create distribution summary from a probability density function.

    :param pdf: 2D array (N, 2) with values in column 0 and probabilities in
        column 1
    :param count: Number of original observations; defaults to PDF length
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :param validate: Whether to validate probabilities sum to 1 and are non-negative
    :return: Complete distribution summary with statistics
    :raises ValueError: If PDF shape is invalid or probabilities are invalid
    """
    expected_shape = (None, 2)

    if len(pdf.shape) != len(expected_shape) or pdf.shape[1] != expected_shape[1]:
        raise ValueError(
            "PDF must be a 2D array of shape (N, 2) where first column is values "
            f"and second column is probabilities. Got {pdf.shape} instead."
        )

    if pdf.shape[0] == 0:
        return DistributionSummary(
            mean=0.0,
            median=0.0,
            mode=0.0,
            variance=0.0,
            std_dev=0.0,
            min=0.0,
            max=0.0,
            count=0 if count is None else count,
            total_sum=0.0,
            percentiles=Percentiles.from_pdf(pdf, epsilon=epsilon),
            pdf=None if include_pdf is False else [],
        )

    # Calculate stats
    values = pdf[:, 0]
    probabilities = pdf[:, 1]

    if validate:
        # Fail if probabilities don't sum to 1 or are negative
        if np.any(probabilities < 0):
            raise ValueError("Probabilities must be non-negative.")

        prob_sum = np.sum(probabilities)
        if not np.isclose(prob_sum, 1.0, atol=epsilon):
            raise ValueError(f"Probabilities must sum to 1.0 (sum={prob_sum}).")

        # Fail if values are not sorted
        if not np.all(values[:-1] <= values[1:]):
            raise ValueError("Values in PDF must be sorted in ascending order.")

    percentiles = Percentiles.from_pdf(pdf, epsilon=epsilon, validate=False)
    median = percentiles.p50
    mean = np.sum(values * probabilities).item()
    mode = values[np.argmax(probabilities)].item()
    variance = np.sum((values - mean) ** 2 * probabilities).item()
    std_dev = math.sqrt(variance)
    minimum = values[0].item()
    maximum = values[-1].item()

    if count is None:
        count = len(pdf)

    total_sum = mean * count
    sampled_pdf = cls._sample_pdf(pdf, include_pdf)

    return DistributionSummary(
        mean=mean,
        median=median,
        mode=mode,
        variance=variance,
        std_dev=std_dev,
        min=minimum,
        max=maximum,
        count=count,
        total_sum=total_sum,
        percentiles=percentiles,
        pdf=sampled_pdf,
    )

from_values(values, count=None, include_pdf=False, epsilon=1e-06) classmethod

Create distribution summary from raw values with optional weights.

Parameters:

Name Type Description Default
values Sequence[float | tuple[float, float]] | ndarray

Values or (value, weight) tuples, or numpy array

required
count int | None

Number of original observations; defaults to sum of weights

None
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
DistributionSummary

Distribution summary computed from the values

Raises:

Type Description
ValueError

If total weight is zero or invalid

Source code in src/guidellm/schemas/statistics.py
@classmethod
def from_values(
    cls,
    values: Sequence[float | tuple[float, float]] | np.ndarray,
    count: int | None = None,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> DistributionSummary:
    """
    Create distribution summary from raw values with optional weights.

    :param values: Values or (value, weight) tuples, or numpy array
    :param count: Number of original observations; defaults to sum of weights
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Distribution summary computed from the values
    :raises ValueError: If total weight is zero or invalid
    """
    np_values = cls._to_weighted_ndarray(values, num_values_per_item=2)

    if np_values.shape[0] == 0:
        return DistributionSummary.from_pdf(
            pdf=np.empty((0, 2)), count=0, include_pdf=include_pdf, epsilon=epsilon
        )

    if count is None:
        count = round(np.sum(np_values[:, 1]).item())

    # Sort values and weights by values
    sort_ind = np.argsort(np_values[:, 0])
    sorted_values = np_values[sort_ind, 0]
    sorted_weights = np_values[sort_ind, 1]

    # Combine any duplicate values by summing their weights
    unique_values, inverse_indices = np.unique(sorted_values, return_inverse=True)
    combined_weights = np.zeros_like(unique_values, dtype=float)
    np.add.at(combined_weights, inverse_indices, sorted_weights)

    # Remove any values with zero weight
    nonzero_mask = combined_weights > 0
    final_values = unique_values[nonzero_mask]
    final_weights = combined_weights[nonzero_mask]

    # Create PDF by normalizing weights and stacking
    total_weight = np.sum(final_weights)
    if total_weight <= epsilon:
        # No valid weights to create PDF, overwrite to uniform distribution
        final_weights = np.ones_like(final_values)
        total_weight = np.sum(final_weights)

    probabilities = final_weights / total_weight
    pdf = np.column_stack((final_values, probabilities))

    return DistributionSummary.from_pdf(
        pdf=pdf,
        count=count,
        include_pdf=include_pdf,
        epsilon=epsilon,
        validate=False,
    )

rate_distribution_from_timings(event_times, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create rate distribution from event timestamps.

Computes event rates over time intervals weighted by interval duration for analyzing request throughput patterns.

Parameters:

Name Type Description Default
event_times Sequence[float | tuple[float, float]] | ndarray

Event timestamps or (timestamp, weight) tuples

required
start_time float | None

Analysis window start; filters earlier events

None
end_time float | None

Analysis window end; filters later events

None
threshold float | None

Time threshold for merging nearby events; 1/10th millisecond

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
DistributionSummary

Distribution summary of event rates over time

Source code in src/guidellm/schemas/statistics.py
@classmethod
def rate_distribution_from_timings(
    cls,
    event_times: Sequence[float | tuple[float, float]] | np.ndarray,
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,  # 1/10th of a millisecond
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> DistributionSummary:
    """
    Create rate distribution from event timestamps.

    Computes event rates over time intervals weighted by interval duration for
    analyzing request throughput patterns.

    :param event_times: Event timestamps or (timestamp, weight) tuples
    :param start_time: Analysis window start; filters earlier events
    :param end_time: Analysis window end; filters later events
    :param threshold: Time threshold for merging nearby events; 1/10th millisecond
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Distribution summary of event rates over time
    """
    weighted_times = cls._to_weighted_ndarray(event_times, num_values_per_item=2)

    if start_time is not None:
        # Filter out any times before start, insert start time with 0 weight
        weighted_times = np.insert(
            weighted_times[weighted_times[:, 0] >= start_time],
            0,
            [start_time, 0.0],
            axis=0,
        )

    if end_time is not None:
        # Filter out any times after end, insert end time with 0 weight
        weighted_times = np.append(
            weighted_times[weighted_times[:, 0] <= end_time],
            [[end_time, 0.0]],
            axis=0,
        )

    # Sort by time for merging, merge any times within threshold
    sort_ind = np.argsort(weighted_times[:, 0])
    weighted_times = weighted_times[sort_ind]
    weighted_times = cls._merge_sorted_times_with_weights(weighted_times, threshold)

    if len(weighted_times) <= 1:
        # No data to calculate rates from (need at least two times)
        return cls.from_values(
            [],
            count=len(weighted_times),
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    times = weighted_times[:, 0]
    occurrences = weighted_times[:, 1]

    # Calculate local duration for each event: ((times[i+1] - times[i-1])) / 2
    midpoints = (times[1:] + times[:-1]) / 2
    durations = np.empty_like(times)
    durations[0] = midpoints[0] - times[0]
    durations[1:-1] = midpoints[1:] - midpoints[:-1]
    durations[-1] = np.clip(times[-1] - midpoints[-1], epsilon, None)

    # Calculate rate at each interval: occurences[i] / duration[i]
    rates = occurrences / durations
    count = round(np.sum(occurrences).item())

    return cls.from_values(
        np.column_stack((rates, durations)),
        count=count,
        include_pdf=include_pdf,
        epsilon=epsilon,
    )

GenerationRequest

Bases: StandardBaseModel

Complete request specification for backend generation operations.

Encapsulates all components needed to execute a generation request including unique identification, request type specification, HTTP arguments, and input/output usage metrics. Serves as the primary interface between the scheduler and backend services for coordinating AI generation tasks.

Example:: request = GenerationRequest( arguments=GenerationRequestArguments( method="POST", body={"prompt": "Hello world", "max_tokens": 100} ) )

Source code in src/guidellm/schemas/request.py
class GenerationRequest(StandardBaseModel):
    """
    Complete request specification for backend generation operations.

    Encapsulates all components needed to execute a generation request including
    unique identification, request type specification, HTTP arguments, and input/output
    usage metrics. Serves as the primary interface between the scheduler and backend
    services for coordinating AI generation tasks.

    Example::
        request = GenerationRequest(
            arguments=GenerationRequestArguments(
                method="POST",
                body={"prompt": "Hello world", "max_tokens": 100}
            )
        )
    """

    request_id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="Unique identifier for the request.",
    )
    columns: dict[str, list[Any]] = Field(
        default_factory=dict,
        description=(
            "Columnar data associated with the request, structured as a dictionary "
            "where keys are column names and values are lists of column entries."
        ),
    )
    turn_type: TurnType = Field(
        default="standard",
        description="Discriminator for the kind of turn this request represents. "
        "'standard' is a normal user turn. "
        "'client_tool_call' expects the server to produce tool calls that the "
        "client will handle by injecting tool responses in a follow-up turn. "
        "'tool_response_injection' sends tool output back to the server and "
        "expects a text response. "
        "'server_tool_call' is a turn where the server handles tool execution "
        "end-to-end; it prevents tool_choice='none' from being set so that "
        "server-configured tools remain usable.",
    )
    input_metrics: UsageMetrics = Field(
        default_factory=UsageMetrics,
        description="Input statistics including counts, sizes, and durations.",
    )
    output_metrics: UsageMetrics = Field(
        default_factory=UsageMetrics,
        description="Output statistics including counts, sizes, and durations.",
    )
    settings: RequestSettings = Field(
        default_factory=RequestSettings,
        description=(
            "Per-request scheduling metadata from the dataset finalizer, "
            "for example trace replay relative timestamps."
        ),
    )

GenerationRequestArguments

Bases: StandardBaseDict

HTTP request arguments for generation operations.

Encapsulates all necessary HTTP request components including method, headers, parameters, and payload data required to execute generation requests against backend services. Supports file uploads and streaming responses.

Source code in src/guidellm/schemas/request.py
class GenerationRequestArguments(StandardBaseDict):
    """
    HTTP request arguments for generation operations.

    Encapsulates all necessary HTTP request components including method, headers,
    parameters, and payload data required to execute generation requests against
    backend services. Supports file uploads and streaming responses.
    """

    method: str | None = Field(
        default=None,
        description="The HTTP method to use for the request (e.g., 'POST', 'GET').",
    )
    stream: bool | None = Field(
        default=None,
        description="Whether to stream the response, if applicable.",
    )
    headers: dict[str, str] | None = Field(
        default=None,
        description="Any headers to include in the request, if applicable.",
    )
    params: dict[str, Any] | None = Field(
        default=None,
        description="Query parameters to include in the request, if applicable.",
    )
    body: dict[str, Any] | None = Field(
        default=None,
        description="Content to include in the main request body.",
        examples=[
            {
                "temperature": 0.5,
                "max_tokens": 100,
            }
        ],
    )
    files: dict[str, Any] | None = Field(
        default=None,
        description="Files to include in the request, if applicable.",
    )
    content: dict[str, Any] | None = Field(
        default=None,
        description=(
            "Additional fields to include in generated text content objects, "
            "if applicable."
        ),
    )

    def model_combine(
        self, additional: GenerationRequestArguments | dict[str, Any]
    ) -> GenerationRequestArguments:
        """
        Merge additional request arguments into the current instance.

        Combines method and stream fields by overwriting, while merging collection
        fields like headers, params, body, and files by extending existing values.

        :param additional: Additional arguments to merge with current instance
        :return: Updated instance with merged arguments
        """
        additional_dict = (
            additional.model_dump()
            if isinstance(additional, GenerationRequestArguments)
            else additional
        )

        for overwrite in ("method", "stream"):
            if (val := additional_dict.get(overwrite)) is not None:
                setattr(self, overwrite, val)

        for combine in ("headers", "params", "body", "files"):
            if (val := additional_dict.get(combine)) is not None:
                current = getattr(self, combine, None) or {}
                deep_update(current, val)
                setattr(self, combine, current)

        return self

model_combine(additional)

Merge additional request arguments into the current instance.

Combines method and stream fields by overwriting, while merging collection fields like headers, params, body, and files by extending existing values.

Parameters:

Name Type Description Default
additional GenerationRequestArguments | dict[str, Any]

Additional arguments to merge with current instance

required

Returns:

Type Description
GenerationRequestArguments

Updated instance with merged arguments

Source code in src/guidellm/schemas/request.py
def model_combine(
    self, additional: GenerationRequestArguments | dict[str, Any]
) -> GenerationRequestArguments:
    """
    Merge additional request arguments into the current instance.

    Combines method and stream fields by overwriting, while merging collection
    fields like headers, params, body, and files by extending existing values.

    :param additional: Additional arguments to merge with current instance
    :return: Updated instance with merged arguments
    """
    additional_dict = (
        additional.model_dump()
        if isinstance(additional, GenerationRequestArguments)
        else additional
    )

    for overwrite in ("method", "stream"):
        if (val := additional_dict.get(overwrite)) is not None:
            setattr(self, overwrite, val)

    for combine in ("headers", "params", "body", "files"):
        if (val := additional_dict.get(combine)) is not None:
            current = getattr(self, combine, None) or {}
            deep_update(current, val)
            setattr(self, combine, current)

    return self

GenerationResponse

Bases: StandardBaseModel

Response model for backend generation operations.

Captures the output and metrics from a generation request, providing structured data for text output, tool call payloads, token usage statistics, and compilation of detailed request statistics for analysis and monitoring purposes.

Example: :: response = GenerationResponse( request_id="req-123", text="Generated response text", input_metrics=UsageMetrics(token_count=50), output_metrics=UsageMetrics(token_count=25) ) stats = response.compile_stats(request, info)

Source code in src/guidellm/schemas/response.py
class GenerationResponse(StandardBaseModel):
    """
    Response model for backend generation operations.

    Captures the output and metrics from a generation request, providing structured
    data for text output, tool call payloads, token usage statistics, and compilation
    of detailed request statistics for analysis and monitoring purposes.

    Example:
    ::
        response = GenerationResponse(
            request_id="req-123",
            text="Generated response text",
            input_metrics=UsageMetrics(token_count=50),
            output_metrics=UsageMetrics(token_count=25)
        )
        stats = response.compile_stats(request, info)
    """

    request_id: str = Field(
        description="Unique identifier matching the original GenerationRequest."
    )
    response_id: str | None = Field(
        default=None,
        description="Unique identifier matching the original vLLM Response ID.",
    )
    request_args: str | None = Field(
        description="Arguments passed to the backend for request processing."
    )
    text: str | None = Field(
        default=None,
        description="The generated response text.",
    )
    reasoning_text: str | None = Field(
        default=None,
        description=(
            "Reasoning/chain-of-thought text emitted before the content. "
            "Not included in multi-turn history unless explicitly enabled."
        ),
    )
    tool_calls: list[ToolCall] | None = Field(
        default=None,
        description=(
            "Raw tool call payloads from the model response, each containing "
            "id, type, and function (name + arguments) in OpenAI format."
        ),
    )
    input_metrics: UsageMetrics = Field(
        default_factory=UsageMetrics,
        description="Token usage statistics from the input prompt.",
    )
    output_metrics: UsageMetrics = Field(
        default_factory=UsageMetrics,
        description="Token usage statistics from the generated output.",
    )

    def compile_stats(
        self,
        request: GenerationRequest,
        info: RequestInfo,
        prefer_response: bool = True,
    ) -> GenerativeRequestStats:
        """
        Compile and return comprehensive request statistics.

        Merges metrics from the request and response objects to create a complete
        statistical record, with preference given to response-level metrics when
        available to ensure accuracy of actual execution data.

        :param request: The original generation request containing input data
        :param info: Metadata and timing information for the request execution
        :param prefer_response: Whether to prefer response metrics over request
            metrics when both are available
        :return: A GenerativeRequestStats object containing detailed statistics
        :raises ValueError: When request IDs don't match between objects
        """
        if request.request_id != self.request_id:
            raise ValueError("Mismatched request IDs between request and response.")

        if info.request_id != self.request_id:
            raise ValueError("Mismatched request IDs between info and response.")

        if info.status != "completed":
            # Clear out request output metrics if the request failed since
            # those are not valid.  Preserve tool_call_count=0 when the
            # request expected a tool call so errored-request statistics
            # still contribute to the tool call metrics table.
            is_tool_call_turn = request.turn_type == "client_tool_call"
            request.output_metrics = UsageMetrics()
            if is_tool_call_turn:
                request.output_metrics.tool_call_count = 0

        base_input = request.input_metrics if prefer_response else self.input_metrics
        override_input = (
            self.input_metrics if prefer_response else request.input_metrics
        )
        base_output = request.output_metrics if prefer_response else self.output_metrics
        override_output = (
            self.output_metrics if prefer_response else request.output_metrics
        )

        input_metrics_dict = base_input.model_dump()
        for key, value in override_input.model_dump().items():
            if value is not None:
                input_metrics_dict[key] = value
        output_metrics_dict = base_output.model_dump()
        for key, value in override_output.model_dump().items():
            if value is not None:
                output_metrics_dict[key] = value

        # If tool calls were expected but none were recorded (either because
        # the request errored or the model produced none with ignore_continue),
        # set tool_call_count=0 so the metrics table still appears.
        if (
            request.turn_type == "client_tool_call"
            and output_metrics_dict.get("tool_call_count") is None
        ):
            output_metrics_dict["tool_call_count"] = 0

        return GenerativeRequestStats(
            request_id=self.request_id,
            response_id=self.response_id,
            request_args=self.request_args,
            output=self.text,
            reasoning_output=self.reasoning_text,
            tool_calls=self.tool_calls,
            info=info,
            input_metrics=UsageMetrics(**input_metrics_dict),
            output_metrics=UsageMetrics(**output_metrics_dict),
        )

compile_stats(request, info, prefer_response=True)

Compile and return comprehensive request statistics.

Merges metrics from the request and response objects to create a complete statistical record, with preference given to response-level metrics when available to ensure accuracy of actual execution data.

Parameters:

Name Type Description Default
request GenerationRequest

The original generation request containing input data

required
info RequestInfo

Metadata and timing information for the request execution

required
prefer_response bool

Whether to prefer response metrics over request metrics when both are available

True

Returns:

Type Description
GenerativeRequestStats

A GenerativeRequestStats object containing detailed statistics

Raises:

Type Description
ValueError

When request IDs don't match between objects

Source code in src/guidellm/schemas/response.py
def compile_stats(
    self,
    request: GenerationRequest,
    info: RequestInfo,
    prefer_response: bool = True,
) -> GenerativeRequestStats:
    """
    Compile and return comprehensive request statistics.

    Merges metrics from the request and response objects to create a complete
    statistical record, with preference given to response-level metrics when
    available to ensure accuracy of actual execution data.

    :param request: The original generation request containing input data
    :param info: Metadata and timing information for the request execution
    :param prefer_response: Whether to prefer response metrics over request
        metrics when both are available
    :return: A GenerativeRequestStats object containing detailed statistics
    :raises ValueError: When request IDs don't match between objects
    """
    if request.request_id != self.request_id:
        raise ValueError("Mismatched request IDs between request and response.")

    if info.request_id != self.request_id:
        raise ValueError("Mismatched request IDs between info and response.")

    if info.status != "completed":
        # Clear out request output metrics if the request failed since
        # those are not valid.  Preserve tool_call_count=0 when the
        # request expected a tool call so errored-request statistics
        # still contribute to the tool call metrics table.
        is_tool_call_turn = request.turn_type == "client_tool_call"
        request.output_metrics = UsageMetrics()
        if is_tool_call_turn:
            request.output_metrics.tool_call_count = 0

    base_input = request.input_metrics if prefer_response else self.input_metrics
    override_input = (
        self.input_metrics if prefer_response else request.input_metrics
    )
    base_output = request.output_metrics if prefer_response else self.output_metrics
    override_output = (
        self.output_metrics if prefer_response else request.output_metrics
    )

    input_metrics_dict = base_input.model_dump()
    for key, value in override_input.model_dump().items():
        if value is not None:
            input_metrics_dict[key] = value
    output_metrics_dict = base_output.model_dump()
    for key, value in override_output.model_dump().items():
        if value is not None:
            output_metrics_dict[key] = value

    # If tool calls were expected but none were recorded (either because
    # the request errored or the model produced none with ignore_continue),
    # set tool_call_count=0 so the metrics table still appears.
    if (
        request.turn_type == "client_tool_call"
        and output_metrics_dict.get("tool_call_count") is None
    ):
        output_metrics_dict["tool_call_count"] = 0

    return GenerativeRequestStats(
        request_id=self.request_id,
        response_id=self.response_id,
        request_args=self.request_args,
        output=self.text,
        reasoning_output=self.reasoning_text,
        tool_calls=self.tool_calls,
        info=info,
        input_metrics=UsageMetrics(**input_metrics_dict),
        output_metrics=UsageMetrics(**output_metrics_dict),
    )

GenerativeRequestStats

Bases: StandardBaseDict

Request statistics for generative AI text generation workloads.

Captures comprehensive performance metrics for individual generative requests, including token counts, timing measurements, and derived performance statistics. Provides computed properties for latency analysis, throughput calculations, and token generation metrics essential for benchmark evaluation.

Example: :: stats = GenerativeRequestStats( request_id="req_123", info=request_info, input_metrics=input_usage, output_metrics=output_usage ) throughput = stats.output_tokens_per_second

Source code in src/guidellm/schemas/request_stats.py
class GenerativeRequestStats(StandardBaseDict):
    """
    Request statistics for generative AI text generation workloads.

    Captures comprehensive performance metrics for individual generative requests,
    including token counts, timing measurements, and derived performance statistics.
    Provides computed properties for latency analysis, throughput calculations,
    and token generation metrics essential for benchmark evaluation.

    Example:
    ::
        stats = GenerativeRequestStats(
            request_id="req_123",
            info=request_info,
            input_metrics=input_usage,
            output_metrics=output_usage
        )
        throughput = stats.output_tokens_per_second
    """

    type_: Literal["generative_request_stats"] = "generative_request_stats"
    request_id: str = Field(description="Unique identifier for the request")
    response_id: str | None = Field(
        default=None, description="Unique identifier matching vLLM Response ID"
    )
    request_args: str | None = Field(
        default=None, description="Backend arguments used for this request"
    )
    output: str | None = Field(
        default=None, description="Generated text output from the request"
    )
    reasoning_output: str | None = Field(
        default=None,
        description="Reasoning/chain-of-thought text emitted before content",
    )
    tool_calls: list[ToolCall] | None = Field(
        default=None,
        description="Raw tool call payloads from the model response in OpenAI format",
    )
    info: RequestInfo = Field(description="Request metadata and timing information")
    input_metrics: UsageMetrics = Field(
        description="Token usage statistics for the input prompt"
    )
    output_metrics: UsageMetrics = Field(
        description="Token usage statistics for the generated output"
    )

    # Request stats
    @computed_field  # type: ignore[misc]
    @property
    def request_start_time(self) -> float | None:
        """
        :return: Timestamp when the request started, or None if unavailable
        """
        return (
            self.info.timings.request_start
            if self.info.timings.request_start is not None
            else self.info.timings.resolve_start
        )

    @computed_field  # type: ignore[misc]
    @property
    def request_end_time(self) -> float:
        """
        :return: Timestamp when the request ended, or None if unavailable
        """
        if self.info.timings.resolve_end is None:
            raise ValueError("resolve_end timings should be set but is None.")

        return (
            self.info.timings.request_end
            if self.info.timings.request_end is not None
            else self.info.timings.resolve_end
        )

    @computed_field  # type: ignore[misc]
    @property
    def request_latency(self) -> float | None:
        """
        End-to-end request processing latency in seconds.

        :return: Duration from request start to completion, or None if unavailable
        """
        start = self.info.timings.request_start
        end = self.info.timings.request_end
        if start is None or end is None:
            return None

        return end - start

    # General token stats
    @computed_field  # type: ignore[misc]
    @property
    def prompt_tokens(self) -> int | None:
        """
        :return: Number of tokens in the input prompt, or None if unavailable
        """
        return self.input_metrics.total_tokens

    @computed_field  # type: ignore[misc]
    @property
    def output_tokens(self) -> int | None:
        """
        :return: Number of tokens in the generated output, or None if unavailable
        """
        # Fallback if we did not get usage metrics from the server
        # NOTE: This assumes each iteration is one token
        if self.output_metrics.total_tokens is None:
            return self.info.timings.token_iterations or None

        return self.output_metrics.total_tokens

    @computed_field  # type: ignore[misc]
    @property
    def total_tokens(self) -> int | None:
        """
        :return: Sum of prompt and output tokens, or None if both unavailable
        """
        input_tokens = self.prompt_tokens
        output_tokens = self.output_tokens

        if input_tokens is None and output_tokens is None:
            return None

        return (input_tokens or 0) + (output_tokens or 0)

    @computed_field  # type: ignore[misc]
    @property
    def time_to_first_token_ms(self) -> float | None:
        """
        :return: Time to first token generation in milliseconds, or None if unavailable
        """
        first_token = self.first_token_iteration
        start = self.info.timings.request_start
        if first_token is None or start is None:
            return None

        return 1000 * (first_token - start)

    @computed_field  # type: ignore[misc]
    @property
    def time_per_output_token_ms(self) -> float | None:
        """
        Average time per output token in milliseconds including first token.

        :return: Average milliseconds per output token, or None if unavailable
        """
        if (
            (start := self.info.timings.request_start) is None
            or (
                (last_token := self.last_token_iteration or self.request_end_time)
                is None
            )
            or (output_tokens := self.output_tokens) is None
            or output_tokens == 0
        ):
            return None

        return 1000 * (last_token - start) / output_tokens

    @computed_field  # type: ignore[misc]
    @property
    def inter_token_latency_ms(self) -> float | None:
        """
        Average inter-token latency in milliseconds excluding first token.

        :return: Average milliseconds between token generations, or None if unavailable
        """
        first_token = self.first_token_iteration
        last_token = self.last_token_iteration
        output_tokens = self.output_tokens
        if (
            first_token is None
            or last_token is None
            or output_tokens is None
            or output_tokens <= 1
        ):
            return None

        return 1000 * (last_token - first_token) / (output_tokens - 1)

    @computed_field  # type: ignore[misc]
    @property
    def tokens_per_second(self) -> float | None:
        """
        :return: Total tokens per second throughput, or None if unavailable
        """
        if not (latency := self.request_latency) or self.total_tokens is None:
            return None

        return self.total_tokens / latency

    @computed_field  # type: ignore[misc]
    @property
    def output_tokens_per_second(self) -> float | None:
        """
        :return: Output token generation throughput, or None if unavailable
        """
        if not (latency := self.request_latency) or self.output_tokens is None:
            return None

        return self.output_tokens / latency

    @computed_field  # type: ignore[misc]
    @property
    def time_to_first_output_token_ms(self) -> float | None:
        """
        Time to first content (non-reasoning) token in milliseconds.

        When no reasoning tokens are emitted this equals TTFT.

        :return: Milliseconds from request start to first content token,
            or None if unavailable
        """
        first_output = self.first_output_token_iteration
        start = self.info.timings.request_start
        if first_output is None or start is None:
            return None
        return 1000 * (first_output - start)

    @computed_field  # type: ignore[misc]
    @property
    def iter_tokens_per_iteration(self) -> float | None:
        """
        :return: Average tokens per iteration excluding first token, or None if
            unavailable
        """
        if (
            self.output_tokens is None
            or self.output_tokens <= 1
            or self.token_iterations <= 1
        ):
            return None

        return (self.output_tokens - 1.0) / (
            self.token_iterations - 1.0
        )  # subtract 1 for first token from the prompt, assume first iter is 1 token

    @computed_field  # type: ignore[misc]
    @property
    def output_tokens_per_iteration(self) -> float | None:
        """
        :return: Average output tokens per iteration, or None if unavailable
        """
        if self.output_tokens is None or self.token_iterations < 1:
            return None

        return self.output_tokens / self.token_iterations

    @property
    def first_token_iteration(self) -> float | None:
        """
        :return: Timestamp of first token generation, or None if unavailable
        """
        return self.info.timings.first_token_iteration

    @property
    def first_output_token_iteration(self) -> float | None:
        """
        :return: Timestamp of first token generation, or None if unavailable
        """
        return self.info.timings.first_output_token_iteration

    @property
    def last_token_iteration(self) -> float | None:
        """
        :return: Timestamp of last token generation, or None if unavailable
        """
        return self.info.timings.last_token_iteration

    @property
    def token_iterations(self) -> int:
        """
        :return: Total number of token generation iterations
        """
        return self.info.timings.token_iterations

    @property
    def prompt_tokens_timing(self) -> tuple[float, float]:
        """
        :return: Tuple of (timestamp, token_count) for prompt processing
        :raises ValueError: If resolve_end timings are not set
        """
        return (
            (
                self.first_token_iteration
                if self.first_token_iteration is not None
                else self.request_end_time
            ),
            self.prompt_tokens or 0.0,
        )

    @property
    def output_tokens_timings(self) -> list[tuple[float, float]]:
        """
        :return: List of (timestamp, token_count) tuples for output token generations
        :raises ValueError: If resolve_end timings are not set
        """
        if (
            self.first_token_iteration is None
            or self.last_token_iteration is None
            or self.token_iterations <= 1
        ):
            # No iteration data, return single timing at end with all tokens
            return [
                (
                    (
                        self.last_token_iteration
                        if self.last_token_iteration is not None
                        else self.request_end_time
                    ),
                    self.output_tokens or 0.0,
                )
            ]

        # Return first token timing as 1 token plus per-iteration timings
        return [
            (self.first_token_iteration, 1.0 * bool(self.output_tokens))
        ] + self.iter_tokens_timings

    @property
    def iter_tokens_timings(self) -> list[tuple[float, float]]:
        """
        :return: List of (timestamp, token_count) tuples for iterations excluding
            first token
        """
        if (
            self.first_token_iteration is None
            or self.last_token_iteration is None
            or (tok_per_iter := self.iter_tokens_per_iteration) is None
            or self.token_iterations <= 1
        ):
            return []

        # evenly space the iterations since we don't have per-iteration timings
        # / we don't know the individual token counts per iteration
        iter_times = np.linspace(
            self.first_token_iteration,
            self.last_token_iteration,
            num=self.token_iterations,
        )[1:]  # skip first iteration

        return [(iter_time, tok_per_iter) for iter_time in iter_times]

    @property
    def total_tokens_timings(self) -> list[tuple[float, float]]:
        """
        :return: List of (timestamp, token_count) tuples for all token generations
        """
        prompt_timings = self.prompt_tokens_timing
        output_timings = self.output_tokens_timings

        return ([prompt_timings] if prompt_timings else []) + output_timings

first_output_token_iteration property

Returns:

Type Description
float | None

Timestamp of first token generation, or None if unavailable

first_token_iteration property

Returns:

Type Description
float | None

Timestamp of first token generation, or None if unavailable

inter_token_latency_ms property

Average inter-token latency in milliseconds excluding first token.

Returns:

Type Description
float | None

Average milliseconds between token generations, or None if unavailable

iter_tokens_per_iteration property

Returns:

Type Description
float | None

Average tokens per iteration excluding first token, or None if unavailable

iter_tokens_timings property

Returns:

Type Description
list[tuple[float, float]]

List of (timestamp, token_count) tuples for iterations excluding first token

last_token_iteration property

Returns:

Type Description
float | None

Timestamp of last token generation, or None if unavailable

output_tokens property

Returns:

Type Description
int | None

Number of tokens in the generated output, or None if unavailable

output_tokens_per_iteration property

Returns:

Type Description
float | None

Average output tokens per iteration, or None if unavailable

output_tokens_per_second property

Returns:

Type Description
float | None

Output token generation throughput, or None if unavailable

output_tokens_timings property

Returns:

Type Description
list[tuple[float, float]]

List of (timestamp, token_count) tuples for output token generations

Raises:

Type Description
ValueError

If resolve_end timings are not set

prompt_tokens property

Returns:

Type Description
int | None

Number of tokens in the input prompt, or None if unavailable

prompt_tokens_timing property

Returns:

Type Description
tuple[float, float]

Tuple of (timestamp, token_count) for prompt processing

Raises:

Type Description
ValueError

If resolve_end timings are not set

request_end_time property

Returns:

Type Description
float

Timestamp when the request ended, or None if unavailable

request_latency property

End-to-end request processing latency in seconds.

Returns:

Type Description
float | None

Duration from request start to completion, or None if unavailable

request_start_time property

Returns:

Type Description
float | None

Timestamp when the request started, or None if unavailable

time_per_output_token_ms property

Average time per output token in milliseconds including first token.

Returns:

Type Description
float | None

Average milliseconds per output token, or None if unavailable

time_to_first_output_token_ms property

Time to first content (non-reasoning) token in milliseconds.

When no reasoning tokens are emitted this equals TTFT.

Returns:

Type Description
float | None

Milliseconds from request start to first content token, or None if unavailable

time_to_first_token_ms property

Returns:

Type Description
float | None

Time to first token generation in milliseconds, or None if unavailable

token_iterations property

Returns:

Type Description
int

Total number of token generation iterations

tokens_per_second property

Returns:

Type Description
float | None

Total tokens per second throughput, or None if unavailable

total_tokens property

Returns:

Type Description
int | None

Sum of prompt and output tokens, or None if both unavailable

total_tokens_timings property

Returns:

Type Description
list[tuple[float, float]]

List of (timestamp, token_count) tuples for all token generations

Percentiles

Bases: StandardBaseModel

Standard percentile values for probability distributions.

Captures key percentile points from 0.1th to 99.9th percentile for comprehensive distribution analysis, enabling assessment of central tendency, spread, and tail behavior in benchmark metrics.

Source code in src/guidellm/schemas/statistics.py
class Percentiles(StandardBaseModel):
    """
    Standard percentile values for probability distributions.

    Captures key percentile points from 0.1th to 99.9th percentile for comprehensive
    distribution analysis, enabling assessment of central tendency, spread, and tail
    behavior in benchmark metrics.
    """

    p001: float = Field(description="0.1th percentile value")
    p01: float = Field(description="1st percentile value")
    p05: float = Field(description="5th percentile value")
    p10: float = Field(description="10th percentile value")
    p25: float = Field(description="25th percentile value")
    p50: float = Field(description="50th percentile (median) value")
    p75: float = Field(description="75th percentile value")
    p90: float = Field(description="90th percentile value")
    p95: float = Field(description="95th percentile value")
    p99: float = Field(description="99th percentile value")
    p999: float = Field(description="99.9th percentile value")

    @classmethod
    def from_pdf(
        cls, pdf: np.ndarray, epsilon: float = 1e-6, validate: bool = True
    ) -> Percentiles:
        """
        Create percentiles from a probability density function.

        :param pdf: 2D array (N, 2) with values in column 0 and probabilities in
            column 1
        :param epsilon: Tolerance for probability sum validation
        :param validate: Whether to validate probabilities sum to 1 and are
            non-negative
        :return: Percentiles object with computed values
        :raises ValueError: If PDF shape is invalid, probabilities are negative,
            or probabilities don't sum to 1
        """
        expected_shape = (None, 2)

        if len(pdf.shape) != len(expected_shape) or pdf.shape[1] != expected_shape[1]:
            raise ValueError(
                "PDF must be a 2D array of shape (N, 2) where first column is values "
                f"and second column is probabilities. Got {pdf.shape} instead."
            )

        percentile_probs = {
            "p001": 0.001,
            "p01": 0.01,
            "p05": 0.05,
            "p10": 0.1,
            "p25": 0.25,
            "p50": 0.5,
            "p75": 0.75,
            "p90": 0.9,
            "p95": 0.95,
            "p99": 0.99,
            "p999": 0.999,
        }

        if pdf.shape[0] == 0:
            return Percentiles(**dict.fromkeys(percentile_probs.keys(), 0.0))

        probabilities = pdf[:, 1]

        if validate:
            if np.any(probabilities < 0):
                raise ValueError("Probabilities must be non-negative.")

            prob_sum = np.sum(probabilities)
            if abs(prob_sum - 1.0) > epsilon:
                raise ValueError(f"Probabilities must sum to 1, got {prob_sum}.")

        cdf_probs = np.cumsum(probabilities)

        return Percentiles(
            **{
                key: pdf[np.searchsorted(cdf_probs, value, side="left"), 0].item()
                for key, value in percentile_probs.items()
            }
        )

from_pdf(pdf, epsilon=1e-06, validate=True) classmethod

Create percentiles from a probability density function.

Parameters:

Name Type Description Default
pdf ndarray

2D array (N, 2) with values in column 0 and probabilities in column 1

required
epsilon float

Tolerance for probability sum validation

1e-06
validate bool

Whether to validate probabilities sum to 1 and are non-negative

True

Returns:

Type Description
Percentiles

Percentiles object with computed values

Raises:

Type Description
ValueError

If PDF shape is invalid, probabilities are negative, or probabilities don't sum to 1

Source code in src/guidellm/schemas/statistics.py
@classmethod
def from_pdf(
    cls, pdf: np.ndarray, epsilon: float = 1e-6, validate: bool = True
) -> Percentiles:
    """
    Create percentiles from a probability density function.

    :param pdf: 2D array (N, 2) with values in column 0 and probabilities in
        column 1
    :param epsilon: Tolerance for probability sum validation
    :param validate: Whether to validate probabilities sum to 1 and are
        non-negative
    :return: Percentiles object with computed values
    :raises ValueError: If PDF shape is invalid, probabilities are negative,
        or probabilities don't sum to 1
    """
    expected_shape = (None, 2)

    if len(pdf.shape) != len(expected_shape) or pdf.shape[1] != expected_shape[1]:
        raise ValueError(
            "PDF must be a 2D array of shape (N, 2) where first column is values "
            f"and second column is probabilities. Got {pdf.shape} instead."
        )

    percentile_probs = {
        "p001": 0.001,
        "p01": 0.01,
        "p05": 0.05,
        "p10": 0.1,
        "p25": 0.25,
        "p50": 0.5,
        "p75": 0.75,
        "p90": 0.9,
        "p95": 0.95,
        "p99": 0.99,
        "p999": 0.999,
    }

    if pdf.shape[0] == 0:
        return Percentiles(**dict.fromkeys(percentile_probs.keys(), 0.0))

    probabilities = pdf[:, 1]

    if validate:
        if np.any(probabilities < 0):
            raise ValueError("Probabilities must be non-negative.")

        prob_sum = np.sum(probabilities)
        if abs(prob_sum - 1.0) > epsilon:
            raise ValueError(f"Probabilities must sum to 1, got {prob_sum}.")

    cdf_probs = np.cumsum(probabilities)

    return Percentiles(
        **{
            key: pdf[np.searchsorted(cdf_probs, value, side="left"), 0].item()
            for key, value in percentile_probs.items()
        }
    )

PydanticClassRegistryMixin

Bases: ReloadableBaseModel, RegistryMixin[type[BaseModelT]], ABC, Generic[BaseModelT]

Polymorphic Pydantic model mixin enabling registry-based dynamic instantiation.

Integrates Pydantic validation with the registry system to enable polymorphic serialization and deserialization based on a discriminator field. Automatically instantiates the correct subclass during validation based on registry mappings, providing a foundation for extensible plugin-style architectures.

Example: :: from speculators.utils import PydanticClassRegistryMixin

class BaseConfig(PydanticClassRegistryMixin["BaseConfig"]):
    schema_discriminator: ClassVar[str] = "config_type"
    config_type: str = Field(description="Configuration type identifier")

    @classmethod
    def __pydantic_schema_base_type__(cls) -> type["BaseConfig"]:
        return BaseConfig

@BaseConfig.register("database")
class DatabaseConfig(BaseConfig):
    config_type: str = "database"
    connection_string: str = Field(description="Database connection string")

# Dynamic instantiation based on discriminator
config = BaseConfig.model_validate({
    "config_type": "database",
    "connection_string": "postgresql://localhost:5432/db"
})

Attributes:

Name Type Description
schema_discriminator str

Field name used for polymorphic type discrimination

Source code in src/guidellm/schemas/base.py
class PydanticClassRegistryMixin(
    ReloadableBaseModel, RegistryMixin[type[BaseModelT]], ABC, Generic[BaseModelT]
):
    """
    Polymorphic Pydantic model mixin enabling registry-based dynamic instantiation.

    Integrates Pydantic validation with the registry system to enable polymorphic
    serialization and deserialization based on a discriminator field. Automatically
    instantiates the correct subclass during validation based on registry mappings,
    providing a foundation for extensible plugin-style architectures.

    Example:
    ::
        from speculators.utils import PydanticClassRegistryMixin

        class BaseConfig(PydanticClassRegistryMixin["BaseConfig"]):
            schema_discriminator: ClassVar[str] = "config_type"
            config_type: str = Field(description="Configuration type identifier")

            @classmethod
            def __pydantic_schema_base_type__(cls) -> type["BaseConfig"]:
                return BaseConfig

        @BaseConfig.register("database")
        class DatabaseConfig(BaseConfig):
            config_type: str = "database"
            connection_string: str = Field(description="Database connection string")

        # Dynamic instantiation based on discriminator
        config = BaseConfig.model_validate({
            "config_type": "database",
            "connection_string": "postgresql://localhost:5432/db"
        })

    :cvar schema_discriminator: Field name used for polymorphic type discrimination
    """

    schema_discriminator: ClassVar[str] = "model_type"

    def __new__(cls, *args, **kwargs):  # noqa: ARG004
        """
        Prevent direct instantiation of base classes that use this mixin.

        Only allows instantiation of concrete subclasses, not the base class.
        """
        base_type = cls.__pydantic_schema_base_type__()
        if cls is base_type:
            raise TypeError(f"only children of '{cls.__name__}' may be instantiated")
        return super().__new__(cls)

    @classmethod
    def register_decorator(
        cls, clazz: RegisterClassT, name: str | list[str] | None = None
    ) -> RegisterClassT:
        """
        Register a Pydantic model class with type validation and schema reload.

        Validates that the class is a proper Pydantic BaseModel subclass before
        registering it in the class registry. Automatically triggers schema
        reload to incorporate the new type into polymorphic validation.

        :param clazz: Pydantic model class to register in the polymorphic hierarchy
        :param name: Registry identifier for the class. Uses class name if None
        :return: The registered class unchanged for decorator chaining
        :raises TypeError: If clazz is not a Pydantic BaseModel subclass
        """
        if not issubclass(clazz, BaseModel):
            raise TypeError(
                f"Cannot register {clazz.__name__} as it is not a subclass of "
                "Pydantic BaseModel"
            )

        super().register_decorator(clazz, name=name)
        cls.reload_schema()

        return cast("RegisterClassT", clazz)

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source_type: Any, handler: GetCoreSchemaHandler
    ) -> CoreSchema:
        """
        Generate polymorphic validation schema for dynamic type instantiation.

        Creates a tagged union schema that enables Pydantic to automatically
        instantiate the correct subclass based on the discriminator field value.
        Falls back to base schema generation when no registry is available.

        :param source_type: Type being processed for schema generation
        :param handler: Pydantic core schema generation handler
        :return: Tagged union schema for polymorphic validation or base schema
        """
        if source_type == cls.__pydantic_schema_base_type__():
            if not cls.registry:
                return cls.__pydantic_generate_base_schema__(handler)

            choices = {
                name: handler(model_class) for name, model_class in cls.registry.items()
            }

            return core_schema.tagged_union_schema(
                choices=choices,
                discriminator=cls.schema_discriminator,
            )

        return handler(cls)

    @classmethod
    @abstractmethod
    def __pydantic_schema_base_type__(cls) -> type[BaseModelT]:
        """
        Define the base type for polymorphic validation hierarchy.

        Must be implemented by subclasses to specify which type serves as the
        root of the polymorphic hierarchy for schema generation and validation.

        :return: Base class type for the polymorphic model hierarchy
        """
        ...

    @classmethod
    def __pydantic_generate_base_schema__(
        cls, handler: GetCoreSchemaHandler
    ) -> CoreSchema:
        """
        Generate fallback schema for polymorphic models without registry.

        Provides a base schema that accepts any valid input when no registry
        is available for polymorphic validation. Used as fallback during
        schema generation when the registry has not been populated.

        :param handler: Pydantic core schema generation handler
        :return: Base CoreSchema that accepts any valid input
        """
        return core_schema.any_schema()

    @classmethod
    def auto_populate_registry(cls) -> bool:
        """
        Initialize registry with auto-discovery and reload validation schema.

        Triggers automatic population of the class registry through the parent
        RegistryMixin functionality and ensures the Pydantic validation schema
        is updated to include all discovered types for polymorphic validation.

        :return: True if registry was populated, False if already populated
        :raises ValueError: If called when registry_auto_discovery is disabled
        """
        populated = super().auto_populate_registry()
        cls.reload_schema()

        return populated

    @classmethod
    def registered_classes(cls) -> tuple[type[BaseModelT], ...]:
        """
        Get all registered pydantic classes from the registry.

        Automatically triggers auto-discovery if registry_auto_discovery is enabled
        to ensure all available implementations are included.

        :return: Tuple of all registered classes including auto-discovered ones
        :raises ValueError: If called before any objects have been registered
        """
        if cls.registry_auto_discovery:
            cls.auto_populate_registry()

        if cls.registry is None:
            raise ValueError(
                "ClassRegistryMixin.registered_classes() must be called after "
                "registering classes with ClassRegistryMixin.register()."
            )

        return tuple(cls.registry.values())

__get_pydantic_core_schema__(source_type, handler) classmethod

Generate polymorphic validation schema for dynamic type instantiation.

Creates a tagged union schema that enables Pydantic to automatically instantiate the correct subclass based on the discriminator field value. Falls back to base schema generation when no registry is available.

Parameters:

Name Type Description Default
source_type Any

Type being processed for schema generation

required
handler GetCoreSchemaHandler

Pydantic core schema generation handler

required

Returns:

Type Description
CoreSchema

Tagged union schema for polymorphic validation or base schema

Source code in src/guidellm/schemas/base.py
@classmethod
def __get_pydantic_core_schema__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """
    Generate polymorphic validation schema for dynamic type instantiation.

    Creates a tagged union schema that enables Pydantic to automatically
    instantiate the correct subclass based on the discriminator field value.
    Falls back to base schema generation when no registry is available.

    :param source_type: Type being processed for schema generation
    :param handler: Pydantic core schema generation handler
    :return: Tagged union schema for polymorphic validation or base schema
    """
    if source_type == cls.__pydantic_schema_base_type__():
        if not cls.registry:
            return cls.__pydantic_generate_base_schema__(handler)

        choices = {
            name: handler(model_class) for name, model_class in cls.registry.items()
        }

        return core_schema.tagged_union_schema(
            choices=choices,
            discriminator=cls.schema_discriminator,
        )

    return handler(cls)

__new__(*args, **kwargs)

Prevent direct instantiation of base classes that use this mixin.

Only allows instantiation of concrete subclasses, not the base class.

Source code in src/guidellm/schemas/base.py
def __new__(cls, *args, **kwargs):  # noqa: ARG004
    """
    Prevent direct instantiation of base classes that use this mixin.

    Only allows instantiation of concrete subclasses, not the base class.
    """
    base_type = cls.__pydantic_schema_base_type__()
    if cls is base_type:
        raise TypeError(f"only children of '{cls.__name__}' may be instantiated")
    return super().__new__(cls)

__pydantic_generate_base_schema__(handler) classmethod

Generate fallback schema for polymorphic models without registry.

Provides a base schema that accepts any valid input when no registry is available for polymorphic validation. Used as fallback during schema generation when the registry has not been populated.

Parameters:

Name Type Description Default
handler GetCoreSchemaHandler

Pydantic core schema generation handler

required

Returns:

Type Description
CoreSchema

Base CoreSchema that accepts any valid input

Source code in src/guidellm/schemas/base.py
@classmethod
def __pydantic_generate_base_schema__(
    cls, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """
    Generate fallback schema for polymorphic models without registry.

    Provides a base schema that accepts any valid input when no registry
    is available for polymorphic validation. Used as fallback during
    schema generation when the registry has not been populated.

    :param handler: Pydantic core schema generation handler
    :return: Base CoreSchema that accepts any valid input
    """
    return core_schema.any_schema()

__pydantic_schema_base_type__() abstractmethod classmethod

Define the base type for polymorphic validation hierarchy.

Must be implemented by subclasses to specify which type serves as the root of the polymorphic hierarchy for schema generation and validation.

Returns:

Type Description
type[BaseModelT]

Base class type for the polymorphic model hierarchy

Source code in src/guidellm/schemas/base.py
@classmethod
@abstractmethod
def __pydantic_schema_base_type__(cls) -> type[BaseModelT]:
    """
    Define the base type for polymorphic validation hierarchy.

    Must be implemented by subclasses to specify which type serves as the
    root of the polymorphic hierarchy for schema generation and validation.

    :return: Base class type for the polymorphic model hierarchy
    """
    ...

auto_populate_registry() classmethod

Initialize registry with auto-discovery and reload validation schema.

Triggers automatic population of the class registry through the parent RegistryMixin functionality and ensures the Pydantic validation schema is updated to include all discovered types for polymorphic validation.

Returns:

Type Description
bool

True if registry was populated, False if already populated

Raises:

Type Description
ValueError

If called when registry_auto_discovery is disabled

Source code in src/guidellm/schemas/base.py
@classmethod
def auto_populate_registry(cls) -> bool:
    """
    Initialize registry with auto-discovery and reload validation schema.

    Triggers automatic population of the class registry through the parent
    RegistryMixin functionality and ensures the Pydantic validation schema
    is updated to include all discovered types for polymorphic validation.

    :return: True if registry was populated, False if already populated
    :raises ValueError: If called when registry_auto_discovery is disabled
    """
    populated = super().auto_populate_registry()
    cls.reload_schema()

    return populated

register_decorator(clazz, name=None) classmethod

Register a Pydantic model class with type validation and schema reload.

Validates that the class is a proper Pydantic BaseModel subclass before registering it in the class registry. Automatically triggers schema reload to incorporate the new type into polymorphic validation.

Parameters:

Name Type Description Default
clazz RegisterClassT

Pydantic model class to register in the polymorphic hierarchy

required
name str | list[str] | None

Registry identifier for the class. Uses class name if None

None

Returns:

Type Description
RegisterClassT

The registered class unchanged for decorator chaining

Raises:

Type Description
TypeError

If clazz is not a Pydantic BaseModel subclass

Source code in src/guidellm/schemas/base.py
@classmethod
def register_decorator(
    cls, clazz: RegisterClassT, name: str | list[str] | None = None
) -> RegisterClassT:
    """
    Register a Pydantic model class with type validation and schema reload.

    Validates that the class is a proper Pydantic BaseModel subclass before
    registering it in the class registry. Automatically triggers schema
    reload to incorporate the new type into polymorphic validation.

    :param clazz: Pydantic model class to register in the polymorphic hierarchy
    :param name: Registry identifier for the class. Uses class name if None
    :return: The registered class unchanged for decorator chaining
    :raises TypeError: If clazz is not a Pydantic BaseModel subclass
    """
    if not issubclass(clazz, BaseModel):
        raise TypeError(
            f"Cannot register {clazz.__name__} as it is not a subclass of "
            "Pydantic BaseModel"
        )

    super().register_decorator(clazz, name=name)
    cls.reload_schema()

    return cast("RegisterClassT", clazz)

registered_classes() classmethod

Get all registered pydantic classes from the registry.

Automatically triggers auto-discovery if registry_auto_discovery is enabled to ensure all available implementations are included.

Returns:

Type Description
tuple[type[BaseModelT], ...]

Tuple of all registered classes including auto-discovered ones

Raises:

Type Description
ValueError

If called before any objects have been registered

Source code in src/guidellm/schemas/base.py
@classmethod
def registered_classes(cls) -> tuple[type[BaseModelT], ...]:
    """
    Get all registered pydantic classes from the registry.

    Automatically triggers auto-discovery if registry_auto_discovery is enabled
    to ensure all available implementations are included.

    :return: Tuple of all registered classes including auto-discovered ones
    :raises ValueError: If called before any objects have been registered
    """
    if cls.registry_auto_discovery:
        cls.auto_populate_registry()

    if cls.registry is None:
        raise ValueError(
            "ClassRegistryMixin.registered_classes() must be called after "
            "registering classes with ClassRegistryMixin.register()."
        )

    return tuple(cls.registry.values())

ReloadableBaseModel

Bases: BaseModel

Base Pydantic model with schema reloading capabilities.

Provides dynamic schema rebuilding functionality for models that need to update their validation schemas at runtime, particularly useful when working with registry-based polymorphic models where new types are registered after initial class definition.

Source code in src/guidellm/schemas/base.py
class ReloadableBaseModel(BaseModel):
    """
    Base Pydantic model with schema reloading capabilities.

    Provides dynamic schema rebuilding functionality for models that need to
    update their validation schemas at runtime, particularly useful when
    working with registry-based polymorphic models where new types are
    registered after initial class definition.
    """

    model_config = standard_model_config(extra="ignore")

    @classmethod
    def reload_schema(cls, parents: bool = False) -> None:
        """
        Reload the class schema with updated registry information.

        Forces a complete rebuild of the Pydantic model schema to incorporate
        any changes made to associated registries or validation rules.

        :param parents: Whether to also rebuild schemas for any pydantic parent
            types that reference this model.
        """
        cls.model_rebuild(force=True)

        if parents:
            cls.reload_parent_schemas()

    @classmethod
    def reload_parent_schemas(cls):
        """
        Recursively reload schemas for all Pydantic models that reference this
        class in their field annotations.

        Walks the subclass trees of guidellm's own model roots
        (ReloadableBaseModel and StandardBaseModel) rather than all BaseModel
        subclasses, so third-party Pydantic models loaded in the same process
        are not visited.
        """
        potential_parents: set[type[BaseModel]] = {
            ReloadableBaseModel,
            StandardBaseModel,
        }
        stack: list[type[BaseModel]] = list(potential_parents)

        while stack:
            current = stack.pop()
            for subclass in current.__subclasses__():
                if (
                    issubclass(subclass, BaseModel)
                    and subclass is not cls
                    and subclass not in potential_parents
                ):
                    potential_parents.add(subclass)
                    stack.append(subclass)

        for check in cls.__mro__:
            if isinstance(check, type) and issubclass(check, BaseModel):
                cls._reload_schemas_depending_on(check, potential_parents)

    @classmethod
    def _reload_schemas_depending_on(cls, target: type[BaseModel], types: set[type]):
        changed = True
        while changed:
            changed = False
            for candidate in types:
                if (
                    isinstance(candidate, type)
                    and issubclass(candidate, BaseModel)
                    and any(
                        cls._uses_type(target, field_info.annotation)
                        for field_info in candidate.model_fields.values()
                        if field_info.annotation is not None
                    )
                ):
                    try:
                        before = candidate.model_json_schema()
                    except Exception:  # noqa: BLE001
                        before = None
                    candidate.model_rebuild(force=True)
                    if before is not None:
                        after = candidate.model_json_schema()
                        changed |= before != after

    @classmethod
    def _uses_type(cls, target: type, candidate: type) -> bool:
        if target is candidate:
            return True

        origin = get_origin(candidate)

        if origin is None:
            return isinstance(candidate, type) and issubclass(candidate, target)

        if isinstance(origin, type) and (
            target is origin or issubclass(origin, target)
        ):
            return True

        for arg in get_args(candidate) or []:
            if isinstance(arg, type) and cls._uses_type(target, arg):
                return True

        return False

reload_parent_schemas() classmethod

Recursively reload schemas for all Pydantic models that reference this class in their field annotations.

Walks the subclass trees of guidellm's own model roots (ReloadableBaseModel and StandardBaseModel) rather than all BaseModel subclasses, so third-party Pydantic models loaded in the same process are not visited.

Source code in src/guidellm/schemas/base.py
@classmethod
def reload_parent_schemas(cls):
    """
    Recursively reload schemas for all Pydantic models that reference this
    class in their field annotations.

    Walks the subclass trees of guidellm's own model roots
    (ReloadableBaseModel and StandardBaseModel) rather than all BaseModel
    subclasses, so third-party Pydantic models loaded in the same process
    are not visited.
    """
    potential_parents: set[type[BaseModel]] = {
        ReloadableBaseModel,
        StandardBaseModel,
    }
    stack: list[type[BaseModel]] = list(potential_parents)

    while stack:
        current = stack.pop()
        for subclass in current.__subclasses__():
            if (
                issubclass(subclass, BaseModel)
                and subclass is not cls
                and subclass not in potential_parents
            ):
                potential_parents.add(subclass)
                stack.append(subclass)

    for check in cls.__mro__:
        if isinstance(check, type) and issubclass(check, BaseModel):
            cls._reload_schemas_depending_on(check, potential_parents)

reload_schema(parents=False) classmethod

Reload the class schema with updated registry information.

Forces a complete rebuild of the Pydantic model schema to incorporate any changes made to associated registries or validation rules.

Parameters:

Name Type Description Default
parents bool

Whether to also rebuild schemas for any pydantic parent types that reference this model.

False
Source code in src/guidellm/schemas/base.py
@classmethod
def reload_schema(cls, parents: bool = False) -> None:
    """
    Reload the class schema with updated registry information.

    Forces a complete rebuild of the Pydantic model schema to incorporate
    any changes made to associated registries or validation rules.

    :param parents: Whether to also rebuild schemas for any pydantic parent
        types that reference this model.
    """
    cls.model_rebuild(force=True)

    if parents:
        cls.reload_parent_schemas()

RequestInfo

Bases: StandardBaseModel

Complete information about a request in the scheduler system.

Encapsulates all metadata, status tracking, and timing information for requests processed through the distributed scheduler. Provides comprehensive lifecycle tracking from initial queuing through final completion, including error handling and node identification for debugging and performance analysis.

Example: :: request = RequestInfo() request.status = "in_progress" start_time = request.started_at completion_time = request.completed_at

Source code in src/guidellm/schemas/info.py
class RequestInfo(StandardBaseModel):
    """
    Complete information about a request in the scheduler system.

    Encapsulates all metadata, status tracking, and timing information for requests
    processed through the distributed scheduler. Provides comprehensive lifecycle
    tracking from initial queuing through final completion, including error handling
    and node identification for debugging and performance analysis.

    Example:
    ::
        request = RequestInfo()
        request.status = "in_progress"
        start_time = request.started_at
        completion_time = request.completed_at
    """

    request_id: str = Field(
        description="Unique identifier for the request",
        default_factory=lambda: str(uuid.uuid4()),
    )
    conversation_id: str | None = Field(
        default=None,
        description=(
            "Identifier for the conversation this request is part of, if applicable."
        ),
    )
    turn_index: int = Field(
        default=0,
        description="Index of the request within the conversation, if applicable.",
    )
    status: Literal[
        "queued",
        "pending",
        "in_progress",
        "first_token",
        "completed",
        "errored",
        "cancelled",
    ] = Field(description="Current processing status of the request", default="queued")
    scheduler_node_id: int = Field(
        description="ID/rank of the scheduler node handling the request",
        default=-1,
    )
    scheduler_process_id: int = Field(
        description="ID/rank of the node's scheduler process handling the request",
        default=-1,
    )
    scheduler_start_time: float = Field(
        description="Unix timestamp when scheduler processing began",
        default=-1,
    )
    timings: RequestTimings = Field(
        default_factory=RequestTimings,
        description="Timing measurements for the request lifecycle",
    )
    settings: RequestSettings = Field(
        default_factory=RequestSettings,
        description="Per-request scheduling metadata for strategy interpretation",
    )

    error: str | None = Field(
        default=None, description="Error message if the request status is 'errored'"
    )
    traceback: str | None = Field(
        default=None,
        description="Full traceback of the error if the request status is 'errored'",
    )

    @computed_field  # type: ignore[misc]
    @property
    def started_at(self) -> float | None:
        """
        Get the effective request processing start time.

        :return: Unix timestamp when processing began, or None if not started
        """
        return self.timings.request_start or self.timings.resolve_start

    @computed_field  # type: ignore[misc]
    @property
    def completed_at(self) -> float | None:
        """
        Get the effective request processing completion time.

        :return: Unix timestamp when processing completed, or None if not completed
        """
        return self.timings.request_end or self.timings.resolve_end

    def model_copy(self, **_kwargs) -> RequestInfo:  # type: ignore[override]  # noqa: ARG002
        """
        Create a deep copy of the request info with copied timing objects.

        :param kwargs: Additional keyword arguments for model copying
        :return: New RequestInfo instance with independent timing objects
        """
        return super().model_copy(
            update={
                "timings": self.timings.model_copy(),
                "settings": self.settings.model_copy(),
            },
            deep=False,
        )

completed_at property

Get the effective request processing completion time.

Returns:

Type Description
float | None

Unix timestamp when processing completed, or None if not completed

started_at property

Get the effective request processing start time.

Returns:

Type Description
float | None

Unix timestamp when processing began, or None if not started

model_copy(**_kwargs)

Create a deep copy of the request info with copied timing objects.

Parameters:

Name Type Description Default
kwargs

Additional keyword arguments for model copying

required

Returns:

Type Description
RequestInfo

New RequestInfo instance with independent timing objects

Source code in src/guidellm/schemas/info.py
def model_copy(self, **_kwargs) -> RequestInfo:  # type: ignore[override]  # noqa: ARG002
    """
    Create a deep copy of the request info with copied timing objects.

    :param kwargs: Additional keyword arguments for model copying
    :return: New RequestInfo instance with independent timing objects
    """
    return super().model_copy(
        update={
            "timings": self.timings.model_copy(),
            "settings": self.settings.model_copy(),
        },
        deep=False,
    )

RequestSettings

Bases: StandardBaseDict

Per-request scheduling metadata attached at enqueue, before worker dequeue.

Populated by dataset finalizers (for example from trace relative_timestamp columns). Scheduling strategies read these fields at dequeue. For trace replay, a non-null relative_timestamp becomes an absolute start time at dequeue: start_time + time_scale * relative_timestamp. When relative_timestamp is null, trace replay schedules the request at benchmark start (no trace offset).

Source code in src/guidellm/schemas/info.py
class RequestSettings(StandardBaseDict):
    """
    Per-request scheduling metadata attached at enqueue, before worker dequeue.

    Populated by dataset finalizers (for example from trace ``relative_timestamp``
    columns). Scheduling strategies read these fields at dequeue. For trace replay,
    a non-null ``relative_timestamp`` becomes an absolute start time at dequeue:
    ``start_time + time_scale * relative_timestamp``. When ``relative_timestamp``
    is null, trace replay schedules the request at benchmark start (no trace offset).
    """

    relative_timestamp: float | None = Field(
        default=None,
        ge=0,
        description=(
            "Trace offset in seconds from the first event after sorting (0 for the "
            "earliest event). Trace replay converts this to an absolute start time "
            "at dequeue: start_time + time_scale * relative_timestamp. When null, "
            "trace replay uses benchmark start time only."
        ),
    )
    requeue_delay: float | None = Field(
        default=None,
        gt=0,
        description=(
            "Delay in seconds before requeueing the conversation. This number is a "
            "lower bound on the delay, subject to scheduling."
        ),
    )

RequestTimings

Bases: StandardBaseDict

Timing measurements for tracking request lifecycle events.

Provides comprehensive timing data for distributed request processing, capturing key timestamps from initial targeting through final completion. Essential for performance analysis, SLA monitoring, and debugging request processing bottlenecks across scheduler workers and backend systems.

Source code in src/guidellm/schemas/info.py
class RequestTimings(StandardBaseDict):
    """
    Timing measurements for tracking request lifecycle events.

    Provides comprehensive timing data for distributed request processing, capturing
    key timestamps from initial targeting through final completion. Essential for
    performance analysis, SLA monitoring, and debugging request processing bottlenecks
    across scheduler workers and backend systems.
    """

    targeted_start: float | None = Field(
        default=None,
        description="Unix timestamp when request was initially targeted for execution",
    )
    queued: float | None = Field(
        default=None,
        description="Unix timestamp when request was placed into processing queue",
    )
    dequeued: float | None = Field(
        default=None,
        description="Unix timestamp when request was removed from queue for processing",
    )
    scheduled_at: float | None = Field(
        default=None,
        description="Unix timestamp when the request was scheduled for processing",
    )
    resolve_start: float | None = Field(
        default=None,
        description="Unix timestamp when backend resolution of the request began",
    )
    request_start: float | None = Field(
        default=None,
        description="Unix timestamp when the backend began processing the request",
    )
    first_request_iteration: float | None = Field(
        default=None,
    )
    first_token_iteration: float | None = Field(
        default=None,
    )
    first_output_token_iteration: float | None = Field(
        default=None,
        description=(
            "Unix timestamp of the first non-reasoning content token. "
            "Equals first_token_iteration when no reasoning tokens are emitted."
        ),
    )
    last_token_iteration: float | None = Field(
        default=None,
    )
    last_request_iteration: float | None = Field(
        default=None,
    )
    request_iterations: int = Field(
        default=0,
    )
    token_iterations: int = Field(
        default=0,
    )
    request_end: float | None = Field(
        default=None,
        description="Unix timestamp when the backend completed processing the request",
    )
    resolve_end: float | None = Field(
        default=None,
        description="Unix timestamp when backend resolution of the request completed",
    )
    finalized: float | None = Field(
        default=None,
        description="Unix timestamp when request was processed by the scheduler",
    )

    @property
    def last_reported(self) -> float | None:
        """
        Get the most recent timing measurement available.

        :return: The latest Unix timestamp from the timing fields, or None if none
        """
        timing_fields = [
            self.queued,
            self.dequeued,
            self.scheduled_at,
            self.resolve_start,
            self.request_start,
            self.request_end,
            self.resolve_end,
        ]
        valid_timings = [field for field in timing_fields if field is not None]
        return max(valid_timings) if valid_timings else None

last_reported property

Get the most recent timing measurement available.

Returns:

Type Description
float | None

The latest Unix timestamp from the timing fields, or None if none

StandardBaseDict

Bases: StandardBaseModel

Base Pydantic model allowing arbitrary additional fields.

Extends StandardBaseModel to accept extra fields beyond those explicitly defined in the model schema. Useful for flexible data structures that need to accommodate varying or unknown field sets while maintaining type safety for known fields.

Source code in src/guidellm/schemas/base.py
class StandardBaseDict(StandardBaseModel):
    """
    Base Pydantic model allowing arbitrary additional fields.

    Extends StandardBaseModel to accept extra fields beyond those explicitly
    defined in the model schema. Useful for flexible data structures that
    need to accommodate varying or unknown field sets while maintaining
    type safety for known fields.
    """

    model_config = standard_model_config(extra="allow")

StandardBaseModel

Bases: BaseModel

Base Pydantic model with standardized configuration for GuideLLM.

Provides consistent validation behavior and configuration settings across all Pydantic models in the application, including field validation, attribute conversion, and default value handling.

Example: :: class MyModel(StandardBaseModel): name: str value: int = 42

# Access default values
default_value = MyModel.get_default("value")  # Returns 42
Source code in src/guidellm/schemas/base.py
class StandardBaseModel(BaseModel):
    """
    Base Pydantic model with standardized configuration for GuideLLM.

    Provides consistent validation behavior and configuration settings across
    all Pydantic models in the application, including field validation,
    attribute conversion, and default value handling.

    Example:
    ::
        class MyModel(StandardBaseModel):
            name: str
            value: int = 42

        # Access default values
        default_value = MyModel.get_default("value")  # Returns 42
    """

    model_config = standard_model_config(extra="ignore")

    @classmethod
    def get_default(cls: type[BaseModel], field: str) -> Any:
        """
        Get default value for a model field.

        :param field: Name of the field to get the default value for
        :return: Default value of the specified field
        :raises KeyError: If the field does not exist in the model
        """
        return cls.model_fields[field].default

get_default(field) classmethod

Get default value for a model field.

Parameters:

Name Type Description Default
field str

Name of the field to get the default value for

required

Returns:

Type Description
Any

Default value of the specified field

Raises:

Type Description
KeyError

If the field does not exist in the model

Source code in src/guidellm/schemas/base.py
@classmethod
def get_default(cls: type[BaseModel], field: str) -> Any:
    """
    Get default value for a model field.

    :param field: Name of the field to get the default value for
    :return: Default value of the specified field
    :raises KeyError: If the field does not exist in the model
    """
    return cls.model_fields[field].default

StatusBreakdown

Bases: BaseModel, Generic[SuccessfulT, ErroredT, IncompleteT, TotalT]

Generic model for organizing results by processing status.

Provides structured categorization of results into successful, errored, incomplete, and total status groups. Supports flexible typing for each status category to accommodate different result types while maintaining consistent organization patterns across the application.

Example: :: from guidellm.utils import StatusBreakdown

# Define a breakdown for request counts
breakdown = StatusBreakdown[int, int, int, int](
    successful=150,
    errored=5,
    incomplete=10,
    total=165
)
Source code in src/guidellm/schemas/base.py
class StatusBreakdown(BaseModel, Generic[SuccessfulT, ErroredT, IncompleteT, TotalT]):
    """
    Generic model for organizing results by processing status.

    Provides structured categorization of results into successful, errored,
    incomplete, and total status groups. Supports flexible typing for each
    status category to accommodate different result types while maintaining
    consistent organization patterns across the application.

    Example:
    ::
        from guidellm.utils import StatusBreakdown

        # Define a breakdown for request counts
        breakdown = StatusBreakdown[int, int, int, int](
            successful=150,
            errored=5,
            incomplete=10,
            total=165
        )
    """

    successful: SuccessfulT = Field(
        description="Results or metrics for requests with successful completion status",
        default=None,  # type: ignore[assignment]
    )
    errored: ErroredT = Field(
        description="Results or metrics for requests with error completion status",
        default=None,  # type: ignore[assignment]
    )
    incomplete: IncompleteT = Field(
        description="Results or metrics for requests with incomplete processing status",
        default=None,  # type: ignore[assignment]
    )
    total: TotalT = Field(
        description="Aggregated results or metrics combining all status categories",
        default=None,  # type: ignore[assignment]
    )

StatusDistributionSummary

Bases: StatusBreakdown[DistributionSummary, DistributionSummary, DistributionSummary, DistributionSummary]

Distribution summaries broken down by request status categories.

Provides separate statistical analysis for successful, incomplete, and errored requests with total aggregate statistics. Enables status-aware performance analysis and SLO validation across different request outcomes in benchmark results.

Source code in src/guidellm/schemas/statistics.py
 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
 759
 760
 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
class StatusDistributionSummary(
    StatusBreakdown[
        DistributionSummary,
        DistributionSummary,
        DistributionSummary,
        DistributionSummary,
    ]
):
    """
    Distribution summaries broken down by request status categories.

    Provides separate statistical analysis for successful, incomplete, and errored
    requests with total aggregate statistics. Enables status-aware performance analysis
    and SLO validation across different request outcomes in benchmark results.
    """

    @property
    def count(self) -> int:
        """
        :return: Total count of samples across all status categories
        """
        return self.total.count

    @property
    def total_sum(self) -> float:
        """
        :return: Total sum of values across all status categories
        """
        return self.total.total_sum

    @classmethod
    def from_values(
        cls,
        successful: Sequence[float | tuple[float, float]] | np.ndarray,
        incomplete: Sequence[float | tuple[float, float]] | np.ndarray,
        errored: Sequence[float | tuple[float, float]] | np.ndarray,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create status-broken-down distribution from values by status category.

        :param successful: Values or (value, weight) tuples for successful requests
        :param incomplete: Values or (value, weight) tuples for incomplete requests
        :param errored: Values or (value, weight) tuples for errored requests
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of distribution summaries
        """
        total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
            successful, incomplete, errored, num_values_per_item=2
        )

        return StatusDistributionSummary(
            total=DistributionSummary.from_values(
                total, include_pdf=include_pdf, epsilon=epsilon
            ),
            successful=DistributionSummary.from_values(
                successful_arr, include_pdf=include_pdf, epsilon=epsilon
            ),
            incomplete=DistributionSummary.from_values(
                incomplete_arr, include_pdf=include_pdf, epsilon=epsilon
            ),
            errored=DistributionSummary.from_values(
                errored_arr, include_pdf=include_pdf, epsilon=epsilon
            ),
        )

    @classmethod
    def from_values_function(
        cls,
        function: Callable[
            [FunctionObjT],
            float | tuple[float, float] | Sequence[float | tuple[float, float]] | None,
        ],
        successful: Sequence[FunctionObjT],
        incomplete: Sequence[FunctionObjT],
        errored: Sequence[FunctionObjT],
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create distribution summary by extracting values from objects via function.

        :param function: Function to extract value(s) from each object
        :param successful: Successful request objects
        :param incomplete: Incomplete request objects
        :param errored: Errored request objects
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of distribution summaries
        """

        def _extract_values(
            _objs: Sequence[FunctionObjT],
        ) -> Sequence[float | tuple[float, float]]:
            _outputs: list[float | tuple[float, float]] = []
            for _obj in _objs:
                if (_result := function(_obj)) is None:
                    continue
                if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                    _outputs.extend(_result)
                else:
                    _outputs.append(_result)
            return _outputs

        return cls.from_values(
            successful=_extract_values(successful),
            incomplete=_extract_values(incomplete),
            errored=_extract_values(errored),
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    @classmethod
    def rate_distribution_from_timings(
        cls,
        successful: Sequence[float | tuple[float, float]] | np.ndarray,
        incomplete: Sequence[float | tuple[float, float]] | np.ndarray,
        errored: Sequence[float | tuple[float, float]] | np.ndarray,
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create status-broken-down rate distribution from event timestamps.

        :param successful: Timestamps for successful request events
        :param incomplete: Timestamps for incomplete request events
        :param errored: Timestamps for errored request events
        :param start_time: Analysis window start
        :param end_time: Analysis window end
        :param threshold: Time threshold for merging nearby events
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of rate distribution summaries
        """
        total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
            successful, incomplete, errored, num_values_per_item=2
        )

        return StatusDistributionSummary(
            total=DistributionSummary.rate_distribution_from_timings(
                total,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            successful=DistributionSummary.rate_distribution_from_timings(
                successful_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            incomplete=DistributionSummary.rate_distribution_from_timings(
                incomplete_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            errored=DistributionSummary.rate_distribution_from_timings(
                errored_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
        )

    @classmethod
    def rate_distribution_from_timings_function(
        cls,
        function: Callable[
            [FunctionObjT],
            float | tuple[float, float] | Sequence[float | tuple[float, float]] | None,
        ],
        successful: Sequence[FunctionObjT],
        incomplete: Sequence[FunctionObjT],
        errored: Sequence[FunctionObjT],
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create rate distribution by extracting timestamps from objects via function.

        :param function: Function to extract timestamp(s) from each object
        :param successful: Successful request objects
        :param incomplete: Incomplete request objects
        :param errored: Errored request objects
        :param start_time: Analysis window start
        :param end_time: Analysis window end
        :param threshold: Time threshold for merging nearby events
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of rate distribution summaries
        """

        def _extract_values(
            _objs: Sequence[FunctionObjT],
        ) -> Sequence[float | tuple[float, float]]:
            _outputs: list[float | tuple[float, float]] = []
            for _obj in _objs:
                if (_result := function(_obj)) is None:
                    continue
                if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                    _outputs.extend(_result)
                else:
                    _outputs.append(_result)
            return _outputs

        return cls.rate_distribution_from_timings(
            successful=_extract_values(successful),
            incomplete=_extract_values(incomplete),
            errored=_extract_values(errored),
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    @classmethod
    def concurrency_distribution_from_timings(
        cls,
        successful: Sequence[tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        incomplete: Sequence[tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        errored: Sequence[tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create status-broken-down concurrency distribution from event intervals.

        :param successful: Event intervals for successful requests
        :param incomplete: Event intervals for incomplete requests
        :param errored: Event intervals for errored requests
        :param start_time: Analysis window start
        :param end_time: Analysis window end
        :param threshold: Time threshold for merging nearby transitions
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of concurrency distribution summaries
        """
        total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
            successful, incomplete, errored, num_values_per_item=3
        )

        return StatusDistributionSummary(
            total=DistributionSummary.concurrency_distribution_from_timings(
                total,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            successful=DistributionSummary.concurrency_distribution_from_timings(
                successful_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            incomplete=DistributionSummary.concurrency_distribution_from_timings(
                incomplete_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
            errored=DistributionSummary.concurrency_distribution_from_timings(
                errored_arr,
                start_time=start_time,
                end_time=end_time,
                threshold=threshold,
                include_pdf=include_pdf,
                epsilon=epsilon,
            ),
        )

    @classmethod
    def concurrency_distribution_from_timings_function(
        cls,
        function: Callable[
            [FunctionObjT],
            tuple[float, float]
            | tuple[float, float, float]
            | Sequence[tuple[float, float] | tuple[float, float, float]]
            | None,
        ],
        successful: Sequence[FunctionObjT],
        incomplete: Sequence[FunctionObjT],
        errored: Sequence[FunctionObjT],
        start_time: float | None = None,
        end_time: float | None = None,
        threshold: float | None = 1e-4,
        include_pdf: bool | int = False,
        epsilon: float = 1e-6,
    ) -> StatusDistributionSummary:
        """
        Create concurrency distribution by extracting intervals from objects.

        :param function: Function to extract time interval(s) from each object
        :param successful: Successful request objects
        :param incomplete: Incomplete request objects
        :param errored: Errored request objects
        :param start_time: Analysis window start
        :param end_time: Analysis window end
        :param threshold: Time threshold for merging nearby transitions
        :param include_pdf: Whether to include PDF; True for full, int for sampled size
        :param epsilon: Tolerance for probability validation
        :return: Status breakdown of concurrency distribution summaries
        """

        def _extract_values(
            _objs: Sequence[FunctionObjT],
        ) -> Sequence[tuple[float, float] | tuple[float, float, float]]:
            _outputs: list[tuple[float, float] | tuple[float, float, float]] = []
            for _obj in _objs:
                if (_result := function(_obj)) is None:
                    continue
                if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                    _outputs.extend(_result)
                else:
                    _outputs.append(_result)
            return _outputs

        return cls.concurrency_distribution_from_timings(
            successful=_extract_values(successful),
            incomplete=_extract_values(incomplete),
            errored=_extract_values(errored),
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        )

    @classmethod
    def _combine_status_arrays(
        cls,
        successful: Sequence[float | tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        incomplete: Sequence[float | tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        errored: Sequence[float | tuple[float, float] | tuple[float, float, float]]
        | np.ndarray,
        num_values_per_item: Literal[2, 3],
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        successful_array = DistributionSummary._to_weighted_ndarray(  # noqa: SLF001
            successful, num_values_per_item=num_values_per_item
        )
        incomplete_array = DistributionSummary._to_weighted_ndarray(  # noqa: SLF001
            incomplete, num_values_per_item=num_values_per_item
        )
        errored_array = DistributionSummary._to_weighted_ndarray(  # noqa: SLF001
            errored, num_values_per_item=num_values_per_item
        )
        total_array = np.concatenate(
            (successful_array, incomplete_array, errored_array), axis=0
        )
        return total_array, successful_array, incomplete_array, errored_array

count property

Returns:

Type Description
int

Total count of samples across all status categories

total_sum property

Returns:

Type Description
float

Total sum of values across all status categories

concurrency_distribution_from_timings(successful, incomplete, errored, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create status-broken-down concurrency distribution from event intervals.

Parameters:

Name Type Description Default
successful Sequence[tuple[float, float] | tuple[float, float, float]] | ndarray

Event intervals for successful requests

required
incomplete Sequence[tuple[float, float] | tuple[float, float, float]] | ndarray

Event intervals for incomplete requests

required
errored Sequence[tuple[float, float] | tuple[float, float, float]] | ndarray

Event intervals for errored requests

required
start_time float | None

Analysis window start

None
end_time float | None

Analysis window end

None
threshold float | None

Time threshold for merging nearby transitions

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of concurrency distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def concurrency_distribution_from_timings(
    cls,
    successful: Sequence[tuple[float, float] | tuple[float, float, float]]
    | np.ndarray,
    incomplete: Sequence[tuple[float, float] | tuple[float, float, float]]
    | np.ndarray,
    errored: Sequence[tuple[float, float] | tuple[float, float, float]]
    | np.ndarray,
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create status-broken-down concurrency distribution from event intervals.

    :param successful: Event intervals for successful requests
    :param incomplete: Event intervals for incomplete requests
    :param errored: Event intervals for errored requests
    :param start_time: Analysis window start
    :param end_time: Analysis window end
    :param threshold: Time threshold for merging nearby transitions
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of concurrency distribution summaries
    """
    total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
        successful, incomplete, errored, num_values_per_item=3
    )

    return StatusDistributionSummary(
        total=DistributionSummary.concurrency_distribution_from_timings(
            total,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        successful=DistributionSummary.concurrency_distribution_from_timings(
            successful_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        incomplete=DistributionSummary.concurrency_distribution_from_timings(
            incomplete_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        errored=DistributionSummary.concurrency_distribution_from_timings(
            errored_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
    )

concurrency_distribution_from_timings_function(function, successful, incomplete, errored, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create concurrency distribution by extracting intervals from objects.

Parameters:

Name Type Description Default
function Callable[[FunctionObjT], tuple[float, float] | tuple[float, float, float] | Sequence[tuple[float, float] | tuple[float, float, float]] | None]

Function to extract time interval(s) from each object

required
successful Sequence[FunctionObjT]

Successful request objects

required
incomplete Sequence[FunctionObjT]

Incomplete request objects

required
errored Sequence[FunctionObjT]

Errored request objects

required
start_time float | None

Analysis window start

None
end_time float | None

Analysis window end

None
threshold float | None

Time threshold for merging nearby transitions

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of concurrency distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def concurrency_distribution_from_timings_function(
    cls,
    function: Callable[
        [FunctionObjT],
        tuple[float, float]
        | tuple[float, float, float]
        | Sequence[tuple[float, float] | tuple[float, float, float]]
        | None,
    ],
    successful: Sequence[FunctionObjT],
    incomplete: Sequence[FunctionObjT],
    errored: Sequence[FunctionObjT],
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create concurrency distribution by extracting intervals from objects.

    :param function: Function to extract time interval(s) from each object
    :param successful: Successful request objects
    :param incomplete: Incomplete request objects
    :param errored: Errored request objects
    :param start_time: Analysis window start
    :param end_time: Analysis window end
    :param threshold: Time threshold for merging nearby transitions
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of concurrency distribution summaries
    """

    def _extract_values(
        _objs: Sequence[FunctionObjT],
    ) -> Sequence[tuple[float, float] | tuple[float, float, float]]:
        _outputs: list[tuple[float, float] | tuple[float, float, float]] = []
        for _obj in _objs:
            if (_result := function(_obj)) is None:
                continue
            if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                _outputs.extend(_result)
            else:
                _outputs.append(_result)
        return _outputs

    return cls.concurrency_distribution_from_timings(
        successful=_extract_values(successful),
        incomplete=_extract_values(incomplete),
        errored=_extract_values(errored),
        start_time=start_time,
        end_time=end_time,
        threshold=threshold,
        include_pdf=include_pdf,
        epsilon=epsilon,
    )

from_values(successful, incomplete, errored, include_pdf=False, epsilon=1e-06) classmethod

Create status-broken-down distribution from values by status category.

Parameters:

Name Type Description Default
successful Sequence[float | tuple[float, float]] | ndarray

Values or (value, weight) tuples for successful requests

required
incomplete Sequence[float | tuple[float, float]] | ndarray

Values or (value, weight) tuples for incomplete requests

required
errored Sequence[float | tuple[float, float]] | ndarray

Values or (value, weight) tuples for errored requests

required
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def from_values(
    cls,
    successful: Sequence[float | tuple[float, float]] | np.ndarray,
    incomplete: Sequence[float | tuple[float, float]] | np.ndarray,
    errored: Sequence[float | tuple[float, float]] | np.ndarray,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create status-broken-down distribution from values by status category.

    :param successful: Values or (value, weight) tuples for successful requests
    :param incomplete: Values or (value, weight) tuples for incomplete requests
    :param errored: Values or (value, weight) tuples for errored requests
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of distribution summaries
    """
    total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
        successful, incomplete, errored, num_values_per_item=2
    )

    return StatusDistributionSummary(
        total=DistributionSummary.from_values(
            total, include_pdf=include_pdf, epsilon=epsilon
        ),
        successful=DistributionSummary.from_values(
            successful_arr, include_pdf=include_pdf, epsilon=epsilon
        ),
        incomplete=DistributionSummary.from_values(
            incomplete_arr, include_pdf=include_pdf, epsilon=epsilon
        ),
        errored=DistributionSummary.from_values(
            errored_arr, include_pdf=include_pdf, epsilon=epsilon
        ),
    )

from_values_function(function, successful, incomplete, errored, include_pdf=False, epsilon=1e-06) classmethod

Create distribution summary by extracting values from objects via function.

Parameters:

Name Type Description Default
function Callable[[FunctionObjT], float | tuple[float, float] | Sequence[float | tuple[float, float]] | None]

Function to extract value(s) from each object

required
successful Sequence[FunctionObjT]

Successful request objects

required
incomplete Sequence[FunctionObjT]

Incomplete request objects

required
errored Sequence[FunctionObjT]

Errored request objects

required
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def from_values_function(
    cls,
    function: Callable[
        [FunctionObjT],
        float | tuple[float, float] | Sequence[float | tuple[float, float]] | None,
    ],
    successful: Sequence[FunctionObjT],
    incomplete: Sequence[FunctionObjT],
    errored: Sequence[FunctionObjT],
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create distribution summary by extracting values from objects via function.

    :param function: Function to extract value(s) from each object
    :param successful: Successful request objects
    :param incomplete: Incomplete request objects
    :param errored: Errored request objects
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of distribution summaries
    """

    def _extract_values(
        _objs: Sequence[FunctionObjT],
    ) -> Sequence[float | tuple[float, float]]:
        _outputs: list[float | tuple[float, float]] = []
        for _obj in _objs:
            if (_result := function(_obj)) is None:
                continue
            if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                _outputs.extend(_result)
            else:
                _outputs.append(_result)
        return _outputs

    return cls.from_values(
        successful=_extract_values(successful),
        incomplete=_extract_values(incomplete),
        errored=_extract_values(errored),
        include_pdf=include_pdf,
        epsilon=epsilon,
    )

rate_distribution_from_timings(successful, incomplete, errored, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create status-broken-down rate distribution from event timestamps.

Parameters:

Name Type Description Default
successful Sequence[float | tuple[float, float]] | ndarray

Timestamps for successful request events

required
incomplete Sequence[float | tuple[float, float]] | ndarray

Timestamps for incomplete request events

required
errored Sequence[float | tuple[float, float]] | ndarray

Timestamps for errored request events

required
start_time float | None

Analysis window start

None
end_time float | None

Analysis window end

None
threshold float | None

Time threshold for merging nearby events

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of rate distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def rate_distribution_from_timings(
    cls,
    successful: Sequence[float | tuple[float, float]] | np.ndarray,
    incomplete: Sequence[float | tuple[float, float]] | np.ndarray,
    errored: Sequence[float | tuple[float, float]] | np.ndarray,
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create status-broken-down rate distribution from event timestamps.

    :param successful: Timestamps for successful request events
    :param incomplete: Timestamps for incomplete request events
    :param errored: Timestamps for errored request events
    :param start_time: Analysis window start
    :param end_time: Analysis window end
    :param threshold: Time threshold for merging nearby events
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of rate distribution summaries
    """
    total, successful_arr, incomplete_arr, errored_arr = cls._combine_status_arrays(
        successful, incomplete, errored, num_values_per_item=2
    )

    return StatusDistributionSummary(
        total=DistributionSummary.rate_distribution_from_timings(
            total,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        successful=DistributionSummary.rate_distribution_from_timings(
            successful_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        incomplete=DistributionSummary.rate_distribution_from_timings(
            incomplete_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
        errored=DistributionSummary.rate_distribution_from_timings(
            errored_arr,
            start_time=start_time,
            end_time=end_time,
            threshold=threshold,
            include_pdf=include_pdf,
            epsilon=epsilon,
        ),
    )

rate_distribution_from_timings_function(function, successful, incomplete, errored, start_time=None, end_time=None, threshold=0.0001, include_pdf=False, epsilon=1e-06) classmethod

Create rate distribution by extracting timestamps from objects via function.

Parameters:

Name Type Description Default
function Callable[[FunctionObjT], float | tuple[float, float] | Sequence[float | tuple[float, float]] | None]

Function to extract timestamp(s) from each object

required
successful Sequence[FunctionObjT]

Successful request objects

required
incomplete Sequence[FunctionObjT]

Incomplete request objects

required
errored Sequence[FunctionObjT]

Errored request objects

required
start_time float | None

Analysis window start

None
end_time float | None

Analysis window end

None
threshold float | None

Time threshold for merging nearby events

0.0001
include_pdf bool | int

Whether to include PDF; True for full, int for sampled size

False
epsilon float

Tolerance for probability validation

1e-06

Returns:

Type Description
StatusDistributionSummary

Status breakdown of rate distribution summaries

Source code in src/guidellm/schemas/statistics.py
@classmethod
def rate_distribution_from_timings_function(
    cls,
    function: Callable[
        [FunctionObjT],
        float | tuple[float, float] | Sequence[float | tuple[float, float]] | None,
    ],
    successful: Sequence[FunctionObjT],
    incomplete: Sequence[FunctionObjT],
    errored: Sequence[FunctionObjT],
    start_time: float | None = None,
    end_time: float | None = None,
    threshold: float | None = 1e-4,
    include_pdf: bool | int = False,
    epsilon: float = 1e-6,
) -> StatusDistributionSummary:
    """
    Create rate distribution by extracting timestamps from objects via function.

    :param function: Function to extract timestamp(s) from each object
    :param successful: Successful request objects
    :param incomplete: Incomplete request objects
    :param errored: Errored request objects
    :param start_time: Analysis window start
    :param end_time: Analysis window end
    :param threshold: Time threshold for merging nearby events
    :param include_pdf: Whether to include PDF; True for full, int for sampled size
    :param epsilon: Tolerance for probability validation
    :return: Status breakdown of rate distribution summaries
    """

    def _extract_values(
        _objs: Sequence[FunctionObjT],
    ) -> Sequence[float | tuple[float, float]]:
        _outputs: list[float | tuple[float, float]] = []
        for _obj in _objs:
            if (_result := function(_obj)) is None:
                continue
            if isinstance(_result, Sequence) and not isinstance(_result, tuple):
                _outputs.extend(_result)
            else:
                _outputs.append(_result)
        return _outputs

    return cls.rate_distribution_from_timings(
        successful=_extract_values(successful),
        incomplete=_extract_values(incomplete),
        errored=_extract_values(errored),
        start_time=start_time,
        end_time=end_time,
        threshold=threshold,
        include_pdf=include_pdf,
        epsilon=epsilon,
    )

ToolCall

Bases: BaseModel

A single tool call from an OpenAI-compatible API response.

Source code in src/guidellm/schemas/tool_call.py
class ToolCall(BaseModel):
    """A single tool call from an OpenAI-compatible API response."""

    id: str = ""
    type: str = "function"
    function: ToolCallFunction = Field(default_factory=ToolCallFunction)

ToolCallFunction

Bases: BaseModel

Function name and arguments for a single tool call.

Source code in src/guidellm/schemas/tool_call.py
class ToolCallFunction(BaseModel):
    """Function name and arguments for a single tool call."""

    name: str = ""
    arguments: str = ""

UsageMetrics

Bases: StandardBaseDict

Multimodal usage metrics for generation requests.

Tracks resource consumption across different modalities including text, images, video, and audio. Provides granular metrics for tokens, bytes, duration, and format-specific measurements to enable comprehensive usage monitoring and billing.

Source code in src/guidellm/schemas/request.py
class UsageMetrics(StandardBaseDict):
    """
    Multimodal usage metrics for generation requests.

    Tracks resource consumption across different modalities including text, images,
    video, and audio. Provides granular metrics for tokens, bytes, duration, and
    format-specific measurements to enable comprehensive usage monitoring and billing.
    """

    # Text stats
    text_tokens: int | None = Field(
        default=None, description="Number of text tokens processed/generated."
    )
    text_words: int | None = Field(
        default=None, description="Number of text words processed/generated."
    )
    text_characters: int | None = Field(
        default=None, description="Number of text characters processed/generated."
    )

    # Vision image stats
    image_tokens: int | None = Field(
        default=None, description="Number of image tokens processed/generated."
    )
    image_count: int | None = Field(
        default=None, description="Number of images processed/generated."
    )
    image_pixels: int | None = Field(
        default=None, description="Number of image pixels processed/generated."
    )
    image_bytes: int | None = Field(
        default=None, description="Number of image bytes processed/generated."
    )

    # Vision video stats
    video_tokens: int | None = Field(
        default=None, description="Number of video tokens processed/generated."
    )
    video_frames: int | None = Field(
        default=None, description="Number of video frames processed/generated."
    )
    video_seconds: float | None = Field(
        default=None, description="Duration of video processed/generated in seconds."
    )
    video_bytes: int | None = Field(
        default=None, description="Number of video bytes processed/generated."
    )

    # Audio stats
    audio_tokens: int | None = Field(
        default=None, description="Number of audio tokens processed/generated."
    )
    audio_samples: int | None = Field(
        default=None, description="Number of audio samples processed/generated."
    )
    audio_seconds: float | None = Field(
        default=None, description="Duration of audio processed/generated in seconds."
    )
    audio_bytes: int | None = Field(
        default=None, description="Number of audio bytes processed/generated."
    )

    # Tool call stats (subset of text_tokens)
    tool_call_tokens: int | None = Field(
        default=None,
        description=(
            "Output completion token total for tool-only turns (content null). "
            "Equal to text_tokens when the entire completion is tool output; "
            "None on mixed or text-only turns. Subset of text_tokens. "
            "See mixed_content_tool_tokens for the mixed case."
        ),
    )
    mixed_content_tool_tokens: int | None = Field(
        default=None,
        description=(
            "Output completion token total for mixed content + tool call turns. "
            "Equal to text_tokens when both natural language text and tool calls "
            "are present; None on text-only or tool-only turns. Subset of "
            "text_tokens."
        ),
    )
    tool_call_count: int | None = Field(
        default=None,
        description=(
            "Number of tool calls generated. Set whenever the response includes "
            "tool calls, regardless of whether content is also present."
        ),
    )

    @computed_field  # type: ignore[misc]
    @property
    def total_tokens(self) -> int | None:
        """
        Calculate total tokens across all modalities.

        :return: Sum of text, image, video, and audio tokens, or None if all are None
        """
        token_metrics = [
            self.text_tokens,
            self.image_tokens,
            self.video_tokens,
            self.audio_tokens,
        ]
        # NOTE: None should indicate no data rather than zero usage
        if token_metrics.count(None) == len(token_metrics):
            return None
        else:
            return sum(token or 0 for token in token_metrics)

    def add_text_metrics(self, text):
        """
        Adds the metrics from the given text to the fields
        `text_characters` and `text_words`.

        :param text: Text to add metrics from
        """
        self.text_characters = (self.text_characters or 0) + len(text)
        self.text_words = (self.text_words or 0) + len(text.split())

total_tokens property

Calculate total tokens across all modalities.

Returns:

Type Description
int | None

Sum of text, image, video, and audio tokens, or None if all are None

add_text_metrics(text)

Adds the metrics from the given text to the fields text_characters and text_words.

Parameters:

Name Type Description Default
text

Text to add metrics from

required
Source code in src/guidellm/schemas/request.py
def add_text_metrics(self, text):
    """
    Adds the metrics from the given text to the fields
    `text_characters` and `text_words`.

    :param text: Text to add metrics from
    """
    self.text_characters = (self.text_characters or 0) + len(text)
    self.text_words = (self.text_words or 0) + len(text.split())

standard_model_config(**updates)

Generate a standard Pydantic model configuration with optional updates.

Provides a consistent base configuration for Pydantic models in the application, allowing for easy customization through additional keyword arguments.

Parameters:

Name Type Description Default
updates Any

Additional configuration settings to override defaults

{}

Returns:

Type Description
ConfigDict

ConfigDict with standard settings merged with any updates

Source code in src/guidellm/schemas/base.py
def standard_model_config(**updates: Any) -> ConfigDict:
    """
    Generate a standard Pydantic model configuration with optional updates.

    Provides a consistent base configuration for Pydantic models in the application,
    allowing for easy customization through additional keyword arguments.

    :param updates: Additional configuration settings to override defaults
    :return: ConfigDict with standard settings merged with any updates
    """
    base_config = ConfigDict(
        extra="forbid",
        use_enum_values=True,
        from_attributes=True,
        arbitrary_types_allowed=True,
        ser_json_bytes="base64",
        val_json_bytes="base64",
    )
    return base_config | ConfigDict(**updates)  # type: ignore[typeddict-item]