Elffuss BraidHub

kikocis/auto-code-rover public

main · 4.9 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# litellm.set_verbose = True
19
20
21class GroqModel(Model):
22 """
23 Base class for creating Singleton instances of Groq models.
24 We use native API from Groq through LiteLLM.
25 """
26
27 _instances = {}
28
29 def __new__(cls):
30 if cls not in cls._instances:
31 cls._instances[cls] = super().__new__(cls)
32 cls._instances[cls]._initialized = False
33 return cls._instances[cls]
34
35 def __init__(
36 self,
37 name: str,
38 cost_per_input: float,
39 cost_per_output: float,
40 parallel_tool_call: bool = False,
41 ):
42 if self._initialized:
43 return
44 super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call)
45 self._initialized = True
46
47 def setup(self) -> None:
48 """
49 Check Groq API key.
50 """
51 self.check_api_key()
52
53 def check_api_key(self) -> str:
54 """
55 Check for the GROQ_API_KEY environment variable.
56 """
57 key = os.environ.get("GROQ_API_KEY")
58 if not key:
59 log_and_print("Please set the GROQ_API_KEY env var")
60 sys.exit(1)
61 return key
62
63 def extract_resp_content(self, chat_message: Message) -> str:
64 """
65 Given a chat completion message, extract the content from it.
66 """
67 content = chat_message.content
68 if content is None:
69 return ""
70 else:
71 return content
72
73 @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3))
74 def call(
75 self,
76 messages: list[dict],
77 top_p=1,
78 tools=None,
79 response_format: Literal["text", "json_object"] = "text",
80 **kwargs,
81 ):
82 """
83 Calls the Groq API to generate completions for the given inputs.
84 """
85 # FIXME: ignore tools field since we don't use tools now
86 try:
87 # groq models - prefilling response with { increase the success rate
88 # of producing json output
89 prefill_content = "{"
90 if response_format == "json_object": # prefill
91 messages.append({"role": "assistant", "content": prefill_content})
92
93 response = litellm.completion(
94 model=self.name,
95 messages=messages,
96 temperature=common.MODEL_TEMP,
97 max_tokens=1024,
98 top_p=top_p,
99 stream=False,
100 )
101 assert isinstance(response, ModelResponse)
102 resp_usage = response.usage
103 assert resp_usage is not None
104 input_tokens = int(resp_usage.prompt_tokens)
105 output_tokens = int(resp_usage.completion_tokens)
106 cost = self.calc_cost(input_tokens, output_tokens)
107
108 common.thread_cost.process_cost += cost
109 common.thread_cost.process_input_tokens += input_tokens
110 common.thread_cost.process_output_tokens += output_tokens
111
112 first_resp_choice = response.choices[0]
113 assert isinstance(first_resp_choice, Choices)
114 resp_msg: Message = first_resp_choice.message
115 content = self.extract_resp_content(resp_msg)
116 if response_format == "json_object":
117 # prepend the prefilled character
118 if not content.startswith(prefill_content):
119 content = prefill_content + content
120 return content, cost, input_tokens, output_tokens
121
122 except BadRequestError as e:
123 if e.code == "context_length_exceeded":
124 log_and_print("Context length exceeded")
125 raise e
126
127
128class Llama3_8B(GroqModel):
129 def __init__(self):
130 super().__init__(
131 "groq/llama3-8b-8192", 0.00000005, 0.00000010, parallel_tool_call=True
132 )
133 self.note = "The champion of the Llama series with 8B params from Meta"
134
135
136class Llama3_70B(GroqModel):
137 def __init__(self):
138 super().__init__(
139 "groq/llama3-70b-8192", 0.00000059, 0.00000079, parallel_tool_call=True
140 )
141 self.note = "Llama lastest model with 70B params"
142
143
144class Mixtral_8x7B(GroqModel):
145 def __init__(self):
146 super().__init__(
147 "groq/mixtral-8x7b-32768", 0.00000027, 0.00000027, parallel_tool_call=True
148 )
149 self.note = "Balanced blend of speed and power from Mixtral team with 8 layers and 7B parameters"
150
151
152class Gemma_7B(GroqModel):
153 def __init__(self):
154 super().__init__(
155 "groq/gemma-7b-it", 0.0000001, 0.0000001, parallel_tool_call=True
156 )
157 self.note = "A state-of-the-art open model from Google, boasting 7B parameters"