Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions task_examples/company_research_sales_strategy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Company Research & Sales Strategy Agent

A comprehensive Company Research and Sales Strategy Agent built with the **Upsonic AI Agent Framework**. This example demonstrates how to use `DeepAgent` with specialized subagents to conduct deep company research, analyze industry trends, perform financial analysis, and develop tailored sales strategies.

## Features

- 🔍 **Comprehensive Company Research**: Deep analysis of target companies including business models, products, markets, and competitive positioning
- 📊 **Industry Analysis**: Market trends, competitive landscape, emerging technologies, and regulatory environment analysis
- 💹 **Financial Analysis**: Stock performance, fundamentals, analyst recommendations, and market sentiment using YFinance
- 🎯 **Sales Strategy Development**: Tailored sales strategies with target segments, value propositions, pricing, and messaging
- 🤖 **DeepAgent Orchestration**: Automatically plans and coordinates specialized sub-agents to fulfill complex research goals
- 🧠 **Persistent Memory**: SQLite-based memory for session persistence and conversation history
- 🏗️ **Modular Design**: Clean separation of concerns with specialized agents, schemas, and utilities

## Prerequisites

- Python 3.10+
- OpenAI API key
- (Optional) Tavily API key for enhanced search capabilities

## Installation

1. **Navigate to this directory**:
```bash
cd examples/company_research_sales_strategy
```

2. **Install dependencies**:
```bash
# Install all dependencies (API)
upsonic install

# Or install specific sections:
upsonic install api # API dependencies only (default)
upsonic install development # Development dependencies only
```

3. **Set up environment variables**:
```bash
export OPENAI_API_KEY="your-api-key"
export TAVILY_API_KEY="your-tavily-key" # Optional, falls back to DuckDuckGo
```

## Usage

### Run the API Server

To run the agent as a FastAPI server:

```bash
upsonic run
```

The API will be available at `http://localhost:8000` with automatic OpenAPI documentation at `http://localhost:8000/docs`.

OR

You can run the agent directly:

```bash
python3 main.py
```

**Example API Call:**
```bash
curl -X POST http://localhost:8000/call \
-H "Content-Type: application/json" \
-d '{
"company_name": "OpenAI",
"industry": "Artificial Intelligence",
"company_symbol": null
}'
```

## Project Structure

```
company_research_sales_strategy/
├── main.py # Entry point with main() and amain() functions
├── upsonic_configs.json # Upsonic configuration and dependencies
├── orchestrator.py # DeepAgent orchestrator creation
├── subagents.py # Specialized subagent factory functions
├── schemas.py # Pydantic output schemas
├── task_builder.py # Task description builder
└── README.md # This file
```

## How It Works

1. **Orchestrator Agent**: A `DeepAgent` that coordinates the entire research and strategy development process using planning tools and subagent delegation.

2. **Specialized Subagents**: Four domain experts that handle specific research areas:
- **Company Researcher**: Gathers comprehensive company information using web search
- **Industry Analyst**: Analyzes industry trends and market dynamics
- **Financial Analyst**: Performs financial analysis using YFinance tools
- **Sales Strategist**: Develops tailored sales strategies based on research findings

3. **DeepAgent Coordination**: Instead of manually chaining tasks, `DeepAgent` automatically:
- Creates execution plans using the planning tool
- Delegates tasks to appropriate specialists
- Passes context between subagents
- Synthesizes findings into comprehensive reports

4. **Memory Persistence**: Uses SQLite database to store session history, summaries, and research findings for continuity across runs.

## Example Queries

- Research "Tesla" in the "Electric Vehicles" industry with stock symbol "TSLA"
- Analyze "Microsoft" and develop a sales strategy for the "Cloud Computing" industry
- Research "Anthropic" in the "AI Safety" industry without financial data

## Input Parameters

- `company_name` (required): Name of the target company
- `company_symbol` (optional): Stock symbol for financial analysis (e.g., "AAPL", "TSLA")
- `industry` (optional): Industry name for focused analysis
- `enable_memory` (optional): Whether to enable memory persistence (default: true)
- `storage_path` (optional): Path for SQLite storage (default: "company_research.db")
- `model` (optional): Model identifier (default: "openai/gpt-4o")

## Output

Returns a comprehensive report containing:
- Company research findings
- Industry analysis
- Financial analysis (if symbol provided)
- Tailored sales strategy
- Executive summary with key insights and recommendations

109 changes: 109 additions & 0 deletions task_examples/company_research_sales_strategy/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""
Main entry point for Company Research and Sales Strategy Agent.

This module provides the entry points (main and amain) that coordinate
the comprehensive research and strategy development process.
"""

from __future__ import annotations

from typing import Dict, Any

from upsonic import Task
try:
from .orchestrator import create_orchestrator_agent
from .task_builder import build_research_task
from .schemas import ComprehensiveReportOutput
except ImportError:
from orchestrator import create_orchestrator_agent
from task_builder import build_research_task
from schemas import ComprehensiveReportOutput


def main(inputs: Dict[str, Any]) -> Dict[str, Any]:
"""
Main function for company research and sales strategy development.

