test_chat_completion.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import pytest
  2. from openai import OpenAI
  3. from utils import *
  4. server: ServerProcess
  5. @pytest.fixture(autouse=True)
  6. def create_server():
  7. global server
  8. server = ServerPreset.tinyllama2()
  9. @pytest.mark.parametrize(
  10. "model,system_prompt,user_prompt,max_tokens,re_content,n_prompt,n_predicted,finish_reason,jinja,chat_template",
  11. [
  12. (None, "Book", "Hey", 8, "But she couldn't", 69, 8, "length", False, None),
  13. (None, "Book", "Hey", 8, "But she couldn't", 69, 8, "length", True, None),
  14. (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", False, None),
  15. (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", True, None),
  16. (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", True, 'chatml'),
  17. (None, "Book", "What is the best book", 8, "^ blue", 23, 8, "length", True, "This is not a chat template, it is"),
  18. ("codellama70b", "You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 64, "length", False, None),
  19. ("codellama70b", "You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 64, "length", True, None),
  20. (None, "Book", [{"type": "text", "text": "What is"}, {"type": "text", "text": "the best book"}], 8, "Whillicter", 79, 8, "length", False, None),
  21. (None, "Book", [{"type": "text", "text": "What is"}, {"type": "text", "text": "the best book"}], 8, "Whillicter", 79, 8, "length", True, None),
  22. ]
  23. )
  24. def test_chat_completion(model, system_prompt, user_prompt, max_tokens, re_content, n_prompt, n_predicted, finish_reason, jinja, chat_template):
  25. global server
  26. server.jinja = jinja
  27. server.chat_template = chat_template
  28. server.start()
  29. res = server.make_request("POST", "/chat/completions", data={
  30. "model": model,
  31. "max_tokens": max_tokens,
  32. "messages": [
  33. {"role": "system", "content": system_prompt},
  34. {"role": "user", "content": user_prompt},
  35. ],
  36. })
  37. assert res.status_code == 200
  38. assert "cmpl" in res.body["id"] # make sure the completion id has the expected format
  39. assert res.body["system_fingerprint"].startswith("b")
  40. assert res.body["model"] == model if model is not None else server.model_alias
  41. assert res.body["usage"]["prompt_tokens"] == n_prompt
  42. assert res.body["usage"]["completion_tokens"] == n_predicted
  43. choice = res.body["choices"][0]
  44. assert "assistant" == choice["message"]["role"]
  45. assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
  46. assert choice["finish_reason"] == finish_reason
  47. @pytest.mark.parametrize(
  48. "system_prompt,user_prompt,max_tokens,re_content,n_prompt,n_predicted,finish_reason",
  49. [
  50. ("Book", "What is the best book", 8, "(Suddenly)+", 77, 8, "length"),
  51. ("You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 64, "length"),
  52. ]
  53. )
  54. def test_chat_completion_stream(system_prompt, user_prompt, max_tokens, re_content, n_prompt, n_predicted, finish_reason):
  55. global server
  56. server.model_alias = None # try using DEFAULT_OAICOMPAT_MODEL
  57. server.start()
  58. res = server.make_stream_request("POST", "/chat/completions", data={
  59. "max_tokens": max_tokens,
  60. "messages": [
  61. {"role": "system", "content": system_prompt},
  62. {"role": "user", "content": user_prompt},
  63. ],
  64. "stream": True,
  65. })
  66. content = ""
  67. last_cmpl_id = None
  68. for i, data in enumerate(res):
  69. choice = data["choices"][0]
  70. if i == 0:
  71. # Check first role message for stream=True
  72. assert choice["delta"]["content"] == ""
  73. assert choice["delta"]["role"] == "assistant"
  74. else:
  75. assert "role" not in choice["delta"]
  76. assert data["system_fingerprint"].startswith("b")
  77. assert "gpt-3.5" in data["model"] # DEFAULT_OAICOMPAT_MODEL, maybe changed in the future
  78. if last_cmpl_id is None:
  79. last_cmpl_id = data["id"]
  80. assert last_cmpl_id == data["id"] # make sure the completion id is the same for all events in the stream
  81. if choice["finish_reason"] in ["stop", "length"]:
  82. assert data["usage"]["prompt_tokens"] == n_prompt
  83. assert data["usage"]["completion_tokens"] == n_predicted
  84. assert "content" not in choice["delta"]
  85. assert match_regex(re_content, content)
  86. assert choice["finish_reason"] == finish_reason
  87. else:
  88. assert choice["finish_reason"] is None
  89. content += choice["delta"]["content"]
  90. def test_chat_completion_with_openai_library():
  91. global server
  92. server.start()
  93. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  94. res = client.chat.completions.create(
  95. model="gpt-3.5-turbo-instruct",
  96. messages=[
  97. {"role": "system", "content": "Book"},
  98. {"role": "user", "content": "What is the best book"},
  99. ],
  100. max_tokens=8,
  101. seed=42,
  102. temperature=0.8,
  103. )
  104. assert res.system_fingerprint is not None and res.system_fingerprint.startswith("b")
  105. assert res.choices[0].finish_reason == "length"
  106. assert res.choices[0].message.content is not None
  107. assert match_regex("(Suddenly)+", res.choices[0].message.content)
  108. def test_chat_template():
  109. global server
  110. server.chat_template = "llama3"
  111. server.debug = True # to get the "__verbose" object in the response
  112. server.start()
  113. res = server.make_request("POST", "/chat/completions", data={
  114. "max_tokens": 8,
  115. "messages": [
  116. {"role": "system", "content": "Book"},
  117. {"role": "user", "content": "What is the best book"},
  118. ]
  119. })
  120. assert res.status_code == 200
  121. assert "__verbose" in res.body
  122. assert res.body["__verbose"]["prompt"] == "<s> <|start_header_id|>system<|end_header_id|>\n\nBook<|eot_id|><|start_header_id|>user<|end_header_id|>\n\nWhat is the best book<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
  123. def test_apply_chat_template():
  124. global server
  125. server.chat_template = "command-r"
  126. server.start()
  127. res = server.make_request("POST", "/apply-template", data={
  128. "messages": [
  129. {"role": "system", "content": "You are a test."},
  130. {"role": "user", "content":"Hi there"},
  131. ]
  132. })
  133. assert res.status_code == 200
  134. assert "prompt" in res.body
  135. assert res.body["prompt"] == "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>You are a test.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hi there<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>"
  136. @pytest.mark.parametrize("response_format,n_predicted,re_content", [
  137. ({"type": "json_object", "schema": {"const": "42"}}, 6, "\"42\""),
  138. ({"type": "json_object", "schema": {"items": [{"type": "integer"}]}}, 10, "[ -3000 ]"),
  139. ({"type": "json_schema", "json_schema": {"schema": {"const": "foooooo"}}}, 10, "\"foooooo\""),
  140. ({"type": "json_object"}, 10, "(\\{|John)+"),
  141. ({"type": "sound"}, 0, None),
  142. # invalid response format (expected to fail)
  143. ({"type": "json_object", "schema": 123}, 0, None),
  144. ({"type": "json_object", "schema": {"type": 123}}, 0, None),
  145. ({"type": "json_object", "schema": {"type": "hiccup"}}, 0, None),
  146. ])
  147. def test_completion_with_response_format(response_format: dict, n_predicted: int, re_content: str | None):
  148. global server
  149. server.start()
  150. res = server.make_request("POST", "/chat/completions", data={
  151. "max_tokens": n_predicted,
  152. "messages": [
  153. {"role": "system", "content": "You are a coding assistant."},
  154. {"role": "user", "content": "Write an example"},
  155. ],
  156. "response_format": response_format,
  157. })
  158. if re_content is not None:
  159. assert res.status_code == 200
  160. choice = res.body["choices"][0]
  161. assert match_regex(re_content, choice["message"]["content"])
  162. else:
  163. assert res.status_code != 200
  164. assert "error" in res.body
  165. @pytest.mark.parametrize("jinja,json_schema,n_predicted,re_content", [
  166. (False, {"const": "42"}, 6, "\"42\""),
  167. (True, {"const": "42"}, 6, "\"42\""),
  168. ])
  169. def test_completion_with_json_schema(jinja: bool, json_schema: dict, n_predicted: int, re_content: str):
  170. global server
  171. server.jinja = jinja
  172. server.start()
  173. res = server.make_request("POST", "/chat/completions", data={
  174. "max_tokens": n_predicted,
  175. "messages": [
  176. {"role": "system", "content": "You are a coding assistant."},
  177. {"role": "user", "content": "Write an example"},
  178. ],
  179. "json_schema": json_schema,
  180. })
  181. assert res.status_code == 200, f'Expected 200, got {res.status_code}'
  182. choice = res.body["choices"][0]
  183. assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
  184. @pytest.mark.parametrize("jinja,grammar,n_predicted,re_content", [
  185. (False, 'root ::= "a"{5,5}', 6, "a{5,5}"),
  186. (True, 'root ::= "a"{5,5}', 6, "a{5,5}"),
  187. ])
  188. def test_completion_with_grammar(jinja: bool, grammar: str, n_predicted: int, re_content: str):
  189. global server
  190. server.jinja = jinja
  191. server.start()
  192. res = server.make_request("POST", "/chat/completions", data={
  193. "max_tokens": n_predicted,
  194. "messages": [
  195. {"role": "user", "content": "Does not matter what I say, does it?"},
  196. ],
  197. "grammar": grammar,
  198. })
  199. assert res.status_code == 200, res.body
  200. choice = res.body["choices"][0]
  201. assert match_regex(re_content, choice["message"]["content"]), choice["message"]["content"]
  202. @pytest.mark.parametrize("messages", [
  203. None,
  204. "string",
  205. [123],
  206. [{}],
  207. [{"role": 123}],
  208. [{"role": "system", "content": 123}],
  209. # [{"content": "hello"}], # TODO: should not be a valid case
  210. [{"role": "system", "content": "test"}, {}],
  211. ])
  212. def test_invalid_chat_completion_req(messages):
  213. global server
  214. server.start()
  215. res = server.make_request("POST", "/chat/completions", data={
  216. "messages": messages,
  217. })
  218. assert res.status_code == 400 or res.status_code == 500
  219. assert "error" in res.body
  220. def test_chat_completion_with_timings_per_token():
  221. global server
  222. server.start()
  223. res = server.make_stream_request("POST", "/chat/completions", data={
  224. "max_tokens": 10,
  225. "messages": [{"role": "user", "content": "test"}],
  226. "stream": True,
  227. "timings_per_token": True,
  228. })
  229. for i, data in enumerate(res):
  230. if i == 0:
  231. # Check first role message for stream=True
  232. assert data["choices"][0]["delta"]["content"] == ""
  233. assert data["choices"][0]["delta"]["role"] == "assistant"
  234. else:
  235. assert "role" not in data["choices"][0]["delta"]
  236. assert "timings" in data
  237. assert "prompt_per_second" in data["timings"]
  238. assert "predicted_per_second" in data["timings"]
  239. assert "predicted_n" in data["timings"]
  240. assert data["timings"]["predicted_n"] <= 10
  241. def test_logprobs():
  242. global server
  243. server.start()
  244. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  245. res = client.chat.completions.create(
  246. model="gpt-3.5-turbo-instruct",
  247. temperature=0.0,
  248. messages=[
  249. {"role": "system", "content": "Book"},
  250. {"role": "user", "content": "What is the best book"},
  251. ],
  252. max_tokens=5,
  253. logprobs=True,
  254. top_logprobs=10,
  255. )
  256. output_text = res.choices[0].message.content
  257. aggregated_text = ''
  258. assert res.choices[0].logprobs is not None
  259. assert res.choices[0].logprobs.content is not None
  260. for token in res.choices[0].logprobs.content:
  261. aggregated_text += token.token
  262. assert token.logprob <= 0.0
  263. assert token.bytes is not None
  264. assert len(token.top_logprobs) > 0
  265. assert aggregated_text == output_text
  266. def test_logprobs_stream():
  267. global server
  268. server.start()
  269. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  270. res = client.chat.completions.create(
  271. model="gpt-3.5-turbo-instruct",
  272. temperature=0.0,
  273. messages=[
  274. {"role": "system", "content": "Book"},
  275. {"role": "user", "content": "What is the best book"},
  276. ],
  277. max_tokens=5,
  278. logprobs=True,
  279. top_logprobs=10,
  280. stream=True,
  281. )
  282. output_text = ''
  283. aggregated_text = ''
  284. for i, data in enumerate(res):
  285. choice = data.choices[0]
  286. if i == 0:
  287. # Check first role message for stream=True
  288. assert choice.delta.content == ""
  289. assert choice.delta.role == "assistant"
  290. else:
  291. assert choice.delta.role is None
  292. if choice.finish_reason is None:
  293. if choice.delta.content:
  294. output_text += choice.delta.content
  295. assert choice.logprobs is not None
  296. assert choice.logprobs.content is not None
  297. for token in choice.logprobs.content:
  298. aggregated_text += token.token
  299. assert token.logprob <= 0.0
  300. assert token.bytes is not None
  301. assert token.top_logprobs is not None
  302. assert len(token.top_logprobs) > 0
  303. assert aggregated_text == output_text