-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
50 lines (38 loc) · 1.11 KB
/
model.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
import json
import dataclasses
from typing import Literal
@dataclasses.dataclass
class Message:
role: Literal['user', 'system', 'assistant']
content: str
@classmethod
def user(cls, prompt: str):
return cls(role='user', content=prompt)
@classmethod
def system(cls, prompt: str):
return cls(role='system', content=prompt)
@classmethod
def assistant(cls, prompt: str):
return cls(role='assistant', content=prompt)
def to_json(self):
return dataclasses.asdict(self)
@dataclasses.dataclass
class UsageMetrics:
prompt_tokens: int
completion_tokens: int
total_tokens: int
@dataclasses.dataclass
class ModelResponse:
usage: UsageMetrics
_model: str
_response: str
@classmethod
def from_api_response(cls, response: dict) -> 'ModelResponse':
return cls(
usage=UsageMetrics(**response['usage']),
_model=response['model'],
_response=response['choices'][0]['message']['content']
)
def json(self) -> dict:
json_str = self._response.strip("'")
return json.loads(json_str)