test_llm.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import os
  2. from collections.abc import Generator
  3. import pytest
  4. from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta
  5. from core.model_runtime.entities.message_entities import (
  6. AssistantPromptMessage,
  7. PromptMessageTool,
  8. SystemPromptMessage,
  9. UserPromptMessage,
  10. )
  11. from core.model_runtime.entities.model_entities import AIModelEntity
  12. from core.model_runtime.errors.validate import CredentialsValidateFailedError
  13. from core.model_runtime.model_providers.chatglm.llm.llm import ChatGLMLargeLanguageModel
  14. from tests.integration_tests.model_runtime.__mock.openai import setup_openai_mock
  15. def test_predefined_models():
  16. model = ChatGLMLargeLanguageModel()
  17. model_schemas = model.predefined_models()
  18. assert len(model_schemas) >= 1
  19. assert isinstance(model_schemas[0], AIModelEntity)
  20. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  21. def test_validate_credentials_for_chat_model(setup_openai_mock):
  22. model = ChatGLMLargeLanguageModel()
  23. with pytest.raises(CredentialsValidateFailedError):
  24. model.validate_credentials(model="chatglm2-6b", credentials={"api_base": "invalid_key"})
  25. model.validate_credentials(model="chatglm2-6b", credentials={"api_base": os.environ.get("CHATGLM_API_BASE")})
  26. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  27. def test_invoke_model(setup_openai_mock):
  28. model = ChatGLMLargeLanguageModel()
  29. response = model.invoke(
  30. model="chatglm2-6b",
  31. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  32. prompt_messages=[
  33. SystemPromptMessage(
  34. content="You are a helpful AI assistant.",
  35. ),
  36. UserPromptMessage(content="Hello World!"),
  37. ],
  38. model_parameters={
  39. "temperature": 0.7,
  40. "top_p": 1.0,
  41. },
  42. stop=["you"],
  43. user="abc-123",
  44. stream=False,
  45. )
  46. assert isinstance(response, LLMResult)
  47. assert len(response.message.content) > 0
  48. assert response.usage.total_tokens > 0
  49. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  50. def test_invoke_stream_model(setup_openai_mock):
  51. model = ChatGLMLargeLanguageModel()
  52. response = model.invoke(
  53. model="chatglm2-6b",
  54. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  55. prompt_messages=[
  56. SystemPromptMessage(
  57. content="You are a helpful AI assistant.",
  58. ),
  59. UserPromptMessage(content="Hello World!"),
  60. ],
  61. model_parameters={
  62. "temperature": 0.7,
  63. "top_p": 1.0,
  64. },
  65. stop=["you"],
  66. stream=True,
  67. user="abc-123",
  68. )
  69. assert isinstance(response, Generator)
  70. for chunk in response:
  71. assert isinstance(chunk, LLMResultChunk)
  72. assert isinstance(chunk.delta, LLMResultChunkDelta)
  73. assert isinstance(chunk.delta.message, AssistantPromptMessage)
  74. assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True
  75. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  76. def test_invoke_stream_model_with_functions(setup_openai_mock):
  77. model = ChatGLMLargeLanguageModel()
  78. response = model.invoke(
  79. model="chatglm3-6b",
  80. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  81. prompt_messages=[
  82. SystemPromptMessage(
  83. content="你是一个天气机器人,你不知道今天的天气怎么样,你需要通过调用一个函数来获取天气信息。"
  84. ),
  85. UserPromptMessage(content="波士顿天气如何?"),
  86. ],
  87. model_parameters={
  88. "temperature": 0,
  89. "top_p": 1.0,
  90. },
  91. stop=["you"],
  92. user="abc-123",
  93. stream=True,
  94. tools=[
  95. PromptMessageTool(
  96. name="get_current_weather",
  97. description="Get the current weather in a given location",
  98. parameters={
  99. "type": "object",
  100. "properties": {
  101. "location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
  102. "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
  103. },
  104. "required": ["location"],
  105. },
  106. )
  107. ],
  108. )
  109. assert isinstance(response, Generator)
  110. call: LLMResultChunk = None
  111. chunks = []
  112. for chunk in response:
  113. chunks.append(chunk)
  114. assert isinstance(chunk, LLMResultChunk)
  115. assert isinstance(chunk.delta, LLMResultChunkDelta)
  116. assert isinstance(chunk.delta.message, AssistantPromptMessage)
  117. assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True
  118. if chunk.delta.message.tool_calls and len(chunk.delta.message.tool_calls) > 0:
  119. call = chunk
  120. break
  121. assert call is not None
  122. assert call.delta.message.tool_calls[0].function.name == "get_current_weather"
  123. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  124. def test_invoke_model_with_functions(setup_openai_mock):
  125. model = ChatGLMLargeLanguageModel()
  126. response = model.invoke(
  127. model="chatglm3-6b",
  128. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  129. prompt_messages=[UserPromptMessage(content="What is the weather like in San Francisco?")],
  130. model_parameters={
  131. "temperature": 0.7,
  132. "top_p": 1.0,
  133. },
  134. stop=["you"],
  135. user="abc-123",
  136. stream=False,
  137. tools=[
  138. PromptMessageTool(
  139. name="get_current_weather",
  140. description="Get the current weather in a given location",
  141. parameters={
  142. "type": "object",
  143. "properties": {
  144. "location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
  145. "unit": {"type": "string", "enum": ["c", "f"]},
  146. },
  147. "required": ["location"],
  148. },
  149. )
  150. ],
  151. )
  152. assert isinstance(response, LLMResult)
  153. assert len(response.message.content) > 0
  154. assert response.usage.total_tokens > 0
  155. assert response.message.tool_calls[0].function.name == "get_current_weather"
  156. def test_get_num_tokens():
  157. model = ChatGLMLargeLanguageModel()
  158. num_tokens = model.get_num_tokens(
  159. model="chatglm2-6b",
  160. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  161. prompt_messages=[
  162. SystemPromptMessage(
  163. content="You are a helpful AI assistant.",
  164. ),
  165. UserPromptMessage(content="Hello World!"),
  166. ],
  167. tools=[
  168. PromptMessageTool(
  169. name="get_current_weather",
  170. description="Get the current weather in a given location",
  171. parameters={
  172. "type": "object",
  173. "properties": {
  174. "location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
  175. "unit": {"type": "string", "enum": ["c", "f"]},
  176. },
  177. "required": ["location"],
  178. },
  179. )
  180. ],
  181. )
  182. assert isinstance(num_tokens, int)
  183. assert num_tokens == 77
  184. num_tokens = model.get_num_tokens(
  185. model="chatglm2-6b",
  186. credentials={"api_base": os.environ.get("CHATGLM_API_BASE")},
  187. prompt_messages=[
  188. SystemPromptMessage(
  189. content="You are a helpful AI assistant.",
  190. ),
  191. UserPromptMessage(content="Hello World!"),
  192. ],
  193. )
  194. assert isinstance(num_tokens, int)
  195. assert num_tokens == 21