-
Notifications
You must be signed in to change notification settings - Fork 2
/
gpt.py
executable file
·190 lines (148 loc) · 6.64 KB
/
gpt.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
import openai
import os
import aiohttp
import asyncio
import ast
import os
import requests
import json
import datetime
class GPTHass:
def __init__(self, config):
self.headers = {
'Authorization': 'Bearer {}'.format(config["hass_token"]),
'Content-Type': 'application/json',
}
self.user_name = config["user_name"]
openai.api_key = config["openai_api_key"]
self.hass_host = config["hass_host"]
self.command_result_callback = None
self.tts_result_callback = None
self.get_hass_entities()
self.interaction_counter = self.last_prompt_number()
self.training = os.environ.get("GEPPETTO_TRAINING", False)
self.file = None
self.location = "Berlin, Germany"
self.update_location()
def update_location(self):
response = requests.get("https://ipapi.co/json")
data = response.json()
if 'error' in data:
return
city = data['city']
country = data['country_name']
self.location = f"{city}, {country}."
def indent_with_tabs(input_string):
indented_string = " ".join(input_string.splitlines(True))
return indented_string.strip().replace("\"", "\\\"")
def last_prompt_number(self):
files = os.listdir('./training/')
prompt_files = [f for f in files if f.startswith('prompt-') and f.endswith('.yml')]
if prompt_files:
prompt_numbers = [int(f.split('-')[1].split('.')[0]) for f in prompt_files]
return max(prompt_numbers) + 1
else:
return 0
def write_prompt(self, content):
if self.training:
self.file = open(f"training/prompt-{self.interaction_counter}.yml", "w")
self.file.write(\
f"prompt: >\n" \
f" \"{GPTHass.indent_with_tabs(content)}\"" \
"\n"
)
def write_answer(self, content):
if self.training:
self.file.write(\
"\nanswer: >\n" \
f" \"{GPTHass.indent_with_tabs(content)}\""
)
self.file.close()
def get_hass_entities(self):
url = 'http://{}/api/states'.format(self.hass_host)
#use requests to make it synchronous
response = requests.get(url, headers=self.headers)
self.entities = ""
if response.status_code == 200:
for state in json.loads(response.text):
entity_id = state["entity_id"]
entity_name = state["attributes"].get("friendly_name")
if entity_name is not None:
if "switch." in entity_id or "lock." in entity_id or \
"light." in entity_id or "media_player." in entity_id or \
"climate." in entity_id or "fan." in entity_id or "cover." in entity_id:
self.entities += entity_id + " = " + entity_name + "\n"
self.entities += "\n"
def assistant_answer(self, asr_text, positive=True):
mood = "positively and affirmatively" if positive else "negatively"
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
prompt = \
f"My name is {self.user_name}. Today is {date} and we are in {self.location}. " \
"You are HAL 9000 and you are connected to the smart home system. " \
f"Give me what HAL 9000 would reply {mood} to this command: \"{asr_text}\" " \
"HAL 9000: "
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": prompt}
]
)
content = response["choices"][0].message["content"]
if self.tts_result_callback != None:
self.tts_result_callback(content)
def answer(self, asr_text):
prompt = \
"Entities:\n" \
f"{self.entities}\n" \
"\n" \
f"For the prompt \"{asr_text}\", as long as it contains a valid entity, " \
"I need a python list where each item is a dictionary with the service " \
"and entity_id for each item to send trough the Home Assistant API, potentially " \
"with data if needed. If it is command and it does not match to any of the entities, " \
"just answer with the word: Error. If the prompt is not a command, just answer with the word: \"not_command\".\n"
self.write_prompt(prompt)
print(prompt)
try:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": prompt}
]
)
except:
if self.tts_result_callback != None:
self.tts_result_callback("GPT-4 is not available at the moment")
content = response["choices"][0].message["content"]
content = content.replace("```", "")
content = content.replace("python", "").replace("\n", "").replace("\t", "").replace(" ", "")
self.write_answer(content)
self.interaction_counter += 1
if content == "Error":
self.assistant_answer(asr_text, False)
return
elif content == "not_command":
self.assistant_answer(asr_text)
return
try:
commands = json.loads(content)
if self.command_result_callback != None:
self.command_result_callback(commands)
asyncio.run(self.send_all_commands(commands, asr_text))
except Exception as e:
print("Error parsing the response: {}".format(e))
self.assistant_answer(asr_text)
async def send_command(self, command):
async with aiohttp.ClientSession(headers=self.headers) as session:
url = 'http://{}/api/services/'.format(self.hass_host) + \
command['service'].split('.')[0] + \
'/' + command['service'].split('.')[1]
json = { "entity_id": command['entity_id']}
if 'data' in command:
json.update(command['data'])
print(json)
async with session.post(url, json=json) as response:
print(await response.text())
pass
async def send_all_commands(self, commands, tts_response):
await asyncio.gather(*[self.send_command(command) for command in commands])
self.assistant_answer(tts_response)