Skip to content

Set user agent in all embed_* functions #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ importFrom(httr2,req_body_json)
importFrom(httr2,req_perform)
importFrom(httr2,req_retry)
importFrom(httr2,req_url_path_append)
importFrom(httr2,req_user_agent)
importFrom(httr2,request)
importFrom(httr2,resp_body_json)
importFrom(methods,is)
Expand Down
3 changes: 2 additions & 1 deletion R/embed-bedrock.R
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ embed_bedrock <- function(x, model, profile, api_args = list()) {
"https://bedrock-runtime.",
credentials$region,
".amazonaws.com"
))
)) |>
req_user_agent(ragnar_user_agent())

req <- httr2::req_url_path_append(
req,
Expand Down
45 changes: 29 additions & 16 deletions R/embed-vertex.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,13 @@
#' )
#' }
#'@export
embed_google_vertex <- function(x, model, location, project_id, task_type = "RETRIEVAL_QUERY") {
embed_google_vertex <- function(
x,
model,
location,
project_id,
task_type = "RETRIEVAL_QUERY"
) {
if (missing(x) || is.null(x)) {
args <- capture_args()
fn <- partial(quote(ragnar::embed_google_vertex), alist(x = ), args)
Expand Down Expand Up @@ -55,6 +61,7 @@ embed_google_vertex <- function(x, model, location, project_id, task_type = "RET

base_req <- vertex_url(location, project_id) |>
httr2::request() |>
req_user_agent(ragnar_user_agent()) |>
httr2::req_headers(!!!credentials, .redact = names(credentials)) |>
httr2::req_url_path_append(
"models",
Expand All @@ -65,13 +72,14 @@ embed_google_vertex <- function(x, model, location, project_id, task_type = "RET
json$error$message
})


out <- list()
# The gemini model does not support batches
chunk_size <- if (grepl("gemini", model)) 1 else 20

for (indices in chunk_list(seq_along(x), chunk_size)) {
instances <- lapply(indices, \(i) list(task_type = task_type, content = x[[i]]))
instances <- lapply(indices, \(i) {
list(task_type = task_type, content = x[[i]])
})

resp <- base_req |>
httr2::req_body_json(list(
Expand All @@ -95,16 +103,19 @@ embed_google_vertex <- function(x, model, location, project_id, task_type = "RET
}

vertex_url <- function(location, project_id) {
paste(unlist(list(
c("https://", location, "-aiplatform.googleapis.com/v1"),
c("/projects/", project_id),
c("/locations/", location),
"/publishers/google/"
)), collapse="")
paste(
unlist(list(
c("https://", location, "-aiplatform.googleapis.com/v1"),
c("/projects/", project_id),
c("/locations/", location),
"/publishers/google/"
)),
collapse = ""
)
}


google_credentials <- function (error_call = caller_env()) {
google_credentials <- function(error_call = caller_env()) {
scope <- "https://www.googleapis.com/auth/cloud-platform"
if (has_connect_viewer_token(scope = scope)) {
return(function() {
Expand All @@ -119,7 +130,6 @@ google_credentials <- function (error_call = caller_env()) {

check_installed("gargle", "for Google authentication")


gargle::with_cred_funs(
funs = list(credentials_app_default = gargle::credentials_app_default),
{
Expand All @@ -133,10 +143,13 @@ google_credentials <- function (error_call = caller_env()) {
}

if (is.null(token)) {
cli::cli_abort(c(
"No Google credentials are available.",
i = "Try suppling an API key or configuring Google's application default credentials."
), call = error_call)
cli::cli_abort(
c(
"No Google credentials are available.",
i = "Try suppling an API key or configuring Google's application default credentials."
),
call = error_call
)
}

if (!token$can_refresh()) {
Expand All @@ -155,7 +168,7 @@ google_credentials <- function (error_call = caller_env()) {
})
}

has_connect_viewer_token <- function (...) {
has_connect_viewer_token <- function(...) {
if (!is_installed("connectcreds")) {
return(FALSE)
}
Expand Down
23 changes: 20 additions & 3 deletions R/embed.R
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ embed_ollama <- function(

embeddings <- map2(starts, ends, function(start, end) {
req <- request(base_url) |>
req_user_agent(ragnar_user_agent()) |>
req_url_path_append("/api/embed") |>
req_body_json(list(model = model, input = x[start:end]))

Expand All @@ -90,7 +91,7 @@ embed_openai <- function(
base_url = "https://api.openai.com/v1",
api_key = get_envvar("OPENAI_API_KEY"),
dims = NULL,
user = get_ragnar_username(),
user = get_user(),
batch_size = 20L
) {
if (missing(x) || is.null(x)) {
Expand Down Expand Up @@ -138,6 +139,7 @@ embed_openai <- function(
data$input <- as.list(text[start:end])

req <- request(base_url) |>
req_user_agent(ragnar_user_agent()) |>
req_url_path_append("/embeddings") |>
req_auth_bearer_token(api_key) |>
req_retry(max_tries = 2L) |>
Expand Down Expand Up @@ -184,10 +186,25 @@ get_envvar <- function(name, error_call = caller_env()) {
val
}

get_ragnar_username <- function() {
sprintf("'%s' via ragnar", Sys.info()[["user"]])
get_user <- function() {
sys_info <- Sys.info()
user <- sys_info[["effective_user"]]
if (user != "unknown") {
return(user)
}
user <- sys_info[["user"]]
if (user != "unknown") {
return(user)
}
NULL
}

ragnar_user_agent <- function() {
paste0("r-ragnar/", .package_version)
}

is_testing <- function() {
identical(Sys.getenv("TESTTHAT"), "true")
}

.package_version <- c(read.dcf('DESCRIPTION', 'Version'))
26 changes: 19 additions & 7 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
#' vec_fill_missing vec_unique vec_slice vec_c list_unchop new_data_frame
#' vec_chop
#' @importFrom httr2 request req_url_path_append req_body_json req_perform
#' resp_body_json req_retry req_auth_bearer_token
#' resp_body_json req_retry req_auth_bearer_token req_user_agent
#' @importFrom DBI dbExecute dbConnect dbExistsTable dbGetQuery dbQuoteString
#' dbWriteTable dbListTables dbReadTable
#' @importFrom glue glue glue_data as_glue
Expand Down Expand Up @@ -49,13 +49,17 @@ map_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)

map2 <- function(.x, .y, .f, ...) {
out <- .mapply(.f, list(.x, .y), list(...))
if (length(.x) == length(out)) names(out) <- names(.x)
if (length(.x) == length(out)) {
names(out) <- names(.x)
}
out
}

map3 <- function(.x, .y, .z, .f, ...) {
out <- .mapply(.f, list(.x, .y, .z), list(...))
if (length(.x) == length(out)) names(out) <- names(.x)
if (length(.x) == length(out)) {
names(out) <- names(.x)
}
out
}

Expand Down Expand Up @@ -84,13 +88,19 @@ imap <- function(.x, .f, ...) {
# is_double2(x, c(NA, NA, NA)) # FALSE
# is_double2(x, 12) # FALSE
is_double2 <- function(x, dim = NULL) {
if (is.null(dim)) return(is_double(x))
if (is.null(dim)) {
return(is_double(x))
}

if (!is.double(x)) return(FALSE)
if (!is.double(x)) {
return(FALSE)
}

actual_size <- base::dim(x)
expected_size <- as.integer(dim)
if (length(actual_size) != length(expected_size)) return(FALSE)
if (length(actual_size) != length(expected_size)) {
return(FALSE)
}

all(expected_size == actual_size, na.rm = TRUE)
}
Expand Down Expand Up @@ -136,7 +146,9 @@ partial <- function(.fn, .sig, ...) {

reorder_names <- function(..., last = NULL) {
x <- unique(c(...))
if (!is.null(last)) x <- unique(c(x, last), fromLast = TRUE)
if (!is.null(last)) {
x <- unique(c(x, last), fromLast = TRUE)
}
x
}

Expand Down
2 changes: 1 addition & 1 deletion man/embed_ollama.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions man/read_as_markdown.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.