ernie_bot_chat.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. from typing import Dict
  18. class ErnieBotChat(BaseChat):
  19. """Ernie Bot Chat"""
  20. entities = [
  21. "ernie-4.0",
  22. "ernie-3.5",
  23. "ernie-3.5-8k",
  24. "ernie-lite",
  25. "ernie-tiny-8k",
  26. "ernie-speed",
  27. "ernie-speed-128k",
  28. "ernie-char-8k",
  29. ]
  30. def __init__(self, config: Dict) -> None:
  31. """Initializes the ErnieBotChat with given configuration.
  32. Args:
  33. config (Dict): Configuration dictionary containing model_name, api_type, ak, sk, and access_token.
  34. Raises:
  35. ValueError: If model_name is not in the predefined entities,
  36. api_type is not one of ['aistudio', 'qianfan'],
  37. access_token is None for 'aistudio' api_type,
  38. or ak and sk are None for 'qianfan' api_type.
  39. """
  40. super().__init__()
  41. model_name = config.get("model_name", None)
  42. api_type = config.get("api_type", None)
  43. ak = config.get("ak", None)
  44. sk = config.get("sk", None)
  45. access_token = config.get("access_token", None)
  46. if model_name not in self.entities:
  47. raise ValueError(f"model_name must be in {self.entities} of ErnieBotChat.")
  48. if api_type not in ["aistudio", "qianfan"]:
  49. raise ValueError("api_type must be one of ['aistudio', 'qianfan']")
  50. if api_type == "aistudio" and access_token is None:
  51. raise ValueError("access_token cannot be empty when api_type is aistudio.")
  52. if api_type == "qianfan" and (ak is None or sk is None):
  53. raise ValueError("ak and sk cannot be empty when api_type is qianfan.")
  54. self.model_name = model_name
  55. self.config = config
  56. def generate_chat_results(
  57. self, prompt: str, temperature: float = 0.001, max_retries: int = 1
  58. ) -> Dict:
  59. """
  60. Generate chat results using the specified model and configuration.
  61. Args:
  62. prompt (str): The user's input prompt.
  63. temperature (float, optional): The temperature parameter for llms, defaults to 0.001.
  64. max_retries (int, optional): The maximum number of retries for llms API calls, defaults to 1.
  65. Returns:
  66. Dict: The chat completion result from the model.
  67. """
  68. try:
  69. cur_config = {
  70. "api_type": self.config["api_type"],
  71. "max_retries": max_retries,
  72. }
  73. if self.config["api_type"] == "aistudio":
  74. cur_config["access_token"] = self.config["access_token"]
  75. elif self.config["api_type"] == "qianfan":
  76. cur_config["ak"] = self.config["ak"]
  77. cur_config["sk"] = self.config["sk"]
  78. chat_completion = erniebot.ChatCompletion.create(
  79. _config_=cur_config,
  80. model=self.model_name,
  81. messages=[{"role": "user", "content": prompt}],
  82. temperature=float(temperature),
  83. )
  84. llm_result = chat_completion.get_result()
  85. return llm_result
  86. except Exception as e:
  87. if len(e.args) < 1:
  88. self.ERROR_MASSAGE = "暂无权限访问ErnieBot服务,请检查访问令牌。"
  89. elif (
  90. e.args[-1]
  91. == "暂无权限使用,请在 AI Studio 正确获取访问令牌(access token)使用"
  92. ):
  93. self.ERROR_MASSAGE = "暂无权限访问ErnieBot服务,请检查访问令牌。"
  94. else:
  95. logging.error(e)
  96. self.ERROR_MASSAGE = "大模型调用失败"
  97. return None