Skip to content
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

Direct Exporter - Blob store #41

Merged
merged 11 commits into from
Oct 14, 2024
15 changes: 11 additions & 4 deletions Monocle_User_Guide.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#Monocle User Guide
# Monocle User Guide

## Monocle Concepts
### Traces
Expand All @@ -13,15 +13,20 @@ It’s typically the workflow code components of an application that generate th
```
> pip install monocle_apptrace
```
- For Azure support (to upload traces to Azure), install with the azure extra:
```
> pip install monocle_apptrace[azure]
```
- You can locally build and install Monocle library from source
```
> pip install .
> pip install .
```
- Install the optional test dependencies listed against dev in pyproject.toml in editable mode
```
> pip install -e ".[dev]"
> pip install -e ".[dev]"
```


## Using Monocle with your application to generate traces
### Enable Monocle tracing
You need to import monocle package and invoke the API ``setup_monocle_telemetry(workflow=<workflow-name>)`` to enable the tracing. The 'workflow-name' is what you define to identify the give application workflow, for example "customer-chatbot". Monocle trace will include this name in every trace. The trace output will include a list of spans in the traces. You can print the output on the console or send it to an HTTP endpoint.
Expand All @@ -48,7 +53,7 @@ chain.invoke({"number":2})
# Request callbacks: Finally, let's use the request `callbacks` to achieve the same result
chain = LLMChain(llm=llm, prompt=prompt)
chain.invoke({"number":2}, {"callbacks":[handler]})

```

### Accessing monocle trace
Expand All @@ -63,6 +68,8 @@ setup_monocle_telemetry(workflow_name = "simple_math_app",
```
To print the trace on the console, use ```ConsoleSpanExporter()``` instead of ```FileSpanExporter()```

For Azure:
Install the Azure support as shown in the setup section, then use ```AzureBlobSpanExporter()``` to upload the traces to Azure.
### Leveraging Monocle's extensibility to handle customization
When the out of box features from app frameworks are not sufficent, the app developers have to add custom code. For example, if you are extending a LLM class in LlamaIndex to use a model hosted in NVIDIA Triton. This new class is not know to Monocle. You can specify this new class method part of Monocle enabling API and it will be able to trace it.

Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ dev = [
'llama-index-vector-stores-chroma==0.1.9',
'parameterized==0.9.0'
]

azure = [
'azure-storage-blob==12.22.0',
]
[project.urls]
Homepage = "https://github.com/monocle2ai/monocle"
Issues = "https://github.com/monocle2ai/monocle/issues"
Expand Down
117 changes: 117 additions & 0 deletions src/monocle_apptrace/exporters/azure/azure_exporter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import os
sachintendulkar576123 marked this conversation as resolved.
Show resolved Hide resolved
import time
import random
import datetime
import logging
import asyncio
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient # AIO version for async
from azure.core.exceptions import ResourceNotFoundError, ClientAuthenticationError, ServiceRequestError
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
from typing import Sequence
from monocle_apptrace.exporters.span_exporter_base import SpanExporterBase

logger = logging.getLogger(__name__)

class AzureBlobSpanExporter(SpanExporterBase):
def __init__(self, connection_string=None, container_name=None):
super().__init__()
DEFAULT_FILE_PREFIX = "monocle_trace_"
DEFAULT_TIME_FORMAT = "%Y-%m-%d_%H.%M.%S"
self.max_batch_size = 500
self.export_interval = 1
# Use default values if none are provided
if not connection_string:
connection_string = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
if not connection_string:
raise ValueError("Azure Storage connection string is not provided or set in environment variables.")

if not container_name:
container_name = os.getenv('AZURE_STORAGE_CONTAINER_NAME', 'default-container')

self.blob_service_client = BlobServiceClient.from_connection_string(connection_string)
self.container_name = container_name
self.file_prefix = DEFAULT_FILE_PREFIX
self.time_format = DEFAULT_TIME_FORMAT

# Check if container exists or create it
if not self.__container_exists(container_name):
try:
self.blob_service_client.create_container(container_name)
logger.info(f"Container {container_name} created successfully.")
except Exception as e:
logger.error(f"Error creating container {container_name}: {e}")
raise e

def __container_exists(self, container_name):
try:
container_client = self.blob_service_client.get_container_client(container_name)
container_client.get_container_properties()
return True
except ResourceNotFoundError:
return False
except Exception as e:
logger.error(f"Error checking if container {container_name} exists: {e}")
return False

