|
| 1 | +# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== |
| 2 | +# Licensed under the Apache License, Version 2.0 (the “License”); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an “AS IS” BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | +# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== |
| 14 | + |
| 15 | +import os |
| 16 | +from typing import Any, Dict, List, Optional, Union |
| 17 | + |
| 18 | +from openai import OpenAI, Stream |
| 19 | + |
| 20 | +from camel.configs import OPENAI_API_PARAMS |
| 21 | +from camel.messages import OpenAIMessage |
| 22 | +from camel.models import BaseModelBackend |
| 23 | +from camel.types import ChatCompletion, ChatCompletionChunk, ModelType |
| 24 | +from camel.utils import ( |
| 25 | + BaseTokenCounter, |
| 26 | + OpenAITokenCounter, |
| 27 | + model_api_key_required, |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +class ZhipuAIModel(BaseModelBackend): |
| 32 | + r"""ZhipuAI API in a unified BaseModelBackend interface.""" |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + model_type: ModelType, |
| 37 | + model_config_dict: Dict[str, Any], |
| 38 | + api_key: Optional[str] = None, |
| 39 | + url: Optional[str] = None, |
| 40 | + ) -> None: |
| 41 | + r"""Constructor for ZhipuAI backend. |
| 42 | +
|
| 43 | + Args: |
| 44 | + model_type (ModelType): Model for which a backend is created, |
| 45 | + such as GLM_* series. |
| 46 | + model_config_dict (Dict[str, Any]): A dictionary that will |
| 47 | + be fed into openai.ChatCompletion.create(). |
| 48 | + api_key (Optional[str]): The API key for authenticating with the |
| 49 | + ZhipuAI service. (default: :obj:`None`) |
| 50 | + """ |
| 51 | + super().__init__(model_type, model_config_dict) |
| 52 | + self._url = url or os.environ.get("ZHIPUAI_API_BASE_URL") |
| 53 | + self._api_key = api_key or os.environ.get("ZHIPUAI_API_KEY") |
| 54 | + self._client = OpenAI( |
| 55 | + timeout=60, |
| 56 | + max_retries=3, |
| 57 | + api_key=self._api_key, |
| 58 | + base_url=self._url, |
| 59 | + ) |
| 60 | + self._token_counter: Optional[BaseTokenCounter] = None |
| 61 | + |
| 62 | + @model_api_key_required |
| 63 | + def run( |
| 64 | + self, |
| 65 | + messages: List[OpenAIMessage], |
| 66 | + ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]: |
| 67 | + r"""Runs inference of OpenAI chat completion. |
| 68 | +
|
| 69 | + Args: |
| 70 | + messages (List[OpenAIMessage]): Message list with the chat history |
| 71 | + in OpenAI API format. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + Union[ChatCompletion, Stream[ChatCompletionChunk]]: |
| 75 | + `ChatCompletion` in the non-stream mode, or |
| 76 | + `Stream[ChatCompletionChunk]` in the stream mode. |
| 77 | + """ |
| 78 | + # Use OpenAI cilent as interface call ZhipuAI |
| 79 | + # Reference: https://open.bigmodel.cn/dev/api#openai_sdk |
| 80 | + response = self._client.chat.completions.create( |
| 81 | + messages=messages, |
| 82 | + model=self.model_type.value, |
| 83 | + **self.model_config_dict, |
| 84 | + ) |
| 85 | + return response |
| 86 | + |
| 87 | + @property |
| 88 | + def token_counter(self) -> BaseTokenCounter: |
| 89 | + r"""Initialize the token counter for the model backend. |
| 90 | +
|
| 91 | + Returns: |
| 92 | + OpenAITokenCounter: The token counter following the model's |
| 93 | + tokenization style. |
| 94 | + """ |
| 95 | + |
| 96 | + if not self._token_counter: |
| 97 | + # It's a temporary setting for token counter. |
| 98 | + self._token_counter = OpenAITokenCounter(ModelType.GPT_3_5_TURBO) |
| 99 | + return self._token_counter |
| 100 | + |
| 101 | + def check_model_config(self): |
| 102 | + r"""Check whether the model configuration contains any |
| 103 | + unexpected arguments to OpenAI API. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + ValueError: If the model configuration dictionary contains any |
| 107 | + unexpected arguments to OpenAI API. |
| 108 | + """ |
| 109 | + for param in self.model_config_dict: |
| 110 | + if param not in OPENAI_API_PARAMS: |
| 111 | + raise ValueError( |
| 112 | + f"Unexpected argument `{param}` is " |
| 113 | + "input into OpenAI model backend." |
| 114 | + ) |
| 115 | + pass |
| 116 | + |
| 117 | + @property |
| 118 | + def stream(self) -> bool: |
| 119 | + r"""Returns whether the model is in stream mode, which sends partial |
| 120 | + results each time. |
| 121 | +
|
| 122 | + Returns: |
| 123 | + bool: Whether the model is in stream mode. |
| 124 | + """ |
| 125 | + return self.model_config_dict.get('stream', False) |
0 commit comments