Spaces:
Running
Running
File size: 35,355 Bytes
e679d69 |
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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 |
import asyncio
import json
import os
import time
import traceback
import warnings
from concurrent.futures import ThreadPoolExecutor
from logging import getLogger
from threading import Lock
from typing import AsyncGenerator, Dict, List, Optional, Union
import aiohttp
import requests
from ..schema import ModelStatusCode
from ..utils import filter_suffix
from .base_api import AsyncBaseAPILLM, BaseAPILLM
warnings.simplefilter('default')
OPENAI_API_BASE = 'https://api.openai.com/v1/chat/completions'
class GPTAPI(BaseAPILLM):
"""Model wrapper around OpenAI's models.
Args:
model_type (str): The name of OpenAI's model.
retry (int): Number of retires if the API call fails. Defaults to 2.
key (str or List[str]): OpenAI key(s). In particular, when it
is set to "ENV", the key will be fetched from the environment
variable $OPENAI_API_KEY, as how openai defaults to be. If it's a
list, the keys will be used in round-robin manner. Defaults to
'ENV'.
org (str or List[str], optional): OpenAI organization(s). If not
specified, OpenAI uses the default organization bound to each API
key. If specified, the orgs will be posted with each request in
round-robin manner. Defaults to None.
meta_template (Dict, optional): The model's meta prompt
template if needed, in case the requirement of injecting or
wrapping of any meta instructions.
api_base (str): The base url of OpenAI's API. Defaults to
'https://api.openai.com/v1/chat/completions'.
gen_params: Default generation configuration which could be overridden
on the fly of generation.
"""
is_api: bool = True
def __init__(self,
model_type: str = 'gpt-3.5-turbo',
retry: int = 2,
json_mode: bool = False,
key: Union[str, List[str]] = 'ENV',
org: Optional[Union[str, List[str]]] = None,
meta_template: Optional[Dict] = [
dict(role='system', api_role='system'),
dict(role='user', api_role='user'),
dict(role='assistant', api_role='assistant'),
dict(role='environment', api_role='system')
],
api_base: str = OPENAI_API_BASE,
proxies: Optional[Dict] = None,
**gen_params):
if 'top_k' in gen_params:
warnings.warn('`top_k` parameter is deprecated in OpenAI APIs.',
DeprecationWarning)
gen_params.pop('top_k')
super().__init__(
model_type=model_type,
meta_template=meta_template,
retry=retry,
**gen_params)
self.gen_params.pop('top_k')
self.logger = getLogger(__name__)
if isinstance(key, str):
self.keys = [os.getenv('OPENAI_API_KEY') if key == 'ENV' else key]
else:
self.keys = key
# record invalid keys and skip them when requesting API
# - keys have insufficient_quota
self.invalid_keys = set()
self.key_ctr = 0
if isinstance(org, str):
self.orgs = [org]
else:
self.orgs = org
self.org_ctr = 0
self.url = api_base
self.model_type = model_type
self.proxies = proxies
self.json_mode = json_mode
def chat(
self,
inputs: Union[List[dict], List[List[dict]]],
**gen_params,
) -> Union[str, List[str]]:
"""Generate responses given the contexts.
Args:
inputs (Union[List[dict], List[List[dict]]]): a list of messages
or list of lists of messages
gen_params: additional generation configuration
Returns:
Union[str, List[str]]: generated string(s)
"""
assert isinstance(inputs, list)
if 'max_tokens' in gen_params:
raise NotImplementedError('unsupported parameter: max_tokens')
gen_params = {**self.gen_params, **gen_params}
with ThreadPoolExecutor(max_workers=20) as executor:
tasks = [
executor.submit(self._chat,
self.template_parser._prompt2api(messages),
**gen_params)
for messages in (
[inputs] if isinstance(inputs[0], dict) else inputs)
]
ret = [task.result() for task in tasks]
return ret[0] if isinstance(inputs[0], dict) else ret
def stream_chat(
self,
inputs: List[dict],
**gen_params,
):
"""Generate responses given the contexts.
Args:
inputs (List[dict]): a list of messages
gen_params: additional generation configuration
Returns:
str: generated string
"""
assert isinstance(inputs, list)
if 'max_tokens' in gen_params:
raise NotImplementedError('unsupported parameter: max_tokens')
gen_params = self.update_gen_params(**gen_params)
gen_params['stream'] = True
resp = ''
finished = False
stop_words = gen_params.get('stop_words')
if stop_words is None:
stop_words = []
# mapping to role that openai supports
messages = self.template_parser._prompt2api(inputs)
for text in self._stream_chat(messages, **gen_params):
if self.model_type.lower().startswith('qwen'):
resp = text
else:
resp += text
if not resp:
continue
# remove stop_words
for sw in stop_words:
if sw in resp:
resp = filter_suffix(resp, stop_words)
finished = True
break
yield ModelStatusCode.STREAM_ING, resp, None
if finished:
break
yield ModelStatusCode.END, resp, None
def _chat(self, messages: List[dict], **gen_params) -> str:
"""Generate completion from a list of templates.
Args:
messages (List[dict]): a list of prompt dictionaries
gen_params: additional generation configuration
Returns:
str: The generated string.
"""
assert isinstance(messages, list)
header, data = self.generate_request_data(
model_type=self.model_type,
messages=messages,
gen_params=gen_params,
json_mode=self.json_mode)
max_num_retries, errmsg = 0, ''
while max_num_retries < self.retry:
with Lock():
if len(self.invalid_keys) == len(self.keys):
raise RuntimeError('All keys have insufficient quota.')
# find the next valid key
while True:
self.key_ctr += 1
if self.key_ctr == len(self.keys):
self.key_ctr = 0
if self.keys[self.key_ctr] not in self.invalid_keys:
break
key = self.keys[self.key_ctr]
header['Authorization'] = f'Bearer {key}'
if self.orgs:
with Lock():
self.org_ctr += 1
if self.org_ctr == len(self.orgs):
self.org_ctr = 0
header['OpenAI-Organization'] = self.orgs[self.org_ctr]
response = dict()
try:
raw_response = requests.post(
self.url,
headers=header,
data=json.dumps(data),
proxies=self.proxies)
response = raw_response.json()
return response['choices'][0]['message']['content'].strip()
except requests.ConnectionError:
errmsg = 'Got connection error ' + str(traceback.format_exc())
self.logger.error(errmsg)
continue
except requests.JSONDecodeError:
errmsg = 'JsonDecode error, got ' + str(raw_response.content)
self.logger.error(errmsg)
continue
except KeyError:
if 'error' in response:
if response['error']['code'] == 'rate_limit_exceeded':
time.sleep(1)
continue
elif response['error']['code'] == 'insufficient_quota':
self.invalid_keys.add(key)
self.logger.warn(f'insufficient_quota key: {key}')
continue
errmsg = 'Find error message in response: ' + str(
response['error'])
self.logger.error(errmsg)
except Exception as error:
errmsg = str(error) + '\n' + str(traceback.format_exc())
self.logger.error(errmsg)
max_num_retries += 1
raise RuntimeError('Calling OpenAI failed after retrying for '
f'{max_num_retries} times. Check the logs for '
f'details. errmsg: {errmsg}')
def _stream_chat(self, messages: List[dict], **gen_params) -> str:
"""Generate completion from a list of templates.
Args:
messages (List[dict]): a list of prompt dictionaries
gen_params: additional generation configuration
Returns:
str: The generated string.
"""
def streaming(raw_response):
for chunk in raw_response.iter_lines(
chunk_size=8192, decode_unicode=False, delimiter=b'\n'):
if chunk:
decoded = chunk.decode('utf-8')
if decoded.startswith('data: [DONE]'):
return
if decoded[:5] == 'data:':
decoded = decoded[5:]
if decoded[0] == ' ':
decoded = decoded[1:]
else:
print(decoded)
continue
try:
response = json.loads(decoded)
if 'code' in response and response['code'] == -20003:
# Context exceeds maximum length
yield ''
return
if self.model_type.lower().startswith('qwen'):
choice = response['output']['choices'][0]
yield choice['message']['content']
if choice['finish_reason'] == 'stop':
return
else:
choice = response['choices'][0]
if choice['finish_reason'] == 'stop':
return
yield choice['delta'].get('content', '')
except Exception as exc:
msg = f'response {decoded} lead to exception of {str(exc)}'
self.logger.error(msg)
raise Exception(msg) from exc
assert isinstance(messages, list)
header, data = self.generate_request_data(
model_type=self.model_type,
messages=messages,
gen_params=gen_params,
json_mode=self.json_mode)
max_num_retries, errmsg = 0, ''
while max_num_retries < self.retry:
if len(self.invalid_keys) == len(self.keys):
raise RuntimeError('All keys have insufficient quota.')
# find the next valid key
while True:
self.key_ctr += 1
if self.key_ctr == len(self.keys):
self.key_ctr = 0
if self.keys[self.key_ctr] not in self.invalid_keys:
break
key = self.keys[self.key_ctr]
header['Authorization'] = f'Bearer {key}'
if self.orgs:
self.org_ctr += 1
if self.org_ctr == len(self.orgs):
self.org_ctr = 0
header['OpenAI-Organization'] = self.orgs[self.org_ctr]
response = dict()
try:
raw_response = requests.post(
self.url,
headers=header,
data=json.dumps(data),
proxies=self.proxies)
return streaming(raw_response)
except requests.ConnectionError:
errmsg = 'Got connection error ' + str(traceback.format_exc())
self.logger.error(errmsg)
continue
except requests.JSONDecodeError:
errmsg = 'JsonDecode error, got ' + str(raw_response.content)
self.logger.error(errmsg)
continue
except KeyError:
if 'error' in response:
if response['error']['code'] == 'rate_limit_exceeded':
time.sleep(1)
continue
elif response['error']['code'] == 'insufficient_quota':
self.invalid_keys.add(key)
self.logger.warn(f'insufficient_quota key: {key}')
continue
errmsg = 'Find error message in response: ' + str(
response['error'])
self.logger.error(errmsg)
except Exception as error:
errmsg = str(error) + '\n' + str(traceback.format_exc())
self.logger.error(errmsg)
max_num_retries += 1
raise RuntimeError('Calling OpenAI failed after retrying for '
f'{max_num_retries} times. Check the logs for '
f'details. errmsg: {errmsg}')
def generate_request_data(self,
model_type,
messages,
gen_params,
json_mode=False):
"""
Generates the request data for different model types.
Args:
model_type (str): The type of the model (e.g., 'gpt', 'internlm', 'qwen').
messages (list): The list of messages to be sent to the model.
gen_params (dict): The generation parameters.
json_mode (bool): Flag to determine if the response format should be JSON.
Returns:
tuple: A tuple containing the header and the request data.
"""
# Copy generation parameters to avoid modifying the original dictionary
gen_params = gen_params.copy()
# Hold out 100 tokens due to potential errors in token calculation
max_tokens = min(gen_params.pop('max_new_tokens'), 4096)
if max_tokens <= 0:
return '', ''
# Initialize the header
header = {
'content-type': 'application/json',
}
# Common parameters processing
gen_params['max_tokens'] = max_tokens
if 'stop_words' in gen_params:
gen_params['stop'] = gen_params.pop('stop_words')
if 'repetition_penalty' in gen_params:
gen_params['frequency_penalty'] = gen_params.pop(
'repetition_penalty')
# Model-specific processing
data = {}
if model_type.lower().startswith('gpt'):
if 'top_k' in gen_params:
warnings.warn(
'`top_k` parameter is deprecated in OpenAI APIs.',
DeprecationWarning)
gen_params.pop('top_k')
gen_params.pop('skip_special_tokens', None)
gen_params.pop('session_id', None)
data = {
'model': model_type,
'messages': messages,
'n': 1,
**gen_params
}
if json_mode:
data['response_format'] = {'type': 'json_object'}
elif model_type.lower().startswith('internlm'):
data = {
'model': model_type,
'messages': messages,
'n': 1,
**gen_params
}
if json_mode:
data['response_format'] = {'type': 'json_object'}
elif model_type.lower().startswith('qwen'):
header['X-DashScope-SSE'] = 'enable'
gen_params.pop('skip_special_tokens', None)
gen_params.pop('session_id', None)
if 'frequency_penalty' in gen_params:
gen_params['repetition_penalty'] = gen_params.pop(
'frequency_penalty')
gen_params['result_format'] = 'message'
data = {
'model': model_type,
'input': {
'messages': messages
},
'parameters': {
**gen_params
}
}
else:
raise NotImplementedError(
f'Model type {model_type} is not supported')
return header, data
def tokenize(self, prompt: str) -> list:
"""Tokenize the input prompt.
Args:
prompt (str): Input string.
Returns:
list: token ids
"""
import tiktoken
self.tiktoken = tiktoken
enc = self.tiktoken.encoding_for_model(self.model_type)
return enc.encode(prompt)
class AsyncGPTAPI(AsyncBaseAPILLM):
"""Model wrapper around OpenAI's models.
Args:
model_type (str): The name of OpenAI's model.
retry (int): Number of retires if the API call fails. Defaults to 2.
key (str or List[str]): OpenAI key(s). In particular, when it
is set to "ENV", the key will be fetched from the environment
variable $OPENAI_API_KEY, as how openai defaults to be. If it's a
list, the keys will be used in round-robin manner. Defaults to
'ENV'.
org (str or List[str], optional): OpenAI organization(s). If not
specified, OpenAI uses the default organization bound to each API
key. If specified, the orgs will be posted with each request in
round-robin manner. Defaults to None.
meta_template (Dict, optional): The model's meta prompt
template if needed, in case the requirement of injecting or
wrapping of any meta instructions.
api_base (str): The base url of OpenAI's API. Defaults to
'https://api.openai.com/v1/chat/completions'.
gen_params: Default generation configuration which could be overridden
on the fly of generation.
"""
is_api: bool = True
def __init__(self,
model_type: str = 'gpt-3.5-turbo',
retry: int = 2,
json_mode: bool = False,
key: Union[str, List[str]] = 'ENV',
org: Optional[Union[str, List[str]]] = None,
meta_template: Optional[Dict] = [
dict(role='system', api_role='system'),
dict(role='user', api_role='user'),
dict(role='assistant', api_role='assistant')
],
api_base: str = OPENAI_API_BASE,
proxies: Optional[Dict] = None,
**gen_params):
if 'top_k' in gen_params:
warnings.warn('`top_k` parameter is deprecated in OpenAI APIs.',
DeprecationWarning)
gen_params.pop('top_k')
super().__init__(
model_type=model_type,
meta_template=meta_template,
retry=retry,
**gen_params)
self.gen_params.pop('top_k')
self.logger = getLogger(__name__)
if isinstance(key, str):
self.keys = [os.getenv('OPENAI_API_KEY') if key == 'ENV' else key]
else:
self.keys = key
# record invalid keys and skip them when requesting API
# - keys have insufficient_quota
self.invalid_keys = set()
self.key_ctr = 0
if isinstance(org, str):
self.orgs = [org]
else:
self.orgs = org
self.org_ctr = 0
self.url = api_base
self.model_type = model_type
self.proxies = proxies or {}
self.json_mode = json_mode
async def chat(
self,
inputs: Union[List[dict], List[List[dict]]],
session_ids: Union[int, List[int]] = None,
**gen_params,
) -> Union[str, List[str]]:
"""Generate responses given the contexts.
Args:
inputs (Union[List[dict], List[List[dict]]]): a list of messages
or list of lists of messages
gen_params: additional generation configuration
Returns:
Union[str, List[str]]: generated string(s)
"""
assert isinstance(inputs, list)
if 'max_tokens' in gen_params:
raise NotImplementedError('unsupported parameter: max_tokens')
gen_params = {**self.gen_params, **gen_params}
tasks = [
self._chat(messages, **gen_params) for messages in (
[inputs] if isinstance(inputs[0], dict) else inputs)
]
ret = await asyncio.gather(*tasks)
return ret[0] if isinstance(inputs[0], dict) else ret
async def stream_chat(
self,
inputs: List[dict],
**gen_params,
):
"""Generate responses given the contexts.
Args:
inputs (List[dict]): a list of messages
gen_params: additional generation configuration
Returns:
str: generated string
"""
assert isinstance(inputs, list)
if 'max_tokens' in gen_params:
raise NotImplementedError('unsupported parameter: max_tokens')
gen_params = self.update_gen_params(**gen_params)
gen_params['stream'] = True
resp = ''
finished = False
stop_words = gen_params.get('stop_words')
if stop_words is None:
stop_words = []
# mapping to role that openai supports
messages = self.template_parser._prompt2api(inputs)
async for text in self._stream_chat(messages, **gen_params):
if self.model_type.lower().startswith('qwen'):
resp = text
else:
resp += text
if not resp:
continue
# remove stop_words
for sw in stop_words:
if sw in resp:
resp = filter_suffix(resp, stop_words)
finished = True
break
yield ModelStatusCode.STREAM_ING, resp, None
if finished:
break
yield ModelStatusCode.END, resp, None
async def _chat(self, messages: List[dict], **gen_params) -> str:
"""Generate completion from a list of templates.
Args:
messages (List[dict]): a list of prompt dictionaries
gen_params: additional generation configuration
Returns:
str: The generated string.
"""
assert isinstance(messages, list)
header, data = self.generate_request_data(
model_type=self.model_type,
messages=messages,
gen_params=gen_params,
json_mode=self.json_mode)
max_num_retries, errmsg = 0, ''
while max_num_retries < self.retry:
if len(self.invalid_keys) == len(self.keys):
raise RuntimeError('All keys have insufficient quota.')
# find the next valid key
while True:
self.key_ctr += 1
if self.key_ctr == len(self.keys):
self.key_ctr = 0
if self.keys[self.key_ctr] not in self.invalid_keys:
break
key = self.keys[self.key_ctr]
header['Authorization'] = f'Bearer {key}'
if self.orgs:
self.org_ctr += 1
if self.org_ctr == len(self.orgs):
self.org_ctr = 0
header['OpenAI-Organization'] = self.orgs[self.org_ctr]
response = dict()
try:
async with aiohttp.ClientSession() as session:
async with session.post(
self.url,
headers=header,
json=data,
proxy=self.proxies.get(
'https', self.proxies.get('http'))) as resp:
response = await resp.json()
return response['choices'][0]['message'][
'content'].strip()
except aiohttp.ClientConnectionError:
errmsg = 'Got connection error ' + str(traceback.format_exc())
self.logger.error(errmsg)
continue
except aiohttp.ClientResponseError as e:
errmsg = 'Response error, got ' + str(e)
self.logger.error(errmsg)
continue
except json.JSONDecodeError:
errmsg = 'JsonDecode error, got ' + (await resp.text(
errors='replace'))
self.logger.error(errmsg)
continue
except KeyError:
if 'error' in response:
if response['error']['code'] == 'rate_limit_exceeded':
time.sleep(1)
continue
elif response['error']['code'] == 'insufficient_quota':
self.invalid_keys.add(key)
self.logger.warn(f'insufficient_quota key: {key}')
continue
errmsg = 'Find error message in response: ' + str(
response['error'])
self.logger.error(errmsg)
except Exception as error:
errmsg = str(error) + '\n' + str(traceback.format_exc())
self.logger.error(errmsg)
max_num_retries += 1
raise RuntimeError('Calling OpenAI failed after retrying for '
f'{max_num_retries} times. Check the logs for '
f'details. errmsg: {errmsg}')
async def _stream_chat(self, messages: List[dict],
**gen_params) -> AsyncGenerator[str, None]:
"""Generate completion from a list of templates.
Args:
messages (List[dict]): a list of prompt dictionaries
gen_params: additional generation configuration
Returns:
str: The generated string.
"""
async def streaming(raw_response):
async for chunk in raw_response.content:
if chunk:
decoded = chunk.decode('utf-8')
if decoded.startswith('data: [DONE]'):
return
if decoded[:5] == 'data:':
decoded = decoded[5:]
if decoded[0] == ' ':
decoded = decoded[1:]
else:
print(decoded)
continue
try:
response = json.loads(decoded)
if 'code' in response and response['code'] == -20003:
# Context exceeds maximum length
yield ''
return
if self.model_type.lower().startswith('qwen'):
choice = response['output']['choices'][0]
yield choice['message']['content']
if choice['finish_reason'] == 'stop':
return
else:
choice = response['choices'][0]
if choice['finish_reason'] == 'stop':
return
yield choice['delta'].get('content', '')
except Exception as exc:
msg = f'response {decoded} lead to exception of {str(exc)}'
self.logger.error(msg)
raise Exception(msg) from exc
assert isinstance(messages, list)
header, data = self.generate_request_data(
model_type=self.model_type,
messages=messages,
gen_params=gen_params,
json_mode=self.json_mode)
max_num_retries, errmsg = 0, ''
while max_num_retries < self.retry:
if len(self.invalid_keys) == len(self.keys):
raise RuntimeError('All keys have insufficient quota.')
# find the next valid key
while True:
self.key_ctr += 1
if self.key_ctr == len(self.keys):
self.key_ctr = 0
if self.keys[self.key_ctr] not in self.invalid_keys:
break
key = self.keys[self.key_ctr]
header['Authorization'] = f'Bearer {key}'
if self.orgs:
self.org_ctr += 1
if self.org_ctr == len(self.orgs):
self.org_ctr = 0
header['OpenAI-Organization'] = self.orgs[self.org_ctr]
response = dict()
try:
async with aiohttp.ClientSession() as session:
async with session.post(
self.url,
headers=header,
json=data,
proxy=self.proxies.get(
'https',
self.proxies.get('http'))) as raw_response:
async for msg in streaming(raw_response):
yield msg
return
except aiohttp.ClientConnectionError:
errmsg = 'Got connection error ' + str(traceback.format_exc())
self.logger.error(errmsg)
continue
except aiohttp.ClientResponseError as e:
errmsg = 'Response error, got ' + str(e)
self.logger.error(errmsg)
continue
except KeyError:
if 'error' in response:
if response['error']['code'] == 'rate_limit_exceeded':
time.sleep(1)
continue
elif response['error']['code'] == 'insufficient_quota':
self.invalid_keys.add(key)
self.logger.warn(f'insufficient_quota key: {key}')
continue
errmsg = 'Find error message in response: ' + str(
response['error'])
self.logger.error(errmsg)
except Exception as error:
errmsg = str(error) + '\n' + str(traceback.format_exc())
self.logger.error(errmsg)
max_num_retries += 1
raise RuntimeError('Calling OpenAI failed after retrying for '
f'{max_num_retries} times. Check the logs for '
f'details. errmsg: {errmsg}')
def generate_request_data(self,
model_type,
messages,
gen_params,
json_mode=False):
"""
Generates the request data for different model types.
Args:
model_type (str): The type of the model (e.g., 'gpt', 'internlm', 'qwen').
messages (list): The list of messages to be sent to the model.
gen_params (dict): The generation parameters.
json_mode (bool): Flag to determine if the response format should be JSON.
Returns:
tuple: A tuple containing the header and the request data.
"""
# Copy generation parameters to avoid modifying the original dictionary
gen_params = gen_params.copy()
# Hold out 100 tokens due to potential errors in token calculation
max_tokens = min(gen_params.pop('max_new_tokens'), 4096)
if max_tokens <= 0:
return '', ''
# Initialize the header
header = {
'content-type': 'application/json',
}
# Common parameters processing
gen_params['max_tokens'] = max_tokens
if 'stop_words' in gen_params:
gen_params['stop'] = gen_params.pop('stop_words')
if 'repetition_penalty' in gen_params:
gen_params['frequency_penalty'] = gen_params.pop(
'repetition_penalty')
# Model-specific processing
data = {}
if model_type.lower().startswith('gpt'):
if 'top_k' in gen_params:
warnings.warn(
'`top_k` parameter is deprecated in OpenAI APIs.',
DeprecationWarning)
gen_params.pop('top_k')
gen_params.pop('skip_special_tokens', None)
gen_params.pop('session_id', None)
data = {
'model': model_type,
'messages': messages,
'n': 1,
**gen_params
}
if json_mode:
data['response_format'] = {'type': 'json_object'}
elif model_type.lower().startswith('internlm'):
data = {
'model': model_type,
'messages': messages,
'n': 1,
**gen_params
}
if json_mode:
data['response_format'] = {'type': 'json_object'}
elif model_type.lower().startswith('qwen'):
header['X-DashScope-SSE'] = 'enable'
gen_params.pop('skip_special_tokens', None)
gen_params.pop('session_id', None)
if 'frequency_penalty' in gen_params:
gen_params['repetition_penalty'] = gen_params.pop(
'frequency_penalty')
gen_params['result_format'] = 'message'
data = {
'model': model_type,
'input': {
'messages': messages
},
'parameters': {
**gen_params
}
}
else:
raise NotImplementedError(
f'Model type {model_type} is not supported')
return header, data
def tokenize(self, prompt: str) -> list:
"""Tokenize the input prompt.
Args:
prompt (str): Input string.
Returns:
list: token ids
"""
import tiktoken
self.tiktoken = tiktoken
enc = self.tiktoken.encoding_for_model(self.model_type)
return enc.encode(prompt)
|