test_tool_call.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. #!/usr/bin/env python
  2. import pytest
  3. # ensure grandparent path is in sys.path
  4. from pathlib import Path
  5. import sys
  6. path = Path(__file__).resolve().parents[1]
  7. sys.path.insert(0, str(path))
  8. from utils import *
  9. from enum import Enum
  10. server: ServerProcess
  11. TIMEOUT_SERVER_START = 15*60
  12. TIMEOUT_HTTP_REQUEST = 60
  13. @pytest.fixture(autouse=True)
  14. def create_server():
  15. global server
  16. server = ServerPreset.tinyllama2()
  17. server.model_alias = "tinyllama-2-tool-call"
  18. server.server_port = 8081
  19. server.n_slots = 1
  20. class CompletionMode(Enum):
  21. NORMAL = "normal"
  22. STREAMED = "streamed"
  23. TEST_TOOL = {
  24. "type":"function",
  25. "function": {
  26. "name": "test",
  27. "description": "",
  28. "parameters": {
  29. "type": "object",
  30. "properties": {
  31. "success": {"type": "boolean", "const": True},
  32. },
  33. "required": ["success"]
  34. }
  35. }
  36. }
  37. PYTHON_TOOL = {
  38. "type": "function",
  39. "function": {
  40. "name": "python",
  41. "description": "Runs code in an ipython interpreter and returns the result of the execution after 60 seconds.",
  42. "parameters": {
  43. "type": "object",
  44. "properties": {
  45. "code": {
  46. "type": "string",
  47. "description": "The code to run in the ipython interpreter."
  48. }
  49. },
  50. "required": ["code"]
  51. }
  52. }
  53. }
  54. WEATHER_TOOL = {
  55. "type":"function",
  56. "function":{
  57. "name":"get_current_weather",
  58. "description":"Get the current weather in a given location",
  59. "parameters":{
  60. "type":"object",
  61. "properties":{
  62. "location":{
  63. "type":"string",
  64. "description":"The city and country/state, e.g. 'San Francisco, CA', or 'Paris, France'"
  65. }
  66. },
  67. "required":["location"]
  68. }
  69. }
  70. }
  71. def do_test_completion_with_required_tool_tiny(server: ServerProcess, tool: dict, argument_key: str | None, n_predict, **kwargs):
  72. body = server.make_any_request("POST", "/v1/chat/completions", data={
  73. "max_tokens": n_predict,
  74. "messages": [
  75. {"role": "system", "content": "You are a coding assistant."},
  76. {"role": "user", "content": "Write an example"},
  77. ],
  78. "tool_choice": "required",
  79. "tools": [tool],
  80. "parallel_tool_calls": False,
  81. **kwargs,
  82. })
  83. # assert res.status_code == 200, f"Expected status code 200, got {res.status_code}"
  84. choice = body["choices"][0]
  85. tool_calls = choice["message"].get("tool_calls")
  86. assert tool_calls and len(tool_calls) == 1, f'Expected 1 tool call in {choice["message"]}'
  87. tool_call = tool_calls[0]
  88. assert choice["message"].get("content") in (None, ""), f'Expected no content in {choice["message"]}'
  89. # assert len(tool_call.get("id", "")) > 0, f'Expected non empty tool call id in {tool_call}'
  90. expected_function_name = "python" if tool["type"] == "code_interpreter" else tool["function"]["name"]
  91. assert expected_function_name == tool_call["function"]["name"]
  92. actual_arguments = tool_call["function"]["arguments"]
  93. assert isinstance(actual_arguments, str)
  94. if argument_key is not None:
  95. actual_arguments = json.loads(actual_arguments)
  96. assert argument_key in actual_arguments, f"tool arguments: {json.dumps(actual_arguments)}, expected: {argument_key}"
  97. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  98. @pytest.mark.parametrize("template_name,tool,argument_key", [
  99. ("google-gemma-2-2b-it", TEST_TOOL, "success"),
  100. ("google-gemma-2-2b-it", TEST_TOOL, "success"),
  101. ("meta-llama-Llama-3.3-70B-Instruct", TEST_TOOL, "success"),
  102. ("meta-llama-Llama-3.3-70B-Instruct", TEST_TOOL, "success"),
  103. ("meta-llama-Llama-3.3-70B-Instruct", PYTHON_TOOL, "code"),
  104. ("meta-llama-Llama-3.3-70B-Instruct", PYTHON_TOOL, "code"),
  105. ])
  106. def test_completion_with_required_tool_tiny_fast(template_name: str, tool: dict, argument_key: str | None, stream: CompletionMode):
  107. global server
  108. n_predict = 1024
  109. # server = ServerPreset.stories15m_moe()
  110. server.jinja = True
  111. server.n_predict = n_predict
  112. server.chat_template_file = f'../../../models/templates/{template_name}.jinja'
  113. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  114. do_test_completion_with_required_tool_tiny(server, tool, argument_key, n_predict, stream=stream == CompletionMode.STREAMED, temperature=0.0, top_k=1, top_p=1.0)
  115. @pytest.mark.slow
  116. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  117. @pytest.mark.parametrize("template_name,tool,argument_key", [
  118. ("meta-llama-Llama-3.1-8B-Instruct", TEST_TOOL, "success"),
  119. ("meta-llama-Llama-3.1-8B-Instruct", PYTHON_TOOL, "code"),
  120. ("meetkai-functionary-medium-v3.1", TEST_TOOL, "success"),
  121. ("meetkai-functionary-medium-v3.1", PYTHON_TOOL, "code"),
  122. ("meetkai-functionary-medium-v3.2", TEST_TOOL, "success"),
  123. # Functionary v3.2 format supports raw python content, which w/ a dummy stories model will never end on its own.
  124. # ("meetkai-functionary-medium-v3.2", PYTHON_TOOL, "code"),
  125. ("NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use", TEST_TOOL, "success"),
  126. ("NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use", PYTHON_TOOL, "code"),
  127. ("meta-llama-Llama-3.2-3B-Instruct", TEST_TOOL, "success"),
  128. ("meta-llama-Llama-3.2-3B-Instruct", PYTHON_TOOL, "code"),
  129. ("mistralai-Mistral-Nemo-Instruct-2407", TEST_TOOL, "success"),
  130. ("mistralai-Mistral-Nemo-Instruct-2407", PYTHON_TOOL, "code"),
  131. ("NousResearch-Hermes-3-Llama-3.1-8B-tool_use", TEST_TOOL, "success"),
  132. ("NousResearch-Hermes-3-Llama-3.1-8B-tool_use", PYTHON_TOOL, "code"),
  133. ("deepseek-ai-DeepSeek-R1-Distill-Llama-8B", TEST_TOOL, "success"),
  134. ("deepseek-ai-DeepSeek-R1-Distill-Llama-8B", PYTHON_TOOL, "code"),
  135. ("fireworks-ai-llama-3-firefunction-v2", TEST_TOOL, "success"),
  136. # ("fireworks-ai-llama-3-firefunction-v2", PYTHON_TOOL, "codeFalse), True),
  137. # ("fireworks-ai-llama-3-firefunction-v2", PYTHON_TOOL, "code"),
  138. ])
  139. def test_completion_with_required_tool_tiny_slow(template_name: str, tool: dict, argument_key: str | None, stream: CompletionMode):
  140. global server
  141. n_predict = 512
  142. # server = ServerPreset.stories15m_moe()
  143. server.jinja = True
  144. server.n_predict = n_predict
  145. server.chat_template_file = f'../../../models/templates/{template_name}.jinja'
  146. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  147. do_test_completion_with_required_tool_tiny(server, tool, argument_key, n_predict, stream=stream == CompletionMode.STREAMED)
  148. @pytest.mark.slow
  149. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  150. @pytest.mark.parametrize("tool,argument_key,hf_repo,template_override", [
  151. (TEST_TOOL, "success", "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", None),
  152. (PYTHON_TOOL, "code", "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", None),
  153. (PYTHON_TOOL, "code", "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", "chatml"),
  154. (TEST_TOOL, "success", "bartowski/gemma-2-2b-it-GGUF:Q4_K_M", None),
  155. (PYTHON_TOOL, "code", "bartowski/gemma-2-2b-it-GGUF:Q4_K_M", None),
  156. (PYTHON_TOOL, "code", "bartowski/gemma-2-2b-it-GGUF:Q4_K_M", "chatml"),
  157. (TEST_TOOL, "success", "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  158. (PYTHON_TOOL, "code", "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  159. (PYTHON_TOOL, "code", "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", "chatml"),
  160. (TEST_TOOL, "success", "bartowski/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M", None),
  161. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M", None),
  162. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M", "chatml"),
  163. (TEST_TOOL, "success", "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", None),
  164. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", None),
  165. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", "chatml"),
  166. (TEST_TOOL, "success", "bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", None),
  167. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", None),
  168. (PYTHON_TOOL, "code", "bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", "chatml"),
  169. (TEST_TOOL, "success", "bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-2-Pro-Llama-3-8B", "tool_use")),
  170. (PYTHON_TOOL, "code", "bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-2-Pro-Llama-3-8B", "tool_use")),
  171. (PYTHON_TOOL, "code", "bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", "chatml"),
  172. (TEST_TOOL, "success", "bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-3-Llama-3.1-8B", "tool_use")),
  173. (PYTHON_TOOL, "code", "bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-3-Llama-3.1-8B", "tool_use")),
  174. (PYTHON_TOOL, "code", "bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", "chatml"),
  175. # (TEST_TOOL, "success", "bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", None),
  176. # (PYTHON_TOOL, "code", "bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", None),
  177. # (PYTHON_TOOL, "code", "bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", "chatml"),
  178. (TEST_TOOL, "success", "bartowski/functionary-small-v3.2-GGUF:Q4_K_M", ("meetkai/functionary-medium-v3.2", None)),
  179. (PYTHON_TOOL, "code", "bartowski/functionary-small-v3.2-GGUF:Q4_K_M", ("meetkai/functionary-medium-v3.2", None)),
  180. (PYTHON_TOOL, "code", "bartowski/functionary-small-v3.2-GGUF:Q4_K_M", "chatml"),
  181. (TEST_TOOL, "success", "bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  182. (PYTHON_TOOL, "code", "bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  183. (PYTHON_TOOL, "code", "bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", "chatml"),
  184. (TEST_TOOL, "success", "bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  185. (PYTHON_TOOL, "code", "bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  186. (PYTHON_TOOL, "code", "bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", "chatml"),
  187. (TEST_TOOL, "success", "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  188. (PYTHON_TOOL, "code", "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  189. ])
  190. def test_completion_with_required_tool_real_model(tool: dict, argument_key: str | None, hf_repo: str, template_override: str | Tuple[str, str | None] | None, stream: CompletionMode):
  191. global server
  192. n_predict = 512
  193. server.jinja = True
  194. server.n_ctx = 8192
  195. server.n_predict = n_predict
  196. server.model_hf_repo = hf_repo
  197. server.model_hf_file = None
  198. if isinstance(template_override, tuple):
  199. (template_hf_repo, template_variant) = template_override
  200. server.chat_template_file = f"../../../models/templates/{template_hf_repo.replace('/', '-') + ('-' + template_variant if template_variant else '')}.jinja"
  201. assert os.path.exists(server.chat_template_file), f"Template file {server.chat_template_file} does not exist. Run `python scripts/get_chat_template.py {template_hf_repo} {template_variant} > {server.chat_template_file}` to download the template."
  202. elif isinstance(template_override, str):
  203. server.chat_template = template_override
  204. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  205. body = server.make_any_request("POST", "/v1/chat/completions", data={
  206. "max_tokens": n_predict,
  207. "messages": [
  208. {"role": "system", "content": "You are a coding assistant."},
  209. {"role": "user", "content": "Write an example"},
  210. ],
  211. "tool_choice": "required",
  212. "tools": [tool],
  213. "parallel_tool_calls": False,
  214. "stream": stream == CompletionMode.STREAMED,
  215. "temperature": 0.0,
  216. "top_k": 1,
  217. "top_p": 1.0,
  218. }, timeout=TIMEOUT_HTTP_REQUEST)
  219. choice = body["choices"][0]
  220. tool_calls = choice["message"].get("tool_calls")
  221. assert tool_calls and len(tool_calls) == 1, f'Expected 1 tool call in {choice["message"]}'
  222. tool_call = tool_calls[0]
  223. # assert choice["message"].get("content") in (None, ""), f'Expected no content in {choice["message"]}'
  224. expected_function_name = "python" if tool["type"] == "code_interpreter" else tool["function"]["name"]
  225. assert expected_function_name == tool_call["function"]["name"]
  226. actual_arguments = tool_call["function"]["arguments"]
  227. assert isinstance(actual_arguments, str)
  228. if argument_key is not None:
  229. actual_arguments = json.loads(actual_arguments)
  230. assert argument_key in actual_arguments, f"tool arguments: {json.dumps(actual_arguments)}, expected: {argument_key}"
  231. def do_test_completion_without_tool_call(server: ServerProcess, n_predict: int, tools: list[dict], tool_choice: str | None, **kwargs):
  232. body = server.make_any_request("POST", "/v1/chat/completions", data={
  233. "max_tokens": n_predict,
  234. "messages": [
  235. {"role": "system", "content": "You are a coding assistant."},
  236. {"role": "user", "content": "say hello world with python"},
  237. ],
  238. "tools": tools if tools else None,
  239. "tool_choice": tool_choice,
  240. **kwargs,
  241. }, timeout=TIMEOUT_HTTP_REQUEST)
  242. choice = body["choices"][0]
  243. assert choice["message"].get("tool_calls") is None, f'Expected no tool call in {choice["message"]}'
  244. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  245. @pytest.mark.parametrize("template_name,n_predict,tools,tool_choice", [
  246. ("meta-llama-Llama-3.3-70B-Instruct", 128, [], None),
  247. ("meta-llama-Llama-3.3-70B-Instruct", 128, [TEST_TOOL], None),
  248. ("meta-llama-Llama-3.3-70B-Instruct", 128, [PYTHON_TOOL], 'none'),
  249. ])
  250. def test_completion_without_tool_call_fast(template_name: str, n_predict: int, tools: list[dict], tool_choice: str | None, stream: CompletionMode):
  251. global server
  252. server.n_predict = n_predict
  253. server.jinja = True
  254. server.chat_template_file = f'../../../models/templates/{template_name}.jinja'
  255. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  256. do_test_completion_without_tool_call(server, n_predict, tools, tool_choice, stream=stream == CompletionMode.STREAMED)
  257. @pytest.mark.slow
  258. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  259. @pytest.mark.parametrize("template_name,n_predict,tools,tool_choice", [
  260. ("meetkai-functionary-medium-v3.2", 256, [], None),
  261. ("meetkai-functionary-medium-v3.2", 256, [TEST_TOOL], None),
  262. ("meetkai-functionary-medium-v3.2", 256, [PYTHON_TOOL], 'none'),
  263. ("meetkai-functionary-medium-v3.1", 256, [], None),
  264. ("meetkai-functionary-medium-v3.1", 256, [TEST_TOOL], None),
  265. ("meetkai-functionary-medium-v3.1", 256, [PYTHON_TOOL], 'none'),
  266. ("meta-llama-Llama-3.2-3B-Instruct", 256, [], None),
  267. ("meta-llama-Llama-3.2-3B-Instruct", 256, [TEST_TOOL], None),
  268. ("meta-llama-Llama-3.2-3B-Instruct", 256, [PYTHON_TOOL], 'none'),
  269. ])
  270. def test_completion_without_tool_call_slow(template_name: str, n_predict: int, tools: list[dict], tool_choice: str | None, stream: CompletionMode):
  271. global server
  272. server.n_predict = n_predict
  273. server.jinja = True
  274. server.chat_template_file = f'../../../models/templates/{template_name}.jinja'
  275. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  276. do_test_completion_without_tool_call(server, n_predict, tools, tool_choice, stream=stream == CompletionMode.STREAMED)
  277. @pytest.mark.slow
  278. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  279. @pytest.mark.parametrize("hf_repo,template_override", [
  280. ("bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", None),
  281. ("bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", "chatml"),
  282. ("bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  283. ("bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", "chatml"),
  284. ("bartowski/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M", None),
  285. ("bartowski/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M", "chatml"),
  286. ("bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", None),
  287. ("bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", "chatml"),
  288. ("bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", None),
  289. ("bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", "chatml"),
  290. ("bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-2-Pro-Llama-3-8B", "tool_use")),
  291. ("bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", "chatml"),
  292. ("bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-3-Llama-3.1-8B", "tool_use")),
  293. ("bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", "chatml"),
  294. # ("bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", None),
  295. # ("bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", "chatml"),
  296. # ("bartowski/functionary-small-v3.2-GGUF:Q8_0", ("meetkai/functionary-medium-v3.2", None)),
  297. # ("bartowski/functionary-small-v3.2-GGUF:Q8_0", "chatml"),
  298. ("bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  299. ("bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", "chatml"),
  300. ("bartowski/c4ai-command-r7b-12-2024-GGUF:Q6_K_L", ("CohereForAI/c4ai-command-r7b-12-2024", "tool_use")),
  301. ("bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  302. # Note: gemma-2-2b-it knows itself as "model", not "assistant", so we don't test the ill-suited chatml on it.
  303. ("bartowski/gemma-2-2b-it-GGUF:Q4_K_M", None),
  304. # ("bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", ("meta-llama/Llama-3.2-3B-Instruct", None)),
  305. ])
  306. def test_weather(hf_repo: str, template_override: str | Tuple[str, str | None] | None, stream: CompletionMode):
  307. global server
  308. n_predict = 512
  309. server.jinja = True
  310. server.n_ctx = 8192
  311. server.n_predict = n_predict
  312. server.model_hf_repo = hf_repo
  313. server.model_hf_file = None
  314. if isinstance(template_override, tuple):
  315. (template_hf_repo, template_variant) = template_override
  316. server.chat_template_file = f"../../../models/templates/{template_hf_repo.replace('/', '-') + ('-' + template_variant if template_variant else '')}.jinja"
  317. assert os.path.exists(server.chat_template_file), f"Template file {server.chat_template_file} does not exist. Run `python scripts/get_chat_template.py {template_hf_repo} {template_variant} > {server.chat_template_file}` to download the template."
  318. elif isinstance(template_override, str):
  319. server.chat_template = template_override
  320. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  321. do_test_weather(server, stream=stream == CompletionMode.STREAMED, max_tokens=n_predict)
  322. def do_test_weather(server: ServerProcess, **kwargs):
  323. body = server.make_any_request("POST", "/v1/chat/completions", data={
  324. "messages": [
  325. {"role": "system", "content": "You are a chatbot that uses tools/functions. Dont overthink things."},
  326. {"role": "user", "content": "What is the weather in Istanbul?"},
  327. ],
  328. "tools": [WEATHER_TOOL],
  329. **kwargs,
  330. }, timeout=TIMEOUT_HTTP_REQUEST)
  331. choice = body["choices"][0]
  332. tool_calls = choice["message"].get("tool_calls")
  333. assert tool_calls and len(tool_calls) == 1, f'Expected 1 tool call in {choice["message"]}'
  334. tool_call = tool_calls[0]
  335. # assert choice["message"].get("content") in (None, ""), f'Expected no content in {choice["message"]}'
  336. assert tool_call["function"]["name"] == WEATHER_TOOL["function"]["name"], f'Expected weather tool call, got {tool_call["function"]["name"]}'
  337. # assert len(tool_call.get("id", "")) > 0, f'Expected non empty tool call id in {tool_call}'
  338. actual_arguments = json.loads(tool_call["function"]["arguments"])
  339. assert 'location' in actual_arguments, f"location not found in {json.dumps(actual_arguments)}"
  340. location = actual_arguments["location"]
  341. assert isinstance(location, str), f"Expected location to be a string, got {type(location)}: {json.dumps(location)}"
  342. assert re.match('^Istanbul(( |, ?)(TR|Turkey|Türkiye))?$', location), f'Expected Istanbul for location, got {location}'
  343. @pytest.mark.slow
  344. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  345. @pytest.mark.parametrize("result_override,n_predict,hf_repo,template_override", [
  346. (None, 128, "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", "chatml"),
  347. (None, 128, "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", None),
  348. (None, 128, "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF:Q4_K_M", "chatml"),
  349. (None, 128, "bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", "chatml"),
  350. (None, 128, "bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-2-Pro-Llama-3-8B", "tool_use")),
  351. (None, 128, "bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-3-Llama-3.1-8B", "tool_use")),
  352. (None, 128, "bartowski/functionary-small-v3.2-GGUF:Q8_0", ("meetkai/functionary-medium-v3.2", None)),
  353. (None, 128, "bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", None),
  354. (None, 128, "bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", "chatml"),
  355. (None, 128, "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  356. ("[\\s\\S]*?\\*\\*\\s*0.5($|\\*\\*)", 8192, "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", ("llama-cpp-deepseek-r1", None)),
  357. # TODO: fix these (wrong results, either didn't respect decimal instruction or got wrong value)
  358. # (None, 128, "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", None),
  359. # ("[\\s\\S]*?\\*\\*\\s*0.5($|\\*\\*)", 8192, "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  360. ])
  361. def test_calc_result(result_override: str | None, n_predict: int, hf_repo: str, template_override: str | Tuple[str, str | None] | None, stream: CompletionMode):
  362. global server
  363. server.jinja = True
  364. server.n_ctx = 8192 * 2
  365. server.n_predict = n_predict
  366. server.model_hf_repo = hf_repo
  367. server.model_hf_file = None
  368. if isinstance(template_override, tuple):
  369. (template_hf_repo, template_variant) = template_override
  370. server.chat_template_file = f"../../../models/templates/{template_hf_repo.replace('/', '-') + ('-' + template_variant if template_variant else '')}.jinja"
  371. assert os.path.exists(server.chat_template_file), f"Template file {server.chat_template_file} does not exist. Run `python scripts/get_chat_template.py {template_hf_repo} {template_variant} > {server.chat_template_file}` to download the template."
  372. elif isinstance(template_override, str):
  373. server.chat_template = template_override
  374. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  375. do_test_calc_result(server, result_override, n_predict, stream=stream == CompletionMode.STREAMED)
  376. def do_test_calc_result(server: ServerProcess, result_override: str | None, n_predict: int, **kwargs):
  377. body = server.make_any_request("POST", "/v1/chat/completions", data={
  378. "max_tokens": n_predict,
  379. "messages": [
  380. {"role": "system", "content": "You are a tools-calling assistant. You express numerical values with at most two decimals."},
  381. {"role": "user", "content": "What's the y coordinate of a point on the unit sphere at angle 30 degrees?"},
  382. {
  383. "role": "assistant",
  384. "content": None,
  385. "tool_calls": [
  386. {
  387. "id": "call_6789",
  388. "type": "function",
  389. "function": {
  390. "name": "calculate",
  391. "arguments": "{\"expression\":\"sin(30 * pi / 180)\"}"
  392. }
  393. }
  394. ]
  395. },
  396. {
  397. "role": "tool",
  398. "name": "calculate",
  399. "content": "0.55644242476",
  400. "tool_call_id": "call_6789"
  401. }
  402. ],
  403. "tools": [
  404. {
  405. "type":"function",
  406. "function":{
  407. "name":"calculate",
  408. "description":"A calculator function that computes values of arithmetic expressions in the Python syntax",
  409. "parameters":{
  410. "type":"object",
  411. "properties":{
  412. "expression":{
  413. "type":"string",
  414. "description":"An arithmetic expression to compute the value of (Python syntad, assuming all floats)"
  415. }
  416. },
  417. "required":["expression"]
  418. }
  419. }
  420. }
  421. ],
  422. **kwargs,
  423. }, timeout=TIMEOUT_HTTP_REQUEST)
  424. choice = body["choices"][0]
  425. tool_calls = choice["message"].get("tool_calls")
  426. assert tool_calls is None, f'Expected no tool call in {choice["message"]}'
  427. content = choice["message"].get("content")
  428. assert content is not None, f'Expected content in {choice["message"]}'
  429. if result_override is not None:
  430. assert re.match(result_override, content), f'Expected {result_override}, got {content}'
  431. else:
  432. assert re.match('^[\\s\\S]*?((That\'s|\\bis) (approximately )?)?\\b0\\.(5\\b|56\\b|556)', content), \
  433. f'Expected something like "The y coordinate is 0.56.", got {content}'
  434. @pytest.mark.slow
  435. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  436. @pytest.mark.parametrize("n_predict,reasoning_format,expect_reasoning_content,expect_content,hf_repo,template_override", [
  437. (128, 'deepseek', None, "^The sum of 102 and 7 is 109[\\s\\S]*", "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  438. (128, None, None, "^The sum of 102 and 7 is 109[\\s\\S]*", "bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  439. (1024, 'deepseek', "I need to calculate the sum of 102 and 7[\\s\\S]*", "To find the sum of[\\s\\S]*", "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  440. (1024, 'deepseek', "First, I [\\s\\S]*", "To find the sum of[\\s\\S]*", "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", ("llama-cpp-deepseek-r1", None)),
  441. # (1024, 'none', CompletionMode.NORMAL, None, "^(<think>\\s*)?I need[\\s\\S]*?</think>\\s*To find[\\s\\S]*", "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  442. # (128, 'deepseek', None, "^Okay, let me figure out the sum of 102 and 7[\\s\\S]*", "bartowski/Qwen_QwQ-32B-GGUF:Q4_K_M", None),
  443. ])
  444. def test_thoughts(n_predict: int, reasoning_format: Literal['deepseek', 'none'] | None, expect_content: str | None, expect_reasoning_content: str | None, hf_repo: str, template_override: str | Tuple[str, str | None] | None, stream: CompletionMode):
  445. global server
  446. server.reasoning_format = reasoning_format
  447. server.jinja = True
  448. server.n_ctx = 8192 * 2
  449. server.n_predict = n_predict
  450. server.model_hf_repo = hf_repo
  451. server.model_hf_file = None
  452. if isinstance(template_override, tuple):
  453. (template_hf_repo, template_variant) = template_override
  454. server.chat_template_file = f"../../../models/templates/{template_hf_repo.replace('/', '-') + ('-' + template_variant if template_variant else '')}.jinja"
  455. assert os.path.exists(server.chat_template_file), f"Template file {server.chat_template_file} does not exist. Run `python scripts/get_chat_template.py {template_hf_repo} {template_variant} > {server.chat_template_file}` to download the template."
  456. elif isinstance(template_override, str):
  457. server.chat_template = template_override
  458. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  459. body = server.make_any_request("POST", "/v1/chat/completions", data={
  460. "max_tokens": n_predict,
  461. "messages": [
  462. {"role": "user", "content": "What's the sum of 102 and 7?"},
  463. ],
  464. "stream": stream == CompletionMode.STREAMED,
  465. }, timeout=TIMEOUT_HTTP_REQUEST)
  466. choice = body["choices"][0]
  467. assert choice["message"].get("tool_calls") is None, f'Expected no tool call in {choice["message"]}'
  468. content = choice["message"].get("content")
  469. if expect_content is None:
  470. assert choice["message"].get("content") in (None, ""), f'Expected no content in {choice["message"]}'
  471. else:
  472. assert re.match(expect_content, content), f'Expected {expect_content}, got {content}'
  473. reasoning_content = choice["message"].get("reasoning_content")
  474. if expect_reasoning_content is None:
  475. assert reasoning_content is None, f'Expected no reasoning content in {choice["message"]}'
  476. else:
  477. assert re.match(expect_reasoning_content, reasoning_content), f'Expected {expect_reasoning_content}, got {reasoning_content}'
  478. @pytest.mark.slow
  479. @pytest.mark.parametrize("stream", [CompletionMode.NORMAL, CompletionMode.STREAMED])
  480. @pytest.mark.parametrize("hf_repo,template_override", [
  481. ("bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF:Q4_K_M", None),
  482. ("bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", None),
  483. ("bartowski/Phi-3.5-mini-instruct-GGUF:Q4_K_M", "chatml"),
  484. ("bartowski/functionary-small-v3.2-GGUF:Q8_0", ("meetkai-functionary-medium-v3.2", None)),
  485. ("bartowski/functionary-small-v3.2-GGUF:Q8_0", "chatml"),
  486. # ("bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", None),
  487. ("bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M", "chatml"),
  488. ("bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", ("meta-llama-Llama-3.2-3B-Instruct", None)),
  489. ("bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", None),
  490. ("bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", ("meta-llama-Llama-3.2-3B-Instruct", None)),
  491. ("bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M", None),
  492. ("bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", None),
  493. ("bartowski/Qwen2.5-7B-Instruct-GGUF:Q4_K_M", "chatml"),
  494. ("bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", ("NousResearch/Hermes-2-Pro-Llama-3-8B", "tool_use")),
  495. ("bartowski/Hermes-2-Pro-Llama-3-8B-GGUF:Q4_K_M", "chatml"),
  496. ("bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", ("NousResearch-Hermes-3-Llama-3.1-8B", "tool_use")),
  497. ("bartowski/Hermes-3-Llama-3.1-8B-GGUF:Q4_K_M", "chatml"),
  498. ("bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", None),
  499. ("bartowski/Mistral-Nemo-Instruct-2407-GGUF:Q4_K_M", "chatml"),
  500. ("bartowski/gemma-2-2b-it-GGUF:Q4_K_M", None),
  501. ("bartowski/gemma-2-2b-it-GGUF:Q4_K_M", "chatml"),
  502. ])
  503. def test_hello_world(hf_repo: str, template_override: str | Tuple[str, str | None] | None, stream: CompletionMode):
  504. global server
  505. n_predict = 512 # High because of DeepSeek R1
  506. server.jinja = True
  507. server.n_ctx = 8192
  508. server.n_predict = n_predict
  509. server.model_hf_repo = hf_repo
  510. server.model_hf_file = None
  511. if isinstance(template_override, tuple):
  512. (template_hf_repo, template_variant) = template_override
  513. server.chat_template_file = f"../../../models/templates/{template_hf_repo.replace('/', '-') + ('-' + template_variant if template_variant else '')}.jinja"
  514. assert os.path.exists(server.chat_template_file), f"Template file {server.chat_template_file} does not exist. Run `python scripts/get_chat_template.py {template_hf_repo} {template_variant} > {server.chat_template_file}` to download the template."
  515. elif isinstance(template_override, str):
  516. server.chat_template = template_override
  517. server.start(timeout_seconds=TIMEOUT_SERVER_START)
  518. do_test_hello_world(server, stream=stream == CompletionMode.STREAMED, max_tokens=n_predict)
  519. def do_test_hello_world(server: ServerProcess, **kwargs):
  520. body = server.make_any_request("POST", "/v1/chat/completions", data={
  521. "messages": [
  522. {"role": "system", "content": "You are a tool-calling agent."},
  523. {"role": "user", "content": "say hello world with python"},
  524. ],
  525. "tools": [PYTHON_TOOL],
  526. **kwargs,
  527. }, timeout=TIMEOUT_HTTP_REQUEST)
  528. choice = body["choices"][0]
  529. tool_calls = choice["message"].get("tool_calls")
  530. assert tool_calls and len(tool_calls) == 1, f'Expected 1 tool call in {choice["message"]}'
  531. tool_call = tool_calls[0]
  532. # assert choice["message"].get("content") in (None, ""), f'Expected no content in {choice["message"]}'
  533. assert tool_call["function"]["name"] == PYTHON_TOOL["function"]["name"]
  534. # assert len(tool_call.get("id", "")) > 0, f'Expected non empty tool call id in {tool_call}'
  535. actual_arguments = json.loads(tool_call["function"]["arguments"])
  536. assert 'code' in actual_arguments, f"code not found in {json.dumps(actual_arguments)}"
  537. code = actual_arguments["code"]
  538. assert isinstance(code, str), f"Expected code to be a string, got {type(code)}: {json.dumps(code)}"
  539. assert re.match(r'''print\(("[Hh]ello,? [Ww]orld!?"|'[Hh]ello,? [Ww]orld!?')\)''', re.sub(r'#.*\n?', '', code)), f'Expected hello world, got {code}'