🐍 Examples
This guide demonstrates the revolutionary TaskRunner interface introduced in v0.2.1, showcasing how complex WebSocket operations have been simplified from 400+ lines to just 10-20 lines of code.
You'll learn modern best practices for client initialization, resource management, and both automated and interactive task execution.
✅ Prerequisites
Before running any of these examples, ensure you have:
- Installed the SDK: Follow the instructions in the Getting Started guide.
- Configured Your API Key: Refer to the Authentication guide for secure API key setup.
- v0.2.1+: Ensure you're using the latest SDK version with TaskRunner support.
Step 1: 🚀 Modern Client Initialization
Initialize the Client with enhanced error handling and validation:
import os
from wyseos.mate import Client, ClientOptions
from wyseos.mate.config import load_config
def initialize_client():
"""Initialize WyseOS Client with robust error handling."""
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(script_dir, "mate.yaml")
client = Client(load_config(config_path))
print("✅ Loaded configuration from mate.yaml")
return client
except FileNotFoundError:
print("⚠️ mate.yaml not found, using environment variables")
# Fallback to environment variables
api_key = os.getenv('WYSEOS_API_KEY')
if not api_key:
raise ValueError("API key required: set WYSEOS_API_KEY or create mate.yaml")
client = Client(ClientOptions(api_key=api_key))
print("✅ Client initialized from environment")
return client
except Exception as e:
print(f"❌ Error loading configuration: {e}")
raise
client = initialize_client()Step 2: 📊 Resource Discovery
Query your available resources efficiently:
from wyseos.mate.models import ListOptions
def discover_resources(client: Client):
"""Discover available teams and agents."""
# List teams
teams = client.team.get_list("all", ListOptions(page_size=5))
print(f"📋 Found {teams.total} teams:")
for team in teams.data:
print(f" • {team.name} (ID: {team.team_id})")
# List agents
agents = client.agent.get_list("all", ListOptions(page_size=5))
print(f"🤖 Found {agents.total} agents:")
for agent in agents.data:
print(f" • {agent.name} ({agent.agent_type})")
return teams.data[0] if teams.data else None
# Discover available resources
team = discover_resources(client)
if not team:
raise ValueError("No teams available")Step 3: 💬 Session Management
Create and manage sessions with proper error handling:
from wyseos.mate.models import CreateSessionRequest
def create_session(client: Client, team_id: str, task: str):
"""Create a new session for task execution."""
try:
request = CreateSessionRequest(team_id=team_id, task=task)
response = client.session.create(request)
session = client.session.get_info(response.session_id)
print(f"✅ Session created: {session.session_id}")
print(f" Status: {session.status}")
print(f" Team: {team_id}")
return session
except Exception as e:
print(f"❌ Failed to create session: {e}")
raise
# Create session for our task
task_description = "Analyze the latest market trends in renewable energy"
session = create_session(client, team.team_id, task_description)Step 4: 🤖 TaskRunner - Automated Execution
Experience the power of the new TaskRunner interface for automated task execution:
from wyseos.mate.websocket import WebSocketClient, TaskExecutionOptions
def run_automated_task(client: Client, session, task: str, team_id: str):
"""Execute a task using the revolutionary TaskRunner interface."""
# Create WebSocket client and TaskRunner
ws_client = WebSocketClient(
base_url=client.base_url,
api_key=client.api_key,
session_id=session.session_id,
heartbeat_interval=30
)
task_runner = ws_client.create_task_runner(client, session)
# Configure execution options for optimal performance
options = TaskExecutionOptions(
auto_accept_plan=True, # Automatically accept execution plans
capture_screenshots=False, # Disable screenshots for faster execution
enable_browser_logging=True, # Keep browser logs for debugging
enable_event_logging=True, # Enable detailed event logging
completion_timeout=300 # 5-minute timeout
)
print(f"🚀 Starting automated task execution...")
print(f" Task: {task}")
# Execute the task - this replaces 400+ lines of complex WebSocket code!
result = task_runner.run_task(task, team_id, options)
# Process results
if result.success:
print(f"✅ Task completed successfully!")
print(f" Duration: {result.session_duration:.1f} seconds")
print(f" Messages: {result.message_count}")
print(f" Answer: {result.final_answer}")
else:
print(f"❌ Task failed: {result.error}")
return result
# Execute automated task
result = run_automated_task(client, session, task_description, team.team_id)Step 5: 💬 TaskRunner - Interactive Session
For scenarios requiring user interaction, use the interactive mode:
def run_interactive_session(client: Client, session, initial_task: str, team_id: str):
"""Run an interactive session with user input capabilities."""
ws_client = WebSocketClient(
base_url=client.base_url,
api_key=client.api_key,
session_id=session.session_id
)
task_runner = ws_client.create_task_runner(client, session)
# Configure for interactive use
options = TaskExecutionOptions(
auto_accept_plan=False, # Manual plan approval
capture_screenshots=True, # Capture screenshots for review
enable_browser_logging=True,
enable_event_logging=True,
completion_timeout=600 # Longer timeout for user interaction
)
print(f"🎮 Starting interactive session...")
print(f" Initial task: {initial_task}")
print(f" Type 'exit' to end the session")
# Start interactive session
task_runner.run_interactive_session(initial_task, team_id, options)
# Example interactive session
# run_interactive_session(client, session, "Help me research AI developments", team.team_id)Step 6: 📂 File Upload Integration
Combine file uploads with task execution for comprehensive workflows:
def upload_and_analyze(client: Client, session, file_paths: list, analysis_task: str, team_id: str):
"""Upload files and analyze them using TaskRunner."""
uploaded_files = []
# Upload files
for file_path in file_paths:
try:
with open(file_path, 'rb') as f:
upload_result = client.file_upload.upload_file(
session_id=session.session_id,
file=f,
filename=os.path.basename(file_path)
)
uploaded_files.append(upload_result)
print(f"📎 Uploaded: {os.path.basename(file_path)}")
except Exception as e:
print(f"❌ Upload failed for {file_path}: {e}")
if not uploaded_files:
print("⚠️ No files uploaded successfully")
return None
# Create TaskRunner and analyze files
ws_client = WebSocketClient(
base_url=client.base_url,
api_key=client.api_key,
session_id=session.session_id
)
task_runner = ws_client.create_task_runner(client, session)
# Enhanced task with file context
enhanced_task = f"{analysis_task}\n\nAnalyze the {len(uploaded_files)} uploaded files."
options = TaskExecutionOptions(
auto_accept_plan=True,
capture_screenshots=True, # Capture analysis results
enable_event_logging=True
)
result = task_runner.run_task(enhanced_task, team_id, options)
if result.success:
print(f"📊 File analysis completed!")
print(f" Files processed: {len(uploaded_files)}")
print(f" Screenshots captured: {len(result.screenshots)}")
return result
else:
print(f"❌ Analysis failed: {result.error}")
return None
# Example file upload and analysis
# file_paths = ["data.csv", "report.pdf"]
# analysis_result = upload_and_analyze(
# client, session, file_paths,
# "Summarize key insights from these documents",
# team.team_id
# )Step 7: 🔍 Advanced Result Processing
Process TaskRunner results with comprehensive analysis:
def analyze_task_results(result):
"""Analyze and display detailed task execution results."""
if not result:
return
print("📊 Task Execution Analysis:")
print(f" Success: {'✅' if result.success else '❌'}")
print(f" Duration: {result.session_duration:.2f} seconds")
print(f" Messages: {result.message_count}")
if result.execution_logs:
print(f" Log entries: {len(result.execution_logs)}")
# Show recent log entries
for log in result.execution_logs[-3:]:
print(f" - {log.get('timestamp', 'N/A')}: {log.get('message', 'N/A')}")
if result.screenshots:
print(f" Screenshots: {len(result.screenshots)}")
# Screenshots are available when capture_screenshots=True
if result.plan_history:
print(f" Plan changes: {len(result.plan_history)}")
print(f"📝 Final Answer: {result.final_answer}")
# Analyze previous results
analyze_task_results(result)🏁 Complete Example
Here's a complete script that ties everything together:
def main():
"""Complete example demonstrating v0.2.1 TaskRunner capabilities."""
# 1. Initialize client
client = initialize_client()
# 2. Discover resources
team = discover_resources(client)
if not team:
print("❌ No teams available")
return
# 3. Create session
task = input("Enter your task (or press Enter for demo): ").strip()
if not task:
task = "Analyze the current state of renewable energy technology"
session = create_session(client, team.team_id, task)
# 4. Choose execution mode
mode = input("Choose mode (1=automated, 2=interactive): ").strip()
if mode == "2":
# Interactive mode
run_interactive_session(client, session, task, team.team_id)
else:
# Automated mode (default)
result = run_automated_task(client, session, task, team.team_id)
analyze_task_results(result)
print("🎉 Example completed!")
if __name__ == "__main__":
main()🌟 Key Benefits of v0.2.1
The examples above demonstrate the revolutionary improvements in v0.2.1:
- 🎯 90% Code Reduction: Complex WebSocket operations simplified to just a few lines
- ⚡ Instant Productivity: Get from zero to running tasks in under 30 seconds
- 🔧 Flexible Configuration: Fine-tune behavior with
TaskExecutionOptions - 📊 Rich Results: Comprehensive execution data with
TaskResult - 🛡️ Robust Error Handling: Built-in error management and recovery
- 🎮 Dual Modes: Both automated and interactive execution patterns
The TaskRunner interface transforms complex WebSocket programming into simple, intuitive method calls while maintaining full power and flexibility.