Skip to main content

Attributes

The Task system is configured through the Task class, which provides the following attributes:

Core Attributes

AttributeTypeDefaultDescription
descriptionstr(required)A clear statement of what the task entails
attachmentsList[str] | NoneNoneList of file paths to attach to the task. Files can also be extracted from context if provided. Files and folders in context are automatically extracted and added to attachments
toolslist[Any] | NoneNoneThe tools/resources the agent can use for this task
response_formatUnion[Type[BaseModel], type[str], None]strThe expected output format (string or Pydantic model)
responsestr | bytes | NoneNonePre-set response value (internal use, typically set via task_response() method)
response_langstr | None"en"Language for the response
contextAny | NoneNoneContext for this task (files, images, knowledge bases, etc.). File paths and folder paths in context are automatically extracted to attachments recursively
not_main_taskboolFalseWhether this task is a sub-task (not the main task)

Tool Configuration

AttributeTypeDefaultDescription
enable_thinking_toolbool | NoneNoneEnable thinking tool for complex reasoning. Overrides agent-level setting
enable_reasoning_toolbool | NoneNoneEnable reasoning tool for multi-step analysis. Overrides agent-level setting
registered_task_toolsDict[str, Any]{}Dictionary of registered tools for this task (set at runtime)
task_builtin_toolsList[Any][]List of builtin tools registered for this task (set at runtime)

Guardrail Configuration

AttributeTypeDefaultDescription
guardrailCallable | NoneNoneFunction to validate task output before proceeding. Must be a callable that accepts the task output. Raises TypeError if not callable
guardrail_retriesint | NoneNoneMaximum number of retries when guardrail validation fails

Cache Configuration

AttributeTypeDefaultDescription
enable_cacheboolFalseWhether to enable caching for this task
cache_methodLiteral[“vector_search”, “llm_call”]"vector_search"Method to use for caching: ‘vector_search’ or ‘llm_call’. Raises ValueError if invalid
cache_thresholdfloat0.7Similarity threshold for cache hits (0.0-1.0). Must be between 0.0 and 1.0. Raises ValueError if out of range
cache_embedding_providerAny | NoneNoneEmbedding provider for vector search caching. Required when cache_method="vector_search" and enable_cache=True. Auto-detected if not provided
cache_duration_minutesint60How long to cache results in minutes

Vector Search Configuration

AttributeTypeDefaultDescription
vector_search_top_kint | NoneNoneNumber of top results to return from vector search (for RAG/knowledge base)
vector_search_alphafloat | NoneNoneHybrid search alpha parameter (0.0 = keyword only, 1.0 = vector only)
vector_search_fusion_methodLiteral[‘rrf’, ‘weighted’] | NoneNoneMethod to fuse vector and keyword search results: ‘rrf’ (Reciprocal Rank Fusion) or ‘weighted’
vector_search_similarity_thresholdfloat | NoneNoneMinimum similarity score threshold for vector search results
vector_search_filterDict[str, Any] | NoneNoneMetadata filters to apply to vector search results

Runtime Status Attributes

AttributeTypeDefaultDescription
statusRunStatus | NoneNoneCurrent execution status of the task. Values: RUNNING, COMPLETED, PAUSED, CANCELLED, ERROR
is_pausedboolFalseWhether the task execution is currently paused
start_timeint | NoneNoneUnix timestamp when task execution started (set automatically)
end_timeint | NoneNoneUnix timestamp when task execution ended (set automatically)

Properties

