-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathlm.py
251 lines (209 loc) · 8.2 KB
/
lm.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
import random
import threading
import time
import dspy
import os
from openai import OpenAI
from typing import Optional, Literal, Any
from dashscope import Generation
# This code is originally sourced from Repository STORM
# URL: [https://github.com/stanford-oval/storm]
class OpenAIModel_dashscope(dspy.OpenAI):
"""A wrapper class for dspy.OpenAI."""
def __init__(
self,
model: str = "gpt-4o",
max_tokens: int = 2000,
api_key: Optional[str] = None,
**kwargs
):
super().__init__(model=model, api_key=api_key, **kwargs)
self.model = model
self._token_usage_lock = threading.Lock()
self.max_tokens = max_tokens
self.prompt_tokens = 0
self.completion_tokens = 0
def log_usage(self, response):
"""Log the total tokens from the OpenAI API response."""
usage_data = response.get('usage')
if usage_data:
with self._token_usage_lock:
self.prompt_tokens += usage_data.get('input_tokens', 0)
self.completion_tokens += usage_data.get('output_tokens', 0)
def get_usage_and_reset(self):
"""Get the total tokens used and reset the token usage."""
usage = {
self.kwargs.get('model') or self.kwargs.get('engine'):
{'prompt_tokens': self.prompt_tokens, 'completion_tokens': self.completion_tokens}
}
self.prompt_tokens = 0
self.completion_tokens = 0
return usage
def __call__(
self,
prompt: str,
only_completed: bool = True,
return_sorted: bool = False,
**kwargs,
) -> list[dict[str, Any]]:
"""Copied from dspy/dsp/modules/gpt3.py with the addition of tracking token usage."""
assert only_completed, "for now"
assert return_sorted is False, "for now"
CALL_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
LM_KEY = os.getenv('LM_KEY')
HEADERS = {
'Content-Type': 'application/json',
"Authorization": f"Bearer {LM_KEY}"
}
kwargs = dict(
model=self.model,
messages=[{"role": "user", "content": prompt}],
max_completion_tokens=self.max_tokens,
stream=False,
)
import requests
max_try = 3
for i in range(max_try):
try:
ret = requests.post(CALL_URL, json=kwargs,
headers=HEADERS, timeout=180)
if ret.status_code != 200:
raise Exception(f"http status_code: {ret.status_code}\n{ret.content}")
ret_json = ret.json()
for output in ret_json['choices']:
if output['finish_reason'] not in ['stop', 'function_call']:
raise Exception(f'openai finish with error...\n{ret_json}')
return [ret_json['choices'][0]['message']['content']]
except Exception as e:
print(f"请求失败: {e}. 尝试重新请求...")
time.sleep(1)
class DeepSeekModel(dspy.OpenAI):
"""A wrapper class for dspy.OpenAI."""
def __init__(
self,
model: str = "deepseek-chat",
api_key: Optional[str] = None,
**kwargs
):
super().__init__(model=model, api_key=api_key, **kwargs)
self.model = model
self.api_key = api_key
self._token_usage_lock = threading.Lock()
self.prompt_tokens = 0
self.completion_tokens = 0
def log_usage(self, response):
"""Log the total tokens from the OpenAI API response."""
usage_data = response.get('usage')
if usage_data:
with self._token_usage_lock:
self.prompt_tokens += usage_data.get('input_tokens', 0)
self.completion_tokens += usage_data.get('output_tokens', 0)
def get_usage_and_reset(self):
"""Get the total tokens used and reset the token usage."""
usage = {
self.kwargs.get('model') or self.kwargs.get('engine'):
{'prompt_tokens': self.prompt_tokens, 'completion_tokens': self.completion_tokens}
}
self.prompt_tokens = 0
self.completion_tokens = 0
return usage
def __call__(
self,
prompt: str,
only_completed: bool = True,
return_sorted: bool = False,
**kwargs,
) -> list[dict[str, Any]]:
"""Copied from dspy/dsp/modules/gpt3.py with the addition of tracking token usage."""
assert only_completed, "for now"
assert return_sorted is False, "for now"
LM_KEY = os.getenv('LM_KEY')
client = OpenAI(api_key=LM_KEY, base_url="https://api.deepseek.com")
max_retries = 3
attempt = 0
messages = []
if self.model != "deepseek-reasoner":
messages.append({"role": "system", "content": "You are a helpful assistant"})
messages.append({"role": "user", "content": prompt})
print(messages)
while attempt < max_retries:
try:
response = client.chat.completions.create(
model=self.model,
messages=messages,
stream=False
)
choices = response["output"]["choices"]
break
except Exception as e:
delay = random.uniform(0, 3)
time.sleep(delay)
attempt += 1
self.log_usage(response)
completed_choices = [c for c in choices if c["finish_reason"] != "length"]
if only_completed and len(completed_choices):
choices = completed_choices
completions = [c['message']['content'] for c in choices]
return completions
class QwenModel(dspy.OpenAI):
"""A wrapper class for dspy.OpenAI."""
def __init__(
self,
model: str = "qwen-max-allinone",
api_key: Optional[str] = None,
**kwargs
):
super().__init__(model=model, api_key=api_key, **kwargs)
self.model = model
self.api_key = api_key
self._token_usage_lock = threading.Lock()
self.prompt_tokens = 0
self.completion_tokens = 0
def log_usage(self, response):
"""Log the total tokens from the OpenAI API response."""
usage_data = response.get('usage')
if usage_data:
with self._token_usage_lock:
self.prompt_tokens += usage_data.get('input_tokens', 0)
self.completion_tokens += usage_data.get('output_tokens', 0)
def get_usage_and_reset(self):
"""Get the total tokens used and reset the token usage."""
usage = {
self.kwargs.get('model') or self.kwargs.get('engine'):
{'prompt_tokens': self.prompt_tokens, 'completion_tokens': self.completion_tokens}
}
self.prompt_tokens = 0
self.completion_tokens = 0
return usage
def __call__(
self,
prompt: str,
only_completed: bool = True,
return_sorted: bool = False,
**kwargs,
) -> list[dict[str, Any]]:
"""Copied from dspy/dsp/modules/gpt3.py with the addition of tracking token usage."""
assert only_completed, "for now"
assert return_sorted is False, "for now"
messages = [{'role': 'user', 'content': prompt}]
max_retries = 3
attempt = 0
while attempt < max_retries:
try:
response = Generation.call(
model=self.model,
messages=messages,
result_format='message',
)
choices = response["output"]["choices"]
break
except Exception as e:
delay = random.uniform(0, 10)
time.sleep(delay)
attempt += 1
self.log_usage(response)
completed_choices = [c for c in choices if c["finish_reason"] != "length"]
if only_completed and len(completed_choices):
choices = completed_choices
completions = [c['message']['content'] for c in choices]
return completions