| 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 AnthropicModel(Model): |
| 20 | """ |
| 21 | Base class for creating Singleton instances of Antropic 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 | max_output_token: int = 4096, |
| 38 | parallel_tool_call: bool = False, |
| 39 | ): |
| 40 | if self._initialized: |
| 41 | return |
| 42 | super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) |
| 43 | self.max_output_token = max_output_token |
| 44 | self._initialized = True |
| 45 | |
| 46 | def setup(self) -> None: |
| 47 | """ |
| 48 | Check API key. |
| 49 | """ |
| 50 | self.check_api_key() |
| 51 | |
| 52 | def check_api_key(self) -> str: |
| 53 | key_name = "ANTHROPIC_API_KEY" |
| 54 | key = os.getenv(key_name) |
| 55 | if not key: |
| 56 | print(f"Please set the {key_name} env var") |
| 57 | sys.exit(1) |
| 58 | return key |
| 59 | |
| 60 | def extract_resp_content(self, chat_message: Message) -> str: |
| 61 | """ |
| 62 | Given a chat completion message, extract the content from it. |
| 63 | """ |
| 64 | content = chat_message.content |
| 65 | if content is None: |
| 66 | return "" |
| 67 | else: |
| 68 | return content |
| 69 | |
| 70 | @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) |
| 71 | def call( |
| 72 | self, |
| 73 | messages: list[dict], |
| 74 | top_p=1, |
| 75 | tools=None, |
| 76 | response_format: Literal["text", "json_object"] = "text", |
| 77 | temperature: float | None = None, |
| 78 | **kwargs, |
| 79 | ): |
| 80 | # FIXME: ignore tools field since we don't use tools now |
| 81 | if temperature is None: |
| 82 | temperature = common.MODEL_TEMP |
| 83 | |
| 84 | try: |
| 85 | # antropic models - prefilling response with { increase the success rate |
| 86 | # of producing json output |
| 87 | prefill_content = "{" |
| 88 | if response_format == "json_object": # prefill |
| 89 | messages.append({"role": "assistant", "content": prefill_content}) |
| 90 | |
| 91 | response = litellm.completion( |
| 92 | model=self.name, |
| 93 | messages=messages, |
| 94 | temperature=temperature, |
| 95 | max_tokens=self.max_output_token, |
| 96 | top_p=top_p, |
| 97 | stream=False, |
| 98 | ) |
| 99 | assert isinstance(response, ModelResponse) |
| 100 | resp_usage = response.usage |
| 101 | assert resp_usage is not None |
| 102 | input_tokens = int(resp_usage.prompt_tokens) |
| 103 | output_tokens = int(resp_usage.completion_tokens) |
| 104 | cost = self.calc_cost(input_tokens, output_tokens) |
| 105 | |
| 106 | common.thread_cost.process_cost += cost |
| 107 | common.thread_cost.process_input_tokens += input_tokens |
| 108 | common.thread_cost.process_output_tokens += output_tokens |
| 109 | |
| 110 | first_resp_choice = response.choices[0] |
| 111 | assert isinstance(first_resp_choice, Choices) |
| 112 | resp_msg: Message = first_resp_choice.message |
| 113 | content = self.extract_resp_content(resp_msg) |
| 114 | if response_format == "json_object": |
| 115 | # prepend the prefilled character |
| 116 | if not content.startswith(prefill_content): |
| 117 | content = prefill_content + content |
| 118 | return content, cost, input_tokens, output_tokens |
| 119 | |
| 120 | except BadRequestError as e: |
| 121 | if e.code == "context_length_exceeded": |
| 122 | log_and_print("Context length exceeded") |
| 123 | raise e |
| 124 | |
| 125 | |
| 126 | class Claude3Opus(AnthropicModel): |
| 127 | def __init__(self): |
| 128 | super().__init__( |
| 129 | "claude-3-opus-20240229", 0.000015, 0.000075, parallel_tool_call=True |
| 130 | ) |
| 131 | self.note = "Most powerful model among Claude 3" |
| 132 | |
| 133 | |
| 134 | class Claude3Sonnet(AnthropicModel): |
| 135 | def __init__(self): |
| 136 | super().__init__( |
| 137 | "claude-3-sonnet-20240229", 0.000003, 0.000015, parallel_tool_call=True |
| 138 | ) |
| 139 | self.note = "Most balanced (intelligence and speed) model from Antropic" |
| 140 | |
| 141 | |
| 142 | class Claude3Haiku(AnthropicModel): |
| 143 | def __init__(self): |
| 144 | super().__init__( |
| 145 | "claude-3-haiku-20240307", 0.00000025, 0.00000125, parallel_tool_call=True |
| 146 | ) |
| 147 | self.note = "Fastest model from Antropic" |
| 148 | |
| 149 | |
| 150 | class Claude3_5Sonnet(AnthropicModel): |
| 151 | def __init__(self): |
| 152 | super().__init__( |
| 153 | "claude-3-5-sonnet-20240620", |
| 154 | 0.000003, |
| 155 | 0.000015, |
| 156 | max_output_token=8192, |
| 157 | parallel_tool_call=True, |
| 158 | ) |
| 159 | self.note = "Most intelligent model from Antropic" |