forked from togethercomputer/MoA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
188 lines (140 loc) · 4.99 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import json
import time
import requests
import openai
import copy
from loguru import logger
from dotenv import load_dotenv
load_dotenv()
DEBUG = int(os.environ.get("DEBUG", "0"))
def generate_together(
model,
messages,
max_tokens=2048,
temperature=0.7,
streaming=False,
):
output = None
for sleep_time in [1, 2, 4, 8, 16, 32]:
try:
endpoint = "https://api.groq.com/openai/v1/chat/completions"
if DEBUG:
logger.debug(
f"Sending messages ({len(messages)}) (last message: `{messages[-1]['content'][:20]}...`) to `{model}`."
)
res = requests.post(
endpoint,
json={
"model": model,
"max_tokens": max_tokens,
"temperature": (temperature if temperature > 1e-4 else 0),
"messages": messages,
},
headers={
"Authorization": f"Bearer {os.environ.get('GROQ_API_KEY')}",
},
)
if "error" in res.json():
logger.error(res.json())
if res.json()["error"]["type"] == "invalid_request_error":
logger.info("Input + output is longer than max_position_id.")
return None
output = res.json()["choices"][0]["message"]["content"]
break
except Exception as e:
logger.error(e)
if DEBUG:
logger.debug(f"Msgs: `{messages}`")
logger.info(f"Retry in {sleep_time}s..")
time.sleep(sleep_time)
if output is None:
return output
output = output.strip()
if DEBUG:
logger.debug(f"Output: `{output[:20]}...`.")
return output
def generate_together_stream(
model,
messages,
max_tokens=2048,
temperature=0.7,
):
endpoint = "https://api.groq.com/openai/v1/"
client = openai.OpenAI(
api_key=os.environ.get("GROQ_API_KEY"), base_url=endpoint
)
endpoint = "https://api.groq.com/openai/v1/chat/completions"
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature if temperature > 1e-4 else 0,
max_tokens=max_tokens,
stream=True, # this time, we set stream=True
)
return response
def generate_openai(
model,
messages,
max_tokens=2048,
temperature=0.7,
):
client = openai.OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
for sleep_time in [1, 2, 4, 8, 16, 32]:
try:
if DEBUG:
logger.debug(
f"Sending messages ({len(messages)}) (last message: `{messages[-1]['content'][:20]}`) to `{model}`."
)
completion = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
output = completion.choices[0].message.content
break
except Exception as e:
logger.error(e)
logger.info(f"Retry in {sleep_time}s..")
time.sleep(sleep_time)
output = output.strip()
return output
def inject_references_to_messages(
messages,
references,
):
messages = copy.deepcopy(messages)
system = f"""You have been provided with a set of responses from various open-source models to the latest user query. Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
Responses from models:"""
for i, reference in enumerate(references):
system += f"\n{i+1}. {reference}"
if messages[0]["role"] == "system":
messages[0]["content"] += "\n\n" + system
else:
messages = [{"role": "system", "content": system}] + messages
return messages
def generate_with_references(
model,
messages,
references=[],
max_tokens=2048,
temperature=0.7,
generate_fn=generate_together_stream,
):
if len(references) > 0:
messages = inject_references_to_messages(messages, references)
# Generate response using the provided generate function
response = generate_fn(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
# Check if the response is in the expected format
if hasattr(response, 'choices'):
return response
else:
return [{"choices": [{"delta": {"content": response}}]}]