-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsimulation_microservice.py
More file actions
135 lines (113 loc) · 4.92 KB
/
simulation_microservice.py
File metadata and controls
135 lines (113 loc) · 4.92 KB
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
import requests
from time import time
from uuid import uuid4
import numpy as np
import re
import os
import openai
from time import time,sleep
def open_file(filepath):
with open(filepath, 'r', encoding='utf-8') as infile:
return infile.read()
def save_file(filepath, content):
with open(filepath, 'w', encoding='utf-8') as outfile:
outfile.write(content)
openai.api_key = open_file('openaiapikey.txt')
scene_dir = 'scenes/'
service_name = 'sensor_simulation'
content_prefix = 'Sensory input scene: '
tempo = 30
def gpt3_completion(prompt, engine='text-davinci-002', temp=0.7, top_p=1.0, tokens=1000, freq_pen=0.0, pres_pen=0.0, stop=['asdfasdf', 'asdasdf']):
max_retry = 5
retry = 0
prompt = prompt.encode(encoding='ASCII',errors='ignore').decode()
while True:
try:
response = openai.Completion.create(
engine=engine,
prompt=prompt,
temperature=temp,
max_tokens=tokens,
top_p=top_p,
frequency_penalty=freq_pen,
presence_penalty=pres_pen,
stop=stop)
text = response['choices'][0]['text'].strip()
text = re.sub('\s+', ' ', text)
filename = '%s_gpt3.txt' % time()
save_file('gpt3_logs/%s' % filename, prompt + '\n\n==========\n\n' + text)
return text
except Exception as oops:
retry += 1
if retry >= max_retry:
return "GPT3 error: %s" % oops
print('Error communicating with OpenAI:', oops)
sleep(1)
def get_embedding(payload): # payload is a list of strings
# payload example: ['bacon bacon bacon', 'ham ham ham']
# response example: [{'string': 'bacon bacon bacon', 'vector': '[1, 1 ... ]'}, {'string': 'ham ham ham', 'vector': '[1, 1 ... ]'}]
# embedding is already rendered as a JSON-friendly string
url = 'http://127.0.0.1:999' # currently the USEv5 service, about 0.02 seconds per transaction!
response = requests.request(method='POST', url=url, json=payload)
return response.json()
def nexus_send(payload): # REQUIRED: content
url = 'http://127.0.0.1:8888/add'
payload['time'] = time()
payload['uuid'] = str(uuid4())
payload['content'] = content_prefix + payload['content']
embeddings = get_embedding([payload['content']])
payload['vector'] = embeddings[0]['vector']
payload['service'] = service_name
response = requests.request(method='POST', url=url, json=payload)
print(response.text)
def nexus_search(payload):
url = 'http://127.0.0.1:8888/search'
response = requests.request(method='POST', url=url, json=payload)
return response.json()
def nexus_bound(payload):
url = 'http://127.0.0.1:8888/bound'
response = requests.request(method='POST', url=url, json=payload)
#print(response)
return response.json()
def nexus_save():
url = 'http://127.0.0.1:8888/save'
response = requests.request(method='POST', url=url)
print(response.text)
def find_actions(memories):
for m in memories:
if m['service'] == 'executive_action':
return m['content']
return None # no actions detected in memories
if __name__ == '__main__':
new_scene = 'Two men are sitting at a stone chess table in Central Park. They are playing chess. The sun is shining and birds are singing. It is a summer day. Children are running and playing in the distance. Horns honking and the bustle of New York can be heard in the background.'
backstory = new_scene
while True:
last_scene = new_scene
# generate event
prompt = open_file('prompt_event.txt').replace('<<SCENE>>', last_scene).replace('<<STORY>>', backstory).replace('<<RARITY>>', 'likely')
event = gpt3_completion(prompt)
filename = '%s_event.txt' % time()
save_file(scene_dir + filename, event)
nexus_send({'content': event})
# incorporate actions from the nexus
payload = {'lower_bound': time() - tempo, 'upper_bound': time()}
memories = nexus_bound(payload)
action = find_actions(memories)
if action:
event = event + '\nAction I will take: %s' % action
print('\n\nEVENT:', event)
# new scene
prompt = open_file('prompt_scene.txt').replace('<<SCENE>>', last_scene).replace('<<EVENT>>', event).replace('<<STORY>>', backstory)
new_scene = gpt3_completion(prompt)
print('\n\nSCENE:', new_scene)
# save scene
filename = '%s_scene.txt' % time()
save_file(scene_dir + filename, new_scene)
nexus_send({'content': new_scene})
# summarize backstory up to this point
backstory = (backstory + ' ' + event + ' ' + new_scene).strip()
prompt = open_file('prompt_concise_summary.txt').replace('<<STORY>>', backstory)
backstory = gpt3_completion(prompt)
print('\n\nBACKSTORY:', backstory)
# wait
sleep(tempo)