gpt-batch 0.1.1__py3-none-any.whl → 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gpt_batch/__init__.py CHANGED
@@ -1,3 +1,4 @@
1
1
  from .batcher import GPTBatcher
2
2
 
3
+
3
4
  __all__ = ['GPTBatcher']
gpt_batch/batcher.py CHANGED
@@ -4,7 +4,31 @@ from functools import partial
4
4
  from tqdm import tqdm
5
5
 
6
6
  class GPTBatcher:
7
- def __init__(self, api_key, model_name="gpt-3.5-turbo-0125", system_prompt="",temperature=1,num_workers=64,timeout_duration=60,retry_attempts=2):
7
+ """
8
+ A class to handle batching and sending requests to the OpenAI GPT model efficiently.
9
+
10
+ Attributes:
11
+ client (OpenAI): The client instance to communicate with the OpenAI API using the provided API key.
12
+ model_name (str): The name of the GPT model to be used. Default is 'gpt-3.5-turbo-0125'.
13
+ system_prompt (str): Initial prompt or context to be used with the model. Default is an empty string.
14
+ temperature (float): Controls the randomness of the model's responses. Higher values lead to more diverse outputs. Default is 1.
15
+ num_workers (int): Number of worker threads used for handling concurrent requests. Default is 64.
16
+ timeout_duration (int): Maximum time (in seconds) to wait for a response from the API before timing out. Default is 60 seconds.
17
+ retry_attempts (int): Number of retries if a request fails. Default is 2.
18
+ miss_index (list): Tracks the indices of requests that failed to process correctly.
19
+
20
+ Parameters:
21
+ api_key (str): API key for authenticating requests to the OpenAI API.
22
+ model_name (str, optional): Specifies the GPT model version. Default is 'gpt-3.5-turbo-0125'.
23
+ system_prompt (str, optional): Initial text or question to seed the model with. Default is empty.
24
+ temperature (float, optional): Sets the creativity of the responses. Default is 1.
25
+ num_workers (int, optional): Number of parallel workers for request handling. Default is 64.
26
+ timeout_duration (int, optional): Timeout for API responses in seconds. Default is 60.
27
+ retry_attempts (int, optional): How many times to retry a failed request. Default is 2.
28
+ """
29
+
30
+ def __init__(self, api_key, model_name="gpt-3.5-turbo-0125", system_prompt="",temperature=1,num_workers=64,timeout_duration=60,retry_attempts=2,api_base_url=None):
31
+
8
32
  self.client = OpenAI(api_key=api_key)
9
33
  self.model_name = model_name
10
34
  self.system_prompt = system_prompt
@@ -13,6 +37,8 @@ class GPTBatcher:
13
37
  self.timeout_duration = timeout_duration
14
38
  self.retry_attempts = retry_attempts
15
39
  self.miss_index =[]
40
+ if api_base_url:
41
+ self.client.base_url = api_base_url
16
42
 
17
43
  def get_attitude(self, ask_text):
18
44
  index, ask_text = ask_text
@@ -44,7 +70,7 @@ class GPTBatcher:
44
70
  new_list.extend(future.result() for future in done if future.done())
45
71
  if len(not_done) == 0:
46
72
  break
47
- future_to_message = {executor.submit(self.get_attitude, (future_to_message[future], msg), temperature): future_to_message[future] for future, msg in not_done}
73
+ future_to_message = {executor.submit(self.get_attitude, future_to_message[future]): future_to_message[future] for future in not_done}
48
74
  executor.shutdown(wait=False)
49
75
  return new_list
50
76
 
@@ -80,6 +106,43 @@ class GPTBatcher:
80
106
  attitude_list = self.complete_attitude_list(attitude_list, max_length)
81
107
  attitude_list = [x[1] for x in attitude_list]
82
108
  return attitude_list
109
+
110
+ def process_embedding(self,message_list):
111
+ new_list = []
112
+ executor = ThreadPoolExecutor(max_workers=self.num_workers)
113
+ # Split message_list into chunks
114
+ message_chunks = list(self.chunk_list(message_list, self.num_workers))
115
+ fixed_get_embedding = partial(self.get_embedding)
116
+ for chunk in tqdm(message_chunks, desc="Processing messages"):
117
+ future_to_message = {executor.submit(fixed_get_embedding, message): message for message in chunk}
118
+ for i in range(self.retry_attempts):
119
+ done, not_done = wait(future_to_message.keys(), timeout=self.timeout_duration)
120
+ for future in not_done:
121
+ future.cancel()
122
+ new_list.extend(future.result() for future in done if future.done())
123
+ if len(not_done) == 0:
124
+ break
125
+ future_to_message = {executor.submit(fixed_get_embedding, future_to_message[future]): future_to_message[future] for future in not_done}
126
+ executor.shutdown(wait=False)
127
+ return new_list
128
+ def get_embedding(self,text):
129
+ index,text = text
130
+ response = self.client.embeddings.create(
131
+ input=text,
132
+ model=self.model_name)
133
+ return (index,response.data[0].embedding)
134
+
135
+ def handle_embedding_list(self,message_list):
136
+ indexed_list = [(index, data) for index, data in enumerate(message_list)]
137
+ max_length = len(indexed_list)
138
+ attitude_list = self.process_embedding(indexed_list)
139
+ attitude_list.sort(key=lambda x: x[0])
140
+ attitude_list = self.complete_attitude_list(attitude_list, max_length)
141
+ attitude_list = [x[1] for x in attitude_list]
142
+ return attitude_list
143
+
144
+ def get_miss_index(self):
145
+ return self.miss_index
83
146
 
