from distbot.common.config import conf_get
from distbot.common.message import get_nick_from_message, get_words
from distbot.common.utils import giphy
+from distbot.plugins.openai import ask_chatgpt, get_openai_session
logger = logging.getLogger(__name__)
def parse_body(self, msg):
sender = get_nick_from_message(msg)
- if sender in conf_get("meanies"):
+
+ try:
+ api_key = conf_get("openai_api_key")
+ session = get_openai_session(api_key)
+ response = ask_chatgpt(msg["body"], session)
+ return Action(msg='{}: {}'.format(sender, response))
+ except:
+ pass
+
+ meanies = conf_get("meanies") or []
+ if sender in meanies:
replys = self.insults
else:
replys = self.me_replies
--- /dev/null
+import requests
+import hashlib
+import os
+import json
+
+
+API_URL = "https://api.openai.com/v1/chat/completions"
+
+
+def get_openai_session(api_key=None):
+ session = requests.session()
+ if not api_key:
+ api_key = os.environ.get("OPENAI_API_KEY")
+ if not api_key:
+ raise RuntimeError("no OPENAI_API_KEY set")
+ session.headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
+ return session
+
+def hash_user(username):
+ username = username or "anonymous"
+ hashed_val = hashlib.sha256()
+ hashed_val.update(username.encode("utf-8"))
+ return hashed_val.hexdigest()
+
+
+def ask_chatgpt(line, session=None, sender=None):
+ session = session if session else get_openai_session()
+ req = {
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "system", "content": "You are a sassy little chat bot with low intent to help, but to humor. Your name is urlbug. Respond in the language being talked to. Avoid multiple lines in your response."},
+ {"role": "user", "content": line}
+ ],
+ "max_api_keys": 150,
+ "user": hash_user(sender)
+ }
+ resp = session.post(API_URL, json=req)
+ resp.raise_for_status()
+ response = resp.json()
+ cost = response["usage"]["total_tokens"]
+ # TODO dump cost somewhere
+ print(json.dumps(response, indent=2))
+ message = response["choices"][0]
+ stop_reason = message["finish_reason"]
+ if stop_reason == "content_filter":
+ print("warning: redacted, you're getting on the naughty list soon.")
+ return message["message"]["content"]
+
+
+def main():
+ line = "/me glaubt, urlbug hat wieder zuviel Maschinenöl geschnüffelt"
+ print(ask_in_chat(line))
+
+
+if __name__ == "__main__":
+ main()
+