ernie_bot_chat.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from .....utils import logging
  15. from .base import BaseChat
  16. import erniebot
  17. class ErnieBotChat(BaseChat):
  18. """Ernie Bot Chat"""
  19. entities = [
  20. "ernie-4.0",
  21. "ernie-3.5",
  22. "ernie-3.5-8k",
  23. "ernie-lite",
  24. "ernie-tiny-8k",
  25. "ernie-speed",
  26. "ernie-speed-128k",
  27. "ernie-char-8k",
  28. ]
  29. def __init__(self, config):
  30. super().__init__()
  31. model_name = config.get("model_name", None)
  32. api_type = config.get("api_type", None)
  33. ak = config.get("ak", None)
  34. sk = config.get("sk", None)
  35. access_token = config.get("access_token", None)
  36. if model_name not in self.entities:
  37. raise ValueError(f"model_name must be in {self.entities} of ErnieBotChat.")
  38. if api_type not in ["aistudio", "qianfan"]:
  39. raise ValueError("api_type must be one of ['aistudio', 'qianfan']")
  40. if api_type == "aistudio" and access_token is None:
  41. raise ValueError("access_token cannot be empty when api_type is aistudio.")
  42. if api_type == "qianfan" and (ak is None or sk is None):
  43. raise ValueError("ak and sk cannot be empty when api_type is qianfan.")
  44. self.model_name = model_name
  45. self.config = config
  46. def generate_chat_results(self, prompt, temperature=0.001, max_retries=1):
  47. """
  48. args:
  49. return:
  50. """
  51. try:
  52. cur_config = {
  53. "api_type": self.config["api_type"],
  54. "max_retries": max_retries,
  55. }
  56. if self.config["api_type"] == "aistudio":
  57. cur_config["access_token"] = self.config["access_token"]
  58. elif self.config["api_type"] == "qianfan":
  59. cur_config["ak"] = self.config["ak"]
  60. cur_config["sk"] = self.config["sk"]
  61. chat_completion = erniebot.ChatCompletion.create(
  62. _config_=cur_config,
  63. model=self.model_name,
  64. messages=[{"role": "user", "content": prompt}],
  65. temperature=float(temperature),
  66. )
  67. llm_result = chat_completion.get_result()
  68. return llm_result
  69. except Exception as e:
  70. if len(e.args) < 1:
  71. self.ERROR_MASSAGE = "暂无权限访问ErnieBot服务,请检查访问令牌。"
  72. elif (
  73. e.args[-1]
  74. == "暂无权限使用,请在 AI Studio 正确获取访问令牌(access token)使用"
  75. ):
  76. self.ERROR_MASSAGE = "暂无权限访问ErnieBot服务,请检查访问令牌。"
  77. else:
  78. logging.error(e)
  79. self.ERROR_MASSAGE = "大模型调用失败"
  80. return None