kikocis/auto-code-rover public
Changesets · Branches · Tags · Compare
| Changeset | c90f4874b21f5260033dc01dc7dbf1f308f166007bf18253e60cbb61a15753ee |
|---|---|
| Author | Martin Mirchev <mirchevmartin2203@gmail.com> · 2024-07-19 00:04 +08:00 |
| Committer | Martin Mirchev <mirchevmartin2203@gmail.com> · 2024-07-19 00:04 +08:00 |
| Parents | 0c61f33175b1 |
2 files changed
modified app/main.py +11 −2
| @@ -186,11 +186,20 @@ | ||
| 186 | 186 | default=False, |
| 187 | 187 | help="Do not print most messages to stdout.", |
| 188 | 188 | ) |
| 189 | + | |
| 190 | + def model_parser(name: str): | |
| 191 | + if not isinstance(name, str): | |
| 192 | + raise TypeError(f"Invalid model name: {name}") | |
| 193 | + if name in common.MODEL_HUB.keys(): | |
| 194 | + return name | |
| 195 | + if name.startswith("litellm-generic-"): | |
| 196 | + return name | |
| 197 | + raise TypeError(f"Invalid model name: {name}") | |
| 198 | + | |
| 189 | 199 | parser.add_argument( |
| 190 | 200 | "--model", |
| 191 | - type=str, | |
| 201 | + type=model_parser, | |
| 192 | 202 | default="gpt-3.5-turbo-0125", |
| 193 | - choices=list(common.MODEL_HUB.keys()), | |
| 194 | 203 | help="The model to use. Currently only OpenAI models are supported.", |
| 195 | 204 | ) |
| 196 | 205 | parser.add_argument( |
modified app/model/common.py +126 −3
| @@ -1,8 +1,16 @@ | ||
| 1 | +import os | |
| 1 | 2 | import sys |
| 2 | 3 | import threading |
| 3 | 4 | from abc import ABC, abstractmethod |
| 5 | +from typing import Literal | |
| 4 | 6 | |
| 5 | -from app.log import log_and_cprint | |
| 7 | +import litellm | |
| 8 | +from litellm import cost_per_token | |
| 9 | +from litellm.utils import Choices, Message, ModelResponse | |
| 10 | +from openai import BadRequestError | |
| 11 | +from tenacity import retry, stop_after_attempt, wait_random_exponential | |
| 12 | + | |
| 13 | +from app.log import log_and_cprint, log_and_print | |
| 6 | 14 | |
| 7 | 15 | # Variables for each process. Since models are singleton objects, their references are copied |
| 8 | 16 | # to each process, but they all point to the same objects. For safe updating costs per process, |
| @@ -68,6 +76,104 @@ | ||
| 68 | 76 | } |
| 69 | 77 | |
| 70 | 78 | |
| 79 | +class LiteLLMGeneric(Model): | |
| 80 | + """ | |
| 81 | + Base class for creating instances of LiteLLM-supported models. | |
| 82 | + """ | |
| 83 | + | |
| 84 | + _instances = {} | |
| 85 | + | |
| 86 | + def __new__(cls, model_name: str, cost_per_input: float, cost_per_output: float): | |
| 87 | + if model_name not in cls._instances: | |
| 88 | + cls._instances[model_name] = super().__new__(cls) | |
| 89 | + cls._instances[model_name]._initialized = False | |
| 90 | + return cls._instances[model_name] | |
| 91 | + | |
| 92 | + def __init__( | |
| 93 | + self, | |
| 94 | + name: str, | |
| 95 | + cost_per_input: float, | |
| 96 | + cost_per_output: float, | |
| 97 | + parallel_tool_call: bool = False, | |
| 98 | + ): | |
| 99 | + if self._initialized: | |
| 100 | + return | |
| 101 | + super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) | |
| 102 | + self._initialized = True | |
| 103 | + | |
| 104 | + def setup(self) -> None: | |
| 105 | + """ | |
| 106 | + Check API key. | |
| 107 | + """ | |
| 108 | + pass | |
| 109 | + | |
| 110 | + def check_api_key(self) -> str: | |
| 111 | + return "" | |
| 112 | + | |
| 113 | + def extract_resp_content(self, chat_message: Message) -> str: | |
| 114 | + """ | |
| 115 | + Given a chat completion message, extract the content from it. | |
| 116 | + """ | |
| 117 | + content = chat_message.content | |
| 118 | + if content is None: | |
| 119 | + return "" | |
| 120 | + else: | |
| 121 | + return content | |
| 122 | + | |
| 123 | + @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) | |
| 124 | + def call( | |
| 125 | + self, | |
| 126 | + messages: list[dict], | |
| 127 | + top_p=1, | |
| 128 | + tools=None, | |
| 129 | + response_format: Literal["text", "json_object"] = "text", | |
| 130 | + **kwargs, | |
| 131 | + ): | |
| 132 | + # FIXME: ignore tools field since we don't use tools now | |
| 133 | + try: | |
| 134 | + prefill_content = "{" | |
| 135 | + if response_format == "json_object": # prefill | |
| 136 | + messages.append({"role": "assistant", "content": prefill_content}) | |
| 137 | + | |
| 138 | + response = litellm.completion( | |
| 139 | + model=self.name, | |
| 140 | + messages=messages, | |
| 141 | + temperature=MODEL_TEMP, | |
| 142 | + max_tokens=os.getenv("ACR_TOKEN_LIMIT", 1024), | |
| 143 | + response_format=( | |
| 144 | + {"type": response_format} if "gpt" in self.name else None | |
| 145 | + ), | |
| 146 | + top_p=top_p, | |
| 147 | + stream=False, | |
| 148 | + ) | |
| 149 | + assert isinstance(response, ModelResponse) | |
| 150 | + resp_usage = response.usage | |
| 151 | + assert resp_usage is not None | |
| 152 | + input_tokens = int(resp_usage.prompt_tokens) | |
| 153 | + output_tokens = int(resp_usage.completion_tokens) | |
| 154 | + cost = self.calc_cost(input_tokens, output_tokens) | |
| 155 | + | |
| 156 | + thread_cost.process_cost += cost | |
| 157 | + thread_cost.process_input_tokens += input_tokens | |
| 158 | + thread_cost.process_output_tokens += output_tokens | |
| 159 | + | |
| 160 | + first_resp_choice = response.choices[0] | |
| 161 | + assert isinstance(first_resp_choice, Choices) | |
| 162 | + resp_msg: Message = first_resp_choice.message | |
| 163 | + content = self.extract_resp_content(resp_msg) | |
| 164 | + if response_format == "json_object": | |
| 165 | + # prepend the prefilled character | |
| 166 | + if not content.startswith(prefill_content): | |
| 167 | + content = prefill_content + content | |
| 168 | + | |
| 169 | + return content, cost, input_tokens, output_tokens | |
| 170 | + | |
| 171 | + except BadRequestError as e: | |
| 172 | + if e.code == "context_length_exceeded": | |
| 173 | + log_and_print("Context length exceeded") | |
| 174 | + raise e | |
| 175 | + | |
| 176 | + | |
| 71 | 177 | MODEL_HUB = {} |
| 72 | 178 | |
| 73 | 179 | |
| @@ -86,10 +192,27 @@ | ||
| 86 | 192 | |
| 87 | 193 | def set_model(model_name: str): |
| 88 | 194 | global SELECTED_MODEL |
| 89 | - if model_name not in MODEL_HUB: | |
| 195 | + if model_name not in MODEL_HUB and not model_name.startswith("litellm-generic-"): | |
| 90 | 196 | print(f"Invalid model name: {model_name}") |
| 91 | 197 | sys.exit(1) |
| 92 | - SELECTED_MODEL = MODEL_HUB[model_name] | |
| 198 | + if model_name.startswith("litellm-generic-"): | |
| 199 | + prompt_tokens = 5 | |
| 200 | + completion_tokens = 10 | |
| 201 | + prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar = ( | |
| 202 | + cost_per_token( | |
| 203 | + model="gpt-3.5-turbo", | |
| 204 | + prompt_tokens=prompt_tokens, | |
| 205 | + completion_tokens=completion_tokens, | |
| 206 | + ) | |
| 207 | + ) | |
| 208 | + litellm.set_verbose = True | |
| 209 | + SELECTED_MODEL = LiteLLMGeneric( | |
| 210 | + model_name.removeprefix("litellm-generic-"), | |
| 211 | + prompt_tokens_cost_usd_dollar, | |
| 212 | + completion_tokens_cost_usd_dollar, | |
| 213 | + ) | |
| 214 | + else: | |
| 215 | + SELECTED_MODEL = MODEL_HUB[model_name] | |
| 93 | 216 | SELECTED_MODEL.setup() |
| 94 | 217 | |
| 95 | 218 |