test_chat_completion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 data in res:
  69. choice = data["choices"][0]
  70. assert data["system_fingerprint"].startswith("b")
  71. assert "gpt-3.5" in data["model"] # DEFAULT_OAICOMPAT_MODEL, maybe changed in the future
  72. if last_cmpl_id is None:
  73. last_cmpl_id = data["id"]
  74. assert last_cmpl_id == data["id"] # make sure the completion id is the same for all events in the stream
  75. if choice["finish_reason"] in ["stop", "length"]:
  76. assert data["usage"]["prompt_tokens"] == n_prompt
  77. assert data["usage"]["completion_tokens"] == n_predicted
  78. assert "content" not in choice["delta"]
  79. assert match_regex(re_content, content)
  80. assert choice["finish_reason"] == finish_reason
  81. else:
  82. assert choice["finish_reason"] is None
  83. content += choice["delta"]["content"]
  84. def test_chat_completion_with_openai_library():
  85. global server
  86. server.start()
  87. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  88. res = client.chat.completions.create(
  89. model="gpt-3.5-turbo-instruct",
  90. messages=[
  91. {"role": "system", "content": "Book"},
  92. {"role": "user", "content": "What is the best book"},
  93. ],
  94. max_tokens=8,
  95. seed=42,
  96. temperature=0.8,
  97. )
  98. assert res.system_fingerprint is not None and res.system_fingerprint.startswith("b")
  99. assert res.choices[0].finish_reason == "length"
  100. assert res.choices[0].message.content is not None
  101. assert match_regex("(Suddenly)+", res.choices[0].message.content)
  102. def test_chat_template():
  103. global server
  104. server.chat_template = "llama3"
  105. server.debug = True # to get the "__verbose" object in the response
  106. server.start()
  107. res = server.make_request("POST", "/chat/completions", data={
  108. "max_tokens": 8,
  109. "messages": [
  110. {"role": "system", "content": "Book"},
  111. {"role": "user", "content": "What is the best book"},
  112. ]
  113. })
  114. assert res.status_code == 200
  115. assert "__verbose" in res.body
  116. 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"
  117. def test_apply_chat_template():
  118. global server
  119. server.chat_template = "command-r"
  120. server.start()
  121. res = server.make_request("POST", "/apply-template", data={
  122. "messages": [
  123. {"role": "system", "content": "You are a test."},
  124. {"role": "user", "content":"Hi there"},
  125. ]
  126. })
  127. assert res.status_code == 200
  128. assert "prompt" in res.body
  129. 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|>"
  130. @pytest.mark.parametrize("response_format,n_predicted,re_content", [
  131. ({"type": "json_object", "schema": {"const": "42"}}, 6, "\"42\""),
  132. ({"type": "json_object", "schema": {"items": [{"type": "integer"}]}}, 10, "[ -3000 ]"),
  133. ({"type": "json_object"}, 10, "(\\{|John)+"),
  134. ({"type": "sound"}, 0, None),
  135. # invalid response format (expected to fail)
  136. ({"type": "json_object", "schema": 123}, 0, None),
  137. ({"type": "json_object", "schema": {"type": 123}}, 0, None),
  138. ({"type": "json_object", "schema": {"type": "hiccup"}}, 0, None),
  139. ])
  140. def test_completion_with_response_format(response_format: dict, n_predicted: int, re_content: str | None):
  141. global server
  142. server.start()
  143. res = server.make_request("POST", "/chat/completions", data={
  144. "max_tokens": n_predicted,
  145. "messages": [
  146. {"role": "system", "content": "You are a coding assistant."},
  147. {"role": "user", "content": "Write an example"},
  148. ],
  149. "response_format": response_format,
  150. })
  151. if re_content is not None:
  152. assert res.status_code == 200
  153. choice = res.body["choices"][0]
  154. assert match_regex(re_content, choice["message"]["content"])
  155. else:
  156. assert res.status_code != 200
  157. assert "error" in res.body
  158. @pytest.mark.parametrize("jinja,json_schema,n_predicted,re_content", [
  159. (False, {"const": "42"}, 6, "\"42\""),
  160. (True, {"const": "42"}, 6, "\"42\""),
  161. ])
  162. def test_completion_with_json_schema(jinja: bool, json_schema: dict, n_predicted: int, re_content: str):
  163. global server
  164. server.jinja = jinja
  165. server.start()
  166. res = server.make_request("POST", "/chat/completions", data={
  167. "max_tokens": n_predicted,
  168. "messages": [
  169. {"role": "system", "content": "You are a coding assistant."},
  170. {"role": "user", "content": "Write an example"},
  171. ],
  172. "json_schema": json_schema,
  173. })
  174. assert res.status_code == 200, f'Expected 200, got {res.status_code}'
  175. choice = res.body["choices"][0]
  176. assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
  177. @pytest.mark.parametrize("jinja,grammar,n_predicted,re_content", [
  178. (False, 'root ::= "a"{5,5}', 6, "a{5,5}"),
  179. (True, 'root ::= "a"{5,5}', 6, "a{5,5}"),
  180. ])
  181. def test_completion_with_grammar(jinja: bool, grammar: str, n_predicted: int, re_content: str):
  182. global server
  183. server.jinja = jinja
  184. server.start()
  185. res = server.make_request("POST", "/chat/completions", data={
  186. "max_tokens": n_predicted,
  187. "messages": [
  188. {"role": "user", "content": "Does not matter what I say, does it?"},
  189. ],
  190. "grammar": grammar,
  191. })
  192. assert res.status_code == 200, res.body
  193. choice = res.body["choices"][0]
  194. assert match_regex(re_content, choice["message"]["content"]), choice["message"]["content"]
  195. @pytest.mark.parametrize("messages", [
  196. None,
  197. "string",
  198. [123],
  199. [{}],
  200. [{"role": 123}],
  201. [{"role": "system", "content": 123}],
  202. # [{"content": "hello"}], # TODO: should not be a valid case
  203. [{"role": "system", "content": "test"}, {}],
  204. ])
  205. def test_invalid_chat_completion_req(messages):
  206. global server
  207. server.start()
  208. res = server.make_request("POST", "/chat/completions", data={
  209. "messages": messages,
  210. })
  211. assert res.status_code == 400 or res.status_code == 500
  212. assert "error" in res.body
  213. def test_chat_completion_with_timings_per_token():
  214. global server
  215. server.start()
  216. res = server.make_stream_request("POST", "/chat/completions", data={
  217. "max_tokens": 10,
  218. "messages": [{"role": "user", "content": "test"}],
  219. "stream": True,
  220. "timings_per_token": True,
  221. })
  222. for data in res:
  223. assert "timings" in data
  224. assert "prompt_per_second" in data["timings"]
  225. assert "predicted_per_second" in data["timings"]
  226. assert "predicted_n" in data["timings"]
  227. assert data["timings"]["predicted_n"] <= 10
  228. def test_logprobs():
  229. global server
  230. server.start()
  231. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  232. res = client.chat.completions.create(
  233. model="gpt-3.5-turbo-instruct",
  234. temperature=0.0,
  235. messages=[
  236. {"role": "system", "content": "Book"},
  237. {"role": "user", "content": "What is the best book"},
  238. ],
  239. max_tokens=5,
  240. logprobs=True,
  241. top_logprobs=10,
  242. )
  243. output_text = res.choices[0].message.content
  244. aggregated_text = ''
  245. assert res.choices[0].logprobs is not None
  246. assert res.choices[0].logprobs.content is not None
  247. for token in res.choices[0].logprobs.content:
  248. aggregated_text += token.token
  249. assert token.logprob <= 0.0
  250. assert token.bytes is not None
  251. assert len(token.top_logprobs) > 0
  252. assert aggregated_text == output_text
  253. def test_logprobs_stream():
  254. global server
  255. server.start()
  256. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
  257. res = client.chat.completions.create(
  258. model="gpt-3.5-turbo-instruct",
  259. temperature=0.0,
  260. messages=[
  261. {"role": "system", "content": "Book"},
  262. {"role": "user", "content": "What is the best book"},
  263. ],
  264. max_tokens=5,
  265. logprobs=True,
  266. top_logprobs=10,
  267. stream=True,
  268. )
  269. output_text = ''
  270. aggregated_text = ''
  271. for data in res:
  272. choice = data.choices[0]
  273. if choice.finish_reason is None:
  274. if choice.delta.content:
  275. output_text += choice.delta.content
  276. assert choice.logprobs is not None
  277. assert choice.logprobs.content is not None
  278. for token in choice.logprobs.content:
  279. aggregated_text += token.token
  280. assert token.logprob <= 0.0
  281. assert token.bytes is not None
  282. assert token.top_logprobs is not None
  283. assert len(token.top_logprobs) > 0
  284. assert aggregated_text == output_text