forked from AntonOsika/gpt-engineer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.py
406 lines (341 loc) · 11.4 KB
/
ai.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
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
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import List, Optional, Union
import openai
import tiktoken
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage,
messages_from_dict,
messages_to_dict,
)
Message = Union[AIMessage, HumanMessage, SystemMessage]
logger = logging.getLogger(__name__)
@dataclass
class TokenUsage:
step_name: str
in_step_prompt_tokens: int
in_step_completion_tokens: int
in_step_total_tokens: int
total_prompt_tokens: int
total_completion_tokens: int
total_tokens: int
class AI:
def __init__(self, model_name="gpt-4", temperature=0.1, azure_endpoint=""):
"""
Initialize the AI class.
Parameters
----------
model_name : str, optional
The name of the model to use, by default "gpt-4".
temperature : float, optional
The temperature to use for the model, by default 0.1.
"""
self.temperature = temperature
self.azure_endpoint = azure_endpoint
self.model_name = (
fallback_model(model_name) if azure_endpoint == "" else model_name
)
self.llm = create_chat_model(self, self.model_name, self.temperature)
self.tokenizer = get_tokenizer(self.model_name)
logger.debug(f"Using model {self.model_name} with llm {self.llm}")
# initialize token usage log
self.cumulative_prompt_tokens = 0
self.cumulative_completion_tokens = 0
self.cumulative_total_tokens = 0
self.token_usage_log = []
def start(self, system: str, user: str, step_name: str) -> List[Message]:
"""
Start the conversation with a system message and a user message.
Parameters
----------
system : str
The content of the system message.
user : str
The content of the user message.
step_name : str
The name of the step.
Returns
-------
List[Message]
The list of messages in the conversation.
"""
messages: List[Message] = [
SystemMessage(content=system),
HumanMessage(content=user),
]
return self.next(messages, step_name=step_name)
def fsystem(self, msg: str) -> SystemMessage:
"""
Create a system message.
Parameters
----------
msg : str
The content of the message.
Returns
-------
SystemMessage
The created system message.
"""
return SystemMessage(content=msg)
def fuser(self, msg: str) -> HumanMessage:
"""
Create a user message.
Parameters
----------
msg : str
The content of the message.
Returns
-------
HumanMessage
The created user message.
"""
return HumanMessage(content=msg)
def fassistant(self, msg: str) -> AIMessage:
"""
Create an AI message.
Parameters
----------
msg : str
The content of the message.
Returns
-------
AIMessage
The created AI message.
"""
return AIMessage(content=msg)
def next(
self,
messages: List[Message],
prompt: Optional[str] = None,
*,
step_name: str,
) -> List[Message]:
"""
Advances the conversation by sending message history
to LLM and updating with the response.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
prompt : Optional[str], optional
The prompt to use, by default None.
step_name : str
The name of the step.
Returns
-------
List[Message]
The updated list of messages in the conversation.
"""
"""
Advances the conversation by sending message history
to LLM and updating with the response.
"""
if prompt:
messages.append(self.fuser(prompt))
logger.debug(f"Creating a new chat completion: {messages}")
callsbacks = [StreamingStdOutCallbackHandler()]
response = self.llm(messages, callbacks=callsbacks) # type: ignore
messages.append(response)
logger.debug(f"Chat completion finished: {messages}")
self.update_token_usage_log(
messages=messages, answer=response.content, step_name=step_name
)
return messages
@staticmethod
def serialize_messages(messages: List[Message]) -> str:
"""
Serialize a list of messages to a JSON string.
Parameters
----------
messages : List[Message]
The list of messages to serialize.
Returns
-------
str
The serialized messages as a JSON string.
"""
return json.dumps(messages_to_dict(messages))
@staticmethod
def deserialize_messages(jsondictstr: str) -> List[Message]:
"""
Deserialize a JSON string to a list of messages.
Parameters
----------
jsondictstr : str
The JSON string to deserialize.
Returns
-------
List[Message]
The deserialized list of messages.
"""
return list(messages_from_dict(json.loads(jsondictstr))) # type: ignore
def update_token_usage_log(
self, messages: List[Message], answer: str, step_name: str
) -> None:
"""
Update the token usage log with the number of tokens used in the current step.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
answer : str
The answer from the AI.
step_name : str
The name of the step.
"""
prompt_tokens = self.num_tokens_from_messages(messages)
completion_tokens = self.num_tokens(answer)
total_tokens = prompt_tokens + completion_tokens
self.cumulative_prompt_tokens += prompt_tokens
self.cumulative_completion_tokens += completion_tokens
self.cumulative_total_tokens += total_tokens
self.token_usage_log.append(
TokenUsage(
step_name=step_name,
in_step_prompt_tokens=prompt_tokens,
in_step_completion_tokens=completion_tokens,
in_step_total_tokens=total_tokens,
total_prompt_tokens=self.cumulative_prompt_tokens,
total_completion_tokens=self.cumulative_completion_tokens,
total_tokens=self.cumulative_total_tokens,
)
)
def format_token_usage_log(self) -> str:
"""
Format the token usage log as a CSV string.
Returns
-------
str
The token usage log formatted as a CSV string.
"""
result = "step_name,"
result += "prompt_tokens_in_step,completion_tokens_in_step,total_tokens_in_step"
result += ",total_prompt_tokens,total_completion_tokens,total_tokens\n"
for log in self.token_usage_log:
result += log.step_name + ","
result += str(log.in_step_prompt_tokens) + ","
result += str(log.in_step_completion_tokens) + ","
result += str(log.in_step_total_tokens) + ","
result += str(log.total_prompt_tokens) + ","
result += str(log.total_completion_tokens) + ","
result += str(log.total_tokens) + "\n"
return result
def num_tokens(self, txt: str) -> int:
"""
Get the number of tokens in a text.
Parameters
----------
txt : str
The text to count the tokens in.
Returns
-------
int
The number of tokens in the text.
"""
return len(self.tokenizer.encode(txt))
def num_tokens_from_messages(self, messages: List[Message]) -> int:
"""
Get the total number of tokens used by a list of messages.
Parameters
----------
messages : List[Message]
The list of messages to count the tokens in.
Returns
-------
int
The total number of tokens used by the messages.
"""
"""Returns the number of tokens used by a list of messages."""
n_tokens = 0
for message in messages:
n_tokens += (
4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
)
n_tokens += self.num_tokens(message.content)
n_tokens += 2 # every reply is primed with <im_start>assistant
return n_tokens
def fallback_model(model: str) -> str:
"""
Retrieve the specified model, or fallback to "gpt-3.5-turbo" if the model is not available.
Parameters
----------
model : str
The name of the model to retrieve.
Returns
-------
str
The name of the retrieved model, or "gpt-3.5-turbo" if the specified model is not available.
"""
try:
openai.Model.retrieve(model)
return model
except openai.InvalidRequestError:
print(
f"Model {model} not available for provided API key. Reverting "
"to gpt-3.5-turbo. Sign up for the GPT-4 wait list here: "
"https://openai.com/waitlist/gpt-4-api\n"
)
return "gpt-3.5-turbo"
def create_chat_model(self, model: str, temperature) -> BaseChatModel:
"""
Create a chat model with the specified model name and temperature.
Parameters
----------
model : str
The name of the model to create.
temperature : float
The temperature to use for the model.
Returns
-------
BaseChatModel
The created chat model.
"""
if self.azure_endpoint:
return AzureChatOpenAI(
openai_api_base=self.azure_endpoint,
openai_api_version="2023-05-15", # might need to be flexible in the future
deployment_name=model,
openai_api_type="azure",
streaming=True,
)
# Fetch available models from OpenAI API
supported = [model["id"] for model in openai.Model.list()["data"]]
if model not in supported:
raise ValueError(
f"Model {model} is not supported, supported models are: {supported}"
)
return ChatOpenAI(
model=model,
temperature=temperature,
streaming=True,
client=openai.ChatCompletion,
)
def get_tokenizer(model: str):
"""
Get the tokenizer for the specified model.
Parameters
----------
model : str
The name of the model to get the tokenizer for.
Returns
-------
Tokenizer
The tokenizer for the specified model.
"""
if "gpt-4" in model or "gpt-3.5" in model:
return tiktoken.encoding_for_model(model)
logger.debug(
f"No encoder implemented for model {model}."
"Defaulting to tiktoken cl100k_base encoder."
"Use results only as estimates."
)
return tiktoken.get_encoding("cl100k_base")
def serialize_messages(messages: List[Message]) -> str:
return AI.serialize_messages(messages)