Repository navigation
Expand file tree
/
Copy pathcall_api.py
More file actions
141 lines (120 loc) · 4.62 KB
/
Copy pathcall_api.py
File metadata and controls
141 lines (120 loc) · 4.62 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
from utils import read_json, print_json, solve_dict, solve_list, read_jsonl
from openai import OpenAI
import time
import ast
import copy
import sys
import concurrent
from tqdm import tqdm
import json
from pathlib import Path
import os
import random
import argparse
import threading
from typing import Literal
class Ontology:
def __init__(self,
temperature=0.7,
top_p=0.95,
model: str = "gpt-oss-120b",
max_retries: int = 5,
port_id: str = "28001",
system_format: list | None = None,
user_format: list | None = None,
res_assert: list | None = None,
return_type: Literal["dict", "list", "str"] = "dict",
need_system: bool = False
):
self.temperature = temperature
self.top_p = top_p
self.model = model
self.max_retries = max_retries
self.port_id = port_id
self.system_format = [] if system_format is None else system_format
self.user_format = [] if user_format is None else user_format
self.res_assert = [] if res_assert is None else res_assert
self.return_type = return_type
self.need_system = need_system
_thread_local = threading.local()
def get_client(onto):
if not hasattr(_thread_local, "client"):
_thread_local.client = OpenAI(
base_url=f"http://127.0.0.1:{onto.port_id}/v1",
api_key="...",
)
return _thread_local.client
def prompt_function(content, prompt_template, onto):
temperature = onto.temperature
top_p = onto.top_p
user_params = {key: content[key] for key in onto.user_format}
user_prompt = prompt_template["user_prompt"].format(**user_params)
if onto.need_system:
system_params = {key: content[key] for key in onto.system_format}
system_prompt = prompt_template["system_prompt"].format(**system_params)
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}]
else :
messages = [{"role": "user", "content": user_prompt}]
client = get_client(onto)
for i in range(onto.max_retries):
try:
start = time.time()
response = client.chat.completions.create(
model=onto.model,
temperature=temperature,
top_p=top_p,
messages=messages,
timeout=200,
#seed=3407
)
answer_content = response.choices[0].message.content
end = time.time()
#print('answer_content :\n', answer_content)
#print("usage :\n", response.usage)
if onto.return_type == "list" :
ans = solve_list(answer_content)
elif onto.return_type == "dict" :
ans = solve_dict(answer_content)
elif onto.return_type == "str" :
ans = answer_content
assert ans, "empty result"
if onto.return_type == "dict" :
for check in onto.res_assert :
assert check in ans, f"{check} not in ans"
return ans
except Exception as e:
print(f"at {i+1} time err: {e}")
def process_tasks_concurrently(content_list, prompt_template, func, onto, max_workers=5):
total = len(content_list)
print(f"begin to solve {total} tasks, workers: {max_workers}")
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_path = {
executor.submit(func, content, prompt_template, onto): content
for content in content_list
}
try:
for future in tqdm(
concurrent.futures.as_completed(future_to_path),
total=total,
desc="Processing",
) :
content = future_to_path[future]
try:
result = future.result()
if "error" in result and isinstance(result, dict):
print(f"task: {content}")
print(f"err: {result['error']}")
print("=" * 50)
else:
results.append((content, result))
except Exception as e:
print(f"solve {content} err: {str(e)}")
except KeyboardInterrupt:
print("cut")
for future in future_to_path:
future.cancel()
executor.shutdown(wait=False)
print("stop")
return results