-
Notifications
You must be signed in to change notification settings - Fork 0
/
prediction.py
80 lines (67 loc) · 2.63 KB
/
prediction.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
import json
import logging
import random
import os
from pathlib import Path
import re
import openai
from llms.openai_gpt import OpenAIAssistant
from llms.prompts import ClassifyPromptCrafter
from llms.datastores import LogFiles
from functools import cache
RESPONSE_DATA_PATH = Path(os.getenv('HOME')) / '.gptlog' / 'responses'
PROMPT_TEMPLATES_PATH = Path(__file__).resolve().parent / 'prompt_templates'
logger = logging.getLogger()
def mock_completion_random(prompt, categories, query_text, options):
"""Random classification for testing baseline."""
multiclass, reasoning = options
query = set(query_text.split())
N = 2 if multiclass else 1
result = [random.choice(categories) for _ in range(N)]
return [res['class_id'] for res in result]
class Prediction:
def __init__(self):
self.datastore = LogFiles(log_path=RESPONSE_DATA_PATH)
self.crafter = ClassifyPromptCrafter(PROMPT_TEMPLATES_PATH / 'prompt3.txt')
self.assistant = OpenAIAssistant(
model='gpt-3.5-turbo',
prompt_crafter=self.crafter,
datastore=self.datastore,
response_format='json'
)
@cache
def predict(self, data):
#TODO: Add caching, async call perhaps
try:
response = self.assistant.get_completion(data)
except openai.RateLimitError as e:
return json.dumps({'result': e.message})
else:
message = self.assistant.get_message(response)
self.assistant.log_response(response)
return message
def format_result_from_plain(self, message):
result_regex = re.compile(r'\[{1}.+\]{1}')
result = result_regex.findall(message)
result = [s.strip() for s in result[0][1:-1].split(',')]
reasoning_regex = re.compile(r'```{1}.+```{1}')
reasoning = reasoning_regex.findall(message)
result = { 'result': result, 'reasoning': reasoning}
return result
def format_result_from_json(self, message):
try:
f_message = json.loads(message)
except json.decoder.JSONDecodeError as e:
logger.error(e)
logger.info(message)
f_message = json.dumps({'result': [], 'reasoning': 'Error encountered while classifying.'})
else:
if len(f_message) == 0:
return {'result': []}
if 'result' not in f_message:
f_message['result'] = []
for name in ['ids', 'categories', 'classes']:
if name in f_message:
f_message['result'] = f_message.get(name, [])
break
return f_message