% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/workflow__run_task.R
\name{run_task}
\alias{run_task}
\title{Run a Structured Task with the Agent}
\usage{
run_task(
  prompt,
  output_format = "text",
  temporal = NULL,
  config = NULL,
  agent = NULL,
  expected_fields = NULL,
  expected_schema = NULL,
  thread_id = NULL,
  field_status = NULL,
  budget_state = NULL,
  search_budget_limit = NULL,
  unknown_after_searches = NULL,
  finalize_on_all_fields_resolved = NULL,
  field_rules = NULL,
  source_policy = NULL,
  retry_policy = NULL,
  finalization_policy = NULL,
  orchestration_options = NULL,
  performance_profile = NULL,
  webpage_policy = NULL,
  query_templates = NULL,
  verbose = FALSE,
  allow_read_webpages = NULL,
  webpage_relevance_mode = NULL,
  webpage_embedding_provider = NULL,
  webpage_embedding_model = NULL,
  use_plan_mode = FALSE,
  recursion_limit = NULL
)
}
\arguments{
\item{prompt}{The task prompt or question for the agent to research}

\item{output_format}{Expected output format. One of:
\itemize{
  \item "text": Returns response text (default)
  \item "json": Parse response as JSON
  \item "raw": Include the raw Python response object for low-level debugging
    in addition to the normal trace fields
  \item Character vector: Extract specific fields from response
}}

\item{temporal}{Named list or \code{asa_temporal} object for temporal filtering:
\itemize{
  \item time_filter: DuckDuckGo time filter - "d" (day), "w" (week),
    "m" (month), "y" (year)
  \item after: ISO 8601 date (e.g., "2020-01-01") - hint for results
    after this date (added to prompt context)
  \item before: ISO 8601 date (e.g., "2024-01-01") - hint for results
    before this date (added to prompt context)
}}

\item{config}{An \code{asa_config} object for unified configuration, or NULL
to use defaults}

\item{agent}{An asa_agent object from \code{\link{initialize_agent}}, or
NULL to use the currently initialized agent}

\item{expected_fields}{Optional character vector of field names expected in
JSON output. When provided, validates that all fields are present and
non-null. The result will include a \code{parsing_status} field with
validation details.}

\item{expected_schema}{Optional JSON schema tree used for best-effort repair
when the agent output is missing required keys (especially when
\code{recursion_limit} is reached). This should be a nested list describing
the required JSON object/array shape, following the conventions used in
\code{asa/tests/testthat/test-langgraph-remainingsteps.R}. When provided,
this bypasses prompt-based schema inference. Structured terminal payloads
automatically include sibling metadata keys \code{<field>_source} (URL or
\code{NULL}) and \code{<field>_confidence} (numeric score in
\code{[0,1]} or \code{NULL}) for top-level schema fields, including
unresolved fields where sibling values are emitted as \code{NULL}, even
when those sibling keys are not listed in \code{expected_schema}.}

\item{thread_id}{Optional stable identifier for memory folding sessions.
When provided, the same thread ID is reused so folded summaries persist
across invocations. Defaults to NULL (new thread each call).}

\item{field_status}{Optional per-field extraction ledger seed passed into the
LangGraph state. Useful for resuming partially resolved schemas.}

\item{budget_state}{Optional tool budget state seed passed into the LangGraph
state (e.g., to resume prior progress).}

\item{search_budget_limit}{Optional integer maximum number of \code{Search} tool
calls for this run.}

\item{unknown_after_searches}{Optional integer threshold after which unresolved
fields may be marked as unknown.}

\item{finalize_on_all_fields_resolved}{Optional logical flag. When TRUE, the
agent finalizes once all required fields are resolved.}

\item{field_rules}{Optional named list/dict of field-level extraction rules
passed directly to the backend state. Use task-agnostic rule objects;
\code{NULL} leaves backend defaults unchanged.}

\item{source_policy}{Optional named list/dict controlling source selection
and evidence-policy behavior in the backend state.}

\item{retry_policy}{Optional named list/dict controlling backend retry
behavior for follow-up planning and field resolution.}

\item{finalization_policy}{Optional named list/dict controlling terminal
finalization behavior in the backend state.}

\item{orchestration_options}{Optional named list/dict of generic orchestration
controls (component enable/mode and thresholds). This is passed directly to
the backend state and must remain task-agnostic.}

\item{performance_profile}{Optional orchestration profile. One of:
\code{"latency"}, \code{"balanced"}, or \code{"quality"}.}

\item{webpage_policy}{Optional structured OpenWebpage policy list with keys:
\code{max_open_calls}, \code{host_cooldown_seconds},
\code{blocked_host_ttl_seconds}, \code{open_only_if_score_ge}, and
\code{parallel_open_limit}.}

\item{query_templates}{Optional named list/dict of backend query template
overrides used when orchestration components generate follow-up searches.}

\item{verbose}{Print progress messages (default: FALSE)}

\item{allow_read_webpages}{If TRUE, allows the agent to open and read full
webpages (HTML/text) via the OpenWebpage tool. Disabled by default.}

\item{webpage_relevance_mode}{Relevance selection for opened webpages.
One of: "auto" (default), "lexical", "embeddings". When "embeddings" or
"auto" with an available provider, the tool uses vector similarity to pick
the most relevant excerpts; otherwise it falls back to lexical overlap.}

\item{webpage_embedding_provider}{Embedding provider to use for relevance.
One of: "auto" (default), "openai", "sentence_transformers".}

\item{webpage_embedding_model}{Embedding model identifier. For OpenAI,
defaults to "text-embedding-3-small". For sentence-transformers, use a
local model name (e.g., "all-MiniLM-L6-v2").}

\item{use_plan_mode}{Logical flag. When TRUE, the agent creates and follows
a structured execution plan, updating step status during the run.}

\item{recursion_limit}{Optional maximum number of agent steps. Precedence is:
per-call value (this argument), then configured default from
\code{initialize_agent()} / \code{asa_config()}, then mode-specific fallback
(memory folding: 100; standard agent: 20).}
}
\value{
An \code{asa_result} object with:
  \itemize{
    \item prompt: The original prompt
    \item message: The agent's response text
    \item parsed: Parsed output (list for JSON/field extraction, NULL for text/raw)
    \item raw_output: Full agent trace (always included)
    \item trace_json: Structured trace JSON (when available)
    \item elapsed_time: Execution time in minutes
    \item status: "success" or "error"
    \item search_tier: Which search tier was used ("primp", "selenium", etc.)
    \item parsing_status: Validation result (if expected_fields provided)
    \item execution: Operational metadata (thread_id, stop_reason, status_code,
      tool budget counters, fold_count, completion_gate, verification_status)
      plus diagnostics counters from runtime quality guards, candidate and
      retrieval telemetry, finalization status, artifact status, and
      orchestration policy metadata.
    \item action_ascii: High-level ASCII action map derived from the trace
      (also available at \code{execution$action_ascii})
    \item action_steps: Parsed high-level action steps (also available at
      \code{execution$action_steps})
    \item action_overall: High-level action summary lines (also available at
      \code{execution$action_overall})
    \item langgraph_step_timings: Per-node LangGraph timings in minutes
      (also available at \code{execution$langgraph_step_timings})
    \item fold_stats: Memory folding diagnostics list
    \item raw_response: Full underlying Python response object
      (for \code{output_format = "raw"})
  }
}
\description{
Executes a research task using the AI search agent with a structured prompt
and returns parsed results. This is the primary function for running
agent tasks.
}
\details{
This function provides the primary interface for running research tasks.
For simple text responses, use \code{output_format = "text"}. For structured
outputs, use \code{output_format = "json"} or specify field names to extract.
Full trace information is returned via \code{raw_output} (and
\code{trace_json} when available) for every invocation. For low-level
debugging with full underlying response access, use \code{output_format = "raw"}.

When temporal filtering is specified, the search tool's time filter is
temporarily set for this task and restored afterward. Date hints (after/before)
are appended to the prompt to guide the agent's search behavior.
}
\examples{
\dontrun{
# Initialize agent first
agent <- initialize_agent(backend = "openai", model = "gpt-4.1-mini")

# Simple text query
result <- run_task(
  prompt = "What is the capital of France?",
  output_format = "text",
  agent = agent
)
print(result$message)

# JSON structured output
result <- run_task(
  prompt = "Find information about Albert Einstein and return JSON with
            fields: birth_year, death_year, nationality, field_of_study",
  output_format = "json",
  agent = agent
)
print(result$parsed)

# Full traces are always included in asa_result
result <- run_task(
  prompt = "Search for information",
  agent = agent
)
cat(result$raw_output)

# Use output_format = "raw" only when you also need raw_response
result <- run_task(
  prompt = "Search for information",
  output_format = "raw",
  agent = agent
)
str(result$raw_response)  # Inspect full underlying Python response

# With temporal filtering (past year only)
result <- run_task(
  prompt = "Find recent AI research breakthroughs",
  temporal = temporal_options(time_filter = "y"),
  agent = agent
)

# With date range hint
result <- run_task(
  prompt = "Find tech companies founded recently",
  temporal = list(
    time_filter = "y",
    after = "2020-01-01",
    before = "2024-01-01"
  ),
  agent = agent
)

# Using asa_config for unified configuration
config <- asa_config(
  backend = "openai",
  model = "gpt-4.1-mini",
  temporal = temporal_options(time_filter = "y")
)
result <- run_task("Find recent AI research breakthroughs", config = config)
}

}
\seealso{
\code{\link{initialize_agent}}, \code{\link{run_task_batch}},
  \code{\link{asa_config}}, \code{\link{temporal_options}}
}
