sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
TauricResearch/TradingAgents:tradingagents/dataflows/stockstats_utils.py
import pandas as pd import yfinance as yf from stockstats import wrap from typing import Annotated import os from .config import get_config class StockstatsUtils: @staticmethod def get_stock_stats( symbol: Annotated[str, "ticker symbol for the company"], indicator: Annotated[ str, "quantitative indicators based off of the stock data for the company" ], curr_date: Annotated[ str, "curr date for retrieving stock price data, YYYY-mm-dd" ], ): config = get_config() today_date = pd.Timestamp.today() curr_date_dt = pd.to_datetime(curr_date) end_date = today_date start_date = today_date - pd.DateOffset(years=15) start_date_str = start_date.strftime("%Y-%m-%d") end_date_str = end_date.strftime("%Y-%m-%d") # Ensure cache directory exists os.makedirs(config["data_cache_dir"], exist_ok=True) data_file = os.path.join( config["data_cache_dir"], f"{symbol}-YFin-data-{start_date_str}-{end_date_str}.csv", ) if os.path.exists(data_file): data = pd.read_csv(data_file) data["Date"] = pd.to_datetime(data["Date"]) else: data = yf.download( symbol, start=start_date_str, end=end_date_str, multi_level_index=False, progress=False, auto_adjust=True, ) data = data.reset_index() data.to_csv(data_file, index=False) df = wrap(data) df["Date"] = df["Date"].dt.strftime("%Y-%m-%d") curr_date_str = curr_date_dt.strftime("%Y-%m-%d") df[indicator] # trigger stockstats to calculate the indicator matching_rows = df[df["Date"].str.startswith(curr_date_str)] if not matching_rows.empty: indicator_value = matching_rows[indicator].values[0] return indicator_value else: return "N/A: Not a trading day (weekend or holiday)"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/stockstats_utils.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/dataflows/utils.py
import os import json import pandas as pd from datetime import date, timedelta, datetime from typing import Annotated SavePathType = Annotated[str, "File path to save data. If None, data is not saved."] def save_output(data: pd.DataFrame, tag: str, save_path: SavePathType = None) -> None: if save_path: data.to_csv(save_path) print(f"{tag} saved to {save_path}") def get_current_date(): return date.today().strftime("%Y-%m-%d") def decorate_all_methods(decorator): def class_decorator(cls): for attr_name, attr_value in cls.__dict__.items(): if callable(attr_value): setattr(cls, attr_name, decorator(attr_value)) return cls return class_decorator def get_next_weekday(date): if not isinstance(date, datetime): date = datetime.strptime(date, "%Y-%m-%d") if date.weekday() >= 5: days_to_add = 7 - date.weekday() next_weekday = date + timedelta(days=days_to_add) return next_weekday else: return date
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/utils.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/default_config.py
import os DEFAULT_CONFIG = { "project_dir": os.path.abspath(os.path.join(os.path.dirname(__file__), ".")), "results_dir": os.getenv("TRADINGAGENTS_RESULTS_DIR", "./results"), "data_cache_dir": os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), ".")), "dataflows/data_cache", ), # LLM settings "llm_provider": "openai", "deep_think_llm": "gpt-5.2", "quick_think_llm": "gpt-5-mini", "backend_url": "https://api.openai.com/v1", # Provider-specific thinking configuration "google_thinking_level": None, # "high", "minimal", etc. "openai_reasoning_effort": None, # "medium", "high", "low" # Debate and discussion settings "max_debate_rounds": 1, "max_risk_discuss_rounds": 1, "max_recur_limit": 100, # Data vendor configuration # Category-level configuration (default for all tools in category) "data_vendors": { "core_stock_apis": "yfinance", # Options: alpha_vantage, yfinance "technical_indicators": "yfinance", # Options: alpha_vantage, yfinance "fundamental_data": "yfinance", # Options: alpha_vantage, yfinance "news_data": "yfinance", # Options: alpha_vantage, yfinance }, # Tool-level configuration (takes precedence over category-level) "tool_vendors": { # Example: "get_stock_data": "alpha_vantage", # Override category default }, }
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/default_config.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/graph/conditional_logic.py
# TradingAgents/graph/conditional_logic.py from tradingagents.agents.utils.agent_states import AgentState class ConditionalLogic: """Handles conditional logic for determining graph flow.""" def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1): """Initialize with configuration parameters.""" self.max_debate_rounds = max_debate_rounds self.max_risk_discuss_rounds = max_risk_discuss_rounds def should_continue_market(self, state: AgentState): """Determine if market analysis should continue.""" messages = state["messages"] last_message = messages[-1] if last_message.tool_calls: return "tools_market" return "Msg Clear Market" def should_continue_social(self, state: AgentState): """Determine if social media analysis should continue.""" messages = state["messages"] last_message = messages[-1] if last_message.tool_calls: return "tools_social" return "Msg Clear Social" def should_continue_news(self, state: AgentState): """Determine if news analysis should continue.""" messages = state["messages"] last_message = messages[-1] if last_message.tool_calls: return "tools_news" return "Msg Clear News" def should_continue_fundamentals(self, state: AgentState): """Determine if fundamentals analysis should continue.""" messages = state["messages"] last_message = messages[-1] if last_message.tool_calls: return "tools_fundamentals" return "Msg Clear Fundamentals" def should_continue_debate(self, state: AgentState) -> str: """Determine if debate should continue.""" if ( state["investment_debate_state"]["count"] >= 2 * self.max_debate_rounds ): # 3 rounds of back-and-forth between 2 agents return "Research Manager" if state["investment_debate_state"]["current_response"].startswith("Bull"): return "Bear Researcher" return "Bull Researcher" def should_continue_risk_analysis(self, state: AgentState) -> str: """Determine if risk analysis should continue.""" if ( state["risk_debate_state"]["count"] >= 3 * self.max_risk_discuss_rounds ): # 3 rounds of back-and-forth between 3 agents return "Risk Judge" if state["risk_debate_state"]["latest_speaker"].startswith("Aggressive"): return "Conservative Analyst" if state["risk_debate_state"]["latest_speaker"].startswith("Conservative"): return "Neutral Analyst" return "Aggressive Analyst"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/graph/conditional_logic.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/graph/propagation.py
# TradingAgents/graph/propagation.py from typing import Dict, Any, List, Optional from tradingagents.agents.utils.agent_states import ( AgentState, InvestDebateState, RiskDebateState, ) class Propagator: """Handles state initialization and propagation through the graph.""" def __init__(self, max_recur_limit=100): """Initialize with configuration parameters.""" self.max_recur_limit = max_recur_limit def create_initial_state( self, company_name: str, trade_date: str ) -> Dict[str, Any]: """Create the initial state for the agent graph.""" return { "messages": [("human", company_name)], "company_of_interest": company_name, "trade_date": str(trade_date), "investment_debate_state": InvestDebateState( {"history": "", "current_response": "", "count": 0} ), "risk_debate_state": RiskDebateState( { "history": "", "current_aggressive_response": "", "current_conservative_response": "", "current_neutral_response": "", "count": 0, } ), "market_report": "", "fundamentals_report": "", "sentiment_report": "", "news_report": "", } def get_graph_args(self, callbacks: Optional[List] = None) -> Dict[str, Any]: """Get arguments for the graph invocation. Args: callbacks: Optional list of callback handlers for tool execution tracking. Note: LLM callbacks are handled separately via LLM constructor. """ config = {"recursion_limit": self.max_recur_limit} if callbacks: config["callbacks"] = callbacks return { "stream_mode": "values", "config": config, }
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/graph/propagation.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/graph/reflection.py
# TradingAgents/graph/reflection.py from typing import Dict, Any from langchain_openai import ChatOpenAI class Reflector: """Handles reflection on decisions and updating memory.""" def __init__(self, quick_thinking_llm: ChatOpenAI): """Initialize the reflector with an LLM.""" self.quick_thinking_llm = quick_thinking_llm self.reflection_system_prompt = self._get_reflection_prompt() def _get_reflection_prompt(self) -> str: """Get the system prompt for reflection.""" return """ You are an expert financial analyst tasked with reviewing trading decisions/analysis and providing a comprehensive, step-by-step analysis. Your goal is to deliver detailed insights into investment decisions and highlight opportunities for improvement, adhering strictly to the following guidelines: 1. Reasoning: - For each trading decision, determine whether it was correct or incorrect. A correct decision results in an increase in returns, while an incorrect decision does the opposite. - Analyze the contributing factors to each success or mistake. Consider: - Market intelligence. - Technical indicators. - Technical signals. - Price movement analysis. - Overall market data analysis - News analysis. - Social media and sentiment analysis. - Fundamental data analysis. - Weight the importance of each factor in the decision-making process. 2. Improvement: - For any incorrect decisions, propose revisions to maximize returns. - Provide a detailed list of corrective actions or improvements, including specific recommendations (e.g., changing a decision from HOLD to BUY on a particular date). 3. Summary: - Summarize the lessons learned from the successes and mistakes. - Highlight how these lessons can be adapted for future trading scenarios and draw connections between similar situations to apply the knowledge gained. 4. Query: - Extract key insights from the summary into a concise sentence of no more than 1000 tokens. - Ensure the condensed sentence captures the essence of the lessons and reasoning for easy reference. Adhere strictly to these instructions, and ensure your output is detailed, accurate, and actionable. You will also be given objective descriptions of the market from a price movements, technical indicator, news, and sentiment perspective to provide more context for your analysis. """ def _extract_current_situation(self, current_state: Dict[str, Any]) -> str: """Extract the current market situation from the state.""" curr_market_report = current_state["market_report"] curr_sentiment_report = current_state["sentiment_report"] curr_news_report = current_state["news_report"] curr_fundamentals_report = current_state["fundamentals_report"] return f"{curr_market_report}\n\n{curr_sentiment_report}\n\n{curr_news_report}\n\n{curr_fundamentals_report}" def _reflect_on_component( self, component_type: str, report: str, situation: str, returns_losses ) -> str: """Generate reflection for a component.""" messages = [ ("system", self.reflection_system_prompt), ( "human", f"Returns: {returns_losses}\n\nAnalysis/Decision: {report}\n\nObjective Market Reports for Reference: {situation}", ), ] result = self.quick_thinking_llm.invoke(messages).content return result def reflect_bull_researcher(self, current_state, returns_losses, bull_memory): """Reflect on bull researcher's analysis and update memory.""" situation = self._extract_current_situation(current_state) bull_debate_history = current_state["investment_debate_state"]["bull_history"] result = self._reflect_on_component( "BULL", bull_debate_history, situation, returns_losses ) bull_memory.add_situations([(situation, result)]) def reflect_bear_researcher(self, current_state, returns_losses, bear_memory): """Reflect on bear researcher's analysis and update memory.""" situation = self._extract_current_situation(current_state) bear_debate_history = current_state["investment_debate_state"]["bear_history"] result = self._reflect_on_component( "BEAR", bear_debate_history, situation, returns_losses ) bear_memory.add_situations([(situation, result)]) def reflect_trader(self, current_state, returns_losses, trader_memory): """Reflect on trader's decision and update memory.""" situation = self._extract_current_situation(current_state) trader_decision = current_state["trader_investment_plan"] result = self._reflect_on_component( "TRADER", trader_decision, situation, returns_losses ) trader_memory.add_situations([(situation, result)]) def reflect_invest_judge(self, current_state, returns_losses, invest_judge_memory): """Reflect on investment judge's decision and update memory.""" situation = self._extract_current_situation(current_state) judge_decision = current_state["investment_debate_state"]["judge_decision"] result = self._reflect_on_component( "INVEST JUDGE", judge_decision, situation, returns_losses ) invest_judge_memory.add_situations([(situation, result)]) def reflect_risk_manager(self, current_state, returns_losses, risk_manager_memory): """Reflect on risk manager's decision and update memory.""" situation = self._extract_current_situation(current_state) judge_decision = current_state["risk_debate_state"]["judge_decision"] result = self._reflect_on_component( "RISK JUDGE", judge_decision, situation, returns_losses ) risk_manager_memory.add_situations([(situation, result)])
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/graph/reflection.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/graph/signal_processing.py
# TradingAgents/graph/signal_processing.py from langchain_openai import ChatOpenAI class SignalProcessor: """Processes trading signals to extract actionable decisions.""" def __init__(self, quick_thinking_llm: ChatOpenAI): """Initialize with an LLM for processing.""" self.quick_thinking_llm = quick_thinking_llm def process_signal(self, full_signal: str) -> str: """ Process a full trading signal to extract the core decision. Args: full_signal: Complete trading signal text Returns: Extracted decision (BUY, SELL, or HOLD) """ messages = [ ( "system", "You are an efficient assistant designed to analyze paragraphs or financial reports provided by a group of analysts. Your task is to extract the investment decision: SELL, BUY, or HOLD. Provide only the extracted decision (SELL, BUY, or HOLD) as your output, without adding any additional text or information.", ), ("human", full_signal), ] return self.quick_thinking_llm.invoke(messages).content
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/graph/signal_processing.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/graph/trading_graph.py
# TradingAgents/graph/trading_graph.py import os from pathlib import Path import json from datetime import date from typing import Dict, Any, Tuple, List, Optional from langgraph.prebuilt import ToolNode from tradingagents.llm_clients import create_llm_client from tradingagents.agents import * from tradingagents.default_config import DEFAULT_CONFIG from tradingagents.agents.utils.memory import FinancialSituationMemory from tradingagents.agents.utils.agent_states import ( AgentState, InvestDebateState, RiskDebateState, ) from tradingagents.dataflows.config import set_config # Import the new abstract tool methods from agent_utils from tradingagents.agents.utils.agent_utils import ( get_stock_data, get_indicators, get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement, get_news, get_insider_transactions, get_global_news ) from .conditional_logic import ConditionalLogic from .setup import GraphSetup from .propagation import Propagator from .reflection import Reflector from .signal_processing import SignalProcessor class TradingAgentsGraph: """Main class that orchestrates the trading agents framework.""" def __init__( self, selected_analysts=["market", "social", "news", "fundamentals"], debug=False, config: Dict[str, Any] = None, callbacks: Optional[List] = None, ): """Initialize the trading agents graph and components. Args: selected_analysts: List of analyst types to include debug: Whether to run in debug mode config: Configuration dictionary. If None, uses default config callbacks: Optional list of callback handlers (e.g., for tracking LLM/tool stats) """ self.debug = debug self.config = config or DEFAULT_CONFIG self.callbacks = callbacks or [] # Update the interface's config set_config(self.config) # Create necessary directories os.makedirs( os.path.join(self.config["project_dir"], "dataflows/data_cache"), exist_ok=True, ) # Initialize LLMs with provider-specific thinking configuration llm_kwargs = self._get_provider_kwargs() # Add callbacks to kwargs if provided (passed to LLM constructor) if self.callbacks: llm_kwargs["callbacks"] = self.callbacks deep_client = create_llm_client( provider=self.config["llm_provider"], model=self.config["deep_think_llm"], base_url=self.config.get("backend_url"), **llm_kwargs, ) quick_client = create_llm_client( provider=self.config["llm_provider"], model=self.config["quick_think_llm"], base_url=self.config.get("backend_url"), **llm_kwargs, ) self.deep_thinking_llm = deep_client.get_llm() self.quick_thinking_llm = quick_client.get_llm() # Initialize memories self.bull_memory = FinancialSituationMemory("bull_memory", self.config) self.bear_memory = FinancialSituationMemory("bear_memory", self.config) self.trader_memory = FinancialSituationMemory("trader_memory", self.config) self.invest_judge_memory = FinancialSituationMemory("invest_judge_memory", self.config) self.risk_manager_memory = FinancialSituationMemory("risk_manager_memory", self.config) # Create tool nodes self.tool_nodes = self._create_tool_nodes() # Initialize components self.conditional_logic = ConditionalLogic() self.graph_setup = GraphSetup( self.quick_thinking_llm, self.deep_thinking_llm, self.tool_nodes, self.bull_memory, self.bear_memory, self.trader_memory, self.invest_judge_memory, self.risk_manager_memory, self.conditional_logic, ) self.propagator = Propagator() self.reflector = Reflector(self.quick_thinking_llm) self.signal_processor = SignalProcessor(self.quick_thinking_llm) # State tracking self.curr_state = None self.ticker = None self.log_states_dict = {} # date to full state dict # Set up the graph self.graph = self.graph_setup.setup_graph(selected_analysts) def _get_provider_kwargs(self) -> Dict[str, Any]: """Get provider-specific kwargs for LLM client creation.""" kwargs = {} provider = self.config.get("llm_provider", "").lower() if provider == "google": thinking_level = self.config.get("google_thinking_level") if thinking_level: kwargs["thinking_level"] = thinking_level elif provider == "openai": reasoning_effort = self.config.get("openai_reasoning_effort") if reasoning_effort: kwargs["reasoning_effort"] = reasoning_effort return kwargs def _create_tool_nodes(self) -> Dict[str, ToolNode]: """Create tool nodes for different data sources using abstract methods.""" return { "market": ToolNode( [ # Core stock data tools get_stock_data, # Technical indicators get_indicators, ] ), "social": ToolNode( [ # News tools for social media analysis get_news, ] ), "news": ToolNode( [ # News and insider information get_news, get_global_news, get_insider_transactions, ] ), "fundamentals": ToolNode( [ # Fundamental analysis tools get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement, ] ), } def propagate(self, company_name, trade_date): """Run the trading agents graph for a company on a specific date.""" self.ticker = company_name # Initialize state init_agent_state = self.propagator.create_initial_state( company_name, trade_date ) args = self.propagator.get_graph_args() if self.debug: # Debug mode with tracing trace = [] for chunk in self.graph.stream(init_agent_state, **args): if len(chunk["messages"]) == 0: pass else: chunk["messages"][-1].pretty_print() trace.append(chunk) final_state = trace[-1] else: # Standard mode without tracing final_state = self.graph.invoke(init_agent_state, **args) # Store current state for reflection self.curr_state = final_state # Log state self._log_state(trade_date, final_state) # Return decision and processed signal return final_state, self.process_signal(final_state["final_trade_decision"]) def _log_state(self, trade_date, final_state): """Log the final state to a JSON file.""" self.log_states_dict[str(trade_date)] = { "company_of_interest": final_state["company_of_interest"], "trade_date": final_state["trade_date"], "market_report": final_state["market_report"], "sentiment_report": final_state["sentiment_report"], "news_report": final_state["news_report"], "fundamentals_report": final_state["fundamentals_report"], "investment_debate_state": { "bull_history": final_state["investment_debate_state"]["bull_history"], "bear_history": final_state["investment_debate_state"]["bear_history"], "history": final_state["investment_debate_state"]["history"], "current_response": final_state["investment_debate_state"][ "current_response" ], "judge_decision": final_state["investment_debate_state"][ "judge_decision" ], }, "trader_investment_decision": final_state["trader_investment_plan"], "risk_debate_state": { "aggressive_history": final_state["risk_debate_state"]["aggressive_history"], "conservative_history": final_state["risk_debate_state"]["conservative_history"], "neutral_history": final_state["risk_debate_state"]["neutral_history"], "history": final_state["risk_debate_state"]["history"], "judge_decision": final_state["risk_debate_state"]["judge_decision"], }, "investment_plan": final_state["investment_plan"], "final_trade_decision": final_state["final_trade_decision"], } # Save to file directory = Path(f"eval_results/{self.ticker}/TradingAgentsStrategy_logs/") directory.mkdir(parents=True, exist_ok=True) with open( f"eval_results/{self.ticker}/TradingAgentsStrategy_logs/full_states_log_{trade_date}.json", "w", ) as f: json.dump(self.log_states_dict, f, indent=4) def reflect_and_remember(self, returns_losses): """Reflect on decisions and update memory based on returns.""" self.reflector.reflect_bull_researcher( self.curr_state, returns_losses, self.bull_memory ) self.reflector.reflect_bear_researcher( self.curr_state, returns_losses, self.bear_memory ) self.reflector.reflect_trader( self.curr_state, returns_losses, self.trader_memory ) self.reflector.reflect_invest_judge( self.curr_state, returns_losses, self.invest_judge_memory ) self.reflector.reflect_risk_manager( self.curr_state, returns_losses, self.risk_manager_memory ) def process_signal(self, full_signal): """Process a signal to extract the core decision.""" return self.signal_processor.process_signal(full_signal)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/graph/trading_graph.py", "license": "Apache License 2.0", "lines": 243, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/rich:tests/test_unicode_data.py
from __future__ import annotations import pytest from rich._unicode_data import VERSIONS, _parse_version, load def test_load(): """Test all versions may be loaded.""" for version in VERSIONS: load(version) @pytest.mark.parametrize( "version_str,version_tuple", [ ("1", (1, 0, 0)), ("1.0", (1, 0, 0)), ("1.2", (1, 2, 0)), ("1.2.3", (1, 2, 3)), ], ) def test_parse_version(version_str: str, version_tuple: tuple[str, ...]) -> None: assert _parse_version(version_str) == version_tuple @pytest.mark.parametrize( "version_in,version_selected", [ # Lower versions will pick the first (4.1.0) ("0", "4.1.0"), ("1", "4.1.0"), ("1.0", "4.1.0"), ("1.0.0", "4.1.0"), ("4.0.0", "4.1.0"), ("4.0.2", "4.1.0"), ("4.1.0", "4.1.0"), ("4.1.1", "4.1.0"), ("4.2.1", "4.1.0"), # Nearest version lower ("5", "5.0.0"), ("5.0", "5.0.0"), ("5.0.0", "5.0.0"), ("5.0.1", "5.0.0"), ("5.1.0", "5.1.0"), ("5.1.1", "5.1.0"), # Maximum version if greater than the maximum ("17.0.0", "17.0.0"), ("17.0.1", "17.0.0"), ("17.1.0", "17.0.0"), # Greater than the maximum ("18.0.0", "17.0.0"), ], ) def test_load_version(version_in: str, version_selected: str) -> None: """Test that load will pick the nearest lower version if it exists, or the lowest version if below the first available version.""" assert load(version_in).unicode_version == version_selected def test_load_version_invalid() -> None: """Check that invalid versions load the latest unicode data.""" assert load("foo").unicode_version == "17.0.0" assert load("a.b.c").unicode_version == "17.0.0" assert load("1.2.3a").unicode_version == "17.0.0"
{ "repo_id": "Textualize/rich", "file_path": "tests/test_unicode_data.py", "license": "MIT License", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/rich:tools/make_width_tables.py
import subprocess from pathlib import Path from wcwidth import list_versions from wcwidth.table_vs16 import VS16_NARROW_TO_WIDE from wcwidth.table_wide import WIDE_EASTASIAN from wcwidth.table_zero import ZERO_WIDTH from rich.cells import CellTable UNICODE_VERSIONS: list[str] = list_versions() path = Path("../rich/_unicode_data/_versions.py").resolve().absolute() init = f"""\ VERSIONS = {UNICODE_VERSIONS!r} """ with open(path, "wt") as init_file: init_file.write(init) subprocess.run(f"black {path}", shell=True) narrow_to_wide: set[str] = set() for start, end in VS16_NARROW_TO_WIDE["9.0.0"]: narrow_to_wide.update(chr(codepoint) for codepoint in range(start, end + 1)) for version in UNICODE_VERSIONS: table: list[tuple[int, int, int]] = [] wide_east_asian: list[tuple[int, int]] = WIDE_EASTASIAN.get(version, []) for start, end in wide_east_asian: table.append((start, end, 2)) zero_wide: list[tuple[int, int]] = ZERO_WIDTH.get(version, []) for start, end in zero_wide: table.append((start, end, 0)) table.sort() cell_table = CellTable(version, table, frozenset(narrow_to_wide)) table_file = f"""# Auto generated by tools/make_width_tables.py # Data from wcwidth project (https://github.com/jquast/wcwidth) from rich.cells import CellTable cell_table = CellTable({cell_table.unicode_version!r}, {cell_table.widths!r}, frozenset({sorted(cell_table.narrow_to_wide)!r})) """ version_path = version.replace(".", "-") path = Path(f"../rich/_unicode_data/unicode{version_path}.py").resolve().absolute() with open(path, "wt") as file_out: file_out.write(table_file) subprocess.run(f"black {path}", shell=True)
{ "repo_id": "Textualize/rich", "file_path": "tools/make_width_tables.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:tests/snapshot_tests/snapshot_apps/sparkline.py
import random from statistics import mean from textual.app import App, ComposeResult from textual.widgets import Sparkline random.seed(73) data = [random.expovariate(1 / 3) for _ in range(1000)] class SparklineApp(App[None]): DEFAULT_CSS = """ SparklineApp { Sparkline { height: 1fr; } } """ def compose(self) -> ComposeResult: yield Sparkline(data, summary_function=max) yield Sparkline(data, summary_function=mean) yield Sparkline(data, summary_function=min) if __name__ == "__main__": app = SparklineApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "tests/snapshot_tests/snapshot_apps/sparkline.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:tests/layouts/test_grid.py
from textual import containers, widgets from textual.app import App, ComposeResult from textual.layouts.grid import GridLayout async def test_grid_size(): """Test the `grid_size` property on GridLayout.""" class GridApp(App): CSS = """ Grid { grid-size: 3; grid-columns: auto; height: auto; Label { padding: 2 4; border: blue; } } """ def compose(self) -> ComposeResult: with containers.VerticalScroll(): with containers.Grid(): for _ in range(7): yield widgets.Label("Hello, World!") app = GridApp() async with app.run_test() as pilot: await pilot.pause() await app.wait_for_refresh() grid_layout = app.query_one(containers.Grid).layout assert isinstance(grid_layout, GridLayout) assert grid_layout.grid_size == (3, 3)
{ "repo_id": "Textualize/textual", "file_path": "tests/layouts/test_grid.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:docs/examples/styles/scrollbar_visibility.py
from textual.app import App from textual.containers import Horizontal, VerticalScroll from textual.widgets import Label TEXT = """I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past, I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Only I will remain. """ class ScrollbarApp(App): CSS_PATH = "scrollbar_visibility.tcss" def compose(self): yield Horizontal( VerticalScroll(Label(TEXT * 10), classes="left"), VerticalScroll(Label(TEXT * 10), classes="right"), ) if __name__ == "__main__": app = ScrollbarApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/styles/scrollbar_visibility.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:tests/test_selection.py
import pytest from textual.app import App, ComposeResult from textual.geometry import Offset from textual.selection import Selection from textual.widgets import Static @pytest.mark.parametrize( "text,selection,expected", [ ("Hello", Selection(None, None), "Hello"), ("Hello\nWorld", Selection(None, None), "Hello\nWorld"), ("Hello\nWorld", Selection(Offset(0, 1), None), "World"), ("Hello\nWorld", Selection(None, Offset(5, 0)), "Hello"), ("Foo", Selection(Offset(0, 0), Offset(1, 0)), "F"), ("Foo", Selection(Offset(1, 0), Offset(2, 0)), "o"), ("Foo", Selection(Offset(0, 0), Offset(2, 0)), "Fo"), ("Foo", Selection(Offset(0, 0), None), "Foo"), ], ) def test_extract(text: str, selection: Selection, expected: str) -> None: """Test Selection.extract""" assert selection.extract(text) == expected async def test_double_width(): """Test that selection works with double width characters.""" TEXT = """😂❤️👍Select😊🙏😍\nme🔥💯😭😂❤️👍""" class TextSelectApp(App): def compose(self) -> ComposeResult: yield Static(TEXT) app = TextSelectApp() async with app.run_test() as pilot: await pilot.pause() assert await pilot.mouse_down(offset=(2, 0)) await pilot.pause() assert await pilot.mouse_up(offset=(7, 1)) selected_text = app.screen.get_selected_text() expected = "❤️👍Select😊🙏😍\nme🔥💯😭" assert selected_text == expected
{ "repo_id": "Textualize/textual", "file_path": "tests/test_selection.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:src/textual/_queue.py
from __future__ import annotations import asyncio from asyncio import Event from collections import deque from typing import Generic, TypeVar QueueType = TypeVar("QueueType") class Queue(Generic[QueueType]): """A cut-down version of asyncio.Queue This has just enough functionality to run the message pumps. """ def __init__(self) -> None: self.values: deque[QueueType] = deque() self.ready_event = Event() def put_nowait(self, value: QueueType) -> None: self.values.append(value) self.ready_event.set() def qsize(self) -> int: return len(self.values) def empty(self) -> bool: return not self.values def task_done(self) -> None: pass async def get(self) -> QueueType: if not self.ready_event.is_set(): await self.ready_event.wait() value = self.values.popleft() if not self.values: self.ready_event.clear() return value def get_nowait(self) -> QueueType: if not self.values: raise asyncio.QueueEmpty() value = self.values.popleft() if not self.values: self.ready_event.clear() return value
{ "repo_id": "Textualize/textual", "file_path": "src/textual/_queue.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:src/textual/demo/_project_data.py
from dataclasses import dataclass @dataclass class ProjectInfo: """Dataclass for storing project information.""" title: str author: str url: str description: str repo_url_part: str PROJECTS = [ ProjectInfo( "Posting", "Darren Burns", "https://posting.sh/", "Posting is an HTTP client, not unlike Postman and Insomnia. As a TUI application, it can be used over SSH and enables efficient keyboard-centric workflows. ", "darrenburns/posting", ), ProjectInfo( "Memray", "Bloomberg", "https://github.com/bloomberg/memray", "Memray is a memory profiler for Python. It can track memory allocations in Python code, in native extension modules, and in the Python interpreter itself.", "bloomberg/memray", ), ProjectInfo( "Toolong", "Will McGugan", "https://github.com/Textualize/toolong", "A terminal application to view, tail, merge, and search log files (plus JSONL).", "Textualize/toolong", ), ProjectInfo( "Dolphie", "Charles Thompson", "https://github.com/charles-001/dolphie", "Your single pane of glass for real-time analytics into MySQL/MariaDB & ProxySQL", "charles-001/dolphie", ), ProjectInfo( "Harlequin", "Ted Conbeer", "https://harlequin.sh/", "Portable, powerful, colorful. An easy, fast, and beautiful database client for the terminal.", "tconbeer/harlequin", ), ProjectInfo( "Elia", "Darren Burns", "https://github.com/darrenburns/elia", "A snappy, keyboard-centric terminal user interface for interacting with large language models.", "darrenburns/elia", ), ProjectInfo( "Trogon", "Textualize", "https://github.com/Textualize/trogon", "Auto-generate friendly terminal user interfaces for command line apps.", "Textualize/trogon", ), ProjectInfo( "TFTUI - The Terraform textual UI", "Ido Avraham", "https://github.com/idoavrah/terraform-tui", "TFTUI is a powerful textual UI that empowers users to effortlessly view and interact with their Terraform state.", "idoavrah/terraform-tui", ), ProjectInfo( "RecoverPy", "Pablo Lecolinet", "https://github.com/PabloLec/RecoverPy", "RecoverPy is a powerful tool that leverages your system capabilities to recover lost files.", "PabloLec/RecoverPy", ), ProjectInfo( "Frogmouth", "Dave Pearson", "https://github.com/Textualize/frogmouth", "Frogmouth is a Markdown viewer / browser for your terminal, built with Textual.", "Textualize/frogmouth", ), ProjectInfo( "oterm", "Yiorgis Gozadinos", "https://github.com/ggozad/oterm", "The text-based terminal client for Ollama.", "ggozad/oterm", ), ProjectInfo( "logmerger", "Paul McGuire", "https://github.com/ptmcg/logmerger", "logmerger is a TUI for viewing a merged display of multiple log files, merged by timestamp.", "ptmcg/logmerger", ), ProjectInfo( "doit", "Murli Tawari", "https://github.com/dooit-org/dooit", "A todo manager that you didn't ask for, but needed!", "dooit-org/dooit", ), ]
{ "repo_id": "Textualize/textual", "file_path": "src/textual/demo/_project_data.py", "license": "MIT License", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/textual:src/textual/demo/_project_stargazer_updater.py
import httpx import os import json from rich.console import Console # Not using the Absolute reference because # I can't get python to run it. from _project_data import PROJECTS console = Console() error_console = Console(stderr=True, style="bold red") def main() -> None: STARS = {} for project in PROJECTS: # get each repo console.log(f"Checking {project.repo_url_part}") response = httpx.get(f"https://api.github.com/repos/{project.repo_url_part}") if response.status_code == 200: # get stargazers stargazers = response.json()["stargazers_count"] if stargazers // 1000 != 0: # humanize them stargazers = f"{stargazers / 1000:.1f}k" else: stargazers = str(stargazers) STARS[project.title] = stargazers elif response.status_code == 403: # gh api rate limited error_console.log( "GitHub has received too many requests and started rate limiting." ) exit(1) else: # any other reason print( f"GET https://api.github.com/repos/{project.repo_url_part} returned status code {response.status_code}" ) # replace with open( os.path.join(os.path.dirname(__file__), "_project_stars.py"), "w" ) as file: file.write("STARS = " + json.dumps(STARS, indent=4)) console.log("Done!") if __name__ == "__main__": main()
{ "repo_id": "Textualize/textual", "file_path": "src/textual/demo/_project_stargazer_updater.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:src/textual/demo/_project_stars.py
STARS = { "Posting": "11.4k", "Memray": "14.9k", "Toolong": "3.9k", "Dolphie": "1.1k", "Harlequin": "5.8k", "Elia": "2.4k", "Trogon": "2.8k", "TFTUI - The Terraform textual UI": "1.3k", "RecoverPy": "1.7k", "Frogmouth": "3.1k", "oterm": "2.3k", "logmerger": "250", "doit": "2.8k", }
{ "repo_id": "Textualize/textual", "file_path": "src/textual/demo/_project_stars.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:src/textual/getters.py
""" Descriptors to define properties on your widget, screen, or App. """ from __future__ import annotations from inspect import isclass from typing import TYPE_CHECKING, Callable, Generic, TypeVar, overload from textual._context import NoActiveAppError, active_app from textual.css.query import NoMatches, QueryType, WrongType from textual.widget import Widget if TYPE_CHECKING: from textual.app import App from textual.dom import DOMNode from textual.message_pump import MessagePump AppType = TypeVar("AppType", bound="App") class app(Generic[AppType]): """Create a property to return the active app. All widgets have a default `app` property which returns an App instance. Type checkers will complain if you try to access attributes defined on your App class, which aren't present in the base class. To keep the type checker happy you can add this property to get your specific App subclass. Example: ```python class MyWidget(Widget): app = getters.app(MyApp) ``` Args: app_type: The App subclass, or a callable which returns an App subclass. """ def __init__(self, app_type: type[AppType] | Callable[[], type[AppType]]) -> None: self._app_type = app_type if isclass(app_type) else app_type() def __get__(self, obj: MessagePump, obj_type: type[MessagePump]) -> AppType: try: app = active_app.get() except LookupError: from textual.app import App node: MessagePump | None = obj while not isinstance(node, App): if node is None: raise NoActiveAppError() node = node._parent app = node assert isinstance(app, self._app_type) return app class query_one(Generic[QueryType]): """Create a query one property. A query one property calls [Widget.query_one][textual.dom.DOMNode.query_one] when accessed, and returns a widget. If the widget doesn't exist, then the property will raise the same exceptions as `Widget.query_one`. Example: ```python from textual import getters class MyScreen(screen): # Note this is at the class level output_log = getters.query_one("#output", RichLog) def compose(self) -> ComposeResult: with containers.Vertical(): yield RichLog(id="output") def on_mount(self) -> None: self.output_log.write("Screen started") # Equivalent to the following line: # self.query_one("#output", RichLog).write("Screen started") ``` Args: selector: A TCSS selector, e.g. "#mywidget". Or a widget type, i.e. `Input`. expect_type: The type of the expected widget, e.g. `Input`, if the first argument is a selector. """ selector: str expect_type: type["Widget"] @overload def __init__(self, selector: str) -> None: """ Args: selector: A TCSS selector, e.g. "#mywidget" """ @overload def __init__(self, selector: type[QueryType]) -> None: ... @overload def __init__(self, selector: str, expect_type: type[QueryType]) -> None: ... @overload def __init__( self, selector: type[QueryType], expect_type: type[QueryType] ) -> None: ... def __init__( self, selector: str | type[QueryType], expect_type: type[QueryType] | None = None, ) -> None: if expect_type is None: from textual.widget import Widget self.expect_type = Widget else: self.expect_type = expect_type if isinstance(selector, str): self.selector = selector else: self.selector = selector.__name__ self.expect_type = selector @overload def __get__( self: "query_one[QueryType]", obj: DOMNode, obj_type: type[DOMNode] ) -> QueryType: ... @overload def __get__( self: "query_one[QueryType]", obj: None, obj_type: type[DOMNode] ) -> "query_one[QueryType]": ... def __get__( self: "query_one[QueryType]", obj: DOMNode | None, obj_type: type[DOMNode] ) -> QueryType | Widget | "query_one": """Get the widget matching the selector and/or type.""" if obj is None: return self query_node = obj.query_one(self.selector, self.expect_type) return query_node class child_by_id(Generic[QueryType]): """Create a child_by_id property, which returns the child with the given ID. This is similar using [query_one][textual.getters.query_one] with an id selector, except that only the immediate children are considered. It is also more efficient as it doesn't need to search the DOM. Example: ```python from textual import getters class MyScreen(screen): # Note this is at the class level output_log = getters.child_by_id("output", RichLog) def compose(self) -> ComposeResult: yield RichLog(id="output") def on_mount(self) -> None: self.output_log.write("Screen started") ``` Args: child_id: The `id` of the widget to get (not a selector). expect_type: The type of the expected widget, e.g. `Input`. """ child_id: str expect_type: type[Widget] @overload def __init__(self, child_id: str) -> None: ... @overload def __init__(self, child_id: str, expect_type: type[QueryType]) -> None: ... def __init__( self, child_id: str, expect_type: type[QueryType] | None = None, ) -> None: if expect_type is None: self.expect_type = Widget else: self.expect_type = expect_type self.child_id = child_id @overload def __get__( self: "child_by_id[QueryType]", obj: DOMNode, obj_type: type[DOMNode] ) -> QueryType: ... @overload def __get__( self: "child_by_id[QueryType]", obj: None, obj_type: type[DOMNode] ) -> "child_by_id[QueryType]": ... def __get__( self: "child_by_id[QueryType]", obj: DOMNode | None, obj_type: type[DOMNode] ) -> QueryType | Widget | "child_by_id": """Get the widget matching the selector and/or type.""" if obj is None: return self child = obj._get_dom_base()._nodes._get_by_id(self.child_id) if child is None: raise NoMatches(f"No child found with id={self.child_id!r}") if not isinstance(child, self.expect_type): raise WrongType( f"Child with id={self.child_id!r} is the wrong type; expected type {self.expect_type.__name__!r}, found {child}" ) return child
{ "repo_id": "Textualize/textual", "file_path": "src/textual/getters.py", "license": "MIT License", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/textual:src/textual/layouts/stream.py
from __future__ import annotations from itertools import zip_longest from typing import TYPE_CHECKING from textual.geometry import NULL_OFFSET, Region, Size from textual.layout import ArrangeResult, Layout, WidgetPlacement if TYPE_CHECKING: from textual.widget import Widget class StreamLayout(Layout): """A cut down version of the vertical layout. The stream layout is faster, but has a few limitations compared to the vertical layout. - All widgets are the full width (as if their widget is `1fr`). - All widgets have an effective height of `auto`. - `max-height` is supported, but only if it is a units value, all other extrema rules are ignored. - No absolute positioning. - No overlay: screen. - Layers are ignored. - Non TCSS styles are ignored. The primary use of `layout: stream` is for a long list of widgets in a scrolling container, such as what you might expect from a LLM chat-bot. The speed improvement will only be significant with a lot of child widgets, so stick to vertical layouts unless you see any slowdown. """ name = "stream" def __init__(self) -> None: self._cached_placements: list[WidgetPlacement] | None = None self._cached_width = 0 super().__init__() def arrange( self, parent: Widget, children: list[Widget], size: Size, greedy: bool = True ) -> ArrangeResult: parent.pre_layout(self) if not children: return [] viewport = parent.app.viewport_size if size.width != self._cached_width: self._cached_placements = None previous_results = self._cached_placements or [] layout_widgets = parent.screen._layout_widgets.get(parent, []) _Region = Region _WidgetPlacement = WidgetPlacement placements: list[WidgetPlacement] = [] width = size.width first_child_styles = children[0].styles y = 0 previous_margin = first_child_styles.margin.top null_offset = NULL_OFFSET pre_populate = bool(previous_results and layout_widgets) for widget, placement in zip_longest(children, previous_results): if pre_populate and placement is not None and widget is placement.widget: if widget in layout_widgets: pre_populate = False else: placements.append(placement) y = placement.region.bottom styles = widget.styles._base_styles previous_margin = styles.margin.bottom continue if widget is None: break styles = widget.styles._base_styles margin = styles.margin gutter_width, gutter_height = styles.gutter.totals top, right, bottom, left = margin y += top if top > previous_margin else previous_margin previous_margin = bottom height = ( widget.get_content_height(size, viewport, width - gutter_width) + gutter_height ) if (max_height := styles.max_height) is not None and max_height.is_cells: height = ( height if height < (max_height_value := int(max_height.value)) else max_height_value ) if (min_height := styles.min_height) is not None and min_height.is_cells: height = ( height if height > (min_height_value := int(min_height.value)) else min_height_value ) placements.append( _WidgetPlacement( _Region(left, y, width - (left + right), height), null_offset, margin, widget, 0, False, False, False, ) ) y += height self._cached_width = size.width self._cached_placements = placements return placements def get_content_width(self, widget: Widget, container: Size, viewport: Size) -> int: """Get the optimal content width by arranging children. Args: widget: The container widget. container: The container size. viewport: The viewport size. Returns: Width of the content. """ return widget.scrollable_content_region.width def get_content_height( self, widget: Widget, container: Size, viewport: Size, width: int ) -> int: """Get the content height. Args: widget: The container widget. container: The container size. viewport: The viewport. width: The content width. Returns: Content height (in lines). """ if widget._nodes: arrangement = widget.arrange(Size(width, 0)) height = arrangement.total_region.height else: height = 0 return height
{ "repo_id": "Textualize/textual", "file_path": "src/textual/layouts/stream.py", "license": "MIT License", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/textual:tests/test_filters.py
from rich.color import Color as RichColor from rich.color import ColorType from rich.segment import Segment from rich.style import Style from rich.terminal_theme import MONOKAI from textual.color import Color from textual.filter import ANSIToTruecolor def test_ansi_to_truecolor_8_bit_dim(): """Test that converting an 8-bit color with dim doesn't crash. Regression test for https://github.com/Textualize/textual/issues/5946 """ # Given ansi_filter = ANSIToTruecolor(MONOKAI) test_color = RichColor("color(253)", ColorType.EIGHT_BIT, number=253) test_style = Style(color=test_color, dim=True) segments = [Segment("This should not crash", style=test_style)] background_color = Color(0, 0, 0) # When # This line will crash if the bug is present new_segments = ansi_filter.apply(segments, background_color) # Then assert new_segments is not None
{ "repo_id": "Textualize/textual", "file_path": "tests/test_filters.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:tests/test_getters.py
import pytest from textual import containers, getters from textual.app import App, ComposeResult from textual.css.query import NoMatches, WrongType from textual.widget import Widget from textual.widgets import Input, Label async def test_getters() -> None: """Check the getter descriptors work, and return expected errors.""" class QueryApp(App): label1 = getters.query_one("#label1", Label) label2 = getters.child_by_id("label2", Label) label1_broken = getters.query_one("#label1", Input) label2_broken = getters.child_by_id("label2", Input) label1_missing = getters.query_one("#foo", Widget) label2_missing = getters.child_by_id("bar", Widget) def compose(self) -> ComposeResult: with containers.Vertical(): yield Label(id="label1", classes="red") yield Label(id="label2", classes="green") app = QueryApp() async with app.run_test(): assert isinstance(app.label1, Label) assert app.label1.id == "label1" assert isinstance(app.label2, Label) assert app.label2.id == "label2" with pytest.raises(WrongType): app.label1_broken with pytest.raises(WrongType): app.label2_broken with pytest.raises(NoMatches): app.label1_missing with pytest.raises(NoMatches): app.label2_missing async def test_app_getter() -> None: class MyApp(App): def compose(self) -> ComposeResult: my_widget = MyWidget() my_widget.app yield my_widget class MyWidget(Widget): app = getters.app(MyApp) app = MyApp() async with app.run_test(): assert isinstance(app.query_one(MyWidget).app, MyApp)
{ "repo_id": "Textualize/textual", "file_path": "tests/test_getters.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:tests/test_highlight.py
import pytest from textual.content import Span from textual.highlight import guess_language, highlight def test_highlight() -> None: """Test simple application of highlight.""" import_this = highlight("import this", language="python") assert import_this.plain == "import this" print(import_this.spans) assert import_this.spans == [ Span(0, 11, style="$text"), Span(0, 6, style="$text-error"), Span(7, 11, style="$text-primary"), ] @pytest.mark.parametrize( "code,path,language", [ ("", "", "default"), ("# Don't matter", "foo.tcss", "scss"), ("import this", "foo.py", "python"), ("<xml>", "foo.xml", "xml"), ("{}", "data.json", "json"), ("#! python", "", "python"), ("", "foo.py", "python"), ], ) def test_guess_language(code: str, path: str, language: str) -> None: """Test guess_language is working.""" assert guess_language(code, path) == language
{ "repo_id": "Textualize/textual", "file_path": "tests/test_highlight.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:tests/test_static.py
from textual.content import Content from textual.widgets import Static async def test_content_property(): static = Static() assert static.content == "" static.content = "Foo" assert static.content == "Foo" assert isinstance(static.content, str) assert static.visual == "Foo" assert isinstance(static.visual, Content) static.update("Hello") assert static.content == "Hello" assert isinstance(static.content, str) assert static.visual == "Hello" assert isinstance(static.visual, Content)
{ "repo_id": "Textualize/textual", "file_path": "tests/test_static.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:src/textual/compose.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from textual.app import App, ComposeResult from textual.widget import Widget __all__ = ["compose"] def compose( node: App | Widget, compose_result: ComposeResult | None = None ) -> list[Widget]: """Compose child widgets from a generator in the same way as [compose][textual.widget.Widget.compose]. Example: ```python def on_key(self, event:events.Key) -> None: def add_key(key:str) -> ComposeResult: with containers.HorizontalGroup(): yield Label("You pressed:") yield Label(key) self.mount_all( compose(self, add_key(event.key)), ) ``` Args: node: The parent node. compose_result: A compose result, or `None` to call `node.compose()`. Returns: A list of widgets. """ _rich_traceback_omit = True from textual.widget import MountError, Widget app = node.app nodes: list[Widget] = [] compose_stack: list[Widget] = [] composed: list[Widget] = [] app._compose_stacks.append(compose_stack) app._composed.append(composed) iter_compose = iter( compose_result if compose_result is not None else node.compose() ) is_generator = hasattr(iter_compose, "throw") try: while True: try: child = next(iter_compose) except StopIteration: break if not isinstance(child, Widget): mount_error = MountError( f"Can't mount {type(child)}; expected a Widget instance." ) if is_generator: iter_compose.throw(mount_error) # type: ignore else: raise mount_error from None try: child.id except AttributeError: mount_error = MountError( "Widget is missing an 'id' attribute; did you forget to call super().__init__()?" ) if is_generator: iter_compose.throw(mount_error) # type: ignore else: raise mount_error from None if composed: nodes.extend(composed) composed.clear() if compose_stack: try: compose_stack[-1].compose_add_child(child) except Exception as error: if is_generator: # So the error is raised inside the generator # This will generate a more sensible traceback for the dev iter_compose.throw(error) # type: ignore else: raise else: nodes.append(child) if composed: nodes.extend(composed) composed.clear() finally: app._compose_stacks.pop() app._composed.pop() return nodes
{ "repo_id": "Textualize/textual", "file_path": "src/textual/compose.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/textual:docs/examples/how-to/containers01.py
from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" def compose(self) -> ComposeResult: with Horizontal(): # (1)! yield Box() # (2)! yield Box() yield Box() if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers01.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:docs/examples/how-to/containers02.py
from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" def compose(self) -> ComposeResult: with Vertical(): # (1)! yield Box() yield Box() yield Box() if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers02.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Textualize/textual:docs/examples/how-to/containers03.py
from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with Horizontal(classes="with-border"): # (1)! yield Box() yield Box() yield Box() if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers03.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers04.py
from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with Horizontal(classes="with-border"): yield Box() yield Box() yield Box() with Horizontal(classes="with-border"): yield Box() yield Box() yield Box() if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers04.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers05.py
from textual.app import App, ComposeResult from textual.containers import HorizontalGroup from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with HorizontalGroup(classes="with-border"): yield Box() yield Box() yield Box() with HorizontalGroup(classes="with-border"): yield Box() yield Box() yield Box() if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers05.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers06.py
from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with Horizontal(classes="with-border"): for n in range(10): yield Box(label=f"Box {n+1}") if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers06.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers07.py
from textual.app import App, ComposeResult from textual.containers import HorizontalScroll from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 8; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with HorizontalScroll(classes="with-border"): for n in range(10): yield Box(label=f"Box {n+1}") if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers07.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers08.py
from textual.app import App, ComposeResult from textual.containers import Center, Right from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 5; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: yield Box("Box 1") # (1)! with Center(classes="with-border"): # (2)! yield Box("Box 2") with Right(classes="with-border"): # (3)! yield Box("Box 3") if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers08.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:docs/examples/how-to/containers09.py
from textual.app import App, ComposeResult from textual.containers import Middle from textual.widgets import Placeholder class Box(Placeholder): """Example widget.""" DEFAULT_CSS = """ Box { width: 16; height: 5; } """ class ContainerApp(App): """Simple app to play with containers.""" CSS = """ .with-border { border: heavy green; } """ def compose(self) -> ComposeResult: with Middle(classes="with-border"): # (1)! yield Box("Box 1.") yield Box("Box 2.") yield Box("Box 3.") if __name__ == "__main__": app = ContainerApp() app.run()
{ "repo_id": "Textualize/textual", "file_path": "docs/examples/how-to/containers09.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Textualize/textual:tests/test_logger.py
import inspect from typing import Any from textual import work from textual._log import LogGroup, LogVerbosity from textual.app import App async def test_log_from_worker() -> None: """Check that log calls from threaded workers call app._log""" log_messages: list[tuple] = [] class LogApp(App): def _log( self, group: LogGroup, verbosity: LogVerbosity, _textual_calling_frame: inspect.Traceback, *objects: Any, **kwargs, ) -> None: log_messages.append(objects) @property def _is_devtools_connected(self): """Fake connected devtools.""" return True def on_mount(self) -> None: self.do_work() self.call_after_refresh(self.exit) @work(thread=True) def do_work(self) -> None: self.log("HELLO from do_work") app = LogApp() async with app.run_test() as pilot: await pilot.pause() assert ("HELLO from do_work",) in log_messages
{ "repo_id": "Textualize/textual", "file_path": "tests/test_logger.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
Textualize/textual:src/textual/_compat.py
from __future__ import annotations import sys from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 12): from functools import cached_property else: # based on the code from Python 3.14: # https://github.com/python/cpython/blob/ # 5507eff19c757a908a2ff29dfe423e35595fda00/Lib/functools.py#L1089-L1138 # Copyright (C) 2006 Python Software Foundation. # vendored under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 because # prior to Python 3.12 cached_property used a threading.Lock, which makes # it very slow. _T_co = TypeVar("_T_co", covariant=True) _NOT_FOUND = object() class cached_property(Generic[_T_co]): def __init__(self, func: Callable[[Any, _T_co]]) -> None: self.func = func self.attrname = None self.__doc__ = func.__doc__ self.__module__ = func.__module__ def __set_name__(self, owner: type[any], name: str) -> None: if self.attrname is None: self.attrname = name elif name != self.attrname: raise TypeError( "Cannot assign the same cached_property to two different names " f"({self.attrname!r} and {name!r})." ) @overload def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... @overload def __get__( self, instance: object, owner: type[Any] | None = None ) -> _T_co: ... def __get__( self, instance: object, owner: type[Any] | None = None ) -> _T_co | Self: if instance is None: return self if self.attrname is None: raise TypeError( "Cannot use cached_property instance without calling __set_name__ on it." ) try: cache = instance.__dict__ except ( AttributeError ): # not all objects have __dict__ (e.g. class defines slots) msg = ( f"No '__dict__' attribute on {type(instance).__name__!r} " f"instance to cache {self.attrname!r} property." ) raise TypeError(msg) from None val = cache.get(self.attrname, _NOT_FOUND) if val is _NOT_FOUND: val = self.func(instance) try: cache[self.attrname] = val except TypeError: msg = ( f"The '__dict__' attribute on {type(instance).__name__!r} instance " f"does not support item assignment for caching {self.attrname!r} property." ) raise TypeError(msg) from None return val
{ "repo_id": "Textualize/textual", "file_path": "src/textual/_compat.py", "license": "MIT License", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Textualize/textual:examples/breakpoints.py
from textual.app import App, ComposeResult from textual.containers import Grid from textual.widgets import Footer, Markdown, Placeholder HELP = """\ ## Breakpoints A demonstration of how to make an app respond to the dimensions of the terminal. Try resizing the terminal, then have a look at the source to see how it works! """ class BreakpointApp(App): # A breakpoint consists of a width and a class name to set HORIZONTAL_BREAKPOINTS = [ (0, "-narrow"), (40, "-normal"), (80, "-wide"), (120, "-very-wide"), ] CSS = """ Screen { Placeholder { padding: 2; } Grid { grid-rows: auto; height: auto; } # Change the styles according to the breakpoint classes &.-narrow { Grid { grid-size: 1; } } &.-normal { Grid { grid-size: 2; } } &.-wide { Grid { grid-size: 4; } } &.-very-wide { Grid { grid-size: 6; } } } """ def compose(self) -> ComposeResult: yield Markdown(HELP) with Grid(): for n in range(16): yield Placeholder(f"Placeholder {n+1}") yield Footer() if __name__ == "__main__": BreakpointApp().run()
{ "repo_id": "Textualize/textual", "file_path": "examples/breakpoints.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:other/sliding_window_maximum.py
from collections import deque def sliding_window_maximum(numbers: list[int], window_size: int) -> list[int]: """ Return a list containing the maximum of each sliding window of size window_size. This implementation uses a monotonic deque to achieve O(n) time complexity. Args: numbers: List of integers representing the input array. window_size: Size of the sliding window (must be positive). Returns: List of maximum values for each valid window. Raises: ValueError: If window_size is not a positive integer. Time Complexity: O(n) - each element is added and removed at most once Space Complexity: O(k) - deque stores at most window_size indices Examples: >>> sliding_window_maximum([1, 3, -1, -3, 5, 3, 6, 7], 3) [3, 3, 5, 5, 6, 7] >>> sliding_window_maximum([9, 11], 2) [11] >>> sliding_window_maximum([], 3) [] >>> sliding_window_maximum([4, 2, 12, 3], 1) [4, 2, 12, 3] >>> sliding_window_maximum([1], 1) [1] """ if window_size <= 0: raise ValueError("Window size must be a positive integer") if not numbers: return [] result: list[int] = [] index_deque: deque[int] = deque() for current_index, current_value in enumerate(numbers): # Remove the element which is out of this window if index_deque and index_deque[0] == current_index - window_size: index_deque.popleft() # Remove useless elements (smaller than current) from back while index_deque and numbers[index_deque[-1]] < current_value: index_deque.pop() index_deque.append(current_index) # Start adding to result once we have a full window if current_index >= window_size - 1: result.append(numbers[index_deque[0]]) return result
{ "repo_id": "TheAlgorithms/Python", "file_path": "other/sliding_window_maximum.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:dynamic_programming/narcissistic_number.py
""" Find all narcissistic numbers up to a given limit using dynamic programming. A narcissistic number (also known as an Armstrong number or plus perfect number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is a narcissistic number because 153 = 1^3 + 5^3 + 3^3. This implementation uses dynamic programming with memoization to efficiently compute digit powers and find all narcissistic numbers up to a specified limit. The DP optimization caches digit^power calculations. When searching through many numbers, the same digit power calculations occur repeatedly (e.g., 153, 351, 135 all need 1^3, 5^3, 3^3). Memoization avoids these redundant calculations. Examples of narcissistic numbers: Single digit: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Three digit: 153, 370, 371, 407 Four digit: 1634, 8208, 9474 Five digit: 54748, 92727, 93084 Reference: https://en.wikipedia.org/wiki/Narcissistic_number """ def find_narcissistic_numbers(limit: int) -> list[int]: """ Find all narcissistic numbers up to the given limit using dynamic programming. This function uses memoization to cache digit power calculations, avoiding redundant computations across different numbers with the same digit count. Args: limit: The upper bound for searching narcissistic numbers (exclusive) Returns: list[int]: A sorted list of all narcissistic numbers below the limit Examples: >>> find_narcissistic_numbers(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> find_narcissistic_numbers(160) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153] >>> find_narcissistic_numbers(400) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371] >>> find_narcissistic_numbers(1000) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407] >>> find_narcissistic_numbers(10000) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474] >>> find_narcissistic_numbers(1) [0] >>> find_narcissistic_numbers(0) [] """ if limit <= 0: return [] narcissistic_nums = [] # Memoization: cache[(power, digit)] = digit^power # This avoids recalculating the same power for different numbers power_cache: dict[tuple[int, int], int] = {} def get_digit_power(digit: int, power: int) -> int: """Get digit^power using memoization (DP optimization).""" if (power, digit) not in power_cache: power_cache[(power, digit)] = digit**power return power_cache[(power, digit)] # Check each number up to the limit for number in range(limit): # Count digits num_digits = len(str(number)) # Calculate sum of powered digits using memoized powers remaining = number digit_sum = 0 while remaining > 0: digit = remaining % 10 digit_sum += get_digit_power(digit, num_digits) remaining //= 10 # Check if narcissistic if digit_sum == number: narcissistic_nums.append(number) return narcissistic_nums if __name__ == "__main__": import doctest doctest.testmod() # Demonstrate the dynamic programming approach print("Finding all narcissistic numbers up to 10000:") print("(Using memoization to cache digit power calculations)") print() narcissistic_numbers = find_narcissistic_numbers(10000) print(f"Found {len(narcissistic_numbers)} narcissistic numbers:") print(narcissistic_numbers)
{ "repo_id": "TheAlgorithms/Python", "file_path": "dynamic_programming/narcissistic_number.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:machine_learning/t_stochastic_neighbour_embedding.py
""" t-distributed stochastic neighbor embedding (t-SNE) For more details, see: https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding """ import doctest import numpy as np from numpy import ndarray from sklearn.datasets import load_iris def collect_dataset() -> tuple[ndarray, ndarray]: """ Load the Iris dataset and return features and labels. Returns: tuple[ndarray, ndarray]: Feature matrix and target labels. >>> features, targets = collect_dataset() >>> features.shape (150, 4) >>> targets.shape (150,) """ iris_dataset = load_iris() return np.array(iris_dataset.data), np.array(iris_dataset.target) def compute_pairwise_affinities(data_matrix: ndarray, sigma: float = 1.0) -> ndarray: """ Compute high-dimensional affinities (P matrix) using a Gaussian kernel. Args: data_matrix: Input data of shape (n_samples, n_features). sigma: Gaussian kernel bandwidth. Returns: ndarray: Symmetrized probability matrix. >>> x = np.array([[0.0, 0.0], [1.0, 0.0]]) >>> probabilities = compute_pairwise_affinities(x) >>> float(round(probabilities[0, 1], 3)) 0.25 """ n_samples = data_matrix.shape[0] squared_sum = np.sum(np.square(data_matrix), axis=1) squared_distance = np.add( np.add(-2 * np.dot(data_matrix, data_matrix.T), squared_sum).T, squared_sum ) affinity_matrix = np.exp(-squared_distance / (2 * sigma**2)) np.fill_diagonal(affinity_matrix, 0) affinity_matrix /= np.sum(affinity_matrix) return (affinity_matrix + affinity_matrix.T) / (2 * n_samples) def compute_low_dim_affinities(embedding_matrix: ndarray) -> tuple[ndarray, ndarray]: """ Compute low-dimensional affinities (Q matrix) using a Student-t distribution. Args: embedding_matrix: Low-dimensional embedding of shape (n_samples, n_components). Returns: tuple[ndarray, ndarray]: (Q probability matrix, numerator matrix). >>> y = np.array([[0.0, 0.0], [1.0, 0.0]]) >>> q_matrix, numerators = compute_low_dim_affinities(y) >>> q_matrix.shape (2, 2) """ squared_sum = np.sum(np.square(embedding_matrix), axis=1) numerator_matrix = 1 / ( 1 + np.add( np.add(-2 * np.dot(embedding_matrix, embedding_matrix.T), squared_sum).T, squared_sum, ) ) np.fill_diagonal(numerator_matrix, 0) q_matrix = numerator_matrix / np.sum(numerator_matrix) return q_matrix, numerator_matrix def apply_tsne( data_matrix: ndarray, n_components: int = 2, learning_rate: float = 200.0, n_iter: int = 500, ) -> ndarray: """ Apply t-SNE for dimensionality reduction. Args: data_matrix: Original dataset (features). n_components: Target dimension (2D or 3D). learning_rate: Step size for gradient descent. n_iter: Number of iterations. Returns: ndarray: Low-dimensional embedding of the data. >>> features, _ = collect_dataset() >>> embedding = apply_tsne(features, n_components=2, n_iter=50) >>> embedding.shape (150, 2) """ if n_components < 1 or n_iter < 1: raise ValueError("n_components and n_iter must be >= 1") n_samples = data_matrix.shape[0] rng = np.random.default_rng() embedding = rng.standard_normal((n_samples, n_components)) * 1e-4 high_dim_affinities = compute_pairwise_affinities(data_matrix) high_dim_affinities = np.maximum(high_dim_affinities, 1e-12) embedding_increment = np.zeros_like(embedding) momentum = 0.5 for iteration in range(n_iter): low_dim_affinities, numerator_matrix = compute_low_dim_affinities(embedding) low_dim_affinities = np.maximum(low_dim_affinities, 1e-12) affinity_diff = high_dim_affinities - low_dim_affinities gradient = 4 * ( np.dot((affinity_diff * numerator_matrix), embedding) - np.multiply( np.sum(affinity_diff * numerator_matrix, axis=1)[:, np.newaxis], embedding, ) ) embedding_increment = momentum * embedding_increment - learning_rate * gradient embedding += embedding_increment if iteration == int(n_iter / 4): momentum = 0.8 return embedding def main() -> None: """ Run t-SNE on the Iris dataset and display the first 5 embeddings. >>> main() # doctest: +ELLIPSIS t-SNE embedding (first 5 points): [[... """ features, _labels = collect_dataset() embedding = apply_tsne(features, n_components=2, n_iter=300) if not isinstance(embedding, np.ndarray): raise TypeError("t-SNE embedding must be an ndarray") print("t-SNE embedding (first 5 points):") print(embedding[:5]) # Optional visualization (Ruff/mypy compliant) # import matplotlib.pyplot as plt # plt.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap="viridis") # plt.title("t-SNE Visualization of the Iris Dataset") # plt.xlabel("Dimension 1") # plt.ylabel("Dimension 2") # plt.show() if __name__ == "__main__": doctest.testmod() main()
{ "repo_id": "TheAlgorithms/Python", "file_path": "machine_learning/t_stochastic_neighbour_embedding.py", "license": "MIT License", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:data_structures/arrays/rotate_array.py
def rotate_array(arr: list[int], steps: int) -> list[int]: """ Rotates a list to the right by steps positions. Parameters: arr (List[int]): The list of integers to rotate. steps (int): Number of positions to rotate. Can be negative for left rotation. Returns: List[int]: Rotated list. Examples: >>> rotate_array([1, 2, 3, 4, 5], 2) [4, 5, 1, 2, 3] >>> rotate_array([1, 2, 3, 4, 5], -2) [3, 4, 5, 1, 2] >>> rotate_array([1, 2, 3, 4, 5], 7) [4, 5, 1, 2, 3] >>> rotate_array([], 3) [] """ n = len(arr) if n == 0: return arr steps = steps % n if steps < 0: steps += n def reverse(start: int, end: int) -> None: """ Reverses a portion of the list in place from index start to end. Parameters: start (int): Starting index of the portion to reverse. end (int): Ending index of the portion to reverse. Returns: None Examples: >>> example = [1, 2, 3, 4, 5] >>> def reverse_test(arr, start, end): ... while start < end: ... arr[start], arr[end] = arr[end], arr[start] ... start += 1 ... end -= 1 >>> reverse_test(example, 0, 2) >>> example [3, 2, 1, 4, 5] >>> reverse_test(example, 2, 4) >>> example [3, 2, 5, 4, 1] """ while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 reverse(0, n - 1) reverse(0, steps - 1) reverse(steps, n - 1) return arr if __name__ == "__main__": examples = [ ([1, 2, 3, 4, 5], 2), ([1, 2, 3, 4, 5], -2), ([1, 2, 3, 4, 5], 7), ([], 3), ] for arr, steps in examples: rotated = rotate_array(arr.copy(), steps) print(f"Rotate {arr} by {steps}: {rotated}")
{ "repo_id": "TheAlgorithms/Python", "file_path": "data_structures/arrays/rotate_array.py", "license": "MIT License", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:sorts/stalin_sort.py
""" Stalin Sort algorithm: Removes elements that are out of order. Elements that are not greater than or equal to the previous element are discarded. Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 """ def stalin_sort(sequence: list[int]) -> list[int]: """ Sorts a list using the Stalin sort algorithm. >>> stalin_sort([4, 3, 5, 2, 1, 7]) [4, 5, 7] >>> stalin_sort([1, 2, 3, 4]) [1, 2, 3, 4] >>> stalin_sort([4, 5, 5, 2, 3]) [4, 5, 5] >>> stalin_sort([6, 11, 12, 4, 1, 5]) [6, 11, 12] >>> stalin_sort([5, 0, 4, 3]) [5] >>> stalin_sort([5, 4, 3, 2, 1]) [5] >>> stalin_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> stalin_sort([1, 2, 8, 7, 6]) [1, 2, 8] """ result = [sequence[0]] for element in sequence[1:]: if element >= result[-1]: result.append(element) return result if __name__ == "__main__": import doctest doctest.testmod()
{ "repo_id": "TheAlgorithms/Python", "file_path": "sorts/stalin_sort.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:maths/numerical_analysis/weierstrass_method.py
from collections.abc import Callable import numpy as np def weierstrass_method( polynomial: Callable[[np.ndarray], np.ndarray], degree: int, roots: np.ndarray | None = None, max_iter: int = 100, ) -> np.ndarray: """ Approximates all complex roots of a polynomial using the Weierstrass (Durand-Kerner) method. Args: polynomial: A function that takes a NumPy array of complex numbers and returns the polynomial values at those points. degree: Degree of the polynomial (number of roots to find). Must be ≥ 1. roots: Optional initial guess as a NumPy array of complex numbers. Must have length equal to 'degree'. If None, perturbed complex roots of unity are used. max_iter: Number of iterations to perform (default: 100). Returns: np.ndarray: Array of approximated complex roots. Raises: ValueError: If degree < 1, or if initial roots length doesn't match the degree. Note: - Root updates are clipped to prevent numerical overflow. Example: >>> import numpy as np >>> def check(poly, degree, expected): ... roots = weierstrass_method(poly, degree) ... return np.allclose(np.sort(roots), np.sort(expected)) >>> check( ... lambda x: x**2 - 1, ... 2, ... np.array([-1, 1])) True >>> check( ... lambda x: x**3 - 4.5*x**2 + 5.75*x - 1.875, ... 3, ... np.array([1.5, 0.5, 2.5]) ... ) True See Also: https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method """ if degree < 1: raise ValueError("Degree of the polynomial must be at least 1.") if roots is None: # Use perturbed complex roots of unity as initial guesses rng = np.random.default_rng() roots = np.array( [ np.exp(2j * np.pi * i / degree) * (1 + 1e-3 * rng.random()) for i in range(degree) ], dtype=np.complex128, ) else: roots = np.asarray(roots, dtype=np.complex128) if roots.shape[0] != degree: raise ValueError( "Length of initial roots must match the degree of the polynomial." ) for _ in range(max_iter): # Construct the product denominator for each root denominator = np.array([root - roots for root in roots], dtype=np.complex128) np.fill_diagonal(denominator, 1.0) # Avoid zero in diagonal denominator = np.prod(denominator, axis=1) # Evaluate polynomial at each root numerator = polynomial(roots).astype(np.complex128) # Compute update and clip to prevent overflow delta = numerator / denominator delta = np.clip(delta, -1e10, 1e10) roots -= delta return roots if __name__ == "__main__": import doctest doctest.testmod()
{ "repo_id": "TheAlgorithms/Python", "file_path": "maths/numerical_analysis/weierstrass_method.py", "license": "MIT License", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:data_compression/coordinate_compression.py
""" Assumption: - The values to compress are assumed to be comparable, values can be sorted and compared with '<' and '>' operators. """ class CoordinateCompressor: """ A class for coordinate compression. This class allows you to compress and decompress a list of values. Mapping: In addition to compression and decompression, this class maintains a mapping between original values and their compressed counterparts using two data structures: a dictionary `coordinate_map` and a list `reverse_map`: - `coordinate_map`: A dictionary that maps original values to their compressed coordinates. Keys are original values, and values are compressed coordinates. - `reverse_map`: A list used for reverse mapping, where each index corresponds to a compressed coordinate, and the value at that index is the original value. Example of mapping: Original: 10, Compressed: 0 Original: 52, Compressed: 1 Original: 83, Compressed: 2 Original: 100, Compressed: 3 This mapping allows for efficient compression and decompression of values within the list. """ def __init__(self, arr: list[int | float | str]) -> None: """ Initialize the CoordinateCompressor with a list. Args: arr: The list of values to be compressed. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.compress(100) 3 >>> cc.compress(52) 1 >>> cc.decompress(1) 52 """ # A dictionary to store compressed coordinates self.coordinate_map: dict[int | float | str, int] = {} # A list to store reverse mapping self.reverse_map: list[int | float | str] = [-1] * len(arr) self.arr = sorted(arr) # The input list self.n = len(arr) # The length of the input list self.compress_coordinates() def compress_coordinates(self) -> None: """ Compress the coordinates in the input list. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.coordinate_map[83] 2 >>> cc.coordinate_map[80] # Value not in the original list Traceback (most recent call last): ... KeyError: 80 >>> cc.reverse_map[2] 83 """ key = 0 for val in self.arr: if val not in self.coordinate_map: self.coordinate_map[val] = key self.reverse_map[key] = val key += 1 def compress(self, original: float | str) -> int: """ Compress a single value. Args: original: The value to compress. Returns: The compressed integer, or -1 if not found in the original list. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.compress(100) 3 >>> cc.compress(7) # Value not in the original list -1 """ return self.coordinate_map.get(original, -1) def decompress(self, num: int) -> int | float | str: """ Decompress a single integer. Args: num: The compressed integer to decompress. Returns: The original value. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.decompress(0) 10 >>> cc.decompress(5) # Compressed coordinate out of range -1 """ return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1 if __name__ == "__main__": from doctest import testmod testmod() arr: list[int | float | str] = [100, 10, 52, 83] cc = CoordinateCompressor(arr) for original in arr: compressed = cc.compress(original) decompressed = cc.decompress(compressed) print(f"Original: {decompressed}, Compressed: {compressed}")
{ "repo_id": "TheAlgorithms/Python", "file_path": "data_compression/coordinate_compression.py", "license": "MIT License", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:sorts/cyclic_sort.py
""" This is a pure Python implementation of the Cyclic Sort algorithm. For doctests run following command: python -m doctest -v cyclic_sort.py or python3 -m doctest -v cyclic_sort.py For manual testing run: python cyclic_sort.py or python3 cyclic_sort.py """ def cyclic_sort(nums: list[int]) -> list[int]: """ Sorts the input list of n integers from 1 to n in-place using the Cyclic Sort algorithm. :param nums: List of n integers from 1 to n to be sorted. :return: The same list sorted in ascending order. Time complexity: O(n), where n is the number of integers in the list. Examples: >>> cyclic_sort([]) [] >>> cyclic_sort([3, 5, 2, 1, 4]) [1, 2, 3, 4, 5] """ # Perform cyclic sort index = 0 while index < len(nums): # Calculate the correct index for the current element correct_index = nums[index] - 1 # If the current element is not at its correct position, # swap it with the element at its correct index if index != correct_index: nums[index], nums[correct_index] = nums[correct_index], nums[index] else: # If the current element is already in its correct position, # move to the next element index += 1 return nums if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*cyclic_sort(unsorted), sep=",")
{ "repo_id": "TheAlgorithms/Python", "file_path": "sorts/cyclic_sort.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:project_euler/problem_009/sol4.py
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def get_squares(n: int) -> list[int]: """ >>> get_squares(0) [] >>> get_squares(1) [0] >>> get_squares(2) [0, 1] >>> get_squares(3) [0, 1, 4] >>> get_squares(4) [0, 1, 4, 9] """ return [number * number for number in range(n)] def solution(n: int = 1000) -> int: """ Precomputing squares and checking if a^2 + b^2 is the square by set look-up. >>> solution(12) 60 >>> solution(36) 1620 """ squares = get_squares(n) squares_set = set(squares) for a in range(1, n // 3): for b in range(a + 1, (n - a) // 2 + 1): if ( squares[a] + squares[b] in squares_set and squares[n - a - b] == squares[a] + squares[b] ): return a * b * (n - a - b) return -1 if __name__ == "__main__": print(f"{solution() = }")
{ "repo_id": "TheAlgorithms/Python", "file_path": "project_euler/problem_009/sol4.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:maths/test_factorial.py
# /// script # requires-python = ">=3.13" # dependencies = [ # "pytest", # ] # /// import pytest from maths.factorial import factorial, factorial_recursive @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_zero(function): assert function(0) == 1 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_positive_integers(function): assert function(1) == 1 assert function(5) == 120 assert function(7) == 5040 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_large_number(function): assert function(10) == 3628800 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_negative_number(function): with pytest.raises(ValueError): function(-3) @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_float_number(function): with pytest.raises(ValueError): function(1.5) if __name__ == "__main__": pytest.main(["-v", __file__])
{ "repo_id": "TheAlgorithms/Python", "file_path": "maths/test_factorial.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
TheAlgorithms/Python:financial/straight_line_depreciation.py
""" In accounting, depreciation refers to the decreases in the value of a fixed asset during the asset's useful life. When an organization purchases a fixed asset, the purchase expenditure is not recognized as an expense immediately. Instead, the decreases in the asset's value are recognized as expenses over the years during which the asset is used. The following methods are widely used for depreciation calculation in accounting: - Straight-line method - Diminishing balance method - Units-of-production method The straight-line method is the simplest and most widely used. This method calculates depreciation by spreading the cost evenly over the asset's useful life. The following formula shows how to calculate the yearly depreciation expense: - annual depreciation expense = (purchase cost of asset - residual value) / useful life of asset(years) Further information on: https://en.wikipedia.org/wiki/Depreciation The function, straight_line_depreciation, returns a list of the depreciation expenses over the given period. """ def straight_line_depreciation( useful_years: int, purchase_value: float, residual_value: float = 0.0, ) -> list[float]: """ Calculate the depreciation expenses over the given period :param useful_years: Number of years the asset will be used :param purchase_value: Purchase expenditure for the asset :param residual_value: Residual value of the asset at the end of its useful life :return: A list of annual depreciation expenses over the asset's useful life >>> straight_line_depreciation(10, 1100.0, 100.0) [100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0] >>> straight_line_depreciation(6, 1250.0, 50.0) [200.0, 200.0, 200.0, 200.0, 200.0, 200.0] >>> straight_line_depreciation(4, 1001.0) [250.25, 250.25, 250.25, 250.25] >>> straight_line_depreciation(11, 380.0, 50.0) [30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0] >>> straight_line_depreciation(1, 4985, 100) [4885.0] """ if not isinstance(useful_years, int): raise TypeError("Useful years must be an integer") if useful_years < 1: raise ValueError("Useful years cannot be less than 1") if not isinstance(purchase_value, (float, int)): raise TypeError("Purchase value must be numeric") if not isinstance(residual_value, (float, int)): raise TypeError("Residual value must be numeric") if purchase_value < 0.0: raise ValueError("Purchase value cannot be less than zero") if purchase_value < residual_value: raise ValueError("Purchase value cannot be less than residual value") # Calculate annual depreciation expense depreciable_cost = purchase_value - residual_value annual_depreciation_expense = depreciable_cost / useful_years # List of annual depreciation expenses list_of_depreciation_expenses = [] accumulated_depreciation_expense = 0.0 for period in range(useful_years): if period != useful_years - 1: accumulated_depreciation_expense += annual_depreciation_expense list_of_depreciation_expenses.append(annual_depreciation_expense) else: depreciation_expense_in_end_year = ( depreciable_cost - accumulated_depreciation_expense ) list_of_depreciation_expenses.append(depreciation_expense_in_end_year) return list_of_depreciation_expenses if __name__ == "__main__": user_input_useful_years = int(input("Please Enter Useful Years:\n > ")) user_input_purchase_value = float(input("Please Enter Purchase Value:\n > ")) user_input_residual_value = float(input("Please Enter Residual Value:\n > ")) print( straight_line_depreciation( user_input_useful_years, user_input_purchase_value, user_input_residual_value, ) )
{ "repo_id": "TheAlgorithms/Python", "file_path": "financial/straight_line_depreciation.py", "license": "MIT License", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:graphs/bidirectional_search.py
""" Bidirectional Search Algorithm. This algorithm searches from both the source and target nodes simultaneously, meeting somewhere in the middle. This approach can significantly reduce the search space compared to a traditional one-directional search. Time Complexity: O(b^(d/2)) where b is the branching factor and d is the depth Space Complexity: O(b^(d/2)) https://en.wikipedia.org/wiki/Bidirectional_search """ from collections import deque def expand_search( graph: dict[int, list[int]], queue: deque[int], parents: dict[int, int | None], opposite_direction_parents: dict[int, int | None], ) -> int | None: if not queue: return None current = queue.popleft() for neighbor in graph[current]: if neighbor in parents: continue parents[neighbor] = current queue.append(neighbor) # Check if this creates an intersection if neighbor in opposite_direction_parents: return neighbor return None def construct_path(current: int | None, parents: dict[int, int | None]) -> list[int]: path: list[int] = [] while current is not None: path.append(current) current = parents[current] return path def bidirectional_search( graph: dict[int, list[int]], start: int, goal: int ) -> list[int] | None: """ Perform bidirectional search on a graph to find the shortest path. Args: graph: A dictionary where keys are nodes and values are lists of adjacent nodes start: The starting node goal: The target node Returns: A list representing the path from start to goal, or None if no path exists Examples: >>> graph = { ... 0: [1, 2], ... 1: [0, 3, 4], ... 2: [0, 5, 6], ... 3: [1, 7], ... 4: [1, 8], ... 5: [2, 9], ... 6: [2, 10], ... 7: [3, 11], ... 8: [4, 11], ... 9: [5, 11], ... 10: [6, 11], ... 11: [7, 8, 9, 10], ... } >>> bidirectional_search(graph=graph, start=0, goal=11) [0, 1, 3, 7, 11] >>> bidirectional_search(graph=graph, start=5, goal=5) [5] >>> disconnected_graph = { ... 0: [1, 2], ... 1: [0], ... 2: [0], ... 3: [4], ... 4: [3], ... } >>> bidirectional_search(graph=disconnected_graph, start=0, goal=3) is None True """ if start == goal: return [start] # Check if start and goal are in the graph if start not in graph or goal not in graph: return None # Initialize forward and backward search dictionaries # Each maps a node to its parent in the search forward_parents: dict[int, int | None] = {start: None} backward_parents: dict[int, int | None] = {goal: None} # Initialize forward and backward search queues forward_queue = deque([start]) backward_queue = deque([goal]) # Intersection node (where the two searches meet) intersection = None # Continue until both queues are empty or an intersection is found while forward_queue and backward_queue and intersection is None: # Expand forward search intersection = expand_search( graph=graph, queue=forward_queue, parents=forward_parents, opposite_direction_parents=backward_parents, ) # If no intersection found, expand backward search if intersection is not None: break intersection = expand_search( graph=graph, queue=backward_queue, parents=backward_parents, opposite_direction_parents=forward_parents, ) # If no intersection found, there's no path if intersection is None: return None # Construct path from start to intersection forward_path: list[int] = construct_path( current=intersection, parents=forward_parents ) forward_path.reverse() # Construct path from intersection to goal backward_path: list[int] = construct_path( current=backward_parents[intersection], parents=backward_parents ) # Return the complete path return forward_path + backward_path def main() -> None: """ Run example of bidirectional search algorithm. Examples: >>> main() # doctest: +NORMALIZE_WHITESPACE Path from 0 to 11: [0, 1, 3, 7, 11] Path from 5 to 5: [5] Path from 0 to 3: None """ # Example graph represented as an adjacency list example_graph = { 0: [1, 2], 1: [0, 3, 4], 2: [0, 5, 6], 3: [1, 7], 4: [1, 8], 5: [2, 9], 6: [2, 10], 7: [3, 11], 8: [4, 11], 9: [5, 11], 10: [6, 11], 11: [7, 8, 9, 10], } # Test case 1: Path exists start, goal = 0, 11 path = bidirectional_search(graph=example_graph, start=start, goal=goal) print(f"Path from {start} to {goal}: {path}") # Test case 2: Start and goal are the same start, goal = 5, 5 path = bidirectional_search(graph=example_graph, start=start, goal=goal) print(f"Path from {start} to {goal}: {path}") # Test case 3: No path exists (disconnected graph) disconnected_graph = { 0: [1, 2], 1: [0], 2: [0], 3: [4], 4: [3], } start, goal = 0, 3 path = bidirectional_search(graph=disconnected_graph, start=start, goal=goal) print(f"Path from {start} to {goal}: {path}") if __name__ == "__main__": main()
{ "repo_id": "TheAlgorithms/Python", "file_path": "graphs/bidirectional_search.py", "license": "MIT License", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TheAlgorithms/Python:physics/orbital_transfer_work.py
def orbital_transfer_work( mass_central: float, mass_object: float, r_initial: float, r_final: float ) -> str: """ Calculates the work required to move an object from one orbit to another in a gravitational field based on the change in total mechanical energy. The formula used is: W = (G * M * m / 2) * (1/r_initial - 1/r_final) where: W = work done (Joules) G = gravitational constant (6.67430 * 10^-11 m^3 kg^-1 s^-2) M = mass of the central body (kg) m = mass of the orbiting object (kg) r_initial = initial orbit radius (m) r_final = final orbit radius (m) Args: mass_central (float): Mass of the central body (kg) mass_object (float): Mass of the object being moved (kg) r_initial (float): Initial orbital radius (m) r_final (float): Final orbital radius (m) Returns: str: Work done in Joules as a string in scientific notation (3 decimals) Examples: >>> orbital_transfer_work(5.972e24, 1000, 6.371e6, 7e6) '2.811e+09' >>> orbital_transfer_work(5.972e24, 500, 7e6, 6.371e6) '-1.405e+09' >>> orbital_transfer_work(1.989e30, 1000, 1.5e11, 2.28e11) '1.514e+11' """ gravitational_constant = 6.67430e-11 if r_initial <= 0 or r_final <= 0: raise ValueError("Orbital radii must be greater than zero.") work = (gravitational_constant * mass_central * mass_object / 2) * ( 1 / r_initial - 1 / r_final ) return f"{work:.3e}" if __name__ == "__main__": import doctest doctest.testmod() print("Orbital transfer work calculator\n") try: M = float(input("Enter mass of central body (kg): ").strip()) if M <= 0: r1 = float(input("Enter initial orbit radius (m): ").strip()) if r1 <= 0: raise ValueError("Initial orbit radius must be greater than zero.") r2 = float(input("Enter final orbit radius (m): ").strip()) if r2 <= 0: raise ValueError("Final orbit radius must be greater than zero.") m = float(input("Enter mass of orbiting object (kg): ").strip()) if m <= 0: raise ValueError("Mass of the orbiting object must be greater than zero.") r1 = float(input("Enter initial orbit radius (m): ").strip()) r2 = float(input("Enter final orbit radius (m): ").strip()) result = orbital_transfer_work(M, m, r1, r2) print(f"Work done in orbital transfer: {result} Joules") except ValueError as e: print(f"Input error: {e}")
{ "repo_id": "TheAlgorithms/Python", "file_path": "physics/orbital_transfer_work.py", "license": "MIT License", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:physics/escape_velocity.py
import math def escape_velocity(mass: float, radius: float) -> float: """ Calculates the escape velocity needed to break free from a celestial body's gravitational field. The formula used is: v = sqrt(2 * G * M / R) where: v = escape velocity (m/s) G = gravitational constant (6.67430 * 10^-11 m^3 kg^-1 s^-2) M = mass of the celestial body (kg) R = radius from the center of mass (m) Source: https://en.wikipedia.org/wiki/Escape_velocity Args: mass (float): Mass of the celestial body in kilograms. radius (float): Radius from the center of mass in meters. Returns: float: Escape velocity in meters per second, rounded to 3 decimal places. Examples: >>> escape_velocity(mass=5.972e24, radius=6.371e6) # Earth 11185.978 >>> escape_velocity(mass=7.348e22, radius=1.737e6) # Moon 2376.307 >>> escape_velocity(mass=1.898e27, radius=6.9911e7) # Jupiter 60199.545 >>> escape_velocity(mass=0, radius=1.0) 0.0 >>> escape_velocity(mass=1.0, radius=0) Traceback (most recent call last): ... ZeroDivisionError: Radius cannot be zero. """ gravitational_constant = 6.67430e-11 # m^3 kg^-1 s^-2 if radius == 0: raise ZeroDivisionError("Radius cannot be zero.") velocity = math.sqrt(2 * gravitational_constant * mass / radius) return round(velocity, 3) if __name__ == "__main__": import doctest doctest.testmod() print("Calculate escape velocity of a celestial body...\n") try: mass = float(input("Enter mass of the celestial body (in kgs): ").strip()) radius = float(input("Enter radius from the center of mass (in ms): ").strip()) velocity = escape_velocity(mass=mass, radius=radius) print(f"Escape velocity is {velocity} m/s") except ValueError: print("Invalid input. Please enter valid numeric values.") except ZeroDivisionError as e: print(e)
{ "repo_id": "TheAlgorithms/Python", "file_path": "physics/escape_velocity.py", "license": "MIT License", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:project_euler/problem_095/sol1.py
""" Project Euler Problem 95: https://projecteuler.net/problem=95 Amicable Chains The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number. Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair. Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers: 12496 -> 14288 -> 15472 -> 14536 -> 14264 (-> 12496 -> ...) Since this chain returns to its starting point, it is called an amicable chain. Find the smallest member of the longest amicable chain with no element exceeding one million. Solution is doing the following: - Get relevant prime numbers - Iterate over product combination of prime numbers to generate all non-prime numbers up to max number, by keeping track of prime factors - Calculate the sum of factors for each number - Iterate over found some factors to find longest chain """ from math import isqrt def generate_primes(max_num: int) -> list[int]: """ Calculates the list of primes up to and including `max_num`. >>> generate_primes(6) [2, 3, 5] """ are_primes = [True] * (max_num + 1) are_primes[0] = are_primes[1] = False for i in range(2, isqrt(max_num) + 1): if are_primes[i]: for j in range(i * i, max_num + 1, i): are_primes[j] = False return [prime for prime, is_prime in enumerate(are_primes) if is_prime] def multiply( chain: list[int], primes: list[int], min_prime_idx: int, prev_num: int, max_num: int, prev_sum: int, primes_degrees: dict[int, int], ) -> None: """ Run over all prime combinations to generate non-prime numbers. >>> chain = [0] * 3 >>> primes_degrees = {} >>> multiply( ... chain=chain, ... primes=[2], ... min_prime_idx=0, ... prev_num=1, ... max_num=2, ... prev_sum=0, ... primes_degrees=primes_degrees, ... ) >>> chain [0, 0, 1] >>> primes_degrees {2: 1} """ min_prime = primes[min_prime_idx] num = prev_num * min_prime min_prime_degree = primes_degrees.get(min_prime, 0) min_prime_degree += 1 primes_degrees[min_prime] = min_prime_degree new_sum = prev_sum * min_prime + (prev_sum + prev_num) * (min_prime - 1) // ( min_prime**min_prime_degree - 1 ) chain[num] = new_sum for prime_idx in range(min_prime_idx, len(primes)): if primes[prime_idx] * num > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=num, max_num=max_num, prev_sum=new_sum, primes_degrees=primes_degrees.copy(), ) def find_longest_chain(chain: list[int], max_num: int) -> int: """ Finds the smallest element of longest chain >>> find_longest_chain(chain=[0, 0, 0, 0, 0, 0, 6], max_num=6) 6 """ max_len = 0 min_elem = 0 for start in range(2, len(chain)): visited = {start} elem = chain[start] length = 1 while elem > 1 and elem <= max_num and elem not in visited: visited.add(elem) elem = chain[elem] length += 1 if elem == start and length > max_len: max_len = length min_elem = start return min_elem def solution(max_num: int = 1000000) -> int: """ Runs the calculation for numbers <= `max_num`. >>> solution(10) 6 >>> solution(200000) 12496 """ primes = generate_primes(max_num) chain = [0] * (max_num + 1) for prime_idx, prime in enumerate(primes): if prime**2 > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=1, max_num=max_num, prev_sum=0, primes_degrees={}, ) return find_longest_chain(chain=chain, max_num=max_num) if __name__ == "__main__": print(f"{solution() = }")
{ "repo_id": "TheAlgorithms/Python", "file_path": "project_euler/problem_095/sol1.py", "license": "MIT License", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TheAlgorithms/Python:project_euler/problem_345/sol1.py
""" Project Euler Problem 345: https://projecteuler.net/problem=345 Matrix Sum We define the Matrix Sum of a matrix as the maximum possible sum of matrix elements such that none of the selected elements share the same row or column. For example, the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 + 767): 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 Find the Matrix Sum of: 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805 Brute force solution, with caching intermediate steps to speed up the calculation. """ import numpy as np from numpy.typing import NDArray MATRIX_1 = [ "7 53 183 439 863", "497 383 563 79 973", "287 63 343 169 583", "627 343 773 959 943", "767 473 103 699 303", ] MATRIX_2 = [ "7 53 183 439 863 497 383 563 79 973 287 63 343 169 583", "627 343 773 959 943 767 473 103 699 303 957 703 583 639 913", "447 283 463 29 23 487 463 993 119 883 327 493 423 159 743", "217 623 3 399 853 407 103 983 89 463 290 516 212 462 350", "960 376 682 962 300 780 486 502 912 800 250 346 172 812 350", "870 456 192 162 593 473 915 45 989 873 823 965 425 329 803", "973 965 905 919 133 673 665 235 509 613 673 815 165 992 326", "322 148 972 962 286 255 941 541 265 323 925 281 601 95 973", "445 721 11 525 473 65 511 164 138 672 18 428 154 448 848", "414 456 310 312 798 104 566 520 302 248 694 976 430 392 198", "184 829 373 181 631 101 969 613 840 740 778 458 284 760 390", "821 461 843 513 17 901 711 993 293 157 274 94 192 156 574", "34 124 4 878 450 476 712 914 838 669 875 299 823 329 699", "815 559 813 459 522 788 168 586 966 232 308 833 251 631 107", "813 883 451 509 615 77 281 613 459 205 380 274 302 35 805", ] def solve(arr: NDArray, row: int, cols: set[int], cache: dict[str, int]) -> int: """ Finds the max sum for array `arr` starting with row index `row`, and with columns included in `cols`. `cache` is used for caching intermediate results. >>> solve(arr=np.array([[1, 2], [3, 4]]), row=0, cols={0, 1}, cache={}) 5 """ cache_id = f"{row}, {sorted(cols)}" if cache_id in cache: return cache[cache_id] if row == len(arr): return 0 max_sum = 0 for col in cols: new_cols = cols - {col} max_sum = max( max_sum, int(arr[row, col]) + solve(arr=arr, row=row + 1, cols=new_cols, cache=cache), ) cache[cache_id] = max_sum return max_sum def solution(matrix_str: list[str] = MATRIX_2) -> int: """ Takes list of strings `matrix_str` to parse the matrix and calculates the max sum. >>> solution(["1 2", "3 4"]) 5 >>> solution(MATRIX_1) 3315 """ n = len(matrix_str) arr = np.empty(shape=(n, n), dtype=int) for row, matrix_row_str in enumerate(matrix_str): matrix_row_list_str = matrix_row_str.split() for col, elem_str in enumerate(matrix_row_list_str): arr[row, col] = int(elem_str) cache: dict[str, int] = {} return solve(arr=arr, row=0, cols=set(range(n)), cache=cache) if __name__ == "__main__": print(f"{solution() = }")
{ "repo_id": "TheAlgorithms/Python", "file_path": "project_euler/problem_345/sol1.py", "license": "MIT License", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Z4nzu/hackingtool:install.py
#!/usr/bin/env python3 # install_hackingtool.py (rich-based installer UI) import os import sys import shutil import subprocess from pathlib import Path from rich.console import Console from rich.panel import Panel from rich.prompt import Prompt, Confirm, IntPrompt from rich.table import Table from rich.align import Align from rich.progress import Progress, SpinnerColumn, TextColumn from rich.text import Text from rich import box from random import choice console = Console() REPO_URL = "https://github.com/Z4nzu/hackingtool.git" INSTALL_DIR = Path("/usr/share/hackingtool") BIN_PATH = Path("/usr/bin/hackingtool") VENV_DIR_NAME = "venv" REQUIREMENTS = "requirements.txt" def check_root(): if os.geteuid() != 0: console.print(Panel("[red]This installer must be run as root. Use: sudo python3 install_hackingtool.py[/red]")) sys.exit(1) def run_cmd(cmd, check=True, capture=False, env=None): return subprocess.run(cmd, shell=True, check=check, capture_output=capture, text=True, env=env) def colorful_logo(): logos = ["magenta", "bright_magenta", "cyan", "blue", "green", "yellow"] style = choice(logos) logo_lines = r""" ▄█ █▄ ▄████████ ▄████████ ▄█ ▄█▄ ▄█ ███▄▄▄▄ ▄██████▄ ███ ▄██████▄ ▄██████▄ ▄█ ███ ███ ███ ███ ███ ███ ███ ▄███▀ ███ ███▀▀▀██▄ ███ ███ ▀█████████▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███▐██▀ ███▌ ███ ███ ███ █▀ ▀███▀▀██ ███ ███ ███ ███ ███ ▄███▄▄▄▄███▄▄ ███ ███ ███ ▄█████▀ ███▌ ███ ███ ▄███ ███ ▀ ███ ███ ███ ███ ███ ▀▀███▀▀▀▀███▀ ▀███████████ ███ ▀▀█████▄ ███▌ ███ ███ ▀▀███ ████▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▄ ███▐██▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀███▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▌ ▄ ███ █▀ ███ █▀ ████████▀ ███ ▀█▀ █▀ ▀█ █▀ ████████▀ ▄████▀ ▀██████▀ ▀██████▀ █████▄▄██ ▀ ▀ """ panel = Panel(Text(logo_lines, style=style), box=box.DOUBLE, border_style=style) console.print(panel) console.print(f"[bold {style}]https://github.com/Z4nzu/hackingtool[/bold {style}]\n") def choose_distro(): console.print(Panel("[bold magenta]Select installation target[/bold magenta]\n\n[1] Kali / Parrot (apt)\n[2] Arch (pacman)\n[0] Exit", border_style="bright_magenta")) choice = IntPrompt.ask("Choice", choices=["0", "1", "2"], default=1) return choice def check_internet(): console.print("[yellow]* Checking internet connectivity...[/yellow]") try: run_cmd("curl -sSf --max-time 10 https://www.google.com > /dev/null", check=True) console.print("[green][✔] Internet connection OK[/green]") return True except Exception: try: run_cmd("curl -sSf --max-time 10 https://github.com > /dev/null", check=True) console.print("[green][✔] Internet connection OK[/green]") return True except Exception: console.print("[red][✘] Internet connection not available[/red]") return False def system_update_and_install(choice): if choice == 1: console.print("[yellow]* Running apt update/upgrade...[/yellow]") try: run_cmd("apt update -y && apt upgrade -y") except subprocess.CalledProcessError as e: console.print(f"[red][!][/red] apt update/upgrade failed (non-fatal). Continuing installation. Error: {e}") console.print("[yellow]* Installing required packages (apt)...[/yellow]") try: run_cmd("apt-get install -y git python3-pip python3-venv figlet boxes php curl xdotool wget") except subprocess.CalledProcessError as e: console.print(f"[red][!][/red] apt-get install failed (non-fatal). You may need to install some packages manually. Error: {e}") elif choice == 2: console.print("[yellow]* Running pacman update...[/yellow]") try: run_cmd("pacman -Syu --noconfirm") except subprocess.CalledProcessError as e: console.print(f"[red][!][/red] pacman update failed (non-fatal). Continuing installation. Error: {e}") console.print("[yellow]* Installing required packages (pacman)...[/yellow]") try: run_cmd("pacman -S --noconfirm git python-pip") except subprocess.CalledProcessError as e: console.print(f"[red][!][/red] pacman install failed (non-fatal). You may need to install some packages manually. Error: {e}") else: console.print("[red]Invalid package manager choice[/red]") def prepare_install_dir(): if INSTALL_DIR.exists(): console.print(f"[red]The directory {INSTALL_DIR} already exists.[/red]") if Confirm.ask("Replace it? This will remove the existing directory", default=False): run_cmd(f"rm -rf {str(INSTALL_DIR)}") else: console.print("[red]Installation aborted by user.[/red]") sys.exit(1) INSTALL_DIR.mkdir(parents=True, exist_ok=True) def git_clone(): console.print("[yellow]* Cloning hackingtool repository...[/yellow]") try: run_cmd(f"git clone {REPO_URL} {str(INSTALL_DIR)}") console.print("[green][✔] Repository cloned[/green]") return True except Exception as e: console.print(f"[red][✘] Failed to clone repository: {e}[/red]") return False def create_venv_and_install(choice): venv_path = INSTALL_DIR / VENV_DIR_NAME console.print("[yellow]* Creating virtual environment...[/yellow]") run_cmd(f"python3 -m venv {str(venv_path)}") activate = venv_path / "bin" / "activate" pip = str(venv_path / "bin" / "pip") if (INSTALL_DIR / REQUIREMENTS).exists(): console.print("[yellow]* Installing Python requirements...[/yellow]") run_cmd(f"{pip} install -r {str(INSTALL_DIR / REQUIREMENTS)}") else: console.print("[yellow]requirements.txt not found, skipping pip install.[/yellow]") if choice == 1: run_cmd("apt install figlet -y") elif choice == 2: # try pacman and fallback to AUR instructions try: run_cmd("pacman -S --noconfirm figlet") except Exception: console.print("[yellow]figlet not available in pacman automatically. Consider installing from AUR.[/yellow]") def create_launcher(): console.print("[yellow]* Creating launcher script...[/yellow]") launcher = INSTALL_DIR / "hackingtool.sh" with open(launcher, "w") as f: f.write("#!/bin/bash\n") f.write(f"source {str(INSTALL_DIR / VENV_DIR_NAME)}/bin/activate\n") f.write(f"python3 {str(INSTALL_DIR / 'hackingtool.py')} \"$@\"\n") os.chmod(launcher, 0o755) # move to /usr/bin/hackingtool if BIN_PATH.exists(): BIN_PATH.unlink() shutil.move(str(launcher), str(BIN_PATH)) console.print(f"[green][✔] Launcher installed at {str(BIN_PATH)}[/green]") def final_messages(): panel = Panel( "[bold magenta]Installation complete[/bold magenta]\n\nType [bold cyan]hackingtool[/bold cyan] in terminal to start.", border_style="magenta", ) console.print(panel) def main(): check_root() console.clear() colorful_logo() choice = choose_distro() if choice == 0: console.print("[red]Exiting...[/red]") sys.exit(0) if not check_internet(): sys.exit(1) with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}")) as progress: progress.add_task(description="Preparing system...", total=None) system_update_and_install(choice) prepare_install_dir() ok = git_clone() if not ok: sys.exit(1) with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}")) as progress: progress.add_task(description="Setting up virtualenv & requirements...", total=None) create_venv_and_install(choice) create_launcher() final_messages() if __name__ == "__main__": try: main() except KeyboardInterrupt: console.print("\n[red]Installation interrupted by user[/red]") sys.exit(1) except subprocess.CalledProcessError as e: console.print(f"[red]Command failed: {e}[/red]") sys.exit(1)
{ "repo_id": "Z4nzu/hackingtool", "file_path": "install.py", "license": "MIT License", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:workflow_db.py
#!/usr/bin/env python3 """ Fast N8N Workflow Database SQLite-based workflow indexer and search engine for instant performance. """ import sqlite3 import json import os import datetime import hashlib from typing import Dict, List, Any, Optional, Tuple from pathlib import Path class WorkflowDatabase: """High-performance SQLite database for workflow metadata and search.""" def __init__(self, db_path: str = None): # Use environment variable if no path provided if db_path is None: db_path = os.environ.get("WORKFLOW_DB_PATH", "workflows.db") self.db_path = db_path self.workflows_dir = "workflows" self.init_database() def init_database(self): """Initialize SQLite database with optimized schema and indexes.""" conn = sqlite3.connect(self.db_path) conn.execute("PRAGMA journal_mode=WAL") # Write-ahead logging for performance conn.execute("PRAGMA synchronous=NORMAL") conn.execute("PRAGMA cache_size=10000") conn.execute("PRAGMA temp_store=MEMORY") # Create main workflows table conn.execute(""" CREATE TABLE IF NOT EXISTS workflows ( id INTEGER PRIMARY KEY AUTOINCREMENT, filename TEXT UNIQUE NOT NULL, name TEXT NOT NULL, workflow_id TEXT, active BOOLEAN DEFAULT 0, description TEXT, trigger_type TEXT, complexity TEXT, node_count INTEGER DEFAULT 0, integrations TEXT, -- JSON array tags TEXT, -- JSON array created_at TEXT, updated_at TEXT, file_hash TEXT, file_size INTEGER, analyzed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Create FTS5 table for full-text search conn.execute(""" CREATE VIRTUAL TABLE IF NOT EXISTS workflows_fts USING fts5( filename, name, description, integrations, tags, content=workflows, content_rowid=id ) """) # Create indexes for fast filtering conn.execute( "CREATE INDEX IF NOT EXISTS idx_trigger_type ON workflows(trigger_type)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_complexity ON workflows(complexity)" ) conn.execute("CREATE INDEX IF NOT EXISTS idx_active ON workflows(active)") conn.execute( "CREATE INDEX IF NOT EXISTS idx_node_count ON workflows(node_count)" ) conn.execute("CREATE INDEX IF NOT EXISTS idx_filename ON workflows(filename)") # Create triggers to keep FTS table in sync conn.execute(""" CREATE TRIGGER IF NOT EXISTS workflows_ai AFTER INSERT ON workflows BEGIN INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags) VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags); END """) conn.execute(""" CREATE TRIGGER IF NOT EXISTS workflows_ad AFTER DELETE ON workflows BEGIN INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags) VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags); END """) conn.execute(""" CREATE TRIGGER IF NOT EXISTS workflows_au AFTER UPDATE ON workflows BEGIN INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags) VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags); INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags) VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags); END """) conn.commit() conn.close() def get_file_hash(self, file_path: str) -> str: """Get MD5 hash of file for change detection.""" hash_md5 = hashlib.md5() with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def format_workflow_name(self, filename: str) -> str: """Convert filename to readable workflow name.""" # Remove .json extension name = filename.replace(".json", "") # Split by underscores parts = name.split("_") # Skip the first part if it's just a number if len(parts) > 1 and parts[0].isdigit(): parts = parts[1:] # Convert parts to title case and join with spaces readable_parts = [] for part in parts: # Special handling for common terms if part.lower() == "http": readable_parts.append("HTTP") elif part.lower() == "api": readable_parts.append("API") elif part.lower() == "webhook": readable_parts.append("Webhook") elif part.lower() == "automation": readable_parts.append("Automation") elif part.lower() == "automate": readable_parts.append("Automate") elif part.lower() == "scheduled": readable_parts.append("Scheduled") elif part.lower() == "triggered": readable_parts.append("Triggered") elif part.lower() == "manual": readable_parts.append("Manual") else: # Capitalize first letter readable_parts.append(part.capitalize()) return " ".join(readable_parts) def analyze_workflow_file(self, file_path: str) -> Optional[Dict[str, Any]]: """Analyze a single workflow file and extract metadata.""" try: with open(file_path, "r", encoding="utf-8") as f: data = json.load(f) except (json.JSONDecodeError, UnicodeDecodeError) as e: print(f"Error reading {file_path}: {str(e)}") return None filename = os.path.basename(file_path) file_size = os.path.getsize(file_path) file_hash = self.get_file_hash(file_path) # Extract basic metadata workflow = { "filename": filename, "name": self.format_workflow_name(filename), "workflow_id": data.get("id", ""), "active": data.get("active", False), "nodes": data.get("nodes", []), "connections": data.get("connections", {}), "tags": data.get("tags", []), "created_at": data.get("createdAt", ""), "updated_at": data.get("updatedAt", ""), "file_hash": file_hash, "file_size": file_size, } # Use JSON name if available and meaningful, otherwise use formatted filename json_name = data.get("name", "").strip() if ( json_name and json_name != filename.replace(".json", "") and not json_name.startswith("My workflow") ): workflow["name"] = json_name # If no meaningful JSON name, use formatted filename (already set above) # Analyze nodes node_count = len(workflow["nodes"]) workflow["node_count"] = node_count # Determine complexity if node_count <= 5: complexity = "low" elif node_count <= 15: complexity = "medium" else: complexity = "high" workflow["complexity"] = complexity # Find trigger type and integrations trigger_type, integrations = self.analyze_nodes(workflow["nodes"]) workflow["trigger_type"] = trigger_type workflow["integrations"] = list(integrations) # Use JSON description if available, otherwise generate one json_description = data.get("description", "").strip() if json_description: workflow["description"] = json_description else: workflow["description"] = self.generate_description( workflow, trigger_type, integrations ) return workflow def analyze_nodes(self, nodes: List[Dict]) -> Tuple[str, set]: """Analyze nodes to determine trigger type and integrations.""" trigger_type = "Manual" integrations = set() # Enhanced service mapping for better recognition service_mappings = { # Messaging & Communication "telegram": "Telegram", "telegramTrigger": "Telegram", "discord": "Discord", "slack": "Slack", "whatsapp": "WhatsApp", "mattermost": "Mattermost", "teams": "Microsoft Teams", "rocketchat": "Rocket.Chat", # Email "gmail": "Gmail", "mailjet": "Mailjet", "emailreadimap": "Email (IMAP)", "emailsendsmt": "Email (SMTP)", "outlook": "Outlook", # Cloud Storage "googledrive": "Google Drive", "googledocs": "Google Docs", "googlesheets": "Google Sheets", "dropbox": "Dropbox", "onedrive": "OneDrive", "box": "Box", # Databases "postgres": "PostgreSQL", "mysql": "MySQL", "mongodb": "MongoDB", "redis": "Redis", "airtable": "Airtable", "notion": "Notion", # Project Management "jira": "Jira", "github": "GitHub", "gitlab": "GitLab", "trello": "Trello", "asana": "Asana", "mondaycom": "Monday.com", # AI/ML Services "openai": "OpenAI", "anthropic": "Anthropic", "huggingface": "Hugging Face", # Social Media "linkedin": "LinkedIn", "twitter": "Twitter/X", "facebook": "Facebook", "instagram": "Instagram", # E-commerce "shopify": "Shopify", "stripe": "Stripe", "paypal": "PayPal", # Analytics "googleanalytics": "Google Analytics", "mixpanel": "Mixpanel", # Calendar & Tasks "googlecalendar": "Google Calendar", "googletasks": "Google Tasks", "cal": "Cal.com", "calendly": "Calendly", # Forms & Surveys "typeform": "Typeform", "googleforms": "Google Forms", "form": "Form Trigger", # Development Tools "webhook": "Webhook", "httpRequest": "HTTP Request", "graphql": "GraphQL", "sse": "Server-Sent Events", # Utility nodes (exclude from integrations) "set": None, "function": None, "code": None, "if": None, "switch": None, "merge": None, "split": None, "stickynote": None, "stickyNote": None, "wait": None, "schedule": None, "cron": None, "manual": None, "stopanderror": None, "noop": None, "noOp": None, "error": None, "limit": None, "aggregate": None, "summarize": None, "filter": None, "sort": None, "removeDuplicates": None, "dateTime": None, "extractFromFile": None, "convertToFile": None, "readBinaryFile": None, "readBinaryFiles": None, "executionData": None, "executeWorkflow": None, "executeCommand": None, "respondToWebhook": None, } for node in nodes: node_type = node.get("type", "") node_name = node.get("name", "").lower() # Determine trigger type if "webhook" in node_type.lower() or "webhook" in node_name: trigger_type = "Webhook" elif "cron" in node_type.lower() or "schedule" in node_type.lower(): trigger_type = "Scheduled" elif "trigger" in node_type.lower() and trigger_type == "Manual": if "manual" not in node_type.lower(): trigger_type = "Webhook" # Extract integrations with enhanced mapping service_name = None # Handle n8n-nodes-base nodes if node_type.startswith("n8n-nodes-base."): raw_service = node_type.replace("n8n-nodes-base.", "").lower() raw_service = raw_service.replace("trigger", "") service_name = service_mappings.get( raw_service, raw_service.title() if raw_service else None ) # Handle @n8n/ namespaced nodes elif node_type.startswith("@n8n/"): raw_service = ( node_type.split(".")[-1].lower() if "." in node_type else node_type.lower() ) raw_service = raw_service.replace("trigger", "") service_name = service_mappings.get( raw_service, raw_service.title() if raw_service else None ) # Handle custom nodes elif "-" in node_type or "@" in node_type: # Try to extract service name from custom node names like "n8n-nodes-youtube-transcription-kasha.youtubeTranscripter" parts = node_type.lower().split(".") for part in parts: if "youtube" in part: service_name = "YouTube" break elif "telegram" in part: service_name = "Telegram" break elif "discord" in part: service_name = "Discord" break elif "calcslive" in part: service_name = "CalcsLive" break # Also check node names for service hints (but avoid false positives) for service_key, service_value in service_mappings.items(): if service_key in node_name and service_value: # Avoid false positive: "cal" in calcslive-related terms should not match "Cal.com" if service_key == "cal" and any( term in node_name.lower() for term in ["calcslive", "calc", "calculation"] ): continue service_name = service_value break # Add to integrations if valid service found if service_name and service_name not in ["None", None]: integrations.add(service_name) # Determine if complex based on node variety and count if len(nodes) > 10 and len(integrations) > 3: trigger_type = "Complex" return trigger_type, integrations def generate_description( self, workflow: Dict, trigger_type: str, integrations: set ) -> str: """Generate a descriptive summary of the workflow.""" name = workflow["name"] node_count = workflow["node_count"] # Start with trigger description trigger_descriptions = { "Webhook": "Webhook-triggered automation that", "Scheduled": "Scheduled automation that", "Complex": "Complex multi-step automation that", } desc = trigger_descriptions.get(trigger_type, "Manual workflow that") # Add functionality based on name and integrations if integrations: main_services = list(integrations)[:3] if len(main_services) == 1: desc += f" integrates with {main_services[0]}" elif len(main_services) == 2: desc += f" connects {main_services[0]} and {main_services[1]}" else: desc += f" orchestrates {', '.join(main_services[:-1])}, and {main_services[-1]}" # Add workflow purpose hints from name name_lower = name.lower() if "create" in name_lower: desc += " to create new records" elif "update" in name_lower: desc += " to update existing data" elif "sync" in name_lower: desc += " to synchronize data" elif "notification" in name_lower or "alert" in name_lower: desc += " for notifications and alerts" elif "backup" in name_lower: desc += " for data backup operations" elif "monitor" in name_lower: desc += " for monitoring and reporting" else: desc += " for data processing" desc += f". Uses {node_count} nodes" if len(integrations) > 3: desc += f" and integrates with {len(integrations)} services" return desc + "." def index_all_workflows(self, force_reindex: bool = False) -> Dict[str, int]: """Index all workflow files. Only reprocesses changed files unless force_reindex=True.""" if not os.path.exists(self.workflows_dir): print(f"Warning: Workflows directory '{self.workflows_dir}' not found.") return {"processed": 0, "skipped": 0, "errors": 0} workflows_path = Path(self.workflows_dir) json_files = [str(p) for p in workflows_path.rglob("*.json")] if not json_files: print(f"Warning: No JSON files found in '{self.workflows_dir}' directory.") return {"processed": 0, "skipped": 0, "errors": 0} print(f"Indexing {len(json_files)} workflow files...") conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row stats = {"processed": 0, "skipped": 0, "errors": 0} for file_path in json_files: filename = os.path.basename(file_path) try: # Check if file needs to be reprocessed if not force_reindex: current_hash = self.get_file_hash(file_path) cursor = conn.execute( "SELECT file_hash FROM workflows WHERE filename = ?", (filename,), ) row = cursor.fetchone() if row and row["file_hash"] == current_hash: stats["skipped"] += 1 continue # Analyze workflow workflow_data = self.analyze_workflow_file(file_path) if not workflow_data: stats["errors"] += 1 continue # Insert or update in database conn.execute( """ INSERT OR REPLACE INTO workflows ( filename, name, workflow_id, active, description, trigger_type, complexity, node_count, integrations, tags, created_at, updated_at, file_hash, file_size, analyzed_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) """, ( workflow_data["filename"], workflow_data["name"], workflow_data["workflow_id"], workflow_data["active"], workflow_data["description"], workflow_data["trigger_type"], workflow_data["complexity"], workflow_data["node_count"], json.dumps(workflow_data["integrations"]), json.dumps(workflow_data["tags"]), workflow_data["created_at"], workflow_data["updated_at"], workflow_data["file_hash"], workflow_data["file_size"], ), ) stats["processed"] += 1 except Exception as e: print(f"Error processing {file_path}: {str(e)}") stats["errors"] += 1 continue conn.commit() conn.close() print( f"✅ Indexing complete: {stats['processed']} processed, {stats['skipped']} skipped, {stats['errors']} errors" ) return stats def search_workflows( self, query: str = "", trigger_filter: str = "all", complexity_filter: str = "all", active_only: bool = False, limit: int = 50, offset: int = 0, ) -> Tuple[List[Dict], int]: """Fast search with filters and pagination.""" conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row # Build WHERE clause where_conditions = [] params = [] if active_only: where_conditions.append("w.active = 1") if trigger_filter != "all": where_conditions.append("w.trigger_type = ?") params.append(trigger_filter) if complexity_filter != "all": where_conditions.append("w.complexity = ?") params.append(complexity_filter) # Use FTS search if query provided if query.strip(): # FTS search with ranking base_query = """ SELECT w.*, rank FROM workflows_fts fts JOIN workflows w ON w.id = fts.rowid WHERE workflows_fts MATCH ? """ params.insert(0, query) else: # Regular query without FTS base_query = """ SELECT w.*, 0 as rank FROM workflows w WHERE 1=1 """ if where_conditions: base_query += " AND " + " AND ".join(where_conditions) # Count total results count_query = f"SELECT COUNT(*) as total FROM ({base_query}) t" cursor = conn.execute(count_query, params) total = cursor.fetchone()["total"] # Get paginated results if query.strip(): base_query += " ORDER BY rank" else: base_query += " ORDER BY w.analyzed_at DESC" base_query += f" LIMIT {limit} OFFSET {offset}" cursor = conn.execute(base_query, params) rows = cursor.fetchall() # Convert to dictionaries and parse JSON fields results = [] for row in rows: workflow = dict(row) workflow["integrations"] = json.loads(workflow["integrations"] or "[]") # Parse tags and convert dict tags to strings raw_tags = json.loads(workflow["tags"] or "[]") clean_tags = [] for tag in raw_tags: if isinstance(tag, dict): # Extract name from tag dict if available clean_tags.append(tag.get("name", str(tag.get("id", "tag")))) else: clean_tags.append(str(tag)) workflow["tags"] = clean_tags results.append(workflow) conn.close() return results, total def get_stats(self) -> Dict[str, Any]: """Get database statistics.""" conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row # Basic counts cursor = conn.execute("SELECT COUNT(*) as total FROM workflows") total = cursor.fetchone()["total"] cursor = conn.execute( "SELECT COUNT(*) as active FROM workflows WHERE active = 1" ) active = cursor.fetchone()["active"] # Trigger type breakdown cursor = conn.execute(""" SELECT trigger_type, COUNT(*) as count FROM workflows GROUP BY trigger_type """) triggers = {row["trigger_type"]: row["count"] for row in cursor.fetchall()} # Complexity breakdown cursor = conn.execute(""" SELECT complexity, COUNT(*) as count FROM workflows GROUP BY complexity """) complexity = {row["complexity"]: row["count"] for row in cursor.fetchall()} # Node stats cursor = conn.execute("SELECT SUM(node_count) as total_nodes FROM workflows") total_nodes = cursor.fetchone()["total_nodes"] or 0 # Unique integrations count cursor = conn.execute( "SELECT integrations FROM workflows WHERE integrations != '[]'" ) all_integrations = set() for row in cursor.fetchall(): integrations = json.loads(row["integrations"]) all_integrations.update(integrations) conn.close() return { "total": total, "active": active, "inactive": total - active, "triggers": triggers, "complexity": complexity, "total_nodes": total_nodes, "unique_integrations": len(all_integrations), "last_indexed": datetime.datetime.now().isoformat(), } def get_service_categories(self) -> Dict[str, List[str]]: """Get service categories for enhanced filtering.""" return { "messaging": [ "Telegram", "Discord", "Slack", "WhatsApp", "Mattermost", "Microsoft Teams", "Rocket.Chat", ], "email": ["Gmail", "Mailjet", "Email (IMAP)", "Email (SMTP)", "Outlook"], "cloud_storage": [ "Google Drive", "Google Docs", "Google Sheets", "Dropbox", "OneDrive", "Box", ], "database": [ "PostgreSQL", "MySQL", "MongoDB", "Redis", "Airtable", "Notion", ], "project_management": [ "Jira", "GitHub", "GitLab", "Trello", "Asana", "Monday.com", ], "ai_ml": ["OpenAI", "Anthropic", "Hugging Face", "CalcsLive"], "social_media": ["LinkedIn", "Twitter/X", "Facebook", "Instagram"], "ecommerce": ["Shopify", "Stripe", "PayPal"], "analytics": ["Google Analytics", "Mixpanel"], "calendar_tasks": [ "Google Calendar", "Google Tasks", "Cal.com", "Calendly", ], "forms": ["Typeform", "Google Forms", "Form Trigger"], "development": [ "Webhook", "HTTP Request", "GraphQL", "Server-Sent Events", "YouTube", ], } def search_by_category( self, category: str, limit: int = 50, offset: int = 0 ) -> Tuple[List[Dict], int]: """Search workflows by service category.""" categories = self.get_service_categories() if category not in categories: return [], 0 services = categories[category] conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row # Build OR conditions for all services in category service_conditions = [] params = [] for service in services: service_conditions.append("integrations LIKE ?") params.append(f'%"{service}"%') where_clause = " OR ".join(service_conditions) # Count total results count_query = f"SELECT COUNT(*) as total FROM workflows WHERE {where_clause}" cursor = conn.execute(count_query, params) total = cursor.fetchone()["total"] # Get paginated results query = f""" SELECT * FROM workflows WHERE {where_clause} ORDER BY analyzed_at DESC LIMIT {limit} OFFSET {offset} """ cursor = conn.execute(query, params) rows = cursor.fetchall() # Convert to dictionaries and parse JSON fields results = [] for row in rows: workflow = dict(row) workflow["integrations"] = json.loads(workflow["integrations"] or "[]") raw_tags = json.loads(workflow["tags"] or "[]") clean_tags = [] for tag in raw_tags: if isinstance(tag, dict): clean_tags.append(tag.get("name", str(tag.get("id", "tag")))) else: clean_tags.append(str(tag)) workflow["tags"] = clean_tags results.append(workflow) conn.close() return results, total def main(): """Command-line interface for workflow database.""" import argparse parser = argparse.ArgumentParser(description="N8N Workflow Database") parser.add_argument("--index", action="store_true", help="Index all workflows") parser.add_argument("--force", action="store_true", help="Force reindex all files") parser.add_argument("--search", help="Search workflows") parser.add_argument("--stats", action="store_true", help="Show database statistics") args = parser.parse_args() db = WorkflowDatabase() if args.index: stats = db.index_all_workflows(force_reindex=args.force) print(f"Indexed {stats['processed']} workflows") elif args.search: results, total = db.search_workflows(args.search, limit=10) print(f"Found {total} workflows:") for workflow in results: print( f" - {workflow['name']} ({workflow['trigger_type']}, {workflow['node_count']} nodes)" ) elif args.stats: stats = db.get_stats() print("Database Statistics:") print(f" Total workflows: {stats['total']}") print(f" Active: {stats['active']}") print(f" Total nodes: {stats['total_nodes']}") print(f" Unique integrations: {stats['unique_integrations']}") print(f" Trigger types: {stats['triggers']}") else: parser.print_help() if __name__ == "__main__": main()
{ "repo_id": "Zie619/n8n-workflows", "file_path": "workflow_db.py", "license": "MIT License", "lines": 731, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:scripts/update_github_pages.py
#!/usr/bin/env python3 """ Update GitHub Pages Files Fixes the hardcoded timestamp and ensures proper deployment. Addresses Issues #115 and #129. """ import json from datetime import datetime from pathlib import Path import re def update_html_timestamp(html_file: str): """Update the timestamp in the HTML file to current date.""" file_path = Path(html_file) if not file_path.exists(): print(f"Warning: {html_file} not found") return False # Read the HTML file with open(file_path, "r", encoding="utf-8") as f: content = f.read() # Get current month and year current_date = datetime.now().strftime("%B %Y") # Replace the hardcoded timestamp # Look for pattern like "Last updated: Month Year" pattern = r'(<p class="footer-meta">Last updated:)\s*([^<]+)' replacement = f"\\1 {current_date}" updated_content = re.sub(pattern, replacement, content) # Also add a meta tag with the exact timestamp for better tracking if '<meta name="last-updated"' not in updated_content: timestamp_meta = ( f' <meta name="last-updated" content="{datetime.now().isoformat()}">\n' ) updated_content = updated_content.replace("</head>", f"{timestamp_meta}</head>") # Write back the updated content with open(file_path, "w", encoding="utf-8") as f: f.write(updated_content) print(f"✅ Updated timestamp in {html_file} to: {current_date}") return True def update_api_timestamp(api_dir: str): """Update timestamp in API JSON files.""" api_path = Path(api_dir) if not api_path.exists(): api_path.mkdir(parents=True, exist_ok=True) # Create or update a metadata file with current timestamp metadata = { "last_updated": datetime.now().isoformat(), "last_updated_readable": datetime.now().strftime("%B %d, %Y at %H:%M UTC"), "version": "2.0.1", "deployment_type": "github_pages", } metadata_file = api_path / "metadata.json" with open(metadata_file, "w", encoding="utf-8") as f: json.dump(metadata, f, indent=2) print(f"✅ Created metadata file: {metadata_file}") # Update stats.json if it exists stats_file = api_path / "stats.json" if stats_file.exists(): with open(stats_file, "r", encoding="utf-8") as f: stats = json.load(f) stats["last_updated"] = datetime.now().isoformat() with open(stats_file, "w", encoding="utf-8") as f: json.dump(stats, f, indent=2) print(f"✅ Updated stats file: {stats_file}") return True def create_github_pages_config(): """Create necessary GitHub Pages configuration files.""" # Create/update _config.yml for Jekyll (GitHub Pages) config_content = """# GitHub Pages Configuration theme: null title: N8N Workflows Repository description: Browse and search 2000+ n8n workflow automation templates baseurl: "/n8n-workflows" url: "https://zie619.github.io" # Build settings markdown: kramdown exclude: - workflows/ - scripts/ - src/ - "*.py" - requirements.txt - Dockerfile - docker-compose.yml - k8s/ - helm/ - Documentation/ - context/ - database/ - static/ - templates/ - .github/ - .devcontainer/ """ config_file = Path("docs/_config.yml") with open(config_file, "w", encoding="utf-8") as f: f.write(config_content) print(f"✅ Created Jekyll config: {config_file}") # Create .nojekyll file to bypass Jekyll processing (for pure HTML/JS site) nojekyll_file = Path("docs/.nojekyll") nojekyll_file.touch() print(f"✅ Created .nojekyll file: {nojekyll_file}") # Create a simple 404.html page error_page_content = """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404 - Page Not Found</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; } .container { text-align: center; padding: 2rem; } h1 { font-size: 6rem; margin: 0; } p { font-size: 1.5rem; margin: 1rem 0; } a { display: inline-block; margin-top: 2rem; padding: 1rem 2rem; background: white; color: #667eea; text-decoration: none; border-radius: 5px; transition: transform 0.2s; } a:hover { transform: scale(1.05); } </style> </head> <body> <div class="container"> <h1>404</h1> <p>Page not found</p> <p>The n8n workflows repository has been updated.</p> <a href="/n8n-workflows/">Go to Homepage</a> </div> </body> </html>""" error_file = Path("docs/404.html") with open(error_file, "w", encoding="utf-8") as f: f.write(error_page_content) print(f"✅ Created 404 page: {error_file}") def verify_github_pages_structure(): """Verify that all necessary files exist for GitHub Pages deployment.""" required_files = [ "docs/index.html", "docs/css/styles.css", "docs/js/app.js", "docs/js/search.js", "docs/api/search-index.json", "docs/api/stats.json", "docs/api/categories.json", "docs/api/integrations.json", ] missing_files = [] for file_path in required_files: if not Path(file_path).exists(): missing_files.append(file_path) print(f"❌ Missing: {file_path}") else: print(f"✅ Found: {file_path}") if missing_files: print(f"\n⚠️ Warning: {len(missing_files)} required files are missing") print("Run the following commands to generate them:") print(" python workflow_db.py --index --force") print(" python create_categories.py") print(" python scripts/generate_search_index.py") return False print("\n✅ All required files present for GitHub Pages deployment") return True def fix_base_url_references(): """Fix any hardcoded URLs to use relative paths for GitHub Pages.""" # Update index.html to use relative paths index_file = Path("docs/index.html") if index_file.exists(): with open(index_file, "r", encoding="utf-8") as f: content = f.read() # Replace absolute paths with relative ones replacements = [ ('href="/css/', 'href="css/'), ('src="/js/', 'src="js/'), ('href="/api/', 'href="api/'), ('fetch("/api/', 'fetch("api/'), ("fetch('/api/", "fetch('api/"), ] for old, new in replacements: content = content.replace(old, new) with open(index_file, "w", encoding="utf-8") as f: f.write(content) print("✅ Fixed URL references in index.html") # Update JavaScript files js_files = ["docs/js/app.js", "docs/js/search.js"] for js_file in js_files: js_path = Path(js_file) if js_path.exists(): with open(js_path, "r", encoding="utf-8") as f: content = f.read() # Fix API endpoint references content = content.replace("fetch('/api/", "fetch('api/") content = content.replace('fetch("/api/', 'fetch("api/') content = content.replace("'/api/", "'api/") content = content.replace('"/api/', '"api/') with open(js_path, "w", encoding="utf-8") as f: f.write(content) print(f"✅ Fixed URL references in {js_file}") def main(): """Main function to update GitHub Pages deployment.""" print("🔧 GitHub Pages Update Script") print("=" * 50) # Step 1: Update timestamps print("\n📅 Updating timestamps...") update_html_timestamp("docs/index.html") update_api_timestamp("docs/api") # Step 2: Create GitHub Pages configuration print("\n⚙️ Creating GitHub Pages configuration...") create_github_pages_config() # Step 3: Fix URL references print("\n🔗 Fixing URL references...") fix_base_url_references() # Step 4: Verify structure print("\n✔️ Verifying deployment structure...") if verify_github_pages_structure(): print("\n✨ GitHub Pages setup complete!") print("\nDeployment will be available at:") print(" https://zie619.github.io/n8n-workflows/") print( "\nNote: It may take a few minutes for changes to appear after pushing to GitHub." ) else: print("\n⚠️ Some files are missing. Please generate them first.") if __name__ == "__main__": main()
{ "repo_id": "Zie619/n8n-workflows", "file_path": "scripts/update_github_pages.py", "license": "MIT License", "lines": 240, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:scripts/generate_search_index.py
#!/usr/bin/env python3 """ Generate Static Search Index for GitHub Pages Creates a lightweight JSON index for client-side search functionality. """ import json import os import sys from pathlib import Path from typing import Dict, List, Any # Add the parent directory to path for imports sys.path.append(str(Path(__file__).parent.parent)) from workflow_db import WorkflowDatabase def generate_static_search_index(db_path: str, output_dir: str) -> Dict[str, Any]: """Generate a static search index for client-side searching.""" # Initialize database db = WorkflowDatabase(db_path) # Get all workflows workflows, total = db.search_workflows(limit=10000) # Get all workflows # Get statistics stats = db.get_stats() # Get categories from service mapping categories = db.get_service_categories() # Load existing categories from create_categories.py system existing_categories = load_existing_categories() # Create simplified workflow data for search search_workflows = [] for workflow in workflows: # Create searchable text combining multiple fields searchable_text = " ".join( [ workflow["name"], workflow["description"], workflow["filename"], " ".join(workflow["integrations"]), " ".join(workflow["tags"]) if workflow["tags"] else "", ] ).lower() # Use existing category from create_categories.py system, fallback to integration-based category = get_workflow_category( workflow["filename"], existing_categories, workflow["integrations"], categories, ) search_workflow = { "id": workflow["filename"].replace(".json", ""), "name": workflow["name"], "description": workflow["description"], "filename": workflow["filename"], "active": workflow["active"], "trigger_type": workflow["trigger_type"], "complexity": workflow["complexity"], "node_count": workflow["node_count"], "integrations": workflow["integrations"], "tags": workflow["tags"], "category": category, "searchable_text": searchable_text, "download_url": f"https://raw.githubusercontent.com/Zie619/n8n-workflows/main/workflows/{extract_folder_from_filename(workflow['filename'])}/{workflow['filename']}", } search_workflows.append(search_workflow) # Create comprehensive search index search_index = { "version": "1.0", "generated_at": stats.get("last_indexed", ""), "stats": { "total_workflows": stats["total"], "active_workflows": stats["active"], "inactive_workflows": stats["inactive"], "total_nodes": stats["total_nodes"], "unique_integrations": stats["unique_integrations"], "categories": len(get_category_list(categories)), "triggers": stats["triggers"], "complexity": stats["complexity"], }, "categories": get_category_list(categories), "integrations": get_popular_integrations(workflows), "workflows": search_workflows, } return search_index def load_existing_categories() -> Dict[str, str]: """Load existing categories from search_categories.json created by create_categories.py.""" try: with open("context/search_categories.json", "r", encoding="utf-8") as f: categories_data = json.load(f) # Convert to filename -> category mapping category_mapping = {} for item in categories_data: if item.get("category"): category_mapping[item["filename"]] = item["category"] return category_mapping except FileNotFoundError: print( "Warning: search_categories.json not found, using integration-based categorization" ) return {} def get_workflow_category( filename: str, existing_categories: Dict[str, str], integrations: List[str], service_categories: Dict[str, List[str]], ) -> str: """Get category for workflow, preferring existing assignment over integration-based.""" # First priority: Use existing category from create_categories.py system if filename in existing_categories: return existing_categories[filename] # Fallback: Use integration-based categorization return determine_category(integrations, service_categories) def determine_category( integrations: List[str], categories: Dict[str, List[str]] ) -> str: """Determine the category for a workflow based on its integrations.""" if not integrations: return "Uncategorized" # Check each category for matching integrations for category, services in categories.items(): for integration in integrations: if integration in services: return format_category_name(category) return "Uncategorized" def format_category_name(category_key: str) -> str: """Format category key to display name.""" category_mapping = { "messaging": "Communication & Messaging", "email": "Communication & Messaging", "cloud_storage": "Cloud Storage & File Management", "database": "Data Processing & Analysis", "project_management": "Project Management", "ai_ml": "AI Agent Development", "social_media": "Social Media Management", "ecommerce": "E-commerce & Retail", "analytics": "Data Processing & Analysis", "calendar_tasks": "Project Management", "forms": "Data Processing & Analysis", "development": "Technical Infrastructure & DevOps", } return category_mapping.get(category_key, category_key.replace("_", " ").title()) def get_category_list(categories: Dict[str, List[str]]) -> List[str]: """Get formatted list of all categories.""" formatted_categories = set() for category_key in categories.keys(): formatted_categories.add(format_category_name(category_key)) # Add categories from the create_categories.py system additional_categories = [ "Business Process Automation", "Web Scraping & Data Extraction", "Marketing & Advertising Automation", "Creative Content & Video Automation", "Creative Design Automation", "CRM & Sales", "Financial & Accounting", ] for cat in additional_categories: formatted_categories.add(cat) return sorted(list(formatted_categories)) def get_popular_integrations(workflows: List[Dict]) -> List[Dict[str, Any]]: """Get list of popular integrations with counts.""" integration_counts = {} for workflow in workflows: for integration in workflow["integrations"]: integration_counts[integration] = integration_counts.get(integration, 0) + 1 # Sort by count and take top 50 sorted_integrations = sorted( integration_counts.items(), key=lambda x: x[1], reverse=True )[:50] return [{"name": name, "count": count} for name, count in sorted_integrations] def extract_folder_from_filename(filename: str) -> str: """Extract folder name from workflow filename.""" # Most workflows follow pattern: ID_Service_Purpose_Trigger.json # Extract the service name as folder parts = filename.replace(".json", "").split("_") if len(parts) >= 2: return parts[1].capitalize() # Second part is usually the service return "Misc" def save_search_index(search_index: Dict[str, Any], output_dir: str): """Save the search index to multiple formats for different uses.""" # Ensure output directory exists os.makedirs(output_dir, exist_ok=True) # Save complete index with open( os.path.join(output_dir, "search-index.json"), "w", encoding="utf-8" ) as f: json.dump(search_index, f, indent=2, ensure_ascii=False) # Save stats only (for quick loading) with open(os.path.join(output_dir, "stats.json"), "w", encoding="utf-8") as f: json.dump(search_index["stats"], f, indent=2, ensure_ascii=False) # Save categories only with open(os.path.join(output_dir, "categories.json"), "w", encoding="utf-8") as f: json.dump(search_index["categories"], f, indent=2, ensure_ascii=False) # Save integrations only with open( os.path.join(output_dir, "integrations.json"), "w", encoding="utf-8" ) as f: json.dump(search_index["integrations"], f, indent=2, ensure_ascii=False) print("Search index generated successfully:") print(f" {search_index['stats']['total_workflows']} workflows indexed") print(f" {len(search_index['categories'])} categories") print(f" {len(search_index['integrations'])} popular integrations") print(f" Files saved to: {output_dir}") def main(): """Main function to generate search index.""" # Paths db_path = "database/workflows.db" output_dir = "docs/api" # Check if database exists if not os.path.exists(db_path): print(f"Database not found: {db_path}") print("Run 'python run.py --reindex' first to create the database") sys.exit(1) try: print("Generating static search index...") search_index = generate_static_search_index(db_path, output_dir) save_search_index(search_index, output_dir) print("Static search index ready for GitHub Pages!") except Exception as e: print(f"Error generating search index: {e}") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "Zie619/n8n-workflows", "file_path": "scripts/generate_search_index.py", "license": "MIT License", "lines": 219, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:scripts/update_readme_stats.py
#!/usr/bin/env python3 """ Update README.md with current workflow statistics Replaces hardcoded numbers with live data from the database. """ import os import re import sys from pathlib import Path from datetime import datetime # Add the parent directory to path for imports sys.path.append(str(Path(__file__).parent.parent)) from workflow_db import WorkflowDatabase def get_current_stats(): """Get current workflow statistics from the database.""" db_path = "database/workflows.db" if not os.path.exists(db_path): print("Database not found. Run workflow indexing first.") return None db = WorkflowDatabase(db_path) stats = db.get_stats() # Get categories count categories = db.get_service_categories() return { "total_workflows": stats["total"], "active_workflows": stats["active"], "inactive_workflows": stats["inactive"], "total_nodes": stats["total_nodes"], "unique_integrations": stats["unique_integrations"], "categories_count": len(get_category_list(categories)), "triggers": stats["triggers"], "complexity": stats["complexity"], "last_updated": datetime.now().strftime("%Y-%m-%d"), } def get_category_list(categories): """Get formatted list of all categories (same logic as search index).""" formatted_categories = set() # Map technical categories to display names category_mapping = { "messaging": "Communication & Messaging", "email": "Communication & Messaging", "cloud_storage": "Cloud Storage & File Management", "database": "Data Processing & Analysis", "project_management": "Project Management", "ai_ml": "AI Agent Development", "social_media": "Social Media Management", "ecommerce": "E-commerce & Retail", "analytics": "Data Processing & Analysis", "calendar_tasks": "Project Management", "forms": "Data Processing & Analysis", "development": "Technical Infrastructure & DevOps", } for category_key in categories.keys(): display_name = category_mapping.get( category_key, category_key.replace("_", " ").title() ) formatted_categories.add(display_name) # Add categories from the create_categories.py system additional_categories = [ "Business Process Automation", "Web Scraping & Data Extraction", "Marketing & Advertising Automation", "Creative Content & Video Automation", "Creative Design Automation", "CRM & Sales", "Financial & Accounting", ] for cat in additional_categories: formatted_categories.add(cat) return sorted(list(formatted_categories)) def update_readme_stats(stats): """Update README.md with current statistics.""" readme_path = "README.md" if not os.path.exists(readme_path): print("README.md not found") return False with open(readme_path, "r", encoding="utf-8") as f: content = f.read() # Define replacement patterns and their new values replacements = [ # Main collection description ( r"A professionally organized collection of \*\*[\d,]+\s+n8n workflows\*\*", f"A professionally organized collection of **{stats['total_workflows']:,} n8n workflows**", ), # Total workflows in various contexts ( r"- \*\*[\d,]+\s+workflows\*\* with meaningful", f"- **{stats['total_workflows']:,} workflows** with meaningful", ), # Statistics section ( r"- \*\*Total Workflows\*\*: [\d,]+", f"- **Total Workflows**: {stats['total_workflows']:,}", ), ( r"- \*\*Active Workflows\*\*: [\d,]+ \([\d.]+%", f"- **Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}%", ), ( r"- \*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes", f"- **Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes", ), ( r"- \*\*Unique Integrations\*\*: [\d,]+ different", f"- **Unique Integrations**: {stats['unique_integrations']:,} different", ), # Update complexity/trigger distribution ( r"- \*\*Complex\*\*: [\d,]+ workflows \([\d.]+%\)", f"- **Complex**: {stats['triggers'].get('Complex', 0):,} workflows ({(stats['triggers'].get('Complex', 0) / stats['total_workflows'] * 100):.1f}%)", ), ( r"- \*\*Webhook\*\*: [\d,]+ workflows \([\d.]+%\)", f"- **Webhook**: {stats['triggers'].get('Webhook', 0):,} workflows ({(stats['triggers'].get('Webhook', 0) / stats['total_workflows'] * 100):.1f}%)", ), ( r"- \*\*Manual\*\*: [\d,]+ workflows \([\d.]+%\)", f"- **Manual**: {stats['triggers'].get('Manual', 0):,} workflows ({(stats['triggers'].get('Manual', 0) / stats['total_workflows'] * 100):.1f}%)", ), ( r"- \*\*Scheduled\*\*: [\d,]+ workflows \([\d.]+%\)", f"- **Scheduled**: {stats['triggers'].get('Scheduled', 0):,} workflows ({(stats['triggers'].get('Scheduled', 0) / stats['total_workflows'] * 100):.1f}%)", ), # Update total in current collection stats ( r"\*\*Total Workflows\*\*: [\d,]+ automation", f"**Total Workflows**: {stats['total_workflows']:,} automation", ), ( r"\*\*Active Workflows\*\*: [\d,]+ \([\d.]+% active", f"**Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}% active", ), ( r"\*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes", f"**Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes", ), ( r"\*\*Unique Integrations\*\*: [\d,]+ different", f"**Unique Integrations**: {stats['unique_integrations']:,} different", ), # Categories count ( r"Our system automatically categorizes workflows into [\d]+ service categories", f"Our system automatically categorizes workflows into {stats['categories_count']} service categories", ), # Update any "2000+" references (r"2000\+", f"{stats['total_workflows']:,}+"), (r"2,000\+", f"{stats['total_workflows']:,}+"), # Search across X workflows ( r"Search across [\d,]+ workflows", f"Search across {stats['total_workflows']:,} workflows", ), # Instant search across X workflows ( r"Instant search across [\d,]+ workflows", f"Instant search across {stats['total_workflows']:,} workflows", ), ] # Apply all replacements updated_content = content replacements_made = 0 for pattern, replacement in replacements: old_content = updated_content updated_content = re.sub(pattern, replacement, updated_content) if updated_content != old_content: replacements_made += 1 # Write back to file with open(readme_path, "w", encoding="utf-8") as f: f.write(updated_content) print("README.md updated with current statistics:") print(f" - Total workflows: {stats['total_workflows']:,}") print(f" - Active workflows: {stats['active_workflows']:,}") print(f" - Total nodes: {stats['total_nodes']:,}") print(f" - Unique integrations: {stats['unique_integrations']:,}") print(f" - Categories: {stats['categories_count']}") print(f" - Replacements made: {replacements_made}") return True def main(): """Main function to update README statistics.""" try: print("Getting current workflow statistics...") stats = get_current_stats() if not stats: print("Failed to get statistics") sys.exit(1) print("Updating README.md...") success = update_readme_stats(stats) if success: print("README.md successfully updated with latest statistics!") else: print("Failed to update README.md") sys.exit(1) except Exception as e: print(f"Error updating README stats: {e}") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "Zie619/n8n-workflows", "file_path": "scripts/update_readme_stats.py", "license": "MIT License", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:src/community_features.py
#!/usr/bin/env python3 """ Community Features Module for n8n Workflows Repository Implements rating, review, and social features """ import sqlite3 import json from datetime import datetime from typing import Dict, List, Optional from dataclasses import dataclass @dataclass class WorkflowRating: """Workflow rating data structure""" workflow_id: str user_id: str rating: int # 1-5 stars review: Optional[str] = None helpful_votes: int = 0 created_at: datetime = None updated_at: datetime = None @dataclass class WorkflowStats: """Workflow statistics""" workflow_id: str total_ratings: int average_rating: float total_reviews: int total_views: int total_downloads: int last_updated: datetime class CommunityFeatures: """Community features manager for workflow repository""" def __init__(self, db_path: str = "workflows.db"): """Initialize community features with database connection""" self.db_path = db_path self.init_community_tables() def init_community_tables(self): """Initialize community feature database tables""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Workflow ratings and reviews cursor.execute(""" CREATE TABLE IF NOT EXISTS workflow_ratings ( id INTEGER PRIMARY KEY AUTOINCREMENT, workflow_id TEXT NOT NULL, user_id TEXT NOT NULL, rating INTEGER CHECK(rating >= 1 AND rating <= 5), review TEXT, helpful_votes INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(workflow_id, user_id) ) """) # Workflow usage statistics cursor.execute(""" CREATE TABLE IF NOT EXISTS workflow_stats ( workflow_id TEXT PRIMARY KEY, total_ratings INTEGER DEFAULT 0, average_rating REAL DEFAULT 0.0, total_reviews INTEGER DEFAULT 0, total_views INTEGER DEFAULT 0, total_downloads INTEGER DEFAULT 0, last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # User profiles cursor.execute(""" CREATE TABLE IF NOT EXISTS user_profiles ( user_id TEXT PRIMARY KEY, username TEXT, display_name TEXT, email TEXT, avatar_url TEXT, bio TEXT, github_url TEXT, website_url TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Workflow collections (user favorites) cursor.execute(""" CREATE TABLE IF NOT EXISTS workflow_collections ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT NOT NULL, collection_name TEXT NOT NULL, workflow_ids TEXT, -- JSON array of workflow IDs is_public BOOLEAN DEFAULT FALSE, description TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Workflow comments cursor.execute(""" CREATE TABLE IF NOT EXISTS workflow_comments ( id INTEGER PRIMARY KEY AUTOINCREMENT, workflow_id TEXT NOT NULL, user_id TEXT NOT NULL, parent_id INTEGER, -- For threaded comments comment TEXT NOT NULL, helpful_votes INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() conn.close() def add_rating( self, workflow_id: str, user_id: str, rating: int, review: str = None ) -> bool: """Add or update a workflow rating and review""" if not (1 <= rating <= 5): raise ValueError("Rating must be between 1 and 5") conn = sqlite3.connect(self.db_path) cursor = conn.cursor() try: # Insert or update rating cursor.execute( """ INSERT OR REPLACE INTO workflow_ratings (workflow_id, user_id, rating, review, updated_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) """, (workflow_id, user_id, rating, review), ) # Update workflow statistics self._update_workflow_stats(workflow_id) conn.commit() return True except Exception as e: print(f"Error adding rating: {e}") return False finally: conn.close() def get_workflow_ratings( self, workflow_id: str, limit: int = 10 ) -> List[WorkflowRating]: """Get ratings and reviews for a workflow""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT workflow_id, user_id, rating, review, helpful_votes, created_at, updated_at FROM workflow_ratings WHERE workflow_id = ? ORDER BY helpful_votes DESC, created_at DESC LIMIT ? """, (workflow_id, limit), ) ratings = [] for row in cursor.fetchall(): ratings.append( WorkflowRating( workflow_id=row[0], user_id=row[1], rating=row[2], review=row[3], helpful_votes=row[4], created_at=datetime.fromisoformat(row[5]) if row[5] else None, updated_at=datetime.fromisoformat(row[6]) if row[6] else None, ) ) conn.close() return ratings def get_workflow_stats(self, workflow_id: str) -> Optional[WorkflowStats]: """Get comprehensive statistics for a workflow""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT workflow_id, total_ratings, average_rating, total_reviews, total_views, total_downloads, last_updated FROM workflow_stats WHERE workflow_id = ? """, (workflow_id,), ) row = cursor.fetchone() conn.close() if row: return WorkflowStats( workflow_id=row[0], total_ratings=row[1], average_rating=row[2], total_reviews=row[3], total_views=row[4], total_downloads=row[5], last_updated=datetime.fromisoformat(row[6]) if row[6] else None, ) return None def increment_view(self, workflow_id: str): """Increment view count for a workflow""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ INSERT OR IGNORE INTO workflow_stats (workflow_id, total_views) VALUES (?, 1) """, (workflow_id,), ) cursor.execute( """ UPDATE workflow_stats SET total_views = total_views + 1, last_updated = CURRENT_TIMESTAMP WHERE workflow_id = ? """, (workflow_id,), ) conn.commit() conn.close() def increment_download(self, workflow_id: str): """Increment download count for a workflow""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ INSERT OR IGNORE INTO workflow_stats (workflow_id, total_downloads) VALUES (?, 1) """, (workflow_id,), ) cursor.execute( """ UPDATE workflow_stats SET total_downloads = total_downloads + 1, last_updated = CURRENT_TIMESTAMP WHERE workflow_id = ? """, (workflow_id,), ) conn.commit() conn.close() def get_top_rated_workflows(self, limit: int = 10) -> List[Dict]: """Get top-rated workflows""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT w.filename, w.name, w.description, ws.average_rating, ws.total_ratings FROM workflows w JOIN workflow_stats ws ON w.filename = ws.workflow_id WHERE ws.total_ratings >= 3 ORDER BY ws.average_rating DESC, ws.total_ratings DESC LIMIT ? """, (limit,), ) results = [] for row in cursor.fetchall(): results.append( { "filename": row[0], "name": row[1], "description": row[2], "average_rating": row[3], "total_ratings": row[4], } ) conn.close() return results def get_most_popular_workflows(self, limit: int = 10) -> List[Dict]: """Get most popular workflows by views and downloads""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT w.filename, w.name, w.description, ws.total_views, ws.total_downloads FROM workflows w LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id ORDER BY (ws.total_views + ws.total_downloads) DESC LIMIT ? """, (limit,), ) results = [] for row in cursor.fetchall(): results.append( { "filename": row[0], "name": row[1], "description": row[2], "total_views": row[3] or 0, "total_downloads": row[4] or 0, } ) conn.close() return results def create_collection( self, user_id: str, collection_name: str, workflow_ids: List[str], is_public: bool = False, description: str = None, ) -> bool: """Create a workflow collection""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() try: cursor.execute( """ INSERT INTO workflow_collections (user_id, collection_name, workflow_ids, is_public, description) VALUES (?, ?, ?, ?, ?) """, ( user_id, collection_name, json.dumps(workflow_ids), is_public, description, ), ) conn.commit() return True except Exception as e: print(f"Error creating collection: {e}") return False finally: conn.close() def get_user_collections(self, user_id: str) -> List[Dict]: """Get collections for a user""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT id, collection_name, workflow_ids, is_public, description, created_at FROM workflow_collections WHERE user_id = ? ORDER BY created_at DESC """, (user_id,), ) collections = [] for row in cursor.fetchall(): collections.append( { "id": row[0], "name": row[1], "workflow_ids": json.loads(row[2]) if row[2] else [], "is_public": bool(row[3]), "description": row[4], "created_at": row[5], } ) conn.close() return collections def _update_workflow_stats(self, workflow_id: str): """Update workflow statistics after rating changes""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Calculate new statistics cursor.execute( """ SELECT COUNT(*), AVG(rating), COUNT(CASE WHEN review IS NOT NULL THEN 1 END) FROM workflow_ratings WHERE workflow_id = ? """, (workflow_id,), ) total_ratings, avg_rating, total_reviews = cursor.fetchone() # Update or insert statistics cursor.execute( """ INSERT OR REPLACE INTO workflow_stats (workflow_id, total_ratings, average_rating, total_reviews, last_updated) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) """, (workflow_id, total_ratings or 0, avg_rating or 0.0, total_reviews or 0), ) conn.commit() conn.close() # Example usage and API endpoints def create_community_api_endpoints(app): """Add community feature endpoints to FastAPI app""" community = CommunityFeatures() @app.post("/api/workflows/{workflow_id}/rate") async def rate_workflow(workflow_id: str, rating_data: dict): """Rate a workflow""" try: success = community.add_rating( workflow_id=workflow_id, user_id=rating_data.get("user_id", "anonymous"), rating=rating_data["rating"], review=rating_data.get("review"), ) return {"success": success} except Exception as e: return {"error": str(e)} @app.get("/api/workflows/{workflow_id}/ratings") async def get_workflow_ratings(workflow_id: str, limit: int = 10): """Get workflow ratings and reviews""" ratings = community.get_workflow_ratings(workflow_id, limit) return {"ratings": ratings} @app.get("/api/workflows/{workflow_id}/stats") async def get_workflow_stats(workflow_id: str): """Get workflow statistics""" stats = community.get_workflow_stats(workflow_id) return {"stats": stats} @app.get("/api/workflows/top-rated") async def get_top_rated_workflows(limit: int = 10): """Get top-rated workflows""" workflows = community.get_top_rated_workflows(limit) return {"workflows": workflows} @app.get("/api/workflows/most-popular") async def get_most_popular_workflows(limit: int = 10): """Get most popular workflows""" workflows = community.get_most_popular_workflows(limit) return {"workflows": workflows} @app.post("/api/workflows/{workflow_id}/view") async def track_workflow_view(workflow_id: str): """Track workflow view""" community.increment_view(workflow_id) return {"success": True} @app.post("/api/workflows/{workflow_id}/download") async def track_workflow_download(workflow_id: str): """Track workflow download""" community.increment_download(workflow_id) return {"success": True} if __name__ == "__main__": # Initialize community features community = CommunityFeatures() print("✅ Community features initialized successfully!") # Example: Add a rating # community.add_rating("example-workflow.json", "user123", 5, "Great workflow!") # Example: Get top-rated workflows top_workflows = community.get_top_rated_workflows(5) print(f"📊 Top rated workflows: {len(top_workflows)}")
{ "repo_id": "Zie619/n8n-workflows", "file_path": "src/community_features.py", "license": "MIT License", "lines": 431, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:src/enhanced_api.py
#!/usr/bin/env python3 """ Enhanced API Module for n8n Workflows Repository Advanced features, analytics, and performance optimizations """ import sqlite3 import time from datetime import datetime from typing import Dict, List, Optional from fastapi import FastAPI, HTTPException, Query from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from pydantic import BaseModel import uvicorn # Import community features from community_features import CommunityFeatures, create_community_api_endpoints class WorkflowSearchRequest(BaseModel): """Workflow search request model""" query: str categories: Optional[List[str]] = None trigger_types: Optional[List[str]] = None complexity_levels: Optional[List[str]] = None integrations: Optional[List[str]] = None min_rating: Optional[float] = None limit: int = 20 offset: int = 0 class WorkflowRecommendationRequest(BaseModel): """Workflow recommendation request model""" user_interests: List[str] viewed_workflows: Optional[List[str]] = None preferred_complexity: Optional[str] = None limit: int = 10 class AnalyticsRequest(BaseModel): """Analytics request model""" date_range: str # "7d", "30d", "90d", "1y" metrics: List[str] # ["views", "downloads", "ratings", "searches"] class EnhancedAPI: """Enhanced API with advanced features""" def __init__(self, db_path: str = "workflows.db"): """Initialize enhanced API""" self.db_path = db_path self.community = CommunityFeatures(db_path) self.app = FastAPI( title="N8N Workflows Enhanced API", description="Advanced API for n8n workflows repository with community features", version="2.0.0", ) self._setup_middleware() self._setup_routes() def _setup_middleware(self): """Setup middleware for performance and security""" # CORS middleware self.app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Gzip compression self.app.add_middleware(GZipMiddleware, minimum_size=1000) def _setup_routes(self): """Setup API routes""" # Core workflow endpoints @self.app.get("/api/v2/workflows") async def get_workflows_enhanced( search: Optional[str] = Query(None), category: Optional[str] = Query(None), trigger_type: Optional[str] = Query(None), complexity: Optional[str] = Query(None), integration: Optional[str] = Query(None), min_rating: Optional[float] = Query(None), sort_by: str = Query("name"), sort_order: str = Query("asc"), limit: int = Query(20, le=100), offset: int = Query(0, ge=0), ): """Enhanced workflow search with multiple filters""" start_time = time.time() try: workflows = self._search_workflows_enhanced( search=search, category=category, trigger_type=trigger_type, complexity=complexity, integration=integration, min_rating=min_rating, sort_by=sort_by, sort_order=sort_order, limit=limit, offset=offset, ) response_time = (time.time() - start_time) * 1000 return { "workflows": workflows, "total": len(workflows), "limit": limit, "offset": offset, "response_time_ms": round(response_time, 2), "timestamp": datetime.now().isoformat(), } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @self.app.post("/api/v2/workflows/search") async def advanced_workflow_search(request: WorkflowSearchRequest): """Advanced workflow search with complex queries""" start_time = time.time() try: results = self._advanced_search(request) response_time = (time.time() - start_time) * 1000 return { "results": results, "total": len(results), "query": request.dict(), "response_time_ms": round(response_time, 2), "timestamp": datetime.now().isoformat(), } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @self.app.get("/api/v2/workflows/{workflow_id}") async def get_workflow_enhanced( workflow_id: str, include_stats: bool = Query(True), include_ratings: bool = Query(True), include_related: bool = Query(True), ): """Get detailed workflow information""" try: workflow_data = self._get_workflow_details( workflow_id, include_stats, include_ratings, include_related ) if not workflow_data: raise HTTPException(status_code=404, detail="Workflow not found") return workflow_data except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # Recommendation endpoints @self.app.post("/api/v2/recommendations") async def get_workflow_recommendations(request: WorkflowRecommendationRequest): """Get personalized workflow recommendations""" try: recommendations = self._get_recommendations(request) return { "recommendations": recommendations, "user_profile": request.dict(), "timestamp": datetime.now().isoformat(), } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @self.app.get("/api/v2/recommendations/trending") async def get_trending_workflows(limit: int = Query(10, le=50)): """Get trending workflows based on recent activity""" try: trending = self._get_trending_workflows(limit) return { "trending": trending, "limit": limit, "timestamp": datetime.now().isoformat(), } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # Analytics endpoints @self.app.get("/api/v2/analytics/overview") async def get_analytics_overview(): """Get analytics overview""" try: overview = self._get_analytics_overview() return overview except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @self.app.post("/api/v2/analytics/custom") async def get_custom_analytics(request: AnalyticsRequest): """Get custom analytics data""" try: analytics = self._get_custom_analytics(request) return analytics except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # Performance monitoring @self.app.get("/api/v2/health") async def health_check(): """Health check with performance metrics""" try: health_data = self._get_health_status() return health_data except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # Add community endpoints create_community_api_endpoints(self.app) def _search_workflows_enhanced(self, **kwargs) -> List[Dict]: """Enhanced workflow search with multiple filters""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Build dynamic query query_parts = ["SELECT w.*, ws.average_rating, ws.total_ratings"] query_parts.append("FROM workflows w") query_parts.append("LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id") conditions = [] params = [] # Apply filters if kwargs.get("search"): conditions.append( "(w.name LIKE ? OR w.description LIKE ? OR w.integrations LIKE ?)" ) search_term = f"%{kwargs['search']}%" params.extend([search_term, search_term, search_term]) if kwargs.get("category"): conditions.append("w.category = ?") params.append(kwargs["category"]) if kwargs.get("trigger_type"): conditions.append("w.trigger_type = ?") params.append(kwargs["trigger_type"]) if kwargs.get("complexity"): conditions.append("w.complexity = ?") params.append(kwargs["complexity"]) if kwargs.get("integration"): conditions.append("w.integrations LIKE ?") params.append(f"%{kwargs['integration']}%") if kwargs.get("min_rating"): conditions.append("ws.average_rating >= ?") params.append(kwargs["min_rating"]) # Add conditions to query if conditions: query_parts.append("WHERE " + " AND ".join(conditions)) # Add sorting sort_by = kwargs.get("sort_by", "name") sort_order = kwargs.get("sort_order", "asc").upper() query_parts.append(f"ORDER BY {sort_by} {sort_order}") # Add pagination query_parts.append("LIMIT ? OFFSET ?") params.extend([kwargs.get("limit", 20), kwargs.get("offset", 0)]) # Execute query query = " ".join(query_parts) cursor.execute(query, params) workflows = [] for row in cursor.fetchall(): workflows.append( { "filename": row[0], "name": row[1], "workflow_id": row[2], "active": bool(row[3]), "description": row[4], "trigger_type": row[5], "complexity": row[6], "node_count": row[7], "integrations": row[8], "tags": row[9], "created_at": row[10], "updated_at": row[11], "file_hash": row[12], "file_size": row[13], "analyzed_at": row[14], "average_rating": row[15], "total_ratings": row[16], } ) conn.close() return workflows def _advanced_search(self, request: WorkflowSearchRequest) -> List[Dict]: """Advanced search with complex queries""" # Implementation for advanced search logic # This would include semantic search, fuzzy matching, etc. return self._search_workflows_enhanced( search=request.query, category=request.categories[0] if request.categories else None, trigger_type=request.trigger_types[0] if request.trigger_types else None, complexity=request.complexity_levels[0] if request.complexity_levels else None, limit=request.limit, offset=request.offset, ) def _get_workflow_details( self, workflow_id: str, include_stats: bool, include_ratings: bool, include_related: bool, ) -> Dict: """Get detailed workflow information""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Get basic workflow data cursor.execute("SELECT * FROM workflows WHERE filename = ?", (workflow_id,)) workflow_row = cursor.fetchone() if not workflow_row: conn.close() return None workflow_data = { "filename": workflow_row[0], "name": workflow_row[1], "workflow_id": workflow_row[2], "active": bool(workflow_row[3]), "description": workflow_row[4], "trigger_type": workflow_row[5], "complexity": workflow_row[6], "node_count": workflow_row[7], "integrations": workflow_row[8], "tags": workflow_row[9], "created_at": workflow_row[10], "updated_at": workflow_row[11], "file_hash": workflow_row[12], "file_size": workflow_row[13], "analyzed_at": workflow_row[14], } # Add statistics if requested if include_stats: stats = self.community.get_workflow_stats(workflow_id) workflow_data["stats"] = stats.__dict__ if stats else None # Add ratings if requested if include_ratings: ratings = self.community.get_workflow_ratings(workflow_id, 5) workflow_data["ratings"] = [rating.__dict__ for rating in ratings] # Add related workflows if requested if include_related: related = self._get_related_workflows(workflow_id) workflow_data["related_workflows"] = related conn.close() return workflow_data def _get_recommendations( self, request: WorkflowRecommendationRequest ) -> List[Dict]: """Get personalized workflow recommendations""" # Implementation for recommendation algorithm # This would use collaborative filtering, content-based filtering, etc. conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Simple recommendation based on user interests recommendations = [] for interest in request.user_interests: cursor.execute( """ SELECT * FROM workflows WHERE integrations LIKE ? OR name LIKE ? OR description LIKE ? LIMIT 5 """, (f"%{interest}%", f"%{interest}%", f"%{interest}%"), ) for row in cursor.fetchall(): recommendations.append( { "filename": row[0], "name": row[1], "description": row[4], "reason": f"Matches your interest in {interest}", } ) conn.close() return recommendations[: request.limit] def _get_trending_workflows(self, limit: int) -> List[Dict]: """Get trending workflows based on recent activity""" return self.community.get_most_popular_workflows(limit) def _get_analytics_overview(self) -> Dict: """Get analytics overview""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Total workflows cursor.execute("SELECT COUNT(*) FROM workflows") total_workflows = cursor.fetchone()[0] # Active workflows cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1") active_workflows = cursor.fetchone()[0] # Categories cursor.execute("SELECT category, COUNT(*) FROM workflows GROUP BY category") categories = dict(cursor.fetchall()) # Integrations cursor.execute("SELECT COUNT(DISTINCT integrations) FROM workflows") unique_integrations = cursor.fetchone()[0] conn.close() return { "total_workflows": total_workflows, "active_workflows": active_workflows, "categories": categories, "unique_integrations": unique_integrations, "timestamp": datetime.now().isoformat(), } def _get_custom_analytics(self, request: AnalyticsRequest) -> Dict: """Get custom analytics data""" # Implementation for custom analytics return { "date_range": request.date_range, "metrics": request.metrics, "data": {}, # Placeholder for actual analytics data "timestamp": datetime.now().isoformat(), } def _get_health_status(self) -> Dict: """Get health status and performance metrics""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Database health cursor.execute("SELECT COUNT(*) FROM workflows") total_workflows = cursor.fetchone()[0] # Performance test start_time = time.time() cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1") active_count = cursor.fetchone()[0] query_time = (time.time() - start_time) * 1000 conn.close() return { "status": "healthy", "database": { "total_workflows": total_workflows, "active_workflows": active_count, "connection_status": "connected", }, "performance": { "query_time_ms": round(query_time, 2), "response_time_target": "<100ms", "status": "good" if query_time < 100 else "slow", }, "timestamp": datetime.now().isoformat(), } def _get_related_workflows(self, workflow_id: str, limit: int = 5) -> List[Dict]: """Get related workflows based on similar integrations or categories""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Get current workflow details cursor.execute( "SELECT integrations, category FROM workflows WHERE filename = ?", (workflow_id,), ) current_workflow = cursor.fetchone() if not current_workflow: conn.close() return [] current_integrations = current_workflow[0] or "" current_category = current_workflow[1] or "" # Find related workflows cursor.execute( """ SELECT filename, name, description FROM workflows WHERE filename != ? AND (integrations LIKE ? OR category = ?) LIMIT ? """, (workflow_id, f"%{current_integrations[:50]}%", current_category, limit), ) related = [] for row in cursor.fetchall(): related.append({"filename": row[0], "name": row[1], "description": row[2]}) conn.close() return related def run(self, host: str = "127.0.0.1", port: int = 8000, debug: bool = False): """Run the enhanced API server""" uvicorn.run( self.app, host=host, port=port, log_level="debug" if debug else "info" ) if __name__ == "__main__": # Initialize and run enhanced API api = EnhancedAPI() print("🚀 Starting Enhanced N8N Workflows API...") print( "📊 Features: Advanced search, recommendations, analytics, community features" ) print("🌐 API Documentation: http://127.0.0.1:8000/docs") api.run(debug=True)
{ "repo_id": "Zie619/n8n-workflows", "file_path": "src/enhanced_api.py", "license": "MIT License", "lines": 457, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:src/integration_hub.py
#!/usr/bin/env python3 """ Integration Hub for N8N Workflows Connect with external platforms and services. """ from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse from pydantic import BaseModel, Field from typing import List, Dict, Any import httpx from datetime import datetime class IntegrationConfig(BaseModel): name: str api_key: str base_url: str enabled: bool = True class WebhookPayload(BaseModel): event: str data: Dict[str, Any] timestamp: str = Field(default_factory=lambda: datetime.now().isoformat()) class IntegrationHub: def __init__(self): self.integrations = {} self.webhook_endpoints = {} def register_integration(self, config: IntegrationConfig): """Register a new integration.""" self.integrations[config.name] = config async def sync_with_github(self, repo: str, token: str) -> Dict[str, Any]: """Sync workflows with GitHub repository.""" try: async with httpx.AsyncClient() as client: headers = {"Authorization": f"token {token}"} # Get repository contents response = await client.get( f"https://api.github.com/repos/{repo}/contents/workflows", headers=headers, ) if response.status_code == 200: files = response.json() workflow_files = [f for f in files if f["name"].endswith(".json")] return { "status": "success", "repository": repo, "workflow_files": len(workflow_files), "files": [f["name"] for f in workflow_files], } else: return {"status": "error", "message": "Failed to access repository"} except Exception as e: return {"status": "error", "message": str(e)} async def sync_with_slack(self, webhook_url: str, message: str) -> Dict[str, Any]: """Send notification to Slack.""" try: async with httpx.AsyncClient() as client: payload = { "text": message, "username": "N8N Workflows Bot", "icon_emoji": ":robot_face:", } response = await client.post(webhook_url, json=payload) if response.status_code == 200: return { "status": "success", "message": "Notification sent to Slack", } else: return {"status": "error", "message": "Failed to send to Slack"} except Exception as e: return {"status": "error", "message": str(e)} async def sync_with_discord(self, webhook_url: str, message: str) -> Dict[str, Any]: """Send notification to Discord.""" try: async with httpx.AsyncClient() as client: payload = {"content": message, "username": "N8N Workflows Bot"} response = await client.post(webhook_url, json=payload) if response.status_code == 204: return { "status": "success", "message": "Notification sent to Discord", } else: return {"status": "error", "message": "Failed to send to Discord"} except Exception as e: return {"status": "error", "message": str(e)} async def export_to_airtable( self, base_id: str, table_name: str, api_key: str, workflows: List[Dict] ) -> Dict[str, Any]: """Export workflows to Airtable.""" try: async with httpx.AsyncClient() as client: headers = {"Authorization": f"Bearer {api_key}"} records = [] for workflow in workflows: record = { "fields": { "Name": workflow.get("name", ""), "Description": workflow.get("description", ""), "Trigger Type": workflow.get("trigger_type", ""), "Complexity": workflow.get("complexity", ""), "Node Count": workflow.get("node_count", 0), "Active": workflow.get("active", False), "Integrations": ", ".join(workflow.get("integrations", [])), "Last Updated": datetime.now().isoformat(), } } records.append(record) # Create records in batches batch_size = 10 created_records = 0 for i in range(0, len(records), batch_size): batch = records[i : i + batch_size] response = await client.post( f"https://api.airtable.com/v0/{base_id}/{table_name}", headers=headers, json={"records": batch}, ) if response.status_code == 200: created_records += len(batch) else: return { "status": "error", "message": f"Failed to create records: {response.text}", } return { "status": "success", "message": f"Exported {created_records} workflows to Airtable", } except Exception as e: return {"status": "error", "message": str(e)} async def sync_with_notion( self, database_id: str, token: str, workflows: List[Dict] ) -> Dict[str, Any]: """Sync workflows with Notion database.""" try: async with httpx.AsyncClient() as client: headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json", "Notion-Version": "2022-06-28", } created_pages = 0 for workflow in workflows: page_data = { "parent": {"database_id": database_id}, "properties": { "Name": { "title": [ {"text": {"content": workflow.get("name", "")}} ] }, "Description": { "rich_text": [ { "text": { "content": workflow.get("description", "") } } ] }, "Trigger Type": { "select": {"name": workflow.get("trigger_type", "")} }, "Complexity": { "select": {"name": workflow.get("complexity", "")} }, "Node Count": {"number": workflow.get("node_count", 0)}, "Active": {"checkbox": workflow.get("active", False)}, "Integrations": { "multi_select": [ {"name": integration} for integration in workflow.get("integrations", []) ] }, }, } response = await client.post( "https://api.notion.com/v1/pages", headers=headers, json=page_data, ) if response.status_code == 200: created_pages += 1 else: return { "status": "error", "message": f"Failed to create page: {response.text}", } return { "status": "success", "message": f"Synced {created_pages} workflows to Notion", } except Exception as e: return {"status": "error", "message": str(e)} def register_webhook(self, endpoint: str, handler): """Register a webhook endpoint.""" self.webhook_endpoints[endpoint] = handler async def handle_webhook(self, endpoint: str, payload: WebhookPayload): """Handle incoming webhook.""" if endpoint in self.webhook_endpoints: return await self.webhook_endpoints[endpoint](payload) else: return {"status": "error", "message": "Webhook endpoint not found"} # Initialize integration hub integration_hub = IntegrationHub() # FastAPI app for Integration Hub integration_app = FastAPI(title="N8N Integration Hub", version="1.0.0") @integration_app.post("/integrations/github/sync") async def sync_github(repo: str, token: str): """Sync workflows with GitHub repository.""" try: result = await integration_hub.sync_with_github(repo, token) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.post("/integrations/slack/notify") async def notify_slack(webhook_url: str, message: str): """Send notification to Slack.""" try: result = await integration_hub.sync_with_slack(webhook_url, message) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.post("/integrations/discord/notify") async def notify_discord(webhook_url: str, message: str): """Send notification to Discord.""" try: result = await integration_hub.sync_with_discord(webhook_url, message) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.post("/integrations/airtable/export") async def export_airtable( base_id: str, table_name: str, api_key: str, workflows: List[Dict] ): """Export workflows to Airtable.""" try: result = await integration_hub.export_to_airtable( base_id, table_name, api_key, workflows ) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.post("/integrations/notion/sync") async def sync_notion(database_id: str, token: str, workflows: List[Dict]): """Sync workflows with Notion database.""" try: result = await integration_hub.sync_with_notion(database_id, token, workflows) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.post("/webhooks/{endpoint}") async def handle_webhook_endpoint(endpoint: str, payload: WebhookPayload): """Handle incoming webhook.""" try: result = await integration_hub.handle_webhook(endpoint, payload) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @integration_app.get("/integrations/status") async def get_integration_status(): """Get status of all integrations.""" return { "integrations": list(integration_hub.integrations.keys()), "webhook_endpoints": list(integration_hub.webhook_endpoints.keys()), "status": "operational", } @integration_app.get("/integrations/dashboard") async def get_integration_dashboard(): """Get integration dashboard HTML.""" html_content = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>N8N Integration Hub</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; color: #333; } .dashboard { max-width: 1200px; margin: 0 auto; padding: 20px; } .header { background: white; padding: 30px; border-radius: 15px; margin-bottom: 30px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.1); } .header h1 { font-size: 32px; margin-bottom: 10px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .integrations-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px; } .integration-card { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); transition: transform 0.3s ease; } .integration-card:hover { transform: translateY(-5px); } .integration-icon { font-size: 48px; margin-bottom: 15px; } .integration-title { font-size: 20px; font-weight: bold; margin-bottom: 10px; color: #333; } .integration-description { color: #666; margin-bottom: 20px; line-height: 1.5; } .integration-actions { display: flex; gap: 10px; flex-wrap: wrap; } .action-btn { padding: 10px 20px; border: none; border-radius: 25px; cursor: pointer; font-size: 14px; transition: all 0.3s ease; text-decoration: none; display: inline-block; text-align: center; } .btn-primary { background: #667eea; color: white; } .btn-primary:hover { background: #5a6fd8; } .btn-secondary { background: #f8f9fa; color: #666; border: 1px solid #e9ecef; } .btn-secondary:hover { background: #e9ecef; } .status-indicator { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; } .status-online { background: #28a745; } .status-offline { background: #dc3545; } .webhook-section { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 30px; } .webhook-endpoint { background: #f8f9fa; padding: 15px; border-radius: 10px; margin: 10px 0; font-family: monospace; border-left: 4px solid #667eea; } </style> </head> <body> <div class="dashboard"> <div class="header"> <h1>🔗 N8N Integration Hub</h1> <p>Connect your workflows with external platforms and services</p> </div> <div class="integrations-grid"> <div class="integration-card"> <div class="integration-icon">🐙</div> <div class="integration-title">GitHub</div> <div class="integration-description"> Sync your workflows with GitHub repositories. Version control and collaborate on workflow development. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="syncGitHub()">Sync Repository</button> <button class="action-btn btn-secondary" onclick="showGitHubConfig()">Configure</button> </div> </div> <div class="integration-card"> <div class="integration-icon">💬</div> <div class="integration-title">Slack</div> <div class="integration-description"> Send notifications and workflow updates to Slack channels. Keep your team informed about automation activities. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="testSlack()">Test Notification</button> <button class="action-btn btn-secondary" onclick="showSlackConfig()">Configure</button> </div> </div> <div class="integration-card"> <div class="integration-icon">🎮</div> <div class="integration-title">Discord</div> <div class="integration-description"> Integrate with Discord servers for workflow notifications. Perfect for gaming communities and developer teams. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="testDiscord()">Test Notification</button> <button class="action-btn btn-secondary" onclick="showDiscordConfig()">Configure</button> </div> </div> <div class="integration-card"> <div class="integration-icon">📊</div> <div class="integration-title">Airtable</div> <div class="integration-description"> Export workflow data to Airtable for project management. Create databases of your automation workflows. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="exportAirtable()">Export Data</button> <button class="action-btn btn-secondary" onclick="showAirtableConfig()">Configure</button> </div> </div> <div class="integration-card"> <div class="integration-icon">📝</div> <div class="integration-title">Notion</div> <div class="integration-description"> Sync workflows with Notion databases for documentation. Create comprehensive workflow documentation. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="syncNotion()">Sync Database</button> <button class="action-btn btn-secondary" onclick="showNotionConfig()">Configure</button> </div> </div> <div class="integration-card"> <div class="integration-icon">🔗</div> <div class="integration-title">Webhooks</div> <div class="integration-description"> Create custom webhook endpoints for external integrations. Receive data from any service that supports webhooks. </div> <div class="integration-actions"> <button class="action-btn btn-primary" onclick="createWebhook()">Create Webhook</button> <button class="action-btn btn-secondary" onclick="showWebhookDocs()">Documentation</button> </div> </div> </div> <div class="webhook-section"> <h2>🔗 Webhook Endpoints</h2> <p>Available webhook endpoints for external integrations:</p> <div class="webhook-endpoint"> POST /webhooks/workflow-update<br> <small>Receive notifications when workflows are updated</small> </div> <div class="webhook-endpoint"> POST /webhooks/workflow-execution<br> <small>Receive notifications when workflows are executed</small> </div> <div class="webhook-endpoint"> POST /webhooks/error-report<br> <small>Receive error reports from workflow executions</small> </div> </div> </div> <script> async function syncGitHub() { const repo = prompt('Enter GitHub repository (owner/repo):'); const token = prompt('Enter GitHub token:'); if (repo && token) { try { const response = await fetch('/integrations/github/sync', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({repo, token}) }); const result = await response.json(); alert(result.message || 'GitHub sync completed'); } catch (error) { alert('Error syncing with GitHub: ' + error.message); } } } async function testSlack() { const webhook = prompt('Enter Slack webhook URL:'); const message = 'Test notification from N8N Integration Hub'; if (webhook) { try { const response = await fetch('/integrations/slack/notify', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({webhook_url: webhook, message}) }); const result = await response.json(); alert(result.message || 'Slack notification sent'); } catch (error) { alert('Error sending to Slack: ' + error.message); } } } async function testDiscord() { const webhook = prompt('Enter Discord webhook URL:'); const message = 'Test notification from N8N Integration Hub'; if (webhook) { try { const response = await fetch('/integrations/discord/notify', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({webhook_url: webhook, message}) }); const result = await response.json(); alert(result.message || 'Discord notification sent'); } catch (error) { alert('Error sending to Discord: ' + error.message); } } } function showGitHubConfig() { alert('GitHub Configuration:\\n\\n1. Create a GitHub token with repo access\\n2. Use format: owner/repository\\n3. Ensure workflows are in /workflows directory'); } function showSlackConfig() { alert('Slack Configuration:\\n\\n1. Go to Slack App Directory\\n2. Add "Incoming Webhooks" app\\n3. Create webhook URL\\n4. Use the URL for notifications'); } function showDiscordConfig() { alert('Discord Configuration:\\n\\n1. Go to Server Settings\\n2. Navigate to Integrations\\n3. Create Webhook\\n4. Copy webhook URL'); } function showAirtableConfig() { alert('Airtable Configuration:\\n\\n1. Create a new Airtable base\\n2. Get API key from account settings\\n3. Get base ID from API documentation\\n4. Configure table structure'); } function showNotionConfig() { alert('Notion Configuration:\\n\\n1. Create a Notion integration\\n2. Get integration token\\n3. Create database with proper schema\\n4. Share database with integration'); } function createWebhook() { alert('Webhook Creation:\\n\\n1. Choose endpoint name\\n2. Configure payload structure\\n3. Set up authentication\\n4. Test webhook endpoint'); } function showWebhookDocs() { alert('Webhook Documentation:\\n\\nAvailable at: /docs\\n\\nEndpoints:\\n- POST /webhooks/{endpoint}\\n- Payload: {event, data, timestamp}\\n- Response: {status, message}'); } </script> </body> </html> """ return HTMLResponse(content=html_content) if __name__ == "__main__": import uvicorn uvicorn.run(integration_app, host="127.0.0.1", port=8003)
{ "repo_id": "Zie619/n8n-workflows", "file_path": "src/integration_hub.py", "license": "MIT License", "lines": 574, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Zie619/n8n-workflows:src/performance_monitor.py
#!/usr/bin/env python3 """ Performance Monitoring System for N8N Workflows Real-time metrics, monitoring, and alerting. """ from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse from pydantic import BaseModel from typing import List, Dict, Any import asyncio import time import psutil from datetime import datetime, timedelta import json import threading import queue import os class PerformanceMetrics(BaseModel): timestamp: str cpu_usage: float memory_usage: float disk_usage: float network_io: Dict[str, int] api_response_times: Dict[str, float] active_connections: int database_size: int workflow_executions: int error_rate: float class Alert(BaseModel): id: str type: str severity: str message: str timestamp: str resolved: bool = False class PerformanceMonitor: def __init__(self, db_path: str = "workflows.db"): self.db_path = db_path self.metrics_history = [] self.alerts = [] self.websocket_connections = [] self.monitoring_active = False self.metrics_queue = queue.Queue() def start_monitoring(self): """Start performance monitoring in background thread.""" if not self.monitoring_active: self.monitoring_active = True monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True) monitor_thread.start() def _monitor_loop(self): """Main monitoring loop.""" while self.monitoring_active: try: metrics = self._collect_metrics() self.metrics_history.append(metrics) # Keep only last 1000 metrics if len(self.metrics_history) > 1000: self.metrics_history = self.metrics_history[-1000:] # Check for alerts self._check_alerts(metrics) # Send to websocket connections self._broadcast_metrics(metrics) time.sleep(5) # Collect metrics every 5 seconds except Exception as e: print(f"Monitoring error: {e}") time.sleep(10) def _collect_metrics(self) -> PerformanceMetrics: """Collect current system metrics.""" # CPU and Memory cpu_usage = psutil.cpu_percent(interval=1) memory = psutil.virtual_memory() memory_usage = memory.percent # Disk usage disk = psutil.disk_usage("/") disk_usage = (disk.used / disk.total) * 100 # Network I/O network = psutil.net_io_counters() network_io = { "bytes_sent": network.bytes_sent, "bytes_recv": network.bytes_recv, "packets_sent": network.packets_sent, "packets_recv": network.packets_recv, } # API response times (simulated) api_response_times = { "/api/stats": self._measure_api_time("/api/stats"), "/api/workflows": self._measure_api_time("/api/workflows"), "/api/search": self._measure_api_time("/api/workflows?q=test"), } # Active connections active_connections = len(psutil.net_connections()) # Database size try: db_size = ( os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0 ) except: db_size = 0 # Workflow executions (simulated) workflow_executions = self._get_workflow_executions() # Error rate (simulated) error_rate = self._calculate_error_rate() return PerformanceMetrics( timestamp=datetime.now().isoformat(), cpu_usage=cpu_usage, memory_usage=memory_usage, disk_usage=disk_usage, network_io=network_io, api_response_times=api_response_times, active_connections=active_connections, database_size=db_size, workflow_executions=workflow_executions, error_rate=error_rate, ) def _measure_api_time(self, endpoint: str) -> float: """Measure API response time (simulated).""" # In a real implementation, this would make actual HTTP requests import random return round(random.uniform(10, 100), 2) def _get_workflow_executions(self) -> int: """Get number of workflow executions (simulated).""" # In a real implementation, this would query execution logs import random return random.randint(0, 50) def _calculate_error_rate(self) -> float: """Calculate error rate (simulated).""" # In a real implementation, this would analyze error logs import random return round(random.uniform(0, 5), 2) def _check_alerts(self, metrics: PerformanceMetrics): """Check metrics against alert thresholds.""" # CPU alert if metrics.cpu_usage > 80: self._create_alert( "high_cpu", "warning", f"High CPU usage: {metrics.cpu_usage}%" ) # Memory alert if metrics.memory_usage > 85: self._create_alert( "high_memory", "warning", f"High memory usage: {metrics.memory_usage}%" ) # Disk alert if metrics.disk_usage > 90: self._create_alert( "high_disk", "critical", f"High disk usage: {metrics.disk_usage}%" ) # API response time alert for endpoint, response_time in metrics.api_response_times.items(): if response_time > 1000: # 1 second self._create_alert( "slow_api", "warning", f"Slow API response: {endpoint} ({response_time}ms)", ) # Error rate alert if metrics.error_rate > 10: self._create_alert( "high_error_rate", "critical", f"High error rate: {metrics.error_rate}%" ) def _create_alert(self, alert_type: str, severity: str, message: str): """Create a new alert.""" alert = Alert( id=f"{alert_type}_{int(time.time())}", type=alert_type, severity=severity, message=message, timestamp=datetime.now().isoformat(), ) # Check if similar alert already exists existing_alert = next( (a for a in self.alerts if a.type == alert_type and not a.resolved), None ) if not existing_alert: self.alerts.append(alert) self._broadcast_alert(alert) def _broadcast_metrics(self, metrics: PerformanceMetrics): """Broadcast metrics to all websocket connections.""" if self.websocket_connections: message = {"type": "metrics", "data": metrics.dict()} self._broadcast_to_websockets(message) def _broadcast_alert(self, alert: Alert): """Broadcast alert to all websocket connections.""" message = {"type": "alert", "data": alert.dict()} self._broadcast_to_websockets(message) def _broadcast_to_websockets(self, message: dict): """Broadcast message to all websocket connections.""" disconnected = [] for websocket in self.websocket_connections: try: asyncio.create_task(websocket.send_text(json.dumps(message))) except: disconnected.append(websocket) # Remove disconnected connections for ws in disconnected: self.websocket_connections.remove(ws) def get_metrics_summary(self) -> Dict[str, Any]: """Get performance metrics summary.""" if not self.metrics_history: return {"message": "No metrics available"} latest = self.metrics_history[-1] avg_cpu = sum(m.cpu_usage for m in self.metrics_history[-10:]) / min( 10, len(self.metrics_history) ) avg_memory = sum(m.memory_usage for m in self.metrics_history[-10:]) / min( 10, len(self.metrics_history) ) return { "current": latest.dict(), "averages": { "cpu_usage": round(avg_cpu, 2), "memory_usage": round(avg_memory, 2), }, "alerts": [alert.dict() for alert in self.alerts[-10:]], "status": "healthy" if latest.cpu_usage < 80 and latest.memory_usage < 85 else "warning", } def get_historical_metrics(self, hours: int = 24) -> List[Dict]: """Get historical metrics for specified hours.""" cutoff_time = datetime.now() - timedelta(hours=hours) cutoff_timestamp = cutoff_time.isoformat() return [ metrics.dict() for metrics in self.metrics_history if metrics.timestamp >= cutoff_timestamp ] def resolve_alert(self, alert_id: str) -> bool: """Resolve an alert.""" for alert in self.alerts: if alert.id == alert_id: alert.resolved = True return True return False # Initialize performance monitor performance_monitor = PerformanceMonitor() performance_monitor.start_monitoring() # FastAPI app for Performance Monitoring monitor_app = FastAPI(title="N8N Performance Monitor", version="1.0.0") @monitor_app.get("/monitor/metrics") async def get_current_metrics(): """Get current performance metrics.""" return performance_monitor.get_metrics_summary() @monitor_app.get("/monitor/history") async def get_historical_metrics(hours: int = 24): """Get historical performance metrics.""" return performance_monitor.get_historical_metrics(hours) @monitor_app.get("/monitor/alerts") async def get_alerts(): """Get current alerts.""" return [alert.dict() for alert in performance_monitor.alerts if not alert.resolved] @monitor_app.post("/monitor/alerts/{alert_id}/resolve") async def resolve_alert(alert_id: str): """Resolve an alert.""" success = performance_monitor.resolve_alert(alert_id) if success: return {"message": "Alert resolved"} else: return {"message": "Alert not found"} @monitor_app.websocket("/monitor/ws") async def websocket_endpoint(websocket: WebSocket): """WebSocket endpoint for real-time metrics.""" await websocket.accept() performance_monitor.websocket_connections.append(websocket) try: while True: # Keep connection alive await websocket.receive_text() except WebSocketDisconnect: performance_monitor.websocket_connections.remove(websocket) @monitor_app.get("/monitor/dashboard") async def get_monitoring_dashboard(): """Get performance monitoring dashboard HTML.""" html_content = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>N8N Performance Monitor</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; } .dashboard { max-width: 1400px; margin: 0 auto; padding: 20px; } .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; margin-bottom: 30px; text-align: center; } .header h1 { font-size: 32px; margin-bottom: 10px; } .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; } .metric-card { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); text-align: center; } .metric-value { font-size: 36px; font-weight: bold; margin-bottom: 10px; } .metric-value.cpu { color: #667eea; } .metric-value.memory { color: #28a745; } .metric-value.disk { color: #ffc107; } .metric-value.network { color: #17a2b8; } .metric-label { color: #666; font-size: 16px; } .status-indicator { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 8px; } .status-healthy { background: #28a745; } .status-warning { background: #ffc107; } .status-critical { background: #dc3545; } .chart-container { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 30px; } .chart-title { font-size: 20px; font-weight: bold; margin-bottom: 20px; color: #333; } .alerts-section { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); } .alert { background: #f8f9fa; padding: 15px; border-radius: 10px; margin-bottom: 10px; border-left: 4px solid #667eea; } .alert.warning { border-left-color: #ffc107; background: #fff3cd; } .alert.critical { border-left-color: #dc3545; background: #f8d7da; } .alert-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; } .alert-type { font-weight: bold; color: #333; } .alert-severity { padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: bold; text-transform: uppercase; } .severity-warning { background: #ffc107; color: #856404; } .severity-critical { background: #dc3545; color: white; } .alert-message { color: #666; font-size: 14px; } .alert-timestamp { color: #999; font-size: 12px; margin-top: 5px; } .resolve-btn { background: #28a745; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; } .resolve-btn:hover { background: #218838; } </style> </head> <body> <div class="dashboard"> <div class="header"> <h1>📊 N8N Performance Monitor</h1> <p>Real-time system monitoring and alerting</p> <div id="connectionStatus"> <span class="status-indicator" id="statusIndicator"></span> <span id="statusText">Connecting...</span> </div> </div> <div class="metrics-grid" id="metricsGrid"> <div class="loading">Loading metrics...</div> </div> <div class="chart-container"> <div class="chart-title">CPU & Memory Usage</div> <canvas id="performanceChart" width="400" height="200"></canvas> </div> <div class="chart-container"> <div class="chart-title">API Response Times</div> <canvas id="apiChart" width="400" height="200"></canvas> </div> <div class="alerts-section"> <div class="chart-title">Active Alerts</div> <div id="alertsContainer"> <div class="loading">Loading alerts...</div> </div> </div> </div> <script> let ws = null; let performanceChart = null; let apiChart = null; let metricsData = []; function connectWebSocket() { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${protocol}//${window.location.host}/monitor/ws`; ws = new WebSocket(wsUrl); ws.onopen = function() { updateConnectionStatus(true); loadInitialData(); }; ws.onmessage = function(event) { const data = JSON.parse(event.data); if (data.type === 'metrics') { updateMetrics(data.data); updateCharts(data.data); } else if (data.type === 'alert') { addAlert(data.data); } }; ws.onclose = function() { updateConnectionStatus(false); setTimeout(connectWebSocket, 5000); }; ws.onerror = function() { updateConnectionStatus(false); }; } function updateConnectionStatus(connected) { const indicator = document.getElementById('statusIndicator'); const text = document.getElementById('statusText'); if (connected) { indicator.className = 'status-indicator status-healthy'; text.textContent = 'Connected'; } else { indicator.className = 'status-indicator status-critical'; text.textContent = 'Disconnected'; } } async function loadInitialData() { try { // Load current metrics const metricsResponse = await fetch('/monitor/metrics'); const metrics = await metricsResponse.json(); updateMetrics(metrics.current); // Load alerts const alertsResponse = await fetch('/monitor/alerts'); const alerts = await alertsResponse.json(); displayAlerts(alerts); } catch (error) { console.error('Error loading initial data:', error); } } function updateMetrics(metrics) { const grid = document.getElementById('metricsGrid'); grid.innerHTML = ` <div class="metric-card"> <div class="metric-value cpu">${metrics.cpu_usage?.toFixed(1) || 0}%</div> <div class="metric-label">CPU Usage</div> </div> <div class="metric-card"> <div class="metric-value memory">${metrics.memory_usage?.toFixed(1) || 0}%</div> <div class="metric-label">Memory Usage</div> </div> <div class="metric-card"> <div class="metric-value disk">${metrics.disk_usage?.toFixed(1) || 0}%</div> <div class="metric-label">Disk Usage</div> </div> <div class="metric-card"> <div class="metric-value network">${metrics.active_connections || 0}</div> <div class="metric-label">Active Connections</div> </div> `; metricsData.push(metrics); if (metricsData.length > 20) { metricsData = metricsData.slice(-20); } } function updateCharts(metrics) { if (!performanceChart) { initPerformanceChart(); } if (!apiChart) { initApiChart(); } // Update performance chart const labels = metricsData.map((_, i) => i); performanceChart.data.labels = labels; performanceChart.data.datasets[0].data = metricsData.map(m => m.cpu_usage); performanceChart.data.datasets[1].data = metricsData.map(m => m.memory_usage); performanceChart.update(); // Update API chart if (metrics.api_response_times) { const endpoints = Object.keys(metrics.api_response_times); const times = Object.values(metrics.api_response_times); apiChart.data.labels = endpoints; apiChart.data.datasets[0].data = times; apiChart.update(); } } function initPerformanceChart() { const ctx = document.getElementById('performanceChart').getContext('2d'); performanceChart = new Chart(ctx, { type: 'line', data: { labels: [], datasets: [{ label: 'CPU Usage (%)', data: [], borderColor: '#667eea', backgroundColor: 'rgba(102, 126, 234, 0.1)', tension: 0.4 }, { label: 'Memory Usage (%)', data: [], borderColor: '#28a745', backgroundColor: 'rgba(40, 167, 69, 0.1)', tension: 0.4 }] }, options: { responsive: true, scales: { y: { beginAtZero: true, max: 100 } } } }); } function initApiChart() { const ctx = document.getElementById('apiChart').getContext('2d'); apiChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [{ label: 'Response Time (ms)', data: [], backgroundColor: '#667eea' }] }, options: { responsive: true, scales: { y: { beginAtZero: true } } } }); } function displayAlerts(alerts) { const container = document.getElementById('alertsContainer'); if (alerts.length === 0) { container.innerHTML = '<div class="loading">No active alerts</div>'; return; } container.innerHTML = alerts.map(alert => ` <div class="alert ${alert.severity}"> <div class="alert-header"> <span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span> <span class="alert-severity severity-${alert.severity}">${alert.severity}</span> </div> <div class="alert-message">${alert.message}</div> <div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div> <button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button> </div> `).join(''); } function addAlert(alert) { const container = document.getElementById('alertsContainer'); const alertHtml = ` <div class="alert ${alert.severity}"> <div class="alert-header"> <span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span> <span class="alert-severity severity-${alert.severity}">${alert.severity}</span> </div> <div class="alert-message">${alert.message}</div> <div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div> <button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button> </div> `; container.insertAdjacentHTML('afterbegin', alertHtml); } async function resolveAlert(alertId) { try { const response = await fetch(`/monitor/alerts/${alertId}/resolve`, { method: 'POST' }); if (response.ok) { // Remove alert from UI const alertElement = document.querySelector(`[onclick="resolveAlert('${alertId}')"]`).closest('.alert'); alertElement.remove(); } } catch (error) { console.error('Error resolving alert:', error); } } // Initialize dashboard connectWebSocket(); </script> </body> </html> """ return HTMLResponse(content=html_content) if __name__ == "__main__": import uvicorn uvicorn.run(monitor_app, host="127.0.0.1", port=8005)
{ "repo_id": "Zie619/n8n-workflows", "file_path": "src/performance_monitor.py", "license": "MIT License", "lines": 662, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Zie619/n8n-workflows:src/user_management.py
#!/usr/bin/env python3 """ User Management System for N8N Workflows Multi-user access control and authentication. """ from fastapi import FastAPI, HTTPException, Depends, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.responses import HTMLResponse from pydantic import BaseModel, EmailStr from typing import List, Optional import sqlite3 import hashlib import secrets import jwt from datetime import datetime, timedelta import os # Configuration - Use environment variables for security SECRET_KEY = os.environ.get("JWT_SECRET_KEY", secrets.token_urlsafe(32)) ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 # Security security = HTTPBearer() class User(BaseModel): id: Optional[int] = None username: str email: EmailStr full_name: str role: str = "user" active: bool = True created_at: Optional[str] = None class UserCreate(BaseModel): username: str email: EmailStr full_name: str password: str role: str = "user" class UserLogin(BaseModel): username: str password: str class UserUpdate(BaseModel): full_name: Optional[str] = None email: Optional[EmailStr] = None role: Optional[str] = None active: Optional[bool] = None class Token(BaseModel): access_token: str token_type: str expires_in: int class UserManager: def __init__(self, db_path: str = "users.db"): self.db_path = db_path self.init_database() def init_database(self): """Initialize user database.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, email TEXT UNIQUE NOT NULL, full_name TEXT NOT NULL, password_hash TEXT NOT NULL, role TEXT DEFAULT 'user', active BOOLEAN DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_login TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS user_sessions ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, token_hash TEXT UNIQUE NOT NULL, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users (id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS user_permissions ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, resource TEXT NOT NULL, action TEXT NOT NULL, granted BOOLEAN DEFAULT 1, FOREIGN KEY (user_id) REFERENCES users (id) ) """) conn.commit() conn.close() # Create default admin user if none exists self.create_default_admin() def create_default_admin(self): """Create default admin user if none exists.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'") admin_count = cursor.fetchone()[0] if admin_count == 0: # Use environment variable or generate secure random password admin_password = os.environ.get("ADMIN_PASSWORD", secrets.token_urlsafe(16)) password_hash = self.hash_password(admin_password) cursor.execute( """ INSERT INTO users (username, email, full_name, password_hash, role) VALUES (?, ?, ?, ?, ?) """, ( "admin", "admin@n8n-workflows.com", "System Administrator", password_hash, "admin", ), ) conn.commit() # Only print password if it was auto-generated (not from env) if "ADMIN_PASSWORD" not in os.environ: print(f"Default admin user created: admin/{admin_password}") print( "WARNING: Please change this password immediately after first login!" ) else: print("Default admin user created with environment-configured password") conn.close() def hash_password(self, password: str) -> str: """Hash password using SHA-256.""" return hashlib.sha256(password.encode()).hexdigest() def verify_password(self, password: str, hashed: str) -> bool: """Verify password against hash.""" return self.hash_password(password) == hashed def create_user(self, user_data: UserCreate) -> User: """Create a new user.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() try: # Check if username or email already exists cursor.execute( "SELECT COUNT(*) FROM users WHERE username = ? OR email = ?", (user_data.username, user_data.email), ) if cursor.fetchone()[0] > 0: raise ValueError("Username or email already exists") password_hash = self.hash_password(user_data.password) cursor.execute( """ INSERT INTO users (username, email, full_name, password_hash, role) VALUES (?, ?, ?, ?, ?) """, ( user_data.username, user_data.email, user_data.full_name, password_hash, user_data.role, ), ) user_id = cursor.lastrowid conn.commit() return User( id=user_id, username=user_data.username, email=user_data.email, full_name=user_data.full_name, role=user_data.role, active=True, created_at=datetime.now().isoformat(), ) except Exception as e: conn.rollback() raise e finally: conn.close() def authenticate_user(self, username: str, password: str) -> Optional[User]: """Authenticate user and return user data.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT id, username, email, full_name, password_hash, role, active FROM users WHERE username = ? AND active = 1 """, (username,), ) row = cursor.fetchone() conn.close() if row and self.verify_password(password, row[4]): return User( id=row[0], username=row[1], email=row[2], full_name=row[3], role=row[5], active=bool(row[6]), ) return None def create_access_token(self, user: User) -> str: """Create JWT access token.""" expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = { "sub": str(user.id), "username": user.username, "role": user.role, "exp": expire, } return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) def verify_token(self, token: str) -> Optional[User]: """Verify JWT token and return user data.""" try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id = payload.get("sub") username = payload.get("username") role = payload.get("role") if user_id is None or username is None: return None return User(id=int(user_id), username=username, role=role) except jwt.PyJWTError: return None def get_user_by_id(self, user_id: int) -> Optional[User]: """Get user by ID.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute( """ SELECT id, username, email, full_name, role, active, created_at FROM users WHERE id = ? """, (user_id,), ) row = cursor.fetchone() conn.close() if row: return User( id=row[0], username=row[1], email=row[2], full_name=row[3], role=row[4], active=bool(row[5]), created_at=row[6], ) return None def get_all_users(self) -> List[User]: """Get all users.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" SELECT id, username, email, full_name, role, active, created_at FROM users ORDER BY created_at DESC """) users = [] for row in cursor.fetchall(): users.append( User( id=row[0], username=row[1], email=row[2], full_name=row[3], role=row[4], active=bool(row[5]), created_at=row[6], ) ) conn.close() return users def update_user(self, user_id: int, update_data: UserUpdate) -> Optional[User]: """Update user data.""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() try: # Build update query dynamically updates = [] params = [] if update_data.full_name is not None: updates.append("full_name = ?") params.append(update_data.full_name) if update_data.email is not None: updates.append("email = ?") params.append(update_data.email) if update_data.role is not None: updates.append("role = ?") params.append(update_data.role) if update_data.active is not None: updates.append("active = ?") params.append(update_data.active) if not updates: return self.get_user_by_id(user_id) params.append(user_id) query = f"UPDATE users SET {', '.join(updates)} WHERE id = ?" cursor.execute(query, params) conn.commit() return self.get_user_by_id(user_id) except Exception as e: conn.rollback() raise e finally: conn.close() def delete_user(self, user_id: int) -> bool: """Delete user (soft delete by setting active=False).""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() try: cursor.execute("UPDATE users SET active = 0 WHERE id = ?", (user_id,)) conn.commit() return cursor.rowcount > 0 except Exception as e: conn.rollback() raise e finally: conn.close() # Initialize user manager user_manager = UserManager() # FastAPI app for User Management user_app = FastAPI(title="N8N User Management", version="1.0.0") def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), ) -> User: """Get current authenticated user.""" token = credentials.credentials user = user_manager.verify_token(token) if user is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return user def require_admin(current_user: User = Depends(get_current_user)) -> User: """Require admin role.""" if current_user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required" ) return current_user @user_app.post("/auth/register", response_model=User) async def register_user(user_data: UserCreate): """Register a new user.""" try: user = user_manager.create_user(user_data) return user except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @user_app.post("/auth/login", response_model=Token) async def login_user(login_data: UserLogin): """Login user and return access token.""" user = user_manager.authenticate_user(login_data.username, login_data.password) if user is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token = user_manager.create_access_token(user) return Token( access_token=access_token, token_type="bearer", expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60, ) @user_app.get("/auth/me", response_model=User) async def get_current_user_info(current_user: User = Depends(get_current_user)): """Get current user information.""" return current_user @user_app.get("/users", response_model=List[User]) async def get_all_users(admin: User = Depends(require_admin)): """Get all users (admin only).""" return user_manager.get_all_users() @user_app.get("/users/{user_id}", response_model=User) async def get_user(user_id: int, current_user: User = Depends(get_current_user)): """Get user by ID.""" # Users can only view their own profile unless they're admin if current_user.id != user_id and current_user.role != "admin": raise HTTPException(status_code=403, detail="Access denied") user = user_manager.get_user_by_id(user_id) if user is None: raise HTTPException(status_code=404, detail="User not found") return user @user_app.put("/users/{user_id}", response_model=User) async def update_user( user_id: int, update_data: UserUpdate, current_user: User = Depends(get_current_user), ): """Update user data.""" # Users can only update their own profile unless they're admin if current_user.id != user_id and current_user.role != "admin": raise HTTPException(status_code=403, detail="Access denied") # Non-admin users cannot change roles if current_user.role != "admin" and update_data.role is not None: raise HTTPException(status_code=403, detail="Cannot change role") user = user_manager.update_user(user_id, update_data) if user is None: raise HTTPException(status_code=404, detail="User not found") return user @user_app.delete("/users/{user_id}") async def delete_user(user_id: int, admin: User = Depends(require_admin)): """Delete user (admin only).""" success = user_manager.delete_user(user_id) if not success: raise HTTPException(status_code=404, detail="User not found") return {"message": "User deleted successfully"} @user_app.get("/auth/dashboard") async def get_auth_dashboard(): """Get authentication dashboard HTML.""" html_content = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>N8N User Management</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; color: #333; } .dashboard { max-width: 1000px; margin: 0 auto; padding: 20px; } .header { background: white; padding: 30px; border-radius: 15px; margin-bottom: 30px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.1); } .header h1 { font-size: 32px; margin-bottom: 10px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .auth-section { background: white; padding: 30px; border-radius: 15px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); } .auth-tabs { display: flex; margin-bottom: 20px; border-bottom: 2px solid #e9ecef; } .tab { padding: 15px 30px; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s ease; } .tab.active { border-bottom-color: #667eea; color: #667eea; font-weight: bold; } .tab-content { display: none; } .tab-content.active { display: block; } .form-group { margin-bottom: 20px; } .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #333; } .form-group input { width: 100%; padding: 12px; border: 2px solid #e9ecef; border-radius: 8px; font-size: 16px; transition: border-color 0.3s ease; } .form-group input:focus { outline: none; border-color: #667eea; } .btn { padding: 12px 24px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; transition: all 0.3s ease; text-decoration: none; display: inline-block; text-align: center; } .btn-primary { background: #667eea; color: white; } .btn-primary:hover { background: #5a6fd8; } .btn-secondary { background: #f8f9fa; color: #666; border: 1px solid #e9ecef; } .btn-secondary:hover { background: #e9ecef; } .user-list { background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); } .user-card { background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; } .user-info h3 { margin-bottom: 5px; color: #333; } .user-info p { color: #666; font-size: 14px; } .user-role { background: #667eea; color: white; padding: 4px 12px; border-radius: 15px; font-size: 12px; font-weight: bold; } .user-role.admin { background: #dc3545; } .status-indicator { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; } .status-online { background: #28a745; } .status-offline { background: #dc3545; } .message { padding: 15px; border-radius: 8px; margin-bottom: 20px; display: none; } .message.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } .message.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } </style> </head> <body> <div class="dashboard"> <div class="header"> <h1>👥 N8N User Management</h1> <p>Manage users, roles, and access control for your workflow platform</p> </div> <div class="auth-section"> <div class="auth-tabs"> <div class="tab active" onclick="showTab('login')">Login</div> <div class="tab" onclick="showTab('register')">Register</div> </div> <div id="message" class="message"></div> <div id="login" class="tab-content active"> <h2>Login to Your Account</h2> <form id="loginForm"> <div class="form-group"> <label for="loginUsername">Username</label> <input type="text" id="loginUsername" required> </div> <div class="form-group"> <label for="loginPassword">Password</label> <input type="password" id="loginPassword" required> </div> <button type="submit" class="btn btn-primary">Login</button> </form> </div> <div id="register" class="tab-content"> <h2>Create New Account</h2> <form id="registerForm"> <div class="form-group"> <label for="regUsername">Username</label> <input type="text" id="regUsername" required> </div> <div class="form-group"> <label for="regEmail">Email</label> <input type="email" id="regEmail" required> </div> <div class="form-group"> <label for="regFullName">Full Name</label> <input type="text" id="regFullName" required> </div> <div class="form-group"> <label for="regPassword">Password</label> <input type="password" id="regPassword" required> </div> <button type="submit" class="btn btn-primary">Register</button> </form> </div> </div> <div class="user-list" id="userList" style="display: none;"> <h2>User Management</h2> <div id="usersContainer"> <div class="loading">Loading users...</div> </div> </div> </div> <script> let currentUser = null; let authToken = null; function showTab(tabName) { // Hide all tabs document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active')); document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active')); // Show selected tab event.target.classList.add('active'); document.getElementById(tabName).classList.add('active'); } function showMessage(message, type) { const messageDiv = document.getElementById('message'); messageDiv.textContent = message; messageDiv.className = `message ${type}`; messageDiv.style.display = 'block'; setTimeout(() => { messageDiv.style.display = 'none'; }, 5000); } async function login(username, password) { try { const response = await fetch('/auth/login', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username, password}) }); if (response.ok) { const data = await response.json(); authToken = data.access_token; currentUser = await getCurrentUser(); showMessage('Login successful!', 'success'); loadUsers(); } else { const error = await response.json(); showMessage(error.detail || 'Login failed', 'error'); } } catch (error) { showMessage('Login error: ' + error.message, 'error'); } } async function register(username, email, fullName, password) { try { const response = await fetch('/auth/register', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username, email, full_name: fullName, password, role: 'user'}) }); if (response.ok) { showMessage('Registration successful! Please login.', 'success'); showTab('login'); } else { const error = await response.json(); showMessage(error.detail || 'Registration failed', 'error'); } } catch (error) { showMessage('Registration error: ' + error.message, 'error'); } } async function getCurrentUser() { if (!authToken) return null; try { const response = await fetch('/auth/me', { headers: {'Authorization': `Bearer ${authToken}`} }); if (response.ok) { return await response.json(); } } catch (error) { console.error('Error getting current user:', error); } return null; } async function loadUsers() { if (!authToken) return; try { const response = await fetch('/users', { headers: {'Authorization': `Bearer ${authToken}`} }); if (response.ok) { const users = await response.json(); displayUsers(users); document.getElementById('userList').style.display = 'block'; } else { showMessage('Failed to load users', 'error'); } } catch (error) { showMessage('Error loading users: ' + error.message, 'error'); } } function displayUsers(users) { const container = document.getElementById('usersContainer'); container.innerHTML = users.map(user => ` <div class="user-card"> <div class="user-info"> <h3>${user.full_name}</h3> <p>@${user.username} • ${user.email}</p> </div> <div> <span class="user-role ${user.role}">${user.role.toUpperCase()}</span> <span class="status-indicator ${user.active ? 'status-online' : 'status-offline'}"></span> </div> </div> `).join(''); } // Event listeners document.getElementById('loginForm').addEventListener('submit', (e) => { e.preventDefault(); const username = document.getElementById('loginUsername').value; const password = document.getElementById('loginPassword').value; login(username, password); }); document.getElementById('registerForm').addEventListener('submit', (e) => { e.preventDefault(); const username = document.getElementById('regUsername').value; const email = document.getElementById('regEmail').value; const fullName = document.getElementById('regFullName').value; const password = document.getElementById('regPassword').value; register(username, email, fullName, password); }); </script> </body> </html> """ return HTMLResponse(content=html_content) if __name__ == "__main__": import uvicorn uvicorn.run(user_app, host="127.0.0.1", port=8004)
{ "repo_id": "Zie619/n8n-workflows", "file_path": "src/user_management.py", "license": "MIT License", "lines": 766, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Zie619/n8n-workflows:run.py
#!/usr/bin/env python3 """ 🚀 N8N Workflows Search Engine Launcher Start the advanced search system with optimized performance. """ import sys import os import argparse def print_banner(): """Print application banner.""" print("🚀 n8n-workflows Advanced Search Engine") print("=" * 50) def check_requirements() -> bool: """Check if required dependencies are installed.""" missing_deps = [] try: import sqlite3 except ImportError: missing_deps.append("sqlite3") try: import uvicorn except ImportError: missing_deps.append("uvicorn") try: import fastapi except ImportError: missing_deps.append("fastapi") if missing_deps: print(f"❌ Missing dependencies: {', '.join(missing_deps)}") print("💡 Install with: pip install -r requirements.txt") return False print("✅ Dependencies verified") return True def setup_directories(): """Create necessary directories.""" directories = ["database", "static", "workflows"] for directory in directories: os.makedirs(directory, exist_ok=True) print("✅ Directories verified") def setup_database(force_reindex: bool = False, skip_index: bool = False) -> str: """Setup and initialize the database.""" from workflow_db import WorkflowDatabase db_path = "database/workflows.db" print(f"🔄 Setting up database: {db_path}") db = WorkflowDatabase(db_path) # Skip indexing in CI mode or if explicitly requested if skip_index: print("⏭️ Skipping workflow indexing (CI mode)") stats = db.get_stats() print(f"✅ Database ready: {stats['total']} workflows") return db_path # Check if database has data or force reindex stats = db.get_stats() if stats["total"] == 0 or force_reindex: print("📚 Indexing workflows...") index_stats = db.index_all_workflows(force_reindex=True) print(f"✅ Indexed {index_stats['processed']} workflows") # Show final stats final_stats = db.get_stats() print(f"📊 Database contains {final_stats['total']} workflows") else: print(f"✅ Database ready: {stats['total']} workflows") return db_path def start_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False): """Start the FastAPI server.""" print(f"🌐 Starting server at http://{host}:{port}") print(f"📊 API Documentation: http://{host}:{port}/docs") print(f"🔍 Workflow Search: http://{host}:{port}/api/workflows") print() print("Press Ctrl+C to stop the server") print("-" * 50) # Configure database path os.environ["WORKFLOW_DB_PATH"] = "database/workflows.db" # Start uvicorn with better configuration import uvicorn uvicorn.run( "api_server:app", host=host, port=port, reload=reload, log_level="info", access_log=False, # Reduce log noise ) def main(): """Main entry point with command line arguments.""" sys.stdout.reconfigure(encoding="utf-8") parser = argparse.ArgumentParser( description="N8N Workflows Search Engine", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python run.py # Start with default settings python run.py --port 3000 # Start on port 3000 python run.py --host 0.0.0.0 # Accept external connections python run.py --reindex # Force database reindexing python run.py --dev # Development mode with auto-reload """, ) parser.add_argument( "--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)" ) parser.add_argument( "--port", type=int, default=8000, help="Port to bind to (default: 8000)" ) parser.add_argument( "--reindex", action="store_true", help="Force database reindexing" ) parser.add_argument( "--dev", action="store_true", help="Development mode with auto-reload" ) parser.add_argument( "--skip-index", action="store_true", help="Skip workflow indexing (useful for CI/testing)", ) args = parser.parse_args() # Also check environment variable for CI mode ci_mode = os.environ.get("CI", "").lower() in ("true", "1", "yes") skip_index = args.skip_index or ci_mode print_banner() # Check dependencies if not check_requirements(): sys.exit(1) # Setup directories setup_directories() # Setup database try: setup_database(force_reindex=args.reindex, skip_index=skip_index) except Exception as e: print(f"❌ Database setup error: {e}") sys.exit(1) # Start server try: start_server(host=args.host, port=args.port, reload=args.dev) except KeyboardInterrupt: print("\n👋 Server stopped!") except Exception as e: print(f"❌ Server error: {e}") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "Zie619/n8n-workflows", "file_path": "run.py", "license": "MIT License", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Zie619/n8n-workflows:api_server.py
#!/usr/bin/env python3 """ FastAPI Server for N8N Workflow Documentation High-performance API with sub-100ms response times. """ from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse, FileResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from pydantic import BaseModel, field_validator from typing import Optional, List, Dict, Any import json import os import re import urllib.parse from pathlib import Path import uvicorn import time from collections import defaultdict from workflow_db import WorkflowDatabase # Initialize FastAPI app app = FastAPI( title="N8N Workflow Documentation API", description="Fast API for browsing and searching workflow documentation", version="2.0.0", ) # Security: Rate limiting storage rate_limit_storage = defaultdict(list) MAX_REQUESTS_PER_MINUTE = 60 # Configure as needed # Add middleware for performance app.add_middleware(GZipMiddleware, minimum_size=1000) # Security: Configure CORS properly - restrict origins in production # For local development, you can use localhost # For production, replace with your actual domain ALLOWED_ORIGINS = [ "http://localhost:3000", "http://localhost:8000", "http://localhost:8080", "https://zie619.github.io", # GitHub Pages "https://n8n-workflows-1-xxgm.onrender.com", # Community deployment ] app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, # Security fix: Restrict origins allow_credentials=True, allow_methods=["GET", "POST"], # Security fix: Only allow needed methods allow_headers=["Content-Type", "Authorization"], # Security fix: Restrict headers ) # Initialize database db = WorkflowDatabase() # Security: Helper function for rate limiting def check_rate_limit(client_ip: str) -> bool: """Check if client has exceeded rate limit.""" current_time = time.time() # Clean old entries rate_limit_storage[client_ip] = [ timestamp for timestamp in rate_limit_storage[client_ip] if current_time - timestamp < 60 ] # Check rate limit if len(rate_limit_storage[client_ip]) >= MAX_REQUESTS_PER_MINUTE: return False # Add current request rate_limit_storage[client_ip].append(current_time) return True # Security: Helper function to validate and sanitize filenames def validate_filename(filename: str) -> bool: """ Validate filename to prevent path traversal attacks. Returns True if filename is safe, False otherwise. """ # Decode URL encoding multiple times to catch encoded traversal attempts decoded = filename for _ in range(3): # Decode up to 3 times to catch nested encodings try: decoded = urllib.parse.unquote(decoded, errors="strict") except: return False # Invalid encoding # Check for path traversal patterns dangerous_patterns = [ "..", # Parent directory "..\\", # Windows parent directory "../", # Unix parent directory "\\", # Backslash (Windows path separator) "/", # Forward slash (Unix path separator) "\x00", # Null byte "\n", "\r", # Newlines "~", # Home directory ":", # Drive letter or stream (Windows) "|", "<", ">", # Shell redirection "*", "?", # Wildcards "$", # Variable expansion ";", "&", # Command separators ] for pattern in dangerous_patterns: if pattern in decoded: return False # Check for absolute paths if decoded.startswith("/") or decoded.startswith("\\"): return False # Check for Windows drive letters if len(decoded) >= 2 and decoded[1] == ":": return False # Only allow alphanumeric, dash, underscore, and .json extension if not re.match(r"^[a-zA-Z0-9_\-]+\.json$", decoded): return False # Additional check: filename should end with .json if not decoded.endswith(".json"): return False return True # Startup function to verify database @app.on_event("startup") async def startup_event(): """Verify database connectivity on startup.""" try: stats = db.get_stats() if stats["total"] == 0: print("⚠️ Warning: No workflows found in database. Run indexing first.") else: print(f"✅ Database connected: {stats['total']} workflows indexed") except Exception as e: print(f"❌ Database connection failed: {e}") raise # Response models class WorkflowSummary(BaseModel): id: Optional[int] = None filename: str name: str active: bool description: str = "" trigger_type: str = "Manual" complexity: str = "low" node_count: int = 0 integrations: List[str] = [] tags: List[str] = [] created_at: Optional[str] = None updated_at: Optional[str] = None class Config: # Allow conversion of int to bool for active field validate_assignment = True @field_validator("active", mode="before") @classmethod def convert_active(cls, v): if isinstance(v, int): return bool(v) return v class SearchResponse(BaseModel): workflows: List[WorkflowSummary] total: int page: int per_page: int pages: int query: str filters: Dict[str, Any] class StatsResponse(BaseModel): total: int active: int inactive: int triggers: Dict[str, int] complexity: Dict[str, int] total_nodes: int unique_integrations: int last_indexed: str @app.get("/") async def root(): """Serve the main documentation page.""" static_dir = Path("static") index_file = static_dir / "index.html" if not index_file.exists(): return HTMLResponse( """ <html><body> <h1>Setup Required</h1> <p>Static files not found. Please ensure the static directory exists with index.html</p> <p>Current directory: """ + str(Path.cwd()) + """</p> </body></html> """ ) return FileResponse(str(index_file)) @app.get("/health") async def health_check(): """Health check endpoint.""" return {"status": "healthy", "message": "N8N Workflow API is running"} @app.get("/api/stats", response_model=StatsResponse) async def get_stats(): """Get workflow database statistics.""" try: stats = db.get_stats() return StatsResponse(**stats) except Exception as e: raise HTTPException(status_code=500, detail=f"Error fetching stats: {str(e)}") @app.get("/api/workflows", response_model=SearchResponse) async def search_workflows( q: str = Query("", description="Search query"), trigger: str = Query("all", description="Filter by trigger type"), complexity: str = Query("all", description="Filter by complexity"), active_only: bool = Query(False, description="Show only active workflows"), page: int = Query(1, ge=1, description="Page number"), per_page: int = Query(20, ge=1, le=100, description="Items per page"), ): """Search and filter workflows with pagination.""" try: offset = (page - 1) * per_page workflows, total = db.search_workflows( query=q, trigger_filter=trigger, complexity_filter=complexity, active_only=active_only, limit=per_page, offset=offset, ) # Convert to Pydantic models with error handling workflow_summaries = [] for workflow in workflows: try: # Remove extra fields that aren't in the model clean_workflow = { "id": workflow.get("id"), "filename": workflow.get("filename", ""), "name": workflow.get("name", ""), "active": workflow.get("active", False), "description": workflow.get("description", ""), "trigger_type": workflow.get("trigger_type", "Manual"), "complexity": workflow.get("complexity", "low"), "node_count": workflow.get("node_count", 0), "integrations": workflow.get("integrations", []), "tags": workflow.get("tags", []), "created_at": workflow.get("created_at"), "updated_at": workflow.get("updated_at"), } workflow_summaries.append(WorkflowSummary(**clean_workflow)) except Exception as e: print( f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}" ) # Continue with other workflows instead of failing completely continue pages = (total + per_page - 1) // per_page # Ceiling division return SearchResponse( workflows=workflow_summaries, total=total, page=page, per_page=per_page, pages=pages, query=q, filters={ "trigger": trigger, "complexity": complexity, "active_only": active_only, }, ) except Exception as e: raise HTTPException( status_code=500, detail=f"Error searching workflows: {str(e)}" ) @app.get("/api/workflows/{filename}") async def get_workflow_detail(filename: str, request: Request): """Get detailed workflow information including raw JSON.""" try: # Security: Validate filename to prevent path traversal if not validate_filename(filename): print(f"Security: Blocked path traversal attempt for filename: {filename}") raise HTTPException(status_code=400, detail="Invalid filename format") # Security: Rate limiting client_ip = request.client.host if request.client else "unknown" if not check_rate_limit(client_ip): raise HTTPException( status_code=429, detail="Rate limit exceeded. Please try again later." ) # Get workflow metadata from database workflows, _ = db.search_workflows(f'filename:"{filename}"', limit=1) if not workflows: raise HTTPException( status_code=404, detail="Workflow not found in database" ) workflow_meta = workflows[0] # Load raw JSON from file with security checks workflows_path = Path("workflows").resolve() # Find the file safely matching_file = None for subdir in workflows_path.iterdir(): if subdir.is_dir(): target_file = subdir / filename if target_file.exists() and target_file.is_file(): # Verify the file is actually within workflows directory try: target_file.resolve().relative_to(workflows_path) matching_file = target_file break except ValueError: print( f"Security: Blocked access to file outside workflows: {target_file}" ) continue if not matching_file: print(f"Warning: File {filename} not found in workflows directory") raise HTTPException( status_code=404, detail=f"Workflow file '{filename}' not found on filesystem", ) with open(matching_file, "r", encoding="utf-8") as f: raw_json = json.load(f) return {"metadata": workflow_meta, "raw_json": raw_json} except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"Error loading workflow: {str(e)}") @app.get("/api/workflows/{filename}/download") async def download_workflow(filename: str, request: Request): """Download workflow JSON file with security validation.""" try: # Security: Validate filename to prevent path traversal if not validate_filename(filename): print(f"Security: Blocked path traversal attempt for filename: {filename}") raise HTTPException(status_code=400, detail="Invalid filename format") # Security: Rate limiting client_ip = request.client.host if request.client else "unknown" if not check_rate_limit(client_ip): raise HTTPException( status_code=429, detail="Rate limit exceeded. Please try again later." ) # Only search within the workflows directory workflows_path = Path("workflows").resolve() # Get absolute path # Find the file safely json_files = [] for subdir in workflows_path.iterdir(): if subdir.is_dir(): target_file = subdir / filename if target_file.exists() and target_file.is_file(): # Verify the file is actually within workflows directory (defense in depth) try: target_file.resolve().relative_to(workflows_path) json_files.append(target_file) except ValueError: # File is outside workflows directory print( f"Security: Blocked access to file outside workflows: {target_file}" ) continue if not json_files: print(f"File {filename} not found in workflows directory") raise HTTPException( status_code=404, detail=f"Workflow file '{filename}' not found" ) file_path = json_files[0] # Final security check: Ensure file is within workflows directory try: file_path.resolve().relative_to(workflows_path) except ValueError: print( f"Security: Blocked final attempt to access file outside workflows: {file_path}" ) raise HTTPException(status_code=403, detail="Access denied") return FileResponse( str(file_path), media_type="application/json", filename=filename ) except HTTPException: raise except Exception as e: print(f"Error downloading workflow {filename}: {str(e)}") raise HTTPException( status_code=500, detail=f"Error downloading workflow: {str(e)}" ) @app.get("/api/workflows/{filename}/diagram") async def get_workflow_diagram(filename: str, request: Request): """Get Mermaid diagram code for workflow visualization.""" try: # Security: Validate filename to prevent path traversal if not validate_filename(filename): print(f"Security: Blocked path traversal attempt for filename: {filename}") raise HTTPException(status_code=400, detail="Invalid filename format") # Security: Rate limiting client_ip = request.client.host if request.client else "unknown" if not check_rate_limit(client_ip): raise HTTPException( status_code=429, detail="Rate limit exceeded. Please try again later." ) # Only search within the workflows directory workflows_path = Path("workflows").resolve() # Find the file safely matching_file = None for subdir in workflows_path.iterdir(): if subdir.is_dir(): target_file = subdir / filename if target_file.exists() and target_file.is_file(): # Verify the file is actually within workflows directory try: target_file.resolve().relative_to(workflows_path) matching_file = target_file break except ValueError: print( f"Security: Blocked access to file outside workflows: {target_file}" ) continue if not matching_file: print(f"Warning: File {filename} not found in workflows directory") raise HTTPException( status_code=404, detail=f"Workflow file '{filename}' not found on filesystem", ) with open(matching_file, "r", encoding="utf-8") as f: data = json.load(f) nodes = data.get("nodes", []) connections = data.get("connections", {}) # Generate Mermaid diagram diagram = generate_mermaid_diagram(nodes, connections) return {"diagram": diagram} except HTTPException: raise except json.JSONDecodeError as e: print(f"Error parsing JSON in {filename}: {str(e)}") raise HTTPException( status_code=400, detail=f"Invalid JSON in workflow file: {str(e)}" ) except Exception as e: print(f"Error generating diagram for {filename}: {str(e)}") raise HTTPException( status_code=500, detail=f"Error generating diagram: {str(e)}" ) def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str: """Generate Mermaid.js flowchart code from workflow nodes and connections.""" if not nodes: return "graph TD\n EmptyWorkflow[No nodes found in workflow]" # Create mapping for node names to ensure valid mermaid IDs mermaid_ids = {} for i, node in enumerate(nodes): node_id = f"node{i}" node_name = node.get("name", f"Node {i}") mermaid_ids[node_name] = node_id # Start building the mermaid diagram mermaid_code = ["graph TD"] # Add nodes with styling for node in nodes: node_name = node.get("name", "Unnamed") node_id = mermaid_ids[node_name] node_type = node.get("type", "").replace("n8n-nodes-base.", "") # Determine node style based on type style = "" if any(x in node_type.lower() for x in ["trigger", "webhook", "cron"]): style = "fill:#b3e0ff,stroke:#0066cc" # Blue for triggers elif any(x in node_type.lower() for x in ["if", "switch"]): style = "fill:#ffffb3,stroke:#e6e600" # Yellow for conditional nodes elif any(x in node_type.lower() for x in ["function", "code"]): style = "fill:#d9b3ff,stroke:#6600cc" # Purple for code nodes elif "error" in node_type.lower(): style = "fill:#ffb3b3,stroke:#cc0000" # Red for error handlers else: style = "fill:#d9d9d9,stroke:#666666" # Gray for other nodes # Add node with label (escaping special characters) clean_name = node_name.replace('"', "'") clean_type = node_type.replace('"', "'") label = f"{clean_name}<br>({clean_type})" mermaid_code.append(f' {node_id}["{label}"]') mermaid_code.append(f" style {node_id} {style}") # Add connections between nodes for source_name, source_connections in connections.items(): if source_name not in mermaid_ids: continue if isinstance(source_connections, dict) and "main" in source_connections: main_connections = source_connections["main"] for i, output_connections in enumerate(main_connections): if not isinstance(output_connections, list): continue for connection in output_connections: if not isinstance(connection, dict) or "node" not in connection: continue target_name = connection["node"] if target_name not in mermaid_ids: continue # Add arrow with output index if multiple outputs label = f" -->|{i}| " if len(main_connections) > 1 else " --> " mermaid_code.append( f" {mermaid_ids[source_name]}{label}{mermaid_ids[target_name]}" ) # Format the final mermaid diagram code return "\n".join(mermaid_code) @app.post("/api/reindex") async def reindex_workflows( background_tasks: BackgroundTasks, request: Request, force: bool = False, admin_token: Optional[str] = Query(None, description="Admin authentication token"), ): """Trigger workflow reindexing in the background (requires authentication).""" # Security: Rate limiting client_ip = request.client.host if request.client else "unknown" if not check_rate_limit(client_ip): raise HTTPException( status_code=429, detail="Rate limit exceeded. Please try again later." ) # Security: Basic authentication check # In production, use proper authentication (JWT, OAuth, etc.) # For now, check for environment variable or disable endpoint expected_token = os.environ.get("ADMIN_TOKEN", None) if not expected_token: # If no token is configured, disable the endpoint for security raise HTTPException( status_code=503, detail="Reindexing endpoint is disabled. Set ADMIN_TOKEN environment variable to enable.", ) if admin_token != expected_token: print(f"Security: Unauthorized reindex attempt from {client_ip}") raise HTTPException(status_code=401, detail="Invalid authentication token") def run_indexing(): try: db.index_all_workflows(force_reindex=force) print(f"Reindexing completed successfully (requested by {client_ip})") except Exception as e: print(f"Error during reindexing: {e}") background_tasks.add_task(run_indexing) return {"message": "Reindexing started in background", "requested_by": client_ip} @app.get("/api/integrations") async def get_integrations(): """Get list of all unique integrations.""" try: stats = db.get_stats() # For now, return basic info. Could be enhanced to return detailed integration stats return {"integrations": [], "count": stats["unique_integrations"]} except Exception as e: raise HTTPException( status_code=500, detail=f"Error fetching integrations: {str(e)}" ) @app.get("/api/categories") async def get_categories(): """Get available workflow categories for filtering.""" try: # Try to load from the generated unique categories file categories_file = Path("context/unique_categories.json") if categories_file.exists(): with open(categories_file, "r", encoding="utf-8") as f: categories = json.load(f) return {"categories": categories} else: # Fallback: extract categories from search_categories.json search_categories_file = Path("context/search_categories.json") if search_categories_file.exists(): with open(search_categories_file, "r", encoding="utf-8") as f: search_data = json.load(f) unique_categories = set() for item in search_data: if item.get("category"): unique_categories.add(item["category"]) else: unique_categories.add("Uncategorized") categories = sorted(list(unique_categories)) return {"categories": categories} else: # Last resort: return basic categories return {"categories": ["Uncategorized"]} except Exception as e: print(f"Error loading categories: {e}") raise HTTPException( status_code=500, detail=f"Error fetching categories: {str(e)}" ) @app.get("/api/category-mappings") async def get_category_mappings(): """Get filename to category mappings for client-side filtering.""" try: search_categories_file = Path("context/search_categories.json") if not search_categories_file.exists(): return {"mappings": {}} with open(search_categories_file, "r", encoding="utf-8") as f: search_data = json.load(f) # Convert to a simple filename -> category mapping mappings = {} for item in search_data: filename = item.get("filename") category = item.get("category") or "Uncategorized" if filename: mappings[filename] = category return {"mappings": mappings} except Exception as e: print(f"Error loading category mappings: {e}") raise HTTPException( status_code=500, detail=f"Error fetching category mappings: {str(e)}" ) @app.get("/api/workflows/category/{category}", response_model=SearchResponse) async def search_workflows_by_category( category: str, page: int = Query(1, ge=1, description="Page number"), per_page: int = Query(20, ge=1, le=100, description="Items per page"), ): """Search workflows by service category (messaging, database, ai_ml, etc.).""" try: offset = (page - 1) * per_page workflows, total = db.search_by_category( category=category, limit=per_page, offset=offset ) # Convert to Pydantic models with error handling workflow_summaries = [] for workflow in workflows: try: clean_workflow = { "id": workflow.get("id"), "filename": workflow.get("filename", ""), "name": workflow.get("name", ""), "active": workflow.get("active", False), "description": workflow.get("description", ""), "trigger_type": workflow.get("trigger_type", "Manual"), "complexity": workflow.get("complexity", "low"), "node_count": workflow.get("node_count", 0), "integrations": workflow.get("integrations", []), "tags": workflow.get("tags", []), "created_at": workflow.get("created_at"), "updated_at": workflow.get("updated_at"), } workflow_summaries.append(WorkflowSummary(**clean_workflow)) except Exception as e: print( f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}" ) continue pages = (total + per_page - 1) // per_page return SearchResponse( workflows=workflow_summaries, total=total, page=page, per_page=per_page, pages=pages, query=f"category:{category}", filters={"category": category}, ) except Exception as e: raise HTTPException( status_code=500, detail=f"Error searching by category: {str(e)}" ) # Custom exception handler for better error responses @app.exception_handler(Exception) async def global_exception_handler(request, exc): return JSONResponse( status_code=500, content={"detail": f"Internal server error: {str(exc)}"} ) # Mount static files AFTER all routes are defined static_dir = Path("static") if static_dir.exists(): app.mount("/static", StaticFiles(directory="static"), name="static") print(f"✅ Static files mounted from {static_dir.absolute()}") else: print(f"❌ Warning: Static directory not found at {static_dir.absolute()}") def create_static_directory(): """Create static directory if it doesn't exist.""" static_dir = Path("static") static_dir.mkdir(exist_ok=True) return static_dir def run_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False): """Run the FastAPI server.""" # Ensure static directory exists create_static_directory() # Debug: Check database connectivity try: stats = db.get_stats() print(f"✅ Database connected: {stats['total']} workflows found") if stats["total"] == 0: print("🔄 Database is empty. Indexing workflows...") db.index_all_workflows() stats = db.get_stats() except Exception as e: print(f"❌ Database error: {e}") print("🔄 Attempting to create and index database...") try: db.index_all_workflows() stats = db.get_stats() print(f"✅ Database created: {stats['total']} workflows indexed") except Exception as e2: print(f"❌ Failed to create database: {e2}") stats = {"total": 0} # Debug: Check static files static_path = Path("static") if static_path.exists(): files = list(static_path.glob("*")) print(f"✅ Static files found: {[f.name for f in files]}") else: print(f"❌ Static directory not found at: {static_path.absolute()}") print("🚀 Starting N8N Workflow Documentation API") print(f"📊 Database contains {stats['total']} workflows") print(f"🌐 Server will be available at: http://{host}:{port}") print(f"📁 Static files at: http://{host}:{port}/static/") uvicorn.run( "api_server:app", host=host, port=port, reload=reload, access_log=True, # Enable access logs for debugging log_level="info", ) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description="N8N Workflow Documentation API Server" ) parser.add_argument("--host", default="127.0.0.1", help="Host to bind to") parser.add_argument("--port", type=int, default=8000, help="Port to bind to") parser.add_argument( "--reload", action="store_true", help="Enable auto-reload for development" ) args = parser.parse_args() run_server(host=args.host, port=args.port, reload=args.reload)
{ "repo_id": "Zie619/n8n-workflows", "file_path": "api_server.py", "license": "MIT License", "lines": 707, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/02_agents/04_tools/04_tools_with_literal_type_param.py
""" Example demonstrating Literal type support in Agno tools. This example shows how to use typing.Literal for function parameters in Agno toolkits and standalone tools. Literal types are useful when a parameter should only accept specific predefined values. """ from typing import Literal from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools import Toolkit class FileOperationsToolkit(Toolkit): """A toolkit demonstrating Literal type parameters.""" def __init__(self): super().__init__(name="file_operations", tools=[self.manage_file]) def manage_file( self, filename: str, operation: Literal["create", "read", "update", "delete"] = "read", priority: Literal["low", "medium", "high"] = "medium", ) -> str: """ Manage a file with the specified operation. Args: filename: The name of the file to operate on. operation: The operation to perform on the file. priority: The priority level for this operation. Returns: A message describing what was done. """ return f"Performed '{operation}' on '{filename}' with {priority} priority" def standalone_tool( action: Literal["start", "stop", "restart"], service_name: str, ) -> str: """ Control a service with the specified action. Args: action: The action to perform on the service. service_name: The name of the service to control. Returns: A message describing the action taken. """ return f"Service '{service_name}' has been {action}ed" def main(): # Create an agent with both toolkit and standalone tool agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), tools=[FileOperationsToolkit(), standalone_tool], instructions="You are a helpful assistant that can manage files and services.", markdown=True, ) # Test with file operations print("Testing file operations with Literal types:") agent.print_response( "Create a new file called 'report.txt' with high priority", stream=True ) print("\n" + "=" * 50 + "\n") # Test with service control print("Testing service control with Literal types:") agent.print_response("Restart the web server service", stream=True) if __name__ == "__main__": main()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/02_agents/04_tools/04_tools_with_literal_type_param.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/gemini_3/10_audio_input.py
""" Audio Understanding - Transcribe and Analyze Audio ==================================================== Pass audio files to Gemini for transcription, summarization, and analysis. Key concepts: - Audio(content=..., format=...): Pass audio bytes with format (mp3, wav, etc.) - Native capability: No Whisper or speech-to-text APIs needed - Multi-format: Supports MP3, WAV, FLAC, OGG, and more Example prompts to try: - "Transcribe and summarize this audio" - "What language is being spoken?" - "How many speakers are in this recording?" - "What is the overall sentiment of this conversation?" """ import httpx from agno.agent import Agent from agno.media import Audio from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are an audio analysis expert. Transcribe and summarize audio content clearly. ## Rules - Provide a complete transcription when asked - Note speaker changes if multiple speakers - Summarize key points after transcription\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- audio_agent = Agent( name="Audio Analyst", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Download a sample audio file url = "https://agno-public.s3.amazonaws.com/demo/sample-audio.mp3" response = httpx.get(url) audio_agent.print_response( "Transcribe and summarize this audio.", audio=[ Audio(content=response.content, format="mp3"), ], stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Audio input methods: 1. From URL (download first) import httpx response = httpx.get("https://example.com/audio.mp3") audio=[Audio(content=response.content, format="mp3")] 2. From local file audio_bytes = Path("recording.wav").read_bytes() audio=[Audio(content=audio_bytes, format="wav")] 3. Multiple audio files audio=[Audio(content=clip1, format="mp3"), Audio(content=clip2, format="mp3")] Use cases for music/film/gaming: - Transcribe podcast interviews for show notes - Analyze music samples for mood and genre classification - Extract dialogue from film clips for subtitle generation - Analyze game audio for sound design review """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/10_audio_input.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/11_text_to_speech.py
""" Text-to-Speech - Generate Spoken Audio ======================================== Generate spoken audio from text using Gemini's TTS model. Key concepts: - response_modalities=["AUDIO"]: Tells Gemini to output audio instead of text - speech_config: Configure voice name and other TTS settings - Dedicated TTS model: Uses gemini-2.5-flash-preview-tts (not the standard model) - response_audio: Access the audio bytes from RunOutput Available voices: Kore, Charon, Fenrir, Aoede, Puck, and more. Example prompts to try: - "Say cheerfully: Have a wonderful day!" - "Read this like a news anchor: Breaking news..." - "Narrate this in a dramatic tone: The castle stood silent..." """ from pathlib import Path from agno.agent import Agent from agno.models.google import Gemini from agno.utils.audio import write_wav_audio_to_file WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- tts_agent = Agent( name="TTS Agent", model=Gemini( # Dedicated TTS model, not the standard Gemini model id="gemini-2.5-flash-preview-tts", response_modalities=["AUDIO"], speech_config={ "voice_config": {"prebuilt_voice_config": {"voice_name": "Kore"}} }, ), ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": run_output = tts_agent.run("Say cheerfully: Have a wonderful day!") if run_output.response_audio is not None: audio_data = run_output.response_audio.content output_file = str(WORKSPACE / "greeting.wav") write_wav_audio_to_file(output_file, audio_data) print(f"Audio saved to {output_file}") else: print("No audio in response") # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Voice options for speech_config: - "Kore": Clear, professional female voice - "Charon": Deep, authoritative male voice - "Fenrir": Warm, conversational male voice - "Aoede": Expressive, melodic female voice - "Puck": Energetic, youthful voice Changing voices: speech_config={ "voice_config": { "prebuilt_voice_config": {"voice_name": "Charon"} } } Use cases for music/film/gaming: - Generate voiceover for game cutscenes - Create narration for film trailers - Produce podcast intros and outros - Generate audio descriptions for accessibility """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/11_text_to_speech.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/12_video_input.py
""" Video Understanding - Analyze Video Content ============================================= Pass video files or YouTube URLs to Gemini for scene analysis and Q&A. Key concepts: - Video(content=..., format=...): Pass video bytes with format (mp4, etc.) - Video(url=...): Pass a YouTube URL directly - Native capability: No ffmpeg or video processing libraries needed - Scene understanding: The model processes visual and audio tracks together Example prompts to try: - "Describe and summarize this video" - "What are the key moments in this video?" - "How many people appear in this video?" - "What is the overall mood of this video?" """ import httpx from agno.agent import Agent from agno.media import Video from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a video analysis expert. Describe the key scenes and provide a clear summary. ## Rules - Describe scenes chronologically - Note any text, logos, or titles that appear - Identify the overall theme or message - Mention audio elements when relevant\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- video_agent = Agent( name="Video Analyst", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # --- From bytes content --- print("--- Analyzing video from bytes ---\n") url = "https://agno-public.s3.amazonaws.com/demo/sample_seaview.mp4" response = httpx.get(url) video_agent.print_response( "Describe and summarize this video.", videos=[ Video(content=response.content, format="mp4"), ], stream=True, ) # --- From YouTube URL --- print("\n--- Analyzing YouTube video ---\n") video_agent.print_response( "Tell me about this video.", videos=[Video(url="https://www.youtube.com/watch?v=XinoY2LDdA0")], stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Video input methods: 1. From URL (download first) response = httpx.get("https://example.com/video.mp4") videos=[Video(content=response.content, format="mp4")] 2. From local file video_bytes = Path("clip.mp4").read_bytes() videos=[Video(content=video_bytes, format="mp4")] 3. From YouTube (pass URL directly) videos=[Video(url="https://www.youtube.com/watch?v=...")] Use cases for music/film/gaming: - Analyze music videos for visual themes and mood - Break down film scenes for editing review - Review game trailers for content and pacing - Extract key moments from livestream recordings """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/12_video_input.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/13_pdf_input.py
""" PDF Understanding - Read and Analyze Documents ================================================ Pass PDF documents to Gemini for reading and analysis. No parsing libraries needed. Key concepts: - File(url=..., mime_type="application/pdf"): Pass a PDF from a URL - File(filepath=..., mime_type="application/pdf"): Pass a local PDF - Native capability: No PyPDF, pdfplumber, or other parsing libraries needed - Layout-aware: The model understands tables, columns, and formatting Example prompts to try: - "Summarize the contents of this document" - "What are the main recipes in this cookbook?" - "Extract all the key findings from this research paper" """ from agno.agent import Agent from agno.media import File from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a document analysis expert. Read documents thoroughly and provide clear summaries. ## Rules - Summarize the main points first - Note any tables or structured data - Highlight actionable information\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- doc_reader = Agent( name="Document Reader", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": doc_reader.print_response( "Summarize the contents of this document and suggest a recipe from it.", files=[ File( url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", mime_type="application/pdf", ) ], stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ PDF input methods: 1. From URL files=[File(url="https://example.com/report.pdf", mime_type="application/pdf")] 2. From local file files=[File(filepath="path/to/report.pdf", mime_type="application/pdf")] 3. Multiple PDFs files=[ File(url="...", mime_type="application/pdf"), File(filepath="...", mime_type="application/pdf"), ] 4. With structured output (extract data from PDFs) class Report(BaseModel): title: str key_findings: List[str] recommendations: List[str] agent = Agent(model=Gemini(...), output_schema=Report) result = agent.run("Extract findings", files=[...]) Use cases for music/film/gaming: - Parse music licensing contracts - Extract requirements from game design documents - Analyze film scripts for scene breakdowns """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/13_pdf_input.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/14_csv_input.py
""" CSV Input - Analyze Datasets Directly ======================================= Pass CSV files to Gemini for analysis. No pandas or data processing needed. Key concepts: - File(filepath=..., mime_type="text/csv"): Pass a local CSV file - download_file: Utility to download remote files to local workspace - Native capability: No pandas or data processing libraries needed - Data analysis: The model can compute statistics, find trends, and create summaries Example prompts to try: - "Analyze the top 10 highest-grossing movies in this dataset" - "What genres have the highest average ratings?" - "Find any interesting trends or outliers in this data" """ from pathlib import Path from agno.agent import Agent from agno.media import File from agno.models.google import Gemini from agno.utils.media import download_file WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a data analyst. Analyze datasets and provide clear insights with tables and summaries. ## Rules - Start with an overview of the dataset (rows, columns, types) - Use tables for comparisons and rankings - Highlight interesting patterns or outliers - Be specific with numbers\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- csv_agent = Agent( name="Data Analyst", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": csv_path = WORKSPACE / "IMDB-Movie-Data.csv" # Download sample dataset if not already present download_file( "https://agno-public.s3.amazonaws.com/demo_data/IMDB-Movie-Data.csv", str(csv_path), ) csv_agent.print_response( "Analyze the top 10 highest-grossing movies in this dataset. " "Which genres perform best at the box office?", files=[ File(filepath=csv_path, mime_type="text/csv"), ], stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ CSV analysis patterns: 1. Quick overview "Describe this dataset: columns, row count, data types" 2. Rankings and comparisons "What are the top 10 items by revenue?" 3. Trend analysis "How have ratings changed over the years?" 4. With structured output class DataSummary(BaseModel): total_rows: int top_items: List[str] average_rating: float trend: str agent = Agent(model=Gemini(...), output_schema=DataSummary) result = agent.run("Summarize this data", files=[...]) Use cases for music/film/gaming: - Analyze streaming metrics for music catalog - Review box office performance data for films - Process player engagement data for games """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/14_csv_input.py", "license": "Apache License 2.0", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/15_file_search.py
""" File Search - Server-Side RAG with Citations ============================================== Upload documents to a Google-managed store and query them with automatic RAG. Key concepts: - create_file_search_store: Creates a managed document store on Google's servers - upload_to_file_search_store: Uploads documents for automatic chunking and indexing - file_search_store_names: Links the store to your Gemini model - Citations: Responses include source references you can verify - Managed RAG: No ChromaDB, no embeddings config. Google handles it all Example prompts to try: - "What are the main safety guidelines?" - "What should I do if I see a hazard?" """ from pathlib import Path from textwrap import dedent from agno.agent import Agent from agno.models.google import Gemini WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Create a sample document # --------------------------------------------------------------------------- SAMPLE_DOC = WORKSPACE / "company_guidelines.txt" SAMPLE_DOC.write_text( dedent("""\ Company Safety Guidelines 1. All employees must wear safety equipment in the warehouse. 2. Fire exits must remain clear at all times. 3. Report any safety hazards to your supervisor immediately. 4. First aid kits are located on every floor near the elevators. 5. Emergency drills are conducted quarterly. 6. Remote workers should ensure their home office meets ergonomic standards. 7. All incidents, no matter how minor, must be documented within 24 hours. 8. Visitors must be accompanied by an employee at all times. """) ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- model = Gemini(id="gemini-3.1-pro-preview") file_search_agent = Agent( name="File Search Agent", model=model, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Step 1: Create a File Search store (managed by Google) print("Creating File Search store...") store = model.create_file_search_store(display_name="Guidelines Store") print(f"Created store: {store.name}") # Step 2: Upload the document (auto-chunked and indexed) print("\nUploading document...") operation = model.upload_to_file_search_store( file_path=SAMPLE_DOC, store_name=store.name, display_name="Company Safety Guidelines", ) print("Waiting for upload to complete...") model.wait_for_operation(operation) print("Upload complete.") # Step 3: Configure model to use the store model.file_search_store_names = [store.name] # Step 4: Query the documents print("\nQuerying documents...\n") run = file_search_agent.run( "What are the main safety guidelines? What should I do if I see a hazard?" ) print(run.content) # Step 5: Show citations if run.citations and run.citations.raw: grounding_metadata = run.citations.raw.get("grounding_metadata", {}) chunks = grounding_metadata.get("grounding_chunks", []) or [] if chunks: print(f"\nCitations ({len(chunks)} sources found)") # Cleanup print("\nCleaning up store...") model.delete_file_search_store(store.name, force=True) print("Done.") # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ File Search vs local Knowledge (step 17): File Search (this example): - Fully managed by Google, no local vector DB - Automatic chunking and embedding - Built-in citation support - Best for: quick prototyping, small document sets, when you don't want infra Local Knowledge (step 17): - Uses ChromaDb (or PgVector) locally - You control chunking, embedding model, and search strategy - Hybrid search (semantic + keyword) - Best for: production apps, large document sets, custom search logic Upload multiple files: for doc in ["report.pdf", "faq.txt", "manual.pdf"]: model.upload_to_file_search_store( file_path=doc, store_name=store.name, display_name=doc ) """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/15_file_search.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/16_prompt_caching.py
""" Prompt Caching - Save Tokens on Repeated Queries ================================================== Cache large documents server-side so repeated queries skip the full token cost. Key concepts: - genai.Client().caches.create: Creates a server-side cache with TTL - cached_content: Links the cache to your Gemini model - TTL: Time-to-live for the cache (e.g., "300s" = 5 minutes) - Token savings: Subsequent queries skip the cached content's token cost Example prompts to try: - "Find a lighthearted moment from this transcript" - "What was the most tense moment during the mission?" - "Summarize the key decisions made" """ from pathlib import Path from time import sleep import requests from agno.agent import Agent from agno.models.google import Gemini from google import genai from google.genai.types import UploadFileConfig WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Download and upload the source document # --------------------------------------------------------------------------- client = genai.Client() # Download a large text file (Apollo 11 transcript, ~100K tokens) txt_url = "https://storage.googleapis.com/generativeai-downloads/data/a11.txt" txt_path = WORKSPACE / "a11.txt" if not txt_path.exists(): print("Downloading transcript...") with txt_path.open("wb") as f: resp = requests.get(txt_url, stream=True) for chunk in resp.iter_content(chunk_size=32768): f.write(chunk) # Upload to Google (get-or-create pattern) remote_name = "files/a11" txt_file = None try: txt_file = client.files.get(name=remote_name) print(f"File already uploaded: {txt_file.uri}") except Exception: pass if not txt_file: print("Uploading file...") txt_file = client.files.upload( file=txt_path, config=UploadFileConfig(name=remote_name), ) while txt_file and txt_file.state and txt_file.state.name == "PROCESSING": print("Processing...") sleep(2) txt_file = client.files.get(name=remote_name) print(f"Upload complete: {txt_file.uri}") # --------------------------------------------------------------------------- # Create cache # --------------------------------------------------------------------------- print("\nCreating cache (5 min TTL)...") cache = client.caches.create( model="gemini-3-flash-preview", config={ "system_instruction": "You are an expert at analyzing transcripts.", "contents": [txt_file], # Cache expires after 5 minutes, set higher for production "ttl": "300s", }, ) print(f"Cache created: {cache.name}") # --------------------------------------------------------------------------- # Create Agent with cached content # --------------------------------------------------------------------------- cache_agent = Agent( name="Transcript Analyst", # cached_content links the agent to the pre-loaded cache model=Gemini(id="gemini-3-flash-preview", cached_content=cache.name), ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Query 1: The full transcript is in the cache, no need to re-send run_output = cache_agent.run("Find a lighthearted moment from this transcript") print(f"\nResponse:\n{run_output.content}") print(f"\nMetrics: {run_output.metrics}") # Query 2: Same cache, different question, shows token savings run_output = cache_agent.run("What was the most tense moment during the mission?") print(f"\nResponse:\n{run_output.content}") print(f"\nMetrics: {run_output.metrics}") # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Prompt caching economics: - First query: Full token cost (upload + prompt + response) - Subsequent queries: Only prompt + response tokens (cached content is free) - For a 100K-token document queried 10 times: Without caching: 10 * 100K = 1M input tokens With caching: 100K + 10 * (prompt only) = ~110K input tokens TTL guidelines: - "300s" (5 min): Development and testing - "3600s" (1 hour): Interactive sessions - "86400s" (24 hours): Production batch jobs Cache limitations: - Minimum cached content: ~32K tokens - Maximum TTL varies by model - Cache is per-model, switching models requires a new cache """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/16_prompt_caching.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/gemini_3/17_knowledge.py
""" Knowledge Base + Storage - Recipe Assistant with RAG ===================================================== Give an agent persistent storage and a searchable knowledge base. Key concepts: - Knowledge: A searchable collection of documents stored in a vector database - search_knowledge=True: Agent automatically searches knowledge before answering - SqliteDb: Lightweight local database for conversation history (no Postgres needed) - ChromaDb: Local vector database for embedding and searching documents - Hybrid search: Combines semantic similarity with keyword matching for better results - GeminiEmbedder: Uses Gemini's embedding model for vectorizing documents Example prompts to try: - "What Thai dishes can I make with chicken and coconut milk?" - "How about a vegetarian option from the same cookbook?" - "What desserts do you have in your knowledge base?" """ from pathlib import Path from agno.agent import Agent from agno.knowledge import Knowledge from agno.knowledge.embedder.google import GeminiEmbedder from agno.models.google import Gemini from agno.vectordb.chroma import ChromaDb, SearchType from db import gemini_agents_db WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) knowledge = Knowledge( name="Recipe Knowledge", vector_db=ChromaDb( collection="thai-recipes", path=str(WORKSPACE / "chromadb"), persistent_client=True, # Hybrid search combines vector similarity + keyword matching search_type=SearchType.hybrid, embedder=GeminiEmbedder(), ), # Store metadata about contents in the agent database contents_db=gemini_agents_db, ) # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a recipe assistant with access to a Thai cookbook. ## Workflow 1. Search your knowledge base for relevant recipes 2. Answer the user's question based on what you find 3. Suggest variations or substitutions when appropriate ## Rules - Always search knowledge before answering - Mention specific recipe names from the cookbook - Suggest ingredient substitutions for dietary restrictions\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- recipe_agent = Agent( name="Recipe Assistant", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, knowledge=knowledge, # Agent automatically searches knowledge when relevant search_knowledge=True, db=gemini_agents_db, # Include last 3 conversation turns for context add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Step 1: Load recipe knowledge into the knowledge base print("Loading recipe knowledge...") knowledge.insert( text_content="""\ ## Thai Recipe Collection ### Tom Kha Gai (Chicken Coconut Soup) Ingredients: chicken breast, coconut milk, galangal, lemongrass, kaffir lime leaves, fish sauce, lime juice, mushrooms, chili. Creamy and aromatic, balances sour and savory. ### Green Curry (Gaeng Keow Wan) Ingredients: green curry paste, coconut milk, chicken or tofu, Thai basil, bamboo shoots, eggplant, fish sauce, palm sugar. Rich and fragrant with a moderate heat level. ### Pad Thai Ingredients: rice noodles, shrimp or chicken, eggs, bean sprouts, peanuts, lime, tamarind paste, fish sauce, sugar. The classic Thai stir-fried noodle dish. ### Som Tum (Green Papaya Salad) Ingredients: green papaya, cherry tomatoes, green beans, peanuts, dried shrimp, garlic, chili, lime juice, fish sauce, palm sugar. Refreshing and spicy. ### Massaman Curry Ingredients: massaman curry paste, coconut milk, beef or chicken, potatoes, onions, peanuts, tamarind, cinnamon, cardamom. A mild, rich curry with Indian influences. ### Mango Sticky Rice (Khao Niew Mamuang) Ingredients: glutinous rice, ripe mango, coconut milk, sugar, salt. A beloved Thai dessert, sweet and creamy. """, ) # Step 2: Ask questions about the recipes print("\n--- Session 1: First question ---\n") recipe_agent.print_response( "What Thai dishes can I make with chicken and coconut milk?", user_id="foodie@example.com", session_id="session_1", stream=True, ) # Step 3: Follow-up in the same session (agent has context) print("\n--- Session 1: Follow-up ---\n") recipe_agent.print_response( "How about a vegetarian option from the same cookbook?", user_id="foodie@example.com", session_id="session_1", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Loading knowledge from different sources: 1. From a URL knowledge.insert(url="https://example.com/docs.pdf") 2. From a local file knowledge.insert(path="path/to/document.pdf") 3. From text directly (this example) knowledge.insert(text_content="Your content here...") 4. Named content (prevents duplicates) knowledge.insert(name="recipes-v1", text_content="...") Knowledge vs File Search (step 15): Knowledge (this example): - Local vector DB (ChromaDb, PgVector) - You control embedding, chunking, search - Hybrid search (semantic + keyword) - Best for: production, large datasets, custom logic File Search (step 15): - Fully managed by Google - Automatic chunking and embedding - Built-in citations - Best for: quick prototyping, small datasets """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/17_knowledge.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/18_memory.py
""" Memory + Learning - Agent That Improves Over Time =================================================== The agent learns from interactions so response 1,000 is better than response 1. Key concepts: - LearningMachine: Manages knowledge the agent discovers during conversations - LearningMode.AGENTIC: Agent decides when to save insights (vs ALWAYS or NEVER) - enable_agentic_memory: Builds user profiles from conversation patterns - ReasoningTools: Lets the agent "think" before responding (separate from model thinking) - Two knowledge stores: Static (docs) + dynamic (learned), searched together Example prompts to try: - Session 1: "I'm learning Spanish. I prefer conversations over grammar drills." - Session 2: "Help me practice asking for directions." (agent remembers preferences) """ from pathlib import Path from agno.agent import Agent from agno.knowledge import Knowledge from agno.knowledge.embedder.google import GeminiEmbedder from agno.learn import LearnedKnowledgeConfig, LearningMachine, LearningMode from agno.models.google import Gemini from agno.tools.reasoning import ReasoningTools from agno.vectordb.chroma import ChromaDb, SearchType from db import gemini_agents_db WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Knowledge: Static docs (teaching materials) # --------------------------------------------------------------------------- docs_knowledge = Knowledge( name="Tutor Knowledge", vector_db=ChromaDb( collection="tutor-materials", path=str(WORKSPACE / "chromadb"), persistent_client=True, search_type=SearchType.hybrid, embedder=GeminiEmbedder(), ), contents_db=gemini_agents_db, ) # --------------------------------------------------------------------------- # Knowledge: Dynamic learnings (agent discovers over time) # --------------------------------------------------------------------------- learned_knowledge = Knowledge( vector_db=ChromaDb( collection="tutor-learnings", path=str(WORKSPACE / "chromadb"), persistent_client=True, search_type=SearchType.hybrid, embedder=GeminiEmbedder(), ), contents_db=gemini_agents_db, ) # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a personal language tutor that adapts to each student. ## Workflow 1. Check your learnings and memory for this user's preferences and level 2. Tailor your response to their skill level and learning style 3. Save any new insights about the student for future sessions ## Rules - Adapt difficulty to the student's level - Follow the student's preferred learning style - Track progress and build on previous lessons - Provide corrections gently with explanations\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- tutor_agent = Agent( name="Personal Tutor", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, # ReasoningTools gives the agent a "think" tool for structured reasoning tools=[ReasoningTools()], knowledge=docs_knowledge, search_knowledge=True, learning=LearningMachine( knowledge=learned_knowledge, learned_knowledge=LearnedKnowledgeConfig( # AGENTIC: Agent decides what to save (vs ALWAYS saving everything) mode=LearningMode.AGENTIC, ), ), # Builds user profiles from conversation patterns enable_agentic_memory=True, db=gemini_agents_db, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) # --------------------------------------------------------------------------- # Run Demo # --------------------------------------------------------------------------- if __name__ == "__main__": user_id = "student@example.com" # Session 1: User teaches the agent their preferences print("\n" + "=" * 60) print("SESSION 1: Teaching the agent your preferences") print("=" * 60 + "\n") tutor_agent.print_response( "I'm learning Spanish. I'm at an intermediate level and I prefer " "learning through conversations rather than grammar drills. " "Can you help me practice ordering food at a restaurant?", user_id=user_id, session_id="session_1", stream=True, ) # Show what the agent learned if tutor_agent.learning_machine: print("\n--- Learned Knowledge ---") tutor_agent.learning_machine.learned_knowledge_store.print( query="student preferences" ) # Session 2: New task, agent should apply learned preferences print("\n" + "=" * 60) print("SESSION 2: New task, agent applies learned preferences") print("=" * 60 + "\n") tutor_agent.print_response( "Can you help me practice asking for directions?", user_id=user_id, session_id="session_2", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Learning modes: 1. LearningMode.AGENTIC (this example) Agent decides what to save. Best for production. The agent saves genuinely useful insights, not noise. 2. LearningMode.ALWAYS Save everything. Useful for debugging and development. Can get noisy in production. 3. LearningMode.NEVER Disable learning. Useful for stateless agents. The learning architecture: - Static knowledge: Documents you load (recipes, manuals, docs) - Dynamic knowledge: Insights the agent discovers during conversations - Memory: User profiles built from interaction patterns - All three are searched together when the agent needs context. """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/18_memory.py", "license": "Apache License 2.0", "lines": 145, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/gemini_3/19_team.py
""" Multi-Agent Team - Writer, Editor, and Fact-Checker ===================================================== Coordinate specialized agents with a team leader. Writer drafts, Editor refines, Fact-Checker verifies. Key concepts: - Team: Coordinates multiple agents, each with a specific role - Team leader: An LLM (typically a stronger model) that delegates to members - members: List of Agent instances the team can delegate to - show_members_responses: If True, shows each member's response in the output - role: A short description of what each member agent does (helps the leader delegate) Example prompts to try: - "Write a blog post about the health benefits of Mediterranean diet" - "Create an article about the future of AI in healthcare" - "Write a travel guide for visiting Tokyo in cherry blossom season" """ from agno.agent import Agent from agno.models.google import Gemini from agno.team.team import Team from agno.tools.websearch import WebSearchTools from db import gemini_agents_db # --------------------------------------------------------------------------- # Writer Agent: drafts content # --------------------------------------------------------------------------- writer_instructions = """\ You are a professional content writer. Write engaging, well-structured blog posts. ## Workflow 1. Research the topic using web search 2. Write a compelling draft with clear structure 3. Include an introduction, body sections, and conclusion ## Rules - Use clear, accessible language - Include relevant facts and statistics - Structure with headers and bullet points where appropriate - No emojis\ """ writer = Agent( name="Writer", # role helps the team leader understand what this agent does role="Write engaging blog post drafts", model=Gemini(id="gemini-3-flash-preview"), instructions=writer_instructions, tools=[WebSearchTools()], db=gemini_agents_db, add_datetime_to_context=True, ) # --------------------------------------------------------------------------- # Editor Agent: reviews and improves (no tools, text-only) # --------------------------------------------------------------------------- editor_instructions = """\ You are a senior editor. Review content for quality and suggest improvements. ## Review Checklist - Clarity: Is the message clear and easy to follow? - Structure: Is the content well-organized? - Grammar: Are there any grammatical errors? - Tone: Is the tone consistent and appropriate? - Engagement: Will readers find this interesting? ## Rules - Be specific about what needs improvement - Suggest concrete rewrites, not vague feedback - Acknowledge what works well - No emojis\ """ editor = Agent( name="Editor", role="Review and improve content for clarity and quality", model=Gemini(id="gemini-3-flash-preview"), instructions=editor_instructions, db=gemini_agents_db, add_datetime_to_context=True, ) # --------------------------------------------------------------------------- # Fact-Checker Agent: verifies claims # --------------------------------------------------------------------------- fact_checker_instructions = """\ You are a fact-checker. Verify claims made in the content. ## Workflow 1. Identify all factual claims in the content 2. Search for evidence supporting or contradicting each claim 3. Flag any unverified or incorrect claims 4. Provide corrections with sources ## Rules - Check every statistical claim and date - Provide sources for corrections - Rate confidence: Verified / Unverified / Incorrect - No emojis\ """ fact_checker_member = Agent( name="Fact Checker", role="Verify factual claims using web search", # Uses Gemini's native search for fact-checking model=Gemini(id="gemini-3-flash-preview", search=True), instructions=fact_checker_instructions, db=gemini_agents_db, add_datetime_to_context=True, ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- content_team = Team( name="Content Team", # Team leader uses a stronger model for better delegation decisions model=Gemini(id="gemini-3.1-pro-preview"), members=[writer, editor, fact_checker_member], instructions="""\ You lead a content creation team with a Writer, Editor, and Fact-Checker. ## Process 1. Send the topic to the Writer to create a draft 2. Send the draft to the Editor for review 3. If the Editor finds issues, send back to the Writer to revise 4. Send the final draft to the Fact-Checker to verify claims 5. Synthesize into a final, polished blog post ## Output Format Provide the final blog post followed by: - **Editorial Notes**: Key improvements made during editing - **Fact-Check Summary**: Verification status of key claims\ """, db=gemini_agents_db, # Show each member's response in the output show_members_responses=True, add_datetime_to_context=True, markdown=True, ) # --------------------------------------------------------------------------- # Run Demo # --------------------------------------------------------------------------- if __name__ == "__main__": content_team.print_response( "Write a blog post about the health benefits of Mediterranean diet", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Team patterns: 1. Research team (search + analysis) members=[researcher, analyst, summarizer] 2. Code review team (write + review + test) members=[coder, reviewer, tester] 3. Creative team (ideate + create + critique) members=[brainstormer, creator, critic] When to use teams vs single agents: - Single agent: Task is well-defined, one perspective is enough - Team: Task benefits from multiple specialist perspectives - Workflow (step 20): Steps must happen in a specific, predictable order Use cases for music/film/gaming: - Music: Lyricist + Composer + Producer agents - Film: Scriptwriter + Director + Continuity Checker agents - Gaming: Designer + Artist + QA Tester agents """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/19_team.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/1_basic.py
""" Basic Agent - Your First Gemini Agent ======================================= Simple Agno agent with Gemini 3 Flash. Key concepts: - Agent: The core building block in Agno wraps a model with instructions - print_response: Runs the agent and prints formatted output - stream=True: Streams tokens as they arrive instead of waiting for the full response - Sync vs async: Every Agno method has an async variant (aprint_response, arun, etc.) Example prompts to try: - "What are the top 3 things to see in Paris?" - "Explain quantum computing in simple terms" - "Write a haiku about programming" """ import asyncio from agno.agent import Agent from agno.models.google import Gemini # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- chat_agent = Agent( name="Chat Assistant", model=Gemini(id="gemini-3-flash-preview"), # markdown=True renders rich formatting in the terminal markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # --- Sync --- # chat_agent.print_response("What are the top 3 things to see in Paris?") # --- Sync + Streaming --- # chat_agent.print_response( # "What are the top 3 things to see in Paris?", stream=True # ) # --- Async --- # asyncio.run( # chat_agent.aprint_response("What are the top 3 things to see in Paris?") # ) # --- Async + Streaming --- asyncio.run( chat_agent.aprint_response( "What are the top 3 things to see in Paris?", stream=True ) ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Agno supports four execution modes for every agent: 1. Sync (blocking) agent.print_response("prompt") response = agent.run("prompt") 2. Sync + Streaming (tokens arrive as they're generated) agent.print_response("prompt", stream=True) for chunk in agent.run("prompt", stream=True): print(chunk.content, end="") 3. Async (non-blocking) await agent.aprint_response("prompt") response = await agent.arun("prompt") 4. Async + Streaming await agent.aprint_response("prompt", stream=True) async for chunk in await agent.arun("prompt", stream=True): print(chunk.content, end="") All examples in this guide use sync for simplicity. For production apps, use async (see cookbook/02_agents/ for patterns). """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/1_basic.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/20_workflow.py
""" Workflow - Step-Based Agentic Pipeline ======================================== Build a multi-step pipeline where steps execute in a defined order. Key concepts: - Workflow: Orchestrates steps in sequence, with branching and parallelism - Step: A single unit of work, backed by an Agent, Team, or custom function - Parallel: Run multiple steps concurrently - Condition: Branch based on previous step output - StepInput: Carries the original input + all previous step outputs - StepOutput: What a step returns (content, stop flag, success flag) - session_state: Persistent state across steps (saved to db) Example prompts to try: - "Latest developments in AI agents and autonomous systems" - "The impact of climate change on global food production" - "History and future of space exploration" """ from agno.agent import Agent from agno.models.google import Gemini from agno.tools.websearch import WebSearchTools from agno.workflow import ( Condition, Parallel, Step, StepInput, StepOutput, Workflow, ) from db import gemini_agents_db # --------------------------------------------------------------------------- # Agents: each handles one stage of the pipeline # --------------------------------------------------------------------------- web_researcher = Agent( name="Web Researcher", model=Gemini(id="gemini-3-flash-preview", search=True), instructions="""\ You are a web researcher. Search for the latest information on the given topic. ## Rules - Find recent, credible sources - Include key facts, statistics, and expert opinions - Cite your sources - No emojis\ """, add_datetime_to_context=True, ) deep_researcher = Agent( name="Deep Researcher", model=Gemini(id="gemini-3-flash-preview"), tools=[WebSearchTools()], instructions="""\ You are a deep researcher. Search extensively for background context, historical data, and expert analysis on the given topic. ## Rules - Go beyond surface-level information - Find contrasting viewpoints - Include historical context and trends - No emojis\ """, add_datetime_to_context=True, ) analyst = Agent( name="Analyst", model=Gemini(id="gemini-3.1-pro-preview"), instructions="""\ You are a senior analyst. Synthesize research from multiple sources into a clear, structured analysis. ## Rules - Identify key themes and patterns across sources - Highlight areas of agreement and disagreement - Draw evidence-based conclusions - Structure with clear sections and headers - No emojis\ """, ) report_writer = Agent( name="Report Writer", model=Gemini(id="gemini-3.1-pro-preview"), instructions="""\ You are a report writer. Transform analysis into a polished, publication-ready report. ## Rules - Write a compelling introduction that hooks the reader - Use clear, accessible language - Include an executive summary at the top - End with key takeaways and future outlook - No emojis\ """, ) fact_checker = Agent( name="Fact Checker", model=Gemini(id="gemini-3-flash-preview", search=True), instructions="""\ You are a fact-checker. Verify the factual claims in the report. ## Rules - Check every statistic, date, and named claim - Search for primary sources - Flag anything unverified as [UNVERIFIED] - Provide the corrected report with a verification summary at the end - No emojis\ """, ) # --------------------------------------------------------------------------- # Custom step functions # --------------------------------------------------------------------------- def quality_gate(step_input: StepInput) -> StepOutput: """Check that the analysis has enough substance to proceed.""" content = str(step_input.previous_step_content or "") if len(content) < 200: return StepOutput( content="Quality gate failed: analysis too short. Stopping pipeline.", stop=True, success=False, ) return StepOutput( content=content, success=True, ) def needs_fact_check(step_input: StepInput) -> bool: """Decide whether the report needs fact-checking.""" content = str(step_input.previous_step_content or "").lower() indicators = [ "study", "research", "percent", "%", "million", "billion", "according", ] return any(indicator in content for indicator in indicators) # --------------------------------------------------------------------------- # Build Workflow # --------------------------------------------------------------------------- research_pipeline = Workflow( id="gemini-research-pipeline", name="Research Pipeline", description="Research-to-publication pipeline: parallel research, analysis, quality gate, writing, and conditional fact-checking.", db=gemini_agents_db, steps=[ # Step 1: Research in parallel (two agents search simultaneously) Parallel( "Research", Step(name="web_research", agent=web_researcher), Step(name="deep_research", agent=deep_researcher), ), # Step 2: Analyst synthesizes all research Step(name="analysis", agent=analyst), # Step 3: Quality gate (stop early if analysis is too thin) Step(name="quality_gate", executor=quality_gate), # Step 4: Writer produces the final report Step(name="report", agent=report_writer), # Step 5: Conditionally fact-check (only if the report has factual claims) Condition( name="fact_check_gate", evaluator=needs_fact_check, steps=[Step(name="fact_check", agent=fact_checker)], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": research_pipeline.print_response( "Latest developments in AI agents and autonomous systems", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Workflow vs Team: - Team (step 19): Leader LLM decides who to delegate to at runtime. Flexible but less predictable. Best for creative, open-ended tasks. - Workflow (this step): Steps execute in a defined order with explicit branching logic. Predictable and repeatable. Best for pipelines. Workflow building blocks: 1. Step(agent=...) Run an agent 2. Step(team=...) Run a team 3. Step(executor=fn) Run a custom function 4. Parallel(step1, step2) Run steps concurrently 5. Condition(evaluator, ...) Branch based on logic 6. Loop(steps, ...) Repeat until done 7. Router(choices, selector) Dynamically pick which step to run Accessing previous step outputs in a custom executor: def my_step(step_input: StepInput) -> StepOutput: # Original workflow input original = step_input.input # Output from the immediately preceding step last = step_input.previous_step_content # Output from a specific named step research = step_input.get_step_content("web_research") # All previous outputs concatenated everything = step_input.get_all_previous_content() return StepOutput(content="done") Early stopping from any step: return StepOutput(content="Stopping.", stop=True) """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/20_workflow.py", "license": "Apache License 2.0", "lines": 198, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/21_agent_os.py
""" Agent OS - Deploy All Agents as a Web Service =============================================== Deploy all agents, teams, and workflows from this guide as a single web service. How to use: 1. Start the server: python cookbook/gemini_3/21_agent_os.py 2. Visit https://os.agno.com in your browser 3. Add your local endpoint: http://localhost:7777 4. Select any agent, team, or workflow and start chatting Key concepts: - AgentOS: Wraps agents, teams, and workflows into a FastAPI web service - get_app(): Returns a FastAPI app you can customize - serve(): Starts the server with uvicorn (hot-reload enabled) - tracing=True: Enables request tracing in the Agent OS UI Prerequisites: - GOOGLE_API_KEY environment variable set """ import importlib import sys from pathlib import Path from agno.os import AgentOS from db import gemini_agents_db # Numbered filenames need importlib since Python can't import modules starting with digits sys.path.insert(0, str(Path(__file__).parent)) def _import(module_name: str, attr: str): return getattr(importlib.import_module(module_name), attr) chat_agent = _import("1_basic", "chat_agent") finance_agent = _import("2_tools", "finance_agent") critic_agent = _import("3_structured_output", "critic_agent") news_agent = _import("4_search", "news_agent") url_agent = _import("6_url_context", "url_agent") image_agent = _import("8_image_input", "image_agent") doc_reader = _import("13_pdf_input", "doc_reader") recipe_agent = _import("17_knowledge", "recipe_agent") tutor_agent = _import("18_memory", "tutor_agent") content_team = _import("19_team", "content_team") research_pipeline = _import("20_workflow", "research_pipeline") agent_os = AgentOS( id="gemini-agent-os", agents=[ chat_agent, finance_agent, critic_agent, news_agent, url_agent, image_agent, doc_reader, recipe_agent, tutor_agent, ], teams=[content_team], workflows=[research_pipeline], db=gemini_agents_db, tracing=True, ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="21_agent_os:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/21_agent_os.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/gemini_3/2_tools.py
""" Agent with Tools - Finance Research Agent ========================================== Give an agent tools to search the web and take real-world actions. Key concepts: - tools: A list of Toolkit instances the agent can call - instructions: System-level guidance that shapes the agent's behavior - add_datetime_to_context: Injects the current date/time so the agent knows "today" - WebSearchTools: Built-in toolkit for web search via DuckDuckGo (no API key needed) Example prompts to try: - "Compare the latest funding rounds in AI startups this month" - "What's happening with interest rates this week?" - "Find the latest news about Nvidia's earnings" - "What are the top tech IPOs planned for this quarter?" """ from agno.agent import Agent from agno.models.google import Gemini from agno.tools.websearch import WebSearchTools # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a finance research agent. You find and analyze current financial news. ## Workflow 1. Search the web for the requested financial information 2. Analyze and compare findings 3. Present a clear, structured summary ## Rules - Always cite your sources - Use tables for comparisons - Include dates for all data points\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- finance_agent = Agent( name="Finance Agent", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, tools=[WebSearchTools()], # Adds current date/time to the system message so the agent knows "today" add_datetime_to_context=True, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": finance_agent.print_response( "Compare the latest funding rounds in AI startups this month", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Tools are Python classes that inherit from Toolkit. Agno includes many built-in: 1. Web search (no API key needed) from agno.tools.websearch import WebSearchTools tools=[WebSearchTools()] 2. Yahoo Finance (real market data) from agno.tools.yfinance import YFinanceTools tools=[YFinanceTools(all=True)] 3. Exa search (semantic search, needs EXA_API_KEY) from agno.tools.exa import ExaTools tools=[ExaTools()] 4. Custom tools @tool def my_tool(query: str) -> str: return "result" You can combine multiple toolkits: tools=[WebSearchTools(), YFinanceTools(all=True)] The agent decides which tool to call based on the prompt. """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/2_tools.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/3_structured_output.py
""" Structured Output - Movie Critic with Typed Responses ======================================================= Get typed Pydantic responses instead of free-form text. Key concepts: - output_schema: A Pydantic BaseModel defining the response structure - response.content: The parsed Pydantic object (not a string) - agent.run(): Returns a RunOutput with .content as your typed object - Field(..., description=...): Descriptions guide the model on what to put in each field Example prompts to try: - "Review the movie Inception" - "Review The Shawshank Redemption" - "Review a recent sci-fi film" """ from typing import List from agno.agent import Agent from agno.models.google import Gemini from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Output Schema # --------------------------------------------------------------------------- class MovieReview(BaseModel): title: str = Field(..., description="Movie title") year: int = Field(..., description="Release year") rating: float = Field(..., ge=0, le=10, description="Rating out of 10") genre: str = Field(..., description="Primary genre") pros: List[str] = Field(..., description="What works well") cons: List[str] = Field(..., description="What could be better") verdict: str = Field(..., description="One-sentence final verdict") # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- critic_agent = Agent( name="Movie Critic", model=Gemini(id="gemini-3.1-pro-preview"), instructions="You are a professional movie critic. Provide balanced, thoughtful reviews.", # output_schema forces the agent to return a MovieReview, not free text output_schema=MovieReview, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # agent.run() returns RunOutput; .content is the parsed Pydantic object run = critic_agent.run("Review the movie Inception") review: MovieReview = run.content print(f"Title: {review.title} ({review.year})") print(f"Rating: {review.rating}/10") print(f"Genre: {review.genre}") print("\nPros:") for pro in review.pros: print(f" - {pro}") print("\nCons:") for con in review.cons: print(f" - {con}") print(f"\nVerdict: {review.verdict}") # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Structured output is perfect for: 1. Building UIs review = agent.run("Review Inception").content render_movie_card(review) 2. Storing in databases db.insert("reviews", review.model_dump()) 3. Comparing items inception = agent.run("Review Inception").content tenet = agent.run("Review Tenet").content if inception.rating > tenet.rating: print(f"{inception.title} wins") 4. Building pipelines movies = ["Inception", "Tenet", "Interstellar"] reviews = [agent.run(f"Review {m}").content for m in movies] The schema guarantees you always get the fields you expect. No parsing, no surprises. """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/3_structured_output.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/4_search.py
""" Gemini Native Search - Real-Time News Agent ============================================= Use Gemini's built-in Google Search. Just set search=True on the model. Key concepts: - search=True: Enables native Google Search on the Gemini model - No extra dependencies: Unlike WebSearchTools (step 2), nothing to install - Native search is seamless but less controllable than tool-based search Example prompts to try: - "What are the latest developments in AI this week?" - "What happened in the stock market today?" - "What are the top trending tech stories right now?" """ from agno.agent import Agent from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a news analyst. Summarize the latest developments clearly and concisely. ## Rules - Lead with the most important story - Include dates for all events - Cite sources when possible - Use bullet points for multiple items\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- news_agent = Agent( name="News Agent", # search=True enables Gemini's native Google Search, no extra tools needed model=Gemini(id="gemini-3-flash-preview", search=True), instructions=instructions, add_datetime_to_context=True, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": news_agent.print_response( "What are the latest developments in AI this week?", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Native search vs tool-based search: 1. Native search (this example) model=Gemini(id="gemini-3-flash-preview", search=True) - Seamless: model decides when to search - Less controllable: you can't see individual search calls - No extra packages needed 2. Tool-based search (step 2) tools=[WebSearchTools()] - Explicit: agent calls search as a tool - More controllable: you can see search queries in tool calls - Works with any model, not just Gemini 3. Grounding (step 5) model=Gemini(id="...", grounding=True) - Fact-based: responses include citations - Verifiable: grounding metadata shows sources - Best for factual accuracy Choose based on your needs: - Quick current info → Native search - Full control over search → Tool-based - Cited, verifiable facts → Grounding """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/4_search.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/6_url_context.py
""" URL Context - Read and Compare Web Pages ========================================== Fetch and read web pages natively. Just set url_context=True on the model. Key concepts: - url_context=True: Enables Gemini to fetch and read URLs from the prompt - Native capability: The model handles HTTP requests internally - No extra tools: Unlike web scraping, this needs no additional packages - Best with Pro: URL context works better with Gemini Pro models Example prompts to try: - "Compare the recipes at these two URLs" - "Summarize the key points from this article: <URL>" - "What are the differences between these two product pages?" """ from agno.agent import Agent from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a comparison expert. Analyze content from URLs and provide clear, structured comparisons. ## Rules - Read all provided URLs thoroughly - Use tables for side-by-side comparisons - Highlight key differences and similarities - Be specific, cite details from each source """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- url_agent = Agent( name="URL Context Agent", # url_context=True lets Gemini fetch and read URLs from the prompt model=Gemini(id="gemini-3.1-pro-preview", url_context=True), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": url1 = "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592" url2 = "https://www.allrecipes.com/recipe/83557/juicy-roasted-chicken/" url_agent.print_response( f"Compare the ingredients and cooking times from the recipes at {url1} and {url2}", stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ URL context use cases: 1. Compare two articles "Compare the arguments in <url1> vs <url2>" 2. Summarize a long page "Summarize the key takeaways from <url>" 3. Extract structured data from a page agent = Agent(model=Gemini(id="...", url_context=True), output_schema=MySchema) result = agent.run("Extract product details from <url>") 4. Research across multiple sources "What do these 3 articles say about <topic>? <url1> <url2> <url3>" Note: URL context reads the page content at request time. The model does not cache pages between requests. """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/6_url_context.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/7_thinking.py
""" Extended Thinking - Complex Reasoning with Budget Control ========================================================== Let Gemini "think" before responding for better answers on complex tasks. Key concepts: - thinking_budget: Token budget for thinking (0=disable, -1=dynamic, or a number) - include_thoughts: If True, the model's reasoning is included in the response - Best with Pro: Thinking is most effective with Gemini Pro models - Trade-off: More thinking = better answers but higher latency and cost Example prompts to try: - "Solve the missionaries and cannibals river-crossing puzzle" - "What is 127 * 389 + 256 * 741? Show your work." - "Write a Python function to find all prime factors of a number. Think through edge cases." """ from agno.agent import Agent from agno.models.google import Gemini # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- thinking_agent = Agent( name="Thinking Agent", model=Gemini( id="gemini-3.1-pro-preview", # Token budget for internal reasoning (higher = deeper thinking) thinking_budget=1280, # Show the model's chain of thought in the response include_thoughts=True, ), markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": task = ( "Three missionaries and three cannibals need to cross a river. " "They have a boat that can carry up to two people at a time. " "If, at any time, the cannibals outnumber the missionaries on either " "side of the river, the cannibals will eat the missionaries. " "How can all six people get across the river safely? " "Provide a step-by-step solution and show the solution as an ascii diagram." ) thinking_agent.print_response(task, stream=True) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Thinking budget guidelines: - thinking_budget=0: Disable thinking (fastest, cheapest) - thinking_budget=256: Light reasoning (simple math, basic logic) - thinking_budget=1024: Moderate reasoning (multi-step problems) - thinking_budget=2048: Deep reasoning (complex puzzles, proofs) - thinking_budget=-1: Dynamic (model decides how much to think) When to use thinking: - Math and logic puzzles - Code generation with edge cases - Multi-step planning - Analysis requiring chain-of-thought When NOT to use thinking: - Simple Q&A (adds unnecessary latency) - Creative writing (thinking doesn't help much) - Summarization (straightforward task) """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/7_thinking.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/8_image_input.py
""" Image Understanding - Analyze and Describe Images =================================================== Pass images to Gemini via URL or local file for analysis, description, and Q&A. Key concepts: - Image(url=...): Pass an image from a URL - Image(filepath=...): Pass a local image file - images=[...]: List of Image objects passed to print_response/run - Combine with search: Add search=True to get context about what's in the image Example prompts to try: - "Describe this image in detail" - "What text can you see in this image?" - "Tell me about this image and give me the latest news about it." - "What architectural style is this building?" """ from agno.agent import Agent from agno.media import Image from agno.models.google import Gemini # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are an image analysis expert. Describe what you see in detail and provide relevant context. ## Rules - Describe the main subject first, then details - Note any text visible in the image - Provide historical or cultural context when relevant\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- image_agent = Agent( name="Image Analyst", # search=True lets the agent look up context about what it sees model=Gemini(id="gemini-3-flash-preview", search=True), instructions=instructions, markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": image_agent.print_response( "Tell me about this image and give me the latest news about it.", images=[ Image( url="https://agno-public.s3.amazonaws.com/images/krakow_mariacki.jpg" ), ], stream=True, ) # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Image input methods: 1. From URL images=[Image(url="https://example.com/photo.jpg")] 2. From local file images=[Image(filepath="path/to/photo.jpg")] 3. Multiple images images=[Image(url="..."), Image(filepath="...")] 4. With structured output (extract data from images) class ImageData(BaseModel): objects: List[str] text_content: str mood: str agent = Agent(model=Gemini(...), output_schema=ImageData) result = agent.run("Analyze this image", images=[...]) data: ImageData = result.content Use cases for music/film/gaming: - Analyze album artwork or movie posters - Extract text from game screenshots - Describe scene composition for storyboards """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/8_image_input.py", "license": "Apache License 2.0", "lines": 76, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/9_image_generation.py
""" Image Generation and Editing - Create and Modify Images ========================================================= Generate and edit images natively with Gemini. No external tools needed. Key concepts: - response_modalities=["Text", "Image"]: Tells Gemini to output both text and images - RunOutput.images: Access generated images from the response - Image editing: Pass an existing image + instructions to modify it - No system message: Image generation does not support system instructions Example prompts to try: - "Make me an image of a cat sitting in a tree" - "Create a minimalist logo for a coffee shop called 'Bean Scene'" - "Generate a fantasy landscape with mountains and a castle" """ from io import BytesIO from pathlib import Path from agno.agent import Agent, RunOutput from agno.media import Image from agno.models.google import Gemini WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Create Agent (no system message, required for image generation) # --------------------------------------------------------------------------- image_gen_agent = Agent( name="Image Generator", model=Gemini( id="gemini-3.1-flash-image-preview", # Enable both text and image output response_modalities=["Text", "Image"], ), ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": try: from PIL import Image as PILImage except ImportError: raise ImportError("Install Pillow to run this example: pip install Pillow") # --- Generate an image --- print("Generating an image...") run_response = image_gen_agent.run("Make me an image of a cat sitting in a tree.") if run_response and isinstance(run_response, RunOutput) and run_response.images: for i, image_response in enumerate(run_response.images): image_bytes = image_response.content if image_bytes: image = PILImage.open(BytesIO(image_bytes)) output_path = WORKSPACE / f"generated_{i}.png" image.save(str(output_path)) print(f"Saved generated image to {output_path}") else: print("No images found in response") # --- Edit an existing image --- print("\nEditing the generated image...") generated_path = WORKSPACE / "generated_0.png" if generated_path.exists(): edit_response = image_gen_agent.run( "Add a rainbow in the sky of this image.", images=[Image(filepath=str(generated_path))], ) if ( edit_response and isinstance(edit_response, RunOutput) and edit_response.images ): for i, image_response in enumerate(edit_response.images): image_bytes = image_response.content if image_bytes: image = PILImage.open(BytesIO(image_bytes)) output_path = WORKSPACE / f"edited_{i}.png" image.save(str(output_path)) print(f"Saved edited image to {output_path}") else: print("No edited images found in response") # --------------------------------------------------------------------------- # More Examples # --------------------------------------------------------------------------- """ Image generation tips: 1. Be specific in prompts "A watercolor painting of a sunset over the ocean with warm orange tones" is better than "sunset painting" 2. Image editing workflow # Generate result = agent.run("Create a logo for a tech startup") # Edit result = agent.run("Make the colors more vibrant", images=[...]) # Iterate result = agent.run("Add the text 'ACME' below the logo", images=[...]) 3. No system message allowed Image generation models don't support instructions=... on the agent. Put guidance directly in the prompt instead. Use cases for music/film/gaming: - Generate album cover concepts from descriptions - Create character concept art for games - Produce storyboard frames from scene descriptions - Design promotional materials and posters """
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/9_image_generation.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/gemini_3/db.py
from pathlib import Path from agno.db.sqlite import SqliteDb WORKSPACE = Path(__file__).parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) gemini_agents_db = SqliteDb(db_file=str(WORKSPACE / "gemini_agents.db"))
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/db.py", "license": "Apache License 2.0", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/gemini_3/use_cases/film_scene_breakdown.py
""" Film Scene Breakdown - Analyze a Clip and Script with a Team ============================================================== Combines video analysis, PDF reading, and a multi-agent team for film production. Steps used: 12 (Video), 13 (PDF), 19 (Team) Run: python cookbook/gemini_3/use_cases/film_scene_breakdown.py """ import httpx from agno.agent import Agent from agno.media import File, Video from agno.models.google import Gemini from agno.team.team import Team # --------------------------------------------------------------------------- # Video Analyst: watches and describes the clip # --------------------------------------------------------------------------- video_analyst = Agent( name="Video Analyst", role="Analyze video clips for visual content, pacing, and mood", model=Gemini(id="gemini-3-flash-preview"), instructions="""\ You are a film analysis expert. Watch video clips and provide detailed breakdowns. ## Describe - Shot types (wide, close-up, tracking, etc.) - Scene transitions and pacing - Lighting, color grading, and visual mood - Character actions and expressions - Any text, titles, or graphics on screen ## Rules - Use professional film terminology - Describe chronologically - Note timestamps for key moments - No emojis\ """, markdown=True, ) # --------------------------------------------------------------------------- # Script Reader: extracts relevant content from the script PDF # --------------------------------------------------------------------------- script_reader = Agent( name="Script Reader", role="Read film scripts and extract relevant dialogue and directions", model=Gemini(id="gemini-3-flash-preview"), instructions="""\ You are a script supervisor. Read scripts and extract relevant information. ## Extract - Scene headings (INT/EXT, location, time of day) - Character dialogue - Stage directions and action lines - Camera directions if specified ## Rules - Maintain script formatting conventions - Note page numbers for reference - Flag any ambiguous directions - No emojis\ """, markdown=True, ) # --------------------------------------------------------------------------- # Continuity Editor: checks consistency # --------------------------------------------------------------------------- continuity_editor = Agent( name="Continuity Editor", role="Check consistency between script and footage", model=Gemini(id="gemini-3-flash-preview"), instructions="""\ You are a continuity editor. Compare the script to the footage and flag issues. ## Check - Does the footage match the script's described action? - Are dialogue lines delivered as written? - Are props, costumes, and set dressing consistent? - Does the lighting match the script's time-of-day? ## Rules - Be specific about discrepancies - Rate severity: Minor / Notable / Critical - Suggest solutions for any issues found - No emojis\ """, markdown=True, ) # --------------------------------------------------------------------------- # Team # --------------------------------------------------------------------------- production_team = Team( name="Production Team", model=Gemini(id="gemini-3.1-pro-preview"), members=[video_analyst, script_reader, continuity_editor], instructions="""\ You lead a film production team with a Video Analyst, Script Reader, and Continuity Editor. ## Process 1. Send the video clip to the Video Analyst for visual breakdown 2. Send the script PDF to the Script Reader for dialogue and direction extraction 3. Send both analyses to the Continuity Editor for consistency check 4. Synthesize into a final scene breakdown ## Output Format Provide a scene breakdown with: - **Visual Summary**: Key shots and visual elements - **Script Notes**: Relevant dialogue and directions - **Continuity Report**: Any discrepancies found - **Production Notes**: Recommendations for the edit\ """, show_members_responses=True, markdown=True, ) # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": # Sample: analyze a video clip against a script PDF # Replace these with your own video and script URLs video_url = "https://agno-public.s3.amazonaws.com/demo/sample_seaview.mp4" script_url = "https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf" print("Downloading video sample...") video_response = httpx.get(video_url) print("Running production team analysis...\n") production_team.print_response( "Analyze this video clip and compare it against the provided document. " "Produce a scene breakdown with visual analysis, script notes, " "and a continuity report.", videos=[Video(content=video_response.content, format="mp4")], files=[File(url=script_url)], stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/use_cases/film_scene_breakdown.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:cookbook/gemini_3/use_cases/game_concept_pitch.py
""" Game Concept Pitch - Generate Art and Structure a Pitch ========================================================= Combines image generation, structured output, and a multi-agent team for a game pitch. Steps used: 3 (Structured Output), 9 (Image Generation), 19 (Team) Run: python cookbook/gemini_3/use_cases/game_concept_pitch.py """ from io import BytesIO from pathlib import Path from typing import List from agno.agent import Agent, RunOutput from agno.models.google import Gemini from agno.team.team import Team from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Workspace # --------------------------------------------------------------------------- WORKSPACE = Path(__file__).parent.parent.joinpath("workspace") WORKSPACE.mkdir(parents=True, exist_ok=True) # --------------------------------------------------------------------------- # Output Schema for Game Pitch # --------------------------------------------------------------------------- class GamePitch(BaseModel): title: str = Field(..., description="Game title") tagline: str = Field(..., description="One-line hook (max 15 words)") genre: str = Field( ..., description="Primary genre (e.g., action RPG, puzzle platformer)" ) platform: List[str] = Field(..., description="Target platforms") target_audience: str = Field(..., description="Target demographic") core_mechanic: str = Field(..., description="The one thing that makes the game fun") setting: str = Field( ..., description="World and setting description (2-3 sentences)" ) unique_selling_points: List[str] = Field( ..., description="3-5 unique selling points" ) comparable_titles: List[str] = Field(..., description="2-3 comparable games") monetization: str = Field(..., description="Monetization strategy") elevator_pitch: str = Field(..., description="Full elevator pitch (one paragraph)") # --------------------------------------------------------------------------- # Concept Art Agent (image generation) # --------------------------------------------------------------------------- art_agent = Agent( name="Concept Artist", model=Gemini( id="gemini-3-flash-preview", response_modalities=["Text", "Image"], ), ) # --------------------------------------------------------------------------- # Pitch Writer Agent (structured output) # --------------------------------------------------------------------------- pitch_writer = Agent( name="Pitch Writer", role="Write structured game concept pitches", model=Gemini(id="gemini-3.1-pro-preview"), instructions="""\ You are a game design consultant. Create compelling, structured game pitches. ## Rules - Be specific about mechanics, not vague - Comparable titles should be recent (last 3 years) - Monetization must be realistic for the genre - The tagline should make someone want to hear more - No emojis\ """, output_schema=GamePitch, add_datetime_to_context=True, ) # --------------------------------------------------------------------------- # Review Team # --------------------------------------------------------------------------- market_analyst = Agent( name="Market Analyst", role="Evaluate market viability and competitive landscape", model=Gemini(id="gemini-3-flash-preview", search=True), instructions="""\ You analyze game market trends. Evaluate pitches for market viability. ## Evaluate - Is there market demand for this genre? - How crowded is the competitive space? - Is the monetization realistic? - What's the risk/reward profile? ## Rules - Use recent market data - Be honest about risks - Suggest specific improvements - No emojis\ """, add_datetime_to_context=True, ) creative_director = Agent( name="Creative Director", role="Evaluate creative vision and player experience", model=Gemini(id="gemini-3-flash-preview"), instructions="""\ You evaluate game concepts for creative quality and player appeal. ## Evaluate - Is the core mechanic fun and original? - Does the setting support the gameplay? - Will the target audience connect with this? - What's the "wow factor"? ## Rules - Focus on player experience - Suggest improvements, not just criticism - Consider accessibility - No emojis\ """, ) review_team = Team( name="Review Board", model=Gemini(id="gemini-3.1-pro-preview"), members=[market_analyst, creative_director], instructions="""\ You chair a game pitch review board with a Market Analyst and Creative Director. ## Process 1. Send the pitch to the Market Analyst for viability assessment 2. Send the pitch to the Creative Director for creative evaluation 3. Synthesize into a final review with: - **Market Assessment**: Viability and competitive analysis - **Creative Review**: Strengths and areas for improvement - **Final Verdict**: Go / Revise / Pass with reasoning\ """, show_members_responses=True, markdown=True, ) # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": game_idea = ( "A cozy underwater exploration game where you play as a marine biologist " "discovering and cataloging bioluminescent deep-sea creatures. " "The core loop is diving, photographing creatures, and building " "a living encyclopedia that other players can browse." ) # Step 1: Generate concept art print("Generating concept art...\n") art_result = art_agent.run( f"Create concept art for this game: {game_idea}. " "Show a diver exploring a bioluminescent underwater cave with glowing creatures." ) if art_result and isinstance(art_result, RunOutput) and art_result.images: try: from PIL import Image as PILImage for i, img in enumerate(art_result.images): if img.content: image = PILImage.open(BytesIO(img.content)) path = WORKSPACE / f"game_concept_{i}.png" image.save(str(path)) print(f"Saved concept art to {path}") except ImportError: print("Install Pillow to save images: pip install Pillow") # Step 2: Structure the pitch print("\nWriting game pitch...\n") pitch_result = pitch_writer.run(f"Create a structured game pitch for: {game_idea}") pitch: GamePitch = pitch_result.content print(f"Title: {pitch.title}") print(f"Tagline: {pitch.tagline}") print(f"Genre: {pitch.genre}") print(f"Core Mechanic: {pitch.core_mechanic}") print(f"\nElevator Pitch: {pitch.elevator_pitch}") # Step 3: Review the pitch print("\n\nRunning review board...\n") review_team.print_response( f"Review this game pitch:\n\n" f"Title: {pitch.title}\n" f"Genre: {pitch.genre}\n" f"Platforms: {', '.join(pitch.platform)}\n" f"Target Audience: {pitch.target_audience}\n" f"Core Mechanic: {pitch.core_mechanic}\n" f"Setting: {pitch.setting}\n" f"USPs: {', '.join(pitch.unique_selling_points)}\n" f"Comparable Titles: {', '.join(pitch.comparable_titles)}\n" f"Monetization: {pitch.monetization}\n" f"Elevator Pitch: {pitch.elevator_pitch}", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/use_cases/game_concept_pitch.py", "license": "Apache License 2.0", "lines": 179, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/gemini_3/use_cases/music_asset_brief.py
""" Music Asset Brief - Analyze a Track and Produce a Brief ========================================================= Combines audio analysis, image understanding, web search, and structured output for a music brief. Steps used: 2 (Tools), 3 (Structured Output), 8 (Image), 10 (Audio) Run: python cookbook/gemini_3/use_cases/music_asset_brief.py """ from typing import List import httpx from agno.agent import Agent from agno.media import Audio, Image from agno.models.google import Gemini from agno.tools.websearch import WebSearchTools from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Output Schema # --------------------------------------------------------------------------- class TrackBrief(BaseModel): track_name: str = Field(..., description="Name of the track") artist: str = Field(..., description="Artist or band name") genre: str = Field(..., description="Primary genre") mood: str = Field(..., description="Overall mood (e.g., energetic, melancholic)") tempo_estimate: str = Field(..., description="Estimated tempo (slow, mid, fast)") visual_style: str = Field(..., description="Visual style of the artwork") target_audience: str = Field(..., description="Suggested target audience") marketing_angles: List[str] = Field(..., description="3-5 marketing angles") comparable_artists: List[str] = Field(..., description="2-3 comparable artists") summary: str = Field(..., description="One-paragraph executive summary") # --------------------------------------------------------------------------- # Agent Instructions # --------------------------------------------------------------------------- instructions = """\ You are a music industry analyst. You analyze tracks, artwork, and market context to produce comprehensive asset briefs for A&R and marketing teams. ## Workflow 1. If audio is provided, analyze the track: genre, mood, tempo, production style 2. If an image is provided, analyze the artwork: visual style, themes, color palette 3. Search the web for the artist and current market context 4. Produce a structured brief combining all insights ## Rules - Be specific about genre (not just "pop", say "synth-pop" or "indie pop") - Name comparable artists that are currently relevant - Marketing angles should be actionable - No emojis\ """ # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- music_analyst = Agent( name="Music Analyst", model=Gemini(id="gemini-3-flash-preview"), instructions=instructions, tools=[WebSearchTools()], output_schema=TrackBrief, add_datetime_to_context=True, ) # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": # Sample: analyze a track with audio and artwork # Replace these with your own audio URL and artwork URL audio_url = "https://agno-public.s3.amazonaws.com/demo/sample-audio.mp3" artwork_url = "https://agno-public.s3.amazonaws.com/images/krakow_mariacki.jpg" print("Downloading audio sample...") audio_response = httpx.get(audio_url) print("Analyzing track and artwork...\n") result = music_analyst.run( "Analyze this music track and album artwork. " "Research the artist and produce a comprehensive asset brief.", audio=[Audio(content=audio_response.content, format="mp3")], images=[Image(url=artwork_url)], ) brief: TrackBrief = result.content print(f"Track: {brief.track_name} by {brief.artist}") print(f"Genre: {brief.genre} | Mood: {brief.mood} | Tempo: {brief.tempo_estimate}") print(f"Visual Style: {brief.visual_style}") print(f"Target Audience: {brief.target_audience}") print("\nMarketing Angles:") for angle in brief.marketing_angles: print(f" - {angle}") print(f"\nComparable Artists: {', '.join(brief.comparable_artists)}") print(f"\nSummary: {brief.summary}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/gemini_3/use_cases/music_asset_brief.py", "license": "Apache License 2.0", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/93_components/workflows/registry_agents_in_workflow.py
""" Cookbook: Code-defined agents available to UI-built workflows. This sets up an AgentOS with code-defined agents. When a user builds a workflow through the UI: 1. The UI fetches available agents from /registry (code-defined) and /components (DB-stored) to populate the step agent dropdown. 2. The user selects a code-defined agent (e.g. "research-agent") for a step. 3. The workflow is saved to DB with just the agent_id reference. 4. When the workflow is loaded back, Step.from_dict() resolves the agent from the Registry first, falling back to DB only if not found. The agents below are never saved to the database -- they live in memory via the Registry, which AgentOS auto-populates on startup. Important: Code-defined agents MUST have explicit, stable `id` values. The UI stores these IDs in the workflow config. If the ID changes between restarts, the workflow will fail to resolve the agent. """ from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from agno.os import AgentOS db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" db = PostgresDb(db_url=db_url) # Code-defined agents with stable IDs. # These appear in the UI workflow builder via the /registry endpoint. # They are NOT saved to the database. research_agent = Agent( id="research-agent", name="Research Agent", model=OpenAIChat(id="gpt-4o-mini"), role="Research topics and extract key insights", ) writer_agent = Agent( id="writer-agent", name="Writer Agent", model=OpenAIChat(id="gpt-4o-mini"), role="Write content based on research", ) # AgentOS auto-populates its registry with these agents. # The /registry?resource_type=agent endpoint exposes them to the UI. # Workflows built in the UI that reference these agents by ID will # resolve them from the registry when loaded from DB. agent_os = AgentOS( description="Demo: code-defined agents available to UI workflow builder", db=db, agents=[research_agent, writer_agent], ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="registry_agents_in_workflow:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/93_components/workflows/registry_agents_in_workflow.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/approvals/approval_basic.py
""" Approval Basic ============================= Approval-backed HITL: @approval + @tool(requires_confirmation=True) with persistent DB record. """ import json import httpx from agno.agent import Agent from agno.approval import approval from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIResponses from agno.os import AgentOS from agno.tools import tool DB_FILE = "tmp/approvals_test.db" @approval(type="required") @tool(requires_confirmation=True) def get_top_hackernews_stories(num_stories: int) -> str: """Fetch top stories from Hacker News. Args: num_stories (int): Number of stories to retrieve. Returns: str: JSON string of story details. """ response = httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json") story_ids = response.json() stories = [] for story_id in story_ids[:num_stories]: story = httpx.get( f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json" ).json() story.pop("text", None) stories.append(story) return json.dumps(stories) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- db = SqliteDb( db_file=DB_FILE, session_table="agent_sessions", approvals_table="approvals" ) agent = Agent( name="Approval Basic Agent", model=OpenAIResponses(id="gpt-5-mini"), tools=[get_top_hackernews_stories], markdown=True, db=db, ) agent_os = AgentOS( description="Example app for approvals with basic tool", agents=[ agent, ], db=db, ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="approval_basic:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/approvals/approval_basic.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/approvals/approval_user_input.py
""" Approval User Input ============================= Approval + user input HITL: @approval + @tool(requires_user_input=True). """ import os from agno.agent import Agent from agno.approval import approval from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIResponses from agno.os import AgentOS from agno.tools import tool DB_FILE = "tmp/approvals_test.db" @approval(type="required") @tool(requires_user_input=True, user_input_fields=["recipient", "note"]) def send_money(amount: float, recipient: str, note: str) -> str: """Send money to a recipient. Args: amount (float): The amount of money to send. recipient (str): The recipient to send money to (provided by user). note (str): A note to include with the transfer. Returns: str: Confirmation of the transfer. """ return f"Sent ${amount} to {recipient}: {note}" # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- db = SqliteDb( db_file=DB_FILE, session_table="agent_sessions", approvals_table="approvals" ) agent = Agent( name="Approval User Input Agent", model=OpenAIResponses(id="gpt-5-mini"), tools=[send_money], markdown=True, db=db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Clean up from previous runs if os.path.exists(DB_FILE): os.remove(DB_FILE) os.makedirs("tmp", exist_ok=True) # Re-create after cleanup db = SqliteDb( db_file=DB_FILE, session_table="agent_sessions", approvals_table="approvals" ) agent = Agent( model=OpenAIResponses(id="gpt-5-mini"), tools=[send_money], markdown=True, db=db, ) agent_os = AgentOS( description="Example app for approvals with user input", agents=[ agent, ], db=db, ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="approval_user_input:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/approvals/approval_user_input.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/tests/unit/os/test_knowledge_filters_serialization.py
"""Tests that knowledge_filters serialize correctly in AgentResponse. Covers the fix for https://github.com/agno-agi/agno/issues/6547 where FilterExpr objects caused PydanticSerializationError on GET /agents. """ import json from agno.filters import AND, EQ, GT, IN, LT, NOT, OR, from_dict from agno.os.routers.agents.schema import AgentResponse def _serialize_knowledge_filters(knowledge_filters): """Replicate the serialization logic from AgentResponse.from_agent.""" return ( [f.to_dict() if hasattr(f, "to_dict") else f for f in knowledge_filters] if isinstance(knowledge_filters, list) else knowledge_filters ) def _make_response(knowledge_filters) -> AgentResponse: """Build a minimal AgentResponse with the given knowledge_filters.""" serialized = _serialize_knowledge_filters(knowledge_filters) knowledge = {"knowledge_filters": serialized} if serialized is not None else None return AgentResponse(name="test-agent", knowledge=knowledge) # -- Dict-style filters (most common usage) -- def test_dict_filters_pass_through(): """Dict-style filters must be preserved as-is, not iterated over.""" filters = {"user_id": "jordan_mitchell", "region": "north_america"} result = _serialize_knowledge_filters(filters) assert result == filters def test_dict_filters_roundtrip_json(): """AgentResponse with dict filters must survive Pydantic JSON serialization.""" resp = _make_response({"user_id": "jordan_mitchell"}) dumped = json.loads(resp.model_dump_json()) assert dumped["knowledge"]["knowledge_filters"] == {"user_id": "jordan_mitchell"} # -- List[FilterExpr] filters -- def test_simple_eq_filter(): filters = [EQ("status", "published")] result = _serialize_knowledge_filters(filters) assert result == [{"op": "EQ", "key": "status", "value": "published"}] def test_or_with_nested_and(): """The exact pattern from issue #6547.""" filters = [ OR( EQ("knowledge_type", "general"), AND( EQ("knowledge_type", "user_specific"), IN("username", ["user1", "user2"]), ), ) ] result = _serialize_knowledge_filters(filters) assert len(result) == 1 assert result[0]["op"] == "OR" assert len(result[0]["conditions"]) == 2 assert result[0]["conditions"][0] == {"op": "EQ", "key": "knowledge_type", "value": "general"} and_cond = result[0]["conditions"][1] assert and_cond["op"] == "AND" assert len(and_cond["conditions"]) == 2 def test_not_filter(): filters = [NOT(EQ("status", "archived"))] result = _serialize_knowledge_filters(filters) assert result == [{"op": "NOT", "condition": {"op": "EQ", "key": "status", "value": "archived"}}] def test_gt_lt_filters(): filters = [GT("age", 18), LT("price", 100)] result = _serialize_knowledge_filters(filters) assert result[0] == {"op": "GT", "key": "age", "value": 18} assert result[1] == {"op": "LT", "key": "price", "value": 100} def test_filter_expr_roundtrip_json(): """AgentResponse with FilterExpr list must survive Pydantic JSON serialization.""" resp = _make_response([OR(EQ("a", 1), EQ("b", 2))]) dumped = json.loads(resp.model_dump_json()) kf = dumped["knowledge"]["knowledge_filters"] assert kf == [ {"op": "OR", "conditions": [{"op": "EQ", "key": "a", "value": 1}, {"op": "EQ", "key": "b", "value": 2}]} ] def test_filter_expr_to_dict_from_dict_roundtrip(): """FilterExpr -> to_dict -> from_dict should reconstruct equivalent objects.""" original = OR( AND(EQ("type", "article"), GT("views", 1000)), AND(EQ("type", "tutorial"), NOT(EQ("difficulty", "beginner"))), ) reconstructed = from_dict(original.to_dict()) assert reconstructed.to_dict() == original.to_dict() # -- None filters -- def test_none_filters(): result = _serialize_knowledge_filters(None) assert result is None def test_none_filters_roundtrip_json(): resp = _make_response(None) dumped = json.loads(resp.model_dump_json()) assert dumped.get("knowledge") is None
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/os/test_knowledge_filters_serialization.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/unit/workflow/test_step_image_conversion.py
"""Tests for Step._convert_image_artifacts_to_images handling of raw and base64 image bytes.""" import base64 from unittest.mock import MagicMock import pytest from agno.media import Image from agno.workflow.step import Step @pytest.fixture() def step(): mock_agent = MagicMock() mock_agent.id = "test-agent" return Step(name="test", agent=mock_agent) class TestConvertImageArtifactsToImages: def test_raw_jpeg_bytes_not_dropped(self, step): """Raw JPEG bytes should be preserved, not silently skipped.""" raw_jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF" images = step._convert_image_artifacts_to_images([Image(content=raw_jpeg)]) assert len(images) == 1 assert images[0].content == raw_jpeg def test_raw_png_bytes_not_dropped(self, step): """Raw PNG bytes should be preserved, not silently skipped.""" raw_png = b"\x89PNG\r\n\x1a\n\x00\x00" images = step._convert_image_artifacts_to_images([Image(content=raw_png)]) assert len(images) == 1 assert images[0].content == raw_png def test_base64_encoded_bytes_decoded(self, step): """Base64-encoded bytes should be decoded to raw bytes.""" original = b"test image data" b64_bytes = base64.b64encode(original) images = step._convert_image_artifacts_to_images([Image(content=b64_bytes)]) assert len(images) == 1 assert images[0].content == original def test_url_image_passes_through(self, step): """URL-based images should pass through unchanged.""" images = step._convert_image_artifacts_to_images([Image(url="https://example.com/img.png")]) assert len(images) == 1 assert images[0].url == "https://example.com/img.png" def test_empty_list_returns_empty(self, step): """Empty input should return empty output.""" images = step._convert_image_artifacts_to_images([]) assert images == [] def test_multiple_images_all_preserved(self, step): """Multiple images of different types should all be preserved.""" raw_jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF" raw_png = b"\x89PNG\r\n\x1a\n\x00\x00" images = step._convert_image_artifacts_to_images( [ Image(content=raw_jpeg), Image(content=raw_png), Image(url="https://example.com/img.png"), ] ) assert len(images) == 3 def test_image_with_mime_type_sets_format(self, step): """Image with mime_type should have format extracted.""" raw_png = b"\x89PNG\r\n\x1a\n\x00\x00" images = step._convert_image_artifacts_to_images([Image(content=raw_png, mime_type="image/png")]) assert len(images) == 1 assert images[0].content == raw_png
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/workflow/test_step_image_conversion.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:cookbook/05_agent_os/interfaces/slack/multi_bot.py
""" Multi-Bot Streaming Test ======================== Two agents on the same Slack workspace, mounted on different prefixes. Both use streaming mode. Tests session isolation: each bot gets its own DB session even when responding in the same thread. Setup: 1. Two Slack apps (Ace + Dash) installed to the same workspace 2. Event Subscription URLs: Ace -> https://<tunnel>/ace/events Dash -> https://<tunnel>/slack/events 3. Environment variables: ACE_SLACK_TOKEN, ACE_SLACK_SIGNING_SECRET DASH_SLACK_TOKEN, DASH_SLACK_SIGNING_SECRET 4. ngrok: ngrok http --domain=<your-subdomain>.ngrok-free.dev 7777 Slack scopes (per app): app_mentions:read, assistant:write, chat:write, im:history """ from os import getenv from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.os.app import AgentOS from agno.os.interfaces.slack import Slack db = SqliteDb(session_table="agent_sessions", db_file="tmp/multi_bot.db") ace_agent = Agent( id="ace", name="Ace", model=OpenAIChat(id="gpt-4.1-mini"), db=db, instructions=[ "You are Ace, a research assistant. Always introduce yourself as Ace.", "When answering, cite sources and be thorough.", ], add_history_to_context=True, num_history_runs=5, markdown=True, ) dash_agent = Agent( id="dash", name="Dash", model=OpenAIChat(id="gpt-4.1-mini"), db=db, instructions=[ "You are Dash, a concise summarizer. Always introduce yourself as Dash.", "Keep answers concise - 2-3 sentences max.", ], add_history_to_context=True, num_history_runs=5, markdown=True, ) agent_os = AgentOS( agents=[ace_agent, dash_agent], interfaces=[ Slack( agent=ace_agent, prefix="/ace", token=getenv("ACE_SLACK_TOKEN"), signing_secret=getenv("ACE_SLACK_SIGNING_SECRET"), streaming=True, reply_to_mentions_only=False, ), Slack( agent=dash_agent, prefix="/slack", token=getenv("DASH_SLACK_TOKEN"), signing_secret=getenv("DASH_SLACK_SIGNING_SECRET"), streaming=True, reply_to_mentions_only=False, ), ], ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="multi_bot:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/interfaces/slack/multi_bot.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/interfaces/slack/multimodal_team.py
""" Multimodal Team =============== Tests streaming a multi-agent team with multimodal input/output in Slack. Capabilities tested: - Image INPUT: Send an image to the bot, team analyzes it (GPT-4o vision) - Image OUTPUT: Ask to generate an image, DALL-E creates it, uploaded to Slack - File INPUT: Send a CSV/text file, team analyzes it - Combined: Send image + ask to modify/recreate it Team members: - Vision Analyst: Understands images and files via GPT-4o - Creative Agent: Generates images via DALL-E + web search Slack scopes: app_mentions:read, assistant:write, chat:write, im:history, files:read, files:write """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.os.app import AgentOS from agno.os.interfaces.slack import Slack from agno.team import Team from agno.tools.dalle import DalleTools from agno.tools.websearch import WebSearchTools # --------------------------------------------------------------------------- # Team Members # --------------------------------------------------------------------------- vision_analyst = Agent( name="Vision Analyst", model=OpenAIChat(id="gpt-4o"), role="Analyzes images, files, and visual content in detail.", instructions=[ "You are an expert visual analyst.", "When given an image, describe it thoroughly: subjects, colors, composition, text, mood.", "When given files (CSV, code, text), analyze their content and provide insights.", "Always format with markdown: bold, italics, bullet points.", ], markdown=True, ) creative_agent = Agent( name="Creative Agent", model=OpenAIChat(id="gpt-4o"), role="Generates images with DALL-E and searches the web.", tools=[DalleTools(), WebSearchTools()], instructions=[ "You are a creative assistant with image generation abilities.", "Use DALL-E to generate images when asked.", "Use web search when you need reference information.", "Describe generated images briefly after creation.", ], markdown=True, ) # --------------------------------------------------------------------------- # Team # --------------------------------------------------------------------------- multimodal_team = Team( name="Multimodal Team", mode="coordinate", model=OpenAIChat(id="gpt-4o"), members=[vision_analyst, creative_agent], instructions=[ "Route image analysis and file analysis tasks to Vision Analyst.", "Route image generation and web search tasks to Creative Agent.", "If the user sends an image and asks to recreate/modify it, first ask Vision Analyst to describe it, then ask Creative Agent to generate a new version.", ], show_members_responses=False, markdown=True, ) # --------------------------------------------------------------------------- # AgentOS # --------------------------------------------------------------------------- agent_os = AgentOS( teams=[multimodal_team], interfaces=[ Slack( team=multimodal_team, streaming=True, reply_to_mentions_only=True, suggested_prompts=[ { "title": "Analyze", "message": "Send me an image and I'll analyze it in detail", }, { "title": "Generate", "message": "Generate an image of a sunset over mountains", }, {"title": "Search", "message": "Search for the latest AI art trends"}, ], ) ], ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="multimodal_team:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/interfaces/slack/multimodal_team.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/interfaces/slack/multimodal_workflow.py
""" Multimodal Workflow =================== Tests streaming a workflow with multimodal input/output in Slack. Capabilities tested: - Image INPUT: Send an image, workflow processes it through steps - Image OUTPUT: DALL-E generates images during workflow steps - Parallel execution: Two steps run simultaneously - Sequential synthesis: Final step combines parallel results Workflow structure: Parallel: - Visual Analysis (analyzes any input images/files) - Web Research (searches for related context) Sequential: - Creative Synthesis (generates a new image inspired by analysis + research) Slack scopes: app_mentions:read, assistant:write, chat:write, im:history, files:read, files:write """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.os.app import AgentOS from agno.os.interfaces.slack import Slack from agno.tools.dalle import DalleTools from agno.tools.websearch import WebSearchTools from agno.workflow import Parallel, Step, Workflow # --------------------------------------------------------------------------- # Step Agents # --------------------------------------------------------------------------- analyst = Agent( name="Visual Analyst", model=OpenAIChat(id="gpt-4o"), instructions=[ "Analyze any images or files provided.", "Describe visual elements, composition, colors, mood.", "If no image, analyze the text topic visually.", "Keep analysis concise but detailed.", ], markdown=True, ) researcher = Agent( name="Web Researcher", model=OpenAIChat(id="gpt-4o"), tools=[WebSearchTools()], instructions=[ "Search the web for information related to the user's request.", "Provide relevant facts, trends, and context.", "Format results with markdown.", ], markdown=True, ) synthesizer = Agent( name="Creative Synthesizer", model=OpenAIChat(id="gpt-4o"), tools=[DalleTools()], instructions=[ "Combine the analysis and research from previous steps.", "If the user asked for an image, generate one with DALL-E.", "Provide a final comprehensive response.", "Format with markdown.", ], markdown=True, ) # --------------------------------------------------------------------------- # Workflow # --------------------------------------------------------------------------- analysis_step = Step( name="Visual Analysis", agent=analyst, description="Analyze input images/files or describe the topic visually", ) research_step = Step( name="Web Research", agent=researcher, description="Search the web for related context and information", ) research_phase = Parallel( analysis_step, research_step, name="Research Phase", ) synthesis_step = Step( name="Creative Synthesis", agent=synthesizer, description="Combine analysis + research into a final response, generate images if requested", ) creative_workflow = Workflow( name="Creative Pipeline", steps=[research_phase, synthesis_step], ) # --------------------------------------------------------------------------- # AgentOS # --------------------------------------------------------------------------- agent_os = AgentOS( workflows=[creative_workflow], interfaces=[ Slack( workflow=creative_workflow, streaming=True, reply_to_mentions_only=True, suggested_prompts=[ { "title": "Analyze", "message": "Send me an image to analyze and research", }, { "title": "Create", "message": "Research cyberpunk art trends and generate an image", }, { "title": "Compare", "message": "Compare impressionism and expressionism art styles", }, ], ) ], ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="multimodal_workflow:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/interfaces/slack/multimodal_workflow.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/interfaces/slack/streaming_deep_research.py
""" Streaming Deep Research Agent ============================== A multi-tool research agent that exercises many different tool types to stress-test the Slack streaming plan block UI. Uses 7 toolkits across web search, finance, news, academic papers, and calculations — a single query can trigger 8-12+ tool calls, each rendering as a card in the plan block. Slack scopes: app_mentions:read, assistant:write, chat:write, im:history """ from agno.agent import Agent from agno.db.sqlite.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.os.app import AgentOS from agno.os.interfaces.slack import Slack from agno.tools.arxiv import ArxivTools from agno.tools.calculator import CalculatorTools from agno.tools.duckduckgo import DuckDuckGoTools from agno.tools.hackernews import HackerNewsTools from agno.tools.newspaper4k import Newspaper4kTools from agno.tools.wikipedia import WikipediaTools from agno.tools.yfinance import YFinanceTools agent_db = SqliteDb( session_table="deep_research_sessions", db_file="tmp/deep_research.db" ) deep_research_agent = Agent( name="Deep Research Agent", model=OpenAIChat(id="gpt-4.1"), tools=[ DuckDuckGoTools(), HackerNewsTools(), YFinanceTools( enable_stock_price=True, enable_company_info=True, enable_analyst_recommendations=True, enable_company_news=True, ), WikipediaTools(), ArxivTools(), CalculatorTools(), Newspaper4kTools(), ], instructions=[ "You are a deep research assistant that gathers information from MANY sources.", "For every query, use AT LEAST 4 different tools to provide comprehensive answers.", "Always search the web AND check HackerNews AND Wikipedia for context.", "For finance questions, pull stock data, analyst recommendations, AND company news.", "For technical topics, also search Arxiv for relevant research papers.", "Use the calculator for any numerical analysis or comparisons.", "Use newspaper4k to read full articles when you find interesting URLs.", "Synthesize all findings into a well-structured summary with sections.", ], db=agent_db, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) agent_os = AgentOS( agents=[deep_research_agent], interfaces=[ Slack( agent=deep_research_agent, streaming=True, reply_to_mentions_only=True, loading_messages=[ "Researching across multiple sources...", "Gathering data from 7 different tools...", "Cross-referencing findings...", "Analyzing and synthesizing results...", ], suggested_prompts=[ { "title": "Deep Stock Analysis", "message": "Do a deep analysis of NVDA: get the stock price, company info, analyst recommendations, latest news, search the web for recent developments, check HackerNews discussions, and look up Nvidia on Wikipedia for company background", }, { "title": "AI Research Deep Dive", "message": "Research the latest developments in large language models: search the web, check HackerNews, look up recent Arxiv papers on LLMs, and read the Wikipedia article on large language models for background context", }, { "title": "Tech Company Comparison", "message": "Compare AAPL and MSFT: get both stock prices, analyst recommendations, company info, search for recent news about both, and calculate the price-to-earnings ratio difference", }, { "title": "Trending Tech News", "message": "What are the biggest tech stories today? Check HackerNews top stories, search the web for breaking tech news, and read the full text of the top 2 articles you find", }, ], ) ], ) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="streaming_deep_research:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/interfaces/slack/streaming_deep_research.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/os/interfaces/slack/events.py
""" Slack Streaming Event Handlers ============================== Processes streaming events from agents, teams, and workflows, translating them into Slack task cards and buffered content. Key concepts: - Events are normalized (Team prefix stripped) for unified handling - Workflow mode suppresses inner agent events to reduce noise - Task cards track progress; content is buffered for streaming - Factory pattern generates simple paired handlers (Started/Completed) """ from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Awaitable, Callable, Dict from agno.agent import RunEvent from agno.os.interfaces.slack.helpers import member_name, task_id from agno.os.interfaces.slack.state import StreamState from agno.run.workflow import WorkflowRunEvent if TYPE_CHECKING: from slack_sdk.web.async_chat_stream import AsyncChatStream from agno.run.base import BaseRunOutputEvent # ============================================================================= # Type Aliases # ============================================================================= # Event handlers return True on terminal events to break the stream loop _EventHandler = Callable[ ["BaseRunOutputEvent", StreamState, "AsyncChatStream"], Awaitable[bool], ] # ============================================================================= # Helper Functions # ============================================================================= def _normalize_event(event: str) -> str: """Strip 'Team' prefix so agent and team events use the same handlers.""" return event.removeprefix("Team") @dataclass class _ToolRef: """Reference to a tool call for task card tracking.""" tid: str | None # Slack task card ID (None when tool_call_id is missing) label: str # Display title, e.g. "Researcher: web_search" errored: bool def _extract_tool_ref(chunk: BaseRunOutputEvent, state: StreamState, *, fallback_id: str | None = None) -> _ToolRef: """Build unique (tid, label) for each tool call's Slack task card.""" tool = getattr(chunk, "tool", None) tool_name = (tool.tool_name if tool else None) or "tool" call_id = (tool.tool_call_id if tool else None) or fallback_id member = member_name(chunk, state.entity_name) label = f"{member}: {tool_name}" if member else tool_name tid = task_id(member, call_id) if call_id else None # type: ignore[arg-type] errored = bool(tool.tool_call_error) if tool else False return _ToolRef(tid=tid, label=label, errored=errored) async def _emit_task( stream: AsyncChatStream, card_id: str, title: str, status: str, *, output: str | None = None, ) -> None: """Send a task card update to the Slack stream.""" chunk: dict = {"type": "task_update", "id": card_id, "title": title, "status": status} if output: chunk["output"] = output[:200] # Slack truncates longer task output await stream.append(markdown_text="", chunks=[chunk]) async def _wf_task( chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream, prefix: str, label: str = "", *, started: bool, name_attr: str = "step_name", ) -> None: """Emit a workflow task card for paired events (Started/Completed).""" name = getattr(chunk, name_attr, None) or prefix sid = getattr(chunk, "step_id", None) or name key = f"wf_{prefix}_{sid}" title = f"{label}: {name}" if label else name if started: state.track_task(key, title) await _emit_task(stream, key, title, "in_progress") else: state.complete_task(key) await _emit_task(stream, key, title, "complete") # ============================================================================= # Suppression Set # ============================================================================= # Workflows orchestrate multiple agents via steps/loops/conditions. Without # suppression, each inner agent's tool calls and reasoning events would flood # the Slack stream with low-level noise. We only show step-level progress. # Values are NORMALIZED (no "Team" prefix) so one set covers agent + team events. _SUPPRESSED_IN_WORKFLOW: frozenset[str] = frozenset( { RunEvent.reasoning_started.value, RunEvent.reasoning_completed.value, RunEvent.tool_call_started.value, RunEvent.tool_call_completed.value, RunEvent.tool_call_error.value, RunEvent.memory_update_started.value, RunEvent.memory_update_completed.value, RunEvent.run_content.value, RunEvent.run_intermediate_content.value, RunEvent.run_completed.value, RunEvent.run_error.value, RunEvent.run_cancelled.value, } ) # ============================================================================= # Handler Factory # ============================================================================= def _make_wf_handler( prefix: str, label: str, *, started: bool, name_attr: str = "step_name", ) -> _EventHandler: """ Factory to create workflow event handlers for simple paired events. This eliminates boilerplate for events that just call _wf_task with different parameters (e.g., ParallelStarted, ConditionCompleted, etc.). """ async def handler(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: await _wf_task(chunk, state, stream, prefix, label, started=started, name_attr=name_attr) return False return handler # ============================================================================= # Agent/Team Event Handlers (require custom logic) # ============================================================================= async def _on_reasoning_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: key = f"reasoning_{state.reasoning_round}" state.track_task(key, "Reasoning") await _emit_task(stream, key, "Reasoning", "in_progress") return False async def _on_reasoning_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: key = f"reasoning_{state.reasoning_round}" state.complete_task(key) state.reasoning_round += 1 await _emit_task(stream, key, "Reasoning", "complete") return False async def _on_tool_call_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: # Fallback when SDK chunks omit tool_call_id so cards still render ref = _extract_tool_ref(chunk, state, fallback_id=str(len(state.task_cards))) if ref.tid: state.track_task(ref.tid, ref.label) await _emit_task(stream, ref.tid, ref.label, "in_progress") return False async def _on_tool_call_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: ref = _extract_tool_ref(chunk, state) if ref.tid: # Backfill card when Completed arrives without a prior Started event if ref.tid not in state.task_cards: state.track_task(ref.tid, ref.label) if ref.errored: state.error_task(ref.tid) else: state.complete_task(ref.tid) await _emit_task(stream, ref.tid, ref.label, "error" if ref.errored else "complete") return False async def _on_tool_call_error(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: ref = _extract_tool_ref(chunk, state, fallback_id=f"tool_error_{state.error_count}") error_msg = getattr(chunk, "error", None) or "Tool call failed" state.error_count += 1 if ref.tid: if ref.tid not in state.task_cards: state.track_task(ref.tid, ref.label) state.error_task(ref.tid) await _emit_task(stream, ref.tid, ref.label, "error", output=str(error_msg)) return False async def _on_run_content(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: content = getattr(chunk, "content", None) if content is not None: state.append_content(content) return False async def _on_run_intermediate_content(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: # Teams emit intermediate content from each member as they finish. Showing # these would interleave partial outputs in the stream. The team leader # emits a single consolidated RunContent at the end — that's what we show. if state.entity_type != "team": content = getattr(chunk, "content", None) if content is not None: state.append_content(content) return False async def _on_memory_update_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: state.track_task("memory_update", "Updating memory") await _emit_task(stream, "memory_update", "Updating memory", "in_progress") return False async def _on_memory_update_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: state.complete_task("memory_update") await _emit_task(stream, "memory_update", "Updating memory", "complete") return False async def _on_run_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: return False # Finalization handled by caller after stream ends async def _on_run_error(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: state.error_count += 1 error_msg = getattr(chunk, "content", None) or "An error occurred" state.append_error(error_msg) state.terminal_status = "error" return True # ============================================================================= # Workflow Event Handlers (require custom logic) # ============================================================================= async def _on_step_output(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: # StepOutput is workflow-only (agents/teams never emit it). # Capture but don't stream — WorkflowCompleted uses this as fallback. content = getattr(chunk, "content", None) if content is not None: state.workflow_final_content = str(content) return False async def _on_workflow_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: wf_name = getattr(chunk, "workflow_name", None) or state.entity_name or "Workflow" run_id = getattr(chunk, "run_id", None) or "run" key = f"wf_run_{run_id}" state.track_task(key, f"Workflow: {wf_name}") await _emit_task(stream, key, f"Workflow: {wf_name}", "in_progress") return False async def _on_workflow_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: run_id = getattr(chunk, "run_id", None) or "run" wf_name = getattr(chunk, "workflow_name", None) or state.entity_name or "Workflow" key = f"wf_run_{run_id}" state.complete_task(key) await _emit_task(stream, key, f"Workflow: {wf_name}", "complete") final = getattr(chunk, "content", None) if final is None: final = state.workflow_final_content if final: state.append_content(final) return False async def _on_workflow_error(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: state.error_count += 1 error_msg = getattr(chunk, "error", None) or getattr(chunk, "content", None) or "Workflow failed" state.append_error(error_msg) state.terminal_status = "error" return True async def _on_step_error(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: step_name = getattr(chunk, "step_name", None) or "step" sid = getattr(chunk, "step_id", None) or step_name key = f"wf_step_{sid}" error_msg = getattr(chunk, "error", None) or "Step failed" if key not in state.task_cards: state.track_task(key, step_name) state.error_task(key) await _emit_task(stream, key, step_name, "error", output=str(error_msg)) return False # ============================================================================= # Loop Event Handlers (custom logic for iteration tracking) # ============================================================================= async def _on_loop_execution_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: step_name = getattr(chunk, "step_name", None) or "loop" loop_key = getattr(chunk, "step_id", None) or step_name max_iter = getattr(chunk, "max_iterations", None) title = f"Loop: {step_name}" + (f" (max {max_iter})" if max_iter else "") key = f"wf_loop_{loop_key}" state.track_task(key, title) await _emit_task(stream, key, title, "in_progress") return False async def _on_loop_iteration_started(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: loop_key = getattr(chunk, "step_id", None) or getattr(chunk, "step_name", None) or "loop" iteration = getattr(chunk, "iteration", 0) max_iter = getattr(chunk, "max_iterations", None) title = f"Iteration {iteration}" + (f"/{max_iter}" if max_iter else "") key = f"wf_loop_{loop_key}_iter_{iteration}" state.track_task(key, title) await _emit_task(stream, key, title, "in_progress") return False async def _on_loop_iteration_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: loop_key = getattr(chunk, "step_id", None) or getattr(chunk, "step_name", None) or "loop" iteration = getattr(chunk, "iteration", 0) key = f"wf_loop_{loop_key}_iter_{iteration}" state.complete_task(key) await _emit_task(stream, key, f"Iteration {iteration}", "complete") return False async def _on_loop_execution_completed(chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: step_name = getattr(chunk, "step_name", None) or "loop" loop_key = getattr(chunk, "step_id", None) or step_name key = f"wf_loop_{loop_key}" state.complete_task(key) await _emit_task(stream, key, f"Loop: {step_name}", "complete") return False # ============================================================================= # Dispatch Table # ============================================================================= # Single dispatch table — keys are normalized (no "Team" prefix). # Workflow event names never start with "Team" so normalization is a no-op for them. HANDLERS: Dict[str, _EventHandler] = { # ------------------------------------------------------------------------- # Agent/Team Events (normalized - use RunEvent values) # ------------------------------------------------------------------------- RunEvent.reasoning_started.value: _on_reasoning_started, RunEvent.reasoning_completed.value: _on_reasoning_completed, RunEvent.tool_call_started.value: _on_tool_call_started, RunEvent.tool_call_completed.value: _on_tool_call_completed, RunEvent.tool_call_error.value: _on_tool_call_error, RunEvent.run_content.value: _on_run_content, RunEvent.run_intermediate_content.value: _on_run_intermediate_content, RunEvent.memory_update_started.value: _on_memory_update_started, RunEvent.memory_update_completed.value: _on_memory_update_completed, RunEvent.run_completed.value: _on_run_completed, RunEvent.run_error.value: _on_run_error, RunEvent.run_cancelled.value: _on_run_error, # Treat cancellation as terminal error # ------------------------------------------------------------------------- # Workflow Lifecycle Events # ------------------------------------------------------------------------- WorkflowRunEvent.step_output.value: _on_step_output, WorkflowRunEvent.workflow_started.value: _on_workflow_started, WorkflowRunEvent.workflow_completed.value: _on_workflow_completed, WorkflowRunEvent.workflow_error.value: _on_workflow_error, WorkflowRunEvent.workflow_cancelled.value: _on_workflow_error, # ------------------------------------------------------------------------- # Workflow Step Events # ------------------------------------------------------------------------- WorkflowRunEvent.step_started.value: _make_wf_handler("step", "", started=True), WorkflowRunEvent.step_completed.value: _make_wf_handler("step", "", started=False), WorkflowRunEvent.step_error.value: _on_step_error, # ------------------------------------------------------------------------- # Workflow Loop Events # ------------------------------------------------------------------------- WorkflowRunEvent.loop_execution_started.value: _on_loop_execution_started, WorkflowRunEvent.loop_iteration_started.value: _on_loop_iteration_started, WorkflowRunEvent.loop_iteration_completed.value: _on_loop_iteration_completed, WorkflowRunEvent.loop_execution_completed.value: _on_loop_execution_completed, # ------------------------------------------------------------------------- # Workflow Structural Events (factory-generated) # ------------------------------------------------------------------------- WorkflowRunEvent.parallel_execution_started.value: _make_wf_handler("parallel", "Parallel", started=True), WorkflowRunEvent.parallel_execution_completed.value: _make_wf_handler("parallel", "Parallel", started=False), WorkflowRunEvent.condition_execution_started.value: _make_wf_handler("cond", "Condition", started=True), WorkflowRunEvent.condition_execution_completed.value: _make_wf_handler("cond", "Condition", started=False), WorkflowRunEvent.router_execution_started.value: _make_wf_handler("router", "Router", started=True), WorkflowRunEvent.router_execution_completed.value: _make_wf_handler("router", "Router", started=False), WorkflowRunEvent.workflow_agent_started.value: _make_wf_handler( "agent", "Running", started=True, name_attr="agent_name" ), WorkflowRunEvent.workflow_agent_completed.value: _make_wf_handler( "agent", "Running", started=False, name_attr="agent_name" ), WorkflowRunEvent.steps_execution_started.value: _make_wf_handler("steps", "Steps", started=True), WorkflowRunEvent.steps_execution_completed.value: _make_wf_handler("steps", "Steps", started=False), } async def process_event(ev_raw: str, chunk: BaseRunOutputEvent, state: StreamState, stream: AsyncChatStream) -> bool: """ Process a streaming event and update Slack accordingly. Args: ev_raw: Raw event name (e.g., "ToolCallStarted", "TeamRunContent") chunk: Stream chunk containing event data state: StreamState tracking session state stream: Slack chat_stream for sending updates Returns: True if this is a terminal event and the stream loop should break. """ ev = _normalize_event(ev_raw) # Suppress nested agent internals in workflow mode if state.entity_type == "workflow" and ev in _SUPPRESSED_IN_WORKFLOW: return False handler = HANDLERS.get(ev) if handler: return await handler(chunk, state, stream) return False
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/os/interfaces/slack/events.py", "license": "Apache License 2.0", "lines": 359, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex