A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix finagent - swap Gemini for Mistral Small 4, fix load_dotenv bug, add docstrings, fix broken README example
Tiioluwani7fa8d17b35d6
diff --git a/ai_agents/finagent/.env.example b/ai_agents/finagent/.env.exampleindex 3cac181..cf8f5e6 100644--- a/ai_agents/finagent/.env.example+++ b/ai_agents/finagent/.env.example@@ -1 +1,7 @@-OPENAI_API_KEY=your_openai_api_key_here+# Mistral API key for the Mistral Small 4 (mistral-small-latest) model used by the financial analysis agents.+# Get one at https://console.mistral.ai/api-keys+MISTRAL_API_KEY=your_mistral_api_key_here++# Optional: Firecrawl API key used for enhanced news scraping features.+# Get one at https://firecrawl.dev+FIRECRAWL_API_KEY=your_firecrawl_api_key_herediff --git a/ai_agents/finagent/README.md b/ai_agents/finagent/README.mdindex 140d8a3..09ea10f 100644--- a/ai_agents/finagent/README.md+++ b/ai_agents/finagent/README.md@@ -1,6 +1,10 @@# Finagent - AI-Powered Financial Analysis Tool-A sophisticated financial analysis system that leverages Google's Gemini AI and real-time market data to provide comprehensive stock analysis, automated code generation, and investment insights.+A sophisticated financial analysis system that leverages Mistral Small 4 (mistral-small-latest) and real-time market data to provide comprehensive stock analysis, automated code generation, and investment insights.++## Demo++## Features@@ -9,13 +13,12 @@ A sophisticated financial analysis system that leverages Google's Gemini AI and- **Automated Code Generation**: Creates executable Python code for financial analysis- **News Integration**: Incorporates latest market news into analysis- **MCP Server**: Modern Model Context Protocol server for Claude Desktop integration-- **Professional Visualizations**: Generates matplotlib charts and technical analysis plots- **Risk Assessment**: Provides balanced investment recommendations with proper disclaimers## Prerequisites- Python 3.8+-- Google Gemini API key+- Mistral API key (for the Mistral Small 4 / mistral-small-latest model)- Claude Desktop (for MCP integration)- Firecrawl API key (optional, for enhanced news features)@@ -44,22 +47,22 @@ cd finagent2. **Install required packages**:```bash-pip install google-generativeai yfinance pandas matplotlib numpy mcp python-dotenv+pip install -r requirements.txt```3. **Set up environment variables**:Create a `.env` file in the project root:```env-GEMINI_API_KEY=your_gemini_api_key_here+MISTRAL_API_KEY=your_mistral_api_key_hereFIRECRAWL_API_KEY=your_firecrawl_api_key_here # Optional```## API Keys Setup-### Gemini API Key (Required)+### Mistral API Key (Required)-1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)+1. Visit [Mistral Console](https://console.mistral.ai/api-keys)2. Create a new API key3. Add it to your `.env` file@@ -96,7 +99,7 @@ FIRECRAWL_API_KEY=your_firecrawl_api_key_here # Optional"command": "python","args": ["/absolute/path/to/finagent/main.py"],"env": {- "GEMINI_API_KEY": "your_gemini_api_key_here",+ "MISTRAL_API_KEY": "your_mistral_api_key_here","FIRECRAWL_API_KEY": "your_firecrawl_api_key_here"}}@@ -167,15 +170,12 @@ python main.pyfrom financial_agents import FinancialAnalysisTeamteam = FinancialAnalysisTeam(- gemini_api_key="your_gemini_key",- firecrawl_api_key="your_firecrawl_key"+ mistral_api_key="your_mistral_key")result = team.analyze("Analyze Apple stock over the last 6 months")-print(f"Insights: {result.insights}")-print(f"Recommendations: {result.recommendations}")-print(f"Generated Code:\n{result.code}")+print(result)```## Example Queries@@ -193,7 +193,7 @@ The system understands natural language queries:### Core Components1. **FinancialAnalysisTeam**: Main orchestrator class-2. **GeminiAgent**: Base agent class using Gemini AI+2. **MistralAgent**: Base agent class using Mistral Small 4 (mistral-small-latest)3. **FinancialTools**: Data acquisition utilities4. **MCP Server**: Model Context Protocol server for Claude Desktop@@ -208,7 +208,6 @@ The system understands natural language queries:- **Technical Indicators**: RSI, MACD, Moving averages, Bollinger bands- **Price Analysis**: Trend analysis, support/resistance levels- **Risk Metrics**: Volatility calculations, drawdown analysis-- **Visualizations**: Professional charts with technical overlays- **News Integration**: Latest market sentiment and news impact- **Investment Recommendations**: Buy/Hold/Sell with rationale@@ -233,7 +232,7 @@ The system understands natural language queries:2. **Import Errors**:```bash-pip install google-generativeai yfinance pandas mcp python-dotenv+pip install -r requirements.txt```3. **API Key Issues**:@@ -291,4 +290,4 @@ For questions and support:----**Made with Google Gemini AI & Claude Desktop**+**Made with Mistral Small 4 & Claude Desktop**diff --git a/ai_agents/finagent/assets/demo.gif b/ai_agents/finagent/assets/demo.gifnew file mode 100644index 0000000..61696baBinary files /dev/null and b/ai_agents/finagent/assets/demo.gif differdiff --git a/ai_agents/finagent/financial_agents.py b/ai_agents/finagent/financial_agents.pyindex 4f293e8..c9eb02f 100644--- a/ai_agents/finagent/financial_agents.py+++ b/ai_agents/finagent/financial_agents.py@@ -1,10 +1,16 @@+"""Multi-agent financial analysis pipeline built on Mistral Small 4 and Yahoo Finance market data."""+import osimport reimport jsonimport yfinance as yf-import google.generativeai as genai+from dotenv import load_dotenv+from mistralai.client import Mistral++load_dotenv()def _normalize_period(period: str) -> str:+ """Normalizes a user-supplied time period string into a yfinance-compatible period code."""if not period:return '6mo'p = str(period).strip().lower()@@ -17,30 +23,62 @@ def _normalize_period(period: str) -> str:return p-class GeminiAgent:+def _summarize_stock_data(stock_data) -> str:+ """Builds a compact text summary of real OHLCV price data to ground the analysis prompt."""+ first = stock_data.iloc[0]+ latest = stock_data.iloc[-1]+ start_price = float(first['Close'])+ end_price = float(latest['Close'])+ pct_change = ((end_price - start_price) / start_price) * 100 if start_price else 0.0+ period_high = float(stock_data['High'].max())+ period_low = float(stock_data['Low'].min())+ first_date = stock_data.index[0].strftime('%Y-%m-%d')+ latest_date = stock_data.index[-1].strftime('%Y-%m-%d')++ return (+ f"Data range: {first_date} to {latest_date}\n"+ f"Starting close: {start_price:.2f}\n"+ f"Latest close: {end_price:.2f}\n"+ f"Change over period: {pct_change:.2f}%\n"+ f"Period high: {period_high:.2f}\n"+ f"Period low: {period_low:.2f}\n"+ f"Latest volume: {int(latest['Volume'])}"+ )+++class MistralAgent:+ """Wraps a single Mistral Small 4 chat role with its own system prompt."""+def __init__(self, api_key: str, role: str, system_prompt: str):- genai.configure(api_key=api_key)- self.model = genai.GenerativeModel('gemini-2.5-flash')+ self.client = Mistral(api_key=api_key)+ self.model = 'mistral-small-latest'self.role = roleself.system_prompt = system_promptdef generate(self, prompt: str) -> str:full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"- response = self.model.generate_content(full_prompt)- return response.text+ response = self.client.chat.complete(+ model=self.model,+ messages=[{"role": "user", "content": full_prompt}],+ )+ return response.choices[0].message.contentclass FinancialTools:+ """Provides access to the market data needed by the analysis agents."""+def get_stock_data(self, symbol: str, period: str = "6mo"):ticker = yf.Ticker(symbol)return ticker.history(period=period)class FinancialAnalysisTeam:- def __init__(self, gemini_api_key: str):+ """Coordinates the query parser and market analyst agents to produce a stock analysis."""++ def __init__(self, mistral_api_key: str):self.tools = FinancialTools()- self.query_parser = GeminiAgent(- gemini_api_key,+ self.query_parser = MistralAgent(+ mistral_api_key,"Query Parser","""You are a financial query parser. Extract from the user query:- Stock symbol (ticker)@@ -48,14 +86,15 @@ class FinancialAnalysisTeam:- Time period (like 1d, 1mo, 6mo, 1y)Return a JSON object with keys: symbol, analysis_type, time_period.""")- self.market_analyst = GeminiAgent(- gemini_api_key,+ self.market_analyst = MistralAgent(+ mistral_api_key,"Market Analyst","""You are a senior financial analyst. Provide a clear, professional, and actionable analysis for the stock.Include market trends, price action, risk assessment and investment recommendations.""")def parse_query(self, query: str):+ """Parses a natural language query into a symbol, analysis type, and time period."""response = self.query_parser.generate(query)try:json_match = re.search(r"\{.*\}", response, re.DOTALL)@@ -74,14 +113,19 @@ Include market trends, price action, risk assessment and investment recommendatireturn datadef analyze_market(self, query_info, stock_data) -> str:+ """Asks the market analyst agent for a written analysis grounded in the fetched stock data."""+ data_summary = _summarize_stock_data(stock_data)prompt = (f"Analyze the stock symbol {query_info['symbol']} for the period "- f"{query_info.get('time_period', '6mo')}. Use recent price data and technical indicators "- f"to provide market trends, risk factors, and recommendations."+ f"{query_info.get('time_period', '6mo')} using the following real market data:\n\n"+ f"{data_summary}\n\n"+ f"Base your trends, risk factors, and recommendations only on this data. "+ f"Do not assume any other price information.")return self.market_analyst.generate(prompt)def analyze(self, query: str) -> str:+ """Runs the full parse, fetch, and analyze pipeline for a query and returns the analysis text."""query_info = self.parse_query(query)period = _normalize_period(query_info.get("time_period", "6mo"))stock_data = self.tools.get_stock_data(query_info["symbol"], period)@@ -93,10 +137,11 @@ Include market trends, price action, risk assessment and investment recommendatidef run_financial_analysis(query: str) -> str:- gemini_api_key = os.getenv("GEMINI_API_KEY")- if not gemini_api_key:- return "Error: GEMINI_API_KEY environment variable is not set."- team = FinancialAnalysisTeam(gemini_api_key)+ """Builds a FinancialAnalysisTeam from the configured Mistral API key and runs the given query."""+ mistral_api_key = os.getenv("MISTRAL_API_KEY")+ if not mistral_api_key:+ return "Error: MISTRAL_API_KEY environment variable is not set."+ team = FinancialAnalysisTeam(mistral_api_key)try:return team.analyze(query)except Exception as e:diff --git a/ai_agents/finagent/main.py b/ai_agents/finagent/main.pyindex 3b1a217..702e677 100644--- a/ai_agents/finagent/main.py+++ b/ai_agents/finagent/main.py@@ -1,6 +1,10 @@+"""MCP server exposing the financial stock analysis tools backed by Mistral Small 4."""++from dotenv import load_dotenvfrom mcp.server.fastmcp import FastMCPfrom financial_agents import run_financial_analysis+load_dotenv()# Create FastMCP instancemcp = FastMCP("financial-analyst")diff --git a/ai_agents/finagent/requirements.txt b/ai_agents/finagent/requirements.txtindex cdf3f28..4daf2c8 100644--- a/ai_agents/finagent/requirements.txt+++ b/ai_agents/finagent/requirements.txt@@ -1,7 +1,4 @@-google-generativeai>=0.3.0+mistralai>=1.0.0mcp>=0.1.0yfinance>=0.2.18-pandas>=1.5.0-numpy>=1.21.0-matplotlib>=3.5.0python-dotenv>=0.19.0\ No newline at end of file