Args:
inputs: Dictionary containing:
- company_name: Name of the target company (required)
- company_symbol: Optional stock symbol for financial analysis
- industry: Optional industry name for focused analysis
- enable_memory: Whether to enable memory persistence (default: True)
- storage_path: Optional path for SQLite storage (default: "company_research.db")
- model: Optional model identifier (default: "openai/gpt-4o")

Returns:
Dictionary containing comprehensive research report
"""
company_name = inputs.get("company_name")
if not company_name:
raise ValueError("company_name is required in inputs")

company_symbol = inputs.get("company_symbol")
industry = inputs.get("industry")
enable_memory = inputs.get("enable_memory", True)
storage_path = inputs.get("storage_path")
model = inputs.get("model", "openai/gpt-4o")

orchestrator = create_orchestrator_agent(
model=model,
storage_path=storage_path,
enable_memory=enable_memory,
)

task_description = build_research_task(
company_name=company_name,
company_symbol=company_symbol,
industry=industry,
)

task = Task(task_description, response_format=ComprehensiveReportOutput)

result = orchestrator.do(task)

return {
"company_name": company_name,
"comprehensive_report": result,
"research_completed": True,
}



if __name__ == "__main__":
import json
import sys

test_inputs = {
"company_name": "OpenAI",
"company_symbol": None,
"industry": "Artificial Intelligence",
"enable_memory": False,
"storage_path": None,
"model": "openai/gpt-4o-mini",
}

if len(sys.argv) > 1:
try:
with open(sys.argv[1], "r") as f:
test_inputs = json.load(f)
except Exception as e:
print(f"Error loading JSON file: {e}")
print("Using default test inputs")

try:
result = main(test_inputs)

print("\n" + "=" * 80)
print("Research Completed Successfully!")
print("=" * 80)
print(f"\nCompany: {result.get('company_name')}")
print(f"Research Status: {'Completed' if result.get('research_completed') else 'Failed'}")
print(f"\nComprehensive Report:\n{result.get('comprehensive_report', 'N/A')}")

except Exception as e:
print(f"\n❌ Error during execution: {e}")
import traceback
traceback.print_exc()
sys.exit(1)

103 changes: 103 additions & 0 deletions task_examples/company_research_sales_strategy/orchestrator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""
Orchestrator agent creation and configuration.

Creates the main DeepAgent orchestrator that coordinates all specialized
subagents for comprehensive company research and sales strategy development.
"""

from __future__ import annotations

from typing import Optional

from upsonic.agent.deepagent import DeepAgent
from upsonic.db.database import SqliteDatabase

try:
from .subagents import (
create_research_subagent,
create_industry_analyst_subagent,
create_financial_analyst_subagent,
create_sales_strategist_subagent,
)
except ImportError:
from subagents import (
create_research_subagent,
create_industry_analyst_subagent,
create_financial_analyst_subagent,
create_sales_strategist_subagent,
)


def create_orchestrator_agent(
model: str = "openai/gpt-4o",
storage_path: Optional[str] = None,
enable_memory: bool = True,
) -> DeepAgent:
"""Create the main orchestrator DeepAgent with all subagents.

Args:
model: Model identifier for the orchestrator agent
storage_path: Optional path for SQLite storage database
enable_memory: Whether to enable memory persistence

Returns:
Configured DeepAgent instance with all subagents
"""
db = None
memory = None

if enable_memory:
if storage_path is None:
storage_path = "company_research.db"
db = SqliteDatabase(
db_file=storage_path,
agent_sessions_table_name="agent_sessions",
session_id="company_research_session",
user_id="research_user",
full_session_memory=True,
summary_memory=True,
model=model,
)
memory = db.memory

subagents = [
create_research_subagent(),
create_industry_analyst_subagent(),
create_financial_analyst_subagent(),
create_sales_strategist_subagent(),
]

orchestrator = DeepAgent(
model=model,
name="Company Research & Sales Strategy Orchestrator",
role="Senior Business Strategy Consultant",
goal="Orchestrate comprehensive company research, industry analysis, financial evaluation, and sales strategy development",
system_prompt="""You are a senior business strategy consultant orchestrating a comprehensive
research and strategy development process. Your role is to:

1. Coordinate specialized subagents to conduct deep research on target companies
2. Analyze industry trends and competitive landscape
3. Evaluate financial performance and market position
4. Synthesize findings into actionable sales strategies

Use the planning tool (write_todos) to break down complex research tasks. Delegate specific
research areas to specialized subagents. Synthesize all findings into a comprehensive report
with actionable insights and recommendations.

Always use subagents for specialized tasks:
- Use 'company-researcher' for company-specific research
- Use 'industry-analyst' for industry and market analysis
- Use 'financial-analyst' for financial data and stock analysis
- Use 'sales-strategist' for sales strategy development

Coordinate parallel execution when tasks are independent to maximize efficiency.""",
memory=memory,
subagents=subagents,
enable_planning=True,
enable_filesystem=True,
tool_call_limit=30,
debug=False,
)

return orchestrator

Loading