-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.py
179 lines (141 loc) · 5.7 KB
/
common.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
import argparse
import json
import time
import warnings
from datetime import datetime
from pathlib import Path
from typing import Any, cast
import openai
from openai.types.chat import ChatCompletion
from ratelimit import limits, sleep_and_retry
class ExchangeLogger:
def __init__(self) -> None:
self.file: Path | None = None
self.print_log = False
def config(self, file: Path, print_log: bool = False) -> None:
self.file = file
self.print_log = print_log
def log_exchange(self, params: dict[str, Any], response: dict[str, Any]) -> None:
if self.file is None:
raise ValueError("Must call config() before logging exchanges.")
log = {"params": params, "response": response}
with self.file.open("a") as f:
json.dump(log, f)
f.write("\n")
if self.print_log:
print(json.dumps(log, indent=2))
print()
logger = ExchangeLogger()
def get_key(key_file: Path, key_name: str) -> str:
keys = json.loads(key_file.read_text())
return cast(str, keys[key_name])
def make_msg(role: str, content: str) -> dict[str, str]:
return {"role": role, "content": content}
CALLS_PER_MINUTE = 3500 # full plan
def make_chat_request(client: openai.OpenAI, **kwargs: Any) -> ChatCompletion:
# Ignores (mypy): untyped decorator makes function untyped
@sleep_and_retry # type: ignore[misc]
@limits(calls=CALLS_PER_MINUTE, period=60) # type: ignore[misc]
def _make_chat_request(**kwargs: Any) -> ChatCompletion:
attempts = 0
while True:
try:
response = client.chat.completions.create(**kwargs)
except Exception as e:
ts = datetime.now().isoformat()
print(f'{ts} | Connection error - "{e}" | Attempt {attempts + 1}')
attempts += 1
if isinstance(e, openai.APIStatusError) and e.status_code == 429:
print("Rate limit exceeded. Waiting 10 seconds.")
time.sleep(10)
else:
logger.log_exchange(kwargs, response.model_dump())
return response
# This cast is necessary because of the sleep_and_retry and limits decorators,
# which make the function untyped.
return cast(ChatCompletion, _make_chat_request(**kwargs))
def get_result(response: ChatCompletion) -> str:
return response.choices[0].message.content or "<empty>"
# Costs as of 2023-11-13 from https://openai.com/pricing
# model: input cost, output cost
MODEL_COSTS = {
"gpt-3.5-turbo-0613": ( # in: $0.001 / 1K tokens, out: $0.002 / 1K tokens
0.000001,
0.000002,
),
"gpt-4-1106-preview": ( # in: $0.03 / 1K tokens, out: $0.06 / 1K tokens
0.00003,
0.00006,
),
"gpt-3.5-turbo-0125": ( # in: $0.001 / 1K tokens, out: $0.002 / 1K tokens
0.000001,
0.000002,
),
"gpt-4-0125-preview": ( # in: $0.03 / 1K tokens, out: $0.06 / 1K tokens
0.00003,
0.00006,
),
}
def calculate_cost(model: str, response: ChatCompletion) -> float:
"""Calculate the cost of a GPT response based on the tokens used.
If model is not not valid, a warning is issued and 0 cost is returned. Same if the
usage information is not available in the response.
0 cost is returned instead of raising an exception, because the cost is not that
important, and it's better not to have it than crash the program.
"""
if response.usage is None:
warnings.warn(
"Usage information not available in GPT response. Returning 0 cost."
)
return 0
if model not in MODEL_COSTS:
warnings.warn(f"Model {model} not found in costs table. Returning 0 cost.")
return 0
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
cost_input, cost_output = MODEL_COSTS[model]
return input_tokens * cost_input + output_tokens * cost_output
def log_args(args: argparse.Namespace, path: Path | None) -> None:
args_dict = vars(args).copy()
for key, value in args_dict.items():
if isinstance(value, Path):
args_dict[key] = str(value)
out = json.dumps(args_dict, indent=2)
if path is not None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(out)
else:
print(out)
def init_argparser(*, prompt: bool = True) -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
allow_abbrev=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("key_file", type=Path, help="Path to JSON file with API keys")
parser.add_argument("key_name", type=str, help="Name of key to use")
parser.add_argument(
"--model", type=str, default=next(iter(MODEL_COSTS)), help="Model to use"
)
parser.add_argument(
"--print-logs", action="store_true", help="Print logs to stdout"
)
parser.add_argument(
"--log-file", type=Path, default="chat_log.jsonl", help="Log file"
)
parser.add_argument("--input", "-i", type=Path, help="Input file")
parser.add_argument("--output", "-o", type=Path, help="Output file for predictions")
parser.add_argument("--metrics-path", type=Path, help="Path where to save metrics")
parser.add_argument("--args-path", type=Path, help="Path where to save args")
if prompt:
parser.add_argument(
"--prompt",
type=int,
default=0,
help="User prompt index to use for the chat session",
)
parser.add_argument(
"--sys-prompt",
type=int,
default=0,
help="System prompt index to use for the chat session",
)
return parser