Created
April 29, 2022 06:27
-
-
Save rtindru/e452cad67dadfa837fa69a11aa30e90c to your computer and use it in GitHub Desktop.
Step 4: Handle errors with sentry
This file contains 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
%%writefile sentiment_analysis_service.py | |
# Now let's modify our service to use sentry | |
import bentoml | |
from bentoml.frameworks.sklearn import SklearnModelArtifact | |
from bentoml.service.artifacts.common import PickleArtifact | |
from bentoml.adapters import JsonInput | |
# Edit 1: Import sentry | |
import sentry_sdk | |
import logging | |
from sentry_sdk.integrations.logging import LoggingIntegration | |
# All of this is already happening by default! | |
sentry_logging = LoggingIntegration( | |
level=logging.INFO, # Capture info and above as breadcrumbs | |
event_level=logging.ERROR # Send errors as events | |
) | |
sentry_sdk.init( | |
dsn="https://your_dsn_goes_here.ingest.sentry.io/023049204", | |
integrations=[sentry_logging] | |
) | |
@bentoml.artifacts([PickleArtifact('model')]) | |
@bentoml.env(infer_pip_packages=True) | |
class SKSentimentAnalysis(bentoml.BentoService): | |
sentiment_names = { | |
0: "very negative", | |
1: "somewhat negative", | |
2: "neutral", | |
3: "somewhat positive", | |
4: "very positive", | |
} | |
@bentoml.api(input=JsonInput()) | |
@bentoml.env(pip_packages=["scikit-learn", "pandas", "sentry-sdk==1.5.4"]) | |
def predict(self, parsed_json): | |
""" | |
Sentiment prediction API service | |
Expected input format: | |
{"tweet": "Tweet text to predict the sentiment..."} | |
Output format: | |
{"sentiment_score": 4, "sentiment": "Very Positive", "tweet": "Tweet text to predict the sentiment..."} | |
""" | |
# Edit 3: Update the code to capture exceptions to sentry | |
try: | |
texts = parsed_json | |
predictions = self.artifacts.model.predict(texts) | |
res = [] | |
for idx, pred in enumerate(predictions): | |
# Edit 4: make a deliberate mistake | |
1/ 0 # raise a ZeroDivisionError | |
res.append({ | |
"sentiment_score": pred, | |
"sentiment": self.sentiment_names[pred], | |
"text": texts[idx] | |
}) | |
return res | |
except: | |
sentry_sdk.capture_exception() | |
return "error" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment