-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
287 lines (244 loc) · 8.18 KB
/
Copy pathmodel.py
File metadata and controls
287 lines (244 loc) · 8.18 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
"""
Model abstraction layer for various LLM backends.
This module provides a unified interface for making completions requests to
different LLM providers including OpenAI, Anthropic, and DeepSeek.
"""
import json
from abc import ABC, abstractmethod
from typing import List
from .api_requests import (
create_anthropic_config,
create_chatgpt_config,
request_anthropic_engine,
request_chatgpt_engine,
)
class DecoderBase(ABC):
"""
Abstract base class for LLM decoders.
Provides a common interface for generating code completions from
different language model backends.
"""
def __init__(
self,
name: str,
logger,
batch_size: int = 1,
temperature: float = 0.8,
max_new_tokens: int = 1024,
) -> None:
"""
Initialize the decoder.
Args:
name: Name of the model
logger: Logger instance for logging
batch_size: Number of completions to generate per request
temperature: Sampling temperature
max_new_tokens: Maximum number of tokens to generate
"""
logger.info("Initializing a decoder model: {} ...".format(name))
self.name = name
self.logger = logger
self.batch_size = batch_size
self.temperature = temperature
self.max_new_tokens = max_new_tokens
@abstractmethod
def codegen(
self, message: str, num_samples: int = 1, prompt_cache: bool = False
) -> List[dict]:
"""
Generate code completions for the given message.
Args:
message: Input message/prompt
num_samples: Number of samples to generate
prompt_cache: Whether to use prompt caching
Returns:
List of dictionaries containing responses and usage information
"""
pass
@abstractmethod
def is_direct_completion(self) -> bool:
"""
Check if this decoder supports direct completion mode.
Returns:
True if direct completion is supported, False otherwise
"""
pass
def __repr__(self) -> str:
return self.name
def __str__(self) -> str:
return self.name
class OpenAIChatDecoder(DecoderBase):
"""
Decoder for OpenAI chat models (GPT-4, GPT-3.5, etc.).
"""
def __init__(self, name: str, logger, **kwargs) -> None:
super().__init__(name, logger, **kwargs)
def codegen(
self, message: str, num_samples: int = 1, prompt_cache: bool = False
) -> List[dict]:
"""
Generate completions using OpenAI's chat API.
Args:
message: Input message/prompt
num_samples: Number of samples to generate
prompt_cache: Whether to use prompt caching (not used for OpenAI)
Returns:
List of dictionaries containing responses and usage information
"""
if self.temperature == 0:
assert num_samples == 1
batch_size = min(self.batch_size, num_samples)
config = create_chatgpt_config(
message=message,
max_tokens=self.max_new_tokens,
temperature=self.temperature,
batch_size=batch_size,
model=self.name,
)
ret = request_chatgpt_engine(config, self.logger)
if ret:
responses = [choice.message.content for choice in ret.choices]
completion_tokens = ret.usage.completion_tokens
prompt_tokens = ret.usage.prompt_tokens
else:
responses = [""]
completion_tokens = 0
prompt_tokens = 0
# When generating multiple samples from the same input,
# the input tokens are only charged once according to OpenAI API.
# Therefore, we assume the request cost is only counted for the first sample.
trajs = [
{
"response": responses[0],
"usage": {
"completion_tokens": completion_tokens,
"prompt_tokens": prompt_tokens,
},
}
]
for response in responses[1:]:
trajs.append(
{
"response": response,
"usage": {
"completion_tokens": 0,
"prompt_tokens": 0,
},
}
)
return trajs
def is_direct_completion(self) -> bool:
return False
class AnthropicChatDecoder(OpenAIChatDecoder):
"""
Decoder for Anthropic Claude models.
Inherits from OpenAIChatDecoder since Claude uses an OpenAI-compatible
proxy interface, making the calling method identical.
"""
def __init__(self, name: str, logger, **kwargs) -> None:
super().__init__(name, logger, **kwargs)
def is_direct_completion(self) -> bool:
return False
class DeepSeekChatDecoder(DecoderBase):
"""
Decoder for DeepSeek models.
"""
def __init__(self, name: str, logger, **kwargs) -> None:
super().__init__(name, logger, **kwargs)
def codegen(
self, message: str, num_samples: int = 1, prompt_cache: bool = False
) -> List[dict]:
"""
Generate completions using DeepSeek's API.
Args:
message: Input message/prompt
num_samples: Number of samples to generate
prompt_cache: Whether to use prompt caching (not used for DeepSeek)
Returns:
List of dictionaries containing responses and usage information
"""
if self.temperature == 0:
assert num_samples == 1
trajs = []
for _ in range(num_samples):
config = create_chatgpt_config(
message=message,
max_tokens=self.max_new_tokens,
temperature=self.temperature,
batch_size=1,
model=self.name,
)
ret = request_chatgpt_engine(
config, self.logger, base_url="https://api.deepseek.com"
)
if ret:
trajs.append(
{
"response": ret.choices[0].message.content,
"usage": {
"completion_tokens": ret.usage.completion_tokens,
"prompt_tokens": ret.usage.prompt_tokens,
},
}
)
else:
trajs.append(
{
"response": "",
"usage": {
"completion_tokens": 0,
"prompt_tokens": 0,
},
}
)
return trajs
def is_direct_completion(self) -> bool:
return False
def make_model(
model: str,
backend: str,
logger,
batch_size: int = 1,
max_tokens: int = 1024,
temperature: float = 0.0,
):
"""
Factory function to create a decoder instance.
Args:
model: Name of the model to use
backend: Backend type ("openai", "anthropic", or "deepseek")
logger: Logger instance
batch_size: Number of completions per request
max_tokens: Maximum tokens to generate
temperature: Sampling temperature
Returns:
A decoder instance for the specified backend
Raises:
NotImplementedError: If the backend is not supported
"""
if backend == "openai":
return OpenAIChatDecoder(
name=model,
logger=logger,
batch_size=batch_size,
max_new_tokens=max_tokens,
temperature=temperature,
)
elif backend == "anthropic":
return AnthropicChatDecoder(
name=model,
logger=logger,
batch_size=batch_size,
max_new_tokens=max_tokens,
temperature=temperature,
)
elif backend == "deepseek":
return DeepSeekChatDecoder(
name=model,
logger=logger,
batch_size=batch_size,
max_new_tokens=max_tokens,
temperature=temperature,
)
else:
raise NotImplementedError(f"Backend '{backend}' is not supported")