Elffuss BraidHub

kikocis/auto-code-rover public

Merge branch 'main' of github.com:KasaiHarcore/auto-code-rover into KasaiHarcore-main
Changesetd437da6f3e1ad48688e5d0b061c2d0d1adbcba193cec31fea29f25a913a066fa
AuthorMartin Mirchev <mmirchev@comp.nus.edu.sg> · 2024-06-08 18:38 +08:00
CommitterMartin Mirchev <mmirchev@comp.nus.edu.sg> · 2024-06-08 18:38 +08:00
Parentseba410d8d607, 1850dbf80feb

Browse the files at this changeset

3 files changed

modified README.md +13 −1
@@ -87,7 +87,14 @@
8787 ```
8888 export OPENAI_KEY=sk-YOUR-OPENAI-API-KEY-HERE
8989 ```
90-(Alternatively, if you want to use Anthropic models instead, set `ANTHROPIC_API_KEY`.)
90+
91+For Anthropic model, Set the `ANTHROPIC_API_KEY` env var can be found [here](https://docs.anthropic.com/claude/reference/getting-started-with-the-api)
92+
93+```
94+export ANTHROPIC_API_KEY=sk-ant-api...
95+```
96+
97+The same with `GROQ_API_KEY`
9198
9299 Build and start the docker image:
93100
@@ -270,6 +277,11 @@
270277 | AWS | Claude 3 Opus | --model bedrock/anthropic.claude-3-opus-20240229-v1:0 |
271278 | | Claude 3 Sonnet | --model bedrock/anthropic.claude-3-sonnet-20240229-v1:0 |
272279 | | Claude 3 Haiku | --model bedrock/anthropic.claude-3-haiku-20240307-v1:0 |
280+| Groq | Llama 3 8B | --model groq/llama3-8b-8192 |
281+| | Llama 3 70B | --model groq/llama3-70b-8192 |
282+| | Llama 2 70B | --model groq/llama2-70b-4096 |
283+| | Mixtral 8x7B | --model groq/mixtral-8x7b-32768 |
284+| | Gemma 7B | --model groq/gemma-7b-it |
273285
274286 > [!NOTE]
275287 > Some notes on running ACR with local models such as llama3:
added app/model/groq.py +157 −0
@@ -0,0 +1,157 @@
1+"""
2+Interfacing with Groq cloud.
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+litellm.set_verbose = True
19+
20+
21+class 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+
128+class 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+
136+class 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+
144+class 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+
152+class 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"
modified app/model/register.py +7 −1
@@ -1,4 +1,5 @@
1-from app.model import bedrock, claude, common, gemini, gpt, gptlitellm, ollama
1+from app.model import bedrock, claude, common, gemini, gpt, gptlitellm, groq , ollama
2+
23
34
45 def register_all_models() -> None:
@@ -25,6 +26,11 @@
2526
2627 common.register_model(ollama.Llama3_8B())
2728 common.register_model(ollama.Llama3_70B())
29+
30+ common.register_model(groq.Llama3_8B())
31+ common.register_model(groq.Llama3_70B())
32+ common.register_model(groq.Mixtral_8x7B())
33+ common.register_model(groq.Gemma_7B())
2834
2935 common.register_model(gptlitellm.Gpt4o_20240513LiteLLM())
3036 common.register_model(gptlitellm.Gpt4_Turbo20240409LiteLLM())