Skip to content
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

Correctly implement citation merging for gemini #391

Merged
merged 3 commits into from
Apr 4, 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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# ellmer (development version)

* `chat_gemini()` can now handle responses that include citation metadata
(#358).

* `chat_` functions no longer take a turns object, instead use `set_turns()`
(#427).

Expand Down
7 changes: 7 additions & 0 deletions R/provider-gemini.R
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,12 @@ merge_optional <- function(merge_func) {
merge_objects <- function(...) {
spec <- list(...)
function(left, right, path = NULL) {
if (is.null(left)) {
return(right)
} else if (is.null(right)) {
return(left)
}

# cat(paste(collapse = "", path), "\n")
stopifnot(is.list(left), is.list(right), all(nzchar(names(spec))))
mapply(
Expand Down Expand Up @@ -469,6 +475,7 @@ merge_parts <- function() {
}

# Put it all together...
# https://ai.google.dev/api/generate-content#v1beta.GenerateContentResponse
merge_gemini_chunks <- merge_objects(
candidates = merge_candidate_lists(
content = merge_objects(
Expand Down
29 changes: 29 additions & 0 deletions tests/testthat/test-provider-gemini.R
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,32 @@ test_that("strips suffix from model name", {
"gemini-2.0-pro"
)
})

test_that("can handle citations", {
# based on "Write me a 5-paragraph essay on the history of the tidyverse."
messages <- c(
'{"candidates": [{"content": {"parts": [{"text": "a"}]}, "role": "model"}]}',
'{"candidates": [{
"content": {"parts": [{"text": "a"}]},
"role": "model",
"citationMetadata": {
"citationSources": [
{
"startIndex": 1,
"endIndex": 2,
"uri": "https://example.com",
"license": ""
}
]
}
}]}'
)
chunks <- lapply(messages, jsonlite::parse_json)

out <- merge_gemini_chunks(chunks[[1]], chunks[[2]])
source <- out$candidates[[1]]$citationMetadata$citationSources[[1]]
expect_equal(source$startIndex, 1)
expect_equal(source$endIndex, 2)
expect_equal(source$uri, "https://example.com")
expect_equal(source$license, "")
})