| 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" |