-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
596 lines (482 loc) · 20.2 KB
/
tools.py
File metadata and controls
596 lines (482 loc) · 20.2 KB
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
#other apis
import requests
import os
#gemini
from google import genai
from google.genai.types import GenerationConfig
from google.genai import types
#anthropic
import anthropic
#nebius
from openai import OpenAI
#env
from dotenv import load_dotenv
import os
load_dotenv()
# clean string
import json
import os
from scripts.clean import clean_markdown
# other apis
import requests
# gemini
from google import genai
from google.genai import types
# env
from dotenv import load_dotenv
# any model
from model.LLM import LLM
load_dotenv()
def get_model(model_name):
models = {
"your_model":your_model("your_huggingface_model_path").generate,
"gemini2":google_gemini.gemini2_flash,
"gemini2-5":google_gemini.gemini2_5_flash,
"gemini2-5-think":google_gemini.gemini2_5_flash_thinking,
"sonnet3-7-gen":sonnet.sonnet_37_gen,
"sonnet3-7":sonnet.sonnet_37,
"sonnet3-7-think":sonnet.sonnet_37_thinking,
"sonnet3-5":sonnet.sonnet_35,
"judge":sonnet.sonnet_37_judge,
"gen-think":gpt4o_mini,
"r1":hyperbolic.r1,
"v3":hyperbolic.deepseek_v3,
}
return models.get(model_name, None)
# ---------------- GEMINI CONFIGS ---------------- #
CONFIG_4_ANSWER = types.GenerateContentConfig(
temperature=0.6,
top_p=0.95,
top_k=2,
seed=0,
max_output_tokens=1024,
safety_settings=[
types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="OFF"),
],
)
CONFIG_4_GEN = types.GenerateContentConfig(
temperature=1.2,
top_p=0.90,
top_k=10,
seed=0,
max_output_tokens=1024,
safety_settings=[
types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="OFF"),
],
)
SAFETY_SETTINGS = [
types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="OFF"),
types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="OFF"),
]
def get_processed_cids(jsonl_path):
processed_cids = set()
if os.path.exists(jsonl_path):
with open(jsonl_path, "r", encoding="utf-8") as f:
for line in f:
try:
data = json.loads(line.strip())
processed_cids.add(data["CID"])
except json.JSONDecodeError:
print("Warning: Skipping corrupted line in JSONL file")
return processed_cids
#helper function for cr. anthropic cookbook
def print_thinking_response(response):
"""Pretty print a message response with thinking blocks."""
print("\n==== FULL RESPONSE ====")
for block in response.content:
if block.type == "thinking":
print("\n🧠 THINKING BLOCK:")
# Show truncated thinking for readability
print(block.thinking[:500] + "..." if len(block.thinking) > 500 else block.thinking)
elif block.type == "redacted_thinking":
print("\n🔒 REDACTED THINKING BLOCK:")
print(f"[Data length: {len(block.data) if hasattr(block, 'data') else 'N/A'}]")
elif block.type == "text":
print("\n✓ FINAL ANSWER:")
print(block.text)
print("\n==== END RESPONSE ====")
#helper function for cr. anthropic cookbook
def return_thinking_response(response):
"""Pretty print a message response with thinking blocks and return formatted output."""
output = []
output.append("\n==== FULL RESPONSE ====")
for block in response.content:
if block.type == "thinking":
output.append("\n🧠 THINKING BLOCK:")
thinking_text = block.thinking[:500] + "..." if len(block.thinking) > 500 else block.thinking
output.append(thinking_text)
elif block.type == "redacted_thinking":
output.append("\n🔒 REDACTED THINKING BLOCK:")
output.append(f"[Data length: {len(block.data) if hasattr(block, 'data') else 'N/A'}]")
elif block.type == "text":
output.append("\n✓ FINAL ANSWER:")
output.append(block.text)
output.append("\n==== END RESPONSE ====")
return "\n".join(output)
# custom you trained model
class your_model(LLM):
from transformers import AutoTokenizer, AutoModelForCausalLM
def __init__(self,hf_path:str=""):
self.hf_path=hf_path
self.tokenizer = AutoTokenizer.from_pretrained(self.hf_path)
self.model = AutoModelForCausalLM.from_pretrained(self.hf_path)
def generate(self, prompt: str, **kwargs) -> str:
#llama3 template adjust your model here
messages = [
{"role": "user", "content": f"{prompt}"},
]
inputs = self.tokenizer.apply_chat_template(messages,add_generation_prompt=True,tokenize=True,return_dict=True,return_tensors="pt").to("gpu")
outputs = self.model.generate(**inputs, max_new_tokens=40)
return self.tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])
class sonnet:
def sonnet_37(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-7-sonnet-20250219",
messages=[
{
"role": "user",
"content": input_prompt,
},
],
max_tokens=1024,
temperature=0.6,
top_p = 0.95,
)
return response.content[0].text
except:
return "Error: API"
def sonnet_37_gen(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-7-sonnet-20250219",
messages=[
{
"role": "user",
"content": input_prompt,
},
],
max_tokens=1024,
temperature=1,
top_p = 0.90,
)
return response.content[0].text
except:
return "Error: API"
def sonnet_37_judge(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-7-sonnet-20250219",
messages=[
{
"role": "user",
"content": "Help me scoring character role-playing, score point between 0-5 , score have two type: thinking(doec thiking response look like reference character) ,acting(does response acting like the character reference), the output must be this format: think_score,act_score example 3,2,"+input_prompt,
},
],
max_tokens=1024,
temperature=0.1,
top_p = 0.90,
)
return response.content[0].text
except:
return "Error: API"
def sonnet_37_thinking(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-7-sonnet-20250219",
thinking={
"type": "enabled",
"budget_tokens": 1024
},
max_tokens=2000,
temperature=1,
#top_p = 0.95,
messages=[
{
"role": "user",
"content": input_prompt,
},
],
)
return return_thinking_response(response)
except:
return "Error: API"
def sonnet_35(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-5-sonnet-20241022",
messages=[
{
"role": "user",
"content": input_prompt,
},
],
max_tokens= 1024,
temperature= 0.6,
top_p = 0.95,
)
return response.content[0].text
except:
return "Error: API"
def think_gen(input_prompt:str="")->str:
client = anthropic.Anthropic(api_key=os.environ["CLAUDE_KEY"])
try:
response=client.messages.create(
model="claude-3-5-sonnet-20241022",
messages=[
{
"role": "user",
"content": """Your task is to **separate** internal thought("thinking") from external behavior ("acting") in the text response.
Wrap the internal thought process in `<thinking>...</thinking>` and the final response or action in `<acting>...</acting>`.
Now process text response:"""+input_prompt,
},
],
max_tokens= 1024,
temperature= 0.6,
top_p = 0.95,
)
return response.content[0].text
except:
return "Error: API"
class hyperbolic:
def r1(input_prompt: str = "") -> str:
url = "https://api.hyperbolic.xyz/v1/chat/completions"
key = os.getenv("R1_API_KEY")
if not key:
raise ValueError("R1_API_KEY is missing from environment variables")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {key}"
}
data = {
"messages": [{"role": "user", "content": input_prompt}],
"model": "deepseek-ai/DeepSeek-R1",
"temperature": 0.6,
"max_tokens": 1024,
"top_p": 0.95,
"top_k": 2,
}
try:
response = requests.post(url, headers=headers, json=data,timeout=1000)
response.raise_for_status()
if not response.text.strip():
print("Warning: API returned an empty response")
return "Error: API Empty response from API"
response_data = response.json()
if "choices" not in response_data or not response_data["choices"]:
print(f"Error: Unexpected API response format: {response_data}")
return f"Error: API Invalid response format - {response_data}"
return clean_markdown(response_data["choices"][0]["message"]["content"])
except requests.exceptions.Timeout:
return "Error: API request timed out"
except requests.exceptions.RequestException as e:
return f"Error: API request failed - {str(e)}"
except ValueError as e:
return f"Error: API JSON decoding failed - {str(e)}"
def gen_think_v3(input_prompt:str="")->str:
url = "https://api.hyperbolic.xyz/v1/chat/completions"
key = os.getenv("R1_API_KEY")
if not key:
raise ValueError("R1_API_KEY is missing from environment variables")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {key}"
}
data = {
"messages": [{"role": "user", "content": f"""Your task is to **separate** internal thought("thinking") from external behavior ("acting") in the text response.Wrap the internal thought process in `<thinking>...</thinking>` and the final response or action in `<acting>...</acting>`.
Now process text response: {input_prompt}"""}],
"model": "deepseek-ai/DeepSeek-V3-0324",
"temperature": 0.1,
"max_tokens": 1024,
"top_p": 0.70,
"top_k": 1,
}
try:
response = requests.post(url, headers=headers, json=data,timeout=1000)
response.raise_for_status()
if not response.text.strip():
return "Error: API Empty response from API"
response_data = response.json()
if "choices" not in response_data or not response_data["choices"]:
print(f"Error: API Unexpected API response format: {response_data}")
return f"Error: API Invalid response format - {response_data}"
return clean_markdown(response_data["choices"][0]["message"]["content"])
except requests.exceptions.Timeout:
return "Error: API request timed out"
except requests.exceptions.RequestException as e:
return f"Error: API request failed - {str(e)}"
except ValueError as e:
return f"Error: API JSON decoding failed - {str(e)}"
def deepseek_v3(input_prompt:str="")->str:
url = "https://api.hyperbolic.xyz/v1/chat/completions"
key = os.getenv("R1_API_KEY")
if not key:
raise ValueError("R1_API_KEY is missing from environment variables")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {key}"
}
data = {
"messages": [{"role": "user", "content": input_prompt}],
"model": "deepseek-ai/DeepSeek-V3-0324",
"temperature": 0.6,
"max_tokens": 1024,
"top_p": 0.95,
"top_k": 2,
}
try:
response = requests.post(url, headers=headers, json=data,timeout=1000)
response.raise_for_status()
if not response.text.strip():
return "Error: API Empty response from API"
response_data = response.json()
if "choices" not in response_data or not response_data["choices"]:
print(f"Error: API Unexpected API response format: {response_data}")
return f"Error: API Invalid response format - {response_data}"
return clean_markdown(response_data["choices"][0]["message"]["content"])
except requests.exceptions.Timeout:
return "Error: API request timed out"
except requests.exceptions.RequestException as e:
return f"Error: API request failed - {str(e)}"
except ValueError as e:
return f"Error: API JSON decoding failed - {str(e)}"
def deepseek_v3(input_prompt:str="")->str:
url = "https://api.deepseek.com/chat/completions"
key = os.getenv("R1_API_KEY")
if not key:
raise ValueError("R1_API_KEY is missing from environment variables")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {key}"
}
data = {
"messages": [{"role": "user", "content": input_prompt}],
"model": "deepseek-chat",
'stream': False,
"temperature": 0.6,
"max_tokens": 1024,
"top_p": 0.95,
"top_k": 2,
}
try:
response = requests.post(url, headers=headers, json=data,timeout=1000)
response.raise_for_status()
if not response.text.strip():
return "Error: API Empty response from API"
response_data = response.json()
if "choices" not in response_data or not response_data["choices"]:
print(f"Error: API Unexpected API response format: {response_data}")
return f"Error: API Invalid response format - {response_data}"
return clean_markdown(response_data["choices"][0]["message"]["content"])
except requests.exceptions.Timeout:
return "Error: API request timed out"
except requests.exceptions.RequestException as e:
return f"Error: API request failed - {str(e)}"
except ValueError as e:
return f"Error: API JSON decoding failed - {str(e)}"
def gpt4o_mini(input_prompt:str="")->str:
client=client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini-2024-07-18",
messages=[{"role": "user", "content": input_prompt}],
temperature=0.1,
)
return response.choices[0].message.content
class google_gemini:
def gemini2_flash_lite(input_prompt:str="")->str:
client = genai.Client(api_key=os.getenv("GEMINI_API"))
try:
response = client.models.generate_content(
model="gemini-2.0-flash-lite",
contents=input_prompt,
config=types.GenerateContentConfig(
max_output_tokens=1024,
temperature=0.6,
top_p=0.95,
top_k=2,
safety_settings=SAFETY_SETTINGS,
)
)
return response.text
except:
return "Error: API"
def gemini2_flash_thinking(input_prompt:str="")->str:
client = genai.Client(api_key=os.getenv("GEMINI_API"))
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=input_prompt,
config=types.GenerateContentConfig(
max_output_tokens=1024,
temperature=0.6,
top_p=0.95,
top_k=2,
thinking_config=types.ThinkingConfig(thinking_budget=512),
safety_settings=SAFETY_SETTINGS,
)
)
return response.text
def gemini2_flash(input_prompt:str="")->str:
client = genai.Client(api_key=os.getenv("GEMINI_API"))
try:
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=input_prompt,
config=types.GenerateContentConfig(
max_output_tokens=1024,
temperature=0.6,
top_p=0.95,
top_k=2,
safety_settings=SAFETY_SETTINGS,
)
)
return response.text
except:
return "Error: API"
def gemini2_5_flash_thinking(input_prompt:str="")->str:
client = genai.Client(api_key=os.getenv("GEMINI_API"))
try:
response = client.models.generate_content(
model="gemini-2.5-flash-preview-04-17",
contents=input_prompt,
config=types.GenerateContentConfig(
max_output_tokens=1024,
temperature=0.6,
top_p=0.95,
top_k=2,
thinking_config=types.ThinkingConfig(thinking_budget=512),
safety_settings=SAFETY_SETTINGS,
)
)
return response.text
except:
return "Error: API"
def gemini2_5_flash(input_prompt:str="")->str:
client = genai.Client(api_key=os.getenv("GEMINI_API"))
try:
response = client.models.generate_content(
model="gemini-2.5-flash-preview-04-17",
contents=input_prompt,
config=types.GenerateContentConfig(
max_output_tokens=1024,
temperature=0.6,
top_p=0.95,
top_k=2,
safety_settings=SAFETY_SETTINGS,
)
)
return response.text
except:
return "Error: API"