test_chat_completion.py 10 KB

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