Count hallucinations produced by an LLM in a generated code snippet
Source:R/hallucination_detect.R
count_hallucinations.RdParses code using base::parse() and walks the resulting AST to
find:
Invented functions – calls to names that appear neither in the rrlmgraph call-graph (
graph) nor in the current R session viagetAnywhere().Invalid arguments – named arguments that are not listed in
base::formals()for the target function (only checked when the function can be resolved in session).Wrong-package namespace calls –
pkg::fn()references wherefndoes not actually exportfn.
Non-standard-evaluation column references (bare names inside dplyr
verbs, data.table indexing, or formula RHS) are not flagged; the
detector only inspects calls whose first element is a symbol.
Value
A named list; each element represents one detected hallucination with fields:
typeCharacter. One of
"invented_function","invalid_argument", or"wrong_namespace".fnCharacter. The function name involved.
detailCharacter. Human-readable explanation.
Returns an empty list when no hallucinations are found.
Examples
code <- "result <- xyzzy_nonexistent_fn(mtcars, foo = 1)"
count_hallucinations(code)
#> [[1]]
#> [[1]]$type
#> [1] "invented_function"
#>
#> [[1]]$fn
#> [1] "xyzzy_nonexistent_fn"
#>
#> [[1]]$detail
#> [1] "'xyzzy_nonexistent_fn' could not be found in the R session or the project graph."
#>
#>