conduit-observability 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ """Conduit SDK: emit agent spans to the Conduit gateway over mTLS/gRPC."""
2
+
3
+ from .client import (
4
+ SEVERITY_DEBUG,
5
+ SEVERITY_ERROR,
6
+ SEVERITY_INFO,
7
+ SEVERITY_UNSPECIFIED,
8
+ SEVERITY_WARN,
9
+ STATUS_ERROR,
10
+ STATUS_OK,
11
+ STATUS_UNSET,
12
+ Client,
13
+ ConduitError,
14
+ LLMCall,
15
+ Span,
16
+ )
17
+ from .llm import estimate_cost_usd
18
+
19
+ __all__ = [
20
+ "Client",
21
+ "ConduitError",
22
+ "LLMCall",
23
+ "Span",
24
+ "SEVERITY_DEBUG",
25
+ "SEVERITY_ERROR",
26
+ "SEVERITY_INFO",
27
+ "SEVERITY_UNSPECIFIED",
28
+ "SEVERITY_WARN",
29
+ "STATUS_ERROR",
30
+ "STATUS_OK",
31
+ "STATUS_UNSET",
32
+ "estimate_cost_usd",
33
+ ]
@@ -0,0 +1 @@
1
+ """Generated protobuf and gRPC stubs (scripts/gen-proto-python.sh). Do not edit."""
@@ -0,0 +1,48 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: ingestion.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'ingestion.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from . import span_pb2 as span__pb2
26
+ from . import metric_pb2 as metric__pb2
27
+ from . import log_pb2 as log__pb2
28
+
29
+
30
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0fingestion.proto\x12\x10observability.v1\x1a\nspan.proto\x1a\x0cmetric.proto\x1a\tlog.proto\"9\n\x11IngestSpanRequest\x12$\n\x04span\x18\x01 \x01(\x0b\x32\x16.observability.v1.Span\"@\n\x12IngestSpanResponse\x12\x10\n\x08\x61\x63\x63\x65pted\x18\x01 \x01(\x08\x12\x18\n\x10rejection_reason\x18\x02 \x01(\t\"\x91\x01\n\x12IngestBatchRequest\x12%\n\x05spans\x18\x01 \x03(\x0b\x32\x16.observability.v1.Span\x12)\n\x07metrics\x18\x02 \x03(\x0b\x32\x18.observability.v1.Metric\x12)\n\x04logs\x18\x03 \x03(\x0b\x32\x1b.observability.v1.LogRecord\"n\n\x13IngestBatchResponse\x12\x16\n\x0espans_accepted\x18\x01 \x01(\x05\x12\x18\n\x10metrics_accepted\x18\x02 \x01(\x05\x12\x15\n\rlogs_accepted\x18\x03 \x01(\x05\x12\x0e\n\x06\x65rrors\x18\x04 \x03(\t2\xc7\x01\n\x10IngestionService\x12W\n\nIngestSpan\x12#.observability.v1.IngestSpanRequest\x1a$.observability.v1.IngestSpanResponse\x12Z\n\x0bIngestBatch\x12$.observability.v1.IngestBatchRequest\x1a%.observability.v1.IngestBatchResponseB$Z\"github.com/tjscanlan/conduit/protob\x06proto3')
31
+
32
+ _globals = globals()
33
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
34
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'ingestion_pb2', _globals)
35
+ if not _descriptor._USE_C_DESCRIPTORS:
36
+ _globals['DESCRIPTOR']._loaded_options = None
37
+ _globals['DESCRIPTOR']._serialized_options = b'Z\"github.com/tjscanlan/conduit/proto'
38
+ _globals['_INGESTSPANREQUEST']._serialized_start=74
39
+ _globals['_INGESTSPANREQUEST']._serialized_end=131
40
+ _globals['_INGESTSPANRESPONSE']._serialized_start=133
41
+ _globals['_INGESTSPANRESPONSE']._serialized_end=197
42
+ _globals['_INGESTBATCHREQUEST']._serialized_start=200
43
+ _globals['_INGESTBATCHREQUEST']._serialized_end=345
44
+ _globals['_INGESTBATCHRESPONSE']._serialized_start=347
45
+ _globals['_INGESTBATCHRESPONSE']._serialized_end=457
46
+ _globals['_INGESTIONSERVICE']._serialized_start=460
47
+ _globals['_INGESTIONSERVICE']._serialized_end=659
48
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,46 @@
1
+ from . import span_pb2 as _span_pb2
2
+ from . import metric_pb2 as _metric_pb2
3
+ from . import log_pb2 as _log_pb2
4
+ from google.protobuf.internal import containers as _containers
5
+ from google.protobuf import descriptor as _descriptor
6
+ from google.protobuf import message as _message
7
+ from collections.abc import Iterable as _Iterable, Mapping as _Mapping
8
+ from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union
9
+
10
+ DESCRIPTOR: _descriptor.FileDescriptor
11
+
12
+ class IngestSpanRequest(_message.Message):
13
+ __slots__ = ("span",)
14
+ SPAN_FIELD_NUMBER: _ClassVar[int]
15
+ span: _span_pb2.Span
16
+ def __init__(self, span: _Optional[_Union[_span_pb2.Span, _Mapping]] = ...) -> None: ...
17
+
18
+ class IngestSpanResponse(_message.Message):
19
+ __slots__ = ("accepted", "rejection_reason")
20
+ ACCEPTED_FIELD_NUMBER: _ClassVar[int]
21
+ REJECTION_REASON_FIELD_NUMBER: _ClassVar[int]
22
+ accepted: bool
23
+ rejection_reason: str
24
+ def __init__(self, accepted: _Optional[bool] = ..., rejection_reason: _Optional[str] = ...) -> None: ...
25
+
26
+ class IngestBatchRequest(_message.Message):
27
+ __slots__ = ("spans", "metrics", "logs")
28
+ SPANS_FIELD_NUMBER: _ClassVar[int]
29
+ METRICS_FIELD_NUMBER: _ClassVar[int]
30
+ LOGS_FIELD_NUMBER: _ClassVar[int]
31
+ spans: _containers.RepeatedCompositeFieldContainer[_span_pb2.Span]
32
+ metrics: _containers.RepeatedCompositeFieldContainer[_metric_pb2.Metric]
33
+ logs: _containers.RepeatedCompositeFieldContainer[_log_pb2.LogRecord]
34
+ def __init__(self, spans: _Optional[_Iterable[_Union[_span_pb2.Span, _Mapping]]] = ..., metrics: _Optional[_Iterable[_Union[_metric_pb2.Metric, _Mapping]]] = ..., logs: _Optional[_Iterable[_Union[_log_pb2.LogRecord, _Mapping]]] = ...) -> None: ...
35
+
36
+ class IngestBatchResponse(_message.Message):
37
+ __slots__ = ("spans_accepted", "metrics_accepted", "logs_accepted", "errors")
38
+ SPANS_ACCEPTED_FIELD_NUMBER: _ClassVar[int]
39
+ METRICS_ACCEPTED_FIELD_NUMBER: _ClassVar[int]
40
+ LOGS_ACCEPTED_FIELD_NUMBER: _ClassVar[int]
41
+ ERRORS_FIELD_NUMBER: _ClassVar[int]
42
+ spans_accepted: int
43
+ metrics_accepted: int
44
+ logs_accepted: int
45
+ errors: _containers.RepeatedScalarFieldContainer[str]
46
+ def __init__(self, spans_accepted: _Optional[int] = ..., metrics_accepted: _Optional[int] = ..., logs_accepted: _Optional[int] = ..., errors: _Optional[_Iterable[str]] = ...) -> None: ...
@@ -0,0 +1,150 @@
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+ import warnings
5
+
6
+ from . import ingestion_pb2 as ingestion__pb2
7
+
8
+ GRPC_GENERATED_VERSION = '1.85.1'
9
+ GRPC_VERSION = grpc.__version__
10
+ _version_not_supported = False
11
+
12
+ try:
13
+ from grpc._utilities import first_version_is_lower
14
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
15
+ except ImportError:
16
+ _version_not_supported = True
17
+
18
+ if _version_not_supported:
19
+ raise RuntimeError(
20
+ f'The grpc package installed is at version {GRPC_VERSION},'
21
+ + ' but the generated code in ingestion_pb2_grpc.py depends on'
22
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
23
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
24
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
25
+ )
26
+
27
+
28
+ class IngestionServiceStub:
29
+ """IngestionService is the gateway's inbound API.
30
+ All RPCs require mTLS — agent identity comes from the client certificate.
31
+ """
32
+
33
+ def __init__(self, channel):
34
+ """Constructor.
35
+
36
+ Args:
37
+ channel: A grpc.Channel.
38
+ """
39
+ self.IngestSpan = channel.unary_unary(
40
+ '/observability.v1.IngestionService/IngestSpan',
41
+ request_serializer=ingestion__pb2.IngestSpanRequest.SerializeToString,
42
+ response_deserializer=ingestion__pb2.IngestSpanResponse.FromString,
43
+ _registered_method=True)
44
+ self.IngestBatch = channel.unary_unary(
45
+ '/observability.v1.IngestionService/IngestBatch',
46
+ request_serializer=ingestion__pb2.IngestBatchRequest.SerializeToString,
47
+ response_deserializer=ingestion__pb2.IngestBatchResponse.FromString,
48
+ _registered_method=True)
49
+
50
+
51
+ class IngestionServiceServicer:
52
+ """IngestionService is the gateway's inbound API.
53
+ All RPCs require mTLS — agent identity comes from the client certificate.
54
+ """
55
+
56
+ def IngestSpan(self, request, context):
57
+ """IngestSpan submits a single span. Used for real-time streaming from agents.
58
+ """
59
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
60
+ context.set_details('Method not implemented!')
61
+ raise NotImplementedError('Method not implemented!')
62
+
63
+ def IngestBatch(self, request, context):
64
+ """IngestBatch submits spans, metrics, and logs. Each item is validated and
65
+ accepted independently (not atomically); rejected items are reported in
66
+ IngestBatchResponse.errors.
67
+ """
68
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
69
+ context.set_details('Method not implemented!')
70
+ raise NotImplementedError('Method not implemented!')
71
+
72
+
73
+ def add_IngestionServiceServicer_to_server(servicer, server):
74
+ rpc_method_handlers = {
75
+ 'IngestSpan': grpc.unary_unary_rpc_method_handler(
76
+ servicer.IngestSpan,
77
+ request_deserializer=ingestion__pb2.IngestSpanRequest.FromString,
78
+ response_serializer=ingestion__pb2.IngestSpanResponse.SerializeToString,
79
+ ),
80
+ 'IngestBatch': grpc.unary_unary_rpc_method_handler(
81
+ servicer.IngestBatch,
82
+ request_deserializer=ingestion__pb2.IngestBatchRequest.FromString,
83
+ response_serializer=ingestion__pb2.IngestBatchResponse.SerializeToString,
84
+ ),
85
+ }
86
+ generic_handler = grpc.method_handlers_generic_handler(
87
+ 'observability.v1.IngestionService', rpc_method_handlers)
88
+ server.add_generic_rpc_handlers((generic_handler,))
89
+ server.add_registered_method_handlers('observability.v1.IngestionService', rpc_method_handlers)
90
+
91
+
92
+ # This class is part of an EXPERIMENTAL API.
93
+ class IngestionService:
94
+ """IngestionService is the gateway's inbound API.
95
+ All RPCs require mTLS — agent identity comes from the client certificate.
96
+ """
97
+
98
+ @staticmethod
99
+ def IngestSpan(request,
100
+ target,
101
+ options=(),
102
+ channel_credentials=None,
103
+ call_credentials=None,
104
+ insecure=False,
105
+ compression=None,
106
+ wait_for_ready=None,
107
+ timeout=None,
108
+ metadata=None):
109
+ return grpc.experimental.unary_unary(
110
+ request,
111
+ target,
112
+ '/observability.v1.IngestionService/IngestSpan',
113
+ ingestion__pb2.IngestSpanRequest.SerializeToString,
114
+ ingestion__pb2.IngestSpanResponse.FromString,
115
+ options,
116
+ channel_credentials,
117
+ insecure,
118
+ call_credentials,
119
+ compression,
120
+ wait_for_ready,
121
+ timeout,
122
+ metadata,
123
+ _registered_method=True)
124
+
125
+ @staticmethod
126
+ def IngestBatch(request,
127
+ target,
128
+ options=(),
129
+ channel_credentials=None,
130
+ call_credentials=None,
131
+ insecure=False,
132
+ compression=None,
133
+ wait_for_ready=None,
134
+ timeout=None,
135
+ metadata=None):
136
+ return grpc.experimental.unary_unary(
137
+ request,
138
+ target,
139
+ '/observability.v1.IngestionService/IngestBatch',
140
+ ingestion__pb2.IngestBatchRequest.SerializeToString,
141
+ ingestion__pb2.IngestBatchResponse.FromString,
142
+ options,
143
+ channel_credentials,
144
+ insecure,
145
+ call_credentials,
146
+ compression,
147
+ wait_for_ready,
148
+ timeout,
149
+ metadata,
150
+ _registered_method=True)
@@ -0,0 +1,44 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: log.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'log.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tlog.proto\x12\x10observability.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\x90\x02\n\tLogRecord\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x08severity\x18\x02 \x01(\x0e\x32\x1d.observability.v1.LogSeverity\x12\x0c\n\x04\x62ody\x18\x03 \x01(\t\x12?\n\nattributes\x18\x04 \x03(\x0b\x32+.observability.v1.LogRecord.AttributesEntry\x12\x10\n\x08trace_id\x18\x05 \x01(\t\x12\x0f\n\x07span_id\x18\x06 \x01(\t\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x89\x01\n\x0bLogSeverity\x12\x1c\n\x18LOG_SEVERITY_UNSPECIFIED\x10\x00\x12\x16\n\x12LOG_SEVERITY_DEBUG\x10\x01\x12\x15\n\x11LOG_SEVERITY_INFO\x10\x02\x12\x15\n\x11LOG_SEVERITY_WARN\x10\x03\x12\x16\n\x12LOG_SEVERITY_ERROR\x10\x04\x42$Z\"github.com/tjscanlan/conduit/protob\x06proto3')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'log_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'Z\"github.com/tjscanlan/conduit/proto'
36
+ _globals['_LOGRECORD_ATTRIBUTESENTRY']._loaded_options = None
37
+ _globals['_LOGRECORD_ATTRIBUTESENTRY']._serialized_options = b'8\001'
38
+ _globals['_LOGSEVERITY']._serialized_start=340
39
+ _globals['_LOGSEVERITY']._serialized_end=477
40
+ _globals['_LOGRECORD']._serialized_start=65
41
+ _globals['_LOGRECORD']._serialized_end=337
42
+ _globals['_LOGRECORD_ATTRIBUTESENTRY']._serialized_start=288
43
+ _globals['_LOGRECORD_ATTRIBUTESENTRY']._serialized_end=337
44
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,47 @@
1
+ import datetime
2
+
3
+ from google.protobuf import timestamp_pb2 as _timestamp_pb2
4
+ from google.protobuf.internal import containers as _containers
5
+ from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import message as _message
8
+ from collections.abc import Mapping as _Mapping
9
+ from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union
10
+
11
+ DESCRIPTOR: _descriptor.FileDescriptor
12
+
13
+ class LogSeverity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
14
+ __slots__ = ()
15
+ LOG_SEVERITY_UNSPECIFIED: _ClassVar[LogSeverity]
16
+ LOG_SEVERITY_DEBUG: _ClassVar[LogSeverity]
17
+ LOG_SEVERITY_INFO: _ClassVar[LogSeverity]
18
+ LOG_SEVERITY_WARN: _ClassVar[LogSeverity]
19
+ LOG_SEVERITY_ERROR: _ClassVar[LogSeverity]
20
+ LOG_SEVERITY_UNSPECIFIED: LogSeverity
21
+ LOG_SEVERITY_DEBUG: LogSeverity
22
+ LOG_SEVERITY_INFO: LogSeverity
23
+ LOG_SEVERITY_WARN: LogSeverity
24
+ LOG_SEVERITY_ERROR: LogSeverity
25
+
26
+ class LogRecord(_message.Message):
27
+ __slots__ = ("timestamp", "severity", "body", "attributes", "trace_id", "span_id")
28
+ class AttributesEntry(_message.Message):
29
+ __slots__ = ("key", "value")
30
+ KEY_FIELD_NUMBER: _ClassVar[int]
31
+ VALUE_FIELD_NUMBER: _ClassVar[int]
32
+ key: str
33
+ value: str
34
+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...
35
+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]
36
+ SEVERITY_FIELD_NUMBER: _ClassVar[int]
37
+ BODY_FIELD_NUMBER: _ClassVar[int]
38
+ ATTRIBUTES_FIELD_NUMBER: _ClassVar[int]
39
+ TRACE_ID_FIELD_NUMBER: _ClassVar[int]
40
+ SPAN_ID_FIELD_NUMBER: _ClassVar[int]
41
+ timestamp: _timestamp_pb2.Timestamp
42
+ severity: LogSeverity
43
+ body: str
44
+ attributes: _containers.ScalarMap[str, str]
45
+ trace_id: str
46
+ span_id: str
47
+ def __init__(self, timestamp: _Optional[_Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping]] = ..., severity: _Optional[_Union[LogSeverity, str]] = ..., body: _Optional[str] = ..., attributes: _Optional[_Mapping[str, str]] = ..., trace_id: _Optional[str] = ..., span_id: _Optional[str] = ...) -> None: ...
@@ -0,0 +1,24 @@
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+ import warnings
5
+
6
+
7
+ GRPC_GENERATED_VERSION = '1.85.1'
8
+ GRPC_VERSION = grpc.__version__
9
+ _version_not_supported = False
10
+
11
+ try:
12
+ from grpc._utilities import first_version_is_lower
13
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
14
+ except ImportError:
15
+ _version_not_supported = True
16
+
17
+ if _version_not_supported:
18
+ raise RuntimeError(
19
+ f'The grpc package installed is at version {GRPC_VERSION},'
20
+ + ' but the generated code in log_pb2_grpc.py depends on'
21
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
22
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
23
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
24
+ )
@@ -0,0 +1,44 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: metric.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'metric.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cmetric.proto\x12\x10observability.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xe5\x01\n\x06Metric\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x06labels\x18\x02 \x03(\x0b\x32$.observability.v1.Metric.LabelsEntry\x12\r\n\x05value\x18\x03 \x01(\x01\x12-\n\ttimestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12*\n\x04type\x18\x05 \x01(\x0e\x32\x1c.observability.v1.MetricType\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*Y\n\nMetricType\x12\x1b\n\x17METRIC_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11METRIC_TYPE_GAUGE\x10\x01\x12\x17\n\x13METRIC_TYPE_COUNTER\x10\x02\x42$Z\"github.com/tjscanlan/conduit/protob\x06proto3')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'metric_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'Z\"github.com/tjscanlan/conduit/proto'
36
+ _globals['_METRIC_LABELSENTRY']._loaded_options = None
37
+ _globals['_METRIC_LABELSENTRY']._serialized_options = b'8\001'
38
+ _globals['_METRICTYPE']._serialized_start=299
39
+ _globals['_METRICTYPE']._serialized_end=388
40
+ _globals['_METRIC']._serialized_start=68
41
+ _globals['_METRIC']._serialized_end=297
42
+ _globals['_METRIC_LABELSENTRY']._serialized_start=252
43
+ _globals['_METRIC_LABELSENTRY']._serialized_end=297
44
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,41 @@
1
+ import datetime
2
+
3
+ from google.protobuf import timestamp_pb2 as _timestamp_pb2
4
+ from google.protobuf.internal import containers as _containers
5
+ from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import message as _message
8
+ from collections.abc import Mapping as _Mapping
9
+ from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union
10
+
11
+ DESCRIPTOR: _descriptor.FileDescriptor
12
+
13
+ class MetricType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
14
+ __slots__ = ()
15
+ METRIC_TYPE_UNSPECIFIED: _ClassVar[MetricType]
16
+ METRIC_TYPE_GAUGE: _ClassVar[MetricType]
17
+ METRIC_TYPE_COUNTER: _ClassVar[MetricType]
18
+ METRIC_TYPE_UNSPECIFIED: MetricType
19
+ METRIC_TYPE_GAUGE: MetricType
20
+ METRIC_TYPE_COUNTER: MetricType
21
+
22
+ class Metric(_message.Message):
23
+ __slots__ = ("name", "labels", "value", "timestamp", "type")
24
+ class LabelsEntry(_message.Message):
25
+ __slots__ = ("key", "value")
26
+ KEY_FIELD_NUMBER: _ClassVar[int]
27
+ VALUE_FIELD_NUMBER: _ClassVar[int]
28
+ key: str
29
+ value: str
30
+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...
31
+ NAME_FIELD_NUMBER: _ClassVar[int]
32
+ LABELS_FIELD_NUMBER: _ClassVar[int]
33
+ VALUE_FIELD_NUMBER: _ClassVar[int]
34
+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]
35
+ TYPE_FIELD_NUMBER: _ClassVar[int]
36
+ name: str
37
+ labels: _containers.ScalarMap[str, str]
38
+ value: float
39
+ timestamp: _timestamp_pb2.Timestamp
40
+ type: MetricType
41
+ def __init__(self, name: _Optional[str] = ..., labels: _Optional[_Mapping[str, str]] = ..., value: _Optional[float] = ..., timestamp: _Optional[_Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping]] = ..., type: _Optional[_Union[MetricType, str]] = ...) -> None: ...
@@ -0,0 +1,24 @@
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+ import warnings
5
+
6
+
7
+ GRPC_GENERATED_VERSION = '1.85.1'
8
+ GRPC_VERSION = grpc.__version__
9
+ _version_not_supported = False
10
+
11
+ try:
12
+ from grpc._utilities import first_version_is_lower
13
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
14
+ except ImportError:
15
+ _version_not_supported = True
16
+
17
+ if _version_not_supported:
18
+ raise RuntimeError(
19
+ f'The grpc package installed is at version {GRPC_VERSION},'
20
+ + ' but the generated code in metric_pb2_grpc.py depends on'
21
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
22
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
23
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
24
+ )
@@ -0,0 +1,46 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: span.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'span.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\nspan.proto\x12\x10observability.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xf6\x02\n\x04Span\x12\x10\n\x08trace_id\x18\x01 \x01(\t\x12\x0f\n\x07span_id\x18\x02 \x01(\t\x12\x11\n\tparent_id\x18\x03 \x01(\t\x12\x0c\n\x04name\x18\x04 \x01(\t\x12.\n\nstart_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x06status\x18\x07 \x01(\x0e\x32\x1c.observability.v1.SpanStatus\x12:\n\nattributes\x18\x08 \x03(\x0b\x32&.observability.v1.Span.AttributesEntry\x12/\n\x08llm_call\x18\t \x01(\x0b\x32\x1d.observability.v1.LLMCallData\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x7f\n\x0bLLMCallData\x12\r\n\x05model\x18\x01 \x01(\t\x12\x0e\n\x06prompt\x18\x02 \x01(\t\x12\x12\n\ncompletion\x18\x03 \x01(\t\x12\x14\n\x0cinput_tokens\x18\x04 \x01(\x05\x12\x15\n\routput_tokens\x18\x05 \x01(\x05\x12\x10\n\x08\x63ost_usd\x18\x06 \x01(\x01*N\n\nSpanStatus\x12\x15\n\x11SPAN_STATUS_UNSET\x10\x00\x12\x12\n\x0eSPAN_STATUS_OK\x10\x01\x12\x15\n\x11SPAN_STATUS_ERROR\x10\x02\x42$Z\"github.com/tjscanlan/conduit/protob\x06proto3')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'span_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'Z\"github.com/tjscanlan/conduit/proto'
36
+ _globals['_SPAN_ATTRIBUTESENTRY']._loaded_options = None
37
+ _globals['_SPAN_ATTRIBUTESENTRY']._serialized_options = b'8\001'
38
+ _globals['_SPANSTATUS']._serialized_start=571
39
+ _globals['_SPANSTATUS']._serialized_end=649
40
+ _globals['_SPAN']._serialized_start=66
41
+ _globals['_SPAN']._serialized_end=440
42
+ _globals['_SPAN_ATTRIBUTESENTRY']._serialized_start=391
43
+ _globals['_SPAN_ATTRIBUTESENTRY']._serialized_end=440
44
+ _globals['_LLMCALLDATA']._serialized_start=442
45
+ _globals['_LLMCALLDATA']._serialized_end=569
46
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,65 @@
1
+ import datetime
2
+
3
+ from google.protobuf import timestamp_pb2 as _timestamp_pb2
4
+ from google.protobuf.internal import containers as _containers
5
+ from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import message as _message
8
+ from collections.abc import Mapping as _Mapping
9
+ from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union
10
+
11
+ DESCRIPTOR: _descriptor.FileDescriptor
12
+
13
+ class SpanStatus(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
14
+ __slots__ = ()
15
+ SPAN_STATUS_UNSET: _ClassVar[SpanStatus]
16
+ SPAN_STATUS_OK: _ClassVar[SpanStatus]
17
+ SPAN_STATUS_ERROR: _ClassVar[SpanStatus]
18
+ SPAN_STATUS_UNSET: SpanStatus
19
+ SPAN_STATUS_OK: SpanStatus
20
+ SPAN_STATUS_ERROR: SpanStatus
21
+
22
+ class Span(_message.Message):
23
+ __slots__ = ("trace_id", "span_id", "parent_id", "name", "start_time", "end_time", "status", "attributes", "llm_call")
24
+ class AttributesEntry(_message.Message):
25
+ __slots__ = ("key", "value")
26
+ KEY_FIELD_NUMBER: _ClassVar[int]
27
+ VALUE_FIELD_NUMBER: _ClassVar[int]
28
+ key: str
29
+ value: str
30
+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...
31
+ TRACE_ID_FIELD_NUMBER: _ClassVar[int]
32
+ SPAN_ID_FIELD_NUMBER: _ClassVar[int]
33
+ PARENT_ID_FIELD_NUMBER: _ClassVar[int]
34
+ NAME_FIELD_NUMBER: _ClassVar[int]
35
+ START_TIME_FIELD_NUMBER: _ClassVar[int]
36
+ END_TIME_FIELD_NUMBER: _ClassVar[int]
37
+ STATUS_FIELD_NUMBER: _ClassVar[int]
38
+ ATTRIBUTES_FIELD_NUMBER: _ClassVar[int]
39
+ LLM_CALL_FIELD_NUMBER: _ClassVar[int]
40
+ trace_id: str
41
+ span_id: str
42
+ parent_id: str
43
+ name: str
44
+ start_time: _timestamp_pb2.Timestamp
45
+ end_time: _timestamp_pb2.Timestamp
46
+ status: SpanStatus
47
+ attributes: _containers.ScalarMap[str, str]
48
+ llm_call: LLMCallData
49
+ def __init__(self, trace_id: _Optional[str] = ..., span_id: _Optional[str] = ..., parent_id: _Optional[str] = ..., name: _Optional[str] = ..., start_time: _Optional[_Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping]] = ..., end_time: _Optional[_Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping]] = ..., status: _Optional[_Union[SpanStatus, str]] = ..., attributes: _Optional[_Mapping[str, str]] = ..., llm_call: _Optional[_Union[LLMCallData, _Mapping]] = ...) -> None: ...
50
+
51
+ class LLMCallData(_message.Message):
52
+ __slots__ = ("model", "prompt", "completion", "input_tokens", "output_tokens", "cost_usd")
53
+ MODEL_FIELD_NUMBER: _ClassVar[int]
54
+ PROMPT_FIELD_NUMBER: _ClassVar[int]
55
+ COMPLETION_FIELD_NUMBER: _ClassVar[int]
56
+ INPUT_TOKENS_FIELD_NUMBER: _ClassVar[int]
57
+ OUTPUT_TOKENS_FIELD_NUMBER: _ClassVar[int]
58
+ COST_USD_FIELD_NUMBER: _ClassVar[int]
59
+ model: str
60
+ prompt: str
61
+ completion: str
62
+ input_tokens: int
63
+ output_tokens: int
64
+ cost_usd: float
65
+ def __init__(self, model: _Optional[str] = ..., prompt: _Optional[str] = ..., completion: _Optional[str] = ..., input_tokens: _Optional[int] = ..., output_tokens: _Optional[int] = ..., cost_usd: _Optional[float] = ...) -> None: ...
@@ -0,0 +1,24 @@
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+ import warnings
5
+
6
+
7
+ GRPC_GENERATED_VERSION = '1.85.1'
8
+ GRPC_VERSION = grpc.__version__
9
+ _version_not_supported = False
10
+
11
+ try:
12
+ from grpc._utilities import first_version_is_lower
13
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
14
+ except ImportError:
15
+ _version_not_supported = True
16
+
17
+ if _version_not_supported:
18
+ raise RuntimeError(
19
+ f'The grpc package installed is at version {GRPC_VERSION},'
20
+ + ' but the generated code in span_pb2_grpc.py depends on'
21
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
22
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
23
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
24
+ )
@@ -0,0 +1,271 @@
1
+ """Conduit SDK for Python agents: send spans to the gateway over mTLS/gRPC.
2
+
3
+ Usage::
4
+
5
+ from conduit_observability import Client, LLMCall
6
+
7
+ with Client.from_env() as client:
8
+ with client.span("agent.run") as run:
9
+ run.set_attr("task", "summarize")
10
+ with client.span("llm.call") as llm: # child of agent.run
11
+ resp = call_model(prompt)
12
+ llm.record_llm_call(LLMCall(model=resp.model, prompt=prompt,
13
+ completion=resp.text,
14
+ input_tokens=resp.in_tokens,
15
+ output_tokens=resp.out_tokens))
16
+
17
+ An exception raised inside ``with client.span(...)`` marks the span as an
18
+ error (recording the message in ``error.message``) and is re-raised.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextvars
24
+ import logging
25
+ import os
26
+ import secrets
27
+ import time
28
+ from contextlib import contextmanager
29
+ from dataclasses import dataclass, field
30
+ from typing import Iterator, Optional
31
+
32
+ import grpc
33
+
34
+ from ._proto import ingestion_pb2, ingestion_pb2_grpc, log_pb2, metric_pb2, span_pb2
35
+
36
+ log = logging.getLogger("conduit_observability")
37
+
38
+ # Mirrors the gateway's schema.MaxAttributeValLen; longer values get the
39
+ # whole span rejected.
40
+ MAX_ATTR_VALUE_BYTES = 4096
41
+
42
+ # The span that new spans become children of, per thread and per asyncio task.
43
+ _current: contextvars.ContextVar[Optional["Span"]] = contextvars.ContextVar("conduit_current_span", default=None)
44
+
45
+
46
+ class ConduitError(Exception):
47
+ """A span could not be delivered or was rejected by the gateway."""
48
+
49
+
50
+ @dataclass
51
+ class LLMCall:
52
+ model: str
53
+ prompt: str
54
+ completion: str
55
+ input_tokens: int
56
+ output_tokens: int
57
+ cost_usd: float = 0.0
58
+
59
+
60
+ SEVERITY_UNSPECIFIED = log_pb2.LOG_SEVERITY_UNSPECIFIED
61
+ SEVERITY_DEBUG = log_pb2.LOG_SEVERITY_DEBUG
62
+ SEVERITY_INFO = log_pb2.LOG_SEVERITY_INFO
63
+ SEVERITY_WARN = log_pb2.LOG_SEVERITY_WARN
64
+ SEVERITY_ERROR = log_pb2.LOG_SEVERITY_ERROR
65
+
66
+ STATUS_UNSET = span_pb2.SPAN_STATUS_UNSET
67
+ STATUS_OK = span_pb2.SPAN_STATUS_OK
68
+ STATUS_ERROR = span_pb2.SPAN_STATUS_ERROR
69
+
70
+
71
+ @dataclass
72
+ class Span:
73
+ trace_id: str
74
+ span_id: str
75
+ parent_id: str
76
+ name: str
77
+ start_ns: int
78
+ attrs: dict = field(default_factory=dict)
79
+ status: int = STATUS_UNSET
80
+ llm_call: Optional[LLMCall] = None
81
+ _client: Optional["Client"] = field(default=None, repr=False)
82
+ _ended: bool = field(default=False, repr=False)
83
+
84
+ def set_attr(self, key: str, value: str) -> "Span":
85
+ self.attrs[key] = str(value)
86
+ return self
87
+
88
+ def set_ok(self) -> "Span":
89
+ self.status = STATUS_OK
90
+ return self
91
+
92
+ def set_error(self, err: Optional[BaseException | str]) -> "Span":
93
+ """Mark the span failed. ``None`` is a no-op, so callers needn't branch."""
94
+ if err is None:
95
+ return self
96
+ self.status = STATUS_ERROR
97
+ self.attrs["error.message"] = _truncate_utf8(str(err), MAX_ATTR_VALUE_BYTES)
98
+ return self
99
+
100
+ def record_llm_call(self, call: LLMCall) -> "Span":
101
+ self.llm_call = call
102
+ return self
103
+
104
+ def end(self) -> None:
105
+ """Send the span (once). Raises ConduitError if it isn't accepted."""
106
+ if self._ended:
107
+ return
108
+ self._ended = True
109
+ if self._client is not None:
110
+ self._client._send(self, time.time_ns())
111
+
112
+
113
+ class Client:
114
+ """SDK client. Create one per process and share it; safe across threads and asyncio tasks."""
115
+
116
+ def __init__(self, gateway_addr: str, tls_cert: str, tls_key: str, tls_ca: str,
117
+ timeout: float = 10.0, agent_name: Optional[str] = None):
118
+ # agent_name is accepted for compatibility but not sent: the gateway takes
119
+ # the agent's identity from its client certificate's CommonName.
120
+ del agent_name
121
+ self._timeout = timeout
122
+ self._channel = _secure_channel(gateway_addr, tls_cert, tls_key, tls_ca)
123
+ self._stub = ingestion_pb2_grpc.IngestionServiceStub(self._channel)
124
+
125
+ @classmethod
126
+ def from_env(cls) -> "Client":
127
+ """Build a client from CONDUIT_GATEWAY_ADDR, TLS_CERT, TLS_KEY, and TLS_CA.
128
+
129
+ OTEL_GATEWAY_ADDR is accepted as a fallback for CONDUIT_GATEWAY_ADDR.
130
+ """
131
+ addr = os.environ.get("CONDUIT_GATEWAY_ADDR") or os.environ["OTEL_GATEWAY_ADDR"]
132
+ return cls(addr, os.environ["TLS_CERT"], os.environ["TLS_KEY"], os.environ["TLS_CA"])
133
+
134
+ def start_span(self, name: str) -> Span:
135
+ """Start a span that is a child of the current span (if any). Call ``end()`` yourself."""
136
+ parent = _current.get()
137
+ return Span(
138
+ # W3C/OTLP sizes: 16-byte trace ID, 8-byte span ID, lowercase hex.
139
+ trace_id=parent.trace_id if parent else secrets.token_hex(16),
140
+ span_id=secrets.token_hex(8),
141
+ parent_id=parent.span_id if parent else "",
142
+ name=name,
143
+ start_ns=time.time_ns(),
144
+ _client=self,
145
+ )
146
+
147
+ @contextmanager
148
+ def span(self, name: str, *, raise_errors: bool = False) -> Iterator[Span]:
149
+ """Open a span as the current span; end and send it on exit.
150
+
151
+ By default, delivery failures are logged and not raised, so
152
+ instrumentation can't break the agent. With ``raise_errors=True`` they
153
+ raise ConduitError, unless the block is already raising its own
154
+ exception, which is never masked.
155
+ """
156
+ s = self.start_span(name)
157
+ token = _current.set(s)
158
+ failed = False
159
+ try:
160
+ yield s
161
+ except BaseException as exc:
162
+ failed = True
163
+ s.set_error(exc)
164
+ raise
165
+ finally:
166
+ _current.reset(token)
167
+ try:
168
+ s.end()
169
+ except ConduitError as err:
170
+ if raise_errors and not failed:
171
+ raise
172
+ log.warning("conduit: span %r not delivered: %s", s.name, err)
173
+
174
+ def log(self, severity: int, body: str, attributes: Optional[dict] = None) -> None:
175
+ """Send one log record. Inside a span (``with client.span(...)``) it is
176
+ linked to that span and its trace. Raises ConduitError if not accepted."""
177
+ rec = log_pb2.LogRecord(
178
+ severity=severity,
179
+ body=body,
180
+ attributes={k: str(v) for k, v in (attributes or {}).items()},
181
+ )
182
+ rec.timestamp.FromNanoseconds(time.time_ns())
183
+ current = _current.get()
184
+ if current is not None:
185
+ rec.trace_id, rec.span_id = current.trace_id, current.span_id
186
+ try:
187
+ resp = self._stub.IngestBatch(ingestion_pb2.IngestBatchRequest(logs=[rec]), timeout=self._timeout)
188
+ except grpc.RpcError as err:
189
+ raise ConduitError(f"ingest log: {err.code().name}: {err.details()}") from err
190
+ if resp.logs_accepted != 1:
191
+ reason = resp.errors[0] if resp.errors else "unknown reason"
192
+ raise ConduitError(f"gateway rejected log: {reason}")
193
+
194
+ def gauge(self, name: str, value: float, labels: Optional[dict] = None) -> None:
195
+ """Record the current value of ``name`` (e.g. a queue depth)."""
196
+ self._metric(name, value, labels, metric_pb2.METRIC_TYPE_GAUGE)
197
+
198
+ def counter(self, name: str, value: float, labels: Optional[dict] = None) -> None:
199
+ """Record a cumulative, non-negative value of ``name`` (e.g. requests_total)."""
200
+ self._metric(name, value, labels, metric_pb2.METRIC_TYPE_COUNTER)
201
+
202
+ def _metric(self, name: str, value: float, labels: Optional[dict], typ: int) -> None:
203
+ m = metric_pb2.Metric(name=name, value=float(value), type=typ,
204
+ labels={k: str(v) for k, v in (labels or {}).items()})
205
+ m.timestamp.FromNanoseconds(time.time_ns())
206
+ try:
207
+ resp = self._stub.IngestBatch(ingestion_pb2.IngestBatchRequest(metrics=[m]), timeout=self._timeout)
208
+ except grpc.RpcError as err:
209
+ raise ConduitError(f"ingest metric: {err.code().name}: {err.details()}") from err
210
+ if resp.metrics_accepted != 1:
211
+ reason = resp.errors[0] if resp.errors else "unknown reason"
212
+ raise ConduitError(f"gateway rejected metric: {reason}")
213
+
214
+ def _send(self, s: Span, end_ns: int) -> None:
215
+ req = ingestion_pb2.IngestSpanRequest(span=_to_proto(s, end_ns))
216
+ try:
217
+ resp = self._stub.IngestSpan(req, timeout=self._timeout)
218
+ except grpc.RpcError as err:
219
+ raise ConduitError(f"ingest span: {err.code().name}: {err.details()}") from err
220
+ if not resp.accepted:
221
+ raise ConduitError(f"gateway rejected span: {resp.rejection_reason}")
222
+
223
+ def close(self) -> None:
224
+ self._channel.close()
225
+
226
+ def __enter__(self) -> "Client":
227
+ return self
228
+
229
+ def __exit__(self, *_exc) -> None:
230
+ self.close()
231
+
232
+
233
+ def _to_proto(s: Span, end_ns: int) -> span_pb2.Span:
234
+ out = span_pb2.Span(
235
+ trace_id=s.trace_id,
236
+ span_id=s.span_id,
237
+ parent_id=s.parent_id,
238
+ name=s.name,
239
+ status=s.status,
240
+ attributes=s.attrs,
241
+ )
242
+ out.start_time.FromNanoseconds(s.start_ns)
243
+ out.end_time.FromNanoseconds(max(end_ns, s.start_ns))
244
+ if s.llm_call is not None:
245
+ c = s.llm_call
246
+ out.llm_call.CopyFrom(span_pb2.LLMCallData(
247
+ model=c.model, prompt=c.prompt, completion=c.completion,
248
+ input_tokens=c.input_tokens, output_tokens=c.output_tokens, cost_usd=c.cost_usd,
249
+ ))
250
+ return out
251
+
252
+
253
+ def _secure_channel(addr: str, cert: str, key: str, ca: str) -> grpc.Channel:
254
+ """mTLS channel that trusts only ``ca`` for the gateway's certificate."""
255
+ def read(path: str) -> bytes:
256
+ with open(path, "rb") as f:
257
+ return f.read()
258
+
259
+ creds = grpc.ssl_channel_credentials(
260
+ root_certificates=read(ca),
261
+ private_key=read(key),
262
+ certificate_chain=read(cert),
263
+ )
264
+ return grpc.secure_channel(addr, creds)
265
+
266
+
267
+ def _truncate_utf8(s: str, limit: int) -> str:
268
+ b = s.encode("utf-8")
269
+ if len(b) <= limit:
270
+ return s
271
+ return b[:limit].decode("utf-8", errors="ignore")
@@ -0,0 +1,24 @@
1
+ """Cost estimation utilities for LLM calls."""
2
+
3
+ # Prices per 1M tokens: (input $/1M, output $/1M)
4
+ _PRICES: dict[str, tuple[float, float]] = {
5
+ "claude-opus-4-6": (15.0, 75.0),
6
+ "claude-sonnet-4-6": (3.0, 15.0),
7
+ "claude-haiku-4-5": (0.80, 4.0),
8
+ "gpt-4o": (5.0, 15.0),
9
+ "gpt-4o-mini": (0.15, 0.60),
10
+ "gemini-1.5-pro": (7.0, 21.0),
11
+ "gemini-1.5-flash": (0.35, 1.05),
12
+ }
13
+
14
+
15
+ def estimate_cost_usd(model: str, input_tokens: int, output_tokens: int) -> float:
16
+ """Estimate cost in USD from token counts and model pricing.
17
+
18
+ Returns 0.0 for unknown models — add the model to _PRICES to fix.
19
+ """
20
+ prices = _PRICES.get(model)
21
+ if prices is None:
22
+ return 0.0
23
+ input_price, output_price = prices
24
+ return (input_tokens * input_price + output_tokens * output_price) / 1_000_000
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.5
2
+ Name: conduit-observability
3
+ Version: 0.1.0
4
+ Summary: Python SDK for Conduit: send traces, logs and metrics from AI agents to a Conduit gateway over mTLS/gRPC
5
+ Project-URL: Homepage, https://tjscanlan.github.io/conduit/
6
+ Project-URL: Documentation, https://tjscanlan.github.io/conduit/sdk-python.html
7
+ Project-URL: Repository, https://github.com/tjscanlan/conduit
8
+ Project-URL: Issues, https://github.com/tjscanlan/conduit/issues
9
+ Author: TJ Scanlan
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: ai-agents,grpc,llm,mtls,observability,telemetry,tracing
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: System :: Logging
24
+ Classifier: Topic :: System :: Monitoring
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: grpcio>=1.85.1
27
+ Requires-Dist: protobuf<8,>=7.35.1
28
+ Provides-Extra: dev
29
+ Requires-Dist: cryptography>=46; extra == 'dev'
30
+ Requires-Dist: pytest>=8; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # conduit-observability
34
+
35
+ The Python SDK for [Conduit](https://tjscanlan.github.io/conduit/), secure, self-hosted observability for AI agents. It sends **traces, logs and metrics** from your agent to a Conduit gateway over gRPC with mutual TLS.
36
+
37
+ ```bash
38
+ pip install conduit-observability
39
+ ```
40
+
41
+ Requires Python 3.10 or newer, and a running Conduit gateway with a client certificate for your agent. See [Deployment](https://tjscanlan.github.io/conduit/deployment.html).
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from conduit_observability import Client, LLMCall, SEVERITY_WARN
47
+
48
+ with Client(
49
+ "gateway.example.com:4317",
50
+ tls_cert="certs/research-bot.crt", # your agent's client certificate
51
+ tls_key="certs/research-bot.key",
52
+ tls_ca="certs/ca.crt", # the only CA trusted for the gateway
53
+ ) as client:
54
+ with client.span("agent.run") as run:
55
+ run.set_attr("task", "summarize")
56
+
57
+ with client.span("llm.call") as llm: # nested: same trace
58
+ resp = call_model(prompt) # an exception marks the span as an error
59
+ llm.record_llm_call(LLMCall(model=resp.model, prompt=prompt, completion=resp.text,
60
+ input_tokens=resp.input_tokens, output_tokens=resp.output_tokens))
61
+ llm.set_ok()
62
+
63
+ client.log(SEVERITY_WARN, "retrying tool call", {"attempt": 2}) # linked to agent.run
64
+ client.gauge("queue_depth", 7, {"queue": "tasks"})
65
+ ```
66
+
67
+ ## What you get
68
+
69
+ - **Spans** that nest automatically. The current span is tracked with `contextvars`, so nesting is correct across threads and asyncio tasks.
70
+ - **Errors recorded for you:** an exception inside `with client.span(...)` marks the span as an error, records the message, and propagates.
71
+ - **Logs** (`client.log`) linked to the current span, and **metrics** (`client.gauge`, `client.counter`).
72
+ - **Strict TLS:** the gateway is verified against your CA only, never the system roots.
73
+ - **Identity from your certificate:** the gateway takes your agent's identity from the certificate's CommonName, so an attribute can't spoof it.
74
+
75
+ ## Documentation
76
+
77
+ - [Python SDK guide](https://tjscanlan.github.io/conduit/sdk-python.html): the full API, limits and delivery semantics.
78
+ - [API reference](https://tjscanlan.github.io/conduit/api.html): the wire protocol and validation limits.
79
+ - [Source](https://github.com/tjscanlan/conduit/tree/main/sdk/python).
80
+
81
+ Licensed under Apache-2.0.
@@ -0,0 +1,20 @@
1
+ conduit_observability/__init__.py,sha256=D99Djt5s37WUypwsS5lgePijDLwpxGea0RSN1niaqcI,615
2
+ conduit_observability/client.py,sha256=7_rtG7wYn7JbRkzjdnHQeFPJuwJiqXNUhVdEINwAHRo,10106
3
+ conduit_observability/llm.py,sha256=Tr3pFP3qjKbyhG9fMzJQoshDJ_OMkMGBrtNWuZ3dc-U,840
4
+ conduit_observability/_proto/__init__.py,sha256=UER8ftXk7Qrs0P5O03dYDC79KrIiwSHoKxpd268mQ7o,84
5
+ conduit_observability/_proto/ingestion_pb2.py,sha256=vVm28y-IsIZ6HOApDPbTz-dGXOlTsM3nEGHRIyVtaRs,2865
6
+ conduit_observability/_proto/ingestion_pb2.pyi,sha256=DgRhJlorLBX2wTvaW4J9xZQ9XIsk4YO8Ns9_1wJkf0E,2351
7
+ conduit_observability/_proto/ingestion_pb2_grpc.py,sha256=8jMJQY4iQuWGg4YGgMQtLr04w3DbLCdKLXQyoDHY1bI,5641
8
+ conduit_observability/_proto/log_pb2.py,sha256=dihfQm0e_ZRqfzK8RX5uQcWSt3N_E3F3ErQe_NmRWyo,2523
9
+ conduit_observability/_proto/log_pb2.pyi,sha256=Klil0-Svr7HrrY8HNdX-fN3alXKrcRA5sZw9rdCZzAo,2135
10
+ conduit_observability/_proto/log_pb2_grpc.py,sha256=hSuBHEpmJFRW-i5yQd0TwcFLyst18LYEmbW7D8koAUA,883
11
+ conduit_observability/_proto/metric_pb2.py,sha256=Pw35RLWNXU4iHHmjOHDRlHSb3KZwZdVurmMCuuAo7LM,2347
12
+ conduit_observability/_proto/metric_pb2.pyi,sha256=itBgErd0oS6G-QeTDQGcNMV_RIxoU91e8RlkMQyTFJc,1823
13
+ conduit_observability/_proto/metric_pb2_grpc.py,sha256=gk08NrDP-jOODRRVnC-SyOkAWTHONO3-KseOVORYihc,886
14
+ conduit_observability/_proto/span_pb2.py,sha256=MinhxGGjMnbhY5VVZByRRZNM7d-sEOfADdcDGij-Zpo,2921
15
+ conduit_observability/_proto/span_pb2.pyi,sha256=0YpDtocy5K7dlXi7pzIoDuJElltiFqxIX_vJpIPeWYc,3111
16
+ conduit_observability/_proto/span_pb2_grpc.py,sha256=oizS2UEvyXmZPrW_1AGpSK1JkMjkgczaV-oj5yx1JIo,884
17
+ conduit_observability-0.1.0.dist-info/METADATA,sha256=NDpiKcuh_qbSg9OEeVjo1MAFZorXBonBhBBZnwDIzpo,3833
18
+ conduit_observability-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
19
+ conduit_observability-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
20
+ conduit_observability-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.