Skip to main content

What is the Task?

Agents are just like the humans. As humans we are creating some virtual steps for our tasks. Like first i will search for the websites, then i will read the content then i will categorize them. For the agents task we have the some structure. The key points for the tasks are:
  • Tasks are the parts of the main job: You need to create the steps to archive your main task over Task system.
  • They increase the accruacy: With the small jobs agents are more focusing on what to do right now and their accuracy increases.
  • You can manage the Tools and Context:: With this focusing setting the tools for the tasks the overall token usage and accuracy increases. Agents only get the required context at the right time.

Core Principles For Tasks

When you are creating a Task, ensure that you define these elements as well:
  • description: Each task should have a clear, actionable description that matches its purpose.
  • context management: Tasks often depend on the results or context of previous tasks. Make sure to specify context when needed.
  • Be specific: Provide specific instructions for what the task should accomplish and how.

Defining Description

Descriptions should be simple and actionable. Keep them short to increase accuracy. There is an tradeoff between the task number and cost. If you want to get more accurate results you need to open more tasks and split your tasks. Good Descriptions
description="Check their website for the following points: 'Terms and Sales', 'About Us', 'SSL Licence' "
description="Go to website and extract their Terms of Sales link"
description="Explain the changes between today and yesterday financial operations"
description="Write an feedback for the coding standards of this code"
Bad Descriptions
description="Analyze their website for the missing things"
description="Make the financial analyze"
description="Review the pull request"

Let’s Create task for Analyzing the Merchant Websites

In Upsonic we have a Task class and they are the core parts of anything that you do actually. When you create an task you can use that task in an Direct LLM Call, Agent and Multi-Agent teams. In this example we will add the task to our merchant Website analyzer.
uv pip install upsonic "upsonic[tools]"
# pip install upsonic "upsonic[tools]"
# Upsonic Docs: Create an Agent
# https://docs.upsonic.ai/guides/2-create-an-agent



# Imports
from upsonic import Agent, Task
from upsonic.tools import WebSearch, WebRead


# Agent Creation
merchant_analyzer_agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="Merchant Analyzer V1",
    role="Analyzing the merchant websites.",
    goal="Getting the right result on their websites and giving as the user requested format",
    instructions="""
    Identify and analyze the product's category and brand.
    If the product belongs to a series, pay special attention to series details and related products.
    Summarize product trends in clear bullet points for easy review.
    Prioritize up-to-date information and highlight any unusual patterns or outliers.
    """
)


# The Company We Want to Analyze
company_name = "Toscrape.com Books"


# Task Creation
task1 = Task(
    description=f"Find the website of the {company_name}",
    tools=[WebSearch, WebRead]    
)

task2 = Task(
    description="Extract the categories in the website", 
    context=[task1],
    tools=[WebRead]
)

task3 = Task(
    description="Extract the products that they are sellin in their websites by the categories", 
    context=[task1, task2],
    tools=[WebRead]
)


# Run the tasks
merchant_analyzer_agent.print_do(task1)
merchant_analyzer_agent.print_do(task2)
merchant_analyzer_agent.print_do(task3)

final_result = task3.response

print("Final Result")
print(final_result)

Adding Files and Documents to Tasks

The context attribute is the comprehensive way to provide any contextual information to your tasks. This includes files, images, documents, other tasks, knowledge bases, or any other relevant data.

Adding Files to Tasks

from upsonic import Agent, Task
from upsonic.tools import WebRead
import json
import csv

