-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGPTInterface.R
94 lines (86 loc) · 2.5 KB
/
GPTInterface.R
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
source("FakeAI.R")
GPTInterface <- R6Class(
"GPTInterface",
public = list(
type = "",
fakeAI = NULL,
agent = NULL,
config = NULL,
initialize = function(agent,config) {
self$agent <- agent
self$type <- config$chatType
self$config <- config
if(self$type=="fakegpt") {
self$fakeAI <- FakeAI$new(config)
}
},
syncChatOpenAI = function(agent,msg) {
encodedMsg <- commandHandler$encodeCommand(msg)
agent$appendMessage("user",encodedMsg)
completion <- create_chat_completion(
model = config$chatgpt$model,
messages = agent$messages,
max_tokens = config$chatgpt$max_tokens,
temperature = config$chatgpt$temperature
)
response <- completion$choices$message.content
agent$appendMessage("assistant",response)
agent$lastChatPartner <- msg$from
response
},
syncChatFakeAI = function(agent,msg) {
Sys.sleep(config$fakegpt$artificialDelaySecs)
encodedMsg <- commandHandler$encodeCommand(msg)
self$fakeAI$syncChat(encodedMsg)
},
chatOpenAI = function(agent,msg) {
Sys.sleep(0.001)
encodedMsg <- commandHandler$encodeCommand(msg)
agent$appendMessage("user",encodedMsg)
completion <- future_promise({create_chat_completion(
model = config$chatgpt$model,
messages = agent$messages,
max_tokens = config$chatgpt$max_tokens,
temperature = config$chatgpt$temperature
)})
completion %...>% (function(r) {
response <- r$choices$message.content
agent$appendMessage("assistant",response)
agent$lastChatPartner <- msg$from
agent$tokensUsed <- r$usage$total_tokens
# wrap the call to handleCommand in a later so that
# the promise will resolve and handleCommand will be
# called when the main thread is idle
later(function() {
commandHandler$handleCommand(response,agent)
})
})
NULL
},
chatFakeAI = function(agent,msg) {
Sys.sleep(config$fakegpt$artificialDelaySecs)
encodedMsg <- commandHandler$encodeCommand(msg)
self$fakeAI$chat(encodedMsg,agent)
NULL
},
syncChat = function(msg) {
f <- switch(self$type,
"chatgpt" = self$syncChatOpenAI,
"fakegpt" = self$syncChatFakeAI
)
f(self$agent,msg)
},
chat = function(msg) {
f <- switch(self$type,
"chatgpt" = self$chatOpenAI,
"fakegpt" = self$chatFakeAI
)
f(self$agent,msg)
# note that there is no response
# as the chat is handled asyncronously
# and when the result is obtained, handle
# command is then called
return(NULL)
}
)
)