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
|
# File 'lib/xfyun/spark/request.rb', line 12
def request(path:, parameters:, stream:)
content = ""
data = nil
EM.run {
url = authorization_url(path)
logging(:info, "request url: #{url}, parameters: #{parameters}")
ws = Faye::WebSocket::Client.new(url)
ws.on(:open) do |event|
ws.send(parameters.to_json)
end
ws.on(:close) do |event|
logging(:info, "ws close: #{event.code} #{event.reason}")
EM.stop
end
ws.on(:error) do |event|
logging(:info, "ws error: #{event.message}")
raise Xfyun::Spark::Error.new(event.message)
end
ws.on(:message) do |event|
logging(:info, "ws message: #{event.data}")
response_data = JSON.parse(event.data)
if stream.respond_to?(:call)
stream.call(response_data)
end
code = response_data.dig('header', 'code')
if code == 0
status = response_data.dig('header', 'status')
case status
when 0, 1
content << response_data.dig('payload', 'choices', 'text', 0, 'content')
when 2
content << response_data.dig('payload', 'choices', 'text', 0, 'content')
response_data['payload']['choices']['text'][0]['content'] = content
data = response_data
end
else
data = response_data
end
end
}
return data
end
|