What methods are used to parallelize (and generally speed up) calls to LLMs in the various scripts in this repository? How can these general approaches be used with OpenAI API instead of LangChain?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Based on the repository code, here are the key methods used to parallelize and optimize LLM calls:
ThreadPoolExecutor for Parallel Processing
The main parallelization approach is using Python's concurrent.futures.ThreadPoolExecutor for making concurrent API calls. This is primarily seen in run_score.py and run_feedback.py. Here's the core pattern:
python
with ThreadPoolExecutor(max_workers=num_threads) as executor:
futures = [executor.submit(threaded_request, llm_instance, prompt) for prompt in prompts]
results = []
for future in concurrent.futures.as_completed(futures):
result = future.result()
results.append(result)
Progress Tracking and Checkpointing
The code implements:
Progress bars using tqdm
Periodic saving of results at intervals
Interrupt handling to save progress on termination
Global tracking of completed requests
Optimized LLM Client
The repository uses a simplified LLM client class (LLMs in llm_oai.py) that wraps API calls with:
Configurable model parameters
Error handling
Optional greedy decoding
System message support
To adapt these approaches for direct OpenAI API usage instead of LangChain, here's how you could implement it:
python
import openai
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
class OptimizedOpenAIClient:
def __init__(self, model="gpt-4", parameters=None):
self.model = model
self.parameters = parameters or {
"temperature": 0.7,
"top_p": 0.9
}
def request(self, prompt, system_message=None):
try:
messages = []
if system_message:
messages.append({"role": "system", "content": system_message})
messages.append({"role": "user", "content": prompt})
response = openai.chat.completions.create(
model=self.model,
messages=messages,
**self.parameters
)
return response.choices[0].message.content
except Exception as e:
print(f"Error in API call: {e}")
return None
def parallel_completion(client, prompts, max_workers=200):
def process_single(prompt_data):
result = client.request(prompt=prompt_data["prompt"])
return {"id": prompt_data["id"], "result": result}
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(process_single, p) for p in prompts]
results = []
for future in tqdm(concurrent.futures.as_completed(futures),
total=len(prompts)):
results.append(future.result())
return results
Key improvements and considerations when using this approach:
Rate Limiting: Consider implementing rate limiting to stay within API limits:
python
import time
from threading import Lock
class RateLimitedOpenAIClient(OptimizedOpenAIClient):
def __init__(self, *args, requests_per_minute=3500, **kwargs):
super().__init__(*args, **kwargs)
self.lock = Lock()
self.requests = []
self.rpm = requests_per_minute
def request(self, prompt, system_message=None):
with self.lock:
current_time = time.time()
self.requests = [t for t in self.requests if current_time - t < 60]
if len(self.requests) >= self.rpm:
time.sleep(60 - (current_time - self.requests[0]))
self.requests.append(current_time)
return super().request(prompt, system_message)
Batch Processing: For large datasets, process in batches:
python
def process_in_batches(client, prompts, batch_size=1000):
results = []
for i in range(0, len(prompts), batch_size):
batch = prompts[i:i + batch_size]
batch_results = parallel_completion(client, batch)
results.extend(batch_results)
# Optional: Save checkpoint after each batch
save_checkpoint(results)
return results
Error Recovery: Implement retry logic for failed requests:
python
def request_with_retry(self, prompt, max_retries=3, delay=1):
for attempt in range(max_retries):
try:
return self.request(prompt)
except Exception as e:
if attempt == max_retries - 1:
raise e
time.sleep(delay * (attempt + 1))
These approaches can significantly improve throughput when making many API calls while maintaining reliability and staying within API limits.