Elffuss BraidHub

kikocis/auto-code-rover public

831d2a8f2ea0 · 4.7 KiBRawPermalink
1"""
2For models other than those from OpenAI, use LiteLLM if possible.
3"""
4
5import os
6import sys
7from typing import Literal
8
9import litellm
10from litellm.utils import Choices, Message, ModelResponse
11from openai import BadRequestError
12from tenacity import retry, stop_after_attempt, wait_random_exponential
13
14from app.log import log_and_print
15from app.model import common
16from app.model.common import Model
17
18
19class 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 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 = "ANTHROPIC_API_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 return key
57
58 def extract_resp_content(self, chat_message: Message) -> str:
59 """
60 Given a chat completion message, extract the content from it.
61 """
62 content = chat_message.content
63 if content is None:
64 return ""
65 else:
66 return content
67
68 @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3))
69 def call(
70 self,
71 messages: list[dict],
72 top_p=1,
73 tools=None,
74 response_format: Literal["text", "json_object"] = "text",
75 **kwargs,
76 ):
77 # FIXME: ignore tools field since we don't use tools now
78 try:
79 # antropic models - prefilling response with { increase the success rate
80 # of producing json output
81 prefill_content = "{"
82 if response_format == "json_object": # prefill
83 messages.append({"role": "assistant", "content": prefill_content})
84
85 response = litellm.completion(
86 model=self.name,
87 messages=messages,
88 temperature=common.MODEL_TEMP,
89 max_tokens=1024,
90 top_p=top_p,
91 stream=False,
92 )
93 assert isinstance(response, ModelResponse)
94 resp_usage = response.usage
95 assert resp_usage is not None
96 input_tokens = int(resp_usage.prompt_tokens)
97 output_tokens = int(resp_usage.completion_tokens)
98 cost = self.calc_cost(input_tokens, output_tokens)
99
100 common.thread_cost.process_cost += cost
101 common.thread_cost.process_input_tokens += input_tokens
102 common.thread_cost.process_output_tokens += output_tokens
103
104 first_resp_choice = response.choices[0]
105 assert isinstance(first_resp_choice, Choices)
106 resp_msg: Message = first_resp_choice.message
107 content = self.extract_resp_content(resp_msg)
108 if response_format == "json_object":
109 # prepend the prefilled character
110 if not content.startswith(prefill_content):
111 content = prefill_content + content
112 return content, cost, input_tokens, output_tokens
113
114 except BadRequestError as e:
115 if e.code == "context_length_exceeded":
116 log_and_print("Context length exceeded")
117 raise e
118
119
120class Claude3Opus(AnthropicModel):
121 def __init__(self):
122 super().__init__(
123 "claude-3-opus-20240229", 0.000015, 0.000075, parallel_tool_call=True
124 )
125 self.note = "Most powerful model from Antropic"
126
127
128class Claude3Sonnet(AnthropicModel):
129 def __init__(self):
130 super().__init__(
131 "claude-3-sonnet-20240229", 0.000003, 0.000015, parallel_tool_call=True
132 )
133 self.note = "Most balanced (intelligence and speed) model from Antropic"
134
135
136class Claude3Haiku(AnthropicModel):
137 def __init__(self):
138 super().__init__(
139 "claude-3-haiku-20240307", 0.00000025, 0.00000125, parallel_tool_call=True
140 )
141 self.note = "Fastest model from Antropic"
142
143
144class Claude3_5Sonnet(AnthropicModel):
145 def __init__(self):
146 super().__init__(
147 "claude-3-5-sonnet-20240620", 0.000003, 0.000015, parallel_tool_call=True
148 )
149 self.note = "Most intelligent model from Antropic"