-
Notifications
You must be signed in to change notification settings - Fork 464
Validator Hub Telemetry #559
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Parent:
import tele changes
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
eba76a6
Add OpenTelemetry class for validator hub
thekaranacharya 5aaecb9
Init global tracer, use it to create nested spans to send usage data
thekaranacharya 6cfcdf4
Add placeholder cli classes to get creds from local file; will have m…
thekaranacharya 9bfc5f5
Update class, endpoint, add new methods for context
thekaranacharya 44fcd93
Add new span, update existing spans, one parent, multiple children
thekaranacharya 2467842
Update endpoint
thekaranacharya 49c83ae
Lint
thekaranacharya ee708e4
Update credentials, and add logger
thekaranacharya 5e4096b
Add util method that will create spans from anywhere, update existing…
thekaranacharya fc87a74
Replace print with logging
thekaranacharya af28d40
Add opt-out
thekaranacharya 2054f91
Update str var to bool
thekaranacharya 6500348
lint
thekaranacharya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import os | ||
| from dataclasses import dataclass | ||
| from os.path import expanduser | ||
| from typing import Optional | ||
|
|
||
| from guardrails.cli_dir.logger import logger | ||
| from guardrails.cli_dir.server.serializeable import Serializeable | ||
|
|
||
|
|
||
| @dataclass | ||
| class Credentials(Serializeable): | ||
| id: Optional[str] = None | ||
| client_id: Optional[str] = None | ||
| client_secret: Optional[str] = None | ||
| no_metrics: Optional[bool] = False | ||
|
|
||
| @staticmethod | ||
| def from_rc_file() -> "Credentials": | ||
| try: | ||
| home = expanduser("~") | ||
| guardrails_rc = os.path.join(home, ".guardrailsrc") | ||
| with open(guardrails_rc) as rc_file: | ||
| lines = rc_file.readlines() | ||
| creds = {} | ||
| for line in lines: | ||
| key, value = line.split("=", 1) | ||
| creds[key.strip()] = value.strip() | ||
| rc_file.close() | ||
| return Credentials.from_dict(creds) | ||
|
|
||
| except FileNotFoundError as e: | ||
| logger.error(e) | ||
| logger.error( | ||
| "Guardrails Hub credentials not found!" | ||
| "You will need to sign up to use any authenticated Validators here:" | ||
| "{insert url}" | ||
| ) | ||
| return Credentials() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import logging | ||
| import os | ||
|
|
||
| import coloredlogs | ||
|
|
||
| os.environ[ | ||
| "COLOREDLOGS_LEVEL_STYLES" | ||
| ] = "spam=white,faint;success=green,bold;debug=magenta;verbose=blue;notice=cyan,bold;warning=yellow;error=red;critical=background=red" # noqa | ||
| LEVELS = { | ||
| "SPAM": 5, | ||
| "VERBOSE": 15, | ||
| "NOTICE": 25, | ||
| "SUCCESS": 35, | ||
| } | ||
| for key in LEVELS: | ||
| logging.addLevelName(LEVELS.get(key), key) # type: ignore | ||
|
|
||
|
|
||
| logger = logging.getLogger("guardrails-cli") | ||
| coloredlogs.install(level="DEBUG", logger=logger) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import inspect | ||
| import json | ||
| from dataclasses import InitVar, asdict, dataclass, field, is_dataclass | ||
| from json import JSONEncoder | ||
| from typing import Any, Dict | ||
|
|
||
|
|
||
| class SerializeableJSONEncoder(JSONEncoder): | ||
| def default(self, o): | ||
| if is_dataclass(o): | ||
| return asdict(o) | ||
| return super().default(o) | ||
|
|
||
|
|
||
| @dataclass | ||
| class Serializeable: | ||
| encoder: InitVar[JSONEncoder] = field( | ||
| kw_only=True, default=SerializeableJSONEncoder # type: ignore | ||
| ) | ||
|
|
||
| @classmethod | ||
| def from_dict(cls, data: Dict[str, Any]): | ||
| annotations = inspect.get_annotations(cls) | ||
| attributes = dict.keys(annotations) | ||
| kwargs = {k: data.get(k) for k in data if k in attributes} | ||
| return cls(**kwargs) # type: ignore | ||
|
|
||
| @property | ||
| def __dict__(self) -> Dict[str, Any]: | ||
| return asdict(self) | ||
|
|
||
| def to_json(self): | ||
| return json.dumps(self, cls=self.encoder) # type: ignore |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| # Imports | ||
| import logging | ||
|
|
||
| from opentelemetry import trace | ||
| from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( # HTTP Exporter | ||
| OTLPSpanExporter, | ||
| ) | ||
| from opentelemetry.sdk.resources import SERVICE_NAME, Resource | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor | ||
| from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator | ||
|
|
||
|
|
||
| class HubTelemetry: | ||
| """Singleton class for initializing a tracer for Guardrails Hub.""" | ||
|
|
||
| _instance = None | ||
| _service_name = None | ||
| _endpoint = None | ||
| _tracer_name = None | ||
| _resource = None | ||
| _tracer_provider = None | ||
| _processor = None | ||
| _tracer = None | ||
| _prop = None | ||
| _carrier = {} | ||
|
|
||
| def __new__( | ||
| cls, | ||
| service_name: str = "guardrails-hub", | ||
| tracer_name: str = "gr_hub", | ||
| export_locally: bool = False, | ||
| ): | ||
| if cls._instance is None: | ||
| logging.debug("Creating HubTelemetry instance...") | ||
| cls._instance = super(HubTelemetry, cls).__new__(cls) | ||
| logging.debug("Initializing HubTelemetry instance...") | ||
| cls._instance.initialize_tracer(service_name, tracer_name, export_locally) | ||
| else: | ||
| logging.debug("Returning existing HubTelemetry instance...") | ||
| return cls._instance | ||
|
|
||
| def initialize_tracer( | ||
| self, | ||
| service_name: str, | ||
| tracer_name: str, | ||
| export_locally: bool, | ||
| ): | ||
| """Initializes a tracer for Guardrails Hub.""" | ||
|
|
||
| self._service_name = service_name | ||
| # self._endpoint = "http://localhost:4318/v1/traces" | ||
| self._endpoint = ( | ||
| "https://hty0gc1ok3.execute-api.us-east-1.amazonaws.com/v1/traces" | ||
| ) | ||
| self._tracer_name = tracer_name | ||
|
|
||
| # Create a resource | ||
| # Service name is required for most backends | ||
| self._resource = Resource(attributes={SERVICE_NAME: self._service_name}) | ||
|
|
||
| # Create a tracer provider and a processor | ||
| self._tracer_provider = TracerProvider(resource=self._resource) | ||
|
|
||
| if export_locally: | ||
| self._processor = SimpleSpanProcessor(ConsoleSpanExporter()) | ||
| else: | ||
| self._processor = SimpleSpanProcessor( | ||
| OTLPSpanExporter(endpoint=self._endpoint) | ||
| ) | ||
|
|
||
| # Add the processor to the provider | ||
| self._tracer_provider.add_span_processor(self._processor) | ||
|
|
||
| # Set the tracer provider and return a tracer | ||
| trace.set_tracer_provider(self._tracer_provider) | ||
| self._tracer = trace.get_tracer(self._tracer_name) | ||
|
|
||
| self._prop = TraceContextTextMapPropagator() | ||
|
|
||
| def inject_current_context(self) -> None: | ||
| """Injects the current context into the carrier.""" | ||
| self._prop.inject(carrier=self._carrier) | ||
|
|
||
| def extract_current_context(self): | ||
| """Extracts the current context from the carrier.""" | ||
|
|
||
| context = self._prop.extract(carrier=self._carrier) | ||
| return context | ||
|
|
||
| def create_new_span( | ||
| self, | ||
| span_name: str, | ||
| attributes: list, | ||
| is_parent: bool, # Inject current context if IS a parent span | ||
| has_parent: bool, # Extract current context if HAS a parent span | ||
| ): | ||
| """Creates a new span within the tracer with the given name and | ||
| attributes. | ||
|
|
||
| If it's a parent span, the current context is injected into the carrier. | ||
| If it has a parent span, the current context is extracted from the carrier. | ||
| Both the conditions can co-exist e.g. a span can be a parent span which | ||
| also has a parent span. | ||
|
|
||
| Args: | ||
| span_name (str): The name of the span. | ||
| attributes (list): A list of attributes to set on the span. | ||
| is_parent (bool): True if the span is a parent span. | ||
| has_parent (bool): True if the span has a parent span. | ||
| """ | ||
|
|
||
| with self._tracer.start_as_current_span( | ||
| span_name, | ||
| context=self.extract_current_context() if has_parent else None, | ||
| ) as span: | ||
| if is_parent: | ||
| # Inject the current context | ||
| self.inject_current_context() | ||
|
|
||
| for attribute in attributes: | ||
| span.set_attribute(attribute[0], attribute[1]) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.