test_llm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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(
  26. model='chatglm2-6b',
  27. credentials={
  28. 'api_base': 'invalid_key'
  29. }
  30. )
  31. model.validate_credentials(
  32. model='chatglm2-6b',
  33. credentials={
  34. 'api_base': os.environ.get('CHATGLM_API_BASE')
  35. }
  36. )
  37. @pytest.mark.parametrize('setup_openai_mock', [['chat']], indirect=True)
  38. def test_invoke_model(setup_openai_mock):
  39. model = ChatGLMLargeLanguageModel()
  40. response = model.invoke(
  41. model='chatglm2-6b',
  42. credentials={
  43. 'api_base': os.environ.get('CHATGLM_API_BASE')
  44. },
  45. prompt_messages=[
  46. SystemPromptMessage(
  47. content='You are a helpful AI assistant.',
  48. ),
  49. UserPromptMessage(
  50. content='Hello World!'
  51. )
  52. ],
  53. model_parameters={
  54. 'temperature': 0.7,
  55. 'top_p': 1.0,
  56. },
  57. stop=['you'],
  58. user="abc-123",
  59. stream=False
  60. )
  61. assert isinstance(response, LLMResult)
  62. assert len(response.message.content) > 0
  63. assert response.usage.total_tokens > 0
  64. @pytest.mark.parametrize('setup_openai_mock', [['chat']], indirect=True)
  65. def test_invoke_stream_model(setup_openai_mock):
  66. model = ChatGLMLargeLanguageModel()
  67. response = model.invoke(
  68. model='chatglm2-6b',
  69. credentials={
  70. 'api_base': os.environ.get('CHATGLM_API_BASE')
  71. },
  72. prompt_messages=[
  73. SystemPromptMessage(
  74. content='You are a helpful AI assistant.',
  75. ),
  76. UserPromptMessage(
  77. content='Hello World!'
  78. )
  79. ],
  80. model_parameters={
  81. 'temperature': 0.7,
  82. 'top_p': 1.0,
  83. },
  84. stop=['you'],
  85. stream=True,
  86. user="abc-123"
  87. )
  88. assert isinstance(response, Generator)
  89. for chunk in response:
  90. assert isinstance(chunk, LLMResultChunk)
  91. assert isinstance(chunk.delta, LLMResultChunkDelta)
  92. assert isinstance(chunk.delta.message, AssistantPromptMessage)
  93. assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True
  94. @pytest.mark.parametrize('setup_openai_mock', [['chat']], indirect=True)
  95. def test_invoke_stream_model_with_functions(setup_openai_mock):
  96. model = ChatGLMLargeLanguageModel()
  97. response = model.invoke(
  98. model='chatglm3-6b',
  99. credentials={
  100. 'api_base': os.environ.get('CHATGLM_API_BASE')
  101. },
  102. prompt_messages=[
  103. SystemPromptMessage(
  104. content='你是一个天气机器人,你不知道今天的天气怎么样,你需要通过调用一个函数来获取天气信息。'
  105. ),
  106. UserPromptMessage(
  107. content='波士顿天气如何?'
  108. )
  109. ],
  110. model_parameters={
  111. 'temperature': 0,
  112. 'top_p': 1.0,
  113. },
  114. stop=['you'],
  115. user='abc-123',
  116. stream=True,
  117. tools=[
  118. PromptMessageTool(
  119. name='get_current_weather',
  120. description='Get the current weather in a given location',
  121. parameters={
  122. "type": "object",
  123. "properties": {
  124. "location": {
  125. "type": "string",
  126. "description": "The city and state e.g. San Francisco, CA"
  127. },
  128. "unit": {
  129. "type": "string",
  130. "enum": ["celsius", "fahrenheit"]
  131. }
  132. },
  133. "required": [
  134. "location"
  135. ]
  136. }
  137. )
  138. ]
  139. )
  140. assert isinstance(response, Generator)
  141. call: LLMResultChunk = None
  142. chunks = []
  143. for chunk in response:
  144. chunks.append(chunk)
  145. assert isinstance(chunk, LLMResultChunk)
  146. assert isinstance(chunk.delta, LLMResultChunkDelta)
  147. assert isinstance(chunk.delta.message, AssistantPromptMessage)
  148. assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True
  149. if chunk.delta.message.tool_calls and len(chunk.delta.message.tool_calls) > 0:
  150. call = chunk
  151. break
  152. assert call is not None
  153. assert call.delta.message.tool_calls[0].function.name == 'get_current_weather'
  154. @pytest.mark.parametrize('setup_openai_mock', [['chat']], indirect=True)
  155. def test_invoke_model_with_functions(setup_openai_mock):
  156. model = ChatGLMLargeLanguageModel()
  157. response = model.invoke(
  158. model='chatglm3-6b',
  159. credentials={
  160. 'api_base': os.environ.get('CHATGLM_API_BASE')
  161. },
  162. prompt_messages=[
  163. UserPromptMessage(
  164. content='What is the weather like in San Francisco?'
  165. )
  166. ],
  167. model_parameters={
  168. 'temperature': 0.7,
  169. 'top_p': 1.0,
  170. },
  171. stop=['you'],
  172. user='abc-123',
  173. stream=False,
  174. tools=[
  175. PromptMessageTool(
  176. name='get_current_weather',
  177. description='Get the current weather in a given location',
  178. parameters={
  179. "type": "object",
  180. "properties": {
  181. "location": {
  182. "type": "string",
  183. "description": "The city and state e.g. San Francisco, CA"
  184. },
  185. "unit": {
  186. "type": "string",
  187. "enum": [
  188. "c",
  189. "f"
  190. ]
  191. }
  192. },
  193. "required": [
  194. "location"
  195. ]
  196. }
  197. )
  198. ]
  199. )
  200. assert isinstance(response, LLMResult)
  201. assert len(response.message.content) > 0
  202. assert response.usage.total_tokens > 0
  203. assert response.message.tool_calls[0].function.name == 'get_current_weather'
  204. def test_get_num_tokens():
  205. model = ChatGLMLargeLanguageModel()
  206. num_tokens = model.get_num_tokens(
  207. model='chatglm2-6b',
  208. credentials={
  209. 'api_base': os.environ.get('CHATGLM_API_BASE')
  210. },
  211. prompt_messages=[
  212. SystemPromptMessage(
  213. content='You are a helpful AI assistant.',
  214. ),
  215. UserPromptMessage(
  216. content='Hello World!'
  217. )
  218. ],
  219. tools=[
  220. PromptMessageTool(
  221. name='get_current_weather',
  222. description='Get the current weather in a given location',
  223. parameters={
  224. "type": "object",
  225. "properties": {
  226. "location": {
  227. "type": "string",
  228. "description": "The city and state e.g. San Francisco, CA"
  229. },
  230. "unit": {
  231. "type": "string",
  232. "enum": [
  233. "c",
  234. "f"
  235. ]
  236. }
  237. },
  238. "required": [
  239. "location"
  240. ]
  241. }
  242. )
  243. ]
  244. )
  245. assert isinstance(num_tokens, int)
  246. assert num_tokens == 77
  247. num_tokens = model.get_num_tokens(
  248. model='chatglm2-6b',
  249. credentials={
  250. 'api_base': os.environ.get('CHATGLM_API_BASE')
  251. },
  252. prompt_messages=[
  253. SystemPromptMessage(
  254. content='You are a helpful AI assistant.',
  255. ),
  256. UserPromptMessage(
  257. content='Hello World!'
  258. )
  259. ],
  260. )
  261. assert isinstance(num_tokens, int)
  262. assert num_tokens == 21