The Task class provides the following read-only properties:
PropertyTypeDescription
idstrGet the task ID. Auto-generates a UUID if not set
task_idstrGet the task ID. Auto-generates a UUID if not set
price_idstrGet the price ID for cost tracking. Auto-generates a UUID if not set
durationfloat | NoneGet task execution duration in seconds (end_time - start_time). Returns None if not started or not ended
responsestr | bytes | NoneGet the task response. Returns None if not yet set
context_formattedstr | NoneGet the formatted context string (read-only). Set by context management process
run_idstr | NoneGet the run ID associated with this task. Allows task continuation with a new agent instance
is_problematicboolCheck if the task’s run is problematic (paused, cancelled, or error). Requires continue_run_async() instead of do_async()
is_completedboolCheck if the task’s run is already completed. A completed task cannot be re-run or continued
cache_hitboolCheck if the last response was retrieved from cache
tool_callsList[Dict[str, Any]]Get all tool calls made during this task’s execution. Each dict contains ‘tool_name’, ‘params’, and ‘tool_result’
total_costfloat | NoneGet the total estimated cost of this task in USD. Returns None if not available
total_input_tokenint | NoneGet the total number of input tokens used by this task. Returns None if not available
total_output_tokenint | NoneGet the total number of output tokens used by this task. Returns None if not available
attachments_base64List[str] | NoneConvert all attachment files to base64 encoded strings. Returns None if no attachments

Methods

Tool Management

MethodSignatureDescription
add_toolsadd_tools(tools: Union[Any, List[Any]]) -> NoneAdd tools to the task’s tool list. Tools are processed at runtime when the agent executes the task
remove_toolsremove_tools(tools: Union[str, List[str], Any, List[Any]], agent: Any) -> NoneRemove tools from the task. Supports removing tool names, function objects, agent objects, MCP handlers, class instances, and builtin tools. Requires agent instance for proper cleanup
validate_toolsvalidate_tools() -> NoneValidates each tool in the tools list. If a tool has a __control__ method, runs it to verify it returns True

Cache Management

MethodSignatureDescription
set_cache_managerset_cache_manager(cache_manager: Any) -> NoneSet the cache manager for this task (called by Agent)
get_cached_responseasync get_cached_response(input_text: str, llm_provider: Optional[Any] = None) -> Optional[Any]Get cached response for the given input text. Returns cached response if found, None otherwise
store_cache_entryasync store_cache_entry(input_text: str, output: Any) -> NoneStore a new cache entry
get_cache_statsget_cache_stats() -> Dict[str, Any]Get cache statistics including total entries, cache hits, cache misses, hit rate, and configuration
clear_cacheclear_cache() -> NoneClear all cache entries

Task Lifecycle

MethodSignatureDescription
task_starttask_start(agent: Any) -> NoneMark task as started. Sets start_time and adds canvas tools if agent has canvas
task_endtask_end() -> NoneMark task as ended. Sets end_time
task_responsetask_response(model_response: Any) -> NoneSet the task response from model output
add_tool_calladd_tool_call(tool_call: Dict[str, Any]) -> NoneAdd a tool call to the task’s history. Dict should include ‘tool_name’, ‘params’, and ‘tool_result’
add_canvasadd_canvas(canvas: Any) -> NoneAdd canvas tools to the task. Prevents duplicates
additional_descriptionasync additional_description(client: Any) -> strGenerate additional description from RAG context. Returns formatted RAG data if available

Utility Methods

MethodSignatureDescription
get_task_idget_task_id() -> strGet formatted task ID as “Task_
get_total_costget_total_cost() -> Optional[Dict[str, Any]]Get total cost information including estimated_cost, input_tokens, and output_tokens
to_dictto_dict(serialize_flag: bool = False) -> Dict[str, Any]Convert task to dictionary. If serialize_flag=True, uses cloudpickle for tools, guardrail, and response_format
from_dict@classmethod from_dict(data: Dict[str, Any], deserialize_flag: bool = False) -> TaskReconstruct Task from dictionary. If deserialize_flag=True, uses cloudpickle to deserialize pickled fields

Internal Attributes

The following attributes are internal and typically not set by users:
  • _response: Internal storage for task response
  • _context_formatted: Internal formatted context string
  • _tool_calls: Internal list of tool calls
  • _cache_manager: Internal cache manager instance (set by Agent)
  • _cache_hit: Internal flag for cache hit status
  • _original_input: Internal storage for original input description
  • _last_cache_entry: Internal storage for last cache entry
  • _run_id: Internal run ID for task continuation
  • _task_todos: Internal todo list for task planning
  • price_id_: Internal price ID (use price_id property)
  • task_id_: Internal task ID (use task_id property)
  • agent: Internal reference to agent instance

