openai_chat.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import re
  2. from collections.abc import Generator
  3. from json import dumps, loads
  4. from time import time
  5. # import monkeypatch
  6. from typing import Any, Literal, Optional, Union
  7. import openai.types.chat.completion_create_params as completion_create_params
  8. from openai import AzureOpenAI, OpenAI
  9. from openai._types import NOT_GIVEN, NotGiven
  10. from openai.resources.chat.completions import Completions
  11. from openai.types import Completion as CompletionMessage
  12. from openai.types.chat import (
  13. ChatCompletion,
  14. ChatCompletionChunk,
  15. ChatCompletionMessageParam,
  16. ChatCompletionMessageToolCall,
  17. ChatCompletionToolChoiceOptionParam,
  18. ChatCompletionToolParam,
  19. )
  20. from openai.types.chat.chat_completion import ChatCompletion as _ChatCompletion
  21. from openai.types.chat.chat_completion import Choice as _ChatCompletionChoice
  22. from openai.types.chat.chat_completion_chunk import (
  23. Choice,
  24. ChoiceDelta,
  25. ChoiceDeltaFunctionCall,
  26. ChoiceDeltaToolCall,
  27. ChoiceDeltaToolCallFunction,
  28. )
  29. from openai.types.chat.chat_completion_message import ChatCompletionMessage, FunctionCall
  30. from openai.types.chat.chat_completion_message_tool_call import Function
  31. from openai.types.completion_usage import CompletionUsage
  32. from core.model_runtime.errors.invoke import InvokeAuthorizationError
  33. class MockChatClass:
  34. @staticmethod
  35. def generate_function_call(
  36. functions: list[completion_create_params.Function] | NotGiven = NOT_GIVEN,
  37. ) -> Optional[FunctionCall]:
  38. if not functions or len(functions) == 0:
  39. return None
  40. function: completion_create_params.Function = functions[0]
  41. function_name = function['name']
  42. function_description = function['description']
  43. function_parameters = function['parameters']
  44. function_parameters_type = function_parameters['type']
  45. if function_parameters_type != 'object':
  46. return None
  47. function_parameters_properties = function_parameters['properties']
  48. function_parameters_required = function_parameters['required']
  49. parameters = {}
  50. for parameter_name, parameter in function_parameters_properties.items():
  51. if parameter_name not in function_parameters_required:
  52. continue
  53. parameter_type = parameter['type']
  54. if parameter_type == 'string':
  55. if 'enum' in parameter:
  56. if len(parameter['enum']) == 0:
  57. continue
  58. parameters[parameter_name] = parameter['enum'][0]
  59. else:
  60. parameters[parameter_name] = 'kawaii'
  61. elif parameter_type == 'integer':
  62. parameters[parameter_name] = 114514
  63. elif parameter_type == 'number':
  64. parameters[parameter_name] = 1919810.0
  65. elif parameter_type == 'boolean':
  66. parameters[parameter_name] = True
  67. return FunctionCall(name=function_name, arguments=dumps(parameters))
  68. @staticmethod
  69. def generate_tool_calls(tools = NOT_GIVEN) -> Optional[list[ChatCompletionMessageToolCall]]:
  70. list_tool_calls = []
  71. if not tools or len(tools) == 0:
  72. return None
  73. tool = tools[0]
  74. if 'type' in tools and tools['type'] != 'function':
  75. return None
  76. function = tool['function']
  77. function_call = MockChatClass.generate_function_call(functions=[function])
  78. if function_call is None:
  79. return None
  80. list_tool_calls.append(ChatCompletionMessageToolCall(
  81. id='sakurajima-mai',
  82. function=Function(
  83. name=function_call.name,
  84. arguments=function_call.arguments,
  85. ),
  86. type='function'
  87. ))
  88. return list_tool_calls
  89. @staticmethod
  90. def mocked_openai_chat_create_sync(
  91. model: str,
  92. functions: list[completion_create_params.Function] | NotGiven = NOT_GIVEN,
  93. tools: list[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
  94. ) -> CompletionMessage:
  95. tool_calls = []
  96. function_call = MockChatClass.generate_function_call(functions=functions)
  97. if not function_call:
  98. tool_calls = MockChatClass.generate_tool_calls(tools=tools)
  99. return _ChatCompletion(
  100. id='cmpl-3QJQa5jXJ5Z5X',
  101. choices=[
  102. _ChatCompletionChoice(
  103. finish_reason='content_filter',
  104. index=0,
  105. message=ChatCompletionMessage(
  106. content='elaina',
  107. role='assistant',
  108. function_call=function_call,
  109. tool_calls=tool_calls
  110. )
  111. )
  112. ],
  113. created=int(time()),
  114. model=model,
  115. object='chat.completion',
  116. system_fingerprint='',
  117. usage=CompletionUsage(
  118. prompt_tokens=2,
  119. completion_tokens=1,
  120. total_tokens=3,
  121. )
  122. )
  123. @staticmethod
  124. def mocked_openai_chat_create_stream(
  125. model: str,
  126. functions: list[completion_create_params.Function] | NotGiven = NOT_GIVEN,
  127. tools: list[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
  128. ) -> Generator[ChatCompletionChunk, None, None]:
  129. tool_calls = []
  130. function_call = MockChatClass.generate_function_call(functions=functions)
  131. if not function_call:
  132. tool_calls = MockChatClass.generate_tool_calls(tools=tools)
  133. full_text = "Hello, world!\n\n```python\nprint('Hello, world!')\n```"
  134. for i in range(0, len(full_text) + 1):
  135. if i == len(full_text):
  136. yield ChatCompletionChunk(
  137. id='cmpl-3QJQa5jXJ5Z5X',
  138. choices=[
  139. Choice(
  140. delta=ChoiceDelta(
  141. content='',
  142. function_call=ChoiceDeltaFunctionCall(
  143. name=function_call.name,
  144. arguments=function_call.arguments,
  145. ) if function_call else None,
  146. role='assistant',
  147. tool_calls=[
  148. ChoiceDeltaToolCall(
  149. index=0,
  150. id='misaka-mikoto',
  151. function=ChoiceDeltaToolCallFunction(
  152. name=tool_calls[0].function.name,
  153. arguments=tool_calls[0].function.arguments,
  154. ),
  155. type='function'
  156. )
  157. ] if tool_calls and len(tool_calls) > 0 else None
  158. ),
  159. finish_reason='function_call',
  160. index=0,
  161. )
  162. ],
  163. created=int(time()),
  164. model=model,
  165. object='chat.completion.chunk',
  166. system_fingerprint='',
  167. usage=CompletionUsage(
  168. prompt_tokens=2,
  169. completion_tokens=17,
  170. total_tokens=19,
  171. ),
  172. )
  173. else:
  174. yield ChatCompletionChunk(
  175. id='cmpl-3QJQa5jXJ5Z5X',
  176. choices=[
  177. Choice(
  178. delta=ChoiceDelta(
  179. content=full_text[i],
  180. role='assistant',
  181. ),
  182. finish_reason='content_filter',
  183. index=0,
  184. )
  185. ],
  186. created=int(time()),
  187. model=model,
  188. object='chat.completion.chunk',
  189. system_fingerprint='',
  190. )
  191. def chat_create(self: Completions, *,
  192. messages: list[ChatCompletionMessageParam],
  193. model: Union[str,Literal[
  194. "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613",
  195. "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613",
  196. "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301",
  197. "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613"],
  198. ],
  199. functions: list[completion_create_params.Function] | NotGiven = NOT_GIVEN,
  200. response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN,
  201. stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN,
  202. tools: list[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
  203. **kwargs: Any,
  204. ):
  205. openai_models = [
  206. "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613",
  207. "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613",
  208. "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301",
  209. "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613",
  210. ]
  211. azure_openai_models = [
  212. "gpt35", "gpt-4v", "gpt-35-turbo"
  213. ]
  214. if not re.match(r'^(https?):\/\/[^\s\/$.?#].[^\s]*$', self._client.base_url.__str__()):
  215. raise InvokeAuthorizationError('Invalid base url')
  216. if model in openai_models + azure_openai_models:
  217. if not re.match(r'sk-[a-zA-Z0-9]{24,}$', self._client.api_key) and type(self._client) == OpenAI:
  218. # sometime, provider use OpenAI compatible API will not have api key or have different api key format
  219. # so we only check if model is in openai_models
  220. raise InvokeAuthorizationError('Invalid api key')
  221. if len(self._client.api_key) < 18 and type(self._client) == AzureOpenAI:
  222. raise InvokeAuthorizationError('Invalid api key')
  223. if stream:
  224. return MockChatClass.mocked_openai_chat_create_stream(model=model, functions=functions, tools=tools)
  225. return MockChatClass.mocked_openai_chat_create_sync(model=model, functions=functions, tools=tools)