client.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import unittest
  2. from g4f.client import Client, ChatCompletion, ChatCompletionChunk
  3. from .mocks import AsyncGeneratorProviderMock, ModelProviderMock, YieldProviderMock
  4. DEFAULT_MESSAGES = [{'role': 'user', 'content': 'Hello'}]
  5. class TestPassModel(unittest.TestCase):
  6. def test_response(self):
  7. client = Client(provider=AsyncGeneratorProviderMock)
  8. response = client.chat.completions.create(DEFAULT_MESSAGES, "")
  9. self.assertIsInstance(response, ChatCompletion)
  10. self.assertEqual("Mock", response.choices[0].message.content)
  11. def test_pass_model(self):
  12. client = Client(provider=ModelProviderMock)
  13. response = client.chat.completions.create(DEFAULT_MESSAGES, "Hello")
  14. self.assertIsInstance(response, ChatCompletion)
  15. self.assertEqual("Hello", response.choices[0].message.content)
  16. def test_max_tokens(self):
  17. client = Client(provider=YieldProviderMock)
  18. messages = [{'role': 'user', 'content': chunk} for chunk in ["How ", "are ", "you", "?"]]
  19. response = client.chat.completions.create(messages, "Hello", max_tokens=1)
  20. self.assertIsInstance(response, ChatCompletion)
  21. self.assertEqual("How ", response.choices[0].message.content)
  22. response = client.chat.completions.create(messages, "Hello", max_tokens=2)
  23. self.assertIsInstance(response, ChatCompletion)
  24. self.assertEqual("How are ", response.choices[0].message.content)
  25. def test_max_stream(self):
  26. client = Client(provider=YieldProviderMock)
  27. messages = [{'role': 'user', 'content': chunk} for chunk in ["How ", "are ", "you", "?"]]
  28. response = client.chat.completions.create(messages, "Hello", stream=True)
  29. for chunk in response:
  30. self.assertIsInstance(chunk, ChatCompletionChunk)
  31. self.assertIsInstance(chunk.choices[0].delta.content, str)
  32. messages = [{'role': 'user', 'content': chunk} for chunk in ["You ", "You ", "Other", "?"]]
  33. response = client.chat.completions.create(messages, "Hello", stream=True, max_tokens=2)
  34. response = list(response)
  35. self.assertEqual(len(response), 2)
  36. for chunk in response:
  37. self.assertEqual(chunk.choices[0].delta.content, "You ")
  38. def no_test_stop(self):
  39. client = Client(provider=YieldProviderMock)
  40. messages = [{'role': 'user', 'content': chunk} for chunk in ["How ", "are ", "you", "?"]]
  41. response = client.chat.completions.create(messages, "Hello", stop=["and"])
  42. self.assertIsInstance(response, ChatCompletion)
  43. self.assertEqual("How are you?", response.choices[0].message.content)
  44. if __name__ == '__main__':
  45. unittest.main()