|
| 1 | +# https://github.com/s2t2/openai-embeddings-2023/blob/main/notebooks/1_botometer_users_sample_and_openai_embeddings_20230704.py |
| 2 | + |
| 3 | +import os |
| 4 | +from time import sleep |
| 5 | +from pprint import pprint |
| 6 | +import json |
| 7 | + |
| 8 | +import openai |
| 9 | +from openai import Model, Embedding |
| 10 | +from pandas import DataFrame |
| 11 | +from dotenv import load_dotenv |
| 12 | + |
| 13 | + |
| 14 | +load_dotenv() |
| 15 | + |
| 16 | +OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") |
| 17 | +MODEL_ID = os.getenv("OPENAI_EMBEDDING_MODEL_ID", default="text-embedding-ada-002") |
| 18 | + |
| 19 | +openai.api_key = OPENAI_API_KEY |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +def split_into_batches(my_list, batch_size=10_000): |
| 24 | + """Splits a list into evenly sized batches""" |
| 25 | + # h/t: https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks |
| 26 | + for i in range(0, len(my_list), batch_size): |
| 27 | + yield my_list[i : i + batch_size] |
| 28 | + |
| 29 | +def dynamic_batches(texts, batch_char_limit=30_000): |
| 30 | + """Splits texts into batches, with specified max number of characters per batch. |
| 31 | + Caps text length at the maximum batch size (individual text cannot exceed batch size). |
| 32 | + Batches may have different lengths. |
| 33 | + """ |
| 34 | + batches = [] |
| 35 | + |
| 36 | + batch = [] |
| 37 | + batch_chars = 0 |
| 38 | + for text in texts: |
| 39 | + text_chars = len(text) |
| 40 | + |
| 41 | + if (batch_chars + text_chars) <= batch_char_limit: |
| 42 | + # THERE IS ROOM TO ADD THIS TEXT TO THE BATCH |
| 43 | + batch.append(text) |
| 44 | + batch_chars += text_chars |
| 45 | + else: |
| 46 | + # NO ROOM IN THIS BATCH, START A NEW ONE: |
| 47 | + |
| 48 | + if text_chars > batch_char_limit: |
| 49 | + # CAP THE TEXT AT THE MAX BATCH LENGTH |
| 50 | + text = text[0:batch_char_limit-1] |
| 51 | + |
| 52 | + batches.append(batch) |
| 53 | + batch = [text] |
| 54 | + batch_chars = text_chars |
| 55 | + |
| 56 | + if batch: |
| 57 | + batches.append(batch) |
| 58 | + |
| 59 | + return batches |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | +class OpenAIService(): |
| 64 | + """OpenAI API Service |
| 65 | +
|
| 66 | + + https://github.com/openai/openai-python |
| 67 | + + https://platform.openai.com/account/api-keys |
| 68 | + + https://platform.openai.com/docs/introduction/key-concepts |
| 69 | + + https://platform.openai.com/docs/models/overview |
| 70 | + + https://platform.openai.com/docs/guides/embeddings/what-are-embeddings |
| 71 | + + https://platform.openai.com/docs/guides/embeddings/embedding-models |
| 72 | +
|
| 73 | + > We recommend using `text-embedding-ada-002` for nearly all |
| 74 | + (Embedding) use cases. It's better, cheaper, and simpler to use. |
| 75 | + """ |
| 76 | + |
| 77 | + def __init__(self, model_id=MODEL_ID): |
| 78 | + self.model_id = model_id |
| 79 | + print("EMBEDDING MODEL:", self.model_id) |
| 80 | + |
| 81 | + |
| 82 | + def get_models(self): |
| 83 | + models = Model.list() |
| 84 | + #print(type(models)) #> openai.openai_object.OpenAIObject |
| 85 | + |
| 86 | + records = [] |
| 87 | + for model in sorted(models.data, key=lambda m: m.id): |
| 88 | + #print(model.id, "...", model.owned_by, "...", model.parent, "...", model.object) |
| 89 | + model_info = model.to_dict() |
| 90 | + del model_info["permission"] # nested list |
| 91 | + #print(model_info) |
| 92 | + records.append(model_info) |
| 93 | + |
| 94 | + models_df = DataFrame(records) |
| 95 | + #models_df.to_csv("openai_models.csv") |
| 96 | + #models_df.sort_values(by=["id"]) |
| 97 | + return models_df |
| 98 | + |
| 99 | + def get_embeddings(self, texts): |
| 100 | + """Pass in a list of strings. Returns a list of embeddings for each.""" |
| 101 | + result = Embedding.create(input=texts, model=self.model_id) # API CALL |
| 102 | + #print(len(result["data"])) |
| 103 | + return [d["embedding"] for d in result["data"]] |
| 104 | + |
| 105 | + def get_embeddings_in_batches(self, texts, batch_size=250, sleep_seconds=60): |
| 106 | + """High level wrapper to work around RateLimitError: |
| 107 | + Rate limit reached for [MODEL] in [ORG] on tokens per min. |
| 108 | + Limit: 1_000_000 tokens / min. |
| 109 | +
|
| 110 | + batch_size : Number of users to request per API call |
| 111 | +
|
| 112 | + sleep : Wait for a minute before requesting the next batch |
| 113 | +
|
| 114 | + Also beware InvalidRequestError: |
| 115 | + This model's maximum context length is 8191 tokens, |
| 116 | + however you requested X tokens (X in your prompt; 0 for the completion). |
| 117 | + Please reduce your prompt; or completion length. |
| 118 | +
|
| 119 | + ... so we should make lots of smaller requests. |
| 120 | + """ |
| 121 | + #embeddings = [] |
| 122 | + #counter = 1 |
| 123 | + #for texts_batch in split_into_batches(texts, batch_size=batch_size): |
| 124 | + # print(counter, len(texts_batch)) |
| 125 | + # embeds_batch = self.get_embeddings(texts_batch) # API CALL |
| 126 | + # embeddings += embeds_batch |
| 127 | + # counter += 1 |
| 128 | + # sleep(sleep_seconds) |
| 129 | + #return embeddings |
| 130 | + |
| 131 | + #embeddings = [] |
| 132 | + #counter = 1 |
| 133 | + #for texts_batch in split_into_batches(texts, batch_size=batch_size): |
| 134 | + # print(counter, len(texts_batch)) |
| 135 | + # try: |
| 136 | + # embeds_batch = self.get_embeddings(texts_batch) # API CALL |
| 137 | + # embeddings += embeds_batch |
| 138 | + # except openai.error.RateLimitError as err: |
| 139 | + # print(f"Rate limit reached. Sleeping for {sleep_seconds} seconds.") |
| 140 | + # sleep(sleep_seconds) |
| 141 | + # continue |
| 142 | + # counter += 1 |
| 143 | + #return embeddings |
| 144 | + |
| 145 | + embeddings = [] |
| 146 | + counter = 1 |
| 147 | + for texts_batch in split_into_batches(texts, batch_size=batch_size): |
| 148 | + print(counter, len(texts_batch)) |
| 149 | + # retry loop |
| 150 | + while True: |
| 151 | + try: |
| 152 | + embeds_batch = self.get_embeddings(texts_batch) # API CALL |
| 153 | + embeddings += embeds_batch |
| 154 | + break # exit the retry loop and go to the next batch |
| 155 | + except openai.error.RateLimitError as err: |
| 156 | + print(f"... Rate limit reached. Sleeping for {sleep_seconds} seconds.") |
| 157 | + sleep(sleep_seconds) |
| 158 | + # retry the same batch |
| 159 | + #except openai.error.InvalidRequestError as err: |
| 160 | + # print("INVALID REQUEST", err) |
| 161 | + counter += 1 |
| 162 | + return embeddings |
| 163 | + |
| 164 | + def get_embeddings_in_dynamic_batches(self, texts, batch_char_limit=30_000, sleep_seconds=60): |
| 165 | + """High level wrapper to work around API limitations |
| 166 | +
|
| 167 | + RateLimitError: |
| 168 | + Rate limit reached for [MODEL] in [ORG] on tokens per min. |
| 169 | + Limit: 1_000_000 tokens / min. |
| 170 | +
|
| 171 | + AND |
| 172 | +
|
| 173 | + InvalidRequestError: |
| 174 | + This model's maximum context length is 8191 tokens, |
| 175 | + however you requested X tokens (X in your prompt; 0 for the completion). |
| 176 | + Please reduce your prompt; or completion length. |
| 177 | +
|
| 178 | + Params: |
| 179 | +
|
| 180 | + batch_char_limit : Number of max characters to request per API call. |
| 181 | + Should be less than around 32_000 based on API docs. |
| 182 | +
|
| 183 | + sleep : Wait for a minute before requesting the next batch |
| 184 | +
|
| 185 | + """ |
| 186 | + embeddings = [] |
| 187 | + counter = 1 |
| 188 | + for texts_batch in dynamic_batches(texts, batch_char_limit=batch_char_limit): |
| 189 | + print(counter, len(texts_batch)) |
| 190 | + # retry loop |
| 191 | + while True: |
| 192 | + try: |
| 193 | + embeds_batch = self.get_embeddings(texts_batch) # API CALL |
| 194 | + embeddings += embeds_batch |
| 195 | + break # exit the retry loop and go to the next batch |
| 196 | + except openai.error.RateLimitError as err: |
| 197 | + print(f"... Rate limit reached. Sleeping for {sleep_seconds} seconds.") |
| 198 | + sleep(sleep_seconds) |
| 199 | + # retry the same batch |
| 200 | + counter += 1 |
| 201 | + return embeddings |
| 202 | + |
| 203 | + |
| 204 | + |
| 205 | + |
| 206 | + |
| 207 | + |
| 208 | + |
| 209 | + |
| 210 | +if __name__ == "__main__": |
| 211 | + |
| 212 | + from app import DATA_DIRPATH |
| 213 | + |
| 214 | + print("-----------------") |
| 215 | + print("TEXTS:") |
| 216 | + texts = [ |
| 217 | + "Short and sweet", |
| 218 | + "Short short", |
| 219 | + "I like apples, but bananas are gross.", |
| 220 | + "This is a tweet about bananas", |
| 221 | + "Drink apple juice!", |
| 222 | + ] |
| 223 | + pprint(texts) |
| 224 | + |
| 225 | + #print("-----------------") |
| 226 | + #print("BATCHES:") |
| 227 | + #batches = list(split_into_batches(texts, batch_size=2)) |
| 228 | + #pprint(batches) |
| 229 | + |
| 230 | + #print("-----------------") |
| 231 | + #print("DYNAMIC BATCHES:") |
| 232 | + #batches = dynamic_batches(texts, batch_char_limit=30) |
| 233 | + #pprint(batches) |
| 234 | + |
| 235 | + print("-----------------") |
| 236 | + print("EMBEDDINGS:") |
| 237 | + |
| 238 | + ai = OpenAIService() |
| 239 | + |
| 240 | + embeddings = ai.get_embeddings(texts) |
| 241 | + #embeddings = ai.get_embeddings_in_dynamic_batches(texts, batch_char_limit=15_000) |
| 242 | + #print(type(embeddings), len(embeddings)) |
| 243 | + #print(len(embeddings[0])) #> 1536 |
| 244 | + |
| 245 | + df = DataFrame({"text": texts, "openai_embeddings": embeddings}) |
| 246 | + print(df) |
| 247 | + |
| 248 | + print("-----------------") |
| 249 | + # UNpacK EMBEdDINGS tO THEIR OWN COLUMNS |
| 250 | + embeds_df = DataFrame(df["openai_embeddings"].values.tolist()) |
| 251 | + embeds_df.columns = [str(i) for i in range(0, len(embeds_df.columns))] |
| 252 | + embeds_df = df.drop(columns=["openai_embeddings"]).merge(embeds_df, left_index=True, right_index=True) |
| 253 | + print(embeds_df) |
| 254 | + |
| 255 | + print("-----------------") |
| 256 | + print("SAVING...") |
| 257 | + |
| 258 | + model_dirpath = os.path.join(DATA_DIRPATH, ai.model_id) |
| 259 | + os.makedirs(model_dirpath, exist_ok=True) |
| 260 | + |
| 261 | + embeddings_csv_filepath = os.path.join(model_dirpath, "example_openai_embeddings.csv") |
| 262 | + #embeddings_json_filepath = os.path.join(model_dirpath, "example_openai_embeddings.json") |
| 263 | + |
| 264 | + embeds_df.to_csv(embeddings_csv_filepath) |
| 265 | + #df.to_json(embeddings_json_filepath) |
0 commit comments