Skip to content

Commit

Permalink
Merge pull request #15 from UpMortem/retry_network_calls
Browse files Browse the repository at this point in the history
Added network retry lib util function
  • Loading branch information
joelbandi authored Feb 10, 2023
2 parents 95b6a2a + 9c5680f commit 342a92d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
13 changes: 13 additions & 0 deletions src/lib/retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import time

def retry(func, retries=3, delay=1, exceptions=(Exception,)):
while retries > 0:
try:
return func()
break
except exceptions as e:
retries -= 1
if retries == 0:
raise e
print(f"Failed, retrying... ({retries} attempts remaining)")
time.sleep(delay)
5 changes: 3 additions & 2 deletions src/services/openai_service.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import openai
import os
from lib.retry import retry

openai.api_key = os.environ["OPENAI_API_KEY"]

base_prompt = "You are a Slack bot named Haly. You are having a conversation with a user.\n\n"

def run_completion(text):
completion = openai.Completion.create(
completion = retry(lambda: openai.Completion.create(
model="text-davinci-003", prompt=text, max_tokens=1000, temperature=0.7
)
))
return completion.choices[0].text

def respond_to_user(text):
Expand Down
12 changes: 6 additions & 6 deletions src/services/slack_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@
import time
import os
from services.openai_service import respond_to_user
from lib.retry import retry

# grabs the credentials from .env directly
slack_app = App()
users_map = {}

def send_message(channel: str, thread_ts: str, text: str):
try:
slack_app.client.chat_postMessage(
retry(lambda: slack_app.client.chat_postMessage(
token=os.environ["SLACK_BOT_TOKEN"],
channel=channel,
text=text,
thread_ts=thread_ts,
)
))
except Exception as e:
print(e)


def get_thread_messages(channel: str, thread_ts: str):
try:
result = slack_app.client.conversations_replies(
return retry(lambda: slack_app.client.conversations_replies(
token=os.environ["SLACK_BOT_TOKEN"],
channel=channel,
ts=thread_ts,
include_all_metadata=True,
)
return result["messages"]
)["messages"])
except Exception as e:
print(e)

Expand All @@ -45,7 +45,7 @@ def get_thread_messages_with_usernames(channel: str, thread_ts: str, bot_id: str

def find_user_by_id(user_id: str):
try:
return slack_app.client.users_info(user=user_id)
return retry(lambda: slack_app.client.users_info(user=user_id))
except Exception as e:
print(e)

Expand Down

0 comments on commit 342a92d

Please sign in to comment.