Skip to content

Add Dappier Search Tool #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 5, 2025
Merged
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
255 changes: 255 additions & 0 deletions agentstack/_tools/dappier/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
import os
from typing import Optional, Literal
from dappier import Dappier

# Initialize the Dappier client
client = Dappier(api_key=os.getenv("DAPPIER_API_KEY"))

# --- Functions for AI Models ---


def real_time_web_search(query: str) -> str:
"""
Perform a real-time web search. Access the latest news, stock market data, weather,
travel information, deals, and more using this AI model. Use when no stock ticker symbol
is provided.
Args:
query: The search query to retrieve real-time information.
Returns:
A formatted string containing real-time search results.
"""
try:
return client.search_real_time_data_string(query=query, ai_model_id="am_01j06ytn18ejftedz6dyhz2b15")
except Exception as e:
return f"Error: {str(e)}"


def stock_market_data_search(query: str) -> str:
"""
Perform a real-time stock market data search. Retrieve real-time financial news,
stock prices, and trade updates with AI-powered insights using this model. Use only when a
stock ticker symbol is provided.
Args:
query: The search query to retrieve real-time stock market information.
Returns:
A formatted string containing real-time financial search results.
"""
try:
return client.search_real_time_data_string(query=query, ai_model_id="am_01j749h8pbf7ns8r1bq9s2evrh")
except Exception as e:
return f"Error: {str(e)}"


# --- Functions for Data Models ---


