1
0

test_chat_completion.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 res.body["model"] == model if model is not None else server.model_alias
  29. assert res.body["usage"]["prompt_tokens"] == n_prompt
  30. assert res.body["usage"]["completion_tokens"] == n_predicted
  31. choice = res.body["choices"][0]
  32. assert "assistant" == choice["message"]["role"]
  33. assert match_regex(re_content, choice["message"]["content"])
  34. assert choice["finish_reason"] == finish_reason
  35. @pytest.mark.parametrize(
  36. "system_prompt,user_prompt,max_tokens,re_content,n_prompt,n_predicted,finish_reason",
  37. [
  38. ("Book", "What is the best book", 8, "(Suddenly)+", 77, 8, "length"),
  39. ("You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 64, "length"),
  40. ]
  41. )
  42. def test_chat_completion_stream(system_prompt, user_prompt, max_tokens, re_content, n_prompt, n_predicted, finish_reason):
  43. global server
  44. server.model_alias = None # try using DEFAULT_OAICOMPAT_MODEL
  45. server.start()
  46. res = server.make_stream_request("POST", "/chat/completions", data={
  47. "max_tokens": max_tokens,
  48. "messages": [
  49. {"role": "system", "content": system_prompt},
  50. {"role": "user", "content": user_prompt},
  51. ],
  52. "stream": True,
  53. })
  54. content = ""
  55. for data in res:
  56. choice = data["choices"][0]
  57. assert "gpt-3.5" in data["model"] # DEFAULT_OAICOMPAT_MODEL, maybe changed in the future
  58. if choice["finish_reason"] in ["stop", "length"]:
  59. assert data["usage"]["prompt_tokens"] == n_prompt
  60. assert data["usage"]["completion_tokens"] == n_predicted
  61. assert "content" not in choice["delta"]
  62. assert match_regex(re_content, content)
  63. assert choice["finish_reason"] == finish_reason
  64. else:
  65. assert choice["finish_reason"] is None
  66. content += choice["delta"]["content"]
  67. def test_chat_completion_with_openai_library():
  68. global server
  69. server.start()
  70. client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}")
  71. res = client.chat.completions.create(
  72. model="gpt-3.5-turbo-instruct",
  73. messages=[
  74. {"role": "system", "content": "Book"},
  75. {"role": "user", "content": "What is the best book"},
  76. ],
  77. max_tokens=8,
  78. seed=42,
  79. temperature=0.8,
  80. )
  81. print(res)
  82. assert res.choices[0].finish_reason == "length"
  83. assert res.choices[0].message.content is not None
  84. assert match_regex("(Suddenly)+", res.choices[0].message.content)
  85. @pytest.mark.parametrize("response_format,n_predicted,re_content", [
  86. ({"type": "json_object", "schema": {"const": "42"}}, 6, "\"42\""),
  87. ({"type": "json_object", "schema": {"items": [{"type": "integer"}]}}, 10, "[ -3000 ]"),
  88. ({"type": "json_object"}, 10, "(\\{|John)+"),
  89. ({"type": "sound"}, 0, None),
  90. # invalid response format (expected to fail)
  91. ({"type": "json_object", "schema": 123}, 0, None),
  92. ({"type": "json_object", "schema": {"type": 123}}, 0, None),
  93. ({"type": "json_object", "schema": {"type": "hiccup"}}, 0, None),
  94. ])
  95. def test_completion_with_response_format(response_format: dict, n_predicted: int, re_content: str | None):
  96. global server
  97. server.start()
  98. res = server.make_request("POST", "/chat/completions", data={
  99. "max_tokens": n_predicted,
  100. "messages": [
  101. {"role": "system", "content": "You are a coding assistant."},
  102. {"role": "user", "content": "Write an example"},
  103. ],
  104. "response_format": response_format,
  105. })
  106. if re_content is not None:
  107. assert res.status_code == 200
  108. choice = res.body["choices"][0]
  109. assert match_regex(re_content, choice["message"]["content"])
  110. else:
  111. assert res.status_code != 200
  112. assert "error" in res.body
  113. @pytest.mark.parametrize("messages", [
  114. None,
  115. "string",
  116. [123],
  117. [{}],
  118. [{"role": 123}],
  119. [{"role": "system", "content": 123}],
  120. # [{"content": "hello"}], # TODO: should not be a valid case
  121. [{"role": "system", "content": "test"}, {}],
  122. ])
  123. def test_invalid_chat_completion_req(messages):
  124. global server
  125. server.start()
  126. res = server.make_request("POST", "/chat/completions", data={
  127. "messages": messages,
  128. })
  129. assert res.status_code == 400 or res.status_code == 500
  130. assert "error" in res.body
  131. def test_chat_completion_with_timings_per_token():
  132. global server
  133. server.start()
  134. res = server.make_stream_request("POST", "/chat/completions", data={
  135. "max_tokens": 10,
  136. "messages": [{"role": "user", "content": "test"}],
  137. "stream": True,
  138. "timings_per_token": True,
  139. })
  140. for data in res:
  141. assert "timings" in data
  142. assert "prompt_per_second" in data["timings"]
  143. assert "predicted_per_second" in data["timings"]
  144. assert "predicted_n" in data["timings"]
  145. assert data["timings"]["predicted_n"] <= 10