test_chat_completion.py 8.2 KB

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