# First, create some sample files to work with
# Create a sample CSV file
with open("sales_data.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["Month", "Revenue", "Units Sold"])
    writer.writerow(["January", "15000", "120"])
    writer.writerow(["February", "18000", "145"])
    writer.writerow(["March", "22000", "180"])

# Create a sample JSON file
data = {
    "products": ["Widget A", "Widget B", "Widget C"],
    "target_market": "Global",
    "year": 2024
}
with open("product_data.json", "w") as f:
    json.dump(data, f, indent=2)

# Create a sample text report
with open("report.txt", "w") as f:
    f.write("Sales Performance Report\n")
    f.write("========================\n\n")
    f.write("Q1 Performance: Strong growth across all segments.\n")
    f.write("Key achievements: Exceeded targets by 15%.\n")

# Create an agent for analysis
analysis_agent = Agent(
    model="openai/gpt-4o-mini",
    name="Data Analyzer",
    role="Analyzing sales and product data",
    goal="Extract insights from various file formats"
)

# Task with file attachments
task_with_files = Task(
    description="Analyze the sales data, product information, and report to extract key insights",
    context=["sales_data.csv", "product_data.json", "report.txt"],
)

# Execute the task
result = analysis_agent.print_do(task_with_files)
print(result)

Using Previous Task Results as Context

from upsonic import Agent, Task
import json

# Create separate data files for Q3 and Q4
with open("q3_data.json", "w") as f:
    json.dump({
        "quarter": "Q3_2024",
        "revenue": 50000,
        "expenses": 35000,
        "growth": "12%",
        "new_customers": 145
    }, f, indent=2)

with open("q4_data.json", "w") as f:
    json.dump({
        "quarter": "Q4_2024",
        "revenue": 58000,
        "expenses": 38000,
        "growth": "16%",
        "new_customers": 178
    }, f, indent=2)

# Create an agent
trend_agent = Agent(
    model="openai/gpt-4o-mini",
    name="Trend Analyzer",
    role="Analyzing business trends"
)

# First task: Analyze Q3 data
previous_analysis_task = Task(
    description="Analyze the Q3 2024 performance data and identify key strengths and weaknesses",
    context=["q3_data.json", "Focus on revenue, growth trends, and customer acquisition"]
)

trend_agent.print_do(previous_analysis_task)

# Second task: Compare Q4 with Q3 analysis
task_with_mixed_context = Task(
    description="Compare Q4 2024 data with the Q3 analysis results and identify key trends and improvements",
    context=[
        "q4_data.json",             # Q4 file attachment
        previous_analysis_task,     # Previous Q3 analysis result
        "Focus on quarter-over-quarter improvements and areas of concern"  # Text context
    ]
)

result = trend_agent.print_do(task_with_mixed_context)
print(result)

Supported File Types

The framework automatically handles various file formats:
  • Images: PNG, JPEG, GIF, BMP, TIFF
  • Documents: PDF, Word (.docx), Text (.txt), Markdown (.md)
  • Data: CSV, JSON, XML, Excel (.xlsx)
  • Code: Python (.py), JavaScript (.js), etc.
from upsonic import Agent, Task
import json
import csv

# Create sample files for demonstration
# 1. CSV file with financial data
with open("financial_data.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["Category", "Q1", "Q2", "Q3", "Q4"])
    writer.writerow(["Revenue", "100k", "120k", "135k", "150k"])
    writer.writerow(["Expenses", "60k", "65k", "70k", "72k"])

# 2. JSON file with raw data
with open("raw_data.json", "w") as f:
    json.dump({
        "markets": ["US", "EU", "Asia"],
        "segments": ["Enterprise", "SMB", "Consumer"],
        "growth_rate": {"US": "15%", "EU": "12%", "Asia": "25%"}
    }, f, indent=2)

# 3. Python code file for analysis
with open("analysis_helpers.py", "w") as f:
    f.write("""
def calculate_growth(current, previous):
    return ((current - previous) / previous) * 100

def format_currency(amount):
    return f"${amount:,.2f}"
""")

# 4. Markdown report
with open("market_report.md", "w") as f:
    f.write("""# Market Analysis Report

## Key Findings
- Strong performance in Asian markets
- Enterprise segment showing consistent growth
- Q4 revenue targets exceeded by 10%

## Recommendations
1. Increase investment in Asia-Pacific region
2. Focus on enterprise customer retention
""")

# Create agent for comprehensive analysis
comprehensive_agent = Agent(
    model="openai/gpt-4o-mini",
    name="Comprehensive Analyzer",
    role="Multi-format data analysis"
)

# Initial research task - analyze market report first
previous_research_task = Task(
    description="Review the market report and identify the top 3 key growth areas with specific metrics",
    context=["market_report.md"]  # Give it the market report to analyze
)

comprehensive_agent.print_do(previous_research_task)

# Task with multiple file types - now uses the previous analysis
comprehensive_task = Task(
    description="Create a comprehensive analysis report combining all data sources and validate the growth areas identified in previous analysis",
    context=[
        "financial_data.csv",       # CSV data
        "market_report.md",         # Markdown document
        "raw_data.json",            # JSON data
        previous_research_task,     # Previous task result
        "Additional context: Focus on emerging markets and growth opportunities"  # Text context
    ]
)

result = comprehensive_agent.print_do(comprehensive_task)
print(result)

Need more advanced features?

The Task system offers several advanced configurations to enhance task management:
  • Structured Output: Define custom Pydantic models for structured responses, ensuring consistent and validated output formats.
  • Contextual Dependencies: Define tasks with dependencies on the results or context of previous tasks, ensuring coherent workflows.
  • Tool Assignment: Assign specific tools to tasks to optimize resource usage and improve accuracy.
  • Caching Mechanisms: Implement intelligent caching with vector search or LLM-based similarity matching to reduce redundant processing.
  • Guardrail Validation: Apply custom validation functions with retry logic to ensure task outputs meet specific quality standards.
  • External Execution: Configure tasks to pause for external tool execution, enabling integration with external systems and human-in-the-loop workflows.
  • Comprehensive Context: Include any contextual information in the context attribute - files, images, documents, other tasks, knowledge bases, or any other relevant data for multimodal processing capabilities.
  • Context Integration: Leverage knowledge bases and RAG systems to provide rich contextual information for task execution.
  • Performance Monitoring: Track task execution metrics including duration, token usage, and cost analysis.
For detailed examples and advanced patterns, see our comprehensive Task Concept Documentation.