% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tool-context.R
\name{tool_context}
\alias{tool_context}
\alias{with_tool_context}
\alias{local_tool_context}
\title{Access the current tool context}
\usage{
tool_context()

with_tool_context(context, code)

local_tool_context(context, .frame = parent.frame())
}
\arguments{
\item{context}{An \code{ellmer_tool_context} object, or a list with fields
\code{request} and \code{turns} (which will be promoted automatically).}

\item{code}{An expression to evaluate with \code{context} on top of the stack.}

\item{.frame}{The environment whose exit triggers the pop. Defaults to
\code{parent.frame()} (the calling function's frame).}
}
\value{
\code{tool_context()} returns the current \code{ellmer_tool_context} object (a
classed list with fields \verb{$request}, \verb{$turns}).

\code{with_tool_context()} returns the value of \code{code}.

\code{local_tool_context()} returns \code{context} invisibly.
}
\description{
When an ellmer tool is called by an LLM, \code{tool_context()} returns a context
object with two fields:
\itemize{
\item \verb{$request}: the \link{ContentToolRequest} for this call, with sub-fields
\verb{@name}, \verb{@id}, \verb{@arguments}, and \verb{@tool}.
\item \verb{$turns}: an eager snapshot of the conversation history (list of \link{Turn}
objects), including the system prompt (if any) as the first turn, up to and
including the assistant turn that issued this tool request. Sibling tool
results from the same turn are not included (they are appended after the
current tool loop finishes).
}

\code{tool_context()} aborts with class \code{ellmer_error_tool_context_unavailable} if
the stack is empty, which happens in two situations:
\enumerate{
\item The function was called outside any tool invocation (e.g. in a test or
top-level script without a live chat).
\item The function was called after an \code{await()} in an async tool. The context
frame closes at the first \code{await}, so you must capture the context before
yielding: \code{ctx <- tool_context()}.
}

The \code{with_tool_context()} and \code{local_tool_context()} helpers are useful for
testing a tool function that calls \code{tool_context()} outside a live chat. They
temporarily make a supplied context available while test code runs.
}
\examples{
# Log the id of the request that triggered this tool call
logging_tool <- tool(
  function() {
    ctx <- tool_context()
    message("Handled request ", ctx$request@id)
    "done"
  },
  name = "logging_tool",
  description = "Log the current request id and return"
)

# Test a tool that uses tool_context() without a live chat
request <- ContentToolRequest(
  id = "test-request",
  name = "logging_tool",
  arguments = list(),
  tool = logging_tool
)
with_tool_context(
  list(request = request, turns = list()),
  logging_tool()
)

}
