-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
llm.py
319 lines (299 loc) Β· 10.7 KB
/
llm.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import json
import os
import re
import anthropic
import backoff
import openai
MAX_NUM_TOKENS = 4096
AVAILABLE_LLMS = [
"claude-3-5-sonnet-20240620",
"claude-3-5-sonnet-20241022",
"gpt-4o-mini-2024-07-18",
"gpt-4o-2024-05-13",
"gpt-4o-2024-08-06",
"o1-preview-2024-09-12",
"o1-mini-2024-09-12",
"deepseek-coder-v2-0724",
"llama3.1-405b",
# Anthropic Claude models via Amazon Bedrock
"bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
"bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0",
"bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
"bedrock/anthropic.claude-3-haiku-20240307-v1:0",
"bedrock/anthropic.claude-3-opus-20240229-v1:0",
# Anthropic Claude models Vertex AI
"vertex_ai/claude-3-opus@20240229",
"vertex_ai/claude-3-5-sonnet@20240620",
"vertex_ai/claude-3-5-sonnet-v2@20241022",
"vertex_ai/claude-3-sonnet@20240229",
"vertex_ai/claude-3-haiku@20240307",
]
# Get N responses from a single message, used for ensembling.
@backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
def get_batch_responses_from_llm(
msg,
client,
model,
system_message,
print_debug=False,
msg_history=None,
temperature=0.75,
n_responses=1,
):
if msg_history is None:
msg_history = []
if model in [
"gpt-4o-2024-05-13",
"gpt-4o-mini-2024-07-18",
"gpt-4o-2024-08-06",
]:
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=n_responses,
stop=None,
seed=0,
)
content = [r.message.content for r in response.choices]
new_msg_history = [
new_msg_history + [{"role": "assistant", "content": c}] for c in content
]
elif model == "deepseek-coder-v2-0724":
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model="deepseek-coder",
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=n_responses,
stop=None,
)
content = [r.message.content for r in response.choices]
new_msg_history = [
new_msg_history + [{"role": "assistant", "content": c}] for c in content
]
elif model == "llama-3-1-405b-instruct":
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model="meta-llama/llama-3.1-405b-instruct",
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=n_responses,
stop=None,
)
content = [r.message.content for r in response.choices]
new_msg_history = [
new_msg_history + [{"role": "assistant", "content": c}] for c in content
]
else:
content, new_msg_history = [], []
for _ in range(n_responses):
c, hist = get_response_from_llm(
msg,
client,
model,
system_message,
print_debug=False,
msg_history=None,
temperature=temperature,
)
content.append(c)
new_msg_history.append(hist)
if print_debug:
# Just print the first one.
print()
print("*" * 20 + " LLM START " + "*" * 20)
for j, msg in enumerate(new_msg_history[0]):
print(f'{j}, {msg["role"]}: {msg["content"]}')
print(content)
print("*" * 21 + " LLM END " + "*" * 21)
print()
return content, new_msg_history
@backoff.on_exception(backoff.expo, (openai.RateLimitError, openai.APITimeoutError))
def get_response_from_llm(
msg,
client,
model,
system_message,
print_debug=False,
msg_history=None,
temperature=0.75,
):
if msg_history is None:
msg_history = []
if "claude" in model:
new_msg_history = msg_history + [
{
"role": "user",
"content": [
{
"type": "text",
"text": msg,
}
],
}
]
response = client.messages.create(
model=model,
max_tokens=MAX_NUM_TOKENS,
temperature=temperature,
system=system_message,
messages=new_msg_history,
)
content = response.content[0].text
new_msg_history = new_msg_history + [
{
"role": "assistant",
"content": [
{
"type": "text",
"text": content,
}
],
}
]
elif model in [
"gpt-4o-2024-05-13",
"gpt-4o-mini-2024-07-18",
"gpt-4o-2024-08-06",
]:
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=1,
stop=None,
seed=0,
)
content = response.choices[0].message.content
new_msg_history = new_msg_history + [{"role": "assistant", "content": content}]
elif model in ["o1-preview-2024-09-12", "o1-mini-2024-09-12"]:
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model=model,
messages=[
{"role": "user", "content": system_message},
*new_msg_history,
],
temperature=1,
max_completion_tokens=MAX_NUM_TOKENS,
n=1,
#stop=None,
seed=0,
)
content = response.choices[0].message.content
new_msg_history = new_msg_history + [{"role": "assistant", "content": content}]
elif model == "deepseek-coder-v2-0724":
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model="deepseek-coder",
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=1,
stop=None,
)
content = response.choices[0].message.content
new_msg_history = new_msg_history + [{"role": "assistant", "content": content}]
elif model in ["meta-llama/llama-3.1-405b-instruct", "llama-3-1-405b-instruct"]:
new_msg_history = msg_history + [{"role": "user", "content": msg}]
response = client.chat.completions.create(
model="meta-llama/llama-3.1-405b-instruct",
messages=[
{"role": "system", "content": system_message},
*new_msg_history,
],
temperature=temperature,
max_tokens=MAX_NUM_TOKENS,
n=1,
stop=None,
)
content = response.choices[0].message.content
new_msg_history = new_msg_history + [{"role": "assistant", "content": content}]
else:
raise ValueError(f"Model {model} not supported.")
if print_debug:
print()
print("*" * 20 + " LLM START " + "*" * 20)
for j, msg in enumerate(new_msg_history):
print(f'{j}, {msg["role"]}: {msg["content"]}')
print(content)
print("*" * 21 + " LLM END " + "*" * 21)
print()
return content, new_msg_history
def extract_json_between_markers(llm_output):
# Regular expression pattern to find JSON content between ```json and ```
json_pattern = r"```json(.*?)```"
matches = re.findall(json_pattern, llm_output, re.DOTALL)
if not matches:
# Fallback: Try to find any JSON-like content in the output
json_pattern = r"\{.*?\}"
matches = re.findall(json_pattern, llm_output, re.DOTALL)
for json_string in matches:
json_string = json_string.strip()
try:
parsed_json = json.loads(json_string)
return parsed_json
except json.JSONDecodeError:
# Attempt to fix common JSON issues
try:
# Remove invalid control characters
json_string_clean = re.sub(r"[\x00-\x1F\x7F]", "", json_string)
parsed_json = json.loads(json_string_clean)
return parsed_json
except json.JSONDecodeError:
continue # Try next match
return None # No valid JSON found
def create_client(model):
if model.startswith("claude-"):
print(f"Using Anthropic API with model {model}.")
return anthropic.Anthropic(), model
elif model.startswith("bedrock") and "claude" in model:
client_model = model.split("/")[-1]
print(f"Using Amazon Bedrock with model {client_model}.")
return anthropic.AnthropicBedrock(), client_model
elif model.startswith("vertex_ai") and "claude" in model:
client_model = model.split("/")[-1]
print(f"Using Vertex AI with model {client_model}.")
return anthropic.AnthropicVertex(), client_model
elif 'gpt' in model:
print(f"Using OpenAI API with model {model}.")
return openai.OpenAI(), model
elif model in ["o1-preview-2024-09-12", "o1-mini-2024-09-12"]:
print(f"Using OpenAI API with model {model}.")
return openai.OpenAI(), model
elif model == "deepseek-coder-v2-0724":
print(f"Using OpenAI API with {model}.")
return openai.OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com"
), model
elif model == "llama3.1-405b":
print(f"Using OpenAI API with {model}.")
return openai.OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1"
), "meta-llama/llama-3.1-405b-instruct"
else:
raise ValueError(f"Model {model} not supported.")