Skip to content
Merged
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
2 changes: 1 addition & 1 deletion swift/infer_engine/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def __post_init__(self):
self.tools = None
elif isinstance(self.tool_choice, dict):
name = self.tool_choice['function']['name']
tool = next(tool for tool in self.tools if tool['function']['name'] == name)
tool = next((tool for tool in self.tools if tool['function']['name'] == name), None)
if tool is None:
raise ValueError(f"Tool choice '{name}' not found in tools.")
self.tools = [tool]
Expand Down
43 changes: 43 additions & 0 deletions tests/general/test_protocol_tool_choice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import unittest

from swift.infer_engine.protocol import ChatCompletionRequest


def _request(tool_choice):
tools = [
{
'type': 'function',
'function': {
'name': 'get_weather'
}
},
{
'type': 'function',
'function': {
'name': 'get_time'
}
},
]
return ChatCompletionRequest(
model='test', messages=[{
'role': 'user',
'content': 'hi'
}], tools=tools, tool_choice=tool_choice)


class TestChatCompletionRequestToolChoice(unittest.TestCase):

def test_selected_tool_keeps_only_that_tool(self):
request = _request({'type': 'function', 'function': {'name': 'get_time'}})
self.assertEqual([tool['function']['name'] for tool in request.tools], ['get_time'])

def test_unknown_tool_raises_value_error(self):
with self.assertRaisesRegex(ValueError, "Tool choice 'no_such_tool' not found in tools."):
_request({'type': 'function', 'function': {'name': 'no_such_tool'}})

def test_string_tool_choice_keeps_every_tool(self):
self.assertEqual(len(_request('auto').tools), 2)


if __name__ == '__main__':
unittest.main()
Loading