|
| 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 YI_API_PARAMS, YiConfig |
| 21 | +from camel.messages import OpenAIMessage |
| 22 | +from camel.models import BaseModelBackend |
| 23 | +from camel.types import ( |
| 24 | + ChatCompletion, |
| 25 | + ChatCompletionChunk, |
| 26 | + ModelType, |
| 27 | +) |
| 28 | +from camel.utils import ( |
| 29 | + BaseTokenCounter, |
| 30 | + OpenAITokenCounter, |
| 31 | + api_keys_required, |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +class YiModel(BaseModelBackend): |
| 36 | + r"""Yi API in a unified BaseModelBackend interface. |
| 37 | +
|
| 38 | + Args: |
| 39 | + model_type (Union[ModelType, str]): Model for which a backend is |
| 40 | + created, one of Yi series. |
| 41 | + model_config_dict (Optional[Dict[str, Any]], optional): A dictionary |
| 42 | + that will be fed into:obj:`openai.ChatCompletion.create()`. If |
| 43 | + :obj:`None`, :obj:`YiConfig().as_dict()` will be used. |
| 44 | + (default: :obj:`None`) |
| 45 | + api_key (Optional[str], optional): The API key for authenticating with |
| 46 | + the Yi service. (default: :obj:`None`) |
| 47 | + url (Optional[str], optional): The url to the Yi service. |
| 48 | + (default: :obj:`https://api.lingyiwanwu.com/v1`) |
| 49 | + token_counter (Optional[BaseTokenCounter], optional): Token counter to |
| 50 | + use for the model. If not provided, :obj:`OpenAITokenCounter( |
| 51 | + ModelType.GPT_4O_MINI)` will be used. |
| 52 | + (default: :obj:`None`) |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + model_type: Union[ModelType, str], |
| 58 | + model_config_dict: Optional[Dict[str, Any]] = None, |
| 59 | + api_key: Optional[str] = None, |
| 60 | + url: Optional[str] = None, |
| 61 | + token_counter: Optional[BaseTokenCounter] = None, |
| 62 | + ) -> None: |
| 63 | + if model_config_dict is None: |
| 64 | + model_config_dict = YiConfig().as_dict() |
| 65 | + api_key = api_key or os.environ.get("YI_API_KEY") |
| 66 | + url = url or os.environ.get( |
| 67 | + "YI_API_BASE_URL", "https://api.lingyiwanwu.com/v1" |
| 68 | + ) |
| 69 | + super().__init__( |
| 70 | + model_type, model_config_dict, api_key, url, token_counter |
| 71 | + ) |
| 72 | + self._client = OpenAI( |
| 73 | + timeout=60, |
| 74 | + max_retries=3, |
| 75 | + api_key=self._api_key, |
| 76 | + base_url=self._url, |
| 77 | + ) |
| 78 | + |
| 79 | + @api_keys_required("YI_API_KEY") |
| 80 | + def run( |
| 81 | + self, |
| 82 | + messages: List[OpenAIMessage], |
| 83 | + ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]: |
| 84 | + r"""Runs inference of Yi chat completion. |
| 85 | +
|
| 86 | + Args: |
| 87 | + messages (List[OpenAIMessage]): Message list with the chat history |
| 88 | + in OpenAI API format. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + Union[ChatCompletion, Stream[ChatCompletionChunk]]: |
| 92 | + `ChatCompletion` in the non-stream mode, or |
| 93 | + `Stream[ChatCompletionChunk]` in the stream mode. |
| 94 | + """ |
| 95 | + response = self._client.chat.completions.create( |
| 96 | + messages=messages, |
| 97 | + model=self.model_type, |
| 98 | + **self.model_config_dict, |
| 99 | + ) |
| 100 | + return response |
| 101 | + |
| 102 | + @property |
| 103 | + def token_counter(self) -> BaseTokenCounter: |
| 104 | + r"""Initialize the token counter for the model backend. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + OpenAITokenCounter: The token counter following the model's |
| 108 | + tokenization style. |
| 109 | + """ |
| 110 | + |
| 111 | + if not self._token_counter: |
| 112 | + self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI) |
| 113 | + return self._token_counter |
| 114 | + |
| 115 | + def check_model_config(self): |
| 116 | + r"""Check whether the model configuration contains any |
| 117 | + unexpected arguments to Yi API. |
| 118 | +
|
| 119 | + Raises: |
| 120 | + ValueError: If the model configuration dictionary contains any |
| 121 | + unexpected arguments to Yi API. |
| 122 | + """ |
| 123 | + for param in self.model_config_dict: |
| 124 | + if param not in YI_API_PARAMS: |
| 125 | + raise ValueError( |
| 126 | + f"Unexpected argument `{param}` is " |
| 127 | + "input into Yi model backend." |
| 128 | + ) |
| 129 | + |
| 130 | + @property |
| 131 | + def stream(self) -> bool: |
| 132 | + r"""Returns whether the model is in stream mode, which sends partial |
| 133 | + results each time. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + bool: Whether the model is in stream mode. |
| 137 | + """ |
| 138 | + return self.model_config_dict.get('stream', False) |
0 commit comments