Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions qwen_agent/llm/oai.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
@register_llm('oai')
class TextChatAtOAI(BaseFnCallModel):

MAX_OAI_STOP_WORDS = 4

def __init__(self, cfg: Optional[Dict] = None):
super().__init__(cfg)
self.model = self.model or 'gpt-4o-mini'
Expand Down Expand Up @@ -95,13 +97,26 @@ def _complete_create(*args, **kwargs):
self._complete_create = _complete_create
self._chat_complete_create = _chat_complete_create

@classmethod
def _normalize_generate_cfg_for_oai(cls, generate_cfg: dict) -> dict:
normalized_cfg = copy.deepcopy(generate_cfg)
stop = normalized_cfg.get('stop')
if isinstance(stop, list) and len(stop) > cls.MAX_OAI_STOP_WORDS:
logger.warning(
f'OpenAI-compatible APIs support at most {cls.MAX_OAI_STOP_WORDS} stop words. '
f'Truncating from {len(stop)} to {cls.MAX_OAI_STOP_WORDS}.'
)
normalized_cfg['stop'] = stop[:cls.MAX_OAI_STOP_WORDS]
return normalized_cfg

def _chat_stream(
self,
messages: List[Message],
delta_stream: bool,
generate_cfg: dict,
) -> Iterator[List[Message]]:
messages = self.convert_messages_to_dicts(messages)
generate_cfg = self._normalize_generate_cfg_for_oai(generate_cfg)
logger.debug(f'LLM Input generate_cfg: \n{generate_cfg}')
try:
response = self._chat_complete_create(model=self.model, messages=messages, stream=True, **generate_cfg)
Expand Down Expand Up @@ -164,6 +179,7 @@ def _chat_no_stream(
generate_cfg: dict,
) -> List[Message]:
messages = self.convert_messages_to_dicts(messages)
generate_cfg = self._normalize_generate_cfg_for_oai(generate_cfg)
try:
response = self._chat_complete_create(model=self.model, messages=messages, stream=False, **generate_cfg)
if hasattr(response.choices[0].message, 'reasoning_content'):
Expand Down
7 changes: 5 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,11 @@ def read_description() -> str:
# Gradio has bad version compatibility. Therefore, we use `==` instead of `>=`.
'pydantic==2.9.2',
'pydantic-core==2.23.4',
'gradio==5.23.1',
'gradio-client==1.8.0',
'gradio==4.44.1; python_version < "3.10"',
'gradio-client==1.3.0; python_version < "3.10"',
'huggingface-hub<1.0; python_version < "3.10"',
'gradio==5.23.1; python_version >= "3.10"',
'gradio-client==1.8.0; python_version >= "3.10"',
'modelscope_studio==1.1.7',
],
},
Expand Down
33 changes: 33 additions & 0 deletions tests/llm/test_oai_stop_cfg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import sys
from types import ModuleType


openai_stub = ModuleType('openai')
openai_stub.__version__ = '1.0.0'
openai_stub.OpenAIError = Exception
openai_stub.OpenAI = object
sys.modules.setdefault('openai', openai_stub)

from qwen_agent.llm.oai import TextChatAtOAI


def test_normalize_generate_cfg_for_oai_truncates_stop_list():
original = {
'temperature': 0.1,
'stop': ['✿RESULT✿', '✿RETURN✿', 'Observation:', 'Observation:\n', '"] , "instruction":'],
}

normalized = TextChatAtOAI._normalize_generate_cfg_for_oai(original)

assert normalized['stop'] == ['✿RESULT✿', '✿RETURN✿', 'Observation:', 'Observation:\n']
assert normalized['temperature'] == 0.1
# Keep input unchanged.
assert len(original['stop']) == 5


def test_normalize_generate_cfg_for_oai_keeps_non_list_stop():
original = {'stop': 'Observation:'}

normalized = TextChatAtOAI._normalize_generate_cfg_for_oai(original)

assert normalized == original