-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai_service.rb
50 lines (44 loc) · 1.12 KB
/
openai_service.rb
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
require 'openai'
class OpenaiService
EMBEDDINGS_MODEL = 'text-embedding-ada-002'
COMPLETIONS_MODEL = 'text-davinci-003'
def initialize
@client = OpenAI::Client.new(access_token: ENV.fetch('OPENAI_API_KEY'))
end
# Requests OpenAI /embeddings to get embeddings for a string.
#
# Params:
# - text (string)
#
# Returns the embedding (array of floats).
def get_embedding(text)
return '' if text.nil?
res = @client.embeddings(
parameters: {
model: EMBEDDINGS_MODEL,
input: text
}
)
res['data'][0]['embedding']
end
# Makes an API request to OpenAI /completions to get an answer to a question.
#
# Params:
# - prompt (string): a text prompt for OpenAI.
#
# Note: currently using RestClient because ruby client was giving me issues for @client.completions
#
# Returns the answer (string).
def get_completion(prompt)
return '' if prompt.nil?
res = @client.completions(
parameters: {
model: COMPLETIONS_MODEL,
prompt: prompt,
temperature: 0,
max_tokens: 150
}
)
res['choices'][0]['text']
end
end