def generate_latest(registry: CollectorRegistry = REGISTRY) -> bytes:
    """Returns the metrics from the registry in latest text format as a string."""

    def sample_line(samples):
        if samples.labels:
            labelstr = '{0}'.format(','.join(
                ['{}="{}"'.format(
                    openmetrics.escape_label_name(k), openmetrics._escape(v))
                    for k, v in sorted(samples.labels.items())]))
        else:
            labelstr = ''
        timestamp = ''
        if samples.timestamp is not None:
            # Convert to milliseconds.
            timestamp = f' {int(float(samples.timestamp) * 1000):d}'
        if _is_valid_legacy_metric_name(samples.name):
            if labelstr:
                labelstr = '{{{0}}}'.format(labelstr)
            return f'{samples.name}{labelstr} {floatToGoString(samples.value)}{timestamp}\n'
        maybe_comma = ''
        if labelstr:
            maybe_comma = ','
        return f'{{{openmetrics.escape_metric_name(samples.name)}{maybe_comma}{labelstr}}} {floatToGoString(samples.value)}{timestamp}\n'

    output = []
    for metric in registry.collect():
        try:
            mname = metric.name
            mtype = metric.type
            # Munging from OpenMetrics into Prometheus format.
            if mtype == 'counter':
                mname = mname + '_total'
            elif mtype == 'info':
                mname = mname + '_info'
                mtype = 'gauge'
            elif mtype == 'stateset':
                mtype = 'gauge'
            elif mtype == 'gaugehistogram':
                # A gauge histogram is really a gauge,
                # but this captures the structure better.
                mtype = 'histogram'
            elif mtype == 'unknown':
                mtype = 'untyped'

            output.append('# HELP {} {}\n'.format(
                openmetrics.escape_metric_name(mname), metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
            output.append(f'# TYPE {openmetrics.escape_metric_name(mname)} {mtype}\n')

            om_samples: Dict[str, List[str]] = {}
            for s in metric.samples:
                for suffix in ['_created', '_gsum', '_gcount']:
                    if s.name == metric.name + suffix:
                        # OpenMetrics specific sample, put in a gauge at the end.
                        om_samples.setdefault(suffix, []).append(sample_line(s))
                        break
                else:
                    output.append(sample_line(s))
        except Exception as exception:
            exception.args = (exception.args or ('',)) + (metric,)
            raise

        for suffix, lines in sorted(om_samples.items()):
            output.append('# HELP {} {}\n'.format(openmetrics.escape_metric_name(metric.name + suffix),
                                                  metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
            output.append(f'# TYPE {openmetrics.escape_metric_name(metric.name + suffix)} gauge\n')
            output.extend(lines)
    return ''.join(output).encode('utf-8')
Returns the metrics from the registry in latest text format as a string.
prometheus_client/exposition.py