test_tool_call.py 32 KB

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