您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

chat_model.py 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from zhipuai import ZhipuAI
  17. from dashscope import Generation
  18. from abc import ABC
  19. from openai import OpenAI
  20. import openai
  21. from rag.nlp import is_english
  22. from rag.utils import num_tokens_from_string
  23. class Base(ABC):
  24. def __init__(self, key, model_name):
  25. pass
  26. def chat(self, system, history, gen_conf):
  27. raise NotImplementedError("Please implement encode method!")
  28. class GptTurbo(Base):
  29. def __init__(self, key, model_name="gpt-3.5-turbo"):
  30. self.client = OpenAI(api_key=key)
  31. self.model_name = model_name
  32. def chat(self, system, history, gen_conf):
  33. if system:
  34. history.insert(0, {"role": "system", "content": system})
  35. try:
  36. response = self.client.chat.completions.create(
  37. model=self.model_name,
  38. messages=history,
  39. **gen_conf)
  40. ans = response.choices[0].message.content.strip()
  41. if response.choices[0].finish_reason == "length":
  42. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  43. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  44. return ans, response.usage.completion_tokens
  45. except openai.APIError as e:
  46. return "**ERROR**: " + str(e), 0
  47. class MoonshotChat(GptTurbo):
  48. def __init__(self, key, model_name="moonshot-v1-8k"):
  49. self.client = OpenAI(
  50. api_key=key, base_url="https://api.moonshot.cn/v1",)
  51. self.model_name = model_name
  52. def chat(self, system, history, gen_conf):
  53. if system:
  54. history.insert(0, {"role": "system", "content": system})
  55. try:
  56. response = self.client.chat.completions.create(
  57. model=self.model_name,
  58. messages=history,
  59. **gen_conf)
  60. ans = response.choices[0].message.content.strip()
  61. if response.choices[0].finish_reason == "length":
  62. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  63. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  64. return ans, response.usage.completion_tokens
  65. except openai.APIError as e:
  66. return "**ERROR**: " + str(e), 0
  67. class QWenChat(Base):
  68. def __init__(self, key, model_name=Generation.Models.qwen_turbo):
  69. import dashscope
  70. dashscope.api_key = key
  71. self.model_name = model_name
  72. def chat(self, system, history, gen_conf):
  73. from http import HTTPStatus
  74. if system:
  75. history.insert(0, {"role": "system", "content": system})
  76. response = Generation.call(
  77. self.model_name,
  78. messages=history,
  79. result_format='message',
  80. **gen_conf
  81. )
  82. ans = ""
  83. tk_count = 0
  84. if response.status_code == HTTPStatus.OK:
  85. ans += response.output.choices[0]['message']['content']
  86. tk_count += response.usage.output_tokens
  87. if response.output.choices[0].get("finish_reason", "") == "length":
  88. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  89. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  90. return ans, tk_count
  91. return "**ERROR**: " + response.message, tk_count
  92. class ZhipuChat(Base):
  93. def __init__(self, key, model_name="glm-3-turbo"):
  94. self.client = ZhipuAI(api_key=key)
  95. self.model_name = model_name
  96. def chat(self, system, history, gen_conf):
  97. if system:
  98. history.insert(0, {"role": "system", "content": system})
  99. try:
  100. response = self.client.chat.completions.create(
  101. model=self.model_name,
  102. messages=history,
  103. **gen_conf
  104. )
  105. ans = response.choices[0].message.content.strip()
  106. if response.choices[0].finish_reason == "length":
  107. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  108. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  109. return ans, response.usage.completion_tokens
  110. except Exception as e:
  111. return "**ERROR**: " + str(e), 0
  112. class LocalLLM(Base):
  113. class RPCProxy:
  114. def __init__(self, host, port):
  115. self.host = host
  116. self.port = int(port)
  117. self.__conn()
  118. def __conn(self):
  119. from multiprocessing.connection import Client
  120. self._connection = Client(
  121. (self.host, self.port), authkey=b'infiniflow-token4kevinhu')
  122. def __getattr__(self, name):
  123. import pickle
  124. def do_rpc(*args, **kwargs):
  125. for _ in range(3):
  126. try:
  127. self._connection.send(
  128. pickle.dumps((name, args, kwargs)))
  129. return pickle.loads(self._connection.recv())
  130. except Exception as e:
  131. self.__conn()
  132. raise Exception("RPC connection lost!")
  133. return do_rpc
  134. def __init__(self, key, model_name="glm-3-turbo"):
  135. self.client = LocalLLM.RPCProxy("127.0.0.1", 7860)
  136. def chat(self, system, history, gen_conf):
  137. if system:
  138. history.insert(0, {"role": "system", "content": system})
  139. try:
  140. ans = self.client.chat(
  141. history,
  142. gen_conf
  143. )
  144. return ans, num_tokens_from_string(ans)
  145. except Exception as e:
  146. return "**ERROR**: " + str(e), 0