Configuration Examples

Task with Structured Response Format

from upsonic import Agent, Task
from upsonic.tools import tool
from pydantic import BaseModel
from typing import List

class AnalysisResult(BaseModel):
    summary: str
    confidence: float
    recommendations: List[str]

# Create a simple function tool
@tool
def get_market_data(year: int, quarter: int) -> str:
    """Retrieve market data for a specific year and quarter."""
    # In a real scenario, this would fetch actual data
    return f"Market data for Q{quarter} {year}: Growth rate 5.2%, Market cap $2.5T"

agent = Agent("anthropic/claude-sonnet-4-5")

task = Task(
    description="Analyze the market trends for Q4 2024",
    response_format=AnalysisResult,
    enable_thinking_tool=True,
    tools=[get_market_data]  # Add the function tool to the task
)

result = agent.print_do(task)
print(result.summary)
print(f"Confidence: {result.confidence}")
print(f"Recommendations: {result.recommendations}")

Task with Caching

from upsonic import Agent, Task
from upsonic.embeddings.factory import auto_detect_best_embedding

agent = Agent("anthropic/claude-sonnet-4-5")

# Get embedding provider for vector search caching
embedding_provider = auto_detect_best_embedding()

task = Task(
    description="Analyze the market trends for Q4 2024",
    enable_cache=True,
    cache_method="vector_search",
    cache_threshold=0.8,
    cache_duration_minutes=60,
    cache_embedding_provider=embedding_provider
)

agent.print_do(task)

# Check if response came from cache
if task.cache_hit:
    print("Response retrieved from cache!")

# Get cache statistics
stats = task.get_cache_stats()
print(f"Cache hit rate: {stats['hit_rate']:.2%}")

Task with Guardrail

from upsonic import Agent, Task

def validate_output(output: str) -> bool:
    """Validate that output contains required information."""
    required_keywords = ["summary", "analysis", "conclusion"]
    return all(keyword in output.lower() for keyword in required_keywords)

agent = Agent("anthropic/claude-sonnet-4-5")

task = Task(
    description="Write a comprehensive market analysis report",
    guardrail=validate_output,
    guardrail_retries=3
)

agent.print_do(task)

Task with Context and Attachments

from upsonic import Agent, Task

agent = Agent("anthropic/claude-sonnet-4-5")

# Files in context are automatically extracted to attachments
task = Task(
    description="Summarize the key points from these documents",
    context=["/path/to/document1.pdf", "/path/to/document2.pdf", "/path/to/image.png"]
)

agent.print_do(task)

Task with Vector Search Configuration

from upsonic import Agent, Task

agent = Agent("anthropic/claude-sonnet-4-5")

task = Task(
    description="Search for relevant information about AI agents",
    vector_search_top_k=10,
    vector_search_alpha=0.7,
    vector_search_fusion_method="rrf",
    vector_search_similarity_threshold=0.6,
    vector_search_filter={"category": "technology", "year": 2024}
)

agent.print_do(task)

Accessing Task Properties

from upsonic import Agent, Task

agent = Agent("anthropic/claude-sonnet-4-5")

task = Task(
    description="Perform a complex analysis"
)

agent.print_do(task)

# Access task properties
print(f"Task ID: {task.id}")
print(f"Duration: {task.duration:.2f} seconds")
print(f"Status: {task.status}")
print(f"Total Cost: ${task.total_cost:.4f}")
print(f"Input Tokens: {task.total_input_token}")
print(f"Output Tokens: {task.total_output_token}")
print(f"Tool Calls: {len(task.tool_calls)}")

# Check task state
if task.is_completed:
    print("Task completed successfully")
elif task.is_problematic:
    print("Task has issues and needs continuation")