22import json
33import ast
44import re
5+ from typing import List , Dict , Any
6+
7+ import math
58
69from dotenv import load_dotenv
710from langchain_core .messages import HumanMessage , SystemMessage
1316from agents .application .prompts import Prompter
1417from agents .polymarket .polymarket import Polymarket
1518
19+ def retain_keys (data , keys_to_retain ):
20+ if isinstance (data , dict ):
21+ return {
22+ key : retain_keys (value , keys_to_retain )
23+ for key , value in data .items ()
24+ if key in keys_to_retain
25+ }
26+ elif isinstance (data , list ):
27+ return [retain_keys (item , keys_to_retain ) for item in data ]
28+ else :
29+ return data
1630
1731class Executor :
18- def __init__ (self ) -> None :
32+ def __init__ (self , default_model = 'gpt-3.5-turbo-16k' ) -> None :
1933 load_dotenv ()
34+ max_token_model = {'gpt-3.5-turbo-16k' :15000 , 'gpt-4-1106-preview' :95000 }
35+ self .token_limit = max_token_model .get (default_model )
2036 self .prompter = Prompter ()
2137 self .openai_api_key = os .getenv ("OPENAI_API_KEY" )
2238 self .llm = ChatOpenAI (
23- model = " gpt-3.5-turbo",
39+ model = default_model , # gpt-3.5-turbo"
2440 temperature = 0 ,
2541 )
2642 self .gamma = Gamma ()
@@ -43,9 +59,12 @@ def get_superforecast(
4359 result = self .llm .invoke (messages )
4460 return result .content
4561
46- def get_polymarket_llm (self , user_input : str ) -> str :
47- data1 = self .gamma .get_current_events ()
48- data2 = self .gamma .get_current_markets ()
62+
63+ def estimate_tokens (self , text : str ) -> int :
64+ # This is a rough estimate. For more accurate results, consider using a tokenizer.
65+ return len (text ) // 4 # Assuming average of 4 characters per token
66+
67+ def process_data_chunk (self , data1 : List [Dict [Any , Any ]], data2 : List [Dict [Any , Any ]], user_input : str ) -> str :
4968 system_message = SystemMessage (
5069 content = str (self .prompter .prompts_polymarket (data1 = data1 , data2 = data2 ))
5170 )
@@ -54,6 +73,55 @@ def get_polymarket_llm(self, user_input: str) -> str:
5473 result = self .llm .invoke (messages )
5574 return result .content
5675
76+
77+ def divide_list (self , original_list , i ):
78+ # Calculate the size of each sublist
79+ sublist_size = math .ceil (len (original_list ) / i )
80+
81+ # Use list comprehension to create sublists
82+ return [original_list [j :j + sublist_size ] for j in range (0 , len (original_list ), sublist_size )]
83+
84+ def get_polymarket_llm (self , user_input : str ) -> str :
85+ data1 = self .gamma .get_current_events ()
86+ data2 = self .gamma .get_current_markets ()
87+
88+ combined_data = str (self .prompter .prompts_polymarket (data1 = data1 , data2 = data2 ))
89+
90+ # Estimate total tokens
91+ total_tokens = self .estimate_tokens (combined_data )
92+
93+ # Set a token limit (adjust as needed, leaving room for system and user messages)
94+ token_limit = self .token_limit
95+ if total_tokens <= token_limit :
96+ # If within limit, process normally
97+ return self .process_data_chunk (data1 , data2 , user_input )
98+ else :
99+ # If exceeding limit, process in chunks
100+ chunk_size = len (combined_data ) // ((total_tokens // token_limit ) + 1 )
101+ print (f'total tokens { total_tokens } exceeding llm capacity, now will split and answer' )
102+ group_size = (total_tokens // token_limit ) + 1 # 3 is safe factor
103+ keys_no_meaning = ['image' ,'pagerDutyNotificationEnabled' ,'resolvedBy' ,'endDate' ,'clobTokenIds' ,'negRiskMarketID' ,'conditionId' ,'updatedAt' ,'startDate' ]
104+ useful_keys = ['id' ,'questionID' ,'description' ,'liquidity' ,'clobTokenIds' ,'outcomes' ,'outcomePrices' ,'volume' ,'startDate' ,'endDate' ,'question' ,'questionID' ,'events' ]
105+ data1 = retain_keys (data1 , useful_keys )
106+ cut_1 = self .divide_list (data1 , group_size )
107+ cut_2 = self .divide_list (data2 , group_size )
108+ cut_data_12 = zip (cut_1 , cut_2 )
109+
110+ results = []
111+
112+ for cut_data in cut_data_12 :
113+ sub_data1 = cut_data [0 ]
114+ sub_data2 = cut_data [1 ]
115+ sub_tokens = self .estimate_tokens (str (self .prompter .prompts_polymarket (data1 = sub_data1 , data2 = sub_data2 )))
116+
117+ result = self .process_data_chunk (sub_data1 , sub_data2 , user_input )
118+ results .append (result )
119+
120+ combined_result = " " .join (results )
121+
122+
123+
124+ return combined_result
57125 def filter_events (self , events : "list[SimpleEvent]" ) -> str :
58126 prompt = self .prompter .filter_events (events )
59127 result = self .llm .invoke (prompt )
0 commit comments