Skip to content

Commit

Permalink
rebasing fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
gromdimon committed Dec 27, 2024
1 parent bb18c27 commit 5af9b4b
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 60 deletions.
12 changes: 3 additions & 9 deletions .env.dev
Original file line number Diff line number Diff line change
Expand Up @@ -19,33 +19,27 @@ MEMORY_VECTOR_SIZE=1536

AGENT_PERSONALITY=You are a financial analyst. You are given a news article and some context. You need to analyze the news and provide insights. You are very naive and trustful. You are very optimistic and believe in the future of humanity.
AGENT_GOAL=Your goal is to analyze the news and provide insights.
AGENT_REST_TIME=300

# === LLMs settings ===

LLM_PROVIDER=openai
PERPLEXITY_NEWS_PROMPT=Search for the latest cryptocurrency news: Neurobro
NEWS_CATEGORY_LIST=[Finance, Regulatory, Market capitalzation, Technical analysis, Price movements]

OPENAI_API_KEY=

# Perplexity
PERPLEXITY_API_KEY=
PERPLEXITY_ENDPOINT=https://api.perplexity.ai/chat/completions
PERPLEXITY_NEWS_PROMPT=Search for the latest cryptocurrency news: Neurobro
NEWS_CATEGORY_LIST=[Finance, Regulatory, Market capitalzation, Technical analysis, Price movements]

# Telegram
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
TELEGRAM_ADMIN_CHAT_ID=
TELEGRAM_REVIEWER_CHAT_IDS=[]

# Twitter
TWITTER_BEARER_TOKEN=
TWITTER_API_KEY=
TWITTER_API_SECRET_KEY=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=

