test_llm.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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.x.llm.llm import XAILargeLanguageModel
  14. """FOR MOCK FIXTURES, DO NOT REMOVE"""
  15. from tests.integration_tests.model_runtime.__mock.openai import setup_openai_mock
  16. def test_predefined_models():
  17. model = XAILargeLanguageModel()
  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 = XAILargeLanguageModel()
  24. with pytest.raises(CredentialsValidateFailedError):
  25. # model name to gpt-3.5-turbo because of mocking
  26. model.validate_credentials(
  27. model="gpt-3.5-turbo",
  28. credentials={"api_key": "invalid_key", "endpoint_url": os.environ.get("XAI_API_BASE"), "mode": "chat"},
  29. )
  30. model.validate_credentials(
  31. model="grok-beta",
  32. credentials={
  33. "api_key": os.environ.get("XAI_API_KEY"),
  34. "endpoint_url": os.environ.get("XAI_API_BASE"),
  35. "mode": "chat",
  36. },
  37. )
  38. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  39. def test_invoke_chat_model(setup_openai_mock):
  40. model = XAILargeLanguageModel()
  41. result = model.invoke(
  42. model="grok-beta",
  43. credentials={
  44. "api_key": os.environ.get("XAI_API_KEY"),
  45. "endpoint_url": os.environ.get("XAI_API_BASE"),
  46. "mode": "chat",
  47. },
  48. prompt_messages=[
  49. SystemPromptMessage(
  50. content="You are a helpful AI assistant.",
  51. ),
  52. UserPromptMessage(content="Hello World!"),
  53. ],
  54. model_parameters={
  55. "temperature": 0.0,
  56. "top_p": 1.0,
  57. "presence_penalty": 0.0,
  58. "frequency_penalty": 0.0,
  59. "max_tokens": 10,
  60. },
  61. stop=["How"],
  62. stream=False,
  63. user="foo",
  64. )
  65. assert isinstance(result, LLMResult)
  66. assert len(result.message.content) > 0
  67. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  68. def test_invoke_chat_model_with_tools(setup_openai_mock):
  69. model = XAILargeLanguageModel()
  70. result = model.invoke(
  71. model="grok-beta",
  72. credentials={
  73. "api_key": os.environ.get("XAI_API_KEY"),
  74. "endpoint_url": os.environ.get("XAI_API_BASE"),
  75. "mode": "chat",
  76. },
  77. prompt_messages=[
  78. SystemPromptMessage(
  79. content="You are a helpful AI assistant.",
  80. ),
  81. UserPromptMessage(
  82. content="what's the weather today in London?",
  83. ),
  84. ],
  85. model_parameters={"temperature": 0.0, "max_tokens": 100},
  86. tools=[
  87. PromptMessageTool(
  88. name="get_weather",
  89. description="Determine weather in my location",
  90. parameters={
  91. "type": "object",
  92. "properties": {
  93. "location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
  94. "unit": {"type": "string", "enum": ["c", "f"]},
  95. },
  96. "required": ["location"],
  97. },
  98. ),
  99. PromptMessageTool(
  100. name="get_stock_price",
  101. description="Get the current stock price",
  102. parameters={
  103. "type": "object",
  104. "properties": {"symbol": {"type": "string", "description": "The stock symbol"}},
  105. "required": ["symbol"],
  106. },
  107. ),
  108. ],
  109. stream=False,
  110. user="foo",
  111. )
  112. assert isinstance(result, LLMResult)
  113. assert isinstance(result.message, AssistantPromptMessage)
  114. @pytest.mark.parametrize("setup_openai_mock", [["chat"]], indirect=True)
  115. def test_invoke_stream_chat_model(setup_openai_mock):
  116. model = XAILargeLanguageModel()
  117. result = model.invoke(
  118. model="grok-beta",
  119. credentials={
  120. "api_key": os.environ.get("XAI_API_KEY"),
  121. "endpoint_url": os.environ.get("XAI_API_BASE"),
  122. "mode": "chat",
  123. },
  124. prompt_messages=[
  125. SystemPromptMessage(
  126. content="You are a helpful AI assistant.",
  127. ),
  128. UserPromptMessage(content="Hello World!"),
  129. ],
  130. model_parameters={"temperature": 0.0, "max_tokens": 100},
  131. stream=True,
  132. user="foo",
  133. )
  134. assert isinstance(result, Generator)
  135. for chunk in result:
  136. assert isinstance(chunk, LLMResultChunk)
  137. assert isinstance(chunk.delta, LLMResultChunkDelta)
  138. assert isinstance(chunk.delta.message, AssistantPromptMessage)
  139. assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True
  140. if chunk.delta.finish_reason is not None:
  141. assert chunk.delta.usage is not None
  142. assert chunk.delta.usage.completion_tokens > 0
  143. def test_get_num_tokens():
  144. model = XAILargeLanguageModel()
  145. num_tokens = model.get_num_tokens(
  146. model="grok-beta",
  147. credentials={"api_key": os.environ.get("XAI_API_KEY"), "endpoint_url": os.environ.get("XAI_API_BASE")},
  148. prompt_messages=[UserPromptMessage(content="Hello World!")],
  149. )
  150. assert num_tokens == 10
  151. num_tokens = model.get_num_tokens(
  152. model="grok-beta",
  153. credentials={"api_key": os.environ.get("XAI_API_KEY"), "endpoint_url": os.environ.get("XAI_API_BASE")},
  154. prompt_messages=[
  155. SystemPromptMessage(
  156. content="You are a helpful AI assistant.",
  157. ),
  158. UserPromptMessage(content="Hello World!"),
  159. ],
  160. tools=[
  161. PromptMessageTool(
  162. name="get_weather",
  163. description="Determine weather in my location",
  164. parameters={
  165. "type": "object",
  166. "properties": {
  167. "location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
  168. "unit": {"type": "string", "enum": ["c", "f"]},
  169. },
  170. "required": ["location"],
  171. },
  172. ),
  173. ],
  174. )
  175. assert num_tokens == 77