-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtextEmbedding.R
51 lines (42 loc) · 1.63 KB
/
textEmbedding.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
#' @title Text Embedding from OpenAI Embeddings API
#' @description This function calls the OpenAI Embeddings API to get the multidimensional vector
#' via text embedding of the input text. This function uses the 'text-embedding-ada-002' model.
#' @param text A string. The input text to get the embedding for. This should be a character string.
#' @param api_key A string. The API key for the OpenAI API. Defaults to the value of the environment variable "OPENAI_API_KEY".
#' @importFrom httr POST add_headers content
#' @importFrom jsonlite toJSON
#' @return A vector representing the text embeddings.
#' @export textEmbedding
#' @author Satoshi Kume
#' @examples
#' \dontrun{
#' Sys.setenv(OPENAI_API_KEY = "Your API key")
#' textEmbedding("Hello, world!")
#' }
textEmbedding <- function(text,
api_key = Sys.getenv("OPENAI_API_KEY")) {
#API endpoint
url <- "https://api.openai.com/v1/embeddings"
# Header information (set API key)
headers <- httr::add_headers(
`Content-Type` = "application/json",
`Authorization` = paste("Bearer", api_key)
)
# Request body (set text data)
body <- list(
"input" = text,
"model" = "text-embedding-ada-002" # text-embedding-3-large or text-embedding-3-small
)
# Send POST request to the server
response <- httr::POST(url = url,
body = jsonlite::toJSON(body, auto_unbox = TRUE),
encode = "json", config = headers)
# Parse response
content <- httr::content(response, "parsed")
#str(content$data[[1]])
#convert to vector
v <- unlist(content$data[[1]]$embedding)
#str(v)
# Return vector
return(v)
}