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