File size: 9,870 Bytes
5e028bf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | from openai import OpenAI
import warnings
from concurrent.futures import ThreadPoolExecutor
from typing import (
Optional,
Dict,
Any,
Callable,
List,
)
class OpenAIClient(OpenAI):
"""
A subclass of ``openai.OpenAI`` that wraps around the chat completions API to provide a simple interface
for generating text with the OpenAI language models, along with cost estimation.
This class provides functionality for interacting with OpenAI's chat models, allowing for
customized generation with options like temperature, top_p, streaming.
It also supports post-processing of the generated content and retrying the request up to a
specified tolerance level if any errors occur during the API call.
"""
def get_text_generation_output(
self,
messages: List[Dict[str, str]],
model: str = "gpt-4o",
post_processor: Optional[Callable[[str], Any]] = None,
max_tolerance: int = 3,
temperature: float = 0.75,
top_p: float = 0.95,
stream: bool = True,
**kwargs
) -> Dict[str, Any]:
"""
Generate text using the OpenAI chat completions API and return the response content,
with optional post-processing.
"""
response_content = None
counter = 0
content = ''
reasoning_content = None
while response_content is None and counter <= max_tolerance:
try:
response = self.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
top_p=top_p,
stream=stream,
**kwargs
)
if stream:
chunks = []
reasoning_chunks = []
for chunk in response:
if len(chunk.choices) > 0:
chunks.append(chunk.choices[0].delta.content or '')
if hasattr(chunk.choices[0].delta, "reasoning_content"):
reasoning_chunks.append(chunk.choices[0].delta.reasoning_content or '')
else:
warnings.warn(
"Find a chunk without `choices` attribute. "
"The model may reject to answer the question. "
"Please check the question and the model you use.",
UserWarning
)
content = ''.join(chunks)
if len(reasoning_chunks) > 0:
reasoning_content = ''.join(reasoning_chunks)
else:
content = response.choices[0].message.content
if hasattr(response.choices[0].message, "reasoning_content"):
reasoning_content = response.choices[0].message.reasoning_content
except Exception as e:
print(e)
finally:
response_content = content if post_processor is None else post_processor(content)
counter += 1
outputs = {
"content": content,
"processed_content": response_content,
}
if reasoning_content is not None:
outputs["reasoning_content"] = reasoning_content
return outputs
def openai_api_batch_inference(
clients: List[OpenAIClient],
messages_list: List[List[Dict[str, str]]],
model: str = "gpt-4o",
post_processor: Optional[Callable[[str], Any]] = None,
max_tolerance: int = 3,
temperature: float = 0.75,
top_p: float = 0.95,
stream: bool = True,
**kwargs
) -> List[Dict[str, Any]]:
"""Process multiple OpenAI API requests in parallel using thread pool."""
n_jobs = len(clients)
if len(messages_list) != n_jobs:
raise ValueError(f"The number of clients ({n_jobs}) must match the number of messages ({len(messages_list)}).")
apply_func = lambda client, messages: client.get_text_generation_output(
messages,
model,
post_processor,
max_tolerance,
temperature,
top_p,
stream,
**kwargs,
)
with ThreadPoolExecutor(max_workers=n_jobs) as executor:
futures = [
executor.submit(apply_func, clients[i], messages_list[i])
for i in range(n_jobs)
]
results = [future.result() for future in futures]
return results
class NativeLLMClient:
"""A client for native LLM inference. Powered by vLLM."""
def __init__(self, model: str, **kwargs) -> None:
from transformers import AutoTokenizer
from vllm import LLM
self.model = LLM(model=model, **kwargs)
self.tokenizer = AutoTokenizer.from_pretrained(model)
def __call__(
self,
messages_list: List[List[Dict[str, str]]],
post_processor: Optional[Callable[[str], Any]] = None,
enable_thinking: Optional[bool] = None,
**kwargs
) -> Dict[str, Any] | List[Dict[str, Any]]:
"""Generate text using the native LLM."""
if enable_thinking is not None:
texts = self.tokenizer.apply_chat_template(
messages_list,
tokenize=False,
add_generation_prompt=True,
enable_thinking=enable_thinking,
)
else:
texts = self.tokenizer.apply_chat_template(
messages_list,
tokenize=False,
# Add additional tokens to ensure the chat model
# Generate a system response instead of continuing a users message
add_generation_prompt=True,
)
if len(kwargs) > 0:
from vllm import SamplingParams
sampling_params = SamplingParams(**kwargs)
outputs = self.model.generate(texts, sampling_params)
else:
# Use default sampling params recommended by the model creator
outputs = self.model.generate(texts)
new_outputs = []
for output in outputs:
content = output.outputs[0].text
processed_content = content
if post_processor is not None:
processed_content = post_processor(content)
if isinstance(processed_content, dict):
new_outputs.append(
{
"content": content,
**processed_content,
}
)
else:
new_outputs.append(
{
"content": content,
"processed_content": processed_content,
}
)
return new_outputs if len(new_outputs) > 1 else new_outputs[0]
class OpenAIClientPool:
"""A pool of OpenAI clients for batch inference."""
def __init__(
self,
api_keys: List[str] | str,
base_urls: List[str] | str,
model: str = "gpt-4o",
**kwargs
) -> None:
"""Initialize a pool of OpenAI clients."""
if len(api_keys) != len(base_urls):
raise ValueError(
f"The number of api_key ({len(api_keys)}) must match the number of base_url ({len(base_urls)})."
)
self.client_pool = [
OpenAIClient(
api_key=api_key,
base_url=base_url,
**kwargs
)
for api_key, base_url in zip(api_keys, base_urls)
]
self.model = model
def __call__(
self,
messages_list: List[List[Dict[str, str]]],
post_processor: Optional[Callable[[str], Any]] = None,
**kwargs
) -> Dict[str, Any] | List[Dict[str, Any]]:
"""Generate text using the OpenAI clients."""
max_batch_size = len(self.client_pool)
outputs = []
for i in range(0, len(messages_list), max_batch_size):
batch_messages_list = messages_list[i: i + max_batch_size]
batch_clients = self.client_pool[0: len(batch_messages_list)]
if len(batch_clients) == 1:
client = batch_clients[0]
outputs.append(
client.get_text_generation_output(
batch_messages_list[0],
model=self.model,
post_processor=post_processor,
**kwargs
)
)
else:
outputs.extend(
openai_api_batch_inference(
batch_clients,
batch_messages_list,
model=self.model,
post_processor=post_processor,
**kwargs
)
)
return outputs if len(outputs) > 1 else outputs[0]
@property
def pool_size(self) -> int:
return len(self.client_pool)
def get_interface_for_inference(
model: str,
api_keys: Optional[List[str] | str] = None,
base_urls: Optional[List[str] | str] = None,
**kwargs
) -> OpenAIClientPool | NativeLLMClient:
"""Get an interface for inference."""
if api_keys is not None and base_urls is not None:
return OpenAIClientPool(api_keys, base_urls, model, **kwargs)
if api_keys is not None or base_urls is not None:
raise ValueError(
"Either both `api_keys` and `base_urls` must be provided, or neither."
)
interface = NativeLLMClient(model, **kwargs)
return interface |