kikocis/auto-code-rover public
Changesets · Branches · Tags · Compare
| Changeset | 33bbb04ea924a0f71bb0683f24cb260f1b65eda825184b5594f9b50502d57e4b |
|---|---|
| Author | Martin Mirchev <mmirchev@comp.nus.edu.sg> · 2024-06-07 12:00 +08:00 |
| Committer | Martin Mirchev <mmirchev@comp.nus.edu.sg> · 2024-06-07 12:00 +08:00 |
| Parents | b9ae86b1fa3b |
3 files changed
added app/model/gemini.py +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +""" | |
| 2 | +For models other than those from OpenAI, use LiteLLM if possible. | |
| 3 | +""" | |
| 4 | + | |
| 5 | +import os | |
| 6 | +import sys | |
| 7 | +from typing import Literal | |
| 8 | + | |
| 9 | +import litellm | |
| 10 | +from litellm.utils import Choices, Message, ModelResponse | |
| 11 | +from openai import BadRequestError | |
| 12 | +from tenacity import retry, stop_after_attempt, wait_random_exponential | |
| 13 | + | |
| 14 | +from app.log import log_and_print | |
| 15 | +from app.model import common | |
| 16 | +from app.model.common import Model | |
| 17 | + | |
| 18 | + | |
| 19 | +class GeminiModel(Model): | |
| 20 | + """ | |
| 21 | + Base class for creating Singleton instances of Gemini models. | |
| 22 | + """ | |
| 23 | + | |
| 24 | + _instances = {} | |
| 25 | + | |
| 26 | + def __new__(cls): | |
| 27 | + if cls not in cls._instances: | |
| 28 | + cls._instances[cls] = super().__new__(cls) | |
| 29 | + cls._instances[cls]._initialized = False | |
| 30 | + return cls._instances[cls] | |
| 31 | + | |
| 32 | + def __init__( | |
| 33 | + self, | |
| 34 | + name: str, | |
| 35 | + cost_per_input: float, | |
| 36 | + cost_per_output: float, | |
| 37 | + parallel_tool_call: bool = False, | |
| 38 | + ): | |
| 39 | + if self._initialized: | |
| 40 | + return | |
| 41 | + super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) | |
| 42 | + self._initialized = True | |
| 43 | + | |
| 44 | + def setup(self) -> None: | |
| 45 | + """ | |
| 46 | + Check API key. | |
| 47 | + """ | |
| 48 | + self.check_api_key() | |
| 49 | + | |
| 50 | + def check_api_key(self) -> str: | |
| 51 | + key_name = "GEMINI_API_KEY" | |
| 52 | + credential_name = "GOOGLE_APPLICATION_CREDENTIALS" | |
| 53 | + | |
| 54 | + gemini_key = os.getenv(key_name) | |
| 55 | + credential_key = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") | |
| 56 | + if not (gemini_key or credential_key): | |
| 57 | + print(f"Please set the {key_name} or {credential_name} env var") | |
| 58 | + sys.exit(1) | |
| 59 | + return gemini_key or credential_key | |
| 60 | + | |
| 61 | + def extract_resp_content(self, chat_message: Message) -> str: | |
| 62 | + """ | |
| 63 | + Given a chat completion message, extract the content from it. | |
| 64 | + """ | |
| 65 | + content = chat_message.content | |
| 66 | + if content is None: | |
| 67 | + return "" | |
| 68 | + else: | |
| 69 | + return content | |
| 70 | + | |
| 71 | + @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) | |
| 72 | + def call( | |
| 73 | + self, | |
| 74 | + messages: list[dict], | |
| 75 | + top_p=1, | |
| 76 | + tools=None, | |
| 77 | + response_format: Literal["text", "json_object"] = "text", | |
| 78 | + **kwargs, | |
| 79 | + ): | |
| 80 | + # FIXME: ignore tools field since we don't use tools now | |
| 81 | + try: | |
| 82 | + prefill_content = "{" | |
| 83 | + if response_format == "json_object": # prefill | |
| 84 | + messages.append({"role": "assistant", "content": prefill_content}) | |
| 85 | + | |
| 86 | + response = litellm.completion( | |
| 87 | + model=self.name, | |
| 88 | + messages=messages, | |
| 89 | + temperature=common.MODEL_TEMP, | |
| 90 | + max_tokens=1024, | |
| 91 | + top_p=top_p, | |
| 92 | + stream=False, | |
| 93 | + ) | |
| 94 | + assert isinstance(response, ModelResponse) | |
| 95 | + resp_usage = response.usage | |
| 96 | + assert resp_usage is not None | |
| 97 | + input_tokens = int(resp_usage.prompt_tokens) | |
| 98 | + output_tokens = int(resp_usage.completion_tokens) | |
| 99 | + cost = self.calc_cost(input_tokens, output_tokens) | |
| 100 | + | |
| 101 | + common.thread_cost.process_cost += cost | |
| 102 | + common.thread_cost.process_input_tokens += input_tokens | |
| 103 | + common.thread_cost.process_output_tokens += output_tokens | |
| 104 | + | |
| 105 | + first_resp_choice = response.choices[0] | |
| 106 | + assert isinstance(first_resp_choice, Choices) | |
| 107 | + resp_msg: Message = first_resp_choice.message | |
| 108 | + content = self.extract_resp_content(resp_msg) | |
| 109 | + if response_format == "json_object": | |
| 110 | + # prepend the prefilled character | |
| 111 | + if not content.startswith(prefill_content): | |
| 112 | + content = prefill_content + content | |
| 113 | + | |
| 114 | + return content, cost, input_tokens, output_tokens | |
| 115 | + | |
| 116 | + except BadRequestError as e: | |
| 117 | + if e.code == "context_length_exceeded": | |
| 118 | + log_and_print("Context length exceeded") | |
| 119 | + raise e | |
| 120 | + | |
| 121 | + | |
| 122 | +class GeminiPro(GeminiModel): | |
| 123 | + def __init__(self): | |
| 124 | + super().__init__( | |
| 125 | + "gemini-1.0-pro-002", 0.00000035, 0.00000105, parallel_tool_call=True | |
| 126 | + ) | |
| 127 | + self.note = "Gemini 1.0 from Google" | |
| 128 | + | |
| 129 | + | |
| 130 | +class Gemini15Pro(GeminiModel): | |
| 131 | + def __init__(self): | |
| 132 | + super().__init__( | |
| 133 | + "gemini-1.5-pro-preview-0409", | |
| 134 | + 0.00000035, | |
| 135 | + 0.00000105, | |
| 136 | + parallel_tool_call=True, | |
| 137 | + ) | |
| 138 | + self.note = "Gemini 1.5 from Google" |
added app/model/gptlitellm.py +189 −0
| @@ -0,0 +1,189 @@ | ||
| 1 | +""" | |
| 2 | +For models other than those from OpenAI, use LiteLLM if possible. | |
| 3 | +""" | |
| 4 | + | |
| 5 | +import os | |
| 6 | +import sys | |
| 7 | +from typing import Literal | |
| 8 | + | |
| 9 | +import litellm | |
| 10 | +from litellm.utils import Choices, Message, ModelResponse | |
| 11 | +from openai import BadRequestError | |
| 12 | +from tenacity import retry, stop_after_attempt, wait_random_exponential | |
| 13 | + | |
| 14 | +from app.log import log_and_print | |
| 15 | +from app.model import common | |
| 16 | +from app.model.common import Model | |
| 17 | + | |
| 18 | + | |
| 19 | +class OpenaiLiteLLMModel(Model): | |
| 20 | + """ | |
| 21 | + Base class for creating Singleton instances of Openai models. | |
| 22 | + """ | |
| 23 | + | |
| 24 | + _instances = {} | |
| 25 | + | |
| 26 | + def __new__(cls): | |
| 27 | + if cls not in cls._instances: | |
| 28 | + cls._instances[cls] = super().__new__(cls) | |
| 29 | + cls._instances[cls]._initialized = False | |
| 30 | + return cls._instances[cls] | |
| 31 | + | |
| 32 | + def __init__( | |
| 33 | + self, | |
| 34 | + name: str, | |
| 35 | + cost_per_input: float, | |
| 36 | + cost_per_output: float, | |
| 37 | + parallel_tool_call: bool = False, | |
| 38 | + ): | |
| 39 | + if self._initialized: | |
| 40 | + return | |
| 41 | + super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) | |
| 42 | + self._initialized = True | |
| 43 | + | |
| 44 | + def setup(self) -> None: | |
| 45 | + """ | |
| 46 | + Check API key. | |
| 47 | + """ | |
| 48 | + self.check_api_key() | |
| 49 | + | |
| 50 | + def check_api_key(self) -> str: | |
| 51 | + key_name = "OPENAI_KEY" | |
| 52 | + key = os.getenv(key_name) | |
| 53 | + if not key: | |
| 54 | + print(f"Please set the {key_name} env var") | |
| 55 | + sys.exit(1) | |
| 56 | + os.environ["OPENAI_API_KEY"] = key | |
| 57 | + return key | |
| 58 | + | |
| 59 | + def extract_resp_content(self, chat_message: Message) -> str: | |
| 60 | + """ | |
| 61 | + Given a chat completion message, extract the content from it. | |
| 62 | + """ | |
| 63 | + content = chat_message.content | |
| 64 | + if content is None: | |
| 65 | + return "" | |
| 66 | + else: | |
| 67 | + return content | |
| 68 | + | |
| 69 | + @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) | |
| 70 | + def call( | |
| 71 | + self, | |
| 72 | + messages: list[dict], | |
| 73 | + top_p=1, | |
| 74 | + tools=None, | |
| 75 | + response_format: Literal["text", "json_object"] = "text", | |
| 76 | + **kwargs, | |
| 77 | + ): | |
| 78 | + # FIXME: ignore tools field since we don't use tools now | |
| 79 | + try: | |
| 80 | + prefill_content = "{" | |
| 81 | + if response_format == "json_object": # prefill | |
| 82 | + messages.append({"role": "assistant", "content": prefill_content}) | |
| 83 | + | |
| 84 | + response = litellm.completion( | |
| 85 | + model=( | |
| 86 | + self.name | |
| 87 | + if not self.name.startswith("litellm-") | |
| 88 | + else self.name[len("litellm-") :] | |
| 89 | + ), | |
| 90 | + messages=messages, | |
| 91 | + temperature=common.MODEL_TEMP, | |
| 92 | + max_tokens=1024, | |
| 93 | + response_format={"type": response_format}, | |
| 94 | + top_p=top_p, | |
| 95 | + stream=False, | |
| 96 | + ) | |
| 97 | + assert isinstance(response, ModelResponse) | |
| 98 | + resp_usage = response.usage | |
| 99 | + assert resp_usage is not None | |
| 100 | + input_tokens = int(resp_usage.prompt_tokens) | |
| 101 | + output_tokens = int(resp_usage.completion_tokens) | |
| 102 | + cost = self.calc_cost(input_tokens, output_tokens) | |
| 103 | + | |
| 104 | + common.thread_cost.process_cost += cost | |
| 105 | + common.thread_cost.process_input_tokens += input_tokens | |
| 106 | + common.thread_cost.process_output_tokens += output_tokens | |
| 107 | + | |
| 108 | + first_resp_choice = response.choices[0] | |
| 109 | + assert isinstance(first_resp_choice, Choices) | |
| 110 | + resp_msg: Message = first_resp_choice.message | |
| 111 | + content = self.extract_resp_content(resp_msg) | |
| 112 | + if response_format == "json_object": | |
| 113 | + # prepend the prefilled character | |
| 114 | + if not content.startswith(prefill_content): | |
| 115 | + content = prefill_content + content | |
| 116 | + | |
| 117 | + return content, cost, input_tokens, output_tokens | |
| 118 | + | |
| 119 | + except BadRequestError as e: | |
| 120 | + if e.code == "context_length_exceeded": | |
| 121 | + log_and_print("Context length exceeded") | |
| 122 | + raise e | |
| 123 | + | |
| 124 | + | |
| 125 | +class Gpt4o_20240513LiteLLM(OpenaiLiteLLMModel): | |
| 126 | + def __init__(self): | |
| 127 | + super().__init__( | |
| 128 | + "litellm-gpt-4o-2024-05-13", 0.000005, 0.000015, parallel_tool_call=True | |
| 129 | + ) | |
| 130 | + self.note = "Multimodal model. Up to Oct 2023." | |
| 131 | + | |
| 132 | + | |
| 133 | +class Gpt4_Turbo20240409LiteLLM(OpenaiLiteLLMModel): | |
| 134 | + def __init__(self): | |
| 135 | + super().__init__( | |
| 136 | + "litellm-gpt-4-turbo-2024-04-09", 0.00001, 0.00003, parallel_tool_call=True | |
| 137 | + ) | |
| 138 | + self.note = "Turbo with vision. Up to Dec 2023." | |
| 139 | + | |
| 140 | + | |
| 141 | +class Gpt4_0125PreviewLiteLLM(OpenaiLiteLLMModel): | |
| 142 | + def __init__(self): | |
| 143 | + super().__init__( | |
| 144 | + "litellm-gpt-4-0125-preview", 0.00001, 0.00003, parallel_tool_call=True | |
| 145 | + ) | |
| 146 | + self.note = "Turbo. Up to Dec 2023." | |
| 147 | + | |
| 148 | + | |
| 149 | +class Gpt4_1106PreviewLiteLLM(OpenaiLiteLLMModel): | |
| 150 | + def __init__(self): | |
| 151 | + super().__init__( | |
| 152 | + "litellm-gpt-4-1106-preview", 0.00001, 0.00003, parallel_tool_call=True | |
| 153 | + ) | |
| 154 | + self.note = "Turbo. Up to Apr 2023." | |
| 155 | + | |
| 156 | + | |
| 157 | +class Gpt35_Turbo0125LiteLLM(OpenaiLiteLLMModel): | |
| 158 | + # cheapest gpt model | |
| 159 | + def __init__(self): | |
| 160 | + super().__init__( | |
| 161 | + "litellm-gpt-3.5-turbo-0125", 0.0000005, 0.0000015, parallel_tool_call=True | |
| 162 | + ) | |
| 163 | + self.note = "Turbo. Up to Sep 2021." | |
| 164 | + | |
| 165 | + | |
| 166 | +class Gpt35_Turbo1106LiteLLM(OpenaiLiteLLMModel): | |
| 167 | + def __init__(self): | |
| 168 | + super().__init__( | |
| 169 | + "litellm-gpt-3.5-turbo-1106", 0.000001, 0.000002, parallel_tool_call=True | |
| 170 | + ) | |
| 171 | + self.note = "Turbo. Up to Sep 2021." | |
| 172 | + | |
| 173 | + | |
| 174 | +class Gpt35_Turbo16k_0613LiteLLM(OpenaiLiteLLMModel): | |
| 175 | + def __init__(self): | |
| 176 | + super().__init__("litellm-gpt-3.5-turbo-16k-0613", 0.000003, 0.000004) | |
| 177 | + self.note = "Turbo. Deprecated. Up to Sep 2021." | |
| 178 | + | |
| 179 | + | |
| 180 | +class Gpt35_Turbo0613LiteLLM(OpenaiLiteLLMModel): | |
| 181 | + def __init__(self): | |
| 182 | + super().__init__("litellm-gpt-3.5-turbo-0613", 0.0000015, 0.000002) | |
| 183 | + self.note = "Turbo. Deprecated. Only 4k window. Up to Sep 2021." | |
| 184 | + | |
| 185 | + | |
| 186 | +class Gpt4_0613LiteLLM(OpenaiLiteLLMModel): | |
| 187 | + def __init__(self): | |
| 188 | + super().__init__("litellm-gpt-4-0613", 0.00003, 0.00006) | |
| 189 | + self.note = "Not turbo. Up to Sep 2021." |
modified app/model/register.py +14 −1
| @@ -1,4 +1,4 @@ | ||
| 1 | -from app.model import claude, common, gpt, ollama | |
| 1 | +from app.model import claude, common, gemini, gpt, gptlitellm, ollama | |
| 2 | 2 | |
| 3 | 3 | |
| 4 | 4 | def register_all_models() -> None: |
| @@ -22,5 +22,18 @@ | ||
| 22 | 22 | common.register_model(ollama.Llama3_8B()) |
| 23 | 23 | common.register_model(ollama.Llama3_70B()) |
| 24 | 24 | |
| 25 | + common.register_model(gptlitellm.Gpt4o_20240513LiteLLM()) | |
| 26 | + common.register_model(gptlitellm.Gpt4_Turbo20240409LiteLLM()) | |
| 27 | + common.register_model(gptlitellm.Gpt4_0125PreviewLiteLLM()) | |
| 28 | + common.register_model(gptlitellm.Gpt4_1106PreviewLiteLLM()) | |
| 29 | + common.register_model(gptlitellm.Gpt35_Turbo0125LiteLLM()) | |
| 30 | + common.register_model(gptlitellm.Gpt35_Turbo1106LiteLLM()) | |
| 31 | + common.register_model(gptlitellm.Gpt35_Turbo16k_0613LiteLLM()) | |
| 32 | + common.register_model(gptlitellm.Gpt35_Turbo0613LiteLLM()) | |
| 33 | + common.register_model(gptlitellm.Gpt4_0613LiteLLM()) | |
| 34 | + | |
| 35 | + common.register_model(gemini.GeminiPro()) | |
| 36 | + common.register_model(gemini.Gemini15Pro()) | |
| 37 | + | |
| 25 | 38 | # register default model as selected |
| 26 | 39 | common.SELECTED_MODEL = gpt.Gpt35_Turbo0125() |