# Agent
AGENT_PERSONALITY=
AGENT_GOAL=
AGENT_REST_TIME=
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: AA Core",
"type": "python",
"request": "launch",
"module": "src.main",
"console": "integratedTerminal",
"justMyCode": true,
"python": "${command:python.interpreterPath}",
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
}
]
}
1 change: 1 addition & 0 deletions src/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ async def _perform_planned_action(self, action_name: AgentAction) -> Optional[st

async def start_runtime_loop(self) -> None:
"""The main runtime loop for the agent."""
await analyze_signal()
logger.info("Starting the autonomous agent runtime loop...")
while True:
try:
Expand Down
43 changes: 16 additions & 27 deletions src/core/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import List

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
Expand Down Expand Up @@ -94,33 +95,6 @@ class Settings(BaseSettings):
# ==========================

# --- Telegram settings ---
#: Perplexity news settings
PERPLEXITY_NEWS_PROMPT: str = "Search for the latest cryptocurrency news: Neurobro"
PERPLEXITY_NEWS_CATEGORY_LIST: List[str] = [
"Finance",
"Regulatory",
"Market capitalzation",
"Technical analysis",
"Price movements",
]
# === LLMs settings ===

LLM_PROVIDER: str = "openai" # or "anthropic"

#: Anthropic
ANTHROPIC_API_KEY: str = ""
ANTHROPIC_MODEL: str = "claude-2"

#: OpenAI
OPENAI_API_KEY: str = ""
OPENAI_MODEL: str = "gpt-4o-mini"
OPENAI_EMBEDDING_MODEL: str = "text-embedding-3-small"

#: Perplexity
PERPLEXITY_API_KEY: str = ""
PERPLEXITY_ENDPOINT: str = ""

# === Telegram settings ===

#: Telegram bot token
TELEGRAM_BOT_TOKEN: str = ""
Expand Down Expand Up @@ -150,6 +124,21 @@ class Settings(BaseSettings):
#: Perplexity endpoint
PERPLEXITY_ENDPOINT: str = "https://api.perplexity.ai/chat/completions"

#: Perplexity news settings
PERPLEXITY_NEWS_PROMPT: str = "Search for the latest cryptocurrency news: Neurobro"
PERPLEXITY_NEWS_CATEGORY_LIST: List[str] = [
"Finance",
"Regulatory",
"Market capitalzation",
"Technical analysis",
"Price movements",
]

# --- Coinstats settings ---

#: Coinstats API key
COINSTATS_API_KEY: str = ""

# ==========================
# Validators
# ==========================
Expand Down
6 changes: 6 additions & 0 deletions src/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,9 @@ class APIError(AgentBaseError):
"""Exception raised when API request fails."""

pass


class CoinstatsError(AgentBaseError):
"""Exception raised when Coinstats API request fails."""

pass
75 changes: 55 additions & 20 deletions src/tools/get_signal.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,68 @@
from datetime import datetime, timedelta
from typing import Dict

import httpx
from loguru import logger

from src.core.config import settings
from src.tools.search_with_perplexity import search_with_perplexity
from src.core.exceptions import CoinstatsError

#: Coinstatst API
COINSTATS_BASE_URL = "https://openapiv1.coinstats.app"

#: Coinstats API headers
COINSTATS_HEADERS = {
"accept": "application/json",
"X-API-KEY": settings.COINSTATS_API_KEY,
}


async def get_coinstats_news() -> Dict[str, str]:
"""get news from coinstats api"""
logger.debug("RETRIEVING NEWS")
try:
now = datetime.now()
yesterday = now - timedelta(days=1)
url = (
f"{COINSTATS_BASE_URL}/news?limit=30&"
f"from={yesterday.strftime('%Y-%m-%d')}&"
f"to={now.strftime('%Y-%m-%d')}"
)

async with httpx.AsyncClient() as client:
response = await client.get(url, headers=COINSTATS_HEADERS)
response.raise_for_status()
data = response.json()

logger.debug(f"COINSTATS NEWS | SUCCESSFULLY RETRIEVED {len(data['result'])} ARTICLES")
return data
except Exception as e:
logger.error(f"ERROR RETRIEVING NEWS: {str(e)}")
raise CoinstatsError("News data currently unavailable")


async def fetch_signal() -> dict:
"""
Fetch a crypto signal from the coingecko API endpoint.
Fetch a crypto signal from the Coinstats API.
Returns:
dict: Parsed JSON response containing actionable crypto news or updates.
Format: {"status": str, "news": str}
- status: "new_data", "no_data", or "error"
- news: title of the latest news article if status is "new_data"
"""
api_url = "https://api.coingecko.com/api/v3/news"
try:
async with httpx.AsyncClient() as client:
response = await client.get(api_url)
if response.status_code == 200:
data = response.json()
logger.debug(f"Signal fetched: {data}")
return {"status": "new_data", "news": data[0]["title"]}
else:
logger.error(f"Failed to fetch signal. Status code: {response.status_code}")
return {"status": "no_data"}
except Exception as e:
logger.error(f"Error fetching signal from API: {e}")
data = await get_coinstats_news()
if data and data.get("result") and len(data["result"]) > 0:
latest_news = data["result"][0]
logger.debug(f"Signal fetched: {latest_news}")
signal = latest_news.get("title", None) # type: ignore
if not signal:
return {"status": "error"}
return {"status": "new_data", "news": signal}
else:
logger.error("No news data available in the response")
return {"status": "no_data"}
except CoinstatsError as e:
logger.error(f"Error fetching signal from Coinstats: {e}")
return {"status": "error"}
if data:
logger.info(f"Signal fetched: {data}")
return {"status": "new_data", "news": data}
else:
logger.info(f"No data available: {data}")
return {"status": "no_data"}
11 changes: 7 additions & 4 deletions src/tools/search_with_perplexity.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ async def search_with_perplexity(query: str) -> str:
"role": "system",
"content": (
"You are a capable and efficient search assistant. "
"Your job is to find relevant and concise information about cryptocurrencies "
"based on the query provided."
"Your job is to find relevant and concise information about "
"cryptocurrencies based on the query provided."
"Validate the results for relevance and clarity. "
"Return the results ONLY in the following string - dictionary format (include curly brackets): "
f'{{ "headline": "all news texts here ", "category": "choose relevant news category from {settings.PERPLEXITY_NEWS_CATEGORY_LIST} ", "timestamp": "..." }}'
"Return the results ONLY in the following string - dictionary format "
"(include curly brackets): "
f'{{ "headline": "all news texts here ", "category": "choose relevant news '
f'category from {settings.PERPLEXITY_NEWS_CATEGORY_LIST} ", "timestamp": '
f'"..." }}'
),
},
{
Expand Down

0 comments on commit 5af9b4b

Please sign in to comment.