generated from teamhide/fastapi-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
chore: Metrics , tracks commands , errors for now #81
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
Merged
Changes from 19 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a8617f8
chore: starting metrics work
vinikatyal eca7af2
chore: analytics tracking
vinikatyal 62f2666
chore: remove not needed code
vinikatyal 9f2238c
chore: update req.txt
vinikatyal 4ebf2a0
Merge branch 'main' into vk/metrics
vinikatyal 87ba0d8
Merge branch 'main' into vk/metrics
vinikatyal 731adae
Merge branch 'main' into vk/metrics
vinikatyal 5c23e38
chore: connect to azure
vinikatyal f783c85
chore: remove screenshot for now
vinikatyal da90219
Merge branch 'main' into vk/metrics
vinikatyal 7b3b6c8
chore: update the tracker code
vinikatyal 371ec35
chore: track dashboard events
vinikatyal d727a2a
chore: remove cli_command
vinikatyal 63c06d5
chore: add
vinikatyal 1340fb4
chore: remove image
vinikatyal 584ec2c
chore: moved to settings
vinikatyal a303977
chore: remove logging
vinikatyal d2c1171
chore: hard coded values
vinikatyal bbb9029
chore: remove nist
vinikatyal 262b362
chore: remove print
vinikatyal 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
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,18 @@ | ||
| from pathlib import Path | ||
| import uuid | ||
|
|
||
| def get_client_id() -> str: | ||
| """Retrieve or create a unique, anonymous client ID for this user.""" | ||
| user_home = Path.home() | ||
| client_id_path = user_home / ".compliant-llm" / ".client-id" | ||
| client_id_path.parent.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| if client_id_path.exists(): | ||
| with open(client_id_path, "r") as f: | ||
| return f.read().strip() | ||
|
|
||
| # Generate and save a new UUID | ||
| new_id = str(uuid.uuid4()) | ||
| with open(client_id_path, "w") as f: | ||
| f.write(new_id) | ||
| return new_id |
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,8 @@ | ||
| def get_azure_settings(): | ||
| """Get Azure Monitor settings.""" | ||
| return { | ||
| "instrumentation_key": "ed532436-db1f-46bb-aeef-17cb4f3dcf8b", | ||
| "ingestion_endpoint": "https://westus-0.in.applicationinsights.azure.com/", | ||
| } | ||
|
|
||
| azure_settings = get_azure_settings() |
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,171 @@ | ||
| import os | ||
| from enum import Enum | ||
| from typing import Optional | ||
| from pydantic import BaseModel, Field | ||
|
|
||
| # OpenTelemetry core | ||
| from opentelemetry import trace | ||
| from opentelemetry.sdk.resources import SERVICE_NAME, Resource | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter | ||
| from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter, AzureMonitorMetricExporter | ||
|
|
||
| # OpenTelemetry metrics | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.metrics import set_meter_provider, get_meter_provider | ||
| from opentelemetry.sdk.metrics.export import ( | ||
| PeriodicExportingMetricReader, | ||
| ConsoleMetricExporter, | ||
| ) | ||
|
|
||
| # ---------------------------- | ||
| # Opt-out utility | ||
| # ---------------------------- | ||
| def is_analytics_enabled() -> bool: | ||
| return os.getenv("DISABLE_COMPLIANT_LLM_TELEMETRY", "false").lower() != "true" | ||
|
|
||
| # ---------------------------- | ||
| # Client ID utility (you should define this) | ||
| # ---------------------------- | ||
| from .client import get_client_id | ||
|
|
||
| # ---------------------------- | ||
| # Event Type Enums and Models | ||
| # ---------------------------- | ||
| class EventType(str, Enum): | ||
| USAGE = "usage" | ||
| ERROR = "error" | ||
|
|
||
| class InteractionType(str, Enum): | ||
| CLI = "cli" | ||
| DASHBOARD = "dashboard" | ||
| API = "api" | ||
| BATCH = "batch" | ||
|
|
||
| class BaseEvent(BaseModel): | ||
| name: str | ||
| interaction_type: InteractionType | ||
| client_id: Optional[str] = Field(default_factory=get_client_id) | ||
| type: EventType | ||
|
|
||
| class UsageEvent(BaseEvent): | ||
| type: EventType = EventType.USAGE | ||
|
|
||
| class ErrorEvent(BaseEvent): | ||
| error_msg: str | ||
| type: EventType = EventType.ERROR | ||
|
|
||
| # ---------------------------- | ||
| # Tracker Class | ||
| # ---------------------------- | ||
| class AnalyticsTracker: | ||
| def __init__(self): | ||
| self.enabled = is_analytics_enabled() | ||
| if not self.enabled: | ||
| self.tracer = None | ||
| self.usage_counter = None | ||
| self.error_counter = None | ||
| return | ||
|
|
||
| from .settings import azure_settings | ||
|
|
||
| instrumentation_key = azure_settings["instrumentation_key"] | ||
| ingestion_endpoint = azure_settings["ingestion_endpoint"] | ||
|
|
||
| # Resource | ||
| resource = Resource.create({ | ||
| SERVICE_NAME: "compliant-llm", | ||
| "service.version": "1.0.0", | ||
| "environment": os.getenv("ENVIRONMENT", "prod") | ||
| }) | ||
|
|
||
| # Initialize tracing | ||
| try: | ||
| trace_exporter = AzureMonitorTraceExporter( | ||
| connection_string=f"InstrumentationKey={instrumentation_key};IngestionEndpoint={ingestion_endpoint}" | ||
| ) | ||
| trace.set_tracer_provider(TracerProvider(resource=resource)) | ||
| tracer_provider = trace.get_tracer_provider() | ||
| tracer_provider.add_span_processor(BatchSpanProcessor(trace_exporter)) | ||
| tracer_provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter())) | ||
| self.tracer = trace.get_tracer("compliant-llm") | ||
| except Exception as e: | ||
| print(f"❌ Failed to initialize tracing: {e}") | ||
|
||
| self.tracer = None | ||
|
|
||
| # Initialize metrics | ||
| try: | ||
| metric_exporter = AzureMonitorMetricExporter( | ||
| connection_string=f"InstrumentationKey={instrumentation_key};IngestionEndpoint={ingestion_endpoint}" | ||
| ) | ||
| metric_readers = [ | ||
| PeriodicExportingMetricReader(ConsoleMetricExporter()), | ||
| PeriodicExportingMetricReader(metric_exporter) | ||
| ] | ||
| meter_provider = MeterProvider(resource=resource, metric_readers=metric_readers) | ||
| set_meter_provider(meter_provider) | ||
| self.meter = get_meter_provider().get_meter("compliant-llm") | ||
| self.usage_counter = self.meter.create_counter( | ||
| name="compliant_llm.command_invocations", | ||
| description="Number of CLI/dashboard/API commands invoked" | ||
| ) | ||
| self.error_counter = self.meter.create_counter( | ||
| name="compliant_llm.errors", | ||
| description="Number of errors encountered" | ||
| ) | ||
| except Exception as e: | ||
| self.usage_counter = None | ||
| self.error_counter = None | ||
|
|
||
| def track(self, event: BaseEvent): | ||
| if not self.enabled: | ||
| return # Opted out | ||
|
|
||
| # --- Tracing --- | ||
| try: | ||
| with self.tracer.start_as_current_span(f"{event.type.value}:{event.name}") as span: | ||
| span.set_attribute("interaction_type", event.interaction_type.value) | ||
| span.set_attribute("event_type", event.type.value) | ||
| span.set_attribute("command", event.name) | ||
| if event.client_id: | ||
| span.set_attribute("client_id", event.client_id) | ||
| if isinstance(event, ErrorEvent): | ||
| span.set_attribute("error_msg", event.error_msg[:100]) | ||
| except Exception as e: | ||
| print(f"❌ Error during tracing: {e}") | ||
vinikatyal marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # --- Metrics --- | ||
| attributes = { | ||
| "interaction_type": event.interaction_type.value, | ||
| "name": event.name | ||
| } | ||
| if event.client_id: | ||
| attributes["client_id"] = event.client_id | ||
| if isinstance(event, ErrorEvent): | ||
| attributes["error_msg"] = event.error_msg[:100] | ||
|
|
||
| try: | ||
| if event.type == EventType.USAGE and self.usage_counter: | ||
| self.usage_counter.add(1, attributes) | ||
| elif event.type == EventType.ERROR and self.error_counter: | ||
| self.error_counter.add(1, attributes) | ||
| except Exception as e: | ||
| print(f"❌ Error during metrics recording: {e}") | ||
vinikatyal marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # ---------------------------- | ||
| # Usage Tracking Decorator | ||
| # ---------------------------- | ||
| def track_usage(name: str, interaction_type: InteractionType = None): | ||
| def decorator(func): | ||
| def wrapper(*args, **kwargs): | ||
| if analytics_tracker.enabled: | ||
| event = UsageEvent(name=name, interaction_type=interaction_type) | ||
| analytics_tracker.track(event) | ||
| return func(*args, **kwargs) | ||
| return wrapper | ||
| return decorator | ||
|
|
||
| # ---------------------------- | ||
| # Global Tracker Instance | ||
| # ---------------------------- | ||
| analytics_tracker = AnalyticsTracker() | ||
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
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
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.