def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
"""Synchronous export method that internally handles async logic."""
try:
# Run the asynchronous export logic in an event loop
asyncio.run(self._export_async(spans))
return SpanExportResult.SUCCESS
except Exception as e:
logger.error(f"Error exporting spans: {e}")
return SpanExportResult.FAILURE

async def _export_async(self, spans: Sequence[ReadableSpan]):
"""The actual async export logic is run here."""
# Add spans to the export queue
for span in spans:
self.export_queue.append(span)
if len(self.export_queue) >= self.max_batch_size:
await self.__export_spans()

# Force a flush if the interval has passed
current_time = time.time()
if current_time - self.last_export_time >= self.export_interval:
await self.__export_spans()
self.last_export_time = current_time

def __serialize_spans(self, spans: Sequence[ReadableSpan]) -> str:
try:
span_data_list = [span.to_json() for span in spans]
return "[" + ", ".join(span_data_list) + "]"
except Exception as e:
logger.error(f"Error serializing spans: {e}")
raise

async def __export_spans(self):
if len(self.export_queue) == 0:
return

batch_to_export = self.export_queue[:self.max_batch_size]
serialized_data = self.__serialize_spans(batch_to_export)
self.export_queue = self.export_queue[self.max_batch_size:]
try:
if asyncio.get_event_loop().is_running():
task = asyncio.create_task(self._retry_with_backoff(self.__upload_to_blob, serialized_data))
await task
else:
await self._retry_with_backoff(self.__upload_to_blob, serialized_data)
except Exception as e:
logger.error(f"Failed to upload span batch: {e}")

def __upload_to_blob(self, span_data_batch: str):
current_time = datetime.datetime.now().strftime(self.time_format)
file_name = f"{self.file_prefix}{current_time}.json"
blob_client = self.blob_service_client.get_blob_client(container=self.container_name, blob=file_name)
blob_client.upload_blob(span_data_batch, overwrite=True)
logger.info(f"Span batch uploaded to Azure Blob Storage as {file_name}.")

async def force_flush(self, timeout_millis: int = 30000) -> bool:
await self.__export_spans()
return True

def shutdown(self) -> None:
logger.info("AzureBlobSpanExporter has been shut down.")
54 changes: 54 additions & 0 deletions src/monocle_apptrace/exporters/span_exporter_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import time
sachintendulkar576123 marked this conversation as resolved.
Show resolved Hide resolved
import random
import logging
from abc import ABC, abstractmethod
from azure.core.exceptions import ServiceRequestError, ClientAuthenticationError
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
from typing import Sequence
import asyncio
sachintendulkar576123 marked this conversation as resolved.
Show resolved Hide resolved

logger = logging.getLogger(__name__)

class SpanExporterBase(ABC):
def __init__(self):
self.backoff_factor = 2
self.max_retries = 10
self.export_queue = []
self.last_export_time = time.time()

@abstractmethod
async def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
pass

@abstractmethod
async def force_flush(self, timeout_millis: int = 30000) -> bool:
pass


def shutdown(self) -> None:
pass

async def _retry_with_backoff(self, func, *args, **kwargs):
"""Handle retries with exponential backoff."""
attempt = 0
while attempt < self.max_retries:
try:
return func(*args, **kwargs)
except ServiceRequestError as e:
logger.warning(f"Network connectivity error: {e}. Retrying in {self.backoff_factor ** attempt} seconds...")
sleep_time = self.backoff_factor * (2 ** attempt) + random.uniform(0, 1)
await asyncio.sleep(sleep_time) # Use asyncio.sleep() instead of time.sleep()
attempt += 1
except ClientAuthenticationError as e:
logger.error(f"Failed to authenticate: {str(e)}")
break # Authentication errors should not be retried
except Exception as e:
logger.warning(f"Retry {attempt}/{self.max_retries} failed due to: {str(e)}")
sleep_time = self.backoff_factor * (2 ** attempt) + random.uniform(0, 1)
logger.info(f"Waiting for {sleep_time:.2f} seconds before retrying...")
await asyncio.sleep(sleep_time)
attempt += 1

logger.error("Max retries exceeded.")
raise ServiceRequestError(message="Max retries exceeded.")