84
147
  # Add other necessary methods similar to the above, refactored to fit within this class structure.
85
148
 
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.1
2
+ Name: gpt-batch
3
+ Version: 0.1.3
4
+ Summary: A package for batch processing with OpenAI API.
5
+ Home-page: https://github.com/fengsxy/gpt_batch
6
+ Author: Ted Yu
7
+ Author-email: liddlerain@gmail.com
8
+ License: UNKNOWN
9
+ Platform: UNKNOWN
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: openai
12
+ Requires-Dist: tqdm
13
+
14
+ Certainly! Here's a clean and comprehensive README for your `GPTBatcher` tool, formatted in Markdown:
15
+
16
+ ```markdown
17
+ # GPT Batcher
18
+
19
+ A simple tool to batch process messages using OpenAI's GPT models. `GPTBatcher` allows for efficient handling of multiple requests simultaneously, ensuring quick responses and robust error management.
20
+
21
+ ## Installation
22
+
23
+ To get started with `GPTBatcher`, clone this repository to your local machine. Navigate to the repository directory and install the required dependencies (if any) by running:
24
+
25
+ ```bash
26
+ pip install gpt_batch
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ To use `GPTBatcher`, you need to instantiate it with your OpenAI API key and the model name you wish to use. Here's a quick guide:
32
+
33
+ ### Handling Message Lists
34
+
35
+ This example demonstrates how to send a list of questions and receive answers:
36
+
37
+ ```python
38
+ from gpt_batch.batcher import GPTBatcher
39
+
40
+ # Initialize the batcher
41
+ batcher = GPTBatcher(api_key='your_key_here', model_name='gpt-3.5-turbo-1106')
42
+
43
+ # Send a list of messages and receive answers
44
+ result = batcher.handle_message_list(['question_1', 'question_2', 'question_3', 'question_4'])
45
+ print(result)
46
+ # Expected output: ["answer_1", "answer_2", "answer_3", "answer_4"]
47
+ ```
48
+
49
+ ### Handling Embedding Lists
50
+
51
+ This example shows how to get embeddings for a list of strings:
52
+
53
+ ```python
54
+ from gpt_batch.batcher import GPTBatcher
55
+
56
+ # Reinitialize the batcher for embeddings
57
+ batcher = GPTBatcher(api_key='your_key_here', model_name='text-embedding-3-small')
58
+
59
+ # Send a list of strings and get their embeddings
60
+ result = batcher.handle_embedding_list(['question_1', 'question_2', 'question_3', 'question_4'])
61
+ print(result)
62
+ # Expected output: ["embedding_1", "embedding_2", "embedding_3", "embedding_4"]
63
+ ```
64
+
65
+ ## Configuration
66
+
67
+ The `GPTBatcher` class can be customized with several parameters to adjust its performance and behavior:
68
+
69
+ - **api_key** (str): Your OpenAI API key.
70
+ - **model_name** (str): Identifier for the GPT model version you want to use, default is 'gpt-3.5-turbo-1106'.
71
+ - **system_prompt** (str): Initial text or question to seed the model, default is empty.
72
+ - **temperature** (float): Adjusts the creativity of the responses, default is 1.
73
+ - **num_workers** (int): Number of parallel workers for request handling, default is 64.
74
+ - **timeout_duration** (int): Timeout for API responses in seconds, default is 60.
75
+ - **retry_attempts** (int): How many times to retry a failed request, default is 2.
76
+ - **miss_index** (list): Tracks indices of requests that failed to process correctly.
77
+
78
+ For more detailed documentation on the parameters and methods, refer to the class docstring.
79
+
80
+
@@ -0,0 +1,8 @@
1
+ gpt_batch/__init__.py,sha256=zGDItktTxKLSQr44GY78dl5LKsSJig0Q59dzusqhU0U,59
2
+ gpt_batch/batcher.py,sha256=DeW9xmD2FIRryLXOKnvfMfDYitW1U3WOfew9A6ljD7A,7258
3
+ tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ tests/test_batcher.py,sha256=N88RZrSuBaDti6Lry7xipyGXHn3jKg85O12mjcHHZA0,3006
5
+ gpt_batch-0.1.3.dist-info/METADATA,sha256=cEtCNyQJVBk1TzFz7x8lcrL2Ih8zyM0Cm8eEI8KOrQo,2932
6
+ gpt_batch-0.1.3.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
7
+ gpt_batch-0.1.3.dist-info/top_level.txt,sha256=FtvJB_L9W_S6jL4G8Em_YWphG1wdKAF20BHUrf4B0yM,16
8
+ gpt_batch-0.1.3.dist-info/RECORD,,
tests/test_batcher.py CHANGED
@@ -18,6 +18,38 @@ def test_handle_message_list():
18
18
  assert len(results) == 2, "There should be two results, one for each message"
