Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

Add RPM support for Fedora/RHEL Linux distributions

tilakpatel225081971d3e0a
diff --git a/.github/workflows/build-artifacts.yml b/.github/workflows/build-artifacts.yml
index eafba14ad..0a1a58bf5 100644
--- a/.github/workflows/build-artifacts.yml
+++ b/.github/workflows/build-artifacts.yml
@@ -140,11 +140,12 @@ jobs:
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.dmg" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.dmg \; 2>/dev/null && echo "[OK] Found .dmg" || echo "[WARN] No .dmg found"
- elif [[ "${{ matrix.platform }}" == "ubuntu-22.04" ]]; then
+ elif [[ "${{ matrix.platform }}" == "ubuntu-20.04" ]]; then
# Linux builds
SUFFIX="Linux-x64"
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.AppImage" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.AppImage \; 2>/dev/null && echo "[OK] Found .AppImage" || echo "[WARN] No .AppImage found"
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.deb" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.deb \; 2>/dev/null && echo "[OK] Found .deb" || echo "[WARN] No .deb found"
+ find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.rpm" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.rpm \; 2>/dev/null && echo "[OK] Found .rpm" || echo "[WARN] No .rpm found"
elif [[ "${{ matrix.platform }}" == "windows-latest" ]]; then
# Windows builds
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.yml
index 09bfc6d79..56c424a43 100644
--- a/.github/workflows/release-production.yml
+++ b/.github/workflows/release-production.yml
@@ -147,11 +147,12 @@ jobs:
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.dmg" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.dmg \; 2>/dev/null && echo "[OK] Found .dmg" || echo "[WARN] No .dmg found"
- elif [[ "${{ matrix.platform }}" == "ubuntu-22.04" ]]; then
+ elif [[ "${{ matrix.platform }}" == "ubuntu-20.04" ]]; then
# Linux builds
SUFFIX="Linux-x64"
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.AppImage" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.AppImage \; 2>/dev/null && echo "[OK] Found .AppImage" || echo "[WARN] No .AppImage found"
find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.deb" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.deb \; 2>/dev/null && echo "[OK] Found .deb" || echo "[WARN] No .deb found"
+ find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.rpm" -exec cp {} release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.rpm \; 2>/dev/null && echo "[OK] Found .rpm" || echo "[WARN] No .rpm found"
elif [[ "${{ matrix.platform }}" == "windows-latest" ]]; then
# Windows builds
@@ -212,7 +213,7 @@ jobs:
mkdir -p release-files
# Move all files to release-files directory
- find all-artifacts -type f \( -name "*.dmg" -o -name "*.msi" -o -name "*.AppImage" -o -name "*.deb" \) -exec cp {} release-files/ \;
+ find all-artifacts -type f \( -name "*.dmg" -o -name "*.msi" -o -name "*.AppImage" -o -name "*.deb" -o -name "*.rpm" \) -exec cp {} release-files/ \;
# Also copy updater files (latest.json and .sig files)
find all-artifacts -type f \( -name "latest.json" -o -name "*.tar.gz" -o -name "*.tar.gz.sig" -o -name "*.zip" -o -name "*.zip.sig" \) -exec cp {} release-files/ \; 2>/dev/null || true
@@ -255,7 +256,8 @@ jobs:
### Linux
- **AppImage (Universal)**: Download \`FinceptTerminal-v${VERSION}-Linux-x64.AppImage\`
- - **Debian/Ubuntu**: Download \`FinceptTerminal-v${VERSION}-Linux-x64.deb\`
+ - **Debian/Ubuntu (.deb)**: Download \`FinceptTerminal-v${VERSION}-Linux-x64.deb\`
+ - **Fedora/RHEL (.rpm)**: Download \`FinceptTerminal-v${VERSION}-Linux-x64.rpm\`
### Windows
- **Windows Installer**: Download \`FinceptTerminal-v${VERSION}-Windows-x64.msi\`
@@ -328,7 +330,8 @@ jobs:
| **macOS** | Apple Silicon (ARM64) | [Download .dmg](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-macOS-arm64.dmg) |
| **macOS** | Intel (x64) | [Download .dmg](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-macOS-x64.dmg) |
| **Linux** | x64 (AppImage) | [Download .AppImage](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-Linux-x64.AppImage) |
- | **Linux** | x64 (Debian) | [Download .deb](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-Linux-x64.deb) |
+ | **Linux** | x64 (Debian/Ubuntu) | [Download .deb](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-Linux-x64.deb) |
+ | **Linux** | x64 (Fedora/RHEL) | [Download .rpm](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-Linux-x64.rpm) |
| **Windows** | x64 | [Download .msi](${REPO_URL}/releases/download/${TAG_NAME}/FinceptTerminal-v${VERSION}-Windows-x64.msi) |
> **One-Click Downloads** - These links will start downloading immediately - no GitHub login required.
diff --git a/fincept-terminal-desktop/dummy.txt b/fincept-terminal-desktop/dummy.txt
new file mode 100644
index 000000000..9daeafb98
--- /dev/null
+++ b/fincept-terminal-desktop/dummy.txt
@@ -0,0 +1 @@
+test
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/configs/agent_definitions.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/configs/agent_definitions.json
index 156abc39f..dc2989c1e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/configs/agent_definitions.json
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/configs/agent_definitions.json
@@ -1,86 +1,149 @@
{
- "version": "1.0.0",
- "last_updated": "2025-12-16",
- "category": "TraderInvestorsAgent",
- "description": "Famous investor persona agents following specific investment philosophies",
-
"agents": [
{
- "id": "warren_buffett_agent",
- "name": "Warren Buffett Investment Agent",
- "role": "Value investor following Warren Buffett's philosophy",
- "goal": "Identify wonderful companies at fair prices with durable competitive advantages",
+ "analysis_rules": {
+ "earnings_predictability": {
+ "consistent_profit_points": 3,
+ "growth_trend_points": 2,
+ "low_volatility_points": 2
+ },
+ "financial_strength": {
+ "high_liquidity_points": 2,
+ "low_debt_points": 3,
+ "positive_fcf_points": 2
+ },
+ "management_quality": {
+ "buyback_points": 2,
+ "rd_efficiency_points": 1,
+ "reinvestment_points": 2
+ },
+ "moat_analysis": {
+ "good_roe_points": 2,
+ "high_roe_points": 3,
+ "stable_margins_points": 2,
+ "steady_growth_points": 2
+ }
+ },
+ "data_sources": {
+ "financial_metrics": [
+ "ROE",
+ "D/E",
+ "Current Ratio"
+ ],
+ "line_items": [
+ "revenue",
+ "net_income",
+ "free_cash_flow",
+ "total_debt",
+ "shareholders_equity",
+ "retained_earnings",
+ "operating_margin",
+ "research_and_development",
+ "outstanding_shares"
+ ],
+ "period": "annual",
+ "required_api_keys": [
+ "FINANCIAL_DATASETS_API_KEY"
+ ],
+ "years_of_data": 10
+ },
+ "debug_mode": false,
"description": "Analyzes stocks through Buffett's framework: economic moats (high ROE, pricing power), predictable earnings, financial fortress (low debt), quality management (capital allocation), and reasonable valuation. Focuses on long-term business quality over short-term price movements.",
-
+ "enable_agentic_memory": true,
+ "enable_memory": true,
+ "goal": "Identify wonderful companies at fair prices with durable competitive advantages",
+ "id": "warren_buffett_agent",
+ "instructions": "You are Warren Buffett's AI investment agent. Follow his core philosophy:\n\n1. 'Buy wonderful companies at fair prices' - Seek businesses with durable competitive advantages\n2. Economic moats: High ROE (15%+ for 7+ years), pricing power, brand strength, network effects\n3. Predictable earnings: Consistent profitability over many years, low volatility\n4. Financial fortress: Low debt (D/E < 0.3), strong balance sheet, reliable cash flow\n5. Quality management: Efficient capital allocation, shareholder-friendly policies\n6. Long-term perspective: 'Our favorite holding period is forever'\n7. Circle of competence: Only invest in businesses you deeply understand\n\nReasoning style:\n- Focus on business fundamentals, not market movements\n- Emphasize competitive advantages and economic moats\n- Discuss management quality and capital allocation decisions\n- Value predictability over explosive growth\n- Use homespun analogies and simple explanations\n- Express high conviction for truly wonderful businesses\n- Be willing to say 'no' to businesses outside your circle of competence\n\nReturn your analysis with clear signal (bullish/neutral/bearish), confidence level, and detailed reasoning grounded in Buffett's principles.",
+ "knowledge_base": "buffett_philosophy",
"llm_config": {
- "provider": "openai",
+ "max_tokens": 3000,
"model_id": "gpt-4-turbo",
- "temperature": 0.6,
- "max_tokens": 3000
+ "provider": "openai",
+ "temperature": 0.6
},
-
- "tools": [
- "financial_metrics_tool",
- "stock_price_tool",
- "web_search"
- ],
-
- "knowledge_base": "buffett_philosophy",
- "enable_memory": true,
- "enable_agentic_memory": true,
-
- "instructions": "You are Warren Buffett's AI investment agent. Follow his core philosophy:\n\n1. 'Buy wonderful companies at fair prices' - Seek businesses with durable competitive advantages\n2. Economic moats: High ROE (15%+ for 7+ years), pricing power, brand strength, network effects\n3. Predictable earnings: Consistent profitability over many years, low volatility\n4. Financial fortress: Low debt (D/E < 0.3), strong balance sheet, reliable cash flow\n5. Quality management: Efficient capital allocation, shareholder-friendly policies\n6. Long-term perspective: 'Our favorite holding period is forever'\n7. Circle of competence: Only invest in businesses you deeply understand\n\nReasoning style:\n- Focus on business fundamentals, not market movements\n- Emphasize competitive advantages and economic moats\n- Discuss management quality and capital allocation decisions\n- Value predictability over explosive growth\n- Use homespun analogies and simple explanations\n- Express high conviction for truly wonderful businesses\n- Be willing to say 'no' to businesses outside your circle of competence\n\nReturn your analysis with clear signal (bullish/neutral/bearish), confidence level, and detailed reasoning grounded in Buffett's principles.",
-
+ "markdown": true,
+ "name": "Warren Buffett Investment Agent",
"output_schema": {
- "type": "InvestmentSignal",
"fields": {
- "signal": "bullish | bearish | neutral",
"confidence": "float (0-1)",
- "moat_score": "float (0-10)",
"earnings_predictability": "float (0-10)",
"financial_strength": "float (0-10)",
"management_quality": "float (0-10)",
- "valuation_score": "float (0-10)",
- "reasoning": "string"
- }
+ "moat_score": "float (0-10)",
+ "reasoning": "string",
+ "signal": "bullish | bearish | neutral",
+ "valuation_score": "float (0-10)"
+ },
+ "type": "InvestmentSignal"
},
-
- "ui_parameters": {
- "configurable": ["temperature", "tools", "llm_config.provider", "llm_config.model_id"],
- "display_fields": ["signal", "confidence", "moat_score", "reasoning"],
- "advanced_options": ["knowledge_base", "enable_agentic_memory", "output_schema"]
+ "role": "Value investor following Warren Buffett's philosophy expert",
+ "scoring_weights": {
+ "earnings_predictability": 0.25,
+ "financial_strength": 0.2,
+ "management_quality": 0.15,
+ "moat_analysis": 0.3,
+ "valuation": 0.1
},
-
"show_tool_calls": true,
- "markdown": true,
- "debug_mode": false
+ "thresholds": {
+ "bearish_score": 4,
+ "bullish_score": 8,
+ "current_ratio_min": 1.5,
+ "debt_to_equity_max": 0.3,
+ "margin_minimum": 0.15,
+ "margin_stability_max": 0.05,
+ "positive_earnings_years": 8,
+ "positive_fcf_years": 8,
+ "revenue_growth_max": 0.15,
+ "revenue_growth_min": 0.05,
+ "roe_excellence": 0.15,
+ "roe_years_required": 7
+ },
+ "tools": [
+ "financial_metrics_tool",
+ "stock_price_tool",
+ "web_search"
+ ],
+ "ui_parameters": {
+ "advanced_options": [
+ "knowledge_base",
+ "enable_agentic_memory",
+ "output_schema"
+ ],
+ "configurable": [
+ "temperature",
+ "tools",
+ "llm_config.provider",
+ "llm_config.model_id"
+ ],
+ "display_fields": [
+ "signal",
+ "confidence",
+ "moat_score",
+ "reasoning"
+ ]
+ }
},
-
{
"id": "benjamin_graham_agent",
"name": "Benjamin Graham Value Agent",
"role": "Deep value investor following Benjamin Graham's principles",
"goal": "Find undervalued stocks trading below intrinsic value with margin of safety",
"description": "Strict value investor focusing on quantitative metrics: P/E ratio, P/B ratio, working capital, asset value, and margin of safety. Emphasizes downside protection and statistical cheapness.",
-
"llm_config": {
"provider": "anthropic",
"model_id": "claude-3-sonnet-20240229",
"temperature": 0.5,
"max_tokens": 2500
},
-
"tools": [
"financial_metrics_tool",
"stock_price_tool"
],
-
"knowledge_base": "graham_value_investing",
"enable_memory": true,
"enable_agentic_memory": false,
-
"instructions": "You are Benjamin Graham's AI investment agent. Follow his strict value investing principles:\n\n1. Margin of Safety: Only buy when price is significantly below intrinsic value (30%+ discount)\n2. Quantitative Focus: P/E < 15, P/B < 1.5, Current Ratio > 2.0, Debt/Equity < 0.5\n3. Asset Protection: Focus on tangible book value and working capital\n4. Earnings Stability: Positive earnings in at least 7 of last 10 years\n5. Dividend Record: Uninterrupted dividends for 20+ years preferred\n6. Defensive Investor: Emphasize safety and downside protection over upside\n7. Statistical Analysis: Rely on numbers, not narratives or market sentiment\n\nReasoning style:\n- Be highly conservative and risk-averse\n- Focus on quantitative metrics and hard numbers\n- Emphasize downside protection and margin of safety\n- Prefer boring, stable businesses over exciting growth stories\n- Use precise calculations and mathematical reasoning\n- Be willing to wait years for the right price\n- Reject speculative investments decisively\n\nReturn signal only when strict quantitative criteria are met.",
-
"output_schema": {
"type": "InvestmentSignal",
"fields": {
@@ -93,44 +156,47 @@
"reasoning": "string"
}
},
-
"ui_parameters": {
- "configurable": ["temperature", "llm_config.provider"],
- "display_fields": ["signal", "confidence", "intrinsic_value", "margin_of_safety", "reasoning"],
- "advanced_options": ["enable_agentic_memory"]
+ "configurable": [
+ "temperature",
+ "llm_config.provider"
+ ],
+ "display_fields": [
+ "signal",
+ "confidence",
+ "intrinsic_value",
+ "margin_of_safety",
+ "reasoning"
+ ],
+ "advanced_options": [
+ "enable_agentic_memory"
+ ]
},
-
"show_tool_calls": true,
"markdown": true,
"debug_mode": false
},
-
{
"id": "peter_lynch_agent",
"name": "Peter Lynch Growth Agent",
"role": "Growth investor following Peter Lynch's philosophy",
"goal": "Find undiscovered growth stocks with strong fundamentals and reasonable valuations",
"description": "Growth at a reasonable price (GARP) investor. Focuses on PEG ratio, earnings growth, competitive position, and understandable businesses. Prefers finding multi-baggers in everyday life.",
-
"llm_config": {
"provider": "google",
"model_id": "gemini-1.5-pro-latest",
"temperature": 0.7,
"max_tokens": 3500
},
-
"tools": [
"financial_metrics_tool",
"stock_price_tool",
"web_search"
],
-
"knowledge_base": "lynch_garp_investing",
"enable_memory": true,
"enable_agentic_memory": true,
-
"instructions": "You are Peter Lynch's AI investment agent. Follow his GARP (Growth At Reasonable Price) philosophy:\n\n1. PEG Ratio: Look for PEG < 1.0 (P/E ratio divided by growth rate)\n2. Earnings Growth: Target 15-25% annual earnings growth\n3. Invest in What You Know: Favor businesses you can understand from everyday life\n4. Story Types: Classify as slow grower, stalwart, fast grower, cyclical, turnaround, or asset play\n5. Competitive Position: Strong market position in growing industry\n6. Balance Sheet: Reasonable debt, positive cash flow\n7. Insider Buying: Management buying shares is a good sign\n8. P/E Relative to Growth: P/E should not exceed growth rate significantly\n\nReasoning style:\n- Use relatable, everyday examples and analogies\n- Classify stocks by Lynch's six categories\n- Focus on earnings growth sustainability\n- Look for overlooked opportunities in boring industries\n- Consider the 'story' but verify with numbers\n- Emphasize PEG ratio as key metric\n- Be enthusiastic about genuine growth opportunities\n\nReturn analysis with clear growth classification and PEG-based valuation.",
-
"output_schema": {
"type": "InvestmentSignal",
"fields": {
@@ -143,28 +209,28 @@
"reasoning": "string"
}
},
-
"ui_parameters": {
- "configurable": ["temperature", "tools", "llm_config.provider", "llm_config.model_id"],
- "display_fields": ["signal", "confidence", "peg_ratio", "lynch_category", "reasoning"],
- "advanced_options": ["knowledge_base", "enable_agentic_memory"]
+ "configurable": [
+ "temperature",
+ "tools",
+ "llm_config.provider",
+ "llm_config.model_id"
+ ],
+ "display_fields": [
+ "signal",
+ "confidence",
+ "peg_ratio",
+ "lynch_category",
+ "reasoning"
+ ],
+ "advanced_options": [
+ "knowledge_base",
+ "enable_agentic_memory"
+ ]
},
-
"show_tool_calls": true,
"markdown": true,
"debug_mode": false
}
- ],
-
- "default_provider": "openai",
- "default_model": "gpt-4-turbo",
- "default_temperature": 0.7,
-
- "shared_tools": [
- "financial_metrics_tool",
- "stock_price_tool",
- "web_search"
- ],
-
- "notes": "These agents represent famous investor philosophies. Each agent should be used according to your investment style and the specific stock being analyzed. Warren Buffett for quality businesses, Benjamin Graham for deep value, Peter Lynch for growth at reasonable prices."
-}
+ ]
+}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py
new file mode 100644
index 000000000..74945487e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/TraderInvestorsAgent/warren_buffett_agent_v2.py
@@ -0,0 +1,295 @@
+"""
+Warren Buffett Agent - JSON-Driven Configuration
+Version 2.0 - Uses finagent_core and JSON config files
+
+User can customize via JSON:
+- Scoring weights
+- Thresholds
+- Data sources
+- Analysis rules
+"""
+
+import json
+import sys
+from pathlib import Path
+from typing import Dict, Any, List
+
+# Add parent directory to path
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from finagent_core.base_agent import AgentRegistry
+
+
+class WarrenBuffettAgent:
+ """JSON-driven Warren Buffett investment analysis agent"""
+
+ def __init__(self, config_path: Path = None):
+ if config_path is None:
+ config_path = Path(__file__).parent / "configs" / "agent_definitions.json"
+
+ registry = AgentRegistry(config_path)
+ self.config = registry.get_agent("warren_buffett_agent")
+
+ if not self.config:
+ raise ValueError("Warren Buffett agent config not found")
+
+ # Extract configuration sections
+ self.weights = self.config._raw_config.get("scoring_weights", {})
+ self.thresholds = self.config._raw_config.get("thresholds", {})
+ self.rules = self.config._raw_config.get("analysis_rules", {})
+ self.data_sources = self.config._raw_config.get("data_sources", {})
+
+ def analyze(self, tickers: List[str], end_date: str, api_key: str = None) -> Dict:
+ """
+ Analyze stocks using Buffett's methodology with JSON-driven parameters
+
+ Args:
+ tickers: List of stock symbols
+ end_date: Analysis end date
+ api_key: Financial datasets API key
+
+ Returns:
+ Dictionary of analysis results per ticker
+ """
+ results = {}
+
+ for ticker in tickers:
+ try:
+ # Fetch data based on JSON config
+ metrics = self._fetch_financial_metrics(ticker, end_date, api_key)
+ line_items = self._fetch_line_items(ticker, end_date, api_key)
+ market_cap = self._fetch_market_cap(ticker, end_date, api_key)
+
+ # Run analyses with JSON-configured parameters
+ moat_score = self._analyze_economic_moat(metrics, line_items)
+ earnings_score = self._analyze_earnings_predictability(line_items)
+ strength_score = self._analyze_financial_strength(metrics, line_items)
+ management_score = self._analyze_management_quality(line_items)
+ valuation_score = self._analyze_valuation(line_items, market_cap)
+
+ # Calculate total score using JSON weights
+ total_score = (
+ moat_score["score"] * self.weights.get("moat_analysis", 0.3) +
+ earnings_score["score"] * self.weights.get("earnings_predictability", 0.25) +
+ strength_score["score"] * self.weights.get("financial_strength", 0.2) +
+ management_score["score"] * self.weights.get("management_quality", 0.15) +
+ valuation_score["score"] * self.weights.get("valuation", 0.1)
+ )
+
+ # Determine signal using JSON thresholds
+ if total_score >= self.thresholds.get("bullish_score", 8.0):
+ signal = "bullish"
+ elif total_score <= self.thresholds.get("bearish_score", 4.0):
+ signal = "bearish"
+ else:
+ signal = "neutral"
+
+ results[ticker] = {
+ "signal": signal,
+ "total_score": total_score,
+ "moat_analysis": moat_score,
+ "earnings_predictability": earnings_score,
+ "financial_strength": strength_score,
+ "management_quality": management_score,
+ "valuation_analysis": valuation_score,
+ "configuration_used": {
+ "weights": self.weights,
+ "thresholds": self.thresholds
+ }
+ }
+
+ except Exception as e:
+ results[ticker] = {
+ "signal": "error",
+ "error": str(e)
+ }
+
+ return results
+
+ def _analyze_economic_moat(self, metrics: List, line_items: List) -> Dict:
+ """Analyze economic moat using JSON-configured rules"""
+ score = 0
+ details = []
+
+ if not metrics:
+ return {"score": 0, "details": "No metrics data"}
+
+ # Get thresholds from JSON
+ roe_threshold = self.thresholds.get("roe_excellence", 0.15)
+ roe_years = self.thresholds.get("roe_years_required", 7)
+ margin_stability = self.thresholds.get("margin_stability_max", 0.05)
+ margin_min = self.thresholds.get("margin_minimum", 0.15)
+
+ # Get points from JSON rules
+ moat_rules = self.rules.get("moat_analysis", {})
+ high_roe_points = moat_rules.get("high_roe_points", 3)
+ good_roe_points = moat_rules.get("good_roe_points", 2)
+ stable_margins_points = moat_rules.get("stable_margins_points", 2)
+ steady_growth_points = moat_rules.get("steady_growth_points", 2)
+
+ # High ROE analysis (JSON-configured)
+ roe_vals = [m.get("return_on_equity") for m in metrics if m.get("return_on_equity")]
+ if roe_vals:
+ high_roe_count = sum(1 for roe in roe_vals if roe > roe_threshold)
+ if high_roe_count >= roe_years:
+ score += high_roe_points
+ details.append(f"Exceptional ROE: {high_roe_count}/10 years >{roe_threshold:.0%}")
+ elif high_roe_count >= 5:
+ score += good_roe_points
+ details.append(f"Good ROE: {high_roe_count}/10 years >{roe_threshold:.0%}")
+
+ # Margin stability (JSON-configured)
+ margins = [item.get("operating_margin") for item in line_items if item.get("operating_margin")]
+ if margins and len(margins) >= 5:
+ margin_vol = max(margins) - min(margins)
+ avg_margin = sum(margins) / len(margins)
+ if margin_vol < margin_stability and avg_margin > margin_min:
+ score += stable_margins_points
+ details.append(f"Stable margins: {avg_margin:.1%} avg")
+
+ # Revenue growth (JSON-configured)
+ revenues = [item.get("revenue") for item in line_items if item.get("revenue")]
+ if len(revenues) >= 5:
+ growth_min = self.thresholds.get("revenue_growth_min", 0.05)
+ growth_max = self.thresholds.get("revenue_growth_max", 0.15)
+ cagr = (revenues[0] / revenues[-1]) ** (1 / len(revenues)) - 1
+ if growth_min <= cagr <= growth_max:
+ score += steady_growth_points
+ details.append(f"Steady growth: {cagr:.1%} CAGR")
+
+ return {"score": score, "details": "; ".join(details)}
+
+ def _analyze_earnings_predictability(self, line_items: List) -> Dict:
+ """Analyze earnings predictability using JSON config"""
+ score = 0
+ details = []
+
+ earnings = [item.get("net_income") for item in line_items if item.get("net_income")]
+ if len(earnings) < 5:
+ return {"score": 0, "details": "Insufficient data"}
+
+ rules = self.rules.get("earnings_predictability", {})
+ years_required = self.thresholds.get("positive_earnings_years", 8)
+
+ # Consistent profitability
+ positive_years = sum(1 for e in earnings if e > 0)
+ if positive_years >= years_required:
+ score += rules.get("consistent_profit_points", 3)
+ details.append(f"Consistent: {positive_years}/10 years profitable")
+
+ # Growth trend
+ if len(earnings) >= 10:
+ recent_avg = sum(earnings[:5]) / 5
+ older_avg = sum(earnings[5:10]) / 5
+ if recent_avg > older_avg * 1.5:
+ score += rules.get("growth_trend_points", 2)
+ details.append("Strong growth trend")
+
+ # Low volatility
+ if earnings:
+ volatility = (max(earnings) - min(earnings)) / max(abs(max(earnings)), abs(min(earnings)))
+ if volatility < 1.0:
+ score += rules.get("low_volatility_points", 2)
+ details.append(f"Low volatility: {volatility:.2f}")
+
+ return {"score": score, "details": "; ".join(details)}
+
+ def _analyze_financial_strength(self, metrics: List, line_items: List) -> Dict:
+ """Analyze financial strength using JSON config"""
+ score = 0
+ details = []
+
+ if not metrics or not line_items:
+ return {"score": 0, "details": "No data"}
+
+ latest = metrics[0] if metrics else {}
+ rules = self.rules.get("financial_strength", {})
+
+ # Low debt (JSON-configured)
+ de_max = self.thresholds.get("debt_to_equity_max", 0.3)
+ if latest.get("debt_to_equity") and latest["debt_to_equity"] < de_max:
+ score += rules.get("low_debt_points", 3)
+ details.append(f"Low debt: {latest['debt_to_equity']:.2f} D/E")
+
+ # High liquidity (JSON-configured)
+ cr_min = self.thresholds.get("current_ratio_min", 1.5)
+ if latest.get("current_ratio") and latest["current_ratio"] > cr_min:
+ score += rules.get("high_liquidity_points", 2)
+ details.append(f"Strong liquidity: {latest['current_ratio']:.1f}")
+
+ # Positive FCF (JSON-configured)
+ fcf_vals = [item.get("free_cash_flow") for item in line_items if item.get("free_cash_flow")]
+ fcf_years = self.thresholds.get("positive_fcf_years", 8)
+ if fcf_vals:
+ positive_fcf = sum(1 for fcf in fcf_vals if fcf > 0)
+ if positive_fcf >= fcf_years:
+ score += rules.get("positive_fcf_points", 2)
+ details.append(f"Reliable FCF: {positive_fcf}/10 years")
+
+ return {"score": score, "details": "; ".join(details)}
+
+ def _analyze_management_quality(self, line_items: List) -> Dict:
+ """Analyze management quality using JSON config"""
+ score = 0
+ details = []
+
+ rules = self.rules.get("management_quality", {})
+
+ # Share buybacks
+ shares = [item.get("outstanding_shares") for item in line_items if item.get("outstanding_shares")]
+ if len(shares) >= 5:
+ reduction = (shares[-1] - shares[0]) / shares[-1]
+ if reduction > 0.1:
+ score += rules.get("buyback_points", 2)
+ details.append(f"Buybacks: {reduction:.1%} reduction")
+
+ # Retained earnings growth
+ re_vals = [item.get("retained_earnings") for item in line_items if item.get("retained_earnings")]
+ if len(re_vals) >= 5:
+ re_growth = (re_vals[0] - re_vals[-1]) / abs(re_vals[-1])
+ if re_growth > 0.5:
+ score += rules.get("reinvestment_points", 2)
+ details.append(f"Reinvestment: {re_growth:.1%} RE growth")
+
+ return {"score": score, "details": "; ".join(details)}
+
+ def _analyze_valuation(self, line_items: List, market_cap: float) -> Dict:
+ """Placeholder for valuation analysis"""
+ # User can add custom valuation logic
+ return {"score": 5.0, "details": "Valuation analysis placeholder"}
+
+ def _fetch_financial_metrics(self, ticker: str, end_date: str, api_key: str) -> List[Dict]:
+ """Fetch metrics - placeholder for API integration"""
+ # TODO: Integrate with actual financial API
+ return []
+
+ def _fetch_line_items(self, ticker: str, end_date: str, api_key: str) -> List[Dict]:
+ """Fetch line items - placeholder for API integration"""
+ # TODO: Integrate with actual financial API
+ return []
+
+ def _fetch_market_cap(self, ticker: str, end_date: str, api_key: str) -> float:
+ """Fetch market cap - placeholder for API integration"""
+ # TODO: Integrate with actual financial API
+ return 0.0
+
+
+def main():
+ """CLI entry point for testing"""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Warren Buffett Agent - JSON Configured")
+ parser.add_argument("--tickers", nargs="+", required=True, help="Stock tickers")
+ parser.add_argument("--end-date", default="2024-12-31", help="Analysis end date")
+ parser.add_argument("--api-key", help="Financial datasets API key")
+
+ args = parser.parse_args()
+
+ agent = WarrenBuffettAgent()
+ results = agent.analyze(args.tickers, args.end_date, args.api_key)
+
+ print(json.dumps(results, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py
index fe7fadb7b..7265ec675 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py
@@ -1,35 +1,14 @@
"""
-Agno Core - Base Infrastructure for Fincept Terminal Agents
-
-This module provides the foundational infrastructure for all agents in the
-Fincept Terminal, replacing the old LangGraph-based system with the production-ready
-Agno framework.
-
-Key Features:
-- Multi-LLM provider support (OpenAI, Anthropic, Google, Ollama, etc.)
-- Dynamic JSON-based agent configuration
-- Persistent memory and session management
-- Team collaboration and delegation
-- RAG knowledge integration
-- Production-ready AgentOS deployment
+FinAgent Core - Simplified agent configuration system
"""
__version__ = "1.0.0"
__author__ = "Fincept Terminal"
-# Export main classes for easy imports
-from finagent_core.config.llm_providers import LLMProviderManager
-from finagent_core.base_agent import AgentConfig, ConfigurableAgent, AgentRegistry
-from finagent_core.tools.tool_registry import ToolRegistry
-from finagent_core.database.db_manager import DatabaseManager
-from finagent_core.utils.path_resolver import PathResolver
+from finagent_core.base_agent import AgentConfig, AgentRegistry, ConfigurableAgent
__all__ = [
- "LLMProviderManager",
"AgentConfig",
- "ConfigurableAgent",
"AgentRegistry",
- "ToolRegistry",
- "DatabaseManager",
- "PathResolver",
+ "ConfigurableAgent",
]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/base_agent.py
index 75a019fe0..6f1f788de 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/base_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/base_agent.py
@@ -1,498 +1,86 @@
"""
-Base Agent - Core configurable agent class for all Fincept Terminal agents
-
-This module provides the foundational ConfigurableAgent class that replaces
-all static agent implementations. All agents (geopolitics, investors, economic, etc.)
-will extend or use this class.
+Base Agent Module - Simplified JSON-based agent configuration loader
+No external dependencies - just loads and manages agent configs
"""
import json
-from typing import Dict, Any, List, Optional, Union
from pathlib import Path
-from pydantic import BaseModel, Field
-from agno.agent import Agent
-from agno.run import RunResponse
-
-from finagent_core.config.llm_providers import LLMProviderManager
-from finagent_core.tools.tool_registry import ToolRegistry, get_tool_registry
-from finagent_core.database.db_manager import DatabaseManager
-from finagent_core.utils.logger import get_logger
-from finagent_core.utils.path_resolver import PathResolver
-
-logger = get_logger(__name__)
-
-
-class AgentConfig(BaseModel):
- """
- Configuration for an Agno-based agent
-
- This model defines all configurable parameters for agents,
- making them fully customizable via JSON configuration files.
- """
-
- id: str = Field(..., description="Unique agent identifier")
- name: str = Field(..., description="Human-readable agent name")
- role: str = Field(..., description="Agent's role/specialty")
- goal: str = Field(..., description="Agent's primary goal")
- description: str = Field(..., description="Detailed agent description")
-
- # LLM Configuration
- llm_config: Dict[str, Any] = Field(
- ...,
- description="LLM configuration (provider, model_id, temperature, max_tokens)"
- )
-
- # Tools and Capabilities
- tools: List[str] = Field(
- default_factory=list,
- description="List of tool names this agent can use"
- )
-
- knowledge_base: Optional[str] = Field(
- None,
- description="Knowledge base identifier for RAG"
- )
-
- # Memory Configuration
- enable_memory: bool = Field(
- True,
- description="Enable persistent memory across sessions"
- )
-
- enable_agentic_memory: bool = Field(
- False,
- description="Enable agent-controlled memory decisions"
- )
-
- # Agent Behavior
- instructions: str = Field(
- ...,
- description="Detailed instructions for agent behavior"
- )
-
- output_schema: Optional[Dict[str, Any]] = Field(
- None,
- description="Expected output schema (Pydantic model definition)"
- )
-
- # UI Configuration
- ui_parameters: Optional[Dict[str, Any]] = Field(
- None,
- description="UI-specific configuration for frontend display"
- )
-
- # Additional Settings
- show_tool_calls: bool = Field(True, description="Display tool calls")
- markdown: bool = Field(True, description="Enable markdown formatting")
- debug_mode: bool = Field(False, description="Enable debug logging")
-
- class Config:
- json_schema_extra = {
- "example": {
- "id": "warren_buffett_agent",
- "name": "Warren Buffett Investment Agent",
- "role": "Value investor following Warren Buffett's philosophy",
- "goal": "Identify wonderful companies at fair prices",
- "description": "Analyzes stocks through Buffett's framework",
- "llm_config": {
- "provider": "openai",
- "model_id": "gpt-4-turbo",
- "temperature": 0.6,
- "max_tokens": 3000
- },
- "tools": ["financial_metrics_tool", "stock_price_tool"],
- "enable_memory": True,
- "instructions": "Analyze stocks using Buffett's criteria..."
- }
- }
-
-
-class ConfigurableAgent:
- """
- Base configurable agent class for all Fincept Terminal agents
+from typing import Dict, Any, List, Optional
- This class wraps Agno's Agent with Fincept-specific functionality,
- making it easy to create and configure agents dynamically.
- Usage:
- config = AgentConfig(...)
- agent = ConfigurableAgent(config)
- response = agent.run("Analyze AAPL stock")
- """
+class AgentConfig:
+ """Simple agent configuration container"""
+ def __init__(self, config_dict: Dict[str, Any]):
+ self.id = config_dict.get('id', '')
+ self.name = config_dict.get('name', '')
+ self.role = config_dict.get('role', '')
+ self.goal = config_dict.get('goal', '')
+ self.description = config_dict.get('description', '')
+ self.llm_config = config_dict.get('llm_config', {})
+ self.tools = config_dict.get('tools', [])
+ self.enable_memory = config_dict.get('enable_memory', False)
+ self.enable_agentic_memory = config_dict.get('enable_agentic_memory', False)
+ self.instructions = config_dict.get('instructions', '')
+ self._raw_config = config_dict
- def __init__(
- self,
- config: Union[AgentConfig, Dict[str, Any]],
- llm_provider_manager: Optional[LLMProviderManager] = None,
- tool_registry: Optional[ToolRegistry] = None,
- db_manager: Optional[DatabaseManager] = None,
- path_resolver: Optional[PathResolver] = None,
- api_keys: Optional[Dict[str, str]] = None
- ):
- """
- Initialize configurable agent
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary"""
+ return self._raw_config
- Args:
- config: Agent configuration (AgentConfig or dict)
- llm_provider_manager: LLM provider manager (uses default if None)
- tool_registry: Tool registry (uses global if None)
- db_manager: Database manager (creates default if None)
- path_resolver: Path resolver (creates default if None)
- api_keys: API keys for LLM providers
- """
- # Convert dict to AgentConfig if needed
- if isinstance(config, dict):
- config = AgentConfig(**config)
- self.config = config
- self.api_keys = api_keys or {}
-
- # Initialize managers
- self.llm_provider_manager = llm_provider_manager or LLMProviderManager()
- self.tool_registry = tool_registry or get_tool_registry()
- self.db_manager = db_manager or DatabaseManager()
- self.path_resolver = path_resolver or PathResolver()
-
- # Set up logger
- self.logger = get_logger(f"Agent.{config.id}")
- self.logger.info(f"Initializing agent: {config.name}")
-
- # Create Agno agent
- self.agent = self._create_agent()
-
- self.logger.info(f"Agent initialized: {config.id}")
-
- def _create_agent(self) -> Agent:
- """Create Agno Agent instance from configuration"""
-
- # Get LLM model
- llm_cfg = self.config.llm_config
- api_key = self.api_keys.get(f"{llm_cfg['provider'].upper()}_API_KEY")
-
- model = self.llm_provider_manager.get_model(
- provider=llm_cfg["provider"],
- model_id=llm_cfg["model_id"],
- api_key=api_key,
- temperature=llm_cfg.get("temperature", 0.7),
- max_tokens=llm_cfg.get("max_tokens", 4096)
- )
-
- # Get tools
- tools = self.tool_registry.get_tools(self.config.tools)
-
- # Get database
- db = self.db_manager.get_database()
-
- # TODO: Get knowledge base (implement when knowledge system is added)
- knowledge = None
-
- # Create Agent
- agent = Agent(
- id=self.config.id,
- name=self.config.name,
- role=self.config.role,
- model=model,
- tools=tools,
- knowledge=knowledge,
- instructions=self.config.instructions,
- enable_user_memories=self.config.enable_memory,
- enable_agentic_memory=self.config.enable_agentic_memory,
- db=db,
- markdown=self.config.markdown,
- show_tool_calls=self.config.show_tool_calls,
- debug_mode=self.config.debug_mode
- )
-
- return agent
-
- def run(
- self,
- query: str,
- user_id: Optional[str] = None,
- session_id: Optional[str] = None,
- stream: bool = False,
- **kwargs
- ) -> RunResponse:
- """
- Execute agent with query
+class AgentRegistry:
+ """Registry for loading and managing agent configurations"""
- Args:
- query: User query/message
- user_id: Optional user identifier
- session_id: Optional session identifier
- stream: Enable streaming responses
- **kwargs: Additional parameters
+ def __init__(self, config_path: Optional[Path] = None):
+ self.config_path = config_path
+ self.agents: Dict[str, AgentConfig] = {}
- Returns:
- RunResponse object with agent output
- """
- self.logger.info(f"Running agent {self.config.id} with query: {query[:100]}...")
+ if config_path and config_path.exists():
+ self.load_configs_from_json(config_path)
+ def load_configs_from_json(self, json_path: Path) -> None:
+ """Load agent configurations from JSON file"""
try:
- response = self.agent.run(
- message=query,
- user_id=user_id,
- session_id=session_id,
- stream=stream,
- **kwargs
- )
+ with open(json_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
- self.logger.info(f"Agent {self.config.id} completed successfully")
- return response
+ agents_list = data.get('agents', [])
+ for agent_dict in agents_list:
+ agent_config = AgentConfig(agent_dict)
+ self.agents[agent_config.id] = agent_config
except Exception as e:
- self.logger.error(f"Error running agent {self.config.id}: {e}", exc_info=True)
- raise
+ print(f"Error loading agent configs from {json_path}: {e}")
- async def arun(
- self,
- query: str,
- user_id: Optional[str] = None,
- session_id: Optional[str] = None,
- stream: bool = False,
- **kwargs
- ) -> RunResponse:
- """
- Execute agent asynchronously
+ def get_agent(self, agent_id: str) -> Optional[AgentConfig]:
+ """Get agent configuration by ID"""
+ return self.agents.get(agent_id)
- Args:
- query: User query/message
- user_id: Optional user identifier
- session_id: Optional session identifier
- stream: Enable streaming responses
- **kwargs: Additional parameters
+ def list_agents(self) -> List[AgentConfig]:
+ """List all registered agents"""
+ return list(self.agents.values())
- Returns:
- RunResponse object with agent output
- """
- self.logger.info(f"Running async agent {self.config.id} with query: {query[:100]}...")
+ def update_agent_config(self, agent_id: str, updates: Dict[str, Any]) -> bool:
+ """Update agent configuration"""
+ if agent_id in self.agents:
+ self.agents[agent_id] = AgentConfig(updates)
+ return True
+ return False
+ def save_configs_to_json(self, json_path: Path) -> bool:
+ """Save all agent configurations back to JSON file"""
try:
- response = await self.agent.arun(
- message=query,
- user_id=user_id,
- session_id=session_id,
- stream=stream,
- **kwargs
- )
+ agents_list = [agent.to_dict() for agent in self.agents.values()]
+ data = {'agents': agents_list}
- self.logger.info(f"Async agent {self.config.id} completed successfully")
- return response
+ with open(json_path, 'w', encoding='utf-8') as f:
+ json.dump(data, f, indent=2)
+ return True
except Exception as e:
- self.logger.error(f"Error running async agent {self.config.id}: {e}", exc_info=True)
- raise
-
- def get_config(self) -> Dict[str, Any]:
- """
- Get agent configuration as dictionary (for UI)
-
- Returns:
- Configuration dictionary
- """
- return self.config.model_dump()
-
- def update_config(self, updates: Dict[str, Any]):
- """
- Update agent configuration dynamically
-
- Args:
- updates: Dictionary of configuration updates
- """
- for key, value in updates.items():
- if hasattr(self.config, key):
- setattr(self.config, key, value)
- self.logger.info(f"Updated config {key} = {value}")
-
- # Recreate agent with new configuration
- self.agent = self._create_agent()
- self.logger.info(f"Agent {self.config.id} reconfigured")
-
- def get_session_history(self, session_id: str) -> List[Dict[str, Any]]:
- """
- Get conversation history for a session
-
- Args:
- session_id: Session identifier
-
- Returns:
- List of messages in session
- """
- # TODO: Implement session history retrieval
- self.logger.warning("Session history retrieval not yet implemented")
- return []
-
- def get_memory(self, user_id: str) -> List[Dict[str, Any]]:
- """
- Get memories for a user
-
- Args:
- user_id: User identifier
-
- Returns:
- List of user memories
- """
- # TODO: Implement memory retrieval
- self.logger.warning("Memory retrieval not yet implemented")
- return []
-
-
-class AgentRegistry:
- """
- Registry for managing multiple agents
-
- This class loads agent configurations from JSON files and
- creates agent instances on demand.
- """
-
- def __init__(
- self,
- base_path: Optional[Path] = None,
- llm_provider_manager: Optional[LLMProviderManager] = None,
- tool_registry: Optional[ToolRegistry] = None,
- db_manager: Optional[DatabaseManager] = None
- ):
- """
- Initialize agent registry
-
- Args:
- base_path: Base path for agent configurations
- llm_provider_manager: LLM provider manager
- tool_registry: Tool registry
- db_manager: Database manager
- """
- self.path_resolver = PathResolver(base_path=base_path)
- self.llm_provider_manager = llm_provider_manager or LLMProviderManager()
- self.tool_registry = tool_registry or get_tool_registry()
- self.db_manager = db_manager or DatabaseManager()
-
- self._agents: Dict[str, ConfigurableAgent] = {}
- self._configs: Dict[str, AgentConfig] = {}
-
- self.logger = get_logger("AgentRegistry")
-
- def load_configs_from_json(self, json_path: Path) -> List[AgentConfig]:
- """
- Load agent configurations from JSON file
-
- Args:
- json_path: Path to JSON configuration file
-
- Returns:
- List of AgentConfig objects
- """
- self.logger.info(f"Loading agent configs from: {json_path}")
-
- with open(json_path, 'r', encoding='utf-8') as f:
- data = json.load(f)
-
- configs = []
- for agent_data in data.get("agents", []):
- try:
- config = AgentConfig(**agent_data)
- configs.append(config)
- self._configs[config.id] = config
- self.logger.info(f"Loaded config for agent: {config.id}")
- except Exception as e:
- self.logger.error(f"Error loading agent config: {e}")
-
- return configs
-
- def get_agent(
- self,
- agent_id: str,
- api_keys: Optional[Dict[str, str]] = None,
- force_reload: bool = False
- ) -> ConfigurableAgent:
- """
- Get agent instance by ID
-
- Args:
- agent_id: Agent identifier
- api_keys: API keys for LLM providers
- force_reload: Force recreation of agent
-
- Returns:
- ConfigurableAgent instance
- """
- # Return cached agent if exists and not forcing reload
- if agent_id in self._agents and not force_reload:
- return self._agents[agent_id]
-
- # Get configuration
- if agent_id not in self._configs:
- raise ValueError(f"Agent configuration not found: {agent_id}")
-
- config = self._configs[agent_id]
-
- # Create agent
- agent = ConfigurableAgent(
- config=config,
- llm_provider_manager=self.llm_provider_manager,
- tool_registry=self.tool_registry,
- db_manager=self.db_manager,
- path_resolver=self.path_resolver,
- api_keys=api_keys
- )
-
- # Cache agent
- self._agents[agent_id] = agent
-
- return agent
-
- def list_agents(self) -> List[Dict[str, Any]]:
- """
- List all available agents
-
- Returns:
- List of agent info dictionaries
- """
- return [
- {
- "id": config.id,
- "name": config.name,
- "role": config.role,
- "description": config.description,
- "tools": config.tools,
- "provider": config.llm_config["provider"],
- "model": config.llm_config["model_id"]
- }
- for config in self._configs.values()
- ]
-
- def get_config(self, agent_id: str) -> Dict[str, Any]:
- """
- Get agent configuration
-
- Args:
- agent_id: Agent identifier
-
- Returns:
- Configuration dictionary
- """
- if agent_id not in self._configs:
- raise ValueError(f"Agent configuration not found: {agent_id}")
-
- return self._configs[agent_id].model_dump()
-
- def update_config(self, agent_id: str, updates: Dict[str, Any]):
- """
- Update agent configuration
-
- Args:
- agent_id: Agent identifier
- updates: Configuration updates
- """
- if agent_id not in self._configs:
- raise ValueError(f"Agent configuration not found: {agent_id}")
-
- config = self._configs[agent_id]
- for key, value in updates.items():
- if hasattr(config, key):
- setattr(config, key, value)
+ print(f"Error saving agent configs to {json_path}: {e}")
+ return False
- # Update cached agent if exists
- if agent_id in self._agents:
- self._agents[agent_id].update_config(updates)
- self.logger.info(f"Updated configuration for agent: {agent_id}")
+# Compatibility alias
+ConfigurableAgent = AgentConfig
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tauri_bridge.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tauri_bridge.py
index 36c7844a6..08dd63c39 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tauri_bridge.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tauri_bridge.py
@@ -1,421 +1,226 @@
"""
-Tauri Bridge - Interface between Rust Tauri commands and Agno agents
+Tauri Bridge - Interface between Rust Tauri commands and agent configs
-This module provides the bridge layer that allows Rust Tauri commands
-to execute Agno agents seamlessly, replacing the old static agent system.
-
-Usage from Rust:
- python finagents/tauri_bridge.py --action execute_agent --parameters '{"agent_id": "buffett", "query": "Analyze AAPL"}' --inputs '{"api_keys": {...}}'
+Simple JSON config loader - no complex dependencies
"""
import json
import sys
import argparse
-from typing import Dict, Any, Optional
+from typing import Dict, Any
from pathlib import Path
-from finagent_core.base_agent import AgentRegistry, ConfigurableAgent
-from finagent_core.config.llm_providers import LLMProviderManager
-from finagent_core.tools.tool_registry import get_tool_registry
-from finagent_core.database.db_manager import DatabaseManager
-from finagent_core.utils.path_resolver import PathResolver
-from finagent_core.utils.logger import get_logger, setup_logger
+# Add parent directory to Python path
+sys.path.insert(0, str(Path(__file__).parent.parent))
-logger = get_logger(__name__)
+from finagent_core.base_agent import AgentRegistry, AgentConfig
class TauriBridge:
- """
- Bridge between Tauri Rust commands and Agno agents
-
- Handles:
- - Agent execution from Rust
- - Agent configuration management
- - API key injection
- - Error handling and logging
- """
-
- def __init__(self, base_path: Optional[str] = None):
- """
- Initialize Tauri bridge
-
- Args:
- base_path: Base path from Rust (via get_script_path)
- """
- # Set up path resolver
- self.path_resolver = PathResolver(base_path=base_path)
-
- # Initialize managers
- self.llm_provider_manager = LLMProviderManager()
- self.tool_registry = get_tool_registry()
- self.db_manager = DatabaseManager(base_path=self.path_resolver.base_path)
-
- # Initialize agent registries (lazy loading)
- self._agent_registries: Dict[str, AgentRegistry] = {}
-
- logger.info(f"TauriBridge initialized with base_path: {self.path_resolver.base_path}")
-
- def get_agent_registry(self, category: str) -> AgentRegistry:
- """
- Get agent registry for a category
-
- Args:
- category: Agent category (GeopoliticsAgents, EconomicAgents, etc.)
-
- Returns:
- AgentRegistry for the category
- """
- if category in self._agent_registries:
- return self._agent_registries[category]
-
- # Create new registry
- registry = AgentRegistry(
- base_path=self.path_resolver.base_path,
- llm_provider_manager=self.llm_provider_manager,
- tool_registry=self.tool_registry,
- db_manager=self.db_manager
- )
-
- # Load configurations from JSON
- config_path = self.path_resolver.get_agent_config_path(category)
- if config_path.exists():
- registry.load_configs_from_json(config_path)
- logger.info(f"Loaded {len(registry._configs)} agents for {category}")
- else:
- logger.warning(f"No configuration file found at: {config_path}")
-
- # Cache registry
- self._agent_registries[category] = registry
-
- return registry
-
- def execute_agent(self, parameters: Dict[str, Any], inputs: Dict[str, Any]) -> Dict[str, Any]:
- """
- Execute a single agent (called from Rust)
-
- Args:
- parameters: Execution parameters
- - agent_id: Agent identifier
- - query: User query
- - user_id: Optional user ID
- - session_id: Optional session ID
- - category: Agent category (default: "TraderInvestorsAgent")
- inputs: Runtime inputs
- - api_keys: Dictionary of API keys
-
- Returns:
- Execution result dictionary
- """
- try:
- agent_id = parameters.get("agent_id")
- if not agent_id:
- return {"success": False, "error": "agent_id is required"}
+ """Bridge between Tauri and agent configurations"""
- query = parameters.get("query")
- if not query:
- return {"success": False, "error": "query is required"}
+ def __init__(self, base_path: str = None):
+ self.base_path = Path(base_path) if base_path else Path(__file__).parent.parent
- user_id = parameters.get("user_id")
- session_id = parameters.get("session_id")
- category = parameters.get("category", "TraderInvestorsAgent")
- api_keys = inputs.get("api_keys", {})
-
- logger.info(f"Executing agent: {agent_id} in category: {category}")
+ def get_config_path(self, category: str) -> Path:
+ """Get path to agent config file for category"""
+ category_path = self.base_path / category / "configs"
- # Get agent registry for category
- registry = self.get_agent_registry(category)
+ # Check for agent_definitions.json or team_config.json
+ agent_defs = category_path / "agent_definitions.json"
+ team_config = category_path / "team_config.json"
- # Get agent
- agent = registry.get_agent(agent_id, api_keys=api_keys)
+ if agent_defs.exists():
+ return agent_defs
+ elif team_config.exists():
+ return team_config
+ else:
+ raise FileNotFoundError(f"No config found for category: {category}")
- # Run agent
- response = agent.run(
- query=query,
- user_id=user_id,
- session_id=session_id
- )
+ def list_agents(self, parameters: Dict) -> Dict:
+ """List all agents in a category"""
+ try:
+ category = parameters.get("category", "TraderInvestorsAgent")
+ config_path = self.get_config_path(category)
- # Extract response content
- content = response.content if hasattr(response, 'content') else str(response)
+ registry = AgentRegistry(config_path)
+ agents = registry.list_agents()
return {
"success": True,
- "agent_id": agent_id,
- "category": category,
- "response": content,
- "run_id": response.run_id if hasattr(response, 'run_id') else None,
- "session_id": response.session_id if hasattr(response, 'session_id') else session_id,
- "metrics": response.metrics if hasattr(response, 'metrics') else {}
+ "agents": [agent.to_dict() for agent in agents],
+ "count": len(agents)
}
-
except Exception as e:
- logger.error(f"Error executing agent: {e}", exc_info=True)
return {
"success": False,
"error": str(e),
- "agent_id": parameters.get("agent_id", "unknown"),
- "category": parameters.get("category", "unknown")
+ "agents": []
}
- def list_agents(self, parameters: Dict[str, Any] = None) -> Dict[str, Any]:
- """
- List all available agents
-
- Args:
- parameters: Optional parameters
- - category: Filter by category
-
- Returns:
- List of available agents
- """
+ def get_config(self, parameters: Dict) -> Dict:
+ """Get configuration for a specific agent"""
try:
- category = (parameters or {}).get("category")
+ agent_id = parameters.get("agent_id")
+ category = parameters.get("category", "TraderInvestorsAgent")
+
+ config_path = self.get_config_path(category)
+ registry = AgentRegistry(config_path)
+ agent = registry.get_agent(agent_id)
- if category:
- # List agents for specific category
- registry = self.get_agent_registry(category)
- agents = registry.list_agents()
+ if agent:
return {
"success": True,
- "category": category,
- "agents": agents,
- "count": len(agents)
+ "config": agent.to_dict()
}
else:
- # List all agents from all categories
- all_categories = [
- "GeopoliticsAgents",
- "EconomicAgents",
- "hedgeFundAgents",
- "TraderInvestorsAgent"
- ]
-
- result = {}
- total_count = 0
-
- for cat in all_categories:
- try:
- registry = self.get_agent_registry(cat)
- agents = registry.list_agents()
- result[cat] = agents
- total_count += len(agents)
- except Exception as e:
- logger.warning(f"Error loading category {cat}: {e}")
- result[cat] = []
-
return {
- "success": True,
- "categories": result,
- "total_count": total_count
+ "success": False,
+ "error": f"Agent not found: {agent_id}"
}
-
except Exception as e:
- logger.error(f"Error listing agents: {e}", exc_info=True)
return {
"success": False,
"error": str(e)
}
- def get_agent_config(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
- """
- Get agent configuration for UI
-
- Args:
- parameters: Parameters
- - agent_id: Agent identifier
- - category: Agent category
-
- Returns:
- Agent configuration
- """
+ def update_config(self, parameters: Dict) -> Dict:
+ """Update agent configuration"""
try:
agent_id = parameters.get("agent_id")
category = parameters.get("category", "TraderInvestorsAgent")
+ updates = parameters.get("updates", {})
- if not agent_id:
- return {"success": False, "error": "agent_id is required"}
-
- registry = self.get_agent_registry(category)
- config = registry.get_config(agent_id)
-
- return {
- "success": True,
- "agent_id": agent_id,
- "category": category,
- "config": config
- }
-
+ config_path = self.get_config_path(category)
+ registry = AgentRegistry(config_path)
+
+ if registry.update_agent_config(agent_id, updates):
+ if registry.save_configs_to_json(config_path):
+ return {
+ "success": True,
+ "message": "Configuration updated successfully"
+ }
+ else:
+ return {
+ "success": False,
+ "error": "Failed to save configuration"
+ }
+ else:
+ return {
+ "success": False,
+ "error": f"Agent not found: {agent_id}"
+ }
except Exception as e:
- logger.error(f"Error getting agent config: {e}", exc_info=True)
return {
"success": False,
- "error": str(e),
- "agent_id": parameters.get("agent_id", "unknown")
+ "error": str(e)
}
- def update_agent_config(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
- """
- Update agent configuration
-
- Args:
- parameters: Parameters
- - agent_id: Agent identifier
- - category: Agent category
- - updates: Configuration updates
+ def get_providers(self, parameters: Dict) -> Dict:
+ """Get available LLM providers"""
+ return {
+ "success": True,
+ "providers": {
+ "openai": {
+ "name": "OpenAI",
+ "models": ["gpt-4-turbo", "gpt-4", "gpt-3.5-turbo"],
+ "api_key_required": True
+ },
+ "anthropic": {
+ "name": "Anthropic",
+ "models": ["claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"],
+ "api_key_required": True
+ },
+ "google": {
+ "name": "Google",
+ "models": ["gemini-pro", "gemini-1.5-pro-latest"],
+ "api_key_required": True
+ },
+ "ollama": {
+ "name": "Ollama",
+ "models": ["llama2", "mistral", "mixtral"],
+ "api_key_required": False
+ }
+ }
+ }
- Returns:
- Update result
- """
+ def execute_agent(self, parameters: Dict, inputs: Dict) -> Dict:
+ """Execute an agent (placeholder - actual execution requires LLM setup)"""
try:
agent_id = parameters.get("agent_id")
category = parameters.get("category", "TraderInvestorsAgent")
- updates = parameters.get("updates", {})
+ query = parameters.get("query", "")
- if not agent_id:
- return {"success": False, "error": "agent_id is required"}
+ config_path = self.get_config_path(category)
+ registry = AgentRegistry(config_path)
+ agent = registry.get_agent(agent_id)
- registry = self.get_agent_registry(category)
- registry.update_config(agent_id, updates)
+ if not agent:
+ return {
+ "success": False,
+ "error": f"Agent not found: {agent_id}"
+ }
+ # For now, return agent info (actual LLM execution would go here)
return {
"success": True,
- "message": f"Agent {agent_id} configuration updated",
"agent_id": agent_id,
- "category": category
+ "response": f"Agent '{agent.name}' received query: {query}\n\nNote: Full LLM execution requires API keys and Agno framework setup.",
+ "config": agent.to_dict()
}
-
except Exception as e:
- logger.error(f"Error updating agent config: {e}", exc_info=True)
return {
"success": False,
- "error": str(e),
- "agent_id": parameters.get("agent_id", "unknown")
+ "error": str(e)
}
- def get_provider_info(self) -> Dict[str, Any]:
- """
- Get information about LLM providers
+ def execute(self, action: str, parameters: Dict, inputs: Dict) -> Dict:
+ """Execute an action"""
+ actions = {
+ "list_agents": self.list_agents,
+ "get_config": self.get_config,
+ "update_config": self.update_config,
+ "get_providers": self.get_providers,
+ "execute_agent": self.execute_agent,
+ }
- Returns:
- Provider information
- """
- try:
- info = self.llm_provider_manager.get_provider_info()
- return {
- "success": True,
- **info
- }
- except Exception as e:
- logger.error(f"Error getting provider info: {e}", exc_info=True)
+ handler = actions.get(action)
+ if handler:
+ if action == "execute_agent":
+ return handler(parameters, inputs)
+ else:
+ return handler(parameters)
+ else:
return {
"success": False,
- "error": str(e)
+ "error": f"Unknown action: {action}"
}
def main():
- """
- CLI entry point for Tauri Rust commands
-
- This function is called from Rust via subprocess execution.
-
- Example Rust call:
- python finagents/tauri_bridge.py \
- --action execute_agent \
- --parameters '{"agent_id": "warren_buffett_agent", "query": "Analyze AAPL"}' \
- --inputs '{"api_keys": {"OPENAI_API_KEY": "sk-..."}}' \
- --base-path /path/to/agents
- """
- parser = argparse.ArgumentParser(description='Agno Agent Execution Bridge for Tauri')
-
- parser.add_argument(
- '--action',
- type=str,
- required=True,
- choices=['execute_agent', 'list_agents', 'get_config', 'update_config', 'get_providers'],
- help='Action to perform'
- )
-
- parser.add_argument(
- '--parameters',
- type=str,
- default='{}',
- help='JSON parameters for the action'
- )
-
- parser.add_argument(
- '--inputs',
- type=str,
- default='{}',
- help='JSON runtime inputs (API keys, etc.)'
- )
-
- parser.add_argument(
- '--base-path',
- type=str,
- default=None,
- help='Base path for agents (provided by Rust get_script_path)'
- )
-
- parser.add_argument(
- '--log-level',
- type=str,
- default='INFO',
- choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
- help='Logging level'
- )
+ """CLI entry point"""
+ parser = argparse.ArgumentParser(description="Tauri Bridge for Agent Configuration")
+ parser.add_argument("--action", required=True, help="Action to perform")
+ parser.add_argument("--parameters", default="{}", help="JSON parameters")
+ parser.add_argument("--inputs", default="{}", help="JSON inputs")
+ parser.add_argument("--base-path", help="Base path for agent configs")
args = parser.parse_args()
- # Set up logging
- import logging
- log_level = getattr(logging, args.log_level)
- setup_logger(__name__, level=log_level, console=True)
-
try:
- # Parse parameters and inputs
parameters = json.loads(args.parameters)
inputs = json.loads(args.inputs)
-
- # Create bridge
- bridge = TauriBridge(base_path=args.base_path)
-
- # Execute action
- if args.action == 'execute_agent':
- result = bridge.execute_agent(parameters, inputs)
- elif args.action == 'list_agents':
- result = bridge.list_agents(parameters)
- elif args.action == 'get_config':
- result = bridge.get_agent_config(parameters)
- elif args.action == 'update_config':
- result = bridge.update_agent_config(parameters)
- elif args.action == 'get_providers':
- result = bridge.get_provider_info()
- else:
- result = {"success": False, "error": f"Unknown action: {args.action}"}
-
- # Output result as JSON
- print(json.dumps(result, indent=2))
- sys.exit(0)
-
except json.JSONDecodeError as e:
- error_result = {
+ print(json.dumps({
"success": False,
- "error": f"Invalid JSON: {e}",
- "action": args.action
- }
- print(json.dumps(error_result), file=sys.stderr)
+ "error": f"Invalid JSON: {str(e)}"
+ }))
sys.exit(1)
- except Exception as e:
- error_result = {
- "success": False,
- "error": str(e),
- "action": args.action
- }
- logger.error(f"Fatal error: {e}", exc_info=True)
- print(json.dumps(error_result), file=sys.stderr)
- sys.exit(1)
+ bridge = TauriBridge(args.base_path)
+ result = bridge.execute(args.action, parameters, inputs)
+
+ print(json.dumps(result))
if __name__ == "__main__":
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index c99e29314..1cdd4b52f 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -29,7 +29,7 @@
},
"bundle": {
"active": true,
- "targets": ["msi", "appimage"],
+ "targets": ["msi", "appimage", "deb", "rpm"],
"createUpdaterArtifacts": true,
"icon": [
"icons/32x32.png",
diff --git a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
index f5a857056..03c615402 100644
--- a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
@@ -625,6 +625,88 @@ const AgentConfigTab: React.FC = () => {
</div>
</div>
+ {/* Scoring Weights */}
+ {(selectedAgent as any).scoring_weights && Object.keys((selectedAgent as any).scoring_weights).length > 0 && (
+ <div>
+ <div style={{ fontSize: '10px', fontWeight: 600, color: BLOOMBERG.GRAY, marginBottom: '6px' }}>
+ SCORING WEIGHTS (User Configurable)
+ </div>
+ <div style={{
+ padding: '8px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.ORANGE}`,
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '8px',
+ fontSize: '10px'
+ }}>
+ {Object.entries((selectedAgent as any).scoring_weights || {}).map(([key, value]) => (
+ <div key={key}>
+ <span style={{ color: BLOOMBERG.GRAY }}>{key}:</span>{' '}
+ <span style={{ color: BLOOMBERG.ORANGE, fontWeight: 600 }}>{((value as number) * 100).toFixed(0)}%</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Thresholds */}
+ {(selectedAgent as any).thresholds && Object.keys((selectedAgent as any).thresholds).length > 0 && (
+ <div>
+ <div style={{ fontSize: '10px', fontWeight: 600, color: BLOOMBERG.GRAY, marginBottom: '6px' }}>
+ ANALYSIS THRESHOLDS (User Configurable)
+ </div>
+ <div style={{
+ padding: '8px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.CYAN}`,
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr',
+ gap: '6px',
+ fontSize: '9px',
+ maxHeight: '150px',
+ overflow: 'auto'
+ }}>
+ {Object.entries((selectedAgent as any).thresholds || {}).map(([key, value]) => (
+ <div key={key}>
+ <span style={{ color: BLOOMBERG.GRAY }}>{key}:</span>{' '}
+ <span style={{ color: BLOOMBERG.CYAN }}>{String(value)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Data Sources */}
+ {(selectedAgent as any).data_sources && (
+ <div>
+ <div style={{ fontSize: '10px', fontWeight: 600, color: BLOOMBERG.GRAY, marginBottom: '6px' }}>
+ DATA SOURCES (User Configurable)
+ </div>
+ <div style={{
+ padding: '8px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.PURPLE}`,
+ fontSize: '10px'
+ }}>
+ {(selectedAgent as any).data_sources?.line_items && Array.isArray((selectedAgent as any).data_sources.line_items) && (
+ <div style={{ marginBottom: '6px' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>Line Items:</span>{' '}
+ <span style={{ color: BLOOMBERG.PURPLE }}>
+ {(selectedAgent as any).data_sources.line_items.join(', ')}
+ </span>
+ </div>
+ )}
+ {(selectedAgent as any).data_sources?.years_of_data != null && (
+ <div>
+ <span style={{ color: BLOOMBERG.GRAY }}>Years of Data:</span>{' '}
+ <span style={{ color: BLOOMBERG.YELLOW }}>{(selectedAgent as any).data_sources.years_of_data}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
{/* Instructions */}
<div>
<div style={{ fontSize: '10px', fontWeight: 600, color: BLOOMBERG.GRAY, marginBottom: '6px' }}>
diff --git a/fincept-terminal-desktop/test-file.txt b/fincept-terminal-desktop/test-file.txt
new file mode 100644
index 000000000..d670460b4
--- /dev/null
+++ b/fincept-terminal-desktop/test-file.txt
@@ -0,0 +1 @@
+test content
diff --git a/fincept-terminal-desktop/test.txt b/fincept-terminal-desktop/test.txt
new file mode 100644
index 000000000..9daeafb98
--- /dev/null
+++ b/fincept-terminal-desktop/test.txt
@@ -0,0 +1 @@
+test