Advertisement
ethdevs

LLM Alerts

Jul 25th, 2023
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.41 KB | None | 0 0
  1. import json
  2. from utils import promptGPT
  3. import requests
  4. import os
  5. import re
  6. alert_api_key = os.getenv("ALERT_API_KEY")
  7. from coingecko_api import get_price
  8. from embeddings import get_similar_embeddings
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16. # should we break up prompt into 2 gpts? One to decide which alert, another to specify template with more targeted examples -> would the extra step cause unnecessary time/computation?
  17. system_prompt_template = """As an AI, you have the capability to create crypto alerts. There are three different types of alerts you can create: price alerts, percent price alerts, and periodic price alerts.
  18. For price alerts, a user will provide you with a coin name, price, and direction. For percent price alerts, a user will provide you with a coin name, percent, direction, and time window.
  19. For periodic price alerts, a user will provide you with a coin name and time interval. Your job is to decide which of these three alerts the user input corresponds to and fill in the JSON templates provided below.
  20. Respond with ONLY the filled JSON output.
  21.  
  22. PRICE ALERT TEMPLATE:
  23. {
  24.  "type": "price",
  25.  "currency": "{coin name}",
  26.  "target_currency": "USD",
  27.  "price": "{price}",
  28.  "channel": { "name": "webhook" },
  29.  "exchange": "Coinbase"
  30. }
  31.  
  32.    EXAMPLE INPUT: "Notify me when ETH reaches above $2000"
  33.    EXAMPLE OUTPUT:
  34.  
  35.    {
  36.        "type": "price",
  37.        "currency": "ETH",
  38.        "target_currency": "USD",
  39.        "price": "2000",
  40.        "channel": { "name": "webhook" },
  41.        "exchange": "Coinbase"
  42.    }
  43.  
  44. PERCENT PRICE ALERT TEMPLATE:
  45. {
  46.  "type": "percent_price",
  47.  "currency": "{coin name}",
  48.  "percent": "{percent}",
  49.  "direction": "up OR down",
  50.  "window": "{time window}", SYSTEM NOTE: unit of measurement in minutes
  51.  "channel": { "name": "webhook" },
  52.  "exchange": "Coinbase"
  53. }
  54.  
  55.    EXAMPLE INPUT: "Let me know when bitcoin increases by 10% in the last hour"
  56.    EXAMPLE OUTPUT:
  57.    
  58.    {
  59.        "type": "percent_price",
  60.        "currency": "BTC",
  61.        "percent": "10",
  62.        "direction": "up",
  63.        "window": "60",
  64.        "channel": { "name": "webhook" },
  65.        "exchange": "Coinbase"
  66.    }
  67.  
  68. PERIODIC PRICE ALERT TEMPLATE:
  69. {
  70.  "type": "periodic_price",
  71.  "currency": "{coin name}",
  72.  "target_currency": "USD",
  73.  "window": "{time interval}", SYSTEM NOTE: unit of measurement in minutes
  74.  "channel": { "name": "webhook" },
  75.  "exchange": "Coinbase"
  76. }
  77.  
  78.    EXAMPLE INPUT: "Give me the price of chainlink every day"
  79.    EXAMPLE OUTPUT:
  80.    
  81.    {
  82.        "type": "periodic_price",
  83.        "currency": "LINK",
  84.        "target_currency": "USD",
  85.        "window": "1440",
  86.        "channel": { "name": "webhook" },
  87.        "exchange": "Coinbase"
  88.    }
  89.  
  90.    Here are more relevant examples:
  91.    {EXAMPLES_STRING}
  92.  
  93. """
  94.  
  95. # Given the GPT response for the coin name, check if it exists in our coingecko coins list and return the corresponding symbol and id if so
  96. def get_symbol_and_id(coin_name):
  97.     with open("market-data/coin_ids.json") as json_file:
  98.         coin_ids = json.load(json_file)
  99.  
  100.         # GPT response has correct coin symbol
  101.         check_symbol = next(filter(lambda d: d.get("symbol").upper() == coin_name.upper(), coin_ids), None)
  102.         if check_symbol != None:
  103.             return check_symbol["symbol"].upper(), check_symbol["id"]
  104.        
  105.         # GPT response has correct name
  106.         check_name = next(filter(lambda d: d.get("name").upper() == coin_name.upper(), coin_ids), None)
  107.         if check_name != None:
  108.             return check_name["symbol"].upper(), check_name["id"]
  109.        
  110.         # Does not exist in list
  111.         return "",""
  112.  
  113. def get_direction(coin_id, desired_price):
  114.     current_price = get_price(coin_id)
  115.     print(current_price)
  116.     return 'above' if (current_price < desired_price) else 'below'
  117.  
  118. def alert_LLM(user_input):
  119.  
  120.     examples = get_similar_embeddings(user_input, 4, vector_dir='vectordb-alerts')
  121.     print('retreived relevant alert example embeddings. num of examples: ', len(examples))
  122.     EXAMPLES_STRING = ""
  123.     for example in examples:
  124.         EXAMPLES_STRING += example
  125.     system_prompt = system_prompt_template.replace("{EXAMPLES_STRING}", EXAMPLES_STRING)
  126.  
  127.  
  128.     llm_result = promptGPT(system_prompt, user_input)
  129.     print('alert llm result: ', llm_result)
  130.  
  131.     #general top level curly command match
  132.     command_match = re.search(r'{.*}', llm_result, re.DOTALL)
  133.     command_json_str = command_match.group(0)
  134.     json_llm_result = json.loads(command_json_str)
  135.  
  136.     coin_symbol, coin_id = get_symbol_and_id(json_llm_result["currency"])
  137.     if coin_symbol == "":
  138.         print("This coin is not supported")
  139.         return
  140.    
  141.     json_llm_result["currency"] = coin_symbol
  142.    
  143.     return_comment = None
  144.     if json_llm_result["type"] == "price":
  145.         json_llm_result["direction"] = get_direction(coin_id, int(json_llm_result["price"]))
  146.         return_comment = f'alert set for {json_llm_result["currency"]} at {json_llm_result["price"]}'
  147.     elif json_llm_result["type"] == "periodic_price":
  148.         f'alert set for {json_llm_result["currency"]} periodically every {json_llm_result["window"]} minute'
  149.     else:
  150.         return_comment = f'alert set for when {json_llm_result["currency"]} goes {json_llm_result["direction"]} {json_llm_result["percent"]} percent'
  151.     headers = {
  152.         "Content-Type": "application/json",
  153.     }
  154.     response = requests.post("https://api.cryptocurrencyalerting.com/v1/alert-conditions", auth=(alert_api_key, ""),
  155.     headers=headers, json=json_llm_result)
  156.  
  157.     print('alert status code: ', response.status_code)
  158.     print(response.json())
  159.     if response.status_code == 200:
  160.         print('returning: ', return_comment)
  161.         return_comment
  162.     else:
  163.         if response:
  164.             text_json = response.text
  165.             text = json.loads(text_json)
  166.             return f'unable to set alert at this time {text["message"]}'
  167.  
  168. def get_price(coin_id):
  169.     url = f'https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd'
  170.     headers = {'accept': 'application/json'}
  171.  
  172.     response = requests.get(url, headers=headers)
  173.  
  174.     return response.json()[coin_id]['usd']
  175.  
  176. def get_coin_ids_list():
  177.     url = "https://api.coingecko.com/api/v3/coins/list"
  178.     response = requests.get(url)
  179.  
  180. # alert_LLM("Create an alert when eth reaches $1")
  181. # alert_LLM("let me know when the price of eth hits 1901")
  182. # alert_LLM("Notify me if DOGE price falls by 10% within 30 minutes")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement