Spaces:
Running
Running
File size: 2,862 Bytes
2319518 |
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 |
import os
from http import HTTPStatus
from typing import Dict, Iterator, List, Optional
import dashscope
from qwen_agent.llm.base import BaseChatModel
class QwenChatAtDS(BaseChatModel):
def __init__(self, model: str, api_key: str):
super().__init__()
self.model = model
dashscope.api_key = api_key.strip() or os.getenv('DASHSCOPE_API_KEY',
default='')
assert dashscope.api_key, 'DASHSCOPE_API_KEY is required.'
def _chat_stream(
self,
messages: List[Dict],
stop: Optional[List[str]] = None,
) -> Iterator[str]:
stop = stop or []
response = dashscope.Generation.call(
self.model,
messages=messages, # noqa
stop_words=[{
'stop_str': word,
'mode': 'exclude'
} for word in stop],
top_p=0.8,
result_format='message',
stream=True,
)
last_len = 0
delay_len = 5
in_delay = False
text = ''
for trunk in response:
if trunk.status_code == HTTPStatus.OK:
text = trunk.output.choices[0].message.content
if (len(text) - last_len) <= delay_len:
in_delay = True
continue
else:
in_delay = False
real_text = text[:-delay_len]
now_rsp = real_text[last_len:]
yield now_rsp
last_len = len(real_text)
else:
err = '\nError code: %s. Error message: %s' % (trunk.code,
trunk.message)
if trunk.code == 'DataInspectionFailed':
err += '\n错误码: 数据检查失败。错误信息: 输入数据可能包含不适当的内容。'
text = ''
yield f'{err}'
if text and (in_delay or (last_len != len(text))):
yield text[last_len:]
def _chat_no_stream(
self,
messages: List[Dict],
stop: Optional[List[str]] = None,
) -> str:
stop = stop or []
response = dashscope.Generation.call(
self.model,
messages=messages, # noqa
result_format='message',
stream=False,
stop_words=[{
'stop_str': word,
'mode': 'exclude'
} for word in stop],
top_p=0.8,
)
if response.status_code == HTTPStatus.OK:
return response.output.choices[0].message.content
else:
err = 'Error code: %s, error message: %s' % (
response.code,
response.message,
)
return err
|