19
19
  assert all(len(result) >= 2 for result in results), "Each result should be at least two elements"
20
20
 
21
+ def test_handle_embedding_list():
22
+ # Initialize the GPTBatcher with hypothetical valid credentials
23
+ #api_key = #get from system environment
24
+ api_key = os.getenv('TEST_KEY')
25
+ if not api_key:
26
+ raise ValueError("API key must be set in the environment variables")
27
+ batcher = GPTBatcher(api_key=api_key, model_name='text-embedding-3-small')
28
+ embedding_list = [ "I think privacy is important", "I don't think privacy is important"]
29
+ results = batcher.handle_embedding_list(embedding_list)
30
+ assert len(results) == 2, "There should be two results, one for each message"
31
+ assert all(len(result) >= 2 for result in results), "Each result should be at least two elements"
32
+
33
+ def test_base_url():
34
+ # Initialize the GPTBatcher with hypothetical valid credentials
35
+ #api_key = #get from system environment
36
+ api_key = os.getenv('TEST_KEY')
37
+ if not api_key:
38
+ raise ValueError("API key must be set in the environment variables")
39
+ batcher = GPTBatcher(api_key=api_key, model_name='gpt-3.5-turbo-1106', api_base_url="https://api.openai.com/v2/")
40
+ assert batcher.client.base_url == "https://api.openai.com/v2/", "The base URL should be set to the provided value"
41
+
42
+ def test_get_miss_index():
43
+ # Initialize the GPTBatcher with hypothetical valid credentials
44
+ #api_key = #get from system environment
45
+ api_key = os.getenv('TEST_KEY')
46
+ if not api_key:
47
+ raise ValueError("API key must be set in the environment variables")
48
+ batcher = GPTBatcher(api_key=api_key, model_name='gpt-3.5-turbo-1106', system_prompt="Your task is to discuss privacy questions and provide persuasive answers with supporting reasons.")
49
+ message_list = ["I think privacy is important", "I don't think privacy is important"]
50
+ results = batcher.handle_message_list(message_list)
51
+ miss_index = batcher.get_miss_index()
52
+ assert miss_index == [], "The miss index should be empty"
21
53
  # Optionally, you can add a test configuration if you have specific needs
22
54
  if __name__ == "__main__":
23
55
  pytest.main()
@@ -1,34 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: gpt-batch
3
- Version: 0.1.1
4
- Summary: A package for batch processing with OpenAI API.
5
- Home-page: https://github.com/fengsxy/gpt_batch
6
- Author: Ted Yu
7
- Author-email: liddlerain@gmail.com
8
- License: UNKNOWN
9
- Platform: UNKNOWN
10
- Description-Content-Type: text/markdown
11
- Requires-Dist: openai
12
- Requires-Dist: tqdm
13
-
14
- # GPT Batcher
15
-
16
- A simple tool to batch process messages using OpenAI's GPT models.
17
-
18
- ## Installation
19
-
20
- Clone this repository and run:
21
-
22
- ## Usage
23
-
24
- Here's how to use the `GPTBatcher`:
25
-
26
- ```python
27
- from gpt_batch.batcher import GPTBatcher
28
-
29
- batcher = GPTBatcher(api_key='your_key_here', model_name='gpt-3.5-turbo-1106')
30
- result = batcher.handle_message_list(['your', 'list', 'of', 'messages'])
31
- print(result)
32
-
33
-
34
-
@@ -1,8 +0,0 @@
1
- gpt_batch/__init__.py,sha256=pZBlF0_7ozJAJGXnExIRNVwqgbDbHHh5COkwI92fGNg,58
2
- gpt_batch/batcher.py,sha256=S7Ni6gOswHoUD-wWarcn_WaTdLLNBeljuToEWnHeO_Y,3635
3
- tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- tests/test_batcher.py,sha256=bYkrDQxc2uUn4BjueXSH0eqPwFvyupjId-SSKeQDI5k,1094
5
- gpt_batch-0.1.1.dist-info/METADATA,sha256=sPfe12nV1TatDlT1e10q5UzFemCOT88wopN3il6JZ98,726
6
- gpt_batch-0.1.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
7
- gpt_batch-0.1.1.dist-info/top_level.txt,sha256=FtvJB_L9W_S6jL4G8Em_YWphG1wdKAF20BHUrf4B0yM,16
8
- gpt_batch-0.1.1.dist-info/RECORD,,