Elffuss BraidHub

kikocis/auto-code-rover public

1850dbf80feb · 5.2 KiBRawPermalink
1"""
2Interfacing with Groq cloud.
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 GroqModel(Model):
20 """
21 Base class for creating Singleton instances of Groq models.
22 We use native API from Groq through LiteLLM.
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 Groq API key.
47 """
48 self.check_api_key()
49
50 def check_api_key(self) -> str:
51 """
52 Check for the GROQ_API_KEY environment variable.
53 """
54 key = os.environ.get("GROQ_API_KEY")
55 if not key:
56 log_and_print("Please set the GROQ_API_KEY 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
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 """
81 Calls the Groq API to generate completions for the given inputs.
82 """
83 # FIXME: ignore tools field since we don't use tools now
84 try:
85 # groq 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=common.MODEL_TEMP,
95 max_tokens=1024,
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
125class Llama3_8B(GroqModel):
126 def __init__(self):
127 super().__init__(
128 "groq/llama3-8b-8192", 0.00000005, 0.00000010, parallel_tool_call=True
129 )
130 self.note = "The champion of the Llama series with 8B params from Meta"
131
132class Llama3_70B(GroqModel):
133 def __init__(self):
134 super().__init__(
135 "groq/llama3-70b-8192", 0.00000059, 0.00000079, parallel_tool_call=True
136 )
137 self.note = "Llama lastest model with 70B params"
138
139class Llama2_70B(GroqModel):
140 def __init__(self):
141 super().__init__(
142 "groq/llama2-70b-4096", 0, 0, parallel_tool_call=True # Price not mentioned on website
143 )
144 self.note = "The predecessor of Llama3, still a formidable model with 70B params"
145
146class Mixtral_8x7B(GroqModel):
147 def __init__(self):
148 super().__init__(
149 "groq/mixtral-8x7b-32768", 0.00000027, 0.00000027, parallel_tool_call=True
150 )
151 self.note = "Balanced blend of speed and power from Mixtral team with 8 layers and 7B parameters"
152
153class Gemma_7B(GroqModel):
154 def __init__(self):
155 super().__init__(
156 "groq/gemma-7b-it", 0.0000001, 0.0000001, parallel_tool_call=True
157 )
158 self.note = "A state-of-the-art open model from Google, boasting 7B parameters"
159