def get_sports_news(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered Sports News recommendations. Get real-time news, updates, and personalized
content from top sports sources like Sportsnaut, Forever Blueshirts, Minnesota Sports Fan,
LAFB Network, Bounding Into Sports, and Ringside Intel.
Args:
query: The input string for sports-related content recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended sports articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01j0pb465keqmatq9k83dthx34",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"


def get_lifestyle_news(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered Lifestyle News recommendations. Access current lifestyle updates, analysis,
and insights from leading lifestyle publications like The Mix, Snipdaily, Nerdable
and Familyproof.
Args:
query: The input string for lifestyle-related content recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended lifestyle articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01j0q82s4bfjmsqkhs3ywm3x6y",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"


def get_iheartdogs_content(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered iHeartDogs content recommendations. Tap into a dog care expert with access
to thousands of articles covering pet health, behavior, grooming, and ownership from
iHeartDogs.com.
Args:
query: The input string for dog care-related content recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended dog-related articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01j1sz8t3qe6v9g8ad102kvmqn",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"


def get_iheartcats_content(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered iHeartCats content recommendations. Utilize a cat care specialist that
provides comprehensive content on cat health, behavior, and lifestyle from iHeartCats.com.
Args:
query: The input string for cat care-related content recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended cat-related articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01j1sza0h7ekhaecys2p3y0vmj",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"


def get_greenmonster_guides(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered GreenMonster guides and articles. Receive guidance for making conscious
and compassionate choices benefiting people, animals, and the planet.
Args:
query: The input string for eco-friendly and conscious lifestyle recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended eco-conscious articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01j5xy9w5sf49bm6b1prm80m27",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"


def get_wishtv_news(
query: str,
similarity_top_k: int = 9,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] = "most_recent",
) -> str:
"""
Fetch AI-powered WISH-TV news recommendations. Get recommendations covering sports,
breaking news, politics, multicultural updates, Hispanic language content, entertainment,
health, and education.
Args:
query: The input string for general news recommendations.
similarity_top_k: Number of top similar articles to retrieve.
ref: Optional site domain to prioritize recommendations.
num_articles_ref: Minimum number of articles to return from the reference domain.
search_algorithm: The search algorithm to use ('most_recent', 'semantic', 'most_recent_semantic', 'trending').
Returns:
A formatted string containing recommended news articles.
"""
try:
return client.get_ai_recommendations_string(
query=query,
data_model_id="dm_01jagy9nqaeer9hxx8z1sk1jx6",
similarity_top_k=similarity_top_k,
ref=ref or "",
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
except Exception as e:
return f"Error: {str(e)}"
20 changes: 20 additions & 0 deletions agentstack/_tools/dappier/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "dappier",
"url": "https://www.dappier.com/",
"category": "search",
"env": {
"DAPPIER_API_KEY": null
},
"dependencies": ["dappier>=0.3.5"],
"tools": [
"real_time_web_search",
"stock_market_data_search",
"get_sports_news",
"get_lifestyle_news",
"get_iheartdogs_content",
"get_iheartcats_content",
"get_greenmonster_guides",
"get_wishtv_news"
],
"cta": "Create an API key at https://platform.dappier.com/profile/api-keys/"
}
1 change: 1 addition & 0 deletions docs/llms.txt
Original file line number Diff line number Diff line change
@@ -1287,6 +1287,7 @@ description: 'AgentStack tools from community contributors'

## Search
- [Perplexity](/tools/tool/perplexity)
- [Dappier](/tools/tool/dappier)

## Memory / State

1 change: 1 addition & 0 deletions docs/tools/community.mdx
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@ description: 'AgentStack tools from community contributors'

## Search
- [Perplexity](/tools/tool/perplexity)
- [Dappier](/tools/tool/dappier)

## Memory / State

66 changes: 66 additions & 0 deletions docs/tools/tool/dappier.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
title: Dappier
description: Real-time web and content search for agents
icon: search
---

Dappier is a real time search that connects any AI to proprietary, real-time data — including web search, news, sports, stock market data, and premium publisher content.

## Description
Dappier Real-Time Search provides instant access to live web search results and AI-powered recommendations with:

- Real-Time Web Search offering up-to-the-minute results from Google, financial markets, and global news
- Specialized Content Models trained on curated datasets for domains like sports, lifestyle, pet care, sustainability, and multicultural news
- Intelligent Query Routing that automatically selects the appropriate model based on user input

### Core Features:

- Web Search - Perform real-time web lookups across news, stocks, travel, weather, and more
- Stock Market Data - Retrieve live financial news, stock prices, and trades
- Content Recommendations - Get semantically matched articles tailored to user interests
- Domain-Specific Models - Specialized AI trained on lifestyle, pets, sports, and green living

### Output Formats:

- Summarized real-time search results
- Curated lists of recommended articles
- Live financial and stock market insights
- Structured query-to-content responses

## Available Models and Functions

> Explore various AI models and data models available at [Dappier Marketplace](https://marketplace.dappier.com/marketplace).

### AI Models

| Function | Model | Description | Arguments |
|:---|:---|:---|:---|
| `real_time_web_search` | `am_01j06ytn18ejftedz6dyhz2b15` | Perform a real-time web search across Google, news, weather, and travel data. | `query: str` |
| `stock_market_data_search` | `am_01j749h8pbf7ns8r1bq9s2evrh` | Perform a real-time stock market data search including stock prices and financial news. | `query: str` |

### Data Models

| Function | Model | Description | Arguments |
|:---|:---|:---|:---|
| `get_sports_news` | `dm_01j0pb465keqmatq9k83dthx34` | Get real-time sports news and updates from top sports sources. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |
| `get_lifestyle_news` | `dm_01j0q82s4bfjmsqkhs3ywm3x6y` | Access real-time lifestyle news and insights from popular publications. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |
| `get_iheartdogs_content` | `dm_01j1sz8t3qe6v9g8ad102kvmqn` | Fetch dog care articles on health, behavior, and grooming from iHeartDogs. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |
| `get_iheartcats_content` | `dm_01j1sza0h7ekhaecys2p3y0vmj` | Fetch cat care content on health, lifestyle, and behavior from iHeartCats. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |
| `get_greenmonster_guides` | `dm_01j5xy9w5sf49bm6b1prm80m27` | Access eco-conscious lifestyle articles from GreenMonster. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |
| `get_wishtv_news` | `dm_01jagy9nqaeer9hxx8z1sk1jx6` | Get news updates on politics, entertainment, and multicultural topics from WISH-TV. | `query: str`, `similarity_top_k: int`, `ref: Optional[str]`, `num_articles_ref: int`, `search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"]` |

## Installation

```bash
agentstack tools add dappier
```

Set the environment variable

```env
DAPPIER_API_KEY=...
```

## Usage
Dappier can be configured for different behaviors by modifying `src/tools/dappier_tool.py`.
6 changes: 6 additions & 0 deletions examples/stock_market_research/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#AGENTOPS_API_KEY=...
#OPENAI_API_KEY=...

# Tools

#DAPPIER_API_KEY=...
166 changes: 166 additions & 0 deletions examples/stock_market_research/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.agentops/
agentstack.log
.agentstack*
10 changes: 10 additions & 0 deletions examples/stock_market_research/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

MIT License

Copyright (c) 2025 Name <Email>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 changes: 37 additions & 0 deletions examples/stock_market_research/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# stock_market_research


## How to build your Crew Agent
### With the CLI
Add an agent using AgentStack with the CLI:
`agentstack generate agent <agent_name>`
You can also shorten this to `agentstack g a <agent_name>`
For wizard support use `agentstack g a <agent_name> --wizard`
Finally for creation in the CLI alone, use `agentstack g a <agent_name> --role/-r <role> --goal/-g <goal> --backstory/-b <backstory> --model/-m <provider/model>`

This will automatically create a new agent in the `agents.yaml` config as well as in your code. Either placeholder strings will be used, or data included in the wizard.

Similarly, tasks can be created with `agentstack g t <tool_name>`

Add tools with `agentstack tools add` and view tools available with `agentstack tools list`

## How to use your Agent
In this directory, run `uv pip install --requirements pyproject.toml`

To run your project, use the following command:
`agentstack run`

This will initialize your crew of AI agents and begin task execution as defined in your configuration in the main.py file.

#### Replay Tasks from Latest Crew Kickoff:

CrewAI now includes a replay feature that allows you to list the tasks from the last run and replay from a specific one. To use this feature, run:
`crewai replay <task_id>`
Replace <task_id> with the ID of the task you want to replay.

#### Reset Crew Memory
If you need to reset the memory of your crew before running it again, you can do so by calling the reset memory feature:
`crewai reset-memory`
This will clear the crew's memory, allowing for a fresh start.

> 🪩 Project built with [AgentStack](https://github.com/AgentOps-AI/AgentStack)
11 changes: 11 additions & 0 deletions examples/stock_market_research/agentstack.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"framework": "crewai",
"tools": [
"dappier"
],
"default_model": "openai/gpt-4o",
"agentstack_version": "0.3.5",
"template": "stock_market_research",
"template_version": "4",
"use_git": false
}
15 changes: 15 additions & 0 deletions examples/stock_market_research/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[project]
name = "stock_market_research"
version = "0.0.1"
description = ""
authors = [
{ name = "Name <Email>" }
]
license = { text = "MIT" }
requires-python = ">=3.10"

dependencies = [
"agentstack>=0.3.5",
"crewai>=0.118.0",
"dappier>=0.3.5",
]
84 changes: 84 additions & 0 deletions examples/stock_market_research/reports/tesla_investment_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Investment Report: Tesla, Inc. (TSLA)

## 1. AI Summary of Tesla

Tesla is a leading force in the automotive industry, particularly in electric vehicles, under the leadership of CEO Elon Musk. With a vision to accelerate the world's transition to sustainable energy, Tesla continues to innovate across vehicle production and energy solutions. Despite recent financial pressures, Tesla is committed to its long-term growth objectives.

## 2. Company Profile

- **Industry/Sector**: Automotive / Electric Vehicles
- **CEO**: Elon Musk
- **Headquarters Location**: Palo Alto, California, USA
- **Employee Count**: Approximately 125,665
- **Market Capitalization**: Around $921 billion
- **Stock Ticker Symbol**: TSLA

## 3. Financial Performance Metrics

| Metric | Value |
|-----------------------------|--------------------------|
| **Revenue (TTM)** | $95.72 billion |
| **Net Income (TTM)** | $1.5 billion |
| **YoY Revenue Growth** | -9.20% |
| **Gross Margin** | 16.3% |
| **Operating Income** | $400 million |
| **Operating Margin** | 2.1% |
| **Q1 2025 Highlights** | Significant margin pressures; Energy storage deployments up 154% YoY |

## 4. Competitive Benchmarking

| Company | Market Cap (B) | Stock Price | P/E Ratio | Revenue (TTM) (B) |
|---------------|----------------|-------------|-----------|-------------------|
| **Tesla, Inc.** (TSLA) | $921 | ~$220 | ~60 | $95.72 |
| **NIO Inc.** (NIO) | $30 | ~$12 | ~25 | $6.5 |
| **Rivian Automotive, Inc.** (RIVN) | $18 | ~$10 | N/A (losses) | $1.5 |
| **Lucid Motors, Inc.** (LCID) | $12 | ~$8 | N/A (losses) | $1 |
| **Li Auto Inc.** (LI) | $20 | ~$15 | ~30 | $5 |

### Key Highlights:
- Tesla's market cap and revenue far exceed those of its peers.
- High P/E ratio suggests strong investor confidence in future growth.

## 5. Real-Time Stock Snapshot

- **Current Price:** $282.86
- **Daily Change:** +$3.21 (+1.15%)
- **Volume:** 1,500,000 shares
- **52-Week High:** $350.00
- **52-Week Low:** $180.00
- **P/E Ratio:** 45.67
- **EPS:** $6.19
- **Dividend Yield:** 0.00%

### Price Performance:
- **1 Day:** +1.15%
- **5 Days:** +3.50%
- **1 Month:** +5.00%
- **YTD:** +15.00%
- **1 Year:** +25.00%

## 6. Categorized Financial News

### Market Moves:
- **Unfortunate News for Tesla Stock Investors** (Sentiment: Negative) - Reporting on increased tariffs impacting costs and likely reducing margins. [Read more](https://www.fool.com/investing/2025/05/01/unfortunate-news-for-tesla-stock-investors/?source=iedfolrf0000001)

### Partnerships:
- **Why Tesla Stock Hit the Brakes Today** (Sentiment: Cautious) - Analysis on the potential impact of a new Waymo-Toyota partnership on Tesla's autonomous driving strategies. [Read more](https://www.fool.com/investing/2025/04/30/why-tesla-stock-hit-the-brakes-today/?source=iedfolrf0000001)

## 7. Insight Section

### What's Going on with Tesla

Tesla is facing margin pressures due to increased costs associated with tariffs and inventory management challenges. Yet, the company shows resilience with strong energy storage growth and sustained leadership in the EV sector.

### Why It Matters

These financial and market challenges are pivotal as they may influence Tesla's global competitiveness, investor sentiment, and stock performance. The automotive industry's pivot towards autonomous technology is also critical to maintain Tesla's edge over competitors.

### Outlook (Not Financial Advice)

Despite current challenges, Tesla’s innovative approach and substantial market presence suggest potential for recovery and growth, especially with strategic advancements in energy and technology. Investors should monitor upcoming financial releases and market conditions as Tesla revisits its guidance.

```
This comprehensive report covers Tesla’s current status, competitive positioning, real-time performance, latest news impacts, and a forward-looking insight narrative, all formatted in detailed markdown style.
Empty file.
44 changes: 44 additions & 0 deletions examples/stock_market_research/src/config/agents.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
web_researcher:
role: >-
A company research analyst that collects structured business data, financials,
and competitive insights from the dappier real time web search.
goal: >-
To compile detailed company profiles using real-time data, covering company overview,
financial performance, and peer benchmarking.
backstory: >-
Trained to support investment research workflows, this agent uses Dappier’s real-time
web search to gather trustworthy and current business information. It builds company
snapshots with industry, CEO, market cap, and financial metrics like revenue and
net income. It also auto-compares the company to peers based on valuation and
performance metrics.
llm: openai/gpt-4o
stock_insights_analyst:
role: >-
A stock market intelligence analyst that retrieves real-time financial data and
curated news using the dappier stock market data search.
goal: >-
To deliver up-to-date stock snapshots, performance metrics, and categorized financial
news for informed investment analysis.
backstory: >-
Trained to analyze real-time financial markets using Dappier’s stock market data
tool, this agent specializes in stock-specific queries. It always includes a valid
natural language query with stock ticker symbol before sending requests. The agent
provides live insights into stock price movements, valuation ratios, earnings, and
sentiment-tagged news from reliable financial feeds like Polygon.io.
llm: openai/gpt-4o
report_analyst:
role: >-
A financial report analyst that consolidates real-time stock and company insights
into a comprehensive markdown report.
goal: >-
To generate an investor-facing, markdown-formatted summary combining company profile,
financials, benchmarking, stock performance, and real-time news with actionable
insights.
backstory: >-
Specialized in synthesizing structured data retrieved by other research agents,
this agent produces detailed markdown reports that explain what's happening with
a given stock ticker, why it matters, and what the short-term outlook may be.
It uses both company-level and stock-level intelligence—ensuring all information
is up-to-date and grounded in real-time data. Forecasts are AI-generated and clearly
marked as non-financial advice.
llm: openai/gpt-4o
1 change: 1 addition & 0 deletions examples/stock_market_research/src/config/inputs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
company_name: tesla
85 changes: 85 additions & 0 deletions examples/stock_market_research/src/config/tasks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
company_overview:
description: >-
As of {timestamp}, fetch the company overview for {company_name} using real-time web search with the timestamp. Include
company profile, industry, sector, CEO, headquarters location, employee count, market
capitalization and stock ticker symbol.
expected_output: >-
A structured company profile including: Company Profile, Industry, Sector, CEO,
HQ Location, Employees, Market Cap and the stock ticker symbol.
agent: >-
web_researcher
financials_performance:
description: >-
As of {timestamp}, use real-time web search with the timestamp to extract financial performance data for {company_name},
including Revenue (TTM), Net Income (TTM), Year-over-Year revenue growth, gross
margin, and recent quarterly trends. Include any earnings trends or management
commentary available.
expected_output: >-
A structured summary of financial metrics for {company_name}: Revenue (TTM), Net
Income (TTM), YoY Revenue Growth, Gross Margin, Quarterly Trends, and Earnings
Commentary.
agent: >-
web_researcher
competitive_benchmarking:
description: >-
As of {timestamp}, perform real-time web search with the timestamp to identify 3-5 peer companies in the same sector
as {company_name}. Extract and compare key metrics such as P/E ratio, revenue,
stock price, and market cap. Highlight any standout metrics where {company_name}
outperforms or underperforms.
expected_output: >-
A comparison table of {company_name} and 3-5 peers showing P/E, revenue, price,
and market cap. Highlight metrics where {company_name} stands out.
agent: >-
web_researcher
real_time_stock_snapshot:
description: >-
As of {timestamp}, convert {company_name} to its stock ticker symbol and retrieve a real-time stock
snapshot using Dappier’s stock market data tool with the timestamp. Include current price with %
daily change, volume, 52-week high/low, P/E ratio, EPS, dividend yield, and chart
data for 1D, 5D, 1M, YTD, and 1Y in the query.
expected_output: >-
A structured stock summary for {company_name}, including:
Price, % Daily Change, Volume, 52-Week High/Low, P/E Ratio, EPS, Dividend Yield,
and chart data for 1D, 5D, 1M, YTD, 1Y.
agent: >-
stock_insights_analyst
news_and_sentiment:
description: >-
As of {timestamp}, convert {company_name} to its stock ticker symbol and fetch a real-time financial
news stream using Dappier’s stock market data tool with the timestamp. Categorize the news by topic:
Earnings, Analyst Ratings, Market Moves, Partnerships, and Legal/Regulatory in the
query.
expected_output: >-
A categorized list of real-time financial news headlines
for {company_name}, organized by topic: Earnings, Analyst
Ratings, Market Moves, Partnerships, Legal/Regulatory in the query.
agent: >-
stock_insights_analyst
generate_investment_report:
description: >-
As of {timestamp}, compile a comprehensive, markdown-formatted investment report
for {company_name} by synthesizing the outputs of all prior tasks: company overview,
financial performance, competitive benchmarking, real-time stock snapshot, and
categorized financial news. Use the timestamp in all queries. Include a concise AI-generated company summary,
structured data tables, sentiment-tagged news, and a narrative insight section.
expected_output: >-
A markdown-formatted investment report containing:
1. Quick AI summary of {company_name} (e.g., "Apple is a global tech leader…")
2. Structured company profile: Industry, Sector, CEO, HQ, Employees, Market Cap
3. Financial performance metrics: Revenue (TTM), Net Income (TTM), YoY Growth, Gross Margin, Trends
4. Competitive benchmarking table: P/E, Revenue, Stock Price, Market Cap vs. 3–5 peers
5. Real-time stock snapshot: Price, % Change, Volume, 52W High/Low, P/E, EPS, Dividend, charts
6. Categorized news: Earnings, Analyst Ratings, Market Moves, Partnerships, Legal/Regulatory (with sentiment tags)
7. Final 3-part insight section:
- What's going on with {company_name}
- Why it matters
- Outlook (clearly marked as not financial advice)
agent: >-
report_analyst
output_file: reports/{company_name}_investment_report.md
create_directory: true
87 changes: 87 additions & 0 deletions examples/stock_market_research/src/crew.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
import agentstack

@CrewBase
class StockmarketresearchCrew():
"""stock_market_research crew"""

@agent
def web_researcher(self) -> Agent:
return Agent(
config=self.agents_config['web_researcher'],
tools = [
get_dappier_tool("real_time_web_search")
],
verbose=True,
)

@agent
def stock_insights_analyst(self) -> Agent:
return Agent(
config=self.agents_config['stock_insights_analyst'],
tools = [
get_dappier_tool("stock_market_data_search")
],
verbose=True,
)

@agent
def report_analyst(self) -> Agent:
return Agent(
config=self.agents_config['report_analyst'],
verbose=True,
)

@task
def company_overview(self) -> Task:
return Task(
config=self.tasks_config['company_overview'],
)

@task
def financials_performance(self) -> Task:
return Task(
config=self.tasks_config['financials_performance'],
)

@task
def competitive_benchmarking(self) -> Task:
return Task(
config=self.tasks_config['competitive_benchmarking'],
)

@task
def real_time_stock_snapshot(self) -> Task:
return Task(
config=self.tasks_config['real_time_stock_snapshot'],
)

@task
def news_and_sentiment(self) -> Task:
return Task(
config=self.tasks_config['news_and_sentiment'],
)

@task
def generate_investment_report(self) -> Task:
return Task(
config=self.tasks_config['generate_investment_report'],
)

@crew
def crew(self) -> Crew:
"""Creates the Test crew"""
return Crew(
agents=self.agents, # Automatically created by the @agent decorator
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
)


def get_dappier_tool(tool_name: str):
for tool in agentstack.tools["dappier"]:
if tool.name == tool_name:
return tool
return None
61 changes: 61 additions & 0 deletions examples/stock_market_research/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/usr/bin/env python
from datetime import datetime, timezone
import sys
from crew import StockmarketresearchCrew
import agentstack
import agentops

agentops.init(default_tags=agentstack.get_tags())

instance = StockmarketresearchCrew().crew()

def run():
"""
Run the agent.
"""
inputs = agentstack.get_inputs()
inputs["timestamp"] = datetime.now(timezone.utc).isoformat()

instance.kickoff(inputs=inputs)


def train():
"""
Train the crew for a given number of iterations.
"""
try:
instance.train(
n_iterations=int(sys.argv[1]),
filename=sys.argv[2],
inputs=agentstack.get_inputs(),
)
except Exception as e:
raise Exception(f"An error occurred while training the crew: {e}")


def replay():
"""
Replay the crew execution from a specific task.
"""
try:
instance.replay(task_id=sys.argv[1])
except Exception as e:
raise Exception(f"An error occurred while replaying the crew: {e}")


def test():
"""
Test the crew execution and returns the results.
"""
try:
instance.test(
n_iterations=int(sys.argv[1]),
openai_model_name=sys.argv[2],
inputs=agentstack.get_inputs(),
)
except Exception as e:
raise Exception(f"An error occurred while replaying the crew: {e}")


if __name__ == '__main__':
run()
2 changes: 2 additions & 0 deletions examples/stock_market_research/src/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

# tool import