repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/mcp_ai_agents/browser_mcp_agent/main.py
mcp_ai_agents/browser_mcp_agent/main.py
import asyncio import os import streamlit as st from textwrap import dedent from mcp_agent.app import MCPApp from mcp_agent.agents.agent import Agent from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM from mcp_agent.workflows.llm.augmented_llm import RequestParams # Page config st.set_page_config(page_title="Browser MCP Agent", page_icon="🌐", layout="wide") # Title and description st.markdown("<h1 class='main-header'>🌐 Browser MCP Agent</h1>", unsafe_allow_html=True) st.markdown("Interact with a powerful web browsing agent that can navigate and interact with websites") # Setup sidebar with example commands with st.sidebar: st.markdown("### Example Commands") st.markdown("**Navigation**") st.markdown("- Go to github.com/Shubhamsaboo/awesome-llm-apps") st.markdown("**Interactions**") st.markdown("- click on mcp_ai_agents") st.markdown("- Scroll down to view more content") st.markdown("**Multi-step Tasks**") st.markdown("- Navigate to github.com/Shubhamsaboo/awesome-llm-apps, scroll down, and report details") st.markdown("- Scroll down and summarize the github readme") st.markdown("---") st.caption("Note: The agent uses Playwright to control a real browser.") # Query input query = st.text_area("Your Command", placeholder="Ask the agent to navigate to websites and interact with them") # Initialize app and agent if 'initialized' not in st.session_state: st.session_state.initialized = False st.session_state.mcp_app = MCPApp(name="streamlit_mcp_agent") st.session_state.mcp_context = None st.session_state.mcp_agent_app = None st.session_state.browser_agent = None st.session_state.llm = None st.session_state.loop = asyncio.new_event_loop() asyncio.set_event_loop(st.session_state.loop) st.session_state.is_processing = False # Setup function that runs only once async def setup_agent(): if not st.session_state.initialized: try: # Create context manager and store it in session state st.session_state.mcp_context = st.session_state.mcp_app.run() st.session_state.mcp_agent_app = await st.session_state.mcp_context.__aenter__() # Create and initialize agent st.session_state.browser_agent = Agent( name="browser", instruction="""You are a helpful web browsing assistant that can interact with websites using playwright. - Navigate to websites and perform browser actions (click, scroll, type) - Extract information from web pages - Take screenshots of page elements when useful - Provide concise summaries of web content using markdown - Follow multi-step browsing sequences to complete tasks Respond back with a status update on completing the commands.""", server_names=["playwright"], ) # Initialize agent and attach LLM await st.session_state.browser_agent.initialize() st.session_state.llm = await st.session_state.browser_agent.attach_llm(OpenAIAugmentedLLM) # List tools once logger = st.session_state.mcp_agent_app.logger tools = await st.session_state.browser_agent.list_tools() logger.info("Tools available:", data=tools) # Mark as initialized st.session_state.initialized = True except Exception as e: return f"Error during initialization: {str(e)}" return None # Main function to run agent async def run_mcp_agent(message): if not os.getenv("OPENAI_API_KEY"): return "Error: OpenAI API key not provided" try: # Make sure agent is initialized error = await setup_agent() if error: return error # Generate response without recreating agents # Switch use_history to False to reduce the passed context result = await st.session_state.llm.generate_str( message=message, request_params=RequestParams(use_history=True, maxTokens=10000) ) return result except Exception as e: return f"Error: {str(e)}" # Defaults if 'is_processing' not in st.session_state: st.session_state.is_processing = False if 'last_result' not in st.session_state: st.session_state.last_result = None def start_run(): st.session_state.is_processing = True # Button (use a callback so the click just flips state) st.button( "🚀 Run Command", type="primary", use_container_width=True, disabled=st.session_state.is_processing, on_click=start_run, ) # If we’re in a processing run, do the work now if st.session_state.is_processing: with st.spinner("Processing your request..."): result = st.session_state.loop.run_until_complete(run_mcp_agent(query)) # persist result across the next rerun st.session_state.last_result = result # unlock the button and refresh UI st.session_state.is_processing = False st.rerun() # Render the most recent result (after the rerun) if st.session_state.last_result: st.markdown("### Response") st.markdown(st.session_state.last_result) else: # (your existing help text here) pass # Display help text for first-time users if 'result' not in locals(): st.markdown( """<div style='padding: 20px; background-color: #f0f2f6; border-radius: 10px;'> <h4>How to use this app:</h4> <ol> <li>Enter your OpenAI API key in your mcp_agent.secrets.yaml file</li> <li>Type a command for the agent to navigate and interact with websites</li> <li>Click 'Run Command' to see results</li> </ol> <p><strong>Capabilities:</strong></p> <ul> <li>Navigate to websites using Playwright</li> <li>Click on elements, scroll, and type text</li> <li>Take screenshots of specific elements</li> <li>Extract information from web pages</li> <li>Perform multi-step browsing tasks</li> </ul> </div>""", unsafe_allow_html=True ) # Footer st.markdown("---") st.write("Built with Streamlit, Playwright, and [MCP-Agent](https://www.github.com/lastmile-ai/mcp-agent) Framework ❤️")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/mcp_ai_agents/multi_mcp_agent/multi_mcp_agent.py
mcp_ai_agents/multi_mcp_agent/multi_mcp_agent.py
import asyncio import os import uuid from textwrap import dedent from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.mcp import MultiMCPTools from agno.db.sqlite import SqliteDb from dotenv import load_dotenv # Load environment variables load_dotenv() GITHUB_TOKEN = os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY") async def main(): print("\n" + "="*60) print(" 🚀 Multi-MCP Intelligent Assistant 🚀") print("="*60) print("🔗 Connected Services: GitHub • Perplexity • Calendar") print("💡 Powered by OpenAI GPT-4o with Advanced Tool Integration") print("="*60 + "\n") # Validate required environment variables required_vars = { "GITHUB_PERSONAL_ACCESS_TOKEN": GITHUB_TOKEN, "OPENAI_API_KEY": OPENAI_API_KEY, "PERPLEXITY_API_KEY": PERPLEXITY_API_KEY, } missing_vars = [name for name, value in required_vars.items() if not value] if missing_vars: print("❌ ERROR: Missing required environment variables:") for var in missing_vars: print(f" • {var}") print("\nPlease check your .env file and ensure all required variables are set.") return # Generate unique user and session IDs for this terminal session user_id = f"user_{uuid.uuid4().hex[:8]}" session_id = f"session_{uuid.uuid4().hex[:8]}" print(f"👤 User ID: {user_id}") print(f"🔑 Session ID: {session_id}") print("\n🔌 Initializing MCP server connections...\n") # Set up environment variables for MCP servers env = { **os.environ, "GITHUB_PERSONAL_ACCESS_TOKEN": GITHUB_TOKEN, "PERPLEXITY_API_KEY": PERPLEXITY_API_KEY } mcp_servers = [ "npx -y @modelcontextprotocol/server-github", "npx -y @chatmcp/server-perplexity-ask", "npx @gongrzhe/server-calendar-autoauth-mcp", "npx @gongrzhe/server-gmail-autoauth-mcp" ] # Setup database for memory db = SqliteDb(db_file="tmp/multi_mcp_agent.db") # Start the MCP Tools session async with MultiMCPTools(mcp_servers, env=env) as mcp_tools: print("✅ Successfully connected to all MCP servers!") # Create the agent with comprehensive instructions agent = Agent( name="MultiMCPAgent", model=OpenAIChat(id="gpt-4o", api_key=OPENAI_API_KEY), tools=[mcp_tools], description="Advanced AI assistant with GitHub, Perplexity, and Calendar integration", instructions=dedent(f""" You are an elite AI assistant with powerful integrations across multiple platforms. Your mission is to help users be incredibly productive across their digital workspace. 🎯 CORE CAPABILITIES & INSTRUCTIONS: 1. 🔧 TOOL MASTERY • You have DIRECT access to GitHub, Notion, Perplexity, and Calendar through MCP tools • ALWAYS use the appropriate MCP tool calls for any requests related to these platforms • Be proactive in suggesting powerful workflows and automations • Chain multiple tool calls together for complex tasks 2. 📋 GITHUB EXCELLENCE • Repository management: create, clone, fork, search repositories • Issue & PR workflow: create, update, review, merge, comment • Code analysis: search code, review diffs, suggest improvements • Branch management: create, switch, merge branches • Collaboration: manage teams, reviews, and project workflows 4. 🔍 PERPLEXITY RESEARCH • Real-time web search and research • Current events and trending information • Technical documentation and learning resources • Fact-checking and verification 5. 📅 CALENDAR INTEGRATION • Event scheduling and management • Meeting coordination and availability • Deadline tracking and reminders 6. 🎨 INTERACTION PRINCIPLES • Be conversational, helpful, and proactive • Explain what you're doing and why • Suggest follow-up actions and optimizations • Handle errors gracefully with alternative solutions • Ask clarifying questions when needed • Provide rich, formatted responses using markdown 7. 🚀 ADVANCED WORKFLOWS • Cross-platform automation (e.g., GitHub issues → Notion tasks) • Research-driven development (Perplexity → GitHub) • Project management integration • Documentation and knowledge sharing SESSION INFO: • User ID: {user_id} • Session ID: {session_id} • Active Services: GitHub, Notion, Perplexity, Calendar REMEMBER: You're not just answering questions - you're a productivity multiplier. Think big, suggest workflows, and help users achieve more than they imagined possible! """), markdown=True, debug_mode=True, retries=3, db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=10, # Increased for better context retention ) print("\n" + "🎉 " + "="*54 + " 🎉") print(" Multi-MCP Assistant is READY! Let's get productive!") print("🎉 " + "="*54 + " 🎉\n") print("💡 Try these example commands:") print(" • 'Show my recent GitHub repositories'") print(" • 'Search for the latest AI developments'") print(" • 'Schedule a meeting for next week'") print("⚡ Type 'exit', 'quit', or 'bye' to end the session\n") # Start interactive CLI session await agent.acli_app( user_id=user_id, session_id=session_id, user="You", emoji="🤖", stream=True, markdown=True, exit_on=["exit", "quit", "bye", "goodbye"] ) if __name__ == "__main__": asyncio.run(main())
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/mcp_ai_agents/notion_mcp_agent/notion_mcp_agent.py
mcp_ai_agents/notion_mcp_agent/notion_mcp_agent.py
import asyncio import json import os import sys import uuid from textwrap import dedent from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.mcp import MCPTools from agno.db.sqlite import SqliteDb from mcp import StdioServerParameters from dotenv import load_dotenv # Load environment variables load_dotenv() NOTION_TOKEN = os.getenv("NOTION_API_KEY") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") async def main(): print("\n========================================") print(" Notion MCP Terminal Agent") print("========================================\n") # Get configuration from environment or use defaults notion_token = NOTION_TOKEN openai_api_key = OPENAI_API_KEY # Prompt for page ID first page_id = None if len(sys.argv) > 1: # Use command-line argument if provided page_id = sys.argv[1] print(f"Using provided page ID from command line: {page_id}") else: # Ask the user for the page ID print("Please enter your Notion page ID:") print("(You can find this in your page URL, e.g., https://www.notion.so/workspace/Your-Page-1f5b8a8ba283...)") print("The ID is the part after the last dash and before any query parameters") user_input = input("> ") # If user input is empty, prompt again if user_input.strip(): page_id = user_input.strip() print(f"Using provided page ID: {page_id}") else: print("❌ Error: Page ID is required. Please provide a Notion page ID.") return # Generate unique user and session IDs for this terminal session user_id = f"user_{uuid.uuid4().hex[:8]}" session_id = f"session_{uuid.uuid4().hex[:8]}" print(f"User ID: {user_id}") print(f"Session ID: {session_id}") print("\nConnecting to Notion MCP server...\n") # Configure the MCP Tools server_params = StdioServerParameters( command="npx", args=["-y", "@notionhq/notion-mcp-server"], env={ "OPENAPI_MCP_HEADERS": json.dumps( {"Authorization": f"Bearer {notion_token}", "Notion-Version": "2022-06-28"} ) } ) # Start the MCP Tools session async with MCPTools(server_params=server_params) as mcp_tools: print("Connected to Notion MCP server successfully!") db = SqliteDb(db_file="agno.db") # SQLite DB for memory # Create the agent agent = Agent( name="NotionDocsAgent", model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), tools=[mcp_tools], description="Agent to query and modify Notion docs via MCP", instructions=dedent(f""" You are an expert Notion assistant that helps users interact with their Notion pages. IMPORTANT INSTRUCTIONS: 1. You have direct access to Notion documents through MCP tools - make full use of them. 2. ALWAYS use the page ID: {page_id} for all operations unless the user explicitly provides another ID. 3. When asked to update, read, or search pages, ALWAYS use the appropriate MCP tool calls. 4. Be proactive in suggesting actions users can take with their Notion documents. 5. When making changes, explain what you did and confirm the changes were made. 6. If a tool call fails, explain the issue and suggest alternatives. Example tasks you can help with: - Reading page content - Searching for specific information - Adding new content or updating existing content - Creating lists, tables, and other Notion blocks - Explaining page structure - Adding comments to specific blocks The user's current page ID is: {page_id} """), markdown=True, retries=3, db=db, enable_user_memories=True, # This enables Memory for the Agent add_history_to_context=True, # Include conversation history num_history_runs=5, # Keep track of the last 5 interactions ) print("\n\nNotion MCP Agent is ready! Start chatting with your Notion pages.\n") print("Type 'exit' or 'quit' to end the conversation.\n") # Start interactive CLI session with memory and proper session management await agent.acli_app( user_id=user_id, session_id=session_id, user="You", emoji="🤖", stream=True, markdown=True, exit_on=["exit", "quit", "bye", "goodbye"] ) if __name__ == "__main__": asyncio.run(main())
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/mcp_ai_agents/github_mcp_agent/github_agent.py
mcp_ai_agents/github_mcp_agent/github_agent.py
import asyncio import os import streamlit as st from textwrap import dedent from agno.agent import Agent from agno.run.agent import RunOutput from agno.tools.mcp import MCPTools from mcp import StdioServerParameters st.set_page_config(page_title="🐙 GitHub MCP Agent", page_icon="🐙", layout="wide") st.markdown("<h1 class='main-header'>🐙 GitHub MCP Agent</h1>", unsafe_allow_html=True) st.markdown("Explore GitHub repositories with natural language using the Model Context Protocol") with st.sidebar: st.header("🔑 Authentication") openai_key = st.text_input("OpenAI API Key", type="password", help="Required for the AI agent to interpret queries and format results") if openai_key: os.environ["OPENAI_API_KEY"] = openai_key github_token = st.text_input("GitHub Token", type="password", help="Create a token with repo scope at github.com/settings/tokens") if github_token: os.environ["GITHUB_TOKEN"] = github_token st.markdown("---") st.markdown("### Example Queries") st.markdown("**Issues**") st.markdown("- Show me issues by label") st.markdown("- What issues are being actively discussed?") st.markdown("**Pull Requests**") st.markdown("- What PRs need review?") st.markdown("- Show me recent merged PRs") st.markdown("**Repository**") st.markdown("- Show repository health metrics") st.markdown("- Show repository activity patterns") st.markdown("---") st.caption("Note: Always specify the repository in your query if not already selected in the main input.") col1, col2 = st.columns([3, 1]) with col1: repo = st.text_input("Repository", value="Shubhamsaboo/awesome-llm-apps", help="Format: owner/repo") with col2: query_type = st.selectbox("Query Type", [ "Issues", "Pull Requests", "Repository Activity", "Custom" ]) if query_type == "Issues": query_template = f"Find issues labeled as bugs in {repo}" elif query_type == "Pull Requests": query_template = f"Show me recent merged PRs in {repo}" elif query_type == "Repository Activity": query_template = f"Analyze code quality trends in {repo}" else: query_template = "" query = st.text_area("Your Query", value=query_template, placeholder="What would you like to know about this repository?") async def run_github_agent(message): if not os.getenv("GITHUB_TOKEN"): return "Error: GitHub token not provided" if not os.getenv("OPENAI_API_KEY"): return "Error: OpenAI API key not provided" try: server_params = StdioServerParameters( command="docker", args=[ "run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "-e", "GITHUB_TOOLSETS", "ghcr.io/github/github-mcp-server" ], env={ **os.environ, "GITHUB_PERSONAL_ACCESS_TOKEN": os.getenv('GITHUB_TOKEN'), "GITHUB_TOOLSETS": "repos,issues,pull_requests" } ) async with MCPTools(server_params=server_params) as mcp_tools: agent = Agent( tools=[mcp_tools], instructions=dedent("""\ You are a GitHub assistant. Help users explore repositories and their activity. - Provide organized, concise insights about the repository - Focus on facts and data from the GitHub API - Use markdown formatting for better readability - Present numerical data in tables when appropriate - Include links to relevant GitHub pages when helpful """), markdown=True, ) response: RunOutput = await asyncio.wait_for(agent.arun(message), timeout=120.0) return response.content except asyncio.TimeoutError: return "Error: Request timed out after 120 seconds" except Exception as e: return f"Error: {str(e)}" if st.button("🚀 Run Query", type="primary", use_container_width=True): if not openai_key: st.error("Please enter your OpenAI API key in the sidebar") elif not github_token: st.error("Please enter your GitHub token in the sidebar") elif not query: st.error("Please enter a query") else: with st.spinner("Analyzing GitHub repository..."): if repo and repo not in query: full_query = f"{query} in {repo}" else: full_query = query result = asyncio.run(run_github_agent(full_query)) st.markdown("### Results") st.markdown(result) if 'result' not in locals(): st.markdown( """<div class='info-box'> <h4>How to use this app:</h4> <ol> <li>Enter your <strong>OpenAI API key</strong> in the sidebar (powers the AI agent)</li> <li>Enter your <strong>GitHub token</strong> in the sidebar</li> <li>Specify a repository (e.g., Shubhamsaboo/awesome-llm-apps)</li> <li>Select a query type or write your own</li> <li>Click 'Run Query' to see results</li> </ol> <p><strong>How it works:</strong></p> <ul> <li>Uses the official GitHub MCP server via Docker for real-time access to GitHub API</li> <li>AI Agent (powered by OpenAI) interprets your queries and calls appropriate GitHub APIs</li> <li>Results are formatted in readable markdown with insights and links</li> <li>Queries work best when focused on specific aspects like issues, PRs, or repository info</li> </ul> </div>""", unsafe_allow_html=True )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/mixture_of_agents/mixture-of-agents.py
starter_ai_agents/mixture_of_agents/mixture-of-agents.py
import streamlit as st import asyncio import os from together import AsyncTogether, Together # Set up the Streamlit app st.title("Mixture-of-Agents LLM App") # Get API key from the user together_api_key = st.text_input("Enter your Together API Key:", type="password") if together_api_key: os.environ["TOGETHER_API_KEY"] = together_api_key client = Together(api_key=together_api_key) async_client = AsyncTogether(api_key=together_api_key) # Define the models reference_models = [ "Qwen/Qwen2-72B-Instruct", "Qwen/Qwen1.5-72B-Chat", "mistralai/Mixtral-8x22B-Instruct-v0.1", "databricks/dbrx-instruct", ] aggregator_model = "mistralai/Mixtral-8x22B-Instruct-v0.1" # Define the aggregator system prompt aggregator_system_prompt = """You have been provided with a set of responses from various open-source models to the latest user query. Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability. Responses from models:""" # Get user input user_prompt = st.text_input("Enter your question:") async def run_llm(model): """Run a single LLM call with a reference model.""" response = await async_client.chat.completions.create( model=model, messages=[{"role": "user", "content": user_prompt}], temperature=0.7, max_tokens=512, ) return model, response.choices[0].message.content async def main(): results = await asyncio.gather(*[run_llm(model) for model in reference_models]) # Display individual model responses st.subheader("Individual Model Responses:") for model, response in results: with st.expander(f"Response from {model}"): st.write(response) # Aggregate responses st.subheader("Aggregated Response:") finalStream = client.chat.completions.create( model=aggregator_model, messages=[ {"role": "system", "content": aggregator_system_prompt}, {"role": "user", "content": ",".join(response for _, response in results)}, ], stream=True, ) # Display aggregated response response_container = st.empty() full_response = "" for chunk in finalStream: content = chunk.choices[0].delta.content or "" full_response += content response_container.markdown(full_response + "▌") response_container.markdown(full_response) if st.button("Get Answer"): if user_prompt: asyncio.run(main()) else: st.warning("Please enter a question.") else: st.warning("Please enter your Together API key to use the app.") # Add some information about the app st.sidebar.title("About this app") st.sidebar.write( "This app demonstrates a Mixture-of-Agents approach using multiple Language Models (LLMs) " "to answer a single question." ) st.sidebar.subheader("How it works:") st.sidebar.markdown( """ 1. The app sends your question to multiple LLMs: - Qwen/Qwen2-72B-Instruct - Qwen/Qwen1.5-72B-Chat - mistralai/Mixtral-8x22B-Instruct-v0.1 - databricks/dbrx-instruct 2. Each model provides its own response 3. All responses are then aggregated using Mixtral-8x22B-Instruct-v0.1 4. The final aggregated response is displayed """ ) st.sidebar.write( "This approach allows for a more comprehensive and balanced answer by leveraging multiple AI models." )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/web_scrapping_ai_agent/local_ai_scrapper.py
starter_ai_agents/web_scrapping_ai_agent/local_ai_scrapper.py
# Import the required libraries import streamlit as st from scrapegraphai.graphs import SmartScraperGraph # Set up the Streamlit app st.title("Web Scrapping AI Agent 🕵️‍♂️") st.caption("This app allows you to scrape a website using Llama 3.2") # Set up the configuration for the SmartScraperGraph graph_config = { "llm": { "model": "ollama/llama3.2", "temperature": 0, "format": "json", # Ollama needs the format to be specified explicitly "base_url": "http://localhost:11434", # set Ollama URL }, "embeddings": { "model": "ollama/nomic-embed-text", "base_url": "http://localhost:11434", # set Ollama URL }, "verbose": True, } # Get the URL of the website to scrape url = st.text_input("Enter the URL of the website you want to scrape") # Get the user prompt user_prompt = st.text_input("What you want the AI agent to scrape from the website?") # Create a SmartScraperGraph object smart_scraper_graph = SmartScraperGraph( prompt=user_prompt, source=url, config=graph_config ) # Scrape the website if st.button("Scrape"): result = smart_scraper_graph.run() st.write(result)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/web_scrapping_ai_agent/ai_scrapper.py
starter_ai_agents/web_scrapping_ai_agent/ai_scrapper.py
# Import the required libraries import streamlit as st from scrapegraphai.graphs import SmartScraperGraph # Set up the Streamlit app st.title("Web Scrapping AI Agent 🕵️‍♂️") st.caption("This app allows you to scrape a website using OpenAI API") # Get OpenAI API key from user openai_access_token = st.text_input("OpenAI API Key", type="password") if openai_access_token: model = st.radio( "Select the model", ["gpt-4o", "gpt-5"], index=0, ) graph_config = { "llm": { "api_key": openai_access_token, "model": model, }, } # Get the URL of the website to scrape url = st.text_input("Enter the URL of the website you want to scrape") # Get the user prompt user_prompt = st.text_input("What you want the AI agent to scrae from the website?") # Create a SmartScraperGraph object smart_scraper_graph = SmartScraperGraph( prompt=user_prompt, source=url, config=graph_config ) # Scrape the website if st.button("Scrape"): result = smart_scraper_graph.run() st.write(result)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/xai_finance_agent/xai_finance_agent.py
starter_ai_agents/xai_finance_agent/xai_finance_agent.py
# import necessary python libraries from agno.agent import Agent from agno.models.xai import xAI from agno.tools.yfinance import YFinanceTools from agno.tools.duckduckgo import DuckDuckGoTools from agno.os import AgentOS # create the AI finance agent agent = Agent( name="xAI Finance Agent", model = xAI(id="grok-4-1-fast"), tools=[DuckDuckGoTools(), YFinanceTools()], instructions = ["Always use tables to display financial/numerical data. For text data use bullet points and small paragrpahs."], debug_mode = True, markdown = True, ) # UI for finance agent agent_os = AgentOS(agents=[agent]) app = agent_os.get_app() if __name__ == "__main__": agent_os.serve(app="xai_finance_agent:app", reload=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/opeani_research_agent/research_agent.py
starter_ai_agents/opeani_research_agent/research_agent.py
import os import uuid import asyncio import streamlit as st from datetime import datetime from dotenv import load_dotenv from agents import ( Agent, Runner, WebSearchTool, function_tool, handoff, trace, ) from pydantic import BaseModel # Load environment variables load_dotenv() # Set up page configuration st.set_page_config( page_title="OpenAI Researcher Agent", page_icon="📰", layout="wide", initial_sidebar_state="expanded" ) # Make sure API key is set if not os.environ.get("OPENAI_API_KEY"): st.error("Please set your OPENAI_API_KEY environment variable") st.stop() # App title and description st.title("📰 OpenAI Researcher Agent") st.subheader("Powered by OpenAI Agents SDK") st.markdown(""" This app demonstrates the power of OpenAI's Agents SDK by creating a multi-agent system that researches news topics and generates comprehensive research reports. """) # Define data models class ResearchPlan(BaseModel): topic: str search_queries: list[str] focus_areas: list[str] class ResearchReport(BaseModel): title: str outline: list[str] report: str sources: list[str] word_count: int # Custom tool for saving facts found during research @function_tool def save_important_fact(fact: str, source: str = None) -> str: """Save an important fact discovered during research. Args: fact: The important fact to save source: Optional source of the fact Returns: Confirmation message """ if "collected_facts" not in st.session_state: st.session_state.collected_facts = [] st.session_state.collected_facts.append({ "fact": fact, "source": source or "Not specified", "timestamp": datetime.now().strftime("%H:%M:%S") }) return f"Fact saved: {fact}" # Define the agents research_agent = Agent( name="Research Agent", instructions="You are a research assistant. Given a search term, you search the web for that term and" "produce a concise summary of the results. The summary must 2-3 paragraphs and less than 300" "words. Capture the main points. Write succintly, no need to have complete sentences or good" "grammar. This will be consumed by someone synthesizing a report, so its vital you capture the" "essence and ignore any fluff. Do not include any additional commentary other than the summary" "itself.", model="gpt-4o-mini", tools=[ WebSearchTool(), save_important_fact ], ) editor_agent = Agent( name="Editor Agent", handoff_description="A senior researcher who writes comprehensive research reports", instructions="You are a senior researcher tasked with writing a cohesive report for a research query. " "You will be provided with the original query, and some initial research done by a research " "assistant.\n" "You should first come up with an outline for the report that describes the structure and " "flow of the report. Then, generate the report and return that as your final output.\n" "The final output should be in markdown format, and it should be lengthy and detailed. Aim " "for 5-10 pages of content, at least 1000 words.", model="gpt-4o-mini", output_type=ResearchReport, ) triage_agent = Agent( name="Triage Agent", instructions="""You are the coordinator of this research operation. Your job is to: 1. Understand the user's research topic 2. Create a research plan with the following elements: - topic: A clear statement of the research topic - search_queries: A list of 3-5 specific search queries that will help gather information - focus_areas: A list of 3-5 key aspects of the topic to investigate 3. Hand off to the Research Agent to collect information 4. After research is complete, hand off to the Editor Agent who will write a comprehensive report Make sure to return your plan in the expected structured format with topic, search_queries, and focus_areas. """, handoffs=[ handoff(research_agent), handoff(editor_agent) ], model="gpt-4o-mini", output_type=ResearchPlan, ) # Create sidebar for input and controls with st.sidebar: st.header("Research Topic") user_topic = st.text_input( "Enter a topic to research:", ) start_button = st.button("Start Research", type="primary", disabled=not user_topic) st.divider() st.subheader("Example Topics") example_topics = [ "What are the best cruise lines in USA for first-time travelers who have never been on a cruise?", "What are the best affordable espresso machines for someone upgrading from a French press?", "What are the best off-the-beaten-path destinations in India for a first-time solo traveler?" ] for topic in example_topics: if st.button(topic): user_topic = topic start_button = True # Main content area with two tabs tab1, tab2 = st.tabs(["Research Process", "Report"]) # Initialize session state for storing results if "conversation_id" not in st.session_state: st.session_state.conversation_id = str(uuid.uuid4().hex[:16]) if "collected_facts" not in st.session_state: st.session_state.collected_facts = [] if "research_done" not in st.session_state: st.session_state.research_done = False if "report_result" not in st.session_state: st.session_state.report_result = None # Main research function async def run_research(topic): # Reset state for new research st.session_state.collected_facts = [] st.session_state.research_done = False st.session_state.report_result = None with tab1: message_container = st.container() # Create error handling container error_container = st.empty() # Create a trace for the entire workflow with trace("News Research", group_id=st.session_state.conversation_id): # Start with the triage agent with message_container: st.write("🔍 **Triage Agent**: Planning research approach...") triage_result = await Runner.run( triage_agent, f"Research this topic thoroughly: {topic}. This research will be used to create a comprehensive research report." ) # Check if the result is a ResearchPlan object or a string if hasattr(triage_result.final_output, 'topic'): research_plan = triage_result.final_output plan_display = { "topic": research_plan.topic, "search_queries": research_plan.search_queries, "focus_areas": research_plan.focus_areas } else: # Fallback if we don't get the expected output type research_plan = { "topic": topic, "search_queries": ["Researching " + topic], "focus_areas": ["General information about " + topic] } plan_display = research_plan with message_container: st.write("📋 **Research Plan**:") st.json(plan_display) # Display facts as they're collected fact_placeholder = message_container.empty() # Check for new facts periodically previous_fact_count = 0 for i in range(15): # Check more times to allow for more comprehensive research current_facts = len(st.session_state.collected_facts) if current_facts > previous_fact_count: with fact_placeholder.container(): st.write("📚 **Collected Facts**:") for fact in st.session_state.collected_facts: st.info(f"**Fact**: {fact['fact']}\n\n**Source**: {fact['source']}") previous_fact_count = current_facts await asyncio.sleep(1) # Editor Agent phase with message_container: st.write("📝 **Editor Agent**: Creating comprehensive research report...") try: report_result = await Runner.run( editor_agent, triage_result.to_input_list() ) st.session_state.report_result = report_result.final_output with message_container: st.write("✅ **Research Complete! Report Generated.**") # Preview a snippet of the report if hasattr(report_result.final_output, 'report'): report_preview = report_result.final_output.report[:300] + "..." else: report_preview = str(report_result.final_output)[:300] + "..." st.write("📄 **Report Preview**:") st.markdown(report_preview) st.write("*See the Report tab for the full document.*") except Exception as e: st.error(f"Error generating report: {str(e)}") # Fallback to display raw agent response if hasattr(triage_result, 'new_items'): messages = [item for item in triage_result.new_items if hasattr(item, 'content')] if messages: raw_content = "\n\n".join([str(m.content) for m in messages if m.content]) st.session_state.report_result = raw_content with message_container: st.write("⚠️ **Research completed but there was an issue generating the structured report.**") st.write("Raw research results are available in the Report tab.") st.session_state.research_done = True # Run the research when the button is clicked if start_button: with st.spinner(f"Researching: {user_topic}"): try: asyncio.run(run_research(user_topic)) except Exception as e: st.error(f"An error occurred during research: {str(e)}") # Set a basic report result so the user gets something st.session_state.report_result = f"# Research on {user_topic}\n\nUnfortunately, an error occurred during the research process. Please try again later or with a different topic.\n\nError details: {str(e)}" st.session_state.research_done = True # Display results in the Report tab with tab2: if st.session_state.research_done and st.session_state.report_result: report = st.session_state.report_result # Handle different possible types of report results if hasattr(report, 'title'): # We have a properly structured ResearchReport object title = report.title # Display outline if available if hasattr(report, 'outline') and report.outline: with st.expander("Report Outline", expanded=True): for i, section in enumerate(report.outline): st.markdown(f"{i+1}. {section}") # Display word count if available if hasattr(report, 'word_count'): st.info(f"Word Count: {report.word_count}") # Display the full report in markdown if hasattr(report, 'report'): report_content = report.report st.markdown(report_content) else: report_content = str(report) st.markdown(report_content) # Display sources if available if hasattr(report, 'sources') and report.sources: with st.expander("Sources"): for i, source in enumerate(report.sources): st.markdown(f"{i+1}. {source}") # Add download button for the report st.download_button( label="Download Report", data=report_content, file_name=f"{title.replace(' ', '_')}.md", mime="text/markdown" ) else: # Handle string or other type of response report_content = str(report) title = user_topic.title() st.title(f"{title}") st.markdown(report_content) # Add download button for the report st.download_button( label="Download Report", data=report_content, file_name=f"{title.replace(' ', '_')}.md", mime="text/markdown" )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_medical_imaging_agent/ai_medical_imaging.py
starter_ai_agents/ai_medical_imaging_agent/ai_medical_imaging.py
import os from PIL import Image as PILImage from agno.agent import Agent from agno.models.google import Gemini from agno.run.agent import RunOutput import streamlit as st from agno.tools.duckduckgo import DuckDuckGoTools from agno.media import Image as AgnoImage if "GOOGLE_API_KEY" not in st.session_state: st.session_state.GOOGLE_API_KEY = None with st.sidebar: st.title("ℹ️ Configuration") if not st.session_state.GOOGLE_API_KEY: api_key = st.text_input( "Enter your Google API Key:", type="password" ) st.caption( "Get your API key from [Google AI Studio]" "(https://aistudio.google.com/apikey) 🔑" ) if api_key: st.session_state.GOOGLE_API_KEY = api_key st.success("API Key saved!") st.rerun() else: st.success("API Key is configured") if st.button("🔄 Reset API Key"): st.session_state.GOOGLE_API_KEY = None st.rerun() st.info( "This tool provides AI-powered analysis of medical imaging data using " "advanced computer vision and radiological expertise." ) st.warning( "⚠DISCLAIMER: This tool is for educational and informational purposes only. " "All analyses should be reviewed by qualified healthcare professionals. " "Do not make medical decisions based solely on this analysis." ) medical_agent = Agent( model=Gemini( id="gemini-2.5-pro", api_key=st.session_state.GOOGLE_API_KEY ), tools=[DuckDuckGoTools()], markdown=True ) if st.session_state.GOOGLE_API_KEY else None if not medical_agent: st.warning("Please configure your API key in the sidebar to continue") # Medical Analysis Query query = """ You are a highly skilled medical imaging expert with extensive knowledge in radiology and diagnostic imaging. Analyze the patient's medical image and structure your response as follows: ### 1. Image Type & Region - Specify imaging modality (X-ray/MRI/CT/Ultrasound/etc.) - Identify the patient's anatomical region and positioning - Comment on image quality and technical adequacy ### 2. Key Findings - List primary observations systematically - Note any abnormalities in the patient's imaging with precise descriptions - Include measurements and densities where relevant - Describe location, size, shape, and characteristics - Rate severity: Normal/Mild/Moderate/Severe ### 3. Diagnostic Assessment - Provide primary diagnosis with confidence level - List differential diagnoses in order of likelihood - Support each diagnosis with observed evidence from the patient's imaging - Note any critical or urgent findings ### 4. Patient-Friendly Explanation - Explain the findings in simple, clear language that the patient can understand - Avoid medical jargon or provide clear definitions - Include visual analogies if helpful - Address common patient concerns related to these findings ### 5. Research Context IMPORTANT: Use the DuckDuckGo search tool to: - Find recent medical literature about similar cases - Search for standard treatment protocols - Provide a list of relevant medical links of them too - Research any relevant technological advances - Include 2-3 key references to support your analysis Format your response using clear markdown headers and bullet points. Be concise yet thorough. """ st.title("🏥 Medical Imaging Diagnosis Agent") st.write("Upload a medical image for professional analysis") # Create containers for better organization upload_container = st.container() image_container = st.container() analysis_container = st.container() with upload_container: uploaded_file = st.file_uploader( "Upload Medical Image", type=["jpg", "jpeg", "png", "dicom"], help="Supported formats: JPG, JPEG, PNG, DICOM" ) if uploaded_file is not None: with image_container: col1, col2, col3 = st.columns([1, 2, 1]) with col2: image = PILImage.open(uploaded_file) width, height = image.size aspect_ratio = width / height new_width = 500 new_height = int(new_width / aspect_ratio) resized_image = image.resize((new_width, new_height)) st.image( resized_image, caption="Uploaded Medical Image", use_container_width=True ) analyze_button = st.button( "🔍 Analyze Image", type="primary", use_container_width=True ) with analysis_container: if analyze_button: with st.spinner("🔄 Analyzing image... Please wait."): try: temp_path = "temp_resized_image.png" resized_image.save(temp_path) # Create AgnoImage object agno_image = AgnoImage(filepath=temp_path) # Run analysis response: RunOutput = medical_agent.run(query, images=[agno_image]) st.markdown("### 📋 Analysis Results") st.markdown("---") st.markdown(response.content) st.markdown("---") st.caption( "Note: This analysis is generated by AI and should be reviewed by " "a qualified healthcare professional." ) except Exception as e: st.error(f"Analysis error: {e}") else: st.info("👆 Please upload a medical image to begin analysis")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_life_insurance_advisor_agent/life_insurance_advisor_agent.py
starter_ai_agents/ai_life_insurance_advisor_agent/life_insurance_advisor_agent.py
import json import os from datetime import datetime from typing import Any, Dict, Optional import streamlit as st from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.e2b import E2BTools from agno.tools.firecrawl import FirecrawlTools st.set_page_config( page_title="Life Insurance Coverage Advisor", page_icon="🛡️", layout="centered", ) st.title("🛡️ Life Insurance Coverage Advisor") st.caption( "Prototype Streamlit app powered by Agno Agents, OpenAI GPT-5, E2B sandboxed code execution, and Firecrawl search." ) # ----------------------------------------------------------------------------- # Sidebar configuration for API keys # ----------------------------------------------------------------------------- with st.sidebar: st.header("API Keys") st.write("All keys stay local in your browser session.") openai_api_key = st.text_input( "OpenAI API Key", type="password", key="openai_api_key", help="Create one at https://platform.openai.com/api-keys", ) firecrawl_api_key = st.text_input( "Firecrawl API Key", type="password", key="firecrawl_api_key", help="Create one at https://www.firecrawl.dev/app/api-keys", ) e2b_api_key = st.text_input( "E2B API Key", type="password", key="e2b_api_key", help="Create one at https://e2b.dev", ) st.markdown("---") st.caption( "The agent uses E2B for deterministic coverage math and Firecrawl for fresh term-life product research." ) # ----------------------------------------------------------------------------- # Helper functions # ----------------------------------------------------------------------------- def safe_number(value: Any) -> float: """Best-effort conversion to float for agent outputs.""" if value is None: return 0.0 try: return float(value) except (TypeError, ValueError): if isinstance(value, str): stripped = value for token in [",", "$", "€", "£", "₹", "C$", "A$"]: stripped = stripped.replace(token, "") stripped = stripped.strip() try: return float(stripped) except ValueError: return 0.0 return 0.0 def format_currency(amount: float, currency_code: str) -> str: symbol_map = { "USD": "$", "EUR": "€", "GBP": "£", "CAD": "C$", "AUD": "A$", "INR": "₹", } code = (currency_code or "USD").upper() symbol = symbol_map.get(code, "") formatted = f"{amount:,.0f}" return f"{symbol}{formatted}" if symbol else f"{formatted} {code}" def extract_json(payload: str) -> Optional[Dict[str, Any]]: if not payload: return None content = payload.strip() if content.startswith("```"): lines = content.splitlines() if lines[0].startswith("```"): lines = lines[1:] if lines and lines[-1].startswith("```"): lines = lines[:-1] content = "\n".join(lines).strip() try: return json.loads(content) except json.JSONDecodeError: return None def parse_percentage(value: Any, fallback: float = 0.02) -> float: """Convert percentage-like values to decimal form (e.g., "2%" -> 0.02).""" if value is None: return fallback if isinstance(value, (int, float)): # assume already decimal if less than 1, otherwise treat as percentage value return float(value) if value < 1 else float(value) / 100 if isinstance(value, str): cleaned = value.strip().replace("%", "") try: numeric = float(cleaned) return numeric if numeric < 1 else numeric / 100 except ValueError: return fallback return fallback def compute_local_breakdown(profile: Dict[str, Any], real_rate: float) -> Dict[str, float]: """Replicate the coverage math locally so we can show it to the user.""" income = safe_number(profile.get("annual_income")) years = max(0, int(profile.get("income_replacement_years", 0) or 0)) total_debt = safe_number(profile.get("total_debt")) savings = safe_number(profile.get("available_savings")) existing_cover = safe_number(profile.get("existing_life_insurance")) if real_rate <= 0: discounted_income = income * years annuity_factor = years else: annuity_factor = (1 - (1 + real_rate) ** (-years)) / real_rate if years else 0 discounted_income = income * annuity_factor assets_offset = savings + existing_cover recommended = max(0.0, discounted_income + total_debt - assets_offset) return { "income": income, "years": years, "real_rate": real_rate, "annuity_factor": annuity_factor, "discounted_income": discounted_income, "debt": total_debt, "assets_offset": -assets_offset, "recommended": recommended, } @st.cache_resource(show_spinner=False) def get_agent(openai_key: str, firecrawl_key: str, e2b_key: str) -> Optional[Agent]: if not (openai_key and firecrawl_key and e2b_key): return None os.environ["OPENAI_API_KEY"] = openai_key os.environ["FIRECRAWL_API_KEY"] = firecrawl_key os.environ["E2B_API_KEY"] = e2b_key return Agent( name="Life Insurance Advisor", model=OpenAIChat( id="gpt-5-mini-2025-08-07", api_key=openai_key, ), tools=[ E2BTools(timeout=180), FirecrawlTools( api_key=firecrawl_key, enable_search=True, enable_crawl=True, enable_scrape=False, search_params={"limit": 5, "lang": "en"}, ), ], instructions=[ "You provide conservative life insurance guidance. Your workflow is strictly:", "1. ALWAYS call `run_python_code` from the E2B tools to compute the coverage recommendation using the provided client JSON.", " - Treat missing numeric values as 0.", " - Use a default real discount rate of 2% when discounting income replacement cash flows.", " - Compute: discounted_income = annual_income * ((1 - (1 + r)**(-income_replacement_years)) / r).", " - Recommended coverage = max(0, discounted_income + total_debt - savings - existing_life_insurance).", " - Print a JSON with keys: coverage_amount, coverage_currency, breakdown, assumptions.", "2. Use Firecrawl `search` followed by optional `scrape_website` calls to gather up-to-date term life insurance options for the client's region.", "3. Respond ONLY with JSON containing the following top-level keys: coverage_amount, coverage_currency, breakdown, assumptions, recommendations, research_notes, timestamp.", " - `coverage_amount`: integer of total recommended coverage.", " - `coverage_currency`: 3-letter currency code.", " - `breakdown`: include income_replacement, debt_obligations, assets_offset, methodology.", " - `assumptions`: include income_replacement_years, real_discount_rate, additional_notes.", " - `recommendations`: list of up to three objects (name, summary, link, source).", " - `research_notes`: brief disclaimer + recency of sources.", " - `timestamp`: ISO 8601 date-time string.", "Do not include markdown, commentary, or tool call traces in the final JSON output.", ], markdown=False, ) # ----------------------------------------------------------------------------- # User input form # ----------------------------------------------------------------------------- st.subheader("Tell us about yourself") with st.form("coverage_form"): col1, col2 = st.columns(2) with col1: age = st.number_input("Age", min_value=18, max_value=85, value=35) annual_income = st.number_input( "Annual Income", min_value=0.0, value=85000.0, step=1000.0, ) dependents = st.number_input( "Dependents", min_value=0, max_value=10, value=2, step=1, ) location = st.text_input( "Country / State", value="United States", help="Used to localize recommended insurers.", ) with col2: total_debt = st.number_input( "Total Outstanding Debt (incl. mortgage)", min_value=0.0, value=200000.0, step=5000.0, ) savings = st.number_input( "Savings & Investments available to dependents", min_value=0.0, value=50000.0, step=5000.0, ) existing_cover = st.number_input( "Existing Life Insurance", min_value=0.0, value=100000.0, step=5000.0, ) currency = st.selectbox( "Currency", options=["USD", "CAD", "EUR", "GBP", "AUD", "INR"], index=0, ) income_replacement_years = st.selectbox( "Income Replacement Horizon", options=[5, 10, 15], index=1, help="Number of years your income should be replaced for dependents.", ) submitted = st.form_submit_button("Generate Coverage & Options") def build_client_profile() -> Dict[str, Any]: return { "age": age, "annual_income": annual_income, "dependents": dependents, "location": location, "total_debt": total_debt, "available_savings": savings, "existing_life_insurance": existing_cover, "income_replacement_years": income_replacement_years, "currency": currency, "request_timestamp": datetime.utcnow().isoformat(), } def render_recommendations(result: Dict[str, Any], profile: Dict[str, Any]) -> None: coverage_currency = result.get("coverage_currency", currency) coverage_amount = safe_number(result.get("coverage_amount", 0)) st.subheader("Recommended Coverage") st.metric( label="Total Coverage Needed", value=format_currency(coverage_amount, coverage_currency), ) assumptions = result.get("assumptions", {}) real_rate = parse_percentage(assumptions.get("real_discount_rate", "2%")) local_breakdown = compute_local_breakdown(profile, real_rate) st.subheader("Calculation Inputs") st.table( { "Input": [ "Annual income", "Income replacement horizon", "Total debt", "Liquid assets", "Existing life cover", "Real discount rate", ], "Value": [ format_currency(local_breakdown["income"], coverage_currency), f"{local_breakdown['years']} years", format_currency(local_breakdown["debt"], coverage_currency), format_currency(safe_number(profile.get("available_savings")), coverage_currency), format_currency(safe_number(profile.get("existing_life_insurance")), coverage_currency), f"{real_rate * 100:.2f}%", ], } ) st.subheader("Step-by-step Coverage Math") step_rows = [ ("Annuity factor", f"{local_breakdown['annuity_factor']:.3f}"), ("Discounted income replacement", format_currency(local_breakdown["discounted_income"], coverage_currency)), ("+ Outstanding debt", format_currency(local_breakdown["debt"], coverage_currency)), ("- Assets & existing cover", format_currency(local_breakdown["assets_offset"], coverage_currency)), ("= Formula estimate", format_currency(local_breakdown["recommended"], coverage_currency)), ] step_rows.append(("= Agent recommendation", format_currency(coverage_amount, coverage_currency))) st.table({"Step": [s for s, _ in step_rows], "Amount": [a for _, a in step_rows]}) breakdown = result.get("breakdown", {}) with st.expander("How this number was calculated", expanded=True): st.markdown( f"- Income replacement value: {format_currency(safe_number(breakdown.get('income_replacement')), coverage_currency)}" ) st.markdown( f"- Debt obligations: {format_currency(safe_number(breakdown.get('debt_obligations')), coverage_currency)}" ) assets_offset = safe_number(breakdown.get("assets_offset")) st.markdown( f"- Assets & existing cover offset: {format_currency(assets_offset, coverage_currency)}" ) methodology = breakdown.get("methodology") if methodology: st.caption(methodology) recommendations = result.get("recommendations", []) if recommendations: st.subheader("Top Term Life Options") for idx, option in enumerate(recommendations, start=1): with st.container(): name = option.get("name", "Unnamed Product") summary = option.get("summary", "No summary provided.") st.markdown(f"**{idx}. {name}** — {summary}") link = option.get("link") if link: st.markdown(f"[View details]({link})") source = option.get("source") if source: st.caption(f"Source: {source}") st.markdown("---") with st.expander("Model assumptions"): st.write( { "Income replacement years": assumptions.get( "income_replacement_years", income_replacement_years ), "Real discount rate": assumptions.get("real_discount_rate", "2%"), "Notes": assumptions.get("additional_notes", ""), } ) if result.get("research_notes"): st.caption(result["research_notes"]) if result.get("timestamp"): st.caption(f"Generated: {result['timestamp']}") with st.expander("Agent response JSON"): st.json(result) if submitted: if not all([openai_api_key, firecrawl_api_key, e2b_api_key]): st.error("Please configure OpenAI, Firecrawl, and E2B API keys in the sidebar.") st.stop() advisor_agent = get_agent(openai_api_key, firecrawl_api_key, e2b_api_key) if not advisor_agent: st.error("Unable to initialize the advisor. Double-check API keys.") st.stop() client_profile = build_client_profile() user_prompt = ( "You will receive a JSON object describing the client's profile. Follow your workflow instructions to calculate coverage and surface suitable products.\n" f"Client profile JSON: {json.dumps(client_profile)}" ) with st.spinner("Consulting advisor agent..."): response = advisor_agent.run(user_prompt, stream=False) parsed = extract_json(response.content if response else "") if not parsed: st.error("The agent returned an unexpected response. Enable debug below to inspect raw output.") with st.expander("Raw agent output"): st.write(response.content if response else "<empty>") else: render_recommendations(parsed, client_profile) with st.expander("Agent debug"): st.write(response.content) st.divider() st.caption( "This prototype is for educational use only and does not provide licensed financial advice. " "Verify all recommendations with a qualified professional and the insurers listed." )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_blog_to_podcast_agent/blog_to_podcast_agent.py
starter_ai_agents/ai_blog_to_podcast_agent/blog_to_podcast_agent.py
import os from uuid import uuid4 from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.openai import OpenAIChat from agno.tools.firecrawl import FirecrawlTools from elevenlabs import ElevenLabs import streamlit as st # Streamlit Setup st.set_page_config(page_title="📰 ➡️ 🎙️ Blog to Podcast", page_icon="🎙️") st.title("📰 ➡️ 🎙️ Blog to Podcast Agent") # API Keys (Runtime Input) st.sidebar.header("🔑 API Keys") openai_key = st.sidebar.text_input("OpenAI API Key", type="password") elevenlabs_key = st.sidebar.text_input("ElevenLabs API Key", type="password") firecrawl_key = st.sidebar.text_input("Firecrawl API Key", type="password") # Blog URL Input url = st.text_input("Enter Blog URL:", "") # Generate Button if st.button("🎙️ Generate Podcast", disabled=not all([openai_key, elevenlabs_key, firecrawl_key])): if not url.strip(): st.warning("Please enter a blog URL") else: with st.spinner("Scraping blog and generating podcast..."): try: # Set API keys os.environ["OPENAI_API_KEY"] = openai_key os.environ["FIRECRAWL_API_KEY"] = firecrawl_key # Create agent for scraping and summarization agent = Agent( name="Blog Summarizer", model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools()], instructions=[ "Scrape the blog URL and create a concise, engaging summary (max 2000 characters) suitable for a podcast.", "The summary should be conversational and capture the main points." ], ) # Get summary response: RunOutput = agent.run(f"Scrape and summarize this blog for a podcast: {url}") summary = response.content if hasattr(response, 'content') else str(response) if summary: # Initialize ElevenLabs client and generate audio client = ElevenLabs(api_key=elevenlabs_key) # Generate audio using text_to_speech.convert audio_generator = client.text_to_speech.convert( text=summary, voice_id="JBFqnCBsd6RMkjVDRZzb", model_id="eleven_multilingual_v2" ) # Collect audio chunks if it's a generator audio_chunks = [] for chunk in audio_generator: if chunk: audio_chunks.append(chunk) audio_bytes = b"".join(audio_chunks) # Display audio st.success("Podcast generated! 🎧") st.audio(audio_bytes, format="audio/mp3") # Download button st.download_button( "Download Podcast", audio_bytes, "podcast.mp3", "audio/mp3" ) # Show summary with st.expander("📄 Podcast Summary"): st.write(summary) else: st.error("Failed to generate summary") except Exception as e: st.error(f"Error: {e}")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_travel_agent/local_travel_agent.py
starter_ai_agents/ai_travel_agent/local_travel_agent.py
from textwrap import dedent from agno.agent import Agent from agno.run.agent import RunOutput from agno.tools.serpapi import SerpApiTools import streamlit as st import re from agno.models.ollama import Ollama from icalendar import Calendar, Event from datetime import datetime, timedelta def generate_ics_content(plan_text:str, start_date: datetime = None) -> bytes: """ Generate an ICS calendar file from a travel itinerary text. Args: plan_text: The travel itinerary text start_date: Optional start date for the itinerary (defaults to today) Returns: bytes: The ICS file content as bytes """ cal = Calendar() cal.add('prodid','-//AI Travel Planner//github.com//' ) cal.add('version', '2.0') if start_date is None: start_date = datetime.today() # Split the plan into days day_pattern = re.compile(r'Day (\d+)[:\s]+(.*?)(?=Day \d+|$)', re.DOTALL) days = day_pattern.findall(plan_text) if not days: # If no day pattern found, create a single all-day event with the entire content event = Event() event.add('summary', "Travel Itinerary") event.add('description', plan_text) event.add('dtstart', start_date.date()) event.add('dtend', start_date.date()) event.add("dtstamp", datetime.now()) cal.add_component(event) else: # Process each day for day_num, day_content in days: day_num = int(day_num) current_date = start_date + timedelta(days=day_num - 1) # Create a single event for the entire day event = Event() event.add('summary', f"Day {day_num} Itinerary") event.add('description', day_content.strip()) # Make it an all-day event event.add('dtstart', current_date.date()) event.add('dtend', current_date.date()) event.add("dtstamp", datetime.now()) cal.add_component(event) return cal.to_ical() # Set up the Streamlit app st.title("AI Travel Planner using Llama-3.2 ") st.caption("Plan your next adventure with AI Travel Planner by researching and planning a personalized itinerary on autopilot using local Llama-3") # Initialize session state to store the generated itinerary if 'itinerary' not in st.session_state: st.session_state.itinerary = None # Get SerpAPI key from the user serp_api_key = st.text_input("Enter Serp API Key for Search functionality", type="password") if serp_api_key: researcher = Agent( name="Researcher", role="Searches for travel destinations, activities, and accommodations based on user preferences", model=Ollama(id="llama3.2"), description=dedent( """\ You are a world-class travel researcher. Given a travel destination and the number of days the user wants to travel for, generate a list of search terms for finding relevant travel activities and accommodations. Then search the web for each term, analyze the results, and return the 10 most relevant results. """ ), instructions=[ "Given a travel destination and the number of days the user wants to travel for, first generate a list of 3 search terms related to that destination and the number of days.", "For each search term, `search_google` and analyze the results." "From the results of all searches, return the 10 most relevant results to the user's preferences.", "Remember: the quality of the results is important.", ], tools=[SerpApiTools(api_key=serp_api_key)], add_datetime_to_context=True, ) planner = Agent( name="Planner", role="Generates a draft itinerary based on user preferences and research results", model=Ollama(id="llama3.2"), description=dedent( """\ You are a senior travel planner. Given a travel destination, the number of days the user wants to travel for, and a list of research results, your goal is to generate a draft itinerary that meets the user's needs and preferences. """ ), instructions=[ "Given a travel destination, the number of days the user wants to travel for, and a list of research results, generate a draft itinerary that includes suggested activities and accommodations.", "Ensure the itinerary is well-structured, informative, and engaging.", "Ensure you provide a nuanced and balanced itinerary, quoting facts where possible.", "Remember: the quality of the itinerary is important.", "Focus on clarity, coherence, and overall quality.", "Never make up facts or plagiarize. Always provide proper attribution.", ], add_datetime_to_context=True, ) # Input fields for the user's destination and the number of days they want to travel for destination = st.text_input("Where do you want to go?") num_days = st.number_input("How many days do you want to travel for?", min_value=1, max_value=30, value=7) col1, col2 = st.columns(2) with col1: if st.button("Generate Itinerary"): with st.spinner("Processing..."): # Get the response from the assistant response: RunOutput = planner.run(f"{destination} for {num_days} days", stream=False) # Store the response in session state st.session_state.itinerary = response.content st.write(response.content) # Only show download button if there's an itinerary with col2: if st.session_state.itinerary: # Generate the ICS file ics_content = generate_ics_content(st.session_state.itinerary) # Provide the file for download st.download_button( label="Download Itinerary as Calendar (.ics)", data=ics_content, file_name="travel_itinerary.ics", mime="text/calendar" )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_travel_agent/travel_agent.py
starter_ai_agents/ai_travel_agent/travel_agent.py
from textwrap import dedent from agno.agent import Agent from agno.run.agent import RunOutput from agno.tools.serpapi import SerpApiTools import streamlit as st import re from agno.models.openai import OpenAIChat from icalendar import Calendar, Event from datetime import datetime, timedelta def generate_ics_content(plan_text:str, start_date: datetime = None) -> bytes: """ Generate an ICS calendar file from a travel itinerary text. Args: plan_text: The travel itinerary text start_date: Optional start date for the itinerary (defaults to today) Returns: bytes: The ICS file content as bytes """ cal = Calendar() cal.add('prodid','-//AI Travel Planner//github.com//' ) cal.add('version', '2.0') if start_date is None: start_date = datetime.today() # Split the plan into days day_pattern = re.compile(r'Day (\d+)[:\s]+(.*?)(?=Day \d+|$)', re.DOTALL) days = day_pattern.findall(plan_text) if not days: # If no day pattern found, create a single all-day event with the entire content event = Event() event.add('summary', "Travel Itinerary") event.add('description', plan_text) event.add('dtstart', start_date.date()) event.add('dtend', start_date.date()) event.add("dtstamp", datetime.now()) cal.add_component(event) else: # Process each day for day_num, day_content in days: day_num = int(day_num) current_date = start_date + timedelta(days=day_num - 1) # Create a single event for the entire day event = Event() event.add('summary', f"Day {day_num} Itinerary") event.add('description', day_content.strip()) # Make it an all-day event event.add('dtstart', current_date.date()) event.add('dtend', current_date.date()) event.add("dtstamp", datetime.now()) cal.add_component(event) return cal.to_ical() # Set up the Streamlit app st.title("AI Travel Planner ") st.caption("Plan your next adventure with AI Travel Planner by researching and planning a personalized itinerary on autopilot using GPT-4o") # Initialize session state to store the generated itinerary if 'itinerary' not in st.session_state: st.session_state.itinerary = None # Get OpenAI API key from user openai_api_key = st.text_input("Enter OpenAI API Key to access GPT-4o", type="password") # Get SerpAPI key from the user serp_api_key = st.text_input("Enter Serp API Key for Search functionality", type="password") if openai_api_key and serp_api_key: researcher = Agent( name="Researcher", role="Searches for travel destinations, activities, and accommodations based on user preferences", model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), description=dedent( """\ You are a world-class travel researcher. Given a travel destination and the number of days the user wants to travel for, generate a list of search terms for finding relevant travel activities and accommodations. Then search the web for each term, analyze the results, and return the 10 most relevant results. """ ), instructions=[ "Given a travel destination and the number of days the user wants to travel for, first generate a list of 3 search terms related to that destination and the number of days.", "For each search term, `search_google` and analyze the results." "From the results of all searches, return the 10 most relevant results to the user's preferences.", "Remember: the quality of the results is important.", ], tools=[SerpApiTools(api_key=serp_api_key)], add_datetime_to_context=True, ) planner = Agent( name="Planner", role="Generates a draft itinerary based on user preferences and research results", model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), description=dedent( """\ You are a senior travel planner. Given a travel destination, the number of days the user wants to travel for, and a list of research results, your goal is to generate a draft itinerary that meets the user's needs and preferences. """ ), instructions=[ "Given a travel destination, the number of days the user wants to travel for, and a list of research results, generate a draft itinerary that includes suggested activities and accommodations.", "Ensure the itinerary is well-structured, informative, and engaging.", "Ensure you provide a nuanced and balanced itinerary, quoting facts where possible.", "Remember: the quality of the itinerary is important.", "Focus on clarity, coherence, and overall quality.", "Never make up facts or plagiarize. Always provide proper attribution.", ], add_datetime_to_context=True, ) # Input fields for the user's destination and the number of days they want to travel for destination = st.text_input("Where do you want to go?") num_days = st.number_input("How many days do you want to travel for?", min_value=1, max_value=30, value=7) col1, col2 = st.columns(2) with col1: if st.button("Generate Itinerary"): with st.spinner("Researching your destination..."): # First get research results research_results: RunOutput = researcher.run(f"Research {destination} for a {num_days} day trip", stream=False) # Show research progress st.write(" Research completed") with st.spinner("Creating your personalized itinerary..."): # Pass research results to planner prompt = f""" Destination: {destination} Duration: {num_days} days Research Results: {research_results.content} Please create a detailed itinerary based on this research. """ response: RunOutput = planner.run(prompt, stream=False) # Store the response in session state st.session_state.itinerary = response.content st.write(response.content) # Only show download button if there's an itinerary with col2: if st.session_state.itinerary: # Generate the ICS file ics_content = generate_ics_content(st.session_state.itinerary) # Provide the file for download st.download_button( label="Download Itinerary as Calendar (.ics)", data=ics_content, file_name="travel_itinerary.ics", mime="text/calendar" )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_startup_trend_analysis_agent/startup_trends_agent.py
starter_ai_agents/ai_startup_trend_analysis_agent/startup_trends_agent.py
import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.tools.duckduckgo import DuckDuckGoTools from agno.models.google import Gemini from agno.tools.newspaper4k import Newspaper4kTools # Setting up Streamlit app st.title("AI Startup Trend Analysis Agent 📈") st.caption("Get the latest trend analysis and startup opportunities based on your topic of interest in a click!.") topic = st.text_input("Enter the area of interest for your Startup:") google_api_key = st.sidebar.text_input("Enter Google API Key", type="password") if st.button("Generate Analysis"): if not google_api_key: st.warning("Please enter the required API key.") else: with st.spinner("Processing your request..."): try: # Initialize Gemini model gemini_model = Gemini(id="gemini-2.5-flash", api_key=google_api_key) # Define News Collector Agent - Duckduckgo_search tool enables an Agent to search the web for information. search_tool = DuckDuckGoTools() news_collector = Agent( name="News Collector", role="Collects recent news articles on the given topic", tools=[search_tool], model=gemini_model, instructions=["Gather latest articles on the topic"], markdown=True, ) # Define Summary Writer Agent news_tool = Newspaper4kTools(enable_read_article=True, include_summary=True) summary_writer = Agent( name="Summary Writer", role="Summarizes collected news articles", tools=[news_tool], model=gemini_model, instructions=["Provide concise summaries of the articles"], markdown=True, ) # Define Trend Analyzer Agent trend_analyzer = Agent( name="Trend Analyzer", role="Analyzes trends from summaries", model=gemini_model, instructions=["Identify emerging trends and startup opportunities"], markdown=True, ) # Executing the workflow # Step 1: Collect news news_response: RunOutput = news_collector.run(f"Collect recent news on {topic}") articles = news_response.content # Step 2: Summarize articles summary_response: RunOutput = summary_writer.run(f"Summarize the following articles:\n{articles}") summaries = summary_response.content # Step 3: Analyze trends trend_response: RunOutput = trend_analyzer.run(f"Analyze trends from the following summaries:\n{summaries}") analysis = trend_response.content # Display results - if incase you want to use this furthur, you can uncomment the below 2 lines to get the summaries too! # st.subheader("News Summaries") # # st.write(summaries) st.subheader("Trend Analysis and Potential Startup Opportunities") st.write(analysis) except Exception as e: st.error(f"An error occurred: {e}") else: st.info("Enter the topic and API keys, then click 'Generate Analysis' to start.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_breakup_recovery_agent/ai_breakup_recovery_agent.py
starter_ai_agents/ai_breakup_recovery_agent/ai_breakup_recovery_agent.py
from agno.agent import Agent from agno.models.google import Gemini from agno.media import Image as AgnoImage from agno.tools.duckduckgo import DuckDuckGoTools import streamlit as st from typing import List, Optional import logging from pathlib import Path import tempfile import os # Configure logging for errors only logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(__name__) def initialize_agents(api_key: str) -> tuple[Agent, Agent, Agent, Agent]: try: model = Gemini(id="gemini-2.0-flash-exp", api_key=api_key) therapist_agent = Agent( model=model, name="Therapist Agent", instructions=[ "You are an empathetic therapist that:", "1. Listens with empathy and validates feelings", "2. Uses gentle humor to lighten the mood", "3. Shares relatable breakup experiences", "4. Offers comforting words and encouragement", "5. Analyzes both text and image inputs for emotional context", "Be supportive and understanding in your responses" ], markdown=True ) closure_agent = Agent( model=model, name="Closure Agent", instructions=[ "You are a closure specialist that:", "1. Creates emotional messages for unsent feelings", "2. Helps express raw, honest emotions", "3. Formats messages clearly with headers", "4. Ensures tone is heartfelt and authentic", "Focus on emotional release and closure" ], markdown=True ) routine_planner_agent = Agent( model=model, name="Routine Planner Agent", instructions=[ "You are a recovery routine planner that:", "1. Designs 7-day recovery challenges", "2. Includes fun activities and self-care tasks", "3. Suggests social media detox strategies", "4. Creates empowering playlists", "Focus on practical recovery steps" ], markdown=True ) brutal_honesty_agent = Agent( model=model, name="Brutal Honesty Agent", tools=[DuckDuckGoTools()], instructions=[ "You are a direct feedback specialist that:", "1. Gives raw, objective feedback about breakups", "2. Explains relationship failures clearly", "3. Uses blunt, factual language", "4. Provides reasons to move forward", "Focus on honest insights without sugar-coating" ], markdown=True ) return therapist_agent, closure_agent, routine_planner_agent, brutal_honesty_agent except Exception as e: st.error(f"Error initializing agents: {str(e)}") return None, None, None, None # Set page config and UI elements st.set_page_config( page_title="💔 Breakup Recovery Squad", page_icon="💔", layout="wide" ) # Sidebar for API key input with st.sidebar: st.header("🔑 API Configuration") if "api_key_input" not in st.session_state: st.session_state.api_key_input = "" api_key = st.text_input( "Enter your Gemini API Key", value=st.session_state.api_key_input, type="password", help="Get your API key from Google AI Studio", key="api_key_widget" ) if api_key != st.session_state.api_key_input: st.session_state.api_key_input = api_key if api_key: st.success("API Key provided! ✅") else: st.warning("Please enter your API key to proceed") st.markdown(""" To get your API key: 1. Go to [Google AI Studio](https://makersuite.google.com/app/apikey) 2. Enable the Generative Language API in your [Google Cloud Console](https://console.developers.google.com/apis/api/generativelanguage.googleapis.com) """) # Main content st.title("💔 Breakup Recovery Squad") st.markdown(""" ### Your AI-powered breakup recovery team is here to help! Share your feelings and chat screenshots, and we'll help you navigate through this tough time. """) # Input section col1, col2 = st.columns(2) with col1: st.subheader("Share Your Feelings") user_input = st.text_area( "How are you feeling? What happened?", height=150, placeholder="Tell us your story..." ) with col2: st.subheader("Upload Chat Screenshots") uploaded_files = st.file_uploader( "Upload screenshots of your chats (optional)", type=["jpg", "jpeg", "png"], accept_multiple_files=True, key="screenshots" ) if uploaded_files: for file in uploaded_files: st.image(file, caption=file.name, use_container_width=True) # Process button and API key check if st.button("Get Recovery Plan 💝", type="primary"): if not st.session_state.api_key_input: st.warning("Please enter your API key in the sidebar first!") else: therapist_agent, closure_agent, routine_planner_agent, brutal_honesty_agent = initialize_agents(st.session_state.api_key_input) if all([therapist_agent, closure_agent, routine_planner_agent, brutal_honesty_agent]): if user_input or uploaded_files: try: st.header("Your Personalized Recovery Plan") def process_images(files): processed_images = [] for file in files: try: temp_dir = tempfile.gettempdir() temp_path = os.path.join(temp_dir, f"temp_{file.name}") with open(temp_path, "wb") as f: f.write(file.getvalue()) agno_image = AgnoImage(filepath=Path(temp_path)) processed_images.append(agno_image) except Exception as e: logger.error(f"Error processing image {file.name}: {str(e)}") continue return processed_images all_images = process_images(uploaded_files) if uploaded_files else [] # Therapist Analysis with st.spinner("🤗 Getting empathetic support..."): therapist_prompt = f""" Analyze the emotional state and provide empathetic support based on: User's message: {user_input} Please provide a compassionate response with: 1. Validation of feelings 2. Gentle words of comfort 3. Relatable experiences 4. Words of encouragement """ response = therapist_agent.run( therapist_prompt, images=all_images ) st.subheader("🤗 Emotional Support") st.markdown(response.content) # Closure Messages with st.spinner("✍️ Crafting closure messages..."): closure_prompt = f""" Help create emotional closure based on: User's feelings: {user_input} Please provide: 1. Template for unsent messages 2. Emotional release exercises 3. Closure rituals 4. Moving forward strategies """ response = closure_agent.run( closure_prompt, images=all_images ) st.subheader("✍️ Finding Closure") st.markdown(response.content) # Recovery Plan with st.spinner("📅 Creating your recovery plan..."): routine_prompt = f""" Design a 7-day recovery plan based on: Current state: {user_input} Include: 1. Daily activities and challenges 2. Self-care routines 3. Social media guidelines 4. Mood-lifting music suggestions """ response = routine_planner_agent.run( routine_prompt, images=all_images ) st.subheader("📅 Your Recovery Plan") st.markdown(response.content) # Honest Feedback with st.spinner("💪 Getting honest perspective..."): honesty_prompt = f""" Provide honest, constructive feedback about: Situation: {user_input} Include: 1. Objective analysis 2. Growth opportunities 3. Future outlook 4. Actionable steps """ response = brutal_honesty_agent.run( honesty_prompt, images=all_images ) st.subheader("💪 Honest Perspective") st.markdown(response.content) except Exception as e: logger.error(f"Error during analysis: {str(e)}") st.error("An error occurred during analysis. Please check the logs for details.") else: st.warning("Please share your feelings or upload screenshots to get help.") else: st.error("Failed to initialize agents. Please check your API key.") # Footer st.markdown("---") st.markdown(""" <div style='text-align: center'> <p>Made with ❤️ by the Breakup Recovery Squad</p> <p>Share your recovery journey with #BreakupRecoverySquad</p> </div> """, unsafe_allow_html=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/multimodal_ai_agent/multimodal_reasoning_agent.py
starter_ai_agents/multimodal_ai_agent/multimodal_reasoning_agent.py
import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.media import Image from agno.models.google import Gemini import tempfile import os def main(): # Streamlit app title st.title("Multimodal Reasoning AI Agent 🧠") # Get Gemini API key from user in sidebar with st.sidebar: st.header("🔑 Configuration") gemini_api_key = st.text_input("Enter your Gemini API Key", type="password") st.caption( "Get your API key from [Google AI Studio]" "(https://aistudio.google.com/apikey) 🔑" ) # Instruction st.write( "Upload an image and provide a reasoning-based task for the AI Agent. " "The AI Agent will analyze the image and respond based on your input." ) if not gemini_api_key: st.warning("Please enter your Gemini API key in the sidebar to continue.") return # Set up the reasoning agent agent = Agent( model=Gemini(id="gemini-2.5-pro", api_key=gemini_api_key), markdown=True ) # File uploader for image uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"]) if uploaded_file is not None: try: # Save uploaded file to temporary file with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file: tmp_file.write(uploaded_file.getvalue()) temp_path = tmp_file.name # Display the uploaded image st.image(uploaded_file, caption="Uploaded Image", use_container_width=True) # Input for dynamic task task_input = st.text_area( "Enter your task/question for the AI Agent:" ) # Button to process the image and task if st.button("Analyze Image") and task_input: with st.spinner("AI is thinking... 🤖"): try: # Call the agent with the dynamic task and image path response: RunOutput = agent.run(task_input, images=[Image(filepath=temp_path)]) # Display the response from the model st.markdown("### AI Response:") st.markdown(response.content) except Exception as e: st.error(f"An error occurred during analysis: {str(e)}") finally: # Clean up temp file if os.path.exists(temp_path): os.unlink(temp_path) except Exception as e: st.error(f"An error occurred while processing the image: {str(e)}") if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/multimodal_ai_agent/mutimodal_agent.py
starter_ai_agents/multimodal_ai_agent/mutimodal_agent.py
import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.google import Gemini from agno.media import Video import time from pathlib import Path import tempfile st.set_page_config( page_title="Multimodal AI Agent", page_icon="🧬", layout="wide" ) st.title("Multimodal AI Agent 🧬") # Get Gemini API key from user in sidebar with st.sidebar: st.header("🔑 Configuration") gemini_api_key = st.text_input("Enter your Gemini API Key", type="password") st.caption( "Get your API key from [Google AI Studio]" "(https://aistudio.google.com/apikey) 🔑" ) # Initialize single agent with both capabilities @st.cache_resource def initialize_agent(api_key): return Agent( name="Multimodal Analyst", model=Gemini(id="gemini-2.5-flash", api_key=api_key), markdown=True, ) if gemini_api_key: agent = initialize_agent(gemini_api_key) # File uploader uploaded_file = st.file_uploader("Upload a video file", type=['mp4', 'mov', 'avi']) if uploaded_file: with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file: tmp_file.write(uploaded_file.read()) video_path = tmp_file.name st.video(video_path) user_prompt = st.text_area( "What would you like to know?", placeholder="Ask any question related to the video - the AI Agent will analyze it and search the web if needed", help="You can ask questions about the video content and get relevant information from the web" ) if st.button("Analyze & Research"): if not user_prompt: st.warning("Please enter your question.") else: try: with st.spinner("Processing video and researching..."): video = Video(filepath=video_path) prompt = f""" First analyze this video and then answer the following question using both the video analysis and web research: {user_prompt} Provide a comprehensive response focusing on practical, actionable information. """ result: RunOutput = agent.run(prompt, videos=[video]) st.subheader("Result") st.markdown(result.content) except Exception as e: st.error(f"An error occurred: {str(e)}") finally: Path(video_path).unlink(missing_ok=True) else: st.info("Please upload a video to begin analysis.") else: st.warning("Please enter your Gemini API key to continue.") st.markdown(""" <style> .stTextArea textarea { height: 100px; } </style> """, unsafe_allow_html=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_data_analysis_agent/ai_data_analyst.py
starter_ai_agents/ai_data_analysis_agent/ai_data_analyst.py
import tempfile import csv import streamlit as st import pandas as pd from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.duckdb import DuckDbTools from agno.tools.pandas import PandasTools # Function to preprocess and save the uploaded file def preprocess_and_save(file): try: # Read the uploaded file into a DataFrame if file.name.endswith('.csv'): df = pd.read_csv(file, encoding='utf-8', na_values=['NA', 'N/A', 'missing']) elif file.name.endswith('.xlsx'): df = pd.read_excel(file, na_values=['NA', 'N/A', 'missing']) else: st.error("Unsupported file format. Please upload a CSV or Excel file.") return None, None, None # Ensure string columns are properly quoted for col in df.select_dtypes(include=['object']): df[col] = df[col].astype(str).replace({r'"': '""'}, regex=True) # Parse dates and numeric columns for col in df.columns: if 'date' in col.lower(): df[col] = pd.to_datetime(df[col], errors='coerce') elif df[col].dtype == 'object': try: df[col] = pd.to_numeric(df[col]) except (ValueError, TypeError): # Keep as is if conversion fails pass # Create a temporary file to save the preprocessed data with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as temp_file: temp_path = temp_file.name # Save the DataFrame to the temporary CSV file with quotes around string fields df.to_csv(temp_path, index=False, quoting=csv.QUOTE_ALL) return temp_path, df.columns.tolist(), df # Return the DataFrame as well except Exception as e: st.error(f"Error processing file: {e}") return None, None, None # Streamlit app st.title("📊 Data Analyst Agent") # Sidebar for API keys with st.sidebar: st.header("API Keys") openai_key = st.text_input("Enter your OpenAI API key:", type="password") if openai_key: st.session_state.openai_key = openai_key st.success("API key saved!") else: st.warning("Please enter your OpenAI API key to proceed.") # File upload widget uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"]) if uploaded_file is not None and "openai_key" in st.session_state: # Preprocess and save the uploaded file temp_path, columns, df = preprocess_and_save(uploaded_file) if temp_path and columns and df is not None: # Display the uploaded data as a table st.write("Uploaded Data:") st.dataframe(df) # Use st.dataframe for an interactive table # Display the columns of the uploaded data st.write("Uploaded columns:", columns) # Initialize DuckDbTools duckdb_tools = DuckDbTools() # Load the CSV file into DuckDB as a table duckdb_tools.load_local_csv_to_table( path=temp_path, table="uploaded_data", ) # Initialize the Agent with DuckDB and Pandas tools data_analyst_agent = Agent( model=OpenAIChat(id="gpt-4o", api_key=st.session_state.openai_key), tools=[duckdb_tools, PandasTools()], system_message="You are an expert data analyst. Use the 'uploaded_data' table to answer user queries. Generate SQL queries using DuckDB tools to solve the user's query. Provide clear and concise answers with the results.", markdown=True, ) # Initialize code storage in session state if "generated_code" not in st.session_state: st.session_state.generated_code = None # Main query input widget user_query = st.text_area("Ask a query about the data:") # Add info message about terminal output st.info("💡 Check your terminal for a clearer output of the agent's response") if st.button("Submit Query"): if user_query.strip() == "": st.warning("Please enter a query.") else: try: # Show loading spinner while processing with st.spinner('Processing your query...'): # Get the response from the agent response = data_analyst_agent.run(user_query) # Extract the content from the response object if hasattr(response, 'content'): response_content = response.content else: response_content = str(response) # Display the response in Streamlit st.markdown(response_content) except Exception as e: st.error(f"Error generating response from the agent: {e}") st.error("Please try rephrasing your query or check if the data format is correct.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_music_generator_agent/music_generator_agent.py
starter_ai_agents/ai_music_generator_agent/music_generator_agent.py
import os from uuid import uuid4 import requests from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.openai import OpenAIChat from agno.tools.models_labs import FileType, ModelsLabTools from agno.utils.log import logger import streamlit as st # Sidebar: User enters the API keys st.sidebar.title("API Key Configuration") openai_api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") models_lab_api_key = st.sidebar.text_input("Enter your ModelsLab API Key", type="password") # Streamlit App UI st.title("🎶 ModelsLab Music Generator") prompt = st.text_area("Enter a music generation prompt:", "Generate a 30 second classical music piece", height=100) # Initialize agent only if both API keys are provided if openai_api_key and models_lab_api_key: agent = Agent( name="ModelsLab Music Agent", agent_id="ml_music_agent", model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), show_tool_calls=True, tools=[ModelsLabTools(api_key=models_lab_api_key, wait_for_completion=True, file_type=FileType.MP3)], description="You are an AI agent that can generate music using the ModelsLabs API.", instructions=[ "When generating music, use the `generate_media` tool with detailed prompts that specify:", "- The genre and style of music (e.g., classical, jazz, electronic)", "- The instruments and sounds to include", "- The tempo, mood and emotional qualities", "- The structure (intro, verses, chorus, bridge, etc.)", "Create rich, descriptive prompts that capture the desired musical elements.", "Focus on generating high-quality, complete instrumental pieces.", ], markdown=True, debug_mode=True, ) if st.button("Generate Music"): if prompt.strip() == "": st.warning("Please enter a prompt first.") else: with st.spinner("Generating music... 🎵"): try: music: RunOutput = agent.run(prompt) if music.audio and len(music.audio) > 0: save_dir = "audio_generations" os.makedirs(save_dir, exist_ok=True) url = music.audio[0].url response = requests.get(url) # 🛡️ Validate response if not response.ok: st.error(f"Failed to download audio. Status code: {response.status_code}") st.stop() content_type = response.headers.get("Content-Type", "") if "audio" not in content_type: st.error(f"Invalid file type returned: {content_type}") st.write("🔍 Debug: Downloaded content was not an audio file.") st.write("🔗 URL:", url) st.stop() # ✅ Save audio filename = f"{save_dir}/music_{uuid4()}.mp3" with open(filename, "wb") as f: f.write(response.content) # 🎧 Play audio st.success("Music generated successfully! 🎶") audio_bytes = open(filename, "rb").read() st.audio(audio_bytes, format="audio/mp3") st.download_button( label="Download Music", data=audio_bytes, file_name="generated_music.mp3", mime="audio/mp3" ) else: st.error("No audio generated. Please try again.") except Exception as e: st.error(f"An error occurred: {e}") logger.error(f"Streamlit app error: {e}") else: st.sidebar.warning("Please enter both the OpenAI and ModelsLab API keys to use the app.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_reasoning_agent/local_ai_reasoning_agent.py
starter_ai_agents/ai_reasoning_agent/local_ai_reasoning_agent.py
from agno.agent import Agent from agno.models.ollama import Ollama from agno.playground import Playground, serve_playground_app reasoning_agent = Agent(name="Reasoning Agent", model=Ollama(id="qwq:32b"), markdown=True) # UI for Reasoning agent app = Playground(agents=[reasoning_agent]).get_app() # Run the Playground app if __name__ == "__main__": serve_playground_app("local_ai_reasoning_agent:app", reload=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_reasoning_agent/reasoning_agent.py
starter_ai_agents/ai_reasoning_agent/reasoning_agent.py
from agno.agent import Agent from agno.models.openai import OpenAIChat from rich.console import Console regular_agent = Agent(model=OpenAIChat(id="gpt-4o-mini"), markdown=True) console = Console() reasoning_agent = Agent( model=OpenAIChat(id="gpt-4o"), reasoning=True, markdown=True, structured_outputs=True, ) task = "How many 'r' are in the word 'supercalifragilisticexpialidocious'?" console.rule("[bold green]Regular Agent[/bold green]") regular_agent.print_response(task, stream=True) console.rule("[bold yellow]Reasoning Agent[/bold yellow]") reasoning_agent.print_response(task, stream=True, show_full_reasoning=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_data_visualisation_agent/ai_data_visualisation_agent.py
starter_ai_agents/ai_data_visualisation_agent/ai_data_visualisation_agent.py
import os import json import re import sys import io import contextlib import warnings from typing import Optional, List, Any, Tuple from PIL import Image import streamlit as st import pandas as pd import base64 from io import BytesIO from together import Together from e2b_code_interpreter import Sandbox warnings.filterwarnings("ignore", category=UserWarning, module="pydantic") pattern = re.compile(r"```python\n(.*?)\n```", re.DOTALL) def code_interpret(e2b_code_interpreter: Sandbox, code: str) -> Optional[List[Any]]: with st.spinner('Executing code in E2B sandbox...'): stdout_capture = io.StringIO() stderr_capture = io.StringIO() with contextlib.redirect_stdout(stdout_capture), contextlib.redirect_stderr(stderr_capture): with warnings.catch_warnings(): warnings.simplefilter("ignore") exec = e2b_code_interpreter.run_code(code) if stderr_capture.getvalue(): print("[Code Interpreter Warnings/Errors]", file=sys.stderr) print(stderr_capture.getvalue(), file=sys.stderr) if stdout_capture.getvalue(): print("[Code Interpreter Output]", file=sys.stdout) print(stdout_capture.getvalue(), file=sys.stdout) if exec.error: print(f"[Code Interpreter ERROR] {exec.error}", file=sys.stderr) return None return exec.results def match_code_blocks(llm_response: str) -> str: match = pattern.search(llm_response) if match: code = match.group(1) return code return "" def chat_with_llm(e2b_code_interpreter: Sandbox, user_message: str, dataset_path: str) -> Tuple[Optional[List[Any]], str]: # Update system prompt to include dataset path information system_prompt = f"""You're a Python data scientist and data visualization expert. You are given a dataset at path '{dataset_path}' and also the user's query. You need to analyze the dataset and answer the user's query with a response and you run Python code to solve them. IMPORTANT: Always use the dataset path variable '{dataset_path}' in your code when reading the CSV file.""" messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}, ] with st.spinner('Getting response from Together AI LLM model...'): client = Together(api_key=st.session_state.together_api_key) response = client.chat.completions.create( model=st.session_state.model_name, messages=messages, ) response_message = response.choices[0].message python_code = match_code_blocks(response_message.content) if python_code: code_interpreter_results = code_interpret(e2b_code_interpreter, python_code) return code_interpreter_results, response_message.content else: st.warning(f"Failed to match any Python code in model's response") return None, response_message.content def upload_dataset(code_interpreter: Sandbox, uploaded_file) -> str: dataset_path = f"./{uploaded_file.name}" try: code_interpreter.files.write(dataset_path, uploaded_file) return dataset_path except Exception as error: st.error(f"Error during file upload: {error}") raise error def main(): """Main Streamlit application.""" st.title("📊 AI Data Visualization Agent") st.write("Upload your dataset and ask questions about it!") # Initialize session state variables if 'together_api_key' not in st.session_state: st.session_state.together_api_key = '' if 'e2b_api_key' not in st.session_state: st.session_state.e2b_api_key = '' if 'model_name' not in st.session_state: st.session_state.model_name = '' with st.sidebar: st.header("API Keys and Model Configuration") st.session_state.together_api_key = st.sidebar.text_input("Together AI API Key", type="password") st.sidebar.info("💡 Everyone gets a free $1 credit by Together AI - AI Acceleration Cloud platform") st.sidebar.markdown("[Get Together AI API Key](https://api.together.ai/signin)") st.session_state.e2b_api_key = st.sidebar.text_input("Enter E2B API Key", type="password") st.sidebar.markdown("[Get E2B API Key](https://e2b.dev/docs/legacy/getting-started/api-key)") # Add model selection dropdown model_options = { "Meta-Llama 3.1 405B": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo", "DeepSeek V3": "deepseek-ai/DeepSeek-V3", "Qwen 2.5 7B": "Qwen/Qwen2.5-7B-Instruct-Turbo", "Meta-Llama 3.3 70B": "meta-llama/Llama-3.3-70B-Instruct-Turbo" } st.session_state.model_name = st.selectbox( "Select Model", options=list(model_options.keys()), index=0 # Default to first option ) st.session_state.model_name = model_options[st.session_state.model_name] uploaded_file = st.file_uploader("Choose a CSV file", type="csv") if uploaded_file is not None: # Display dataset with toggle df = pd.read_csv(uploaded_file) st.write("Dataset:") show_full = st.checkbox("Show full dataset") if show_full: st.dataframe(df) else: st.write("Preview (first 5 rows):") st.dataframe(df.head()) # Query input query = st.text_area("What would you like to know about your data?", "Can you compare the average cost for two people between different categories?") if st.button("Analyze"): if not st.session_state.together_api_key or not st.session_state.e2b_api_key: st.error("Please enter both API keys in the sidebar.") else: with Sandbox(api_key=st.session_state.e2b_api_key) as code_interpreter: # Upload the dataset dataset_path = upload_dataset(code_interpreter, uploaded_file) # Pass dataset_path to chat_with_llm code_results, llm_response = chat_with_llm(code_interpreter, query, dataset_path) # Display LLM's text response st.write("AI Response:") st.write(llm_response) # Display results/visualizations if code_results: for result in code_results: if hasattr(result, 'png') and result.png: # Check if PNG data is available # Decode the base64-encoded PNG data png_data = base64.b64decode(result.png) # Convert PNG data to an image and display it image = Image.open(BytesIO(png_data)) st.image(image, caption="Generated Visualization", use_container_width=False) elif hasattr(result, 'figure'): # For matplotlib figures fig = result.figure # Extract the matplotlib figure st.pyplot(fig) # Display using st.pyplot elif hasattr(result, 'show'): # For plotly figures st.plotly_chart(result) elif isinstance(result, (pd.DataFrame, pd.Series)): st.dataframe(result) else: st.write(result) if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/starter_ai_agents/ai_meme_generator_agent_browseruse/ai_meme_generator_agent.py
starter_ai_agents/ai_meme_generator_agent_browseruse/ai_meme_generator_agent.py
import asyncio import streamlit as st from browser_use import Agent, SystemPrompt from langchain_openai import ChatOpenAI from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage import re async def generate_meme(query: str, model_choice: str, api_key: str) -> None: # Initialize the appropriate LLM based on user selection if model_choice == "Claude": llm = ChatAnthropic( model="claude-3-5-sonnet-20241022", api_key=api_key ) elif model_choice == "Deepseek": llm = ChatOpenAI( base_url='https://api.deepseek.com/v1', model='deepseek-chat', api_key=api_key, temperature=0.3 ) else: # OpenAI llm = ChatOpenAI( model="gpt-4o", api_key=api_key, temperature=0.0 ) task_description = ( "You are a meme generator expert. You are given a query and you need to generate a meme for it.\n" "1. Go to https://imgflip.com/memetemplates \n" "2. Click on the Search bar in the middle and search for ONLY ONE MAIN ACTION VERB (like 'bully', 'laugh', 'cry') in this query: '{0}'\n" "3. Choose any meme template that metaphorically fits the meme topic: '{0}'\n" " by clicking on the 'Add Caption' button below it\n" "4. Write a Top Text (setup/context) and Bottom Text (punchline/outcome) related to '{0}'.\n" "5. Check the preview making sure it is funny and a meaningful meme. Adjust text directly if needed. \n" "6. Look at the meme and text on it, if it doesnt make sense, PLEASE retry by filling the text boxes with different text. \n" "7. Click on the Generate meme button to generate the meme\n" "8. Copy the image link and give it as the output\n" ).format(query) agent = Agent( task=task_description, llm=llm, max_actions_per_step=5, max_failures=25, use_vision=(model_choice != "Deepseek") ) history = await agent.run() # Extract final result from agent history final_result = history.final_result() # Use regex to find the meme URL in the result url_match = re.search(r'https://imgflip\.com/i/(\w+)', final_result) if url_match: meme_id = url_match.group(1) return f"https://i.imgflip.com/{meme_id}.jpg" return None def main(): # Custom CSS styling st.title("🥸 AI Meme Generator Agent - Browser Use") st.info("This AI browser agent does browser automation to generate memes based on your input with browser use. Please enter your API key and describe the meme you want to generate.") # Sidebar configuration with st.sidebar: st.markdown('<p class="sidebar-header">⚙️ Model Configuration</p>', unsafe_allow_html=True) # Model selection model_choice = st.selectbox( "Select AI Model", ["Claude", "Deepseek", "OpenAI"], index=0, help="Choose which LLM to use for meme generation" ) # API key input based on model selection api_key = "" if model_choice == "Claude": api_key = st.text_input("Claude API Key", type="password", help="Get your API key from https://console.anthropic.com") elif model_choice == "Deepseek": api_key = st.text_input("Deepseek API Key", type="password", help="Get your API key from https://platform.deepseek.com") else: api_key = st.text_input("OpenAI API Key", type="password", help="Get your API key from https://platform.openai.com") # Main content area st.markdown('<p class="header-text">🎨 Describe Your Meme Concept</p>', unsafe_allow_html=True) query = st.text_input( "Meme Idea Input", placeholder="Example: 'Ilya's SSI quietly looking at the OpenAI vs Deepseek debate while diligently working on ASI'", label_visibility="collapsed" ) if st.button("Generate Meme 🚀"): if not api_key: st.warning(f"Please provide the {model_choice} API key") st.stop() if not query: st.warning("Please enter a meme idea") st.stop() with st.spinner(f"🧠 {model_choice} is generating your meme..."): try: meme_url = asyncio.run(generate_meme(query, model_choice, api_key)) if meme_url: st.success("✅ Meme Generated Successfully!") st.image(meme_url, caption="Generated Meme Preview", use_container_width=True) st.markdown(f""" **Direct Link:** [Open in ImgFlip]({meme_url}) **Embed URL:** `{meme_url}` """) else: st.error("❌ Failed to generate meme. Please try again with a different prompt.") except Exception as e: st.error(f"Error: {str(e)}") st.info("💡 If using OpenAI, ensure your account has GPT-4o access") if __name__ == '__main__': main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_youtube_videos/test_session_state.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_youtube_videos/test_session_state.py
#!/usr/bin/env python3 """ Test script to verify the session state improvements work correctly """ # Simulate the key functions from the updated app import tempfile from typing import Tuple # Mock streamlit session state for testing class MockSessionState: def __init__(self): self.app = None self.current_video_url = None self.transcript_loaded = False self.transcript_text = None self.word_count = 0 self.chat_history = [] def test_session_state_logic(): """Test the session state logic without Streamlit""" print("🧪 Testing Session State Logic") print("=" * 40) # Mock session state session_state = MockSessionState() # Test 1: Initial state print(f"✓ Initial state - transcript_loaded: {session_state.transcript_loaded}") print(f"✓ Initial state - current_video_url: {session_state.current_video_url}") print(f"✓ Initial state - chat_history: {len(session_state.chat_history)} entries") # Test 2: Simulate loading a video video_url_1 = "https://www.youtube.com/watch?v=9bZkp7q19f0" mock_transcript = "This is a mock transcript for testing purposes. It contains multiple words." # Simulate the logic from the app if video_url_1 != session_state.current_video_url or not session_state.transcript_loaded: print(f"\n🔍 Loading new video: {video_url_1}") # Clear previous data if exists (simulate new video) if session_state.transcript_loaded: session_state.chat_history = [] print(" ✓ Cleared previous chat history") # Store new video data session_state.current_video_url = video_url_1 session_state.transcript_loaded = True session_state.transcript_text = mock_transcript session_state.word_count = len(mock_transcript.split()) print(f" ✅ Video loaded successfully") print(f" 📊 Transcript: {session_state.word_count} words") # Test 3: Simulate multiple questions without reloading questions = [ "What is this video about?", "Can you summarize the main points?", "What are the key takeaways?" ] print(f"\n💬 Testing multiple questions...") for i, question in enumerate(questions, 1): # Simulate chat without reloading transcript mock_answer = f"Mock answer {i} for: {question[:30]}..." session_state.chat_history.append((question, mock_answer)) print(f" Q{i}: {question}") print(f" A{i}: {mock_answer}") print(f"\n✓ Chat history now has {len(session_state.chat_history)} entries") # Test 4: Test loading a different video (should clear history) video_url_2 = "https://www.youtube.com/watch?v=UF8uR6Z6KLc" print(f"\n🔄 Loading different video: {video_url_2}") if video_url_2 != session_state.current_video_url: # Clear previous data session_state.chat_history = [] session_state.current_video_url = video_url_2 session_state.transcript_text = "New mock transcript for the second video." session_state.word_count = len(session_state.transcript_text.split()) print(f" ✅ New video loaded") print(f" 🗑️ Chat history cleared: {len(session_state.chat_history)} entries") print(f" 📊 New transcript: {session_state.word_count} words") # Test 5: Verify no duplicate loading for same URL print(f"\n🔄 Testing same video URL again: {video_url_2}") original_word_count = session_state.word_count if video_url_2 != session_state.current_video_url or not session_state.transcript_loaded: print(" ❌ Should NOT reload transcript for same URL") else: print(" ✅ Correctly skipped reloading for same URL") print(f" 📊 Word count unchanged: {original_word_count}") print(f"\n🎉 Session State Logic Test Complete!") print(f"✅ Final state:") print(f" - Current video: {session_state.current_video_url}") print(f" - Transcript loaded: {session_state.transcript_loaded}") print(f" - Word count: {session_state.word_count}") print(f" - Chat history: {len(session_state.chat_history)} entries") if __name__ == "__main__": test_session_state_logic() print(f"\n💡 Key Improvements Verified:") print(f" 1. ✅ Transcript loads only once per video URL") print(f" 2. ✅ Chat history is preserved for the same video") print(f" 3. ✅ Chat history is cleared when loading a new video") print(f" 4. ✅ No redundant API calls for the same URL") print(f" 5. ✅ Session state properly manages video data")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_youtube_videos/chat_youtube.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_youtube_videos/chat_youtube.py
import tempfile import streamlit as st from embedchain import App from youtube_transcript_api import YouTubeTranscriptApi from typing import Tuple def embedchain_bot(db_path: str, api_key: str) -> App: return App.from_config( config={ "llm": {"provider": "openai", "config": {"model": "gpt-4", "temperature": 0.5, "api_key": api_key}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "openai", "config": {"api_key": api_key}}, } ) def extract_video_id(video_url: str) -> str: if "youtube.com/watch?v=" in video_url: return video_url.split("v=")[-1].split("&")[0] elif "youtube.com/shorts/" in video_url: return video_url.split("/shorts/")[-1].split("?")[0] else: raise ValueError("Invalid YouTube URL") def fetch_video_data(video_url: str) -> Tuple[str, str]: try: video_id = extract_video_id(video_url) # Create API instance (required for new version) api = YouTubeTranscriptApi() # First, check if transcripts are available try: transcript_list = api.list(video_id) available_languages = [t.language_code for t in transcript_list] st.info(f"Available transcripts: {available_languages}") except Exception as list_error: st.error(f"Cannot retrieve transcript list: {list_error}") return "Unknown", "No transcript available for this video." # Try to get transcript with multiple fallback languages languages_to_try = ['en', 'en-US', 'en-GB'] # Try English variants first transcript = None for lang in languages_to_try: if lang in available_languages: try: fetched_transcript = api.fetch(video_id, languages=[lang]) transcript = list(fetched_transcript) # Convert to list of snippets st.success(f"Successfully fetched transcript in language: {lang}") break except Exception: continue # If no English transcript, try any available language if transcript is None and available_languages: try: fetched_transcript = api.fetch(video_id, languages=[available_languages[0]]) transcript = list(fetched_transcript) st.success(f"Successfully fetched transcript in language: {available_languages[0]}") except Exception as final_error: st.error(f"Could not fetch transcript in any language: {final_error}") return "Unknown", "No transcript available for this video." if transcript: # Extract text from FetchedTranscriptSnippet objects transcript_text = " ".join([snippet.text for snippet in transcript]) return "Unknown", transcript_text # Title is set to "Unknown" since we're not fetching it else: return "Unknown", "No transcript available for this video." except ValueError as ve: st.error(f"Invalid YouTube URL: {ve}") return "Unknown", "Invalid YouTube URL provided." except Exception as e: error_type = type(e).__name__ error_msg = str(e) if "VideoUnavailable" in error_type: st.error("❌ Video is unavailable, private, or has been removed.") elif "TranscriptsDisabled" in error_type: st.error("❌ Subtitles/transcripts are disabled for this video.") st.info("💡 Try a different video that has subtitles enabled.") elif "NoTranscriptFound" in error_type: st.error("❌ No transcript found in the requested language.") st.info("💡 Try a video with auto-generated subtitles or manual captions.") elif "ParseError" in error_type: st.error("❌ Unable to parse video data. This might be due to:") st.info("• Video is private or restricted") st.info("• Video has been removed") st.info("• YouTube changed their format") st.info("💡 Try a different video.") else: st.error(f"❌ Error fetching transcript ({error_type}): {error_msg}") return "Unknown", "No transcript available for this video." # Create Streamlit app st.title("Chat with YouTube Video 📺") st.caption("This app allows you to chat with a YouTube video using OpenAI API") # Add helpful instructions with st.expander("ℹ️ How to use this app", expanded=False): st.markdown(""" 1. **Enter your OpenAI API key** (required for AI responses) 2. **Paste a YouTube video URL** (must have subtitles/transcripts available) 3. **Wait for the transcript to load** (you'll see confirmation messages) 4. **Ask questions** about the video content **📝 Note:** This app only works with videos that have: - Auto-generated subtitles, OR - Manually uploaded captions/transcripts **❌ Common issues:** - "Transcripts disabled" = Video doesn't have subtitles - "Video unavailable" = Video might be private, restricted, or removed - Try popular educational videos (TED talks, tutorials, etc.) for best results """) with st.expander("🎯 Try these working example videos", expanded=False): example_videos = [ "https://www.youtube.com/watch?v=9bZkp7q19f0", # Short working video "https://www.youtube.com/watch?v=UF8uR6Z6KLc", # Simon Sinek TED Talk "https://www.youtube.com/watch?v=_uQrJ0TkZlc", # Programming tutorial ] st.markdown("**Working test videos (copy and paste these URLs):**") for i, video in enumerate(example_videos, 1): st.code(video, language=None) st.info("💡 These videos are confirmed to have accessible transcripts.") st.divider() # Initialize session state variables if 'app' not in st.session_state: st.session_state.app = None if 'current_video_url' not in st.session_state: st.session_state.current_video_url = None if 'transcript_loaded' not in st.session_state: st.session_state.transcript_loaded = False if 'transcript_text' not in st.session_state: st.session_state.transcript_text = None if 'word_count' not in st.session_state: st.session_state.word_count = 0 if 'chat_history' not in st.session_state: st.session_state.chat_history = [] # Get OpenAI API key from user openai_access_token = st.text_input("OpenAI API Key", type="password") # If OpenAI API key is provided, create an instance of App if openai_access_token: # Create/update the embedchain app only if needed if st.session_state.app is None: # Create a temporary directory to store the database db_path = tempfile.mkdtemp() # Create an instance of Embedchain App st.session_state.app = embedchain_bot(db_path, openai_access_token) # Get the YouTube video URL from the user video_url = st.text_input("Enter YouTube Video URL", type="default") # Check if we have a new video URL or no transcript loaded yet if video_url and (video_url != st.session_state.current_video_url or not st.session_state.transcript_loaded): with st.spinner("🔍 Checking video and fetching transcript..."): try: title, transcript = fetch_video_data(video_url) if transcript != "No transcript available for this video." and transcript != "Invalid YouTube URL provided.": with st.spinner("🧠 Adding to knowledge base..."): # Clear previous video data if it exists if st.session_state.transcript_loaded: # Create a new app instance for the new video db_path = tempfile.mkdtemp() st.session_state.app = embedchain_bot(db_path, openai_access_token) # Clear chat history for new video st.session_state.chat_history = [] st.session_state.app.add(transcript, data_type="text", metadata={"title": title, "url": video_url}) # Store in session state st.session_state.current_video_url = video_url st.session_state.transcript_loaded = True st.session_state.transcript_text = transcript st.session_state.word_count = len(transcript.split()) st.success(f"✅ Added video to knowledge base! You can now ask questions about it.") st.info(f"📊 Transcript contains {st.session_state.word_count} words") else: st.warning(f"❌ Cannot add video to knowledge base: {transcript}") st.session_state.transcript_loaded = False st.session_state.current_video_url = None except Exception as e: st.error(f"❌ Error processing video: {e}") st.session_state.transcript_loaded = False st.session_state.current_video_url = None # Show current video status if st.session_state.transcript_loaded and st.session_state.current_video_url: col1, col2 = st.columns([3, 1]) with col1: st.success(f"📹 Current video: {st.session_state.current_video_url}") st.info(f"📊 Transcript: {st.session_state.word_count} words loaded in memory") with col2: if st.button("🗑️ Clear Video", help="Remove current video and load a new one"): st.session_state.transcript_loaded = False st.session_state.current_video_url = None st.session_state.transcript_text = None st.session_state.word_count = 0 st.session_state.app = None st.session_state.chat_history = [] st.rerun() # Display chat history if st.session_state.chat_history: with st.expander("💬 Chat History", expanded=True): for i, (question, answer) in enumerate(st.session_state.chat_history): st.markdown(f"**Q{i+1}:** {question}") st.markdown(f"**A{i+1}:** {answer}") st.divider() # Ask a question about the video prompt = st.text_input("Ask any question about the YouTube Video") # Chat with the video if prompt: if st.session_state.transcript_loaded and st.session_state.app: try: with st.spinner("🤔 Thinking..."): answer = st.session_state.app.chat(prompt) # Add to chat history st.session_state.chat_history.append((prompt, answer)) # Display the current answer st.write("**Answer:**") st.write(answer) # Clear the input by refreshing (optional) # st.rerun() except Exception as e: st.error(f"❌ Error chatting with the video: {e}") else: st.warning("⚠️ Please add a valid video with transcripts first before asking questions.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_research_papers/chat_arxiv_llama3.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_research_papers/chat_arxiv_llama3.py
# Import the required libraries import streamlit as st from agno.agent import Agent from agno.models.ollama import Ollama from agno.tools.arxiv import ArxivTools # Set up the Streamlit app st.title("Chat with Research Papers 🔎🤖") st.caption("This app allows you to chat with arXiv research papers using Llama-3 running locally.") # Create an instance of the Assistant assistant = Agent( model=Ollama( id="llama3.1:8b") , tools=[ArxivTools()], show_tool_calls=True ) # Get the search query from the user query= st.text_input("Enter the Search Query", type="default") if query: # Search the web using the AI Assistant response = assistant.run(query, stream=False) st.write(response.content)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_research_papers/chat_arxiv.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_research_papers/chat_arxiv.py
# Import the required libraries import streamlit as st from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.arxiv import ArxivTools # Set up the Streamlit app st.title("Chat with Research Papers 🔎🤖") st.caption("This app allows you to chat with arXiv research papers using OpenAI GPT-4o model.") # Get OpenAI API key from user openai_access_token = st.text_input("OpenAI API Key", type="password") # If OpenAI API key is provided, create an instance of Assistant if openai_access_token: # Create an instance of the Assistant assistant = Agent( model=OpenAIChat( id="gpt-4o", max_tokens=1024, temperature=0.9, api_key=openai_access_token) , tools=[ArxivTools()] ) # Get the search query from the user query= st.text_input("Enter the Search Query", type="default") if query: # Search the web using the AI Assistant response = assistant.run(query, stream=False) st.write(response.content)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_substack/chat_substack.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_substack/chat_substack.py
import streamlit as st from embedchain import App import tempfile # Define the embedchain_bot function def embedchain_bot(db_path, api_key): return App.from_config( config={ "llm": {"provider": "openai", "config": {"model": "gpt-4-turbo", "temperature": 0.5, "api_key": api_key}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "openai", "config": {"api_key": api_key}}, } ) st.title("Chat with Substack Newsletter 📝") st.caption("This app allows you to chat with Substack newsletter using OpenAI API") # Get OpenAI API key from user openai_access_token = st.text_input("OpenAI API Key", type="password") if openai_access_token: # Create a temporary directory to store the database db_path = tempfile.mkdtemp() # Create an instance of Embedchain App app = embedchain_bot(db_path, openai_access_token) # Get the Substack blog URL from the user substack_url = st.text_input("Enter Substack Newsletter URL", type="default") if substack_url: # Add the Substack blog to the knowledge base app.add(substack_url, data_type='substack') st.success(f"Added {substack_url} to knowledge base!") # Ask a question about the Substack blog query = st.text_input("Ask any question about the substack newsletter!") # Query the Substack blog if query: result = app.query(query) st.write(result)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf_llama3.2.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf_llama3.2.py
# Import necessary libraries import os import tempfile import streamlit as st from embedchain import App import base64 from streamlit_chat import message # Define the embedchain_bot function def embedchain_bot(db_path): return App.from_config( config={ "llm": {"provider": "ollama", "config": {"model": "llama3.2:latest", "max_tokens": 250, "temperature": 0.5, "stream": True, "base_url": 'http://localhost:11434'}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "ollama", "config": {"model": "llama3.2:latest", "base_url": 'http://localhost:11434'}}, } ) # Add a function to display PDF def display_pdf(file): base64_pdf = base64.b64encode(file.read()).decode('utf-8') pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="400" type="application/pdf"></iframe>' st.markdown(pdf_display, unsafe_allow_html=True) st.title("Chat with PDF using Llama 3.2") st.caption("This app allows you to chat with a PDF using Llama 3.2 running locally with Ollama!") # Define the database path db_path = tempfile.mkdtemp() # Create a session state to store the app instance and chat history if 'app' not in st.session_state: st.session_state.app = embedchain_bot(db_path) if 'messages' not in st.session_state: st.session_state.messages = [] # Sidebar for PDF upload and preview with st.sidebar: st.header("PDF Upload") pdf_file = st.file_uploader("Upload a PDF file", type="pdf") if pdf_file: st.subheader("PDF Preview") display_pdf(pdf_file) if st.button("Add to Knowledge Base"): with st.spinner("Adding PDF to knowledge base..."): with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f: f.write(pdf_file.getvalue()) st.session_state.app.add(f.name, data_type="pdf_file") os.remove(f.name) st.success(f"Added {pdf_file.name} to knowledge base!") # Chat interface for i, msg in enumerate(st.session_state.messages): message(msg["content"], is_user=msg["role"] == "user", key=str(i)) if prompt := st.chat_input("Ask a question about the PDF"): st.session_state.messages.append({"role": "user", "content": prompt}) message(prompt, is_user=True) with st.spinner("Thinking..."): response = st.session_state.app.chat(prompt) st.session_state.messages.append({"role": "assistant", "content": response}) message(response) # Clear chat history button if st.button("Clear Chat History"): st.session_state.messages = []
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf.py
import os import tempfile import streamlit as st from embedchain import App def embedchain_bot(db_path, api_key): return App.from_config( config={ "llm": {"provider": "openai", "config": {"api_key": api_key}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "openai", "config": {"api_key": api_key}}, } ) st.title("Chat with PDF") openai_access_token = st.text_input("OpenAI API Key", type="password") if openai_access_token: db_path = tempfile.mkdtemp() app = embedchain_bot(db_path, openai_access_token) pdf_file = st.file_uploader("Upload a PDF file", type="pdf") if pdf_file: with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f: f.write(pdf_file.getvalue()) app.add(f.name, data_type="pdf_file") os.remove(f.name) st.success(f"Added {pdf_file.name} to knowledge base!") prompt = st.text_input("Ask a question about the PDF") if prompt: answer = app.chat(prompt) st.write(answer)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf_llama3.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_pdf/chat_pdf_llama3.py
# Import necessary libraries import os import tempfile import streamlit as st from embedchain import App # Define the embedchain_bot function def embedchain_bot(db_path): return App.from_config( config={ "llm": {"provider": "ollama", "config": {"model": "llama3:instruct", "max_tokens": 250, "temperature": 0.5, "stream": True, "base_url": 'http://localhost:11434'}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "ollama", "config": {"model": "llama3:instruct", "base_url": 'http://localhost:11434'}}, } ) st.title("Chat with PDF") st.caption("This app allows you to chat with a PDF using Llama3 running locally wiht Ollama!") # Create a temporary directory to store the PDF file db_path = tempfile.mkdtemp() # Create an instance of the embedchain App app = embedchain_bot(db_path) # Upload a PDF file pdf_file = st.file_uploader("Upload a PDF file", type="pdf") # If a PDF file is uploaded, add it to the knowledge base if pdf_file: with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f: f.write(pdf_file.getvalue()) app.add(f.name, data_type="pdf_file") os.remove(f.name) st.success(f"Added {pdf_file.name} to knowledge base!") # Ask a question about the PDF prompt = st.text_input("Ask a question about the PDF") # Display the answer if prompt: answer = app.chat(prompt) st.write(answer)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_github/chat_github.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_github/chat_github.py
# Import the required libraries from embedchain.pipeline import Pipeline as App from embedchain.loaders.github import GithubLoader import streamlit as st import os loader = GithubLoader( config={ "token":"Your GitHub Token", } ) # Create Streamlit app st.title("Chat with GitHub Repository 💬") st.caption("This app allows you to chat with a GitHub Repo using OpenAI API") # Get OpenAI API key from user openai_access_token = st.text_input("OpenAI API Key", type="password") # If OpenAI API key is provided, create an instance of App if openai_access_token: os.environ["OPENAI_API_KEY"] = openai_access_token # Create an instance of Embedchain App app = App() # Get the GitHub repo from the user git_repo = st.text_input("Enter the GitHub Repo", type="default") if git_repo: # Add the repo to the knowledge base app.add("repo:" + git_repo + " " + "type:repo", data_type="github", loader=loader) st.success(f"Added {git_repo} to knowledge base!") # Ask a question about the Github Repo prompt = st.text_input("Ask any question about the GitHub Repo") # Chat with the GitHub Repo if prompt: answer = app.chat(prompt) st.write(answer)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_github/chat_github_llama3.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_github/chat_github_llama3.py
# Import the required libraries import tempfile from embedchain import App from embedchain.loaders.github import GithubLoader import streamlit as st import os GITHUB_TOKEN = os.getenv("Your GitHub Token") def get_loader(): loader = GithubLoader( config={ "token": GITHUB_TOKEN } ) return loader if "loader" not in st.session_state: st.session_state['loader'] = get_loader() loader = st.session_state.loader # Define the embedchain_bot function def embedchain_bot(db_path): return App.from_config( config={ "llm": {"provider": "ollama", "config": {"model": "llama3:instruct", "max_tokens": 250, "temperature": 0.5, "stream": True, "base_url": 'http://localhost:11434'}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "ollama", "config": {"model": "llama3:instruct", "base_url": 'http://localhost:11434'}}, } ) def load_repo(git_repo): global app # Add the repo to the knowledge base print(f"Adding {git_repo} to knowledge base!") app.add("repo:" + git_repo + " " + "type:repo", data_type="github", loader=loader) st.success(f"Added {git_repo} to knowledge base!") def make_db_path(): ret = tempfile.mkdtemp(suffix="chroma") print(f"Created Chroma DB at {ret}") return ret # Create Streamlit app st.title("Chat with GitHub Repository 💬") st.caption("This app allows you to chat with a GitHub Repo using Llama-3 running with Ollama") # Initialize the Embedchain App if "app" not in st.session_state: st.session_state['app'] = embedchain_bot(make_db_path()) app = st.session_state.app # Get the GitHub repo from the user git_repo = st.text_input("Enter the GitHub Repo", type="default") if git_repo and ("repos" not in st.session_state or git_repo not in st.session_state.repos): if "repos" not in st.session_state: st.session_state["repos"] = [git_repo] else: st.session_state.repos.append(git_repo) load_repo(git_repo) # Ask a question about the Github Repo prompt = st.text_input("Ask any question about the GitHub Repo") # Chat with the GitHub Repo if prompt: answer = st.session_state.app.chat(prompt) st.write(answer)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat_with_X_tutorials/chat_with_gmail/chat_gmail.py
advanced_llm_apps/chat_with_X_tutorials/chat_with_gmail/chat_gmail.py
import tempfile import streamlit as st from embedchain import App # Define the embedchain_bot function def embedchain_bot(db_path, api_key): return App.from_config( config={ "llm": {"provider": "openai", "config": {"model": "gpt-4-turbo", "temperature": 0.5, "api_key": api_key}}, "vectordb": {"provider": "chroma", "config": {"dir": db_path}}, "embedder": {"provider": "openai", "config": {"api_key": api_key}}, } ) # Create Streamlit app st.title("Chat with your Gmail Inbox 📧") st.caption("This app allows you to chat with your Gmail inbox using OpenAI API") # Get the OpenAI API key from the user openai_access_token = st.text_input("Enter your OpenAI API Key", type="password") # Set the Gmail filter statically gmail_filter = "to: me label:inbox" # Add the Gmail data to the knowledge base if the OpenAI API key is provided if openai_access_token: # Create a temporary directory to store the database db_path = tempfile.mkdtemp() # Create an instance of Embedchain App app = embedchain_bot(db_path, openai_access_token) app.add(gmail_filter, data_type="gmail") st.success(f"Added emails from Inbox to the knowledge base!") # Ask a question about the emails prompt = st.text_input("Ask any question about your emails") # Chat with the emails if prompt: answer = app.query(prompt) st.write(answer)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/finetune_gemma3.py
advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/finetune_gemma3.py
import torch from unsloth import FastModel # Unsloth fast loader + training utils from unsloth.chat_templates import get_chat_template, standardize_sharegpt from datasets import load_dataset # Hugging Face datasets from trl import SFTTrainer # Supervised fine-tuning trainer from transformers import TrainingArguments # Training hyperparameters # Minimal config (GPU expected). Adjust sizes: 270m, 1b, 4b, 12b, 27b MODEL_NAME = "unsloth/gemma-3-270m-it" MAX_SEQ_LEN = 2048 LOAD_IN_4BIT = True # 4-bit quantized loading for low VRAM LOAD_IN_8BIT = False # 8-bit quantized loading for low VRAM FULL_FINETUNING = False # LoRA adapters (efficient) instead of full FT def load_model_and_tokenizer(): # Load Gemma 3 + tokenizer with desired context/quantization model, tokenizer = FastModel.from_pretrained( model_name=MODEL_NAME, max_seq_length=MAX_SEQ_LEN, load_in_4bit=LOAD_IN_4BIT, load_in_8bit=LOAD_IN_8BIT, full_finetuning=FULL_FINETUNING, ) if not FULL_FINETUNING: # Add LoRA adapters on attention/MLP projections (PEFT) model = FastModel.get_peft_model( model, r=16, target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], ) # Apply Gemma 3 chat template for correct conversation formatting tokenizer = get_chat_template(tokenizer, chat_template="gemma-3") return model, tokenizer def prepare_dataset(tokenizer): # Load ShareGPT-style conversations and standardize schema dataset = load_dataset("mlabonne/FineTome-100k", split="train") dataset = standardize_sharegpt(dataset) # Render each conversation into a single training string dataset = dataset.map( lambda ex: {"text": [tokenizer.apply_chat_template(c, tokenize=False) for c in ex["conversations"]]}, batched=True, ) return dataset def train(model, dataset): # Choose precision based on CUDA capabilities use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported() use_fp16 = torch.cuda.is_available() and not use_bf16 trainer = SFTTrainer( model=model, train_dataset=dataset, dataset_text_field="text", max_seq_length=MAX_SEQ_LEN, args=TrainingArguments( per_device_train_batch_size=2, gradient_accumulation_steps=4, warmup_steps=5, max_steps=60, learning_rate=2e-4, bf16=use_bf16, fp16=use_fp16, logging_steps=1, output_dir="outputs", ), ) trainer.train() def main(): # 1) Load model/tokenizer, 2) Prep data, 3) Train, 4) Save weights model, tokenizer = load_model_and_tokenizer() dataset = prepare_dataset(tokenizer) train(model, dataset) model.save_pretrained("finetuned_model") if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_finetuning_tutorials/llama3.2_finetuning/finetune_llama3.2.py
advanced_llm_apps/llm_finetuning_tutorials/llama3.2_finetuning/finetune_llama3.2.py
import torch from unsloth import FastLanguageModel from datasets import load_dataset from trl import SFTTrainer from transformers import TrainingArguments from unsloth.chat_templates import get_chat_template, standardize_sharegpt # Load model and tokenizer model, tokenizer = FastLanguageModel.from_pretrained( model_name="unsloth/Llama-3.2-3B-Instruct", max_seq_length=2048, load_in_4bit=True, ) # Add LoRA adapters model = FastLanguageModel.get_peft_model( model, r=16, target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ], ) # Set up chat template and prepare dataset tokenizer = get_chat_template(tokenizer, chat_template="llama-3.1") dataset = load_dataset("mlabonne/FineTome-100k", split="train") dataset = standardize_sharegpt(dataset) dataset = dataset.map( lambda examples: { "text": [ tokenizer.apply_chat_template(convo, tokenize=False) for convo in examples["conversations"] ] }, batched=True ) # Set up trainer trainer = SFTTrainer( model=model, train_dataset=dataset, dataset_text_field="text", max_seq_length=2048, args=TrainingArguments( per_device_train_batch_size=2, gradient_accumulation_steps=4, warmup_steps=5, max_steps=60, learning_rate=2e-4, fp16=not torch.cuda.is_bf16_supported(), bf16=torch.cuda.is_bf16_supported(), logging_steps=1, output_dir="outputs", ), ) # Train the model trainer.train() # Save the finetuned model model.save_pretrained("finetuned_model")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/gpt_oss_critique_improvement_loop/streamlit_app.py
advanced_llm_apps/gpt_oss_critique_improvement_loop/streamlit_app.py
"""Streamlit Critique & Improvement Loop Demo using GPT-OSS via Groq This implements the "Automatic Critique + Improvement Loop" pattern: 1. Generate initial answer (Pro Mode style) 2. Have a critic model identify flaws/missing pieces 3. Revise the answer addressing all critiques 4. Repeat if needed Run with: streamlit run streamlit_app.py """ import os import time import concurrent.futures as cf from typing import List, Dict, Any import streamlit as st from groq import Groq, GroqError MODEL = "openai/gpt-oss-120b" MAX_COMPLETION_TOKENS = 1024 # stay within Groq limits SAMPLE_PROMPTS = [ "Explain how to implement a binary search tree in Python.", "What are the best practices for API design?", "How would you optimize a slow database query?", "Explain the concept of recursion with examples.", ] # --- Helper functions -------------------------------------------------------- def _one_completion(client: Groq, messages: List[Dict[str, str]], temperature: float) -> str: """Single non-streaming completion with basic retries.""" delay = 0.5 for attempt in range(3): try: resp = client.chat.completions.create( model=MODEL, messages=messages, temperature=temperature, max_completion_tokens=MAX_COMPLETION_TOKENS, top_p=1, stream=False, ) return resp.choices[0].message.content except GroqError: if attempt == 2: raise time.sleep(delay) delay *= 2 def generate_initial_answer(client: Groq, prompt: str) -> str: """Generate initial answer using parallel candidates + synthesis (Pro Mode).""" # Generate 3 candidates in parallel candidates = [] with cf.ThreadPoolExecutor(max_workers=3) as ex: futures = [ ex.submit(_one_completion, client, [{"role": "user", "content": prompt}], 0.9) for _ in range(3) ] for fut in cf.as_completed(futures): candidates.append(fut.result()) # Synthesize candidates candidate_texts = [] for i, c in enumerate(candidates): candidate_texts.append(f"--- Candidate {i+1} ---\n{c}") synthesis_prompt = ( f"You are given 3 candidate answers. Synthesize them into ONE best answer, " f"eliminating repetition and ensuring coherence:\n\n" f"{chr(10).join(candidate_texts)}\n\n" f"Return the single best final answer." ) return _one_completion(client, [{"role": "user", "content": synthesis_prompt}], 0.2) def critique_answer(client: Groq, prompt: str, answer: str) -> str: """Have a critic model identify flaws and missing pieces.""" critique_prompt = ( f"Original question: {prompt}\n\n" f"Answer to critique:\n{answer}\n\n" f"Act as a critical reviewer. List specific flaws, missing information, " f"unclear explanations, or areas that need improvement. Be constructive but thorough. " f"Format as a bulleted list starting with '•'." ) return _one_completion(client, [{"role": "user", "content": critique_prompt}], 0.3) def revise_answer(client: Groq, prompt: str, original_answer: str, critiques: str) -> str: """Revise the original answer addressing all critiques.""" revision_prompt = ( f"Original question: {prompt}\n\n" f"Original answer:\n{original_answer}\n\n" f"Critiques to address:\n{critiques}\n\n" f"Revise the original answer to address every critique point. " f"Maintain the good parts, fix the issues, and add missing information. " f"Return the improved answer." ) return _one_completion(client, [{"role": "user", "content": revision_prompt}], 0.2) def critique_improvement_loop(prompt: str, max_iterations: int = 2, groq_api_key: str | None = None) -> Dict[str, Any]: """Main function implementing the critique and improvement loop.""" client = Groq(api_key=groq_api_key) if groq_api_key else Groq() results = { "iterations": [], "final_answer": "", "total_iterations": 0 } # Generate initial answer with st.spinner("Generating initial answer..."): initial_answer = generate_initial_answer(client, prompt) results["iterations"].append({ "type": "initial", "answer": initial_answer, "critiques": None }) current_answer = initial_answer # Improvement loop for iteration in range(max_iterations): with st.spinner(f"Critiquing iteration {iteration + 1}..."): critiques = critique_answer(client, prompt, current_answer) with st.spinner(f"Revising iteration {iteration + 1}..."): revised_answer = revise_answer(client, prompt, current_answer, critiques) results["iterations"].append({ "type": "improvement", "answer": revised_answer, "critiques": critiques }) current_answer = revised_answer results["final_answer"] = current_answer results["total_iterations"] = len(results["iterations"]) return results # --- Streamlit UI ------------------------------------------------------------ st.set_page_config(page_title="Critique & Improvement Loop", page_icon="🔄", layout="wide") st.title("🔄 Critique & Improvement Loop") st.markdown( "Generate high-quality answers through iterative critique and improvement using GPT-OSS." ) with st.sidebar: st.header("Settings") api_key = st.text_input("Groq API Key", value=os.getenv("GROQ_API_KEY", ""), type="password") max_iterations = st.slider("Max Improvement Iterations", 1, 3, 2) st.markdown("---") st.caption("Each iteration adds critique + revision steps for higher quality.") # Initialize prompt in session state if not present if "prompt" not in st.session_state: st.session_state["prompt"] = "" def random_prompt_callback(): import random st.session_state["prompt"] = random.choice(SAMPLE_PROMPTS) prompt = st.text_area("Your prompt", height=150, placeholder="Ask me anything…", key="prompt") col1, col2 = st.columns([1, 1]) with col1: st.button("🔄 Random Sample Prompt", on_click=random_prompt_callback) with col2: generate_clicked = st.button("🚀 Start Critique Loop") if generate_clicked: if not prompt.strip(): st.error("Please enter a prompt.") st.stop() try: results = critique_improvement_loop(prompt, max_iterations, groq_api_key=api_key or None) except Exception as e: st.exception(e) st.stop() # Display results st.subheader("🎯 Final Answer") st.write(results["final_answer"]) # Show improvement history with st.expander(f"📋 Show Improvement History ({results['total_iterations']} iterations)"): for i, iteration in enumerate(results["iterations"]): if iteration["type"] == "initial": st.markdown(f"### 🚀 Initial Answer") st.write(iteration["answer"]) else: st.markdown(f"### 🔍 Iteration {i}") # Show critiques if iteration["critiques"]: st.markdown("**Critiques:**") st.write(iteration["critiques"]) # Show improved answer st.markdown("**Improved Answer:**") st.write(iteration["answer"]) if i < len(results["iterations"]) - 1: st.markdown("---") # Summary metrics st.markdown("---") col1, col2, col3 = st.columns(3) with col1: st.metric("Total Iterations", results["total_iterations"]) with col2: st.metric("Improvement Rounds", max_iterations) with col3: st.metric("Final Answer Length", len(results["final_answer"]))
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/multi_llm_memory/multi_llm_memory.py
advanced_llm_apps/llm_apps_with_memory_tutorials/multi_llm_memory/multi_llm_memory.py
import streamlit as st from mem0 import Memory from openai import OpenAI import os from litellm import completion st.title("Multi-LLM App with Shared Memory 🧠") st.caption("LLM App with a personalized memory layer that remembers each user's choices and interests across multiple users and LLMs") openai_api_key = st.text_input("Enter OpenAI API Key", type="password") anthropic_api_key = st.text_input("Enter Anthropic API Key", type="password") if openai_api_key and anthropic_api_key: os.environ["ANTHROPIC_API_KEY"] = anthropic_api_key # Initialize Mem0 with Qdrant config = { "vector_store": { "provider": "qdrant", "config": { "host": "localhost", "port": 6333, } }, } memory = Memory.from_config(config) user_id = st.sidebar.text_input("Enter your Username") llm_choice = st.sidebar.radio("Select LLM", ('OpenAI GPT-4o', 'Claude Sonnet 3.5')) if llm_choice == 'OpenAI GPT-4o': client = OpenAI(api_key=openai_api_key) elif llm_choice == 'Claude Sonnet 3.5': config = { "llm": { "provider": "litellm", "config": { "model": "claude-3-5-sonnet-20240620", "temperature": 0.5, "max_tokens": 2000, } } } client = Memory.from_config(config) prompt = st.text_input("Ask the LLM") if st.button('Chat with LLM'): with st.spinner('Searching...'): relevant_memories = memory.search(query=prompt, user_id=user_id) context = "Relevant past information:\n" if relevant_memories and "results" in relevant_memories: for memory in relevant_memories["results"]: if "memory" in memory: context += f"- {memory['memory']}\n" full_prompt = f"{context}\nHuman: {prompt}\nAI:" if llm_choice == 'OpenAI GPT-4o': response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant with access to past conversations."}, {"role": "user", "content": full_prompt} ] ) answer = response.choices[0].message.content elif llm_choice == 'Claude Sonnet 3.5': messages=[ {"role": "system", "content": "You are a helpful assistant with access to past conversations."}, {"role": "user", "content": full_prompt} ] response = completion(model="claude-3-5-sonnet-20240620", messages=messages) answer = response.choices[0].message.content st.write("Answer: ", answer) memory.add(answer, user_id=user_id) # Sidebar option to show memory st.sidebar.title("Memory Info") if st.button("View My Memory"): memories = memory.get_all(user_id=user_id) if memories and "results" in memories: st.write(f"Memory history for **{user_id}**:") for mem in memories["results"]: if "memory" in mem: st.write(f"- {mem['memory']}") else: st.sidebar.info("No learning history found for this user ID.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/llama3_stateful_chat/local_llama3_chat.py
advanced_llm_apps/llm_apps_with_memory_tutorials/llama3_stateful_chat/local_llama3_chat.py
import streamlit as st from openai import OpenAI # Set up the Streamlit App st.title("Local ChatGPT with Memory 🦙") st.caption("Chat with locally hosted memory-enabled Llama-3 using the LM Studio 💯") # Point to the local server setup using LM Studio client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio") # Initialize the chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display the chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): st.session_state.messages.append({"role": "system", "content": "When the input starts with /add, don't follow up with a prompt."}) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Generate response response = client.chat.completions.create( model="lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF", messages=st.session_state.messages, temperature=0.7 ) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response.choices[0].message.content}) # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response.choices[0].message.content)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/ai_travel_agent_memory/travel_agent_memory.py
advanced_llm_apps/llm_apps_with_memory_tutorials/ai_travel_agent_memory/travel_agent_memory.py
import streamlit as st from openai import OpenAI from mem0 import Memory # Set up the Streamlit App st.title("AI Travel Agent with Memory 🧳") st.caption("Chat with a travel assistant who remembers your preferences and past interactions.") # Set the OpenAI API key openai_api_key = st.text_input("Enter OpenAI API Key", type="password") if openai_api_key: # Initialize OpenAI client client = OpenAI(api_key=openai_api_key) # Initialize Mem0 with Qdrant config = { "vector_store": { "provider": "qdrant", "config": { "host": "localhost", "port": 6333, } }, } memory = Memory.from_config(config) # Sidebar for username and memory view st.sidebar.title("Enter your username:") previous_user_id = st.session_state.get("previous_user_id", None) user_id = st.sidebar.text_input("Enter your Username") if user_id != previous_user_id: st.session_state.messages = [] st.session_state.previous_user_id = user_id # Sidebar option to show memory st.sidebar.title("Memory Info") if st.button("View My Memory"): memories = memory.get_all(user_id=user_id) if memories and "results" in memories: st.write(f"Memory history for **{user_id}**:") for mem in memories["results"]: if "memory" in mem: st.write(f"- {mem['memory']}") else: st.sidebar.info("No learning history found for this user ID.") else: st.sidebar.error("Please enter a username to view memory info.") # Initialize the chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display the chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input prompt = st.chat_input("Where would you like to travel?") if prompt and user_id: # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Retrieve relevant memories relevant_memories = memory.search(query=prompt, user_id=user_id) context = "Relevant past information:\n" if relevant_memories and "results" in relevant_memories: for memory in relevant_memories["results"]: if "memory" in memory: context += f"- {memory['memory']}\n" # Prepare the full prompt full_prompt = f"{context}\nHuman: {prompt}\nAI:" # Generate response response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a travel assistant with access to past conversations."}, {"role": "user", "content": full_prompt} ] ) answer = response.choices[0].message.content # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": answer}) with st.chat_message("assistant"): st.markdown(answer) # Store the user query and AI response in memory memory.add(prompt, user_id=user_id, metadata={"role": "user"}) memory.add(answer, user_id=user_id, metadata={"role": "assistant"}) elif not user_id: st.error("Please enter a username to start the chat.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/ai_arxiv_agent_memory/ai_arxiv_agent_memory.py
advanced_llm_apps/llm_apps_with_memory_tutorials/ai_arxiv_agent_memory/ai_arxiv_agent_memory.py
import streamlit as st import os from mem0 import Memory from multion.client import MultiOn from openai import OpenAI st.title("AI Research Agent with Memory 📚") api_keys = {k: st.text_input(f"{k.capitalize()} API Key", type="password") for k in ['openai', 'multion']} if all(api_keys.values()): os.environ['OPENAI_API_KEY'] = api_keys['openai'] # Initialize Mem0 with Qdrant config = { "vector_store": { "provider": "qdrant", "config": { "model": "gpt-4o-mini", "host": "localhost", "port": 6333, } }, } memory, multion, openai_client = Memory.from_config(config), MultiOn(api_key=api_keys['multion']), OpenAI(api_key=api_keys['openai']) user_id = st.sidebar.text_input("Enter your Username") #user_interests = st.text_area("Research interests and background") search_query = st.text_input("Research paper search query") def process_with_gpt4(result): """Processes an arXiv search result to produce a structured markdown output. This function takes a search result from arXiv and generates a markdown-formatted table containing details about each paper. The table includes columns for the paper's title, authors, a brief abstract, and a link to the paper on arXiv. Args: result (str): The raw search result from arXiv, typically in a text format. Returns: str: A markdown-formatted string containing a table with paper details.""" prompt = f""" Based on the following arXiv search result, provide a proper structured output in markdown that is readable by the users. Each paper should have a title, authors, abstract, and link. Search Result: {result} Output Format: Table with the following columns: [{{"title": "Paper Title", "authors": "Author Names", "abstract": "Brief abstract", "link": "arXiv link"}}, ...] """ response = openai_client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.2) return response.choices[0].message.content if st.button('Search for Papers'): with st.spinner('Searching and Processing...'): relevant_memories = memory.search(search_query, user_id=user_id, limit=3) prompt = f"Search for arXiv papers: {search_query}\nUser background: {' '.join(mem['text'] for mem in relevant_memories)}" result = process_with_gpt4(multion.browse(cmd=prompt, url="https://arxiv.org/")) st.markdown(result) if st.sidebar.button("View Memory"): st.sidebar.write("\n".join([f"- {mem['text']}" for mem in memory.get_all(user_id=user_id)])) else: st.warning("Please enter your API keys to use this app.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/local_chatgpt_with_memory/local_chatgpt_memory.py
advanced_llm_apps/llm_apps_with_memory_tutorials/local_chatgpt_with_memory/local_chatgpt_memory.py
import streamlit as st from mem0 import Memory from litellm import completion # Configuration for Memory config = { "vector_store": { "provider": "qdrant", "config": { "collection_name": "local-chatgpt-memory", "host": "localhost", "port": 6333, "embedding_model_dims": 768, }, }, "llm": { "provider": "ollama", "config": { "model": "llama3.1:latest", "temperature": 0, "max_tokens": 8000, "ollama_base_url": "http://localhost:11434", # Ensure this URL is correct }, }, "embedder": { "provider": "ollama", "config": { "model": "nomic-embed-text:latest", # Alternatively, you can use "snowflake-arctic-embed:latest" "ollama_base_url": "http://localhost:11434", }, }, "version": "v1.1" } st.title("Local ChatGPT using Llama 3.1 with Personal Memory 🧠") st.caption("Each user gets their own personalized memory space!") # Initialize session state for chat history and previous user ID if "messages" not in st.session_state: st.session_state.messages = [] if "previous_user_id" not in st.session_state: st.session_state.previous_user_id = None # Sidebar for user authentication with st.sidebar: st.title("User Settings") user_id = st.text_input("Enter your Username", key="user_id") # Check if user ID has changed if user_id != st.session_state.previous_user_id: st.session_state.messages = [] # Clear chat history st.session_state.previous_user_id = user_id # Update previous user ID if user_id: st.success(f"Logged in as: {user_id}") # Initialize Memory with the configuration m = Memory.from_config(config) # Memory viewing section st.header("Memory Context") if st.button("View My Memory"): memories = m.get_all(user_id=user_id) if memories and "results" in memories: st.write(f"Memory history for **{user_id}**:") for memory in memories["results"]: if "memory" in memory: st.write(f"- {memory['memory']}") # Main chat interface if user_id: # Only show chat interface if user is "logged in" # Display chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # User input if prompt := st.chat_input("What is your message?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message with st.chat_message("user"): st.markdown(prompt) # Add to memory m.add(prompt, user_id=user_id) # Get context from memory memories = m.get_all(user_id=user_id) context = "" if memories and "results" in memories: for memory in memories["results"]: if "memory" in memory: context += f"- {memory['memory']}\n" # Generate assistant response with st.chat_message("assistant"): message_placeholder = st.empty() full_response = "" # Stream the response try: response = completion( model="ollama/llama3.1:latest", messages=[ {"role": "system", "content": "You are a helpful assistant with access to past conversations. Use the context provided to give personalized responses."}, {"role": "user", "content": f"Context from previous conversations with {user_id}: {context}\nCurrent message: {prompt}"} ], api_base="http://localhost:11434", stream=True ) # Process streaming response for chunk in response: if hasattr(chunk, 'choices') and len(chunk.choices) > 0: content = chunk.choices[0].delta.get('content', '') if content: full_response += content message_placeholder.markdown(full_response + "▌") # Final update message_placeholder.markdown(full_response) except Exception as e: st.error(f"Error generating response: {str(e)}") full_response = "I apologize, but I encountered an error generating the response." message_placeholder.markdown(full_response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": full_response}) # Add response to memory m.add(f"Assistant: {full_response}", user_id=user_id) else: st.info("👈 Please enter your username in the sidebar to start chatting!")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_apps_with_memory_tutorials/llm_app_personalized_memory/llm_app_memory.py
advanced_llm_apps/llm_apps_with_memory_tutorials/llm_app_personalized_memory/llm_app_memory.py
import os import streamlit as st from mem0 import Memory from openai import OpenAI st.title("LLM App with Memory 🧠") st.caption("LLM App with personalized memory layer that remembers ever user's choice and interests") openai_api_key = st.text_input("Enter OpenAI API Key", type="password") os.environ["OPENAI_API_KEY"] = openai_api_key if openai_api_key: # Initialize OpenAI client client = OpenAI(api_key=openai_api_key) # Initialize Mem0 with Qdrant config = { "vector_store": { "provider": "qdrant", "config": { "collection_name": "llm_app_memory", "host": "localhost", "port": 6333, } }, } memory = Memory.from_config(config) user_id = st.text_input("Enter your Username") prompt = st.text_input("Ask ChatGPT") if st.button('Chat with LLM'): with st.spinner('Searching...'): relevant_memories = memory.search(query=prompt, user_id=user_id) # Prepare context with relevant memories context = "Relevant past information:\n" for mem in relevant_memories: context += f"- {mem['text']}\n" # Prepare the full prompt full_prompt = f"{context}\nHuman: {prompt}\nAI:" # Get response from GPT-4 response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant with access to past conversations."}, {"role": "user", "content": full_prompt} ] ) answer = response.choices[0].message.content st.write("Answer: ", answer) # Add AI response to memory memory.add(answer, user_id=user_id) # Sidebar option to show memory st.sidebar.title("Memory Info") if st.button("View My Memory"): memories = memory.get_all(user_id=user_id) if memories and "results" in memories: st.write(f"Memory history for **{user_id}**:") for mem in memories["results"]: if "memory" in mem: st.write(f"- {mem['memory']}") else: st.sidebar.info("No learning history found for this user ID.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/quick_test.py
advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/quick_test.py
""" Quick test to verify Toonify installation and basic functionality Run this to quickly see the token savings in action! """ import json from toon import encode, decode def quick_test(): """Quick demonstration of Toonify savings.""" print("🎯 TOONIFY QUICK TEST") print("=" * 60) # Sample data: Product catalog products = { "products": [ {"id": 1, "name": "Laptop", "price": 1299, "stock": 45}, {"id": 2, "name": "Mouse", "price": 79, "stock": 120}, {"id": 3, "name": "Keyboard", "price": 89, "stock": 85}, {"id": 4, "name": "Monitor", "price": 399, "stock": 32}, {"id": 5, "name": "Webcam", "price": 129, "stock": 67} ] } # Convert to JSON json_str = json.dumps(products, indent=2) json_size = len(json_str) # Convert to TOON toon_str = encode(products) toon_size = len(toon_str) # Calculate savings reduction = ((json_size - toon_size) / json_size) * 100 # Display results print(f"\n📄 JSON ({json_size} bytes):") print(json_str) print(f"\n🎯 TOON ({toon_size} bytes):") print(toon_str) print(f"\n💰 Size Reduction: {reduction:.1f}%") print(f" Saved: {json_size - toon_size} bytes") # Verify roundtrip decoded = decode(toon_str) if decoded == products: print("\n✅ Roundtrip verification: PASSED") else: print("\n❌ Roundtrip verification: FAILED") return False print("\n" + "=" * 60) print("✨ Installation verified! Run toonify_demo.py for full demo.") print("=" * 60) return True if __name__ == "__main__": try: success = quick_test() exit(0 if success else 1) except ImportError as e: print(f"\n❌ Error: {e}") print("\n💡 Install dependencies with: pip install -r requirements.txt") exit(1) except Exception as e: print(f"\n❌ Unexpected error: {e}") exit(1)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/toonify_app.py
advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/toonify_app.py
""" Toonify Interactive Streamlit App Visualize token savings and test TOON format with your own data """ import streamlit as st import json from toon import encode, decode import tiktoken import pandas as pd def count_tokens(text: str, model: str = "gpt-4") -> int: """Count tokens in text.""" encoding = tiktoken.encoding_for_model(model) return len(encoding.encode(text)) def calculate_cost(tokens: int, model: str = "gpt-4") -> float: """Calculate API cost based on token count.""" pricing = { "gpt-4": 0.03 / 1000, # $0.03 per 1K tokens "gpt-4-turbo": 0.01 / 1000, "gpt-3.5-turbo": 0.0015 / 1000, "claude-3-opus": 0.015 / 1000, "claude-3-sonnet": 0.003 / 1000, } return tokens * pricing.get(model, 0.03 / 1000) def main(): st.set_page_config( page_title="Toonify Token Optimizer", page_icon="🎯", layout="wide" ) st.title("🎯 Toonify Token Optimization") st.markdown(""" Reduce your LLM API costs by **30-60%** using TOON format for structured data! [GitHub](https://github.com/ScrapeGraphAI/toonify) | [Documentation](https://docs.scrapegraphai.com/services/toonify) """) # Sidebar with st.sidebar: st.header("⚙️ Settings") model = st.selectbox( "LLM Model", ["gpt-4", "gpt-4-turbo", "gpt-3.5-turbo", "claude-3-opus", "claude-3-sonnet"], help="Select model for token counting and cost calculation" ) delimiter = st.selectbox( "TOON Delimiter", ["comma", "tab", "pipe"], help="Choose delimiter for array elements" ) key_folding = st.selectbox( "Key Folding", ["off", "safe"], help="Collapse nested single-key chains into dotted paths" ) st.markdown("---") st.markdown("### 💡 Quick Tips") st.info(""" **Best for:** - Tabular data - Product catalogs - Survey responses - Analytics data **Avoid for:** - Highly nested data - Irregular structures """) # Main content tab1, tab2, tab3 = st.tabs(["📊 Comparison", "✍️ Custom Data", "📈 Benchmark"]) with tab1: st.header("JSON vs TOON Comparison") # Example data selector example = st.selectbox( "Choose example dataset", [ "E-commerce Products", "Customer Orders", "Survey Responses", "Analytics Data" ] ) # Load example data examples = { "E-commerce Products": { "products": [ {"id": 1, "name": "Laptop Pro", "price": 1299, "stock": 45, "rating": 4.5}, {"id": 2, "name": "Magic Mouse", "price": 79, "stock": 120, "rating": 4.2}, {"id": 3, "name": "USB-C Cable", "price": 19, "stock": 350, "rating": 4.8}, {"id": 4, "name": "Keyboard", "price": 89, "stock": 85, "rating": 4.6}, {"id": 5, "name": "Monitor Stand", "price": 45, "stock": 60, "rating": 4.3} ] }, "Customer Orders": { "orders": [ {"order_id": "ORD001", "customer": "Alice", "total": 299.99, "status": "shipped"}, {"order_id": "ORD002", "customer": "Bob", "total": 149.50, "status": "processing"}, {"order_id": "ORD003", "customer": "Charlie", "total": 449.99, "status": "delivered"} ] }, "Survey Responses": { "responses": [ {"id": 1, "age": 25, "satisfaction": 4, "recommend": True, "comment": "Great service!"}, {"id": 2, "age": 34, "satisfaction": 5, "recommend": True, "comment": "Excellent!"}, {"id": 3, "age": 42, "satisfaction": 3, "recommend": False, "comment": "Could be better"} ] }, "Analytics Data": { "pageviews": [ {"page": "/home", "views": 1523, "avg_time": 45, "bounce_rate": 0.32}, {"page": "/products", "views": 892, "avg_time": 120, "bounce_rate": 0.45}, {"page": "/about", "views": 234, "avg_time": 60, "bounce_rate": 0.28} ] } } data = examples[example] # Convert formats json_str = json.dumps(data, indent=2) toon_options = { 'delimiter': delimiter, 'key_folding': key_folding } toon_str = encode(data, toon_options) # Calculate metrics json_size = len(json_str.encode('utf-8')) toon_size = len(toon_str.encode('utf-8')) json_tokens = count_tokens(json_str, model) toon_tokens = count_tokens(toon_str, model) size_reduction = ((json_size - toon_size) / json_size) * 100 token_reduction = ((json_tokens - toon_tokens) / json_tokens) * 100 json_cost = calculate_cost(json_tokens, model) toon_cost = calculate_cost(toon_tokens, model) cost_savings = json_cost - toon_cost # Display metrics col1, col2, col3, col4 = st.columns(4) with col1: st.metric("Size Reduction", f"{size_reduction:.1f}%") with col2: st.metric("Token Reduction", f"{token_reduction:.1f}%") with col3: st.metric("Cost per Call", f"${toon_cost:.6f}", f"-${cost_savings:.6f}") with col4: savings_1k = cost_savings * 1000 st.metric("Savings per 1K calls", f"${savings_1k:.2f}") # Side-by-side comparison col1, col2 = st.columns(2) with col1: st.subheader("📄 JSON Format") st.code(json_str, language="json") st.caption(f"Size: {json_size} bytes | Tokens: {json_tokens}") with col2: st.subheader("🎯 TOON Format") st.code(toon_str, language="text") st.caption(f"Size: {toon_size} bytes | Tokens: {toon_tokens}") # Cost projection st.subheader("💰 Cost Savings Projection") calls = [100, 1_000, 10_000, 100_000, 1_000_000] json_costs = [json_cost * n for n in calls] toon_costs = [toon_cost * n for n in calls] savings = [json_costs[i] - toon_costs[i] for i in range(len(calls))] df = pd.DataFrame({ "API Calls": [f"{n:,}" for n in calls], "JSON Cost": [f"${c:.2f}" for c in json_costs], "TOON Cost": [f"${c:.2f}" for c in toon_costs], "Savings": [f"${s:.2f}" for s in savings], "Savings %": [f"{token_reduction:.1f}%" for _ in calls] }) st.dataframe(df, use_container_width=True) with tab2: st.header("Test Your Own Data") st.markdown("Paste your JSON data below to see how much you can save:") user_json = st.text_area( "JSON Data", value='{\n "items": [\n {"id": 1, "name": "Example", "value": 100}\n ]\n}', height=300 ) if st.button("🎯 Convert to TOON"): try: # Parse JSON data = json.loads(user_json) # Convert to TOON toon_options = { 'delimiter': delimiter, 'key_folding': key_folding } toon_str = encode(data, toon_options) # Calculate savings json_size = len(user_json.encode('utf-8')) toon_size = len(toon_str.encode('utf-8')) json_tokens = count_tokens(user_json, model) toon_tokens = count_tokens(toon_str, model) size_reduction = ((json_size - toon_size) / json_size) * 100 token_reduction = ((json_tokens - toon_tokens) / json_tokens) * 100 # Display results st.success("✅ Conversion successful!") col1, col2, col3 = st.columns(3) with col1: st.metric("Size Reduction", f"{size_reduction:.1f}%") with col2: st.metric("Token Reduction", f"{token_reduction:.1f}%") with col3: cost_savings = calculate_cost(json_tokens - toon_tokens, model) st.metric("Savings per call", f"${cost_savings:.6f}") st.subheader("🎯 TOON Output") st.code(toon_str, language="text") # Verify roundtrip decoded = decode(toon_str) if decoded == data: st.success("✅ Roundtrip verification passed!") else: st.warning("⚠️ Roundtrip verification failed") except json.JSONDecodeError as e: st.error(f"❌ Invalid JSON: {e}") except Exception as e: st.error(f"❌ Error: {e}") with tab3: st.header("📈 Format Benchmark") st.markdown(""" Based on benchmarks across 50 real-world datasets: """) # Benchmark stats col1, col2, col3 = st.columns(3) with col1: st.metric("Avg Size Reduction", "63.9%") with col2: st.metric("Avg Token Reduction", "54.1%") with col3: st.metric("Best Case", "73.4%") # Data type performance st.subheader("Performance by Data Type") performance_data = { "Data Type": ["Tabular", "E-commerce", "Analytics", "Surveys", "Mixed"], "Token Reduction": [73.4, 68.2, 65.1, 61.5, 48.3], "Use Case": ["✅ Excellent", "✅ Excellent", "✅ Great", "✅ Great", "✅ Good"] } df = pd.DataFrame(performance_data) st.dataframe(df, use_container_width=True) st.info(""" **💡 Optimization Tips:** - Use TOON for uniform, structured data - Enable key folding for deeply nested objects - Choose appropriate delimiter based on your data - Test with your actual data for best results """) st.markdown("---") st.markdown(""" ### 🔗 Learn More - [GitHub Repository](https://github.com/ScrapeGraphAI/toonify) - [Documentation](https://docs.scrapegraphai.com/services/toonify) - [Format Specification](https://github.com/toon-format/toon) """) if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/toonify_demo.py
advanced_llm_apps/llm_optimization_tools/toonify_token_optimization/toonify_demo.py
""" Toonify Token Optimization Demo Demonstrates how to reduce LLM API costs by 30-60% using TOON format """ import json from toon import encode, decode import tiktoken from openai import OpenAI from anthropic import Anthropic import os def count_tokens(text: str, model: str = "gpt-4") -> int: """Count the number of tokens in a text string.""" encoding = tiktoken.encoding_for_model(model) return len(encoding.encode(text)) def format_comparison_demo(): """Compare JSON vs TOON format sizes and token counts.""" print("=" * 80) print("🎯 TOONIFY TOKEN OPTIMIZATION DEMO") print("=" * 80) # Example: E-commerce product catalog products_data = { "products": [ { "id": 101, "name": "Laptop Pro 15", "category": "Electronics", "price": 1299.99, "stock": 45, "rating": 4.5 }, { "id": 102, "name": "Magic Mouse", "category": "Electronics", "price": 79.99, "stock": 120, "rating": 4.2 }, { "id": 103, "name": "USB-C Cable", "category": "Accessories", "price": 19.99, "stock": 350, "rating": 4.8 }, { "id": 104, "name": "Wireless Keyboard", "category": "Electronics", "price": 89.99, "stock": 85, "rating": 4.6 }, { "id": 105, "name": "Monitor Stand", "category": "Accessories", "price": 45.99, "stock": 60, "rating": 4.3 } ] } # Convert to JSON json_str = json.dumps(products_data, indent=2) json_size = len(json_str.encode('utf-8')) json_tokens = count_tokens(json_str) # Convert to TOON toon_str = encode(products_data) toon_size = len(toon_str.encode('utf-8')) toon_tokens = count_tokens(toon_str) # Calculate savings size_reduction = ((json_size - toon_size) / json_size) * 100 token_reduction = ((json_tokens - toon_tokens) / json_tokens) * 100 print("\n📊 FORMAT COMPARISON") print("-" * 80) print("\n📄 JSON Format:") print(json_str) print(f"\nSize: {json_size} bytes") print(f"Tokens: {json_tokens}") print("\n" + "=" * 80) print("\n🎯 TOON Format:") print(toon_str) print(f"\nSize: {toon_size} bytes") print(f"Tokens: {toon_tokens}") print("\n" + "=" * 80) print("\n💰 SAVINGS") print("-" * 80) print(f"Size Reduction: {size_reduction:.1f}%") print(f"Token Reduction: {token_reduction:.1f}%") # Calculate cost savings # GPT-4 pricing: $0.03 per 1K tokens (input) cost_per_token = 0.03 / 1000 json_cost = json_tokens * cost_per_token toon_cost = toon_tokens * cost_per_token savings_per_call = json_cost - toon_cost print(f"\n💵 Cost per API call:") print(f" JSON: ${json_cost:.6f}") print(f" TOON: ${toon_cost:.6f}") print(f" Savings: ${savings_per_call:.6f} ({token_reduction:.1f}%)") print(f"\n📈 Projected savings:") print(f" Per 1,000 calls: ${savings_per_call * 1000:.2f}") print(f" Per 1M calls: ${savings_per_call * 1_000_000:.2f}") print("\n" + "=" * 80) return toon_str, products_data def llm_integration_demo(): """Demonstrate using TOON format with LLM APIs.""" print("\n🤖 LLM INTEGRATION DEMO") print("=" * 80) # Create sample data customer_orders = { "orders": [ {"order_id": "ORD001", "customer": "Alice", "total": 299.99, "status": "shipped"}, {"order_id": "ORD002", "customer": "Bob", "total": 149.50, "status": "processing"}, {"order_id": "ORD003", "customer": "Charlie", "total": 449.99, "status": "delivered"}, {"order_id": "ORD004", "customer": "Diana", "total": 89.99, "status": "pending"}, ] } # Convert to TOON toon_data = encode(customer_orders) json_data = json.dumps(customer_orders, indent=2) print("\n📦 Data to analyze:") print(toon_data) # Check if API keys are available openai_key = os.getenv("OPENAI_API_KEY") anthropic_key = os.getenv("ANTHROPIC_API_KEY") if openai_key: try: print("\n🔵 Testing with OpenAI GPT-4...") client = OpenAI(api_key=openai_key) prompt = f"""Analyze these customer orders and provide a brief summary: {toon_data} Provide: 1) Total revenue, 2) Orders by status, 3) Average order value""" response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": prompt}], max_tokens=200 ) print("\n✅ GPT-4 Response:") print(response.choices[0].message.content) # Show token usage print(f"\n📊 Token Usage:") print(f" Input tokens: {response.usage.prompt_tokens}") print(f" Output tokens: {response.usage.completion_tokens}") print(f" Total tokens: {response.usage.total_tokens}") # Compare with JSON json_tokens = count_tokens(prompt.replace(toon_data, json_data)) toon_tokens = response.usage.prompt_tokens savings = ((json_tokens - toon_tokens) / json_tokens) * 100 print(f"\n💰 Token Savings: {savings:.1f}% (vs JSON)") except Exception as e: print(f"❌ OpenAI Error: {e}") else: print("\n⚠️ Set OPENAI_API_KEY to test with GPT-4") if anthropic_key: try: print("\n🟣 Testing with Anthropic Claude...") client = Anthropic(api_key=anthropic_key) response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=200, messages=[{ "role": "user", "content": f"""Analyze these customer orders and provide a brief summary: {toon_data} Provide: 1) Total revenue, 2) Orders by status, 3) Average order value""" }] ) print("\n✅ Claude Response:") print(response.content[0].text) # Show token usage print(f"\n📊 Token Usage:") print(f" Input tokens: {response.usage.input_tokens}") print(f" Output tokens: {response.usage.output_tokens}") except Exception as e: print(f"❌ Anthropic Error: {e}") else: print("\n⚠️ Set ANTHROPIC_API_KEY to test with Claude") def advanced_features_demo(): """Demonstrate advanced TOON features.""" print("\n⚙️ ADVANCED FEATURES") print("=" * 80) # Key folding example nested_data = { 'api': { 'response': { 'product': { 'title': 'Wireless Keyboard', 'specs': { 'battery': '6 months', 'connectivity': 'Bluetooth 5.0' } } } } } print("\n1️⃣ Key Folding (collapse nested paths)") print("-" * 80) # Without key folding normal_toon = encode(nested_data) print("Without key folding:") print(normal_toon) # With key folding folded_toon = encode(nested_data, {'key_folding': 'safe'}) print("\nWith key folding:") print(folded_toon) print(f"\nSavings: {len(normal_toon)} → {len(folded_toon)} bytes") # Custom delimiters print("\n2️⃣ Custom Delimiters") print("-" * 80) data = { "items": [ ["Product A", "Description with, commas", 29.99], ["Product B", "Another, description", 39.99] ] } print("Tab delimiter (for data with commas):") tab_toon = encode(data, {'delimiter': 'tab'}) print(tab_toon) print("\nPipe delimiter:") pipe_toon = encode(data, {'delimiter': 'pipe'}) print(pipe_toon) def main(): """Run all demos.""" # Basic comparison toon_str, original_data = format_comparison_demo() # Verify roundtrip decoded_data = decode(toon_str) assert decoded_data == original_data, "Roundtrip failed!" print("\n✅ Roundtrip verification: PASSED") # LLM integration (optional, requires API keys) llm_integration_demo() # Advanced features advanced_features_demo() print("\n" + "=" * 80) print("🎉 Demo completed!") print("💡 Set OPENAI_API_KEY or ANTHROPIC_API_KEY to test LLM integration") print("🔗 Learn more: https://github.com/ScrapeGraphAI/toonify") print("=" * 80) if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/resume_job_matcher/app.py
advanced_llm_apps/resume_job_matcher/app.py
import streamlit as st import requests import fitz # PyMuPDF for PDF parsing st.set_page_config(page_title="📄 Resume & Job Matcher", layout="centered") st.title("📄 Resume & Job Matcher") st.sidebar.info(""" This app uses a local LLM via **Ollama**. 1. Install Ollama: https://ollama.ai 2. Run a model (e.g., `ollama run llama3`). 3. Upload a Resume + Job Description to get a fit score and suggestions. """) # Helper: Extract text from PDF def extract_pdf_text(file): text = "" with fitz.open(stream=file.read(), filetype="pdf") as doc: for page in doc: text += page.get_text() return text # File uploaders resume_file = st.file_uploader("Upload Resume (PDF/TXT)", type=["pdf", "txt"]) job_file = st.file_uploader("Upload Job Description (PDF/TXT)", type=["pdf", "txt"]) if st.button("🔍 Match Resume with Job Description"): if resume_file and job_file: # Extract Resume text if resume_file.type == "application/pdf": resume_text = extract_pdf_text(resume_file) else: resume_text = resume_file.read().decode("utf-8") # Extract Job text if job_file.type == "application/pdf": job_text = extract_pdf_text(job_file) else: job_text = job_file.read().decode("utf-8") # Prompt prompt = f""" You are an AI career assistant. Resume: {resume_text} Job Description: {job_text} Please analyze and return: 1. A **Fit Score** (0-100%) of how well this resume matches the job. 2. Key strengths (resume areas that align well). 3. Specific recommendations to improve the resume to better fit the job. Format neatly in Markdown. """ try: with st.spinner("⏳ Analyzing Resume vs Job Description..."): response = requests.post( "http://localhost:11434/api/generate", json={"model": "llama3", "prompt": prompt, "stream": False}, ) data = response.json() output = data.get("response", "⚠️ No response from model.") # Show Results st.subheader("📌 Match Analysis") st.markdown(output) # Save in session for download st.session_state["resume_match"] = output except Exception as e: st.error(f"An error occurred: {str(e)}") else: st.warning("⚠️ Please upload both Resume and Job Description.") # Download button if "resume_match" in st.session_state: st.download_button( "💾 Download Match Report", st.session_state["resume_match"], file_name="resume_match_report.md", mime="text/markdown" )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat-with-tarots/app.py
advanced_llm_apps/chat-with-tarots/app.py
from langchain.prompts import PromptTemplate import pandas as pd from langchain_core.runnables import RunnableParallel, RunnableLambda # Import necessary for LCEL import random import streamlit as st import helpers.help_func as hf from PIL import Image # --- Load the dataset --- csv_file_path = 'data/tarots.csv' try: # Read CSV file df = pd.read_csv(csv_file_path, sep=';', encoding='latin1') print(f"CSV dataset loaded successfully: {csv_file_path}. Number of rows: {len(df)}") # Clean and normalize column names df.columns = df.columns.str.strip().str.lower() # Debug: Show column details print("\nDetails after cleanup:") for col in df.columns: print(f"Column: '{col}' (length: {len(col)})") # Define required columns (in lowercase) required_columns = ['card', 'upright', 'reversed', 'symbolism'] # Verify all required columns are present available_columns = set(df.columns) missing_columns = [col for col in required_columns if col not in available_columns] if missing_columns: raise ValueError( f"Missing columns in CSV file: {', '.join(missing_columns)}\n" f"Available columns: {', '.join(available_columns)}" ) # Create card meanings dictionary with cleaned data card_meanings = {} for _, row in df.iterrows(): card_name = row['card'].strip() card_meanings[card_name] = { 'upright': str(row['upright']).strip() if pd.notna(row['upright']) else '', 'reversed': str(row['reversed']).strip() if pd.notna(row['reversed']) else '', 'symbolism': str(row['symbolism']).strip() if pd.notna(row['symbolism']) else '' } print(f"\nKnowledge base created with {len(card_meanings)} cards, meanings and symbolisms.") except FileNotFoundError: print(f"Error: CSV File not found: {csv_file_path}") raise except ValueError as e: print(f"Validation Error: {str(e)}") raise except Exception as e: print(f"Unexpected error: {str(e)}") raise # --- Define the Prompt Template --- prompt_analysis = PromptTemplate.from_template(""" Analyze the following tarot cards, based on the meanings provided (also considering if they are reversed): {card_details} Pay attention to these aspects: - Provide a detailed analysis of the meaning of each card (upright or reversed). - Then offer a general interpretation of the answer based on the cards, linking it to the context: {context}. - Be mystical and provide information on the interpretation related to the symbolism of the cards, based on the specific column: {symbolism}. - At the end of the reading, always offer advice to improve or address the situation. Also, base it on your knowledge of psychology. """) print("\nPrompt Template 'prompt_analysis' defined.") # --- Create the LangChain Chain --- analyzer = ( RunnableParallel( cards=lambda x: x['cards'], context=lambda x: x['context'] ) | (lambda x: hf.prepare_prompt_input(x, card_meanings)) | prompt_analysis | hf.llm ) # --- Frontend Streamlit --- st.set_page_config( page_title="🔮 Interactive Tarot Reading", page_icon="🃏", layout="wide", initial_sidebar_state="expanded" ) st.title("🔮 Interactive Tarot Reading") st.markdown("Welcome to your personalized tarot consultation!") st.markdown("---") num_cards = st.selectbox("🃏 Select the number of cards for your spread (3 for a more focused answer, 7 for a more general overview).)", [3, 5, 7]) context_question = st.text_area("✍️ Please enter your context or your question here. You can speak in natural language.", height=100) if st.button("✨ Light your path: Draw and Analyze the Cards."): if not context_question: st.warning("For a more precise reading, please enter your context or question.") else: try: card_names_in_dataset = df['card'].unique().tolist() drawn_cards_list = hf.generate_random_draw(num_cards, card_names_in_dataset) st.subheader("✨ Your Cards Revealed:") st.markdown("---") cols = st.columns(len(drawn_cards_list)) for i, card_info in enumerate(drawn_cards_list): with cols[i]: # The card_info['name'] from data/tarots.csv is now the direct image filename e.g., "00-thefool.jpg" image_filename = card_info['name'] image_path = f"images/{image_filename}" reversed_label = "(R)" if 'is_reversed' in card_info else "" caption = f"{card_info['name']} {reversed_label}" try: img = Image.open(image_path) if card_info.get('is_reversed', False): img = img.rotate(180) st.image(img, caption=caption, width=150) except FileNotFoundError: st.info(f"Symbol: {card_info['name']} {reversed_label} (Image not found at {image_path})") st.markdown("---") with st.spinner("🔮 Unveiling the meanings..."): analysis_result = analyzer.invoke({"cards": drawn_cards_list, "context": context_question}) st.subheader("📜 The Interpretation:") st.write(analysis_result.content) except Exception as e: st.error(f"An error has occurred: {e}") st.error(f"Error details: {e}") st.markdown("---") st.info("Remember, the cards offer insights and reflections; your future is in your hands.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/chat-with-tarots/helpers/help_func.py
advanced_llm_apps/chat-with-tarots/helpers/help_func.py
import random from langchain_ollama import ChatOllama # --- Function to generate a random draw of cards --- def generate_random_draw(num_cards, card_names_dataset): """ Generates a list of dictionaries representing a random draw of cards. Args: num_cards (int): The number of cards to include in the draw (3, 5, or 7). card_names_dataset (list): A list of strings containing the names of the available cards in the dataset. Returns: list: A list of dictionaries, where each dictionary has the key "name" (the name of the drawn card) and an optional "is_reversed" key (True if the card is reversed, otherwise absent). """ if num_cards not in [3, 5, 7]: raise ValueError("The number of cards must be 3, 5, or 7.") drawn_cards = [] drawn_cards_sample = random.sample(card_names_dataset, num_cards) for card_name in drawn_cards_sample: card = {"name": card_name} if random.choice([True, False]): card["is_reversed"] = True drawn_cards.append(card) return drawn_cards # --- Helper Functions for LangChain Chain --- def format_card_details_for_prompt(card_data, card_meanings): """Formats card details (name + upright/reversed meaning) for the prompt.""" details = [] for card_info in card_data: card_name = card_info['name'] is_reversed = card_info.get('is_reversed', False) if card_name in card_meanings: meanings = card_meanings[card_name] if is_reversed and 'reversed' in meanings: meaning = meanings['reversed'] orientation = "(reversed)" else: meaning = meanings['upright'] orientation = "(upright)" details.append(f"Card: {card_name} {orientation} - Meaning: {meaning}") else: details.append(f"Meaning of '{card_name}' not found in the dataset.") return "\n".join(details) def prepare_prompt_input(input_dict, meanings_dict): """Prepares the input for the prompt by retrieving card details.""" card_list = input_dict['cards'] context = input_dict['context'] formatted_details = format_card_details_for_prompt(card_list, meanings_dict) # Extract and concatenate the symbolism of each card symbolisms = [] for card_info in card_list: card_name = card_info['name'] if card_name in meanings_dict: symbolism = meanings_dict[card_name].get('symbolism', '') if symbolism: symbolisms.append(f"{card_name}: {symbolism}") symbolism_str = "\n".join(symbolisms) return {"card_details": formatted_details, "context": context, "symbolism": symbolism_str} # --- Configure the LLM model --- llm = ChatOllama( base_url ="http://localhost:11434", model = "phi4", temperature = 0.8, ) print(f"\nLLM model '{llm.model}' configured.") print("\nChain 'analyzer' defined.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/cursor_ai_experiments/ai_web_scrapper.py
advanced_llm_apps/cursor_ai_experiments/ai_web_scrapper.py
import streamlit as st from scrapegraphai.graphs import SmartScraperGraph # Streamlit app title st.title("AI Web Scraper") # Input fields for user prompt and source URL prompt = st.text_input("Enter the information you want to extract:") source_url = st.text_input("Enter the source URL:") # Input field for OpenAI API key api_key = st.text_input("Enter your OpenAI API key:", type="password") # Configuration for the scraping pipeline graph_config = { "llm": { "api_key": api_key, "model": "openai/gpt-4o-mini", }, "verbose": True, "headless": False, } # Button to start the scraping process if st.button("Scrape"): if prompt and source_url and api_key: # Create the SmartScraperGraph instance smart_scraper_graph = SmartScraperGraph( prompt=prompt, source=source_url, config=graph_config ) # Run the pipeline result = smart_scraper_graph.run() # Display the result st.write(result) else: st.error("Please provide all the required inputs.") # Instructions for the user st.markdown(""" ### Instructions 1. Enter the information you want to extract in the first input box. 2. Enter the source URL from which you want to extract the information. 3. Enter your OpenAI API key. 4. Click on the "Scrape" button to start the scraping process. """)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/cursor_ai_experiments/multi_agent_researcher.py
advanced_llm_apps/cursor_ai_experiments/multi_agent_researcher.py
import streamlit as st from crewai import Agent, Task, Crew, Process from langchain_openai import ChatOpenAI import os # Initialize the GPT-4 model gpt4_model = None def create_article_crew(topic): """Creates a team of agents to research, write, and edit an article on a given topic. This function sets up a crew consisting of three agents: a researcher, a writer, and an editor. Each agent is assigned a specific task to ensure the production of a well-researched, well-written, and polished article. The article is formatted using markdown standards. Args: topic (str): The subject matter on which the article will be based. Returns: Crew: A crew object that contains the agents and tasks necessary to complete the article.""" # Create agents researcher = Agent( role='Researcher', goal='Conduct thorough research on the given topic', backstory='You are an expert researcher with a keen eye for detail', verbose=True, allow_delegation=False, llm=gpt4_model ) writer = Agent( role='Writer', goal='Write a detailed and engaging article based on the research, using proper markdown formatting', backstory='You are a skilled writer with expertise in creating informative content and formatting it beautifully in markdown', verbose=True, allow_delegation=False, llm=gpt4_model ) editor = Agent( role='Editor', goal='Review and refine the article for clarity, accuracy, engagement, and proper markdown formatting', backstory='You are an experienced editor with a sharp eye for quality content and excellent markdown structure', verbose=True, allow_delegation=False, llm=gpt4_model ) # Create tasks research_task = Task( description=f"Conduct comprehensive research on the topic: {topic}. Gather key information, statistics, and expert opinions.", agent=researcher, expected_output="A comprehensive research report on the given topic, including key information, statistics, and expert opinions." ) writing_task = Task( description="""Using the research provided, write a detailed and engaging article. Ensure proper structure, flow, and clarity. Format the article using markdown, including: 1. A main title (H1) 2. Section headings (H2) 3. Subsection headings where appropriate (H3) 4. Bullet points or numbered lists where relevant 5. Emphasis on key points using bold or italic text Make sure the content is well-organized and easy to read.""", agent=writer, expected_output="A well-structured, detailed, and engaging article based on the provided research, formatted in markdown with proper headings and subheadings." ) editing_task = Task( description="""Review the article for clarity, accuracy, engagement, and proper markdown formatting. Ensure that: 1. The markdown formatting is correct and consistent 2. Headings and subheadings are used appropriately 3. The content flow is logical and engaging 4. Key points are emphasized correctly Make necessary edits and improvements to both content and formatting.""", agent=editor, expected_output="A final, polished version of the article with improved clarity, accuracy, engagement, and proper markdown formatting." ) # Create the crew crew = Crew( agents=[researcher, writer, editor], tasks=[research_task, writing_task, editing_task], verbose=2, process=Process.sequential ) return crew # Streamlit app st.set_page_config(page_title="Multi Agent AI Researcher", page_icon="📝") # Custom CSS for better appearance st.markdown(""" <style> .stApp { max-width: 1800px; margin: 0 auto; font-family: Arial, sans-serif; } .st-bw { background-color: #f0f2f6; } .stButton>button { background-color: #4CAF50; color: white; font-weight: bold; } .stTextInput>div>div>input { background-color: #ffffff; } </style> """, unsafe_allow_html=True) st.title("📝 Multi Agent AI Researcher") # Sidebar for API key input with st.sidebar: st.header("Configuration") api_key = st.text_input("Enter your OpenAI API Key:", type="password") if api_key: os.environ["OPENAI_API_KEY"] = api_key gpt4_model = ChatOpenAI(model_name="gpt-4o-mini") st.success("API Key set successfully!") else: st.info("Please enter your OpenAI API Key to proceed.") # Main content st.markdown("Generate detailed articles on any topic using AI agents!") topic = st.text_input("Enter the topic for the article:", placeholder="e.g., The Impact of Artificial Intelligence on Healthcare") if st.button("Generate Article"): if not api_key: st.error("Please enter your OpenAI API Key in the sidebar.") elif not topic: st.warning("Please enter a topic for the article.") else: with st.spinner("🤖 AI agents are working on your article..."): crew = create_article_crew(topic) result = crew.kickoff() st.markdown(result) st.markdown("---") st.markdown("Powered by CrewAI and OpenAI :heart:")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/cursor_ai_experiments/chatgpt_clone_llama3.py
advanced_llm_apps/cursor_ai_experiments/chatgpt_clone_llama3.py
import streamlit as st from ollama import Client # Initialize Ollama client client = Client() # Set up Streamlit page st.set_page_config(page_title="Local ChatGPT Clone", page_icon="🤖", layout="wide") st.title("🤖 Local ChatGPT Clone") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # User input if prompt := st.chat_input("What's on your mind?"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Generate AI response with st.chat_message("assistant"): message_placeholder = st.empty() full_response = "" for response in client.chat(model="llama3.1:latest", messages=st.session_state.messages, stream=True): full_response += response['message']['content'] message_placeholder.markdown(full_response + "▌") message_placeholder.markdown(full_response) st.session_state.messages.append({"role": "assistant", "content": full_response}) # Add a sidebar with information st.sidebar.title("About") st.sidebar.info("This is a local ChatGPT clone using Ollama's llama3.1:latest model and Streamlit.") st.sidebar.markdown("---") st.sidebar.markdown("Made with ❤️ by Your Name")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/cursor_ai_experiments/llm_router_app/llm_router.py
advanced_llm_apps/cursor_ai_experiments/llm_router_app/llm_router.py
import os os.environ["OPENAI_API_KEY"] = "your_openai_api_key" os.environ['TOGETHERAI_API_KEY'] = "your_togetherai_api_key" import streamlit as st from routellm.controller import Controller # Initialize RouteLLM client client = Controller( routers=["mf"], strong_model="gpt-4o-mini", weak_model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", ) # Set up Streamlit app st.title("RouteLLM Chat App") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if "model" in message: st.caption(f"Model used: {message['model']}") # Chat input if prompt := st.chat_input("What is your message?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Get RouteLLM response with st.chat_message("assistant"): message_placeholder = st.empty() response = client.chat.completions.create( model="router-mf-0.11593", messages=[{"role": "user", "content": prompt}] ) message_content = response['choices'][0]['message']['content'] model_name = response['model'] # Display assistant's response message_placeholder.markdown(message_content) st.caption(f"Model used: {model_name}") # Add assistant's response to chat history st.session_state.messages.append({"role": "assistant", "content": message_content, "model": model_name})
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_llm_apps/cursor_ai_experiments/local_chatgpt_clone/chatgpt_clone_llama3.py
advanced_llm_apps/cursor_ai_experiments/local_chatgpt_clone/chatgpt_clone_llama3.py
import streamlit as st from openai import OpenAI # Set up the Streamlit App st.title("ChatGPT Clone using Llama-3 🦙") st.caption("Chat with locally hosted Llama-3 using the LM Studio 💯") # Point to the local server setup using LM Studio client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio") # Initialize the chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display the chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Generate response response = client.chat.completions.create( model="lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF", messages=st.session_state.messages, temperature=0.7 ) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response.choices[0].message.content}) # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response.choices[0].message.content)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/product_launch_intelligence_agent/product_launch_intelligence_agent.py
advanced_ai_agents/multi_agent_apps/product_launch_intelligence_agent/product_launch_intelligence_agent.py
import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.team import Team from agno.models.openai import OpenAIChat from agno.tools.firecrawl import FirecrawlTools from dotenv import load_dotenv from textwrap import dedent import os # ---------------- Page Config ---------------- st.set_page_config( page_title="AI Product Intelligence Agent", page_icon="🚀", layout="wide", initial_sidebar_state="expanded" ) # ---------------- Environment & Agent ---------------- load_dotenv() # Add API key inputs in sidebar st.sidebar.header("🔑 API Configuration") with st.sidebar.container(): openai_key = st.text_input( "OpenAI API Key", type="password", value=os.getenv("OPENAI_API_KEY", ""), help="Required for AI agent functionality" ) firecrawl_key = st.text_input( "Firecrawl API Key", type="password", value=os.getenv("FIRECRAWL_API_KEY", ""), help="Required for web search and crawling" ) # Set environment variables if openai_key: os.environ["OPENAI_API_KEY"] = openai_key if firecrawl_key: os.environ["FIRECRAWL_API_KEY"] = firecrawl_key # Initialize team only if both keys are provided if openai_key and firecrawl_key: # Agent 1: Competitor Launch Analyst launch_analyst = Agent( name="Product Launch Analyst", description=dedent(""" You are a senior Go-To-Market strategist who evaluates competitor product launches with a critical, evidence-driven lens. Your objective is to uncover: • How the product is positioned in the market • Which launch tactics drove success (strengths) • Where execution fell short (weaknesses) • Actionable learnings competitors can leverage Always cite observable signals (messaging, pricing actions, channel mix, timing, engagement metrics). Maintain a crisp, executive tone and focus on strategic value. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Agent 2: Market Sentiment Specialist sentiment_analyst = Agent( name="Market Sentiment Specialist", description=dedent(""" You are a market research expert specializing in sentiment analysis and consumer perception tracking. Your expertise includes: • Analyzing social media sentiment and customer feedback • Identifying positive and negative sentiment drivers • Tracking brand perception trends across platforms • Monitoring customer satisfaction and review patterns • Providing actionable insights on market reception Focus on extracting sentiment signals from social platforms, review sites, forums, and customer feedback channels. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Agent 3: Launch Metrics Specialist metrics_analyst = Agent( name="Launch Metrics Specialist", description=dedent(""" You are a product launch performance analyst who specializes in tracking and analyzing launch KPIs. Your focus areas include: • User adoption and engagement metrics • Revenue and business performance indicators • Market penetration and growth rates • Press coverage and media attention analysis • Social media traction and viral coefficient tracking • Competitive market share analysis Always provide quantitative insights with context and benchmark against industry standards when possible. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Create the coordinated team product_intelligence_team = Team( name="Product Intelligence Team", model=OpenAIChat(id="gpt-4o"), members=[launch_analyst, sentiment_analyst, metrics_analyst], instructions=[ "Coordinate the analysis based on the user's request type:", "1. For competitor analysis: Use the Product Launch Analyst to evaluate positioning, strengths, weaknesses, and strategic insights", "2. For market sentiment: Use the Market Sentiment Specialist to analyze social media sentiment, customer feedback, and brand perception", "3. For launch metrics: Use the Launch Metrics Specialist to track KPIs, adoption rates, press coverage, and performance indicators", "Always provide evidence-based insights with specific examples and data points", "Structure responses with clear sections and actionable recommendations", "Include sources section with all URLs crawled or searched" ], markdown=True, debug_mode=True, show_members_responses=True, ) else: product_intelligence_team = None st.warning("⚠️ Please enter both API keys in the sidebar to use the application.") # Helper to craft competitor-focused launch report for product managers def expand_competitor_report(bullet_text: str, competitor: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Transform the insight bullets below into a professional launch review for product managers analysing {competitor}.\n\n" f"Produce well-structured **Markdown** with a mix of tables, call-outs and concise bullet points — avoid long paragraphs.\n\n" f"=== FORMAT SPECIFICATION ===\n" f"# {competitor} – Launch Review\n\n" f"## 1. Market & Product Positioning\n" f"• Bullet point summary of how the product is positioned (max 6 bullets).\n\n" f"## 2. Launch Strengths\n" f"| Strength | Evidence / Rationale |\n|---|---|\n| … | … | (add 4-6 rows)\n\n" f"## 3. Launch Weaknesses\n" f"| Weakness | Evidence / Rationale |\n|---|---|\n| … | … | (add 4-6 rows)\n\n" f"## 4. Strategic Takeaways for Competitors\n" f"1. … (max 5 numbered recommendations)\n\n" f"=== SOURCE BULLETS ===\n{bullet_text}\n\n" f"Guidelines:\n" f"• Populate the tables with specific points derived from the bullets.\n" f"• Only include rows that contain meaningful data; omit any blank entries." ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # Helper to craft market sentiment report def expand_sentiment_report(bullet_text: str, product: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Use the tagged bullets below to create a concise market-sentiment brief for **{product}**.\n\n" f"### Positive Sentiment\n" f"• List each positive point as a separate bullet (max 6).\n\n" f"### Negative Sentiment\n" f"• List each negative point as a separate bullet (max 6).\n\n" f"### Overall Summary\n" f"Provide a short paragraph (≤120 words) summarising the overall sentiment balance and key drivers.\n\n" f"Tagged Bullets:\n{bullet_text}" ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # Helper to craft launch metrics report def expand_metrics_report(bullet_text: str, launch: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Convert the KPI bullets below into a launch-performance snapshot for **{launch}** suitable for an executive dashboard.\n\n" f"## Key Performance Indicators\n" f"| Metric | Value / Detail | Source |\n" f"|---|---|---|\n" f"| … | … | … | (include one row per KPI)\n\n" f"## Qualitative Signals\n" f"• Bullet list of notable qualitative insights (max 5).\n\n" f"## Summary & Implications\n" f"Brief paragraph (≤120 words) highlighting what the metrics imply about launch success and next steps.\n\n" f"KPI Bullets:\n{bullet_text}" ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # ---------------- UI ---------------- st.title("🚀 AI Product Launch Intelligence Agent") st.markdown("*AI-powered insights for GTM, Product Marketing & Growth Teams*") st.divider() # Company input section st.subheader("🏢 Company Analysis") with st.container(): col1, col2 = st.columns([3, 1]) with col1: company_name = st.text_input( label="Company Name", placeholder="Enter company name (e.g., OpenAI, Tesla, Spotify)", help="This company will be analyzed by the coordinated team of specialized agents", label_visibility="collapsed" ) with col2: if company_name: st.success(f"✓ Ready to analyze **{company_name}**") st.divider() # Create tabs for analysis types analysis_tabs = st.tabs([ "🔍 Competitor Analysis", "💬 Market Sentiment", "📈 Launch Metrics" ]) # Store separate responses for each agent if "competitor_response" not in st.session_state: st.session_state.competitor_response = None if "sentiment_response" not in st.session_state: st.session_state.sentiment_response = None if "metrics_response" not in st.session_state: st.session_state.metrics_response = None # -------- Competitor Analysis Tab -------- with analysis_tabs[0]: with st.container(): st.markdown("### 🔍 Competitor Launch Analysis") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Product Launch Analyst** - Strategic GTM Expert Specializes in: - Competitive positioning analysis - Launch strategy evaluation - Strengths & weaknesses identification - Strategic recommendations """) if company_name: col1, col2 = st.columns([2, 1]) with col1: analyze_btn = st.button( "🚀 Analyze Competitor Strategy", key="competitor_btn", type="primary", use_container_width=True ) with col2: if st.session_state.competitor_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if analyze_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("🔍 Product Intelligence Team analyzing competitive strategy..."): try: bullets: RunOutput = product_intelligence_team.run( f"Generate up to 16 evidence-based insight bullets about {company_name}'s most recent product launches.\n" f"Format requirements:\n" f"• Start every bullet with exactly one tag: Positioning | Strength | Weakness | Learning\n" f"• Follow the tag with a concise statement (max 30 words) referencing concrete observations: messaging, differentiation, pricing, channel selection, timing, engagement metrics, or customer feedback." ) long_text = expand_competitor_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.competitor_response = long_text st.success("✅ Competitor analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.competitor_response: st.divider() with st.container(): st.markdown("### 📊 Analysis Results") st.markdown(st.session_state.competitor_response) else: st.info("👆 Please enter a company name above to start the analysis") # -------- Market Sentiment Tab -------- with analysis_tabs[1]: with st.container(): st.markdown("### 💬 Market Sentiment Analysis") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Market Sentiment Specialist** - Consumer Perception Expert Specializes in: - Social media sentiment tracking - Customer feedback analysis - Brand perception monitoring - Review pattern identification """) if company_name: col1, col2 = st.columns([2, 1]) with col1: sentiment_btn = st.button( "📊 Analyze Market Sentiment", key="sentiment_btn", type="primary", use_container_width=True ) with col2: if st.session_state.sentiment_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if sentiment_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("💬 Product Intelligence Team analyzing market sentiment..."): try: bullets: RunOutput = product_intelligence_team.run( f"Summarize market sentiment for {company_name} in <=10 bullets. " f"Cover top positive & negative themes with source mentions (G2, Reddit, Twitter, customer reviews)." ) long_text = expand_sentiment_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.sentiment_response = long_text st.success("✅ Sentiment analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.sentiment_response: st.divider() with st.container(): st.markdown("### 📈 Analysis Results") st.markdown(st.session_state.sentiment_response) else: st.info("👆 Please enter a company name above to start the analysis") # -------- Launch Metrics Tab -------- with analysis_tabs[2]: with st.container(): st.markdown("### 📈 Launch Performance Metrics") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Launch Metrics Specialist** - Performance Analytics Expert Specializes in: - User adoption metrics tracking - Revenue performance analysis - Market penetration evaluation - Press coverage monitoring """) if company_name: col1, col2 = st.columns([2, 1]) with col1: metrics_btn = st.button( "📊 Analyze Launch Metrics", key="metrics_btn", type="primary", use_container_width=True ) with col2: if st.session_state.metrics_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if metrics_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("📈 Product Intelligence Team analyzing launch metrics..."): try: bullets: RunOutput = product_intelligence_team.run( f"List (max 10 bullets) the most important publicly available KPIs & qualitative signals for {company_name}'s recent product launches. " f"Include engagement stats, press coverage, adoption metrics, and market traction data if available." ) long_text = expand_metrics_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.metrics_response = long_text st.success("✅ Metrics analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.metrics_response: st.divider() with st.container(): st.markdown("### 📊 Analysis Results") st.markdown(st.session_state.metrics_response) else: st.info("👆 Please enter a company name above to start the analysis") # ---------------- Sidebar ---------------- # Agent status indicators with st.sidebar.container(): st.markdown("### 🤖 System Status") if openai_key and firecrawl_key: st.success("✅ Product Intelligence Team ready") else: st.error("❌ API keys required") st.sidebar.divider() # Multi-agent system info with st.sidebar.container(): st.markdown("### 🎯 Coordinated Team") agents_info = [ ("🔍", "Product Launch Analyst", "Strategic GTM expert"), ("💬", "Market Sentiment Specialist", "Consumer perception expert"), ("📈", "Launch Metrics Specialist", "Performance analytics expert") ] for icon, name, desc in agents_info: with st.container(): st.markdown(f"**{icon} {name}**") st.caption(desc) st.sidebar.divider() # Analysis status if company_name: with st.sidebar.container(): st.markdown("### 📊 Analysis Status") st.markdown(f"**Company:** {company_name}") status_items = [ ("🔍", "Competitor Analysis", st.session_state.competitor_response), ("💬", "Sentiment Analysis", st.session_state.sentiment_response), ("📈", "Metrics Analysis", st.session_state.metrics_response) ] for icon, name, status in status_items: if status: st.success(f"{icon} {name} ✓") else: st.info(f"{icon} {name} ⏳") st.sidebar.divider() # Quick actions with st.sidebar.container(): st.markdown("### ⚡ Quick Actions") if company_name: st.markdown(""" **J** - Competitor analysis **K** - Market sentiment **L** - Launch metrics """)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/tools.py
advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/tools.py
import os import logging from google import genai from google.genai import types from google.adk.tools import ToolContext from pydantic import BaseModel, Field from dotenv import load_dotenv load_dotenv() # Configure logging logger = logging.getLogger(__name__) # ============================================================================ # Helper Functions for Asset Version Management # ============================================================================ def get_next_version_number(tool_context: ToolContext, asset_name: str) -> int: """Get the next version number for a given asset name.""" asset_versions = tool_context.state.get("asset_versions", {}) current_version = asset_versions.get(asset_name, 0) next_version = current_version + 1 return next_version def update_asset_version(tool_context: ToolContext, asset_name: str, version: int, filename: str) -> None: """Update the version tracking for an asset.""" if "asset_versions" not in tool_context.state: tool_context.state["asset_versions"] = {} if "asset_filenames" not in tool_context.state: tool_context.state["asset_filenames"] = {} tool_context.state["asset_versions"][asset_name] = version tool_context.state["asset_filenames"][asset_name] = filename # Maintain a list of all versions for this asset asset_history_key = f"{asset_name}_history" if asset_history_key not in tool_context.state: tool_context.state[asset_history_key] = [] tool_context.state[asset_history_key].append({"version": version, "filename": filename}) def create_versioned_filename(asset_name: str, version: int, file_extension: str = "png") -> str: """Create a versioned filename for an asset.""" return f"{asset_name}_v{version}.{file_extension}" def get_asset_versions_info(tool_context: ToolContext) -> str: """Get information about all asset versions in the session.""" asset_versions = tool_context.state.get("asset_versions", {}) if not asset_versions: return "No renovation renderings have been created yet." info_lines = ["Current renovation renderings:"] for asset_name, current_version in asset_versions.items(): history_key = f"{asset_name}_history" history = tool_context.state.get(history_key, []) total_versions = len(history) latest_filename = tool_context.state.get("asset_filenames", {}).get(asset_name, "Unknown") info_lines.append(f" • {asset_name}: {total_versions} version(s), latest is v{current_version} ({latest_filename})") return "\n".join(info_lines) def get_reference_images_info(tool_context: ToolContext) -> str: """Get information about all reference images (current room/inspiration) uploaded in the session.""" reference_images = tool_context.state.get("reference_images", {}) if not reference_images: return "No reference images have been uploaded yet." info_lines = ["Available reference images (current room photos & inspiration):"] for filename, info in reference_images.items(): version = info.get("version", "Unknown") image_type = info.get("type", "reference") info_lines.append(f" • {filename} ({image_type} v{version})") return "\n".join(info_lines) async def load_reference_image(tool_context: ToolContext, filename: str): """Load a reference image artifact by filename.""" try: loaded_part = await tool_context.load_artifact(filename) if loaded_part: logger.info(f"Successfully loaded reference image: {filename}") return loaded_part else: logger.warning(f"Reference image not found: {filename}") return None except Exception as e: logger.error(f"Error loading reference image {filename}: {e}") return None def get_latest_reference_image_filename(tool_context: ToolContext) -> str: """Get the filename of the most recently uploaded reference image.""" return tool_context.state.get("latest_reference_image") # ============================================================================ # Pydantic Input Models # ============================================================================ class GenerateRenovationRenderingInput(BaseModel): prompt: str = Field(..., description="A detailed description of the renovated space to generate. Include room type, style, colors, materials, fixtures, lighting, and layout.") aspect_ratio: str = Field(default="16:9", description="The desired aspect ratio, e.g., '1:1', '16:9', '9:16'. Default is 16:9 for room photos.") asset_name: str = Field(default="renovation_rendering", description="Base name for the rendering (will be versioned automatically). Use descriptive names like 'kitchen_modern_farmhouse' or 'bathroom_spa'.") current_room_photo: str = Field(default=None, description="Optional: filename of the current room photo to use as reference for layout/structure.") inspiration_image: str = Field(default=None, description="Optional: filename of an inspiration image to guide the style. Use 'latest' for most recent upload.") class EditRenovationRenderingInput(BaseModel): artifact_filename: str = Field(default=None, description="The filename of the rendering artifact to edit. If not provided, uses the last generated rendering.") prompt: str = Field(..., description="The prompt describing the desired changes (e.g., 'make cabinets darker', 'add pendant lights', 'change floor to hardwood').") asset_name: str = Field(default=None, description="Optional: specify asset name for the new version (defaults to incrementing current asset).") reference_image_filename: str = Field(default=None, description="Optional: filename of a reference image to guide the edit. Use 'latest' for most recent upload.") # ============================================================================ # Image Generation Tool # ============================================================================ async def generate_renovation_rendering(tool_context: ToolContext, inputs: GenerateRenovationRenderingInput) -> str: """ Generates a photorealistic rendering of a renovated space based on the design plan. This tool uses Gemini 3 Pro's image generation capabilities to create visual representations of renovation plans. It can optionally use current room photos and inspiration images as references. """ if "GEMINI_API_KEY" not in os.environ and "GOOGLE_API_KEY" not in os.environ: raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY environment variable not set.") logger.info("Starting renovation rendering generation") try: client = genai.Client() # Handle inputs that might come as dict instead of Pydantic model if isinstance(inputs, dict): inputs = GenerateRenovationRenderingInput(**inputs) # Handle reference images (current room photo or inspiration) reference_images = [] if inputs.current_room_photo: current_photo_part = await load_reference_image(tool_context, inputs.current_room_photo) if current_photo_part: reference_images.append(current_photo_part) logger.info(f"Using current room photo: {inputs.current_room_photo}") if inputs.inspiration_image: if inputs.inspiration_image == "latest": insp_filename = get_latest_reference_image_filename(tool_context) else: insp_filename = inputs.inspiration_image if insp_filename: inspiration_part = await load_reference_image(tool_context, insp_filename) if inspiration_part: reference_images.append(inspiration_part) logger.info(f"Using inspiration image: {insp_filename}") # Build the enhanced prompt base_rewrite_prompt = f""" Create a highly detailed, photorealistic prompt for generating an interior design image. Original description: {inputs.prompt} **CRITICAL REQUIREMENT - PRESERVE EXACT LAYOUT:** The generated image MUST maintain the EXACT same room layout, structure, and spatial arrangement described in the prompt: - Keep all windows, doors, skylights in their exact positions - Keep all cabinets, counters, appliances in their exact positions - Keep the same room dimensions and proportions - Keep the same camera angle/perspective - ONLY change surface finishes: paint colors, cabinet colors, countertop materials, flooring, backsplash, hardware, and decorative elements - DO NOT move, add, or remove any structural elements or major fixtures Enhance this to be a professional interior photography prompt that includes: - Specific camera angle (match original photo perspective if described) - Exact colors and materials mentioned (apply to existing surfaces) - Realistic lighting (natural light from existing windows, fixture types) - Maintain existing spatial layout and dimensions - Texture and finish details for the new materials - Professional interior design photography quality Aspect ratio: {inputs.aspect_ratio} """ if reference_images: base_rewrite_prompt += "\n\n**Reference Image Layout:** The reference image shows the EXACT layout that must be preserved. Match the camera angle, room structure, window/door positions, and furniture/appliance placement EXACTLY. Only change the surface finishes and colors." base_rewrite_prompt += "\n\n**Important:** Output your prompt as a single detailed paragraph optimized for photorealistic interior rendering. Emphasize that the layout must remain unchanged." # Get enhanced prompt rewritten_prompt_response = client.models.generate_content( model="gemini-3-flash-preview", contents=base_rewrite_prompt ) rewritten_prompt = rewritten_prompt_response.text logger.info(f"Enhanced prompt: {rewritten_prompt}") model = "gemini-3-pro-image-preview" # Build content parts content_parts = [types.Part.from_text(text=rewritten_prompt)] content_parts.extend(reference_images) contents = [ types.Content( role="user", parts=content_parts, ), ] generate_content_config = types.GenerateContentConfig( response_modalities=[ "IMAGE", "TEXT", ], ) # Generate versioned filename version = get_next_version_number(tool_context, inputs.asset_name) artifact_filename = create_versioned_filename(inputs.asset_name, version) logger.info(f"Generating rendering with artifact filename: {artifact_filename} (version {version})") # Generate the image for chunk in client.models.generate_content_stream( model=model, contents=contents, config=generate_content_config, ): if ( chunk.candidates is None or chunk.candidates[0].content is None or chunk.candidates[0].content.parts is None ): continue if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data: inline_data = chunk.candidates[0].content.parts[0].inline_data # Create a Part object from the inline data # The inline_data already contains the mime_type from the API response image_part = types.Part(inline_data=inline_data) try: # Save the image as an artifact version = await tool_context.save_artifact( filename=artifact_filename, artifact=image_part ) # Update version tracking update_asset_version(tool_context, inputs.asset_name, version, artifact_filename) # Store in session state tool_context.state["last_generated_rendering"] = artifact_filename tool_context.state["current_asset_name"] = inputs.asset_name logger.info(f"Saved rendering as artifact '{artifact_filename}' (version {version})") return f"✅ Renovation rendering generated successfully!\n\nThe rendering has been saved and is available in the artifacts panel. Artifact name: {inputs.asset_name} (version {version}).\n\nNote: The image is stored as an artifact and can be accessed through the session artifacts, not as a direct image link." except Exception as e: logger.error(f"Error saving artifact: {e}") return f"Error saving rendering as artifact: {e}" else: # Log any text responses if hasattr(chunk, 'text') and chunk.text: logger.info(f"Model response: {chunk.text}") return "No rendering was generated. Please try again with a more detailed prompt." except Exception as e: logger.error(f"Error in generate_renovation_rendering: {e}") return f"An error occurred while generating the rendering: {e}" # ============================================================================ # Image Editing Tool # ============================================================================ async def edit_renovation_rendering(tool_context: ToolContext, inputs: EditRenovationRenderingInput) -> str: """ Edits an existing renovation rendering based on feedback or refinements. This tool allows iterative improvements to the rendered image, such as changing colors, materials, lighting, or layout elements. """ if "GEMINI_API_KEY" not in os.environ and "GOOGLE_API_KEY" not in os.environ: raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY environment variable not set.") logger.info("Starting renovation rendering edit") try: client = genai.Client() # Handle inputs that might come as dict instead of Pydantic model if isinstance(inputs, dict): inputs = EditRenovationRenderingInput(**inputs) # Get artifact_filename from session state if not provided artifact_filename = inputs.artifact_filename if not artifact_filename: artifact_filename = tool_context.state.get("last_generated_rendering") if not artifact_filename: return "❌ No artifact_filename provided and no previous rendering found in session. Please generate a rendering first or specify the artifact filename." logger.info(f"Using last generated rendering from session: {artifact_filename}") # Load the existing rendering logger.info(f"Loading artifact: {artifact_filename}") try: loaded_image_part = await tool_context.load_artifact(artifact_filename) if not loaded_image_part: return f"❌ Could not find rendering artifact: {artifact_filename}" except Exception as e: logger.error(f"Error loading artifact: {e}") return f"Error loading rendering artifact: {e}" # Handle reference image if specified reference_image_part = None if inputs.reference_image_filename: if inputs.reference_image_filename == "latest": ref_filename = get_latest_reference_image_filename(tool_context) else: ref_filename = inputs.reference_image_filename if ref_filename: reference_image_part = await load_reference_image(tool_context, ref_filename) if reference_image_part: logger.info(f"Using reference image for editing: {ref_filename}") model = "gemini-3-pro-image-preview" # Build content parts content_parts = [loaded_image_part, types.Part.from_text(text=inputs.prompt)] if reference_image_part: content_parts.append(reference_image_part) contents = [ types.Content( role="user", parts=content_parts, ), ] generate_content_config = types.GenerateContentConfig( response_modalities=[ "IMAGE", "TEXT", ], ) # Determine asset name and generate versioned filename if inputs.asset_name: asset_name = inputs.asset_name else: current_asset_name = tool_context.state.get("current_asset_name") if current_asset_name: asset_name = current_asset_name else: # Extract from filename base_name = artifact_filename.split('_v')[0] if '_v' in artifact_filename else "renovation_rendering" asset_name = base_name version = get_next_version_number(tool_context, asset_name) edited_artifact_filename = create_versioned_filename(asset_name, version) logger.info(f"Editing rendering with artifact filename: {edited_artifact_filename} (version {version})") # Edit the image for chunk in client.models.generate_content_stream( model=model, contents=contents, config=generate_content_config, ): if ( chunk.candidates is None or chunk.candidates[0].content is None or chunk.candidates[0].content.parts is None ): continue if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data: inline_data = chunk.candidates[0].content.parts[0].inline_data # Create a Part object from the inline data # The inline_data already contains the mime_type from the API response edited_image_part = types.Part(inline_data=inline_data) try: # Save the edited image as an artifact version = await tool_context.save_artifact( filename=edited_artifact_filename, artifact=edited_image_part ) # Update version tracking update_asset_version(tool_context, asset_name, version, edited_artifact_filename) # Store in session state tool_context.state["last_generated_rendering"] = edited_artifact_filename tool_context.state["current_asset_name"] = asset_name logger.info(f"Saved edited rendering as artifact '{edited_artifact_filename}' (version {version})") return f"✅ Rendering edited successfully!\n\nThe updated rendering has been saved and is available in the artifacts panel. Artifact name: {asset_name} (version {version}).\n\nNote: The image is stored as an artifact and can be accessed through the session artifacts, not as a direct image link." except Exception as e: logger.error(f"Error saving edited artifact: {e}") return f"Error saving edited rendering as artifact: {e}" else: # Log any text responses if hasattr(chunk, 'text') and chunk.text: logger.info(f"Model response: {chunk.text}") return "No edited rendering was generated. Please try again." except Exception as e: logger.error(f"Error in edit_renovation_rendering: {e}") return f"An error occurred while editing the rendering: {e}" # ============================================================================ # Utility Tools # ============================================================================ async def list_renovation_renderings(tool_context: ToolContext) -> str: """Lists all renovation renderings created in this session.""" return get_asset_versions_info(tool_context) async def list_reference_images(tool_context: ToolContext) -> str: """Lists all reference images (current room photos & inspiration) uploaded in this session.""" return get_reference_images_info(tool_context) async def save_uploaded_image_as_artifact( tool_context: ToolContext, image_data: str, artifact_name: str, image_type: str = "current_room" ) -> str: """ Saves an uploaded image as a named artifact for later use in editing. This tool is used when the Visual Assessor detects an uploaded image and wants to make it available for the Project Coordinator to edit. Args: tool_context: The tool context image_data: Base64 encoded image data or image bytes artifact_name: Name to save the artifact as (e.g., "current_room_1", "inspiration_1") image_type: Type of image ("current_room" or "inspiration") Returns: Success message with the artifact filename """ try: # Create a Part from the image data # Note: This assumes image_data is already in the right format # In practice, we'll get this from the message content # Save as artifact await tool_context.save_artifact( filename=artifact_name, artifact=image_data ) # Track in state if "uploaded_images" not in tool_context.state: tool_context.state["uploaded_images"] = {} tool_context.state["uploaded_images"][artifact_name] = { "type": image_type, "filename": artifact_name } if image_type == "current_room": tool_context.state["current_room_artifact"] = artifact_name elif image_type == "inspiration": tool_context.state["inspiration_artifact"] = artifact_name logger.info(f"Saved uploaded image as artifact: {artifact_name}") return f"✅ Image saved as artifact: {artifact_name} (type: {image_type}). This can now be used for editing." except Exception as e: logger.error(f"Error saving uploaded image: {e}") return f"❌ Error saving uploaded image: {e}"
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/__init__.py
advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/__init__.py
"""AI Home Renovation Planner - Multi-Agent Pattern Demo with Multimodal Vision""" from .agent import root_agent __all__ = ["root_agent"]
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/agent.py
advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/agent.py
"""AI Home Renovation Planner - Coordinator/Dispatcher Pattern with Multimodal Vision This demonstrates ADK's Coordinator/Dispatcher Pattern with Gemini 3 Flash's multimodal capabilities where a routing agent analyzes requests and delegates to specialists: - General questions → Quick info agent - Renovation planning → Full planning pipeline (Sequential Agent with 3 vision-enabled specialists) Pattern Reference: https://google.github.io/adk-docs/agents/multi-agents/#coordinator-dispatcher-pattern """ from google.adk.agents import LlmAgent, SequentialAgent from google.adk.tools import google_search from google.adk.tools.agent_tool import AgentTool from .tools import ( generate_renovation_rendering, edit_renovation_rendering, list_renovation_renderings, list_reference_images, ) # ============================================================================ # Helper Tool Agent (wraps google_search) # ============================================================================ search_agent = LlmAgent( name="SearchAgent", model="gemini-3-flash-preview", description="Searches for renovation costs, contractors, materials, and design trends", instruction="Use google_search to find current renovation information, costs, materials, and trends. Be concise and cite sources.", tools=[google_search], ) # ============================================================================ # Utility Tools # ============================================================================ def estimate_renovation_cost( room_type: str, scope: str, square_footage: int, ) -> str: """Estimate renovation costs based on room type and scope. Args: room_type: Type of room (kitchen, bathroom, bedroom, living_room, etc.) scope: Renovation scope (cosmetic, moderate, full, luxury) square_footage: Room size in square feet Returns: Estimated cost range """ # Cost per sq ft estimates (2024 ranges) rates = { "kitchen": {"cosmetic": (50, 100), "moderate": (150, 250), "full": (300, 500), "luxury": (600, 1200)}, "bathroom": {"cosmetic": (75, 125), "moderate": (200, 350), "full": (400, 600), "luxury": (800, 1500)}, "bedroom": {"cosmetic": (30, 60), "moderate": (75, 150), "full": (150, 300), "luxury": (400, 800)}, "living_room": {"cosmetic": (40, 80), "moderate": (100, 200), "full": (200, 400), "luxury": (500, 1000)}, } room = room_type.lower().replace(" ", "_") scope_level = scope.lower() if room not in rates: room = "living_room" if scope_level not in rates[room]: scope_level = "moderate" low, high = rates[room][scope_level] total_low = low * square_footage total_high = high * square_footage return f"💰 Estimated Cost: ${total_low:,} - ${total_high:,} ({scope_level} {room_type} renovation, ~{square_footage} sq ft)" def calculate_timeline( scope: str, room_type: str, ) -> str: """Estimate renovation timeline based on scope and room type. Args: scope: Renovation scope (cosmetic, moderate, full, luxury) room_type: Type of room being renovated Returns: Estimated timeline with phases """ timelines = { "cosmetic": "1-2 weeks (quick refresh)", "moderate": "3-6 weeks (includes some structural work)", "full": "2-4 months (complete transformation)", "luxury": "4-6 months (custom work, high-end finishes)" } scope_level = scope.lower() timeline = timelines.get(scope_level, timelines["moderate"]) return f"⏱️ Estimated Timeline: {timeline}" # ============================================================================ # Specialist Agent 1: Info Agent (for general inquiries) # ============================================================================ info_agent = LlmAgent( name="InfoAgent", model="gemini-3-flash-preview", description="Handles general renovation questions and provides system information", instruction=""" You are the Info Agent for the AI Home Renovation Planner. WHEN TO USE: The coordinator routes general questions and casual greetings to you. YOUR RESPONSE: - Keep it brief and helpful (2-4 sentences) - Explain the system helps with home renovations using visual AI - Mention capabilities: photo analysis, design planning, budget estimation, timeline coordination - Ask about their renovation project (which room, can they share photos?) EXAMPLE: "Hi! I'm your AI Home Renovation Planner. I can analyze photos of your current space and inspiration images to create a personalized renovation plan with design suggestions, budget estimates, and timelines. Which room are you thinking of renovating? Feel free to share photos if you have them!" Be enthusiastic about home improvement and helpful! """, ) # ============================================================================ # Specialist Agent 2: Rendering Editor (for iterative refinements) # ============================================================================ rendering_editor = LlmAgent( name="RenderingEditor", model="gemini-3-flash-preview", description="Edits existing renovation renderings based on user feedback", instruction=""" You refine existing renovation renderings. **TASK**: User wants to modify an existing rendering (e.g., "make cabinets cream", "darker flooring"). **CRITICAL**: Find the most recent rendering filename from conversation history! Look for: "Saved as artifact: [filename]" or "kitchen_modern_renovation_v1.png" type references. Use **edit_renovation_rendering** tool: Parameters: 1. artifact_filename: The exact filename of the most recent rendering 2. prompt: Very specific edit instruction (be detailed!) 3. asset_name: Base name without _vX (e.g., "kitchen_modern_renovation") **Example:** User: "Make the cabinets cream instead of white" Last rendering: "kitchen_modern_renovation_v1.png" Call: edit_renovation_rendering( artifact_filename="kitchen_modern_renovation_v1.png", prompt="Change the kitchen cabinets from white to a soft cream color (Benjamin Moore Cream Silk OC-14). Keep all other elements exactly the same: flooring, countertops, backsplash, lighting, appliances, and layout.", asset_name="kitchen_modern_renovation" ) Be SPECIFIC in prompts - vague = poor results! After editing, briefly confirm the change. **IMPORTANT - DO NOT use markdown image syntax!** - Do NOT output `![image](filename.png)` or similar markdown image links - Simply confirm the edit was successful and mention the artifact is available in the artifacts panel """, tools=[edit_renovation_rendering, list_renovation_renderings], ) # ============================================================================ # Specialist Agents 3-5: Full Planning Pipeline (SequentialAgent) # ============================================================================ visual_assessor = LlmAgent( name="VisualAssessor", model="gemini-3-flash-preview", description="Analyzes room photos and inspiration images using visual AI", instruction=""" You are a visual AI specialist. Analyze ANY uploaded images and detect their type automatically. **IMPORTANT NOTE**: You can SEE and ANALYZE uploaded images, but currently the image editing feature has limitations in ADK Web. Focus on providing detailed analysis and design recommendations. AUTOMATICALLY DETECT: 1. If image shows a CURRENT ROOM (existing space that needs renovation) 2. If image shows INSPIRATION/STYLE reference (desired aesthetic) 3. Extract budget constraints from user's message if mentioned ## For CURRENT ROOM images: **Current Space Analysis:** - Room type: [kitchen/bathroom/bedroom/etc.] - Size estimate: [dimensions if visible] - Current condition: [issues, outdated elements, damage] - Existing style: [current aesthetic] - Key problems: [what needs fixing] - Improvement opportunities: [quick wins, major changes] **CRITICAL - DOCUMENT EXACT LAYOUT (for preservation in rendering):** - Window positions: [e.g., "large window on left wall above sink", "skylight in center"] - Door positions: [e.g., "doorway on right side"] - Cabinet layout: [e.g., "L-shaped upper and lower cabinets along back and left walls"] - Appliance positions: [e.g., "stove centered on back wall", "refrigerator on right"] - Sink location: [e.g., "under window on left wall"] - Counter layout: [e.g., "continuous counter along back and left walls"] - Special features: [e.g., "skylight", "breakfast bar", "island"] - Camera angle in photo: [e.g., "shot from doorway looking into kitchen"] ## For INSPIRATION images: **Inspiration Style:** - Style name: [modern farmhouse/minimalist/industrial/etc.] - Color palette: [specific colors] - Key materials: [wood/stone/metal types] - Notable features: [lighting/storage/layout elements] - Design elements: [hardware/finishes/patterns] ## Analysis Output: If BOTH current room + inspiration provided: - Compare current vs. inspiration - Identify specific changes needed to achieve the inspiration look - Note what can stay vs. what needs replacement If ONLY current room provided: - Suggest 2-3 style directions that would work well - Focus on functional improvements + aesthetic upgrades If budget mentioned: - Use estimate_renovation_cost tool with detected room type and appropriate scope - Assess what's achievable within budget **IMPORTANT: At the end of your analysis, output a structured summary:** ``` ASSESSMENT COMPLETE Images Provided: - Current room photo: [Yes/No - describe what you see if yes] - Inspiration photo: [Yes/No - describe style if yes] Room Details: - Type: [kitchen/bathroom/bedroom/etc.] - Current Analysis: [detailed analysis from photo if provided, or from description] - Desired Style: [from inspiration photo or user description] - Key Issues: [problems to address] - Improvement Opportunities: [suggested improvements] - Budget Constraint: $[amount if mentioned, or "Not specified"] **EXACT LAYOUT TO PRESERVE (critical for rendering):** - Windows: [exact positions and sizes] - Doors: [exact positions] - Cabinets: [configuration and placement - upper/lower, which walls] - Appliances: [stove, fridge, dishwasher positions] - Sink: [location] - Counter layout: [shape and coverage] - Special features: [skylights, islands, breakfast bars, etc.] - Camera angle: [perspective of the original photo] ``` Be EXTREMELY DETAILED about the layout - the rendering must match this layout EXACTLY while only changing surface finishes. """, tools=[AgentTool(search_agent), estimate_renovation_cost], ) design_planner = LlmAgent( name="DesignPlanner", model="gemini-3-flash-preview", description="Creates detailed renovation design plan", instruction=""" Read from state: room_analysis, style_preferences, room_type, key_issues, opportunities, budget_constraint Create SPECIFIC, ACTIONABLE design plan tailored to their situation. **CRITICAL RULE - PRESERVE EXACT LAYOUT:** The design plan must KEEP THE EXACT SAME LAYOUT as the current room. DO NOT suggest: - Moving appliances to different locations - Reconfiguring cabinet positions - Adding or removing windows/doors - Changing the room's footprint or structure - Adding islands or removing existing features ONLY specify changes to SURFACE FINISHES applied to the existing layout: - Paint colors for existing walls and cabinets - New countertop material on existing counters - New flooring in the same floor area - New backsplash on existing walls - New hardware on existing cabinets - Lighting upgrades (can add under-cabinet lights, replace fixtures in same positions) ## Design Plan **Budget-Conscious Approach:** - If budget_constraint exists: Prioritize changes that give max impact for the money - Separate "must-haves" vs "nice-to-haves" **Design Specifications (surface finish changes ONLY - no layout changes):** - **Layout**: PRESERVE EXACTLY AS-IS (reference Visual Assessor's layout documentation) - **Cabinet Color**: [exact paint color with code - applied to EXISTING cabinets] - **Wall Color**: [exact paint color with code] - **Countertops**: [material and color - applied to EXISTING counter layout] - **Flooring**: [type, color - same floor area] - **Backsplash**: [material, pattern - same wall areas] - **Hardware**: [handles, pulls - replace on existing cabinets] - **Lighting**: [fixture upgrades in same positions, add under-cabinet if applicable] - **Appliances**: [keep existing OR replace with similar size in SAME locations] - **Key Features**: [decorative elements only] **Style Consistency:** If inspiration photo provided: Match that aesthetic precisely using ONLY surface finish changes If no inspiration: Use style_preferences from state Use calculate_timeline tool with room_type and renovation_scope. **IMPORTANT: At the end, provide a structured summary:** ``` DESIGN COMPLETE Renovation Scope: [cosmetic/moderate - NO structural changes] Layout: PRESERVED EXACTLY (no changes to cabinet positions, appliance locations, or room structure) Surface Finish Changes: - Cabinets: [color change only] - Walls: [paint color] - Countertops: [material/color] - Flooring: [type/color] - Backsplash: [material/pattern] - Hardware: [style/finish] - Lighting: [upgrades] Materials Summary: [Detailed list with product names and color codes] ``` Be SPECIFIC with product names, colors, dimensions. The rendering must show the EXACT same layout with only the surface finishes changed. """, tools=[calculate_timeline], ) project_coordinator = LlmAgent( name="ProjectCoordinator", model="gemini-3-flash-preview", description="Coordinates renovation timeline, budget, execution plan, and generates photorealistic renderings", instruction=""" Read conversation history to extract: - Image detection info from Visual Assessor (current room photo? inspiration photo? filenames?) - Design specifications from Design Planner - Budget constraints mentioned Create CLEAN, SCANNABLE final plan. ## Renovation Plan **Budget Breakdown**: - Materials: $[amount] - Labor: $[amount] - Permits/fees: $[amount] - Contingency (10%): $[amount] - **Total**: $[amount] [If budget_constraint exists: Show "Within your $X budget ✓" or suggest phasing] **Timeline**: [X weeks, broken into phases] **Contractors Needed**: [specific trades] ## Design Summary [Pull key points from design_plan - tight, scannable bullets] ## Action Checklist 1. [immediate first steps] 2. [subsequent actions] ## 🎨 Visual Rendering: Your Renovated Space **🎨 Generate Visual Rendering:** Use **generate_renovation_rendering** tool to CREATE a photorealistic rendering: Build an EXTREMELY DETAILED prompt that incorporates: - **From Visual Assessor**: Room type, current condition analysis, desired style - **From Design Planner**: Exact colors (with codes/names), specific materials, layout details, lighting fixtures, flooring type, all key features **Prompt Structure:** "Professional interior photography of a renovated [room_type]. **CRITICAL - PRESERVE EXACT LAYOUT**: The room must maintain the EXACT same layout, structure, and spatial arrangement as the original photo: - Same window positions and sizes - Same door locations - Same cabinet configuration and placement - Same appliance positions (stove, sink, refrigerator in same spots) - Same architectural features (skylights, alcoves, etc.) - Same room dimensions and proportions - Same camera angle/perspective as the original photo ONLY change the surface finishes, colors, materials, and decorative elements - NOT the structure or layout. Design Specifications (changes to apply to the EXISTING layout): - Style: [exact style from design plan] - Cabinet Color: [specific color names with codes - e.g., 'Benjamin Moore Simply White OC-117' - apply to EXISTING cabinets in their current positions] - Wall Color: [specific paint color] - Countertops: [material and color - apply to EXISTING counter layout] - Flooring: [type and color - same floor area] - Backsplash: [pattern and material - same wall areas] - Hardware: [handles, pulls - replace on existing cabinets] - Lighting: [specific fixtures - same positions or clearly specified additions] - Appliances: [keep existing OR specify replacements in SAME locations] - Key Features: [all important elements] Camera: Match the EXACT camera angle from the original photo Quality: Photorealistic, 8K, professional interior design magazine, natural lighting" Parameters: - prompt: [your ultra-detailed prompt above] - aspect_ratio: "16:9" - asset_name: "[room_type]_[style_keyword]_renovation" (e.g., "kitchen_modern_farmhouse_renovation") **After generating:** Briefly describe (2-3 sentences) key features visible in the rendering and how it addresses their needs. **IMPORTANT - DO NOT use markdown image syntax!** - Do NOT output `![image](filename.png)` or similar markdown image links - Do NOT try to display the image inline with markdown - Simply mention that the rendering has been generated and saved as an artifact - The user can view the artifact through the artifacts panel **Note**: Image editing from uploaded photos has limitations in ADK Web. We generate fresh renderings based on detailed descriptions from the analysis. """, tools=[generate_renovation_rendering, edit_renovation_rendering, list_renovation_renderings], ) # Create the planning pipeline (runs only when coordinator routes planning requests here) planning_pipeline = SequentialAgent( name="PlanningPipeline", description="Full renovation planning pipeline: Visual Assessment → Design Planning → Project Coordination", sub_agents=[ visual_assessor, design_planner, project_coordinator, ], ) # ============================================================================ # Coordinator/Dispatcher (Root Agent) # ============================================================================ root_agent = LlmAgent( name="HomeRenovationPlanner", model="gemini-3-flash-preview", description="Intelligent coordinator that routes renovation requests to the appropriate specialist or planning pipeline. Supports image analysis!", instruction=""" You are the Coordinator for the AI Home Renovation Planner. YOUR ROLE: Analyze the user's request and route it to the right specialist using transfer_to_agent. ROUTING LOGIC: 1. **For general questions/greetings**: → transfer_to_agent to "InfoAgent" → Examples: "hi", "what do you do?", "how much do renovations cost?" 2. **For editing EXISTING renderings** (only if rendering was already generated): → transfer_to_agent to "RenderingEditor" → Examples: "make cabinets cream", "darker", "change color", "add lights" → User wants to MODIFY an existing rendering → Check: Was a rendering generated earlier? 3. **For NEW renovation planning**: → transfer_to_agent to "PlanningPipeline" → Examples: "Plan my kitchen", "Here's my space [photos]", "Help renovate" → First-time planning or new project → ALWAYS route here if images uploaded! CRITICAL: You MUST use transfer_to_agent - don't answer directly! Decision flow: - Rendering exists + wants changes → RenderingEditor - New project/images → PlanningPipeline - Just chatting → InfoAgent Be a smart router - match intent! """, sub_agents=[ info_agent, rendering_editor, planning_pipeline, ], ) __all__ = ["root_agent"]
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_domain_deep_research_agent/ai_domain_deep_research_agent.py
advanced_ai_agents/multi_agent_apps/ai_domain_deep_research_agent/ai_domain_deep_research_agent.py
import os import asyncio import streamlit as st from dotenv import load_dotenv from agno.agent import Agent from agno.run.agent import RunOutput from composio_agno import ComposioToolSet, Action from agno.models.together import Together # Load environment variables load_dotenv() # Set page config st.set_page_config( page_title="AI DeepResearch Agent", page_icon="🔍", layout="wide", initial_sidebar_state="expanded" ) # Sidebar for API keys st.sidebar.header("⚙️ Configuration") # API key inputs together_api_key = st.sidebar.text_input( "Together AI API Key", value=os.getenv("TOGETHER_API_KEY", ""), type="password", help="Get your API key from https://together.ai" ) composio_api_key = st.sidebar.text_input( "Composio API Key", value=os.getenv("COMPOSIO_API_KEY", ""), type="password", help="Get your API key from https://composio.ai" ) # Sidebar info st.sidebar.markdown("---") st.sidebar.markdown("### About") st.sidebar.info( "This AI DeepResearch Agent uses Together AI's Qwen model and Composio tools to perform comprehensive research on any topic. " "It generates research questions, finds answers, and compiles a professional report." ) st.sidebar.markdown("### Tools Used") st.sidebar.markdown("- 🔍 Tavily Search") st.sidebar.markdown("- 🧠 Perplexity AI") st.sidebar.markdown("- 📄 Google Docs Integration") # Initialize session state if 'questions' not in st.session_state: st.session_state.questions = [] if 'question_answers' not in st.session_state: st.session_state.question_answers = [] if 'report_content' not in st.session_state: st.session_state.report_content = "" if 'research_complete' not in st.session_state: st.session_state.research_complete = False # Main content st.title("🔍 AI DeepResearch Agent with Agno and Composio") # Function to initialize the LLM and tools def initialize_agents(together_key, composio_key): # Initialize Together AI LLM llm = Together(id="Qwen/Qwen3-235B-A22B-fp8-tput", api_key=together_key) # Set up Composio tools toolset = ComposioToolSet(api_key=composio_key) composio_tools = toolset.get_tools(actions=[ Action.COMPOSIO_SEARCH_TAVILY_SEARCH, Action.PERPLEXITYAI_PERPLEXITY_AI_SEARCH, Action.GOOGLEDOCS_CREATE_DOCUMENT_MARKDOWN ]) return llm, composio_tools # Function to create agents def create_agents(llm, composio_tools): # Create the question generator agent question_generator = Agent( name="Question Generator", model=llm, instructions=""" You are an expert at breaking down research topics into specific questions. Generate exactly 5 specific yes/no research questions about the given topic in the specified domain. Respond ONLY with the text of the 5 questions formatted as a numbered list, and NOTHING ELSE. """ ) return question_generator # Function to extract questions after think tag def extract_questions_after_think(text): if "</think>" in text: return text.split("</think>", 1)[1].strip() return text.strip() # Function to generate research questions def generate_questions(llm, composio_tools, topic, domain): question_generator = create_agents(llm, composio_tools) with st.spinner("🤖 Generating research questions..."): questions_task: RunOutput = question_generator.run( f"Generate exactly 5 specific yes/no research questions about the topic '{topic}' in the domain '{domain}'." ) questions_text = questions_task.content questions_only = extract_questions_after_think(questions_text) # Extract questions into a list questions_list = [q.strip() for q in questions_only.split('\n') if q.strip()] st.session_state.questions = questions_list return questions_list # Function to research a specific question def research_question(llm, composio_tools, topic, domain, question): research_task = Agent( model=llm, tools=[composio_tools], instructions=f"You are a sophisticated research assistant. Answer the following research question about the topic '{topic}' in the domain '{domain}':\n\n{question}\n\nUse the PERPLEXITYAI_PERPLEXITY_AI_SEARCH and COMPOSIO_SEARCH_TAVILY_SEARCH tools to provide a concise, well-sourced answer." ) research_result: RunOutput = research_task.run() return research_result.content # Function to compile final report def compile_report(llm, composio_tools, topic, domain, question_answers): with st.spinner("📝 Compiling final report and creating Google Doc..."): qa_sections = "\n".join( f"<h2>{idx+1}. {qa['question']}</h2>\n<p>{qa['answer']}</p>" for idx, qa in enumerate(question_answers) ) compile_report_task = Agent( name="Report Compiler", model=llm, tools=[composio_tools], instructions=f""" You are a sophisticated research assistant. Compile the following research findings into a professional, McKinsey-style report. The report should be structured as follows: 1. Executive Summary/Introduction: Briefly introduce the topic and domain, and summarize the key findings. 2. Research Analysis: For each research question, create a section with a clear heading and provide a detailed, analytical answer. Do NOT use a Q&A format; instead, weave the answer into a narrative and analytical style. 3. Conclusion/Implications: Summarize the overall insights and implications of the research. Use clear, structured HTML for the report. Topic: {topic} Domain: {domain} Research Questions and Findings (for your reference): {qa_sections} Use the GOOGLEDOCS_CREATE_DOCUMENT_MARKDOWN tool to create a Google Doc with the report. The text should be in HTML format. You have to create the google document with all the compiled info. You have to do it. """ ) compile_result: RunOutput = compile_report_task.run() st.session_state.report_content = compile_result.content st.session_state.research_complete = True return compile_result.content # Main application flow if together_api_key and composio_api_key: # Initialize agents llm, composio_tools = initialize_agents(together_api_key, composio_api_key) # Main content area st.header("Research Topic") # Input fields col1, col2 = st.columns(2) with col1: topic = st.text_input("What topic would you like to research?", placeholder="American Tariffs") with col2: domain = st.text_input("What domain is this topic in?", placeholder="Politics, Economics, Technology, etc.") # Generate questions section if topic and domain and st.button("Generate Research Questions", key="generate_questions"): # Generate questions questions = generate_questions(llm, composio_tools, topic, domain) # Display the generated questions st.header("Research Questions") for i, question in enumerate(questions): st.markdown(f"**{i+1}. {question}**") # Research section - only show if we have questions if st.session_state.questions and st.button("Start Research", key="start_research"): st.header("Research Results") # Reset answers question_answers = [] # Research each question progress_bar = st.progress(0) for i, question in enumerate(st.session_state.questions): # Update progress progress_bar.progress((i) / len(st.session_state.questions)) # Research the question with st.spinner(f"🔍 Researching question {i+1}..."): answer = research_question(llm, composio_tools, topic, domain, question) question_answers.append({"question": question, "answer": answer}) # Display the answer st.subheader(f"Question {i+1}:") st.markdown(f"**{question}**") st.markdown(answer) # Update progress again progress_bar.progress((i + 1) / len(st.session_state.questions)) # Store the answers st.session_state.question_answers = question_answers # Compile report button if st.button("Compile Final Report", key="compile_report"): report_content = compile_report(llm, composio_tools, topic, domain, question_answers) # Display the report content st.header("Final Report") st.success("Your report has been compiled and a Google Doc has been created.") # Show the full report content with st.expander("View Full Report Content", expanded=True): st.markdown(report_content) # Display previous results if available if len(st.session_state.question_answers) > 0 and not st.session_state.research_complete: st.header("Previous Research Results") # Display research results for i, qa in enumerate(st.session_state.question_answers): with st.expander(f"Question {i+1}: {qa['question']}"): st.markdown(qa['answer']) # Display final report if available if st.session_state.research_complete and st.session_state.report_content: st.header("Final Report") # Display the report content st.success("Your report has been compiled and a Google Doc has been created.") # Show the full report content with st.expander("View Full Report Content", expanded=True): st.markdown(st.session_state.report_content) else: # API keys not provided st.warning("⚠️ Please enter your Together AI and Composio API keys in the sidebar to get started.") # Example UI st.header("How It Works") col1, col2, col3 = st.columns(3) with col1: st.subheader("1️⃣ Define Topic") st.write("Enter your research topic and domain to begin the research process.") with col2: st.subheader("2️⃣ Generate Questions") st.write("The AI generates specific research questions to explore your topic in depth.") with col3: st.subheader("3️⃣ Compile Report") st.write("Research findings are compiled into a professional report and saved to Google Docs.")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_aqi_analysis_agent/ai_aqi_analysis_agent_gradio.py
advanced_ai_agents/multi_agent_apps/ai_aqi_analysis_agent/ai_aqi_analysis_agent_gradio.py
from typing import Dict, Optional from dataclasses import dataclass from pydantic import BaseModel, Field from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.openai import OpenAIChat from firecrawl import FirecrawlApp import gradio as gr import json class AQIResponse(BaseModel): success: bool data: Dict[str, float] status: str expiresAt: str class ExtractSchema(BaseModel): aqi: float = Field(description="Air Quality Index") temperature: float = Field(description="Temperature in degrees Celsius") humidity: float = Field(description="Humidity percentage") wind_speed: float = Field(description="Wind speed in kilometers per hour") pm25: float = Field(description="Particulate Matter 2.5 micrometers") pm10: float = Field(description="Particulate Matter 10 micrometers") co: float = Field(description="Carbon Monoxide level") @dataclass class UserInput: city: str state: str country: str medical_conditions: Optional[str] planned_activity: str class AQIAnalyzer: def __init__(self, firecrawl_key: str) -> None: self.firecrawl = FirecrawlApp(api_key=firecrawl_key) def _format_url(self, country: str, state: str, city: str) -> str: """Format URL based on location, handling cases with and without state""" country_clean = country.lower().replace(' ', '-') city_clean = city.lower().replace(' ', '-') if not state or state.lower() == 'none': return f"https://www.aqi.in/dashboard/{country_clean}/{city_clean}" state_clean = state.lower().replace(' ', '-') return f"https://www.aqi.in/dashboard/{country_clean}/{state_clean}/{city_clean}" def fetch_aqi_data(self, city: str, state: str, country: str) -> tuple[Dict[str, float], str]: """Fetch AQI data using Firecrawl""" try: url = self._format_url(country, state, city) info_msg = f"Accessing URL: {url}" response = self.firecrawl.extract( urls=[f"{url}/*"], params={ 'prompt': 'Extract the current real-time AQI, temperature, humidity, wind speed, PM2.5, PM10, and CO levels from the page. Also extract the timestamp of the data.', 'schema': ExtractSchema.model_json_schema() } ) aqi_response = AQIResponse(**response) if not aqi_response.success: raise ValueError(f"Failed to fetch AQI data: {aqi_response.status}") return aqi_response.data, info_msg except Exception as e: error_msg = f"Error fetching AQI data: {str(e)}" return { 'aqi': 0, 'temperature': 0, 'humidity': 0, 'wind_speed': 0, 'pm25': 0, 'pm10': 0, 'co': 0 }, error_msg class HealthRecommendationAgent: def __init__(self, openai_key: str) -> None: self.agent = Agent( model=OpenAIChat( id="gpt-4o", name="Health Recommendation Agent", api_key=openai_key ) ) def get_recommendations( self, aqi_data: Dict[str, float], user_input: UserInput ) -> str: prompt = self._create_prompt(aqi_data, user_input) response: RunOutput = self.agent.run(prompt) return response.content def _create_prompt(self, aqi_data: Dict[str, float], user_input: UserInput) -> str: return f""" Based on the following air quality conditions in {user_input.city}, {user_input.state}, {user_input.country}: - Overall AQI: {aqi_data['aqi']} - PM2.5 Level: {aqi_data['pm25']} µg/m³ - PM10 Level: {aqi_data['pm10']} µg/m³ - CO Level: {aqi_data['co']} ppb Weather conditions: - Temperature: {aqi_data['temperature']}°C - Humidity: {aqi_data['humidity']}% - Wind Speed: {aqi_data['wind_speed']} km/h User's Context: - Medical Conditions: {user_input.medical_conditions or 'None'} - Planned Activity: {user_input.planned_activity} **Comprehensive Health Recommendations:** 1. **Impact of Current Air Quality on Health:** 2. **Necessary Safety Precautions for Planned Activity:** 3. **Advisability of Planned Activity:** 4. **Best Time to Conduct the Activity:** """ def analyze_conditions( city: str, state: str, country: str, medical_conditions: str, planned_activity: str, firecrawl_key: str, openai_key: str ) -> tuple[str, str, str, str]: """Analyze conditions and return AQI data, recommendations, and status messages""" try: # Initialize analyzers aqi_analyzer = AQIAnalyzer(firecrawl_key=firecrawl_key) health_agent = HealthRecommendationAgent(openai_key=openai_key) # Create user input user_input = UserInput( city=city, state=state, country=country, medical_conditions=medical_conditions, planned_activity=planned_activity ) # Get AQI data aqi_data, info_msg = aqi_analyzer.fetch_aqi_data( city=user_input.city, state=user_input.state, country=user_input.country ) # Format AQI data for display aqi_json = json.dumps({ "Air Quality Index (AQI)": aqi_data['aqi'], "PM2.5": f"{aqi_data['pm25']} µg/m³", "PM10": f"{aqi_data['pm10']} µg/m³", "Carbon Monoxide (CO)": f"{aqi_data['co']} ppb", "Temperature": f"{aqi_data['temperature']}°C", "Humidity": f"{aqi_data['humidity']}%", "Wind Speed": f"{aqi_data['wind_speed']} km/h" }, indent=2) # Get recommendations recommendations = health_agent.get_recommendations(aqi_data, user_input) warning_msg = """ ⚠️ Note: The data shown may not match real-time values on the website. This could be due to: - Cached data in Firecrawl - Rate limiting - Website updates not being captured Consider refreshing or checking the website directly for real-time values. """ return aqi_json, recommendations, info_msg, warning_msg except Exception as e: error_msg = f"Error occurred: {str(e)}" return "", "Analysis failed", error_msg, "" def create_demo() -> gr.Blocks: """Create and configure the Gradio interface""" with gr.Blocks(title="AQI Analysis Agent") as demo: gr.Markdown( """ # 🌍 AQI Analysis Agent Get personalized health recommendations based on air quality conditions. """ ) # API Configuration with gr.Accordion("API Configuration", open=False): firecrawl_key = gr.Textbox( label="Firecrawl API Key", type="password", placeholder="Enter your Firecrawl API key" ) openai_key = gr.Textbox( label="OpenAI API Key", type="password", placeholder="Enter your OpenAI API key" ) # Location Details with gr.Row(): with gr.Column(): city = gr.Textbox(label="City", placeholder="e.g., Mumbai") state = gr.Textbox( label="State", placeholder="Leave blank for Union Territories or US cities", value="" ) country = gr.Textbox(label="Country", value="India") # Personal Details with gr.Row(): with gr.Column(): medical_conditions = gr.Textbox( label="Medical Conditions (optional)", placeholder="e.g., asthma, allergies", lines=2 ) planned_activity = gr.Textbox( label="Planned Activity", placeholder="e.g., morning jog for 2 hours", lines=2 ) # Status Messages info_box = gr.Textbox(label="ℹ️ Status", interactive=False) warning_box = gr.Textbox(label="⚠️ Warning", interactive=False) # Output Areas aqi_data_json = gr.JSON(label="📊 Current Air Quality Data") recommendations = gr.Markdown(label="🏥 Health Recommendations") # Analyze Button analyze_btn = gr.Button("🔍 Analyze & Get Recommendations", variant="primary") analyze_btn.click( fn=analyze_conditions, inputs=[ city, state, country, medical_conditions, planned_activity, firecrawl_key, openai_key ], outputs=[aqi_data_json, recommendations, info_box, warning_box] ) # Examples gr.Examples( examples=[ ["Mumbai", "Maharashtra", "India", "asthma", "morning walk for 30 minutes"], ["Delhi", "", "India", "", "outdoor yoga session"], ["New York", "", "United States", "allergies", "afternoon run"], ["Kakinada", "Andhra Pradesh", "India", "none", "Tennis for 2 hours"] ], inputs=[city, state, country, medical_conditions, planned_activity] ) return demo if __name__ == "__main__": demo = create_demo() demo.launch(share=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_aqi_analysis_agent/ai_aqi_analysis_agent_streamlit.py
advanced_ai_agents/multi_agent_apps/ai_aqi_analysis_agent/ai_aqi_analysis_agent_streamlit.py
from typing import Dict, Optional from dataclasses import dataclass from pydantic import BaseModel, Field from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.openai import OpenAIChat from firecrawl import FirecrawlApp import streamlit as st class AQIResponse(BaseModel): success: bool data: Dict[str, float] status: str expiresAt: str class ExtractSchema(BaseModel): aqi: float = Field(description="Air Quality Index") temperature: float = Field(description="Temperature in degrees Celsius") humidity: float = Field(description="Humidity percentage") wind_speed: float = Field(description="Wind speed in kilometers per hour") pm25: float = Field(description="Particulate Matter 2.5 micrometers") pm10: float = Field(description="Particulate Matter 10 micrometers") co: float = Field(description="Carbon Monoxide level") @dataclass class UserInput: city: str state: str country: str medical_conditions: Optional[str] planned_activity: str class AQIAnalyzer: def __init__(self, firecrawl_key: str) -> None: self.firecrawl = FirecrawlApp(api_key=firecrawl_key) def _format_url(self, country: str, state: str, city: str) -> str: """Format URL based on location, handling cases with and without state""" country_clean = country.lower().replace(' ', '-') city_clean = city.lower().replace(' ', '-') if not state or state.lower() == 'none': return f"https://www.aqi.in/dashboard/{country_clean}/{city_clean}" state_clean = state.lower().replace(' ', '-') return f"https://www.aqi.in/dashboard/{country_clean}/{state_clean}/{city_clean}" def fetch_aqi_data(self, city: str, state: str, country: str) -> Dict[str, float]: """Fetch AQI data using Firecrawl""" try: url = self._format_url(country, state, city) st.info(f"Accessing URL: {url}") # Display URL being accessed response = self.firecrawl.extract( urls=[f"{url}/*"], params={ 'prompt': 'Extract the current real-time AQI, temperature, humidity, wind speed, PM2.5, PM10, and CO levels from the page. Also extract the timestamp of the data.', 'schema': ExtractSchema.model_json_schema() } ) aqi_response = AQIResponse(**response) if not aqi_response.success: raise ValueError(f"Failed to fetch AQI data: {aqi_response.status}") with st.expander("📦 Raw AQI Data", expanded=True): st.json({ "url_accessed": url, "timestamp": aqi_response.expiresAt, "data": aqi_response.data }) st.warning(""" ⚠️ Note: The data shown may not match real-time values on the website. This could be due to: - Cached data in Firecrawl - Rate limiting - Website updates not being captured Consider refreshing or checking the website directly for real-time values. """) return aqi_response.data except Exception as e: st.error(f"Error fetching AQI data: {str(e)}") return { 'aqi': 0, 'temperature': 0, 'humidity': 0, 'wind_speed': 0, 'pm25': 0, 'pm10': 0, 'co': 0 } class HealthRecommendationAgent: def __init__(self, openai_key: str) -> None: self.agent = Agent( model=OpenAIChat( id="gpt-4o", name="Health Recommendation Agent", api_key=openai_key ) ) def get_recommendations( self, aqi_data: Dict[str, float], user_input: UserInput ) -> str: prompt = self._create_prompt(aqi_data, user_input) response: RunOutput = self.agent.run(prompt) return response.content def _create_prompt(self, aqi_data: Dict[str, float], user_input: UserInput) -> str: return f""" Based on the following air quality conditions in {user_input.city}, {user_input.state}, {user_input.country}: - Overall AQI: {aqi_data['aqi']} - PM2.5 Level: {aqi_data['pm25']} µg/m³ - PM10 Level: {aqi_data['pm10']} µg/m³ - CO Level: {aqi_data['co']} ppb Weather conditions: - Temperature: {aqi_data['temperature']}°C - Humidity: {aqi_data['humidity']}% - Wind Speed: {aqi_data['wind_speed']} km/h User's Context: - Medical Conditions: {user_input.medical_conditions or 'None'} - Planned Activity: {user_input.planned_activity} **Comprehensive Health Recommendations:** 1. **Impact of Current Air Quality on Health:** 2. **Necessary Safety Precautions for Planned Activity:** 3. **Advisability of Planned Activity:** 4. **Best Time to Conduct the Activity:** """ def analyze_conditions( user_input: UserInput, api_keys: Dict[str, str] ) -> str: aqi_analyzer = AQIAnalyzer(firecrawl_key=api_keys['firecrawl']) health_agent = HealthRecommendationAgent(openai_key=api_keys['openai']) aqi_data = aqi_analyzer.fetch_aqi_data( city=user_input.city, state=user_input.state, country=user_input.country ) return health_agent.get_recommendations(aqi_data, user_input) def initialize_session_state(): if 'api_keys' not in st.session_state: st.session_state.api_keys = { 'firecrawl': '', 'openai': '' } def setup_page(): st.set_page_config( page_title="AQI Analysis Agent", page_icon="🌍", layout="wide" ) st.title("🌍 AQI Analysis Agent") st.info("Get personalized health recommendations based on air quality conditions.") def render_sidebar(): """Render sidebar with API configuration""" with st.sidebar: st.header("🔑 API Configuration") new_firecrawl_key = st.text_input( "Firecrawl API Key", type="password", value=st.session_state.api_keys['firecrawl'], help="Enter your Firecrawl API key" ) new_openai_key = st.text_input( "OpenAI API Key", type="password", value=st.session_state.api_keys['openai'], help="Enter your OpenAI API key" ) if (new_firecrawl_key and new_openai_key and (new_firecrawl_key != st.session_state.api_keys['firecrawl'] or new_openai_key != st.session_state.api_keys['openai'])): st.session_state.api_keys.update({ 'firecrawl': new_firecrawl_key, 'openai': new_openai_key }) st.success("✅ API keys updated!") def render_main_content(): st.header("📍 Location Details") col1, col2 = st.columns(2) with col1: city = st.text_input("City", placeholder="e.g., Mumbai") state = st.text_input("State", placeholder="If it's a Union Territory or a city in the US, leave it blank") country = st.text_input("Country", value="India", placeholder="United States") with col2: st.header("👤 Personal Details") medical_conditions = st.text_area( "Medical Conditions (optional)", placeholder="e.g., asthma, allergies" ) planned_activity = st.text_area( "Planned Activity", placeholder="e.g., morning jog for 2 hours" ) return UserInput( city=city, state=state, country=country, medical_conditions=medical_conditions, planned_activity=planned_activity ) def main(): """Main application entry point""" initialize_session_state() setup_page() render_sidebar() user_input = render_main_content() result = None if st.button("🔍 Analyze & Get Recommendations"): if not all([user_input.city, user_input.planned_activity]): st.error("Please fill in all required fields (state and medical conditions are optional)") elif not all(st.session_state.api_keys.values()): st.error("Please provide both API keys in the sidebar") else: try: with st.spinner("🔄 Analyzing conditions..."): result = analyze_conditions( user_input=user_input, api_keys=st.session_state.api_keys ) st.success("✅ Analysis completed!") except Exception as e: st.error(f"❌ Error: {str(e)}") if result: st.markdown("### 📦 Recommendations") st.markdown(result) st.download_button( "💾 Download Recommendations", data=result, file_name=f"aqi_recommendations_{user_input.city}_{user_input.state}.txt", mime="text/plain" ) if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_email_gtm_outreach_agent/ai_email_gtm_outreach_agent.py
advanced_ai_agents/multi_agent_apps/ai_email_gtm_outreach_agent/ai_email_gtm_outreach_agent.py
import json import os import sys from typing import Any, Dict, List, Optional import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.tools.exa import ExaTools def require_env(var_name: str) -> None: if not os.getenv(var_name): print(f"Error: {var_name} not set. export {var_name}=...") sys.exit(1) def create_company_finder_agent() -> Agent: exa_tools = ExaTools(category="company") db = SqliteDb(db_file="tmp/gtm_outreach.db") return Agent( model=OpenAIChat(id="gpt-5"), tools=[exa_tools], db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=6, session_id="gtm_outreach_company_finder", debug_mode=True, instructions=[ "You are CompanyFinderAgent. Use ExaTools to search the web for companies that match the targeting criteria.", "Return ONLY valid JSON with key 'companies' as a list; respect the requested limit provided in the user prompt.", "Each item must have: name, website, why_fit (1-2 lines).", ], ) def create_contact_finder_agent() -> Agent: exa_tools = ExaTools() db = SqliteDb(db_file="tmp/gtm_outreach.db") return Agent( model=OpenAIChat(id="gpt-4o"), tools=[exa_tools], db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=6, session_id="gtm_outreach_contact_finder", debug_mode=True, instructions=[ "You are ContactFinderAgent. Use ExaTools to find 1-2 relevant decision makers per company and their emails if available.", "Prioritize roles from Founder's Office, GTM (Marketing/Growth), Sales leadership, Partnerships/Business Development, and Product Marketing.", "Search queries can include patterns like '<Company> email format', 'contact', 'team', 'leadership', and role titles.", "If direct emails are not found, infer likely email using common formats (e.g., first.last@domain), but mark inferred=true.", "Return ONLY valid JSON with key 'companies' as a list; each has: name, contacts: [{full_name, title, email, inferred}]", ], ) def get_email_style_instruction(style_key: str) -> str: styles = { "Professional": "Style: Professional. Clear, respectful, and businesslike. Short paragraphs; no slang.", "Casual": "Style: Casual. Friendly, approachable, first-name basis. No slang or emojis; keep it human.", "Cold": "Style: Cold email. Strong hook in opening 2 lines, tight value proposition, minimal fluff, strong CTA.", "Consultative": "Style: Consultative. Insight-led, frames observed problems and tailored solution hypotheses; soft CTA.", } return styles.get(style_key, styles["Professional"]) def create_email_writer_agent(style_key: str = "Professional") -> Agent: db = SqliteDb(db_file="tmp/gtm_outreach.db") style_instruction = get_email_style_instruction(style_key) return Agent( model=OpenAIChat(id="gpt-5"), tools=[], db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=6, session_id="gtm_outreach_email_writer", debug_mode=False, instructions=[ "You are EmailWriterAgent. Write concise, personalized B2B outreach emails.", style_instruction, "Return ONLY valid JSON with key 'emails' as a list of items: {company, contact, subject, body}.", "Length: 120-160 words. Include 1-2 lines of strong personalization referencing research insights (company website and Reddit findings).", "CTA: suggest a short intro call; include sender company name and calendar link if provided.", ], ) def create_research_agent() -> Agent: """Agent to gather interesting insights from company websites and Reddit.""" exa_tools = ExaTools() db = SqliteDb(db_file="tmp/gtm_outreach.db") return Agent( model=OpenAIChat(id="gpt-5"), tools=[exa_tools], db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=6, session_id="gtm_outreach_researcher", debug_mode=True, instructions=[ "You are ResearchAgent. For each company, collect concise, valuable insights from:", "1) Their official website (about, blog, product pages)", "2) Reddit discussions (site:reddit.com mentions)", "Summarize 2-4 interesting, non-generic points per company that a human would bring up in an email to show genuine effort.", "Return ONLY valid JSON with key 'companies' as a list; each has: name, insights: [strings].", ], ) def extract_json_or_raise(text: str) -> Dict[str, Any]: """Extract JSON from a model response. Assumes the response is pure JSON.""" try: return json.loads(text) except Exception as e: # Try to locate a JSON block if extra text snuck in start = text.find("{") end = text.rfind("}") if start != -1 and end != -1 and end > start: candidate = text[start : end + 1] return json.loads(candidate) raise ValueError(f"Failed to parse JSON: {e}\nResponse was:\n{text}") def run_company_finder(agent: Agent, target_desc: str, offering_desc: str, max_companies: int) -> List[Dict[str, str]]: prompt = ( f"Find exactly {max_companies} companies that are a strong B2B fit given the user inputs.\n" f"Targeting: {target_desc}\n" f"Offering: {offering_desc}\n" "For each, provide: name, website, why_fit (1-2 lines)." ) resp: RunOutput = agent.run(prompt) data = extract_json_or_raise(str(resp.content)) companies = data.get("companies", []) return companies[: max(1, min(max_companies, 10))] def run_contact_finder(agent: Agent, companies: List[Dict[str, str]], target_desc: str, offering_desc: str) -> List[Dict[str, Any]]: prompt = ( "For each company below, find 2-3 relevant decision makers and emails (if available). Ensure at least 2 per company when possible, and cap at 3.\n" "If not available, infer likely email and mark inferred=true.\n" f"Targeting: {target_desc}\nOffering: {offering_desc}\n" f"Companies JSON: {json.dumps(companies, ensure_ascii=False)}\n" "Return JSON: {companies: [{name, contacts: [{full_name, title, email, inferred}]}]}" ) resp: RunOutput = agent.run(prompt) data = extract_json_or_raise(str(resp.content)) return data.get("companies", []) def run_research(agent: Agent, companies: List[Dict[str, str]]) -> List[Dict[str, Any]]: prompt = ( "For each company, gather 2-4 interesting insights from their website and Reddit that would help personalize outreach.\n" f"Companies JSON: {json.dumps(companies, ensure_ascii=False)}\n" "Return JSON: {companies: [{name, insights: [string, ...]}]}" ) resp: RunOutput = agent.run(prompt) data = extract_json_or_raise(str(resp.content)) return data.get("companies", []) def run_email_writer(agent: Agent, contacts_data: List[Dict[str, Any]], research_data: List[Dict[str, Any]], offering_desc: str, sender_name: str, sender_company: str, calendar_link: Optional[str]) -> List[Dict[str, str]]: prompt = ( "Write personalized outreach emails for the following contacts.\n" f"Sender: {sender_name} at {sender_company}.\n" f"Offering: {offering_desc}.\n" f"Calendar link: {calendar_link or 'N/A'}.\n" f"Contacts JSON: {json.dumps(contacts_data, ensure_ascii=False)}\n" f"Research JSON: {json.dumps(research_data, ensure_ascii=False)}\n" "Return JSON with key 'emails' as a list of {company, contact, subject, body}." ) resp: RunOutput = agent.run(prompt) data = extract_json_or_raise(str(resp.content)) return data.get("emails", []) def run_pipeline(target_desc: str, offering_desc: str, sender_name: str, sender_company: str, calendar_link: Optional[str], num_companies: int): company_agent = create_company_finder_agent() contact_agent = create_contact_finder_agent() research_agent = create_research_agent() companies = run_company_finder(company_agent, target_desc, offering_desc, max_companies=num_companies) contacts_data = run_contact_finder(contact_agent, companies, target_desc, offering_desc) if companies else [] research_data = run_research(research_agent, companies) if companies else [] return { "companies": companies, "contacts": contacts_data, "research": research_data, "emails": [], } def main() -> None: st.set_page_config(page_title="GTM B2B Outreach", layout="wide") # Sidebar: API keys st.sidebar.header("API Configuration") openai_key = st.sidebar.text_input("OpenAI API Key", type="password", value=os.getenv("OPENAI_API_KEY", "")) exa_key = st.sidebar.text_input("Exa API Key", type="password", value=os.getenv("EXA_API_KEY", "")) if openai_key: os.environ["OPENAI_API_KEY"] = openai_key if exa_key: os.environ["EXA_API_KEY"] = exa_key if not openai_key or not exa_key: st.sidebar.warning("Enter both API keys to enable the app") # Inputs st.title("GTM B2B Outreach Multi Agent Team") st.info( "GTM teams often need to reach out for demos and discovery calls, but manual research and personalization is slow. " "This app uses GPT-5 with a multi-agent workflow to find target companies, identify contacts, research genuine insights (website + Reddit), " "and generate tailored outreach emails in your chosen style." ) col1, col2 = st.columns(2) with col1: target_desc = st.text_area("Target companies (industry, size, region, tech, etc.)", height=100) offering_desc = st.text_area("Your product/service offering (1-3 sentences)", height=100) with col2: sender_name = st.text_input("Your name", value="Sales Team") sender_company = st.text_input("Your company", value="Our Company") calendar_link = st.text_input("Calendar link (optional)", value="") num_companies = st.number_input("Number of companies", min_value=1, max_value=10, value=5) email_style = st.selectbox( "Email style", options=["Professional", "Casual", "Cold", "Consultative"], index=0, help="Choose the tone/format for the generated emails", ) if st.button("Start Outreach", type="primary"): # Validate if not openai_key or not exa_key: st.error("Please provide API keys in the sidebar") elif not target_desc or not offering_desc: st.error("Please fill in target companies and offering") else: # Stage-by-stage progress UI progress = st.progress(0) stage_msg = st.empty() details = st.empty() try: # Prepare agents company_agent = create_company_finder_agent() contact_agent = create_contact_finder_agent() research_agent = create_research_agent() email_agent = create_email_writer_agent(email_style) # 1. Companies stage_msg.info("1/4 Finding companies...") companies = run_company_finder( company_agent, target_desc.strip(), offering_desc.strip(), max_companies=int(num_companies), ) progress.progress(25) details.write(f"Found {len(companies)} companies") # 2. Contacts stage_msg.info("2/4 Finding contacts (2–3 per company)...") contacts_data = run_contact_finder( contact_agent, companies, target_desc.strip(), offering_desc.strip(), ) if companies else [] progress.progress(50) details.write(f"Collected contacts for {len(contacts_data)} companies") # 3. Research stage_msg.info("3/4 Researching insights (website + Reddit)...") research_data = run_research(research_agent, companies) if companies else [] progress.progress(75) details.write(f"Compiled research for {len(research_data)} companies") # 4. Emails stage_msg.info("4/4 Writing personalized emails...") emails = run_email_writer( email_agent, contacts_data, research_data, offering_desc.strip(), sender_name.strip() or "Sales Team", sender_company.strip() or "Our Company", calendar_link.strip() or None, ) if contacts_data else [] progress.progress(100) details.write(f"Generated {len(emails)} emails") st.session_state["gtm_results"] = { "companies": companies, "contacts": contacts_data, "research": research_data, "emails": emails, } stage_msg.success("Completed") except Exception as e: stage_msg.error("Pipeline failed") st.error(f"{e}") # Show results if present results = st.session_state.get("gtm_results") if results: companies = results.get("companies", []) contacts = results.get("contacts", []) research = results.get("research", []) emails = results.get("emails", []) st.subheader("Top target companies") if companies: for idx, c in enumerate(companies, 1): st.markdown(f"**{idx}. {c.get('name','')}** ") st.write(c.get("website", "")) st.write(c.get("why_fit", "")) else: st.info("No companies found") st.divider() st.subheader("Contacts found") if contacts: for c in contacts: st.markdown(f"**{c.get('name','')}**") for p in c.get("contacts", [])[:3]: inferred = " (inferred)" if p.get("inferred") else "" st.write(f"- {p.get('full_name','')} | {p.get('title','')} | {p.get('email','')}{inferred}") else: st.info("No contacts found") st.divider() st.subheader("Research insights") if research: for r in research: st.markdown(f"**{r.get('name','')}**") for insight in r.get("insights", [])[:4]: st.write(f"- {insight}") else: st.info("No research insights") st.divider() st.subheader("Suggested Outreach Emails") if emails: for i, e in enumerate(emails, 1): with st.expander(f"{i}. {e.get('company','')} → {e.get('contact','')}"): st.write(f"Subject: {e.get('subject','')}") st.text(e.get("body", "")) else: st.info("No emails generated") if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py
advanced_ai_agents/multi_agent_apps/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py
import streamlit as st from autogen import (SwarmAgent, SwarmResult, initiate_swarm_chat, OpenAIWrapper,AFTER_WORK,UPDATE_SYSTEM_MESSAGE) import os os.environ["AUTOGEN_USE_DOCKER"] = "0" if 'output' not in st.session_state: st.session_state.output = { 'assessment': '', 'action': '', 'followup': '' } st.sidebar.title("OpenAI API Key") api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") st.sidebar.warning(""" ## ⚠️ Important Notice This application is a supportive tool and does not replace professional mental health care. If you're experiencing thoughts of self-harm or severe crisis: - Call National Crisis Hotline: 988 - Call Emergency Services: 911 - Seek immediate professional help """) st.title("🧠 Mental Wellbeing Agent") st.info(""" **Meet Your Mental Wellbeing Agent Team:** 🧠 **Assessment Agent** - Analyzes your situation and emotional needs 🎯 **Action Agent** - Creates immediate action plan and connects you with resources 🔄 **Follow-up Agent** - Designs your long-term support strategy """) st.subheader("Personal Information") col1, col2 = st.columns(2) with col1: mental_state = st.text_area("How have you been feeling recently?", placeholder="Describe your emotional state, thoughts, or concerns...") sleep_pattern = st.select_slider( "Sleep Pattern (hours per night)", options=[f"{i}" for i in range(0, 13)], value="7" ) with col2: stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) support_system = st.multiselect( "Current Support System", ["Family", "Friends", "Therapist", "Support Groups", "None"] ) recent_changes = st.text_area( "Any significant life changes or events recently?", placeholder="Job changes, relationships, losses, etc..." ) current_symptoms = st.multiselect( "Current Symptoms", ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", "Mood Swings", "Physical Discomfort"] ) if st.button("Get Support Plan"): if not api_key: st.error("Please enter your OpenAI API key.") else: with st.spinner('🤖 AI Agents are analyzing your situation...'): try: task = f""" Create a comprehensive mental health support plan based on: Emotional State: {mental_state} Sleep: {sleep_pattern} hours per night Stress Level: {stress_level}/10 Support System: {', '.join(support_system) if support_system else 'None reported'} Recent Changes: {recent_changes} Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} """ system_messages = { "assessment_agent": """ You are an experienced mental health professional speaking directly to the user. Your task is to: 1. Create a safe space by acknowledging their courage in seeking support 2. Analyze their emotional state with clinical precision and genuine empathy 3. Ask targeted follow-up questions to understand their full situation 4. Identify patterns in their thoughts, behaviors, and relationships 5. Assess risk levels with validated screening approaches 6. Help them understand their current mental health in accessible language 7. Validate their experiences without minimizing or catastrophizing Always use "you" and "your" when addressing the user. Blend clinical expertise with genuine warmth and never rush to conclusions. """, "action_agent": """ You are a crisis intervention and resource specialist speaking directly to the user. Your task is to: 1. Provide immediate evidence-based coping strategies tailored to their specific situation 2. Prioritize interventions based on urgency and effectiveness 3. Connect them with appropriate mental health services while acknowledging barriers (cost, access, stigma) 4. Create a concrete daily wellness plan with specific times and activities 5. Suggest specific support communities with details on how to join 6. Balance crisis resources with empowerment techniques 7. Teach simple self-regulation techniques they can use immediately Focus on practical, achievable steps that respect their current capacity and energy levels. Provide options ranging from minimal effort to more involved actions. """, "followup_agent": """ You are a mental health recovery planner speaking directly to the user. Your task is to: 1. Design a personalized long-term support strategy with milestone markers 2. Create a progress monitoring system that matches their preferences and habits 3. Develop specific relapse prevention strategies based on their unique triggers 4. Establish a support network mapping exercise to identify existing resources 5. Build a graduated self-care routine that evolves with their recovery 6. Plan for setbacks with self-compassion techniques 7. Set up a maintenance schedule with clear check-in mechanisms Focus on building sustainable habits that integrate with their lifestyle and values. Emphasize progress over perfection and teach skills for self-directed care. """ } llm_config = { "config_list": [{"model": "gpt-4o", "api_key": api_key}] } context_variables = { "assessment": None, "action": None, "followup": None, } def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: context_variables["assessment"] = assessment_summary st.sidebar.success('Assessment: ' + assessment_summary) return SwarmResult(agent="action_agent", context_variables=context_variables) def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: context_variables["action"] = action_summary st.sidebar.success('Action Plan: ' + action_summary) return SwarmResult(agent="followup_agent", context_variables=context_variables) def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: context_variables["followup"] = followup_summary st.sidebar.success('Follow-up Strategy: ' + followup_summary) return SwarmResult(agent="assessment_agent", context_variables=context_variables) def update_system_message_func(agent: SwarmAgent, messages) -> str: system_prompt = system_messages[agent.name] current_gen = agent.name.split("_")[0] if agent._context_variables.get(current_gen) is None: system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} else: agent.llm_config["tools"] = None agent.llm_config['tool_choice'] = None system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." k = list(agent._oai_messages.keys())[-1] agent._oai_messages[k] = agent._oai_messages[k][:1] system_prompt += f"\n\n\nBelow are some context for you to refer to:" for k, v in agent._context_variables.items(): if v is not None: system_prompt += f"\n{k.capitalize()} Summary:\n{v}" agent.client = OpenAIWrapper(**agent.llm_config) return system_prompt state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) assessment_agent = SwarmAgent( "assessment_agent", llm_config=llm_config, functions=update_assessment_overview, update_agent_state_before_reply=[state_update] ) action_agent = SwarmAgent( "action_agent", llm_config=llm_config, functions=update_action_overview, update_agent_state_before_reply=[state_update] ) followup_agent = SwarmAgent( "followup_agent", llm_config=llm_config, functions=update_followup_overview, update_agent_state_before_reply=[state_update] ) assessment_agent.register_hand_off(AFTER_WORK(action_agent)) action_agent.register_hand_off(AFTER_WORK(followup_agent)) followup_agent.register_hand_off(AFTER_WORK(assessment_agent)) result, _, _ = initiate_swarm_chat( initial_agent=assessment_agent, agents=[assessment_agent, action_agent, followup_agent], user_agent=None, messages=task, max_rounds=13, ) st.session_state.output = { 'assessment': result.chat_history[-3]['content'], 'action': result.chat_history[-2]['content'], 'followup': result.chat_history[-1]['content'] } with st.expander("Situation Assessment"): st.markdown(st.session_state.output['assessment']) with st.expander("Action Plan & Resources"): st.markdown(st.session_state.output['action']) with st.expander("Long-term Support Strategy"): st.markdown(st.session_state.output['followup']) st.success('✨ Mental health support plan generated successfully!') except Exception as e: st.error(f"An error occurred: {str(e)}")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_financial_coach_agent/ai_financial_coach_agent.py
advanced_ai_agents/multi_agent_apps/ai_financial_coach_agent/ai_financial_coach_agent.py
import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from typing import Dict, List, Optional, Any import os import asyncio from datetime import datetime from dotenv import load_dotenv import json import logging from pydantic import BaseModel, Field import csv from io import StringIO from google.adk.agents import LlmAgent, SequentialAgent from google.adk.sessions import InMemorySessionService from google.adk.runners import Runner from google.genai import types logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) APP_NAME = "finance_advisor" USER_ID = "default_user" # Pydantic models for output schemas class SpendingCategory(BaseModel): category: str = Field(..., description="Expense category name") amount: float = Field(..., description="Amount spent in this category") percentage: Optional[float] = Field(None, description="Percentage of total spending") class SpendingRecommendation(BaseModel): category: str = Field(..., description="Category for recommendation") recommendation: str = Field(..., description="Recommendation details") potential_savings: Optional[float] = Field(None, description="Estimated monthly savings") class BudgetAnalysis(BaseModel): total_expenses: float = Field(..., description="Total monthly expenses") monthly_income: Optional[float] = Field(None, description="Monthly income") spending_categories: List[SpendingCategory] = Field(..., description="Breakdown of spending by category") recommendations: List[SpendingRecommendation] = Field(..., description="Spending recommendations") class EmergencyFund(BaseModel): recommended_amount: float = Field(..., description="Recommended emergency fund size") current_amount: Optional[float] = Field(None, description="Current emergency fund (if any)") current_status: str = Field(..., description="Status assessment of emergency fund") class SavingsRecommendation(BaseModel): category: str = Field(..., description="Savings category") amount: float = Field(..., description="Recommended monthly amount") rationale: Optional[str] = Field(None, description="Explanation for this recommendation") class AutomationTechnique(BaseModel): name: str = Field(..., description="Name of automation technique") description: str = Field(..., description="Details of how to implement") class SavingsStrategy(BaseModel): emergency_fund: EmergencyFund = Field(..., description="Emergency fund recommendation") recommendations: List[SavingsRecommendation] = Field(..., description="Savings allocation recommendations") automation_techniques: Optional[List[AutomationTechnique]] = Field(None, description="Automation techniques to help save") class Debt(BaseModel): name: str = Field(..., description="Name of debt") amount: float = Field(..., description="Current balance") interest_rate: float = Field(..., description="Annual interest rate (%)") min_payment: Optional[float] = Field(None, description="Minimum monthly payment") class PayoffPlan(BaseModel): total_interest: float = Field(..., description="Total interest paid") months_to_payoff: int = Field(..., description="Months until debt-free") monthly_payment: Optional[float] = Field(None, description="Recommended monthly payment") class PayoffPlans(BaseModel): avalanche: PayoffPlan = Field(..., description="Highest interest first method") snowball: PayoffPlan = Field(..., description="Smallest balance first method") class DebtRecommendation(BaseModel): title: str = Field(..., description="Title of recommendation") description: str = Field(..., description="Details of recommendation") impact: Optional[str] = Field(None, description="Expected impact of this action") class DebtReduction(BaseModel): total_debt: float = Field(..., description="Total debt amount") debts: List[Debt] = Field(..., description="List of all debts") payoff_plans: PayoffPlans = Field(..., description="Debt payoff strategies") recommendations: Optional[List[DebtRecommendation]] = Field(None, description="Recommendations for debt reduction") load_dotenv() GEMINI_API_KEY = os.getenv("GOOGLE_API_KEY") def parse_json_safely(data: str, default_value: Any = None) -> Any: """Safely parse JSON data with error handling""" try: return json.loads(data) if isinstance(data, str) else data except json.JSONDecodeError: return default_value class FinanceAdvisorSystem: def __init__(self): self.session_service = InMemorySessionService() self.budget_analysis_agent = LlmAgent( name="BudgetAnalysisAgent", model="gemini-2.5-flash", description="Analyzes financial data to categorize spending patterns and recommend budget improvements", instruction="""You are a Budget Analysis Agent specialized in reviewing financial transactions and expenses. You are the first agent in a sequence of three financial advisor agents. Your tasks: 1. Analyze income, transactions, and expenses in detail 2. Categorize spending into logical groups with clear breakdown 3. Identify spending patterns and trends across categories 4. Suggest specific areas where spending could be reduced with concrete suggestions 5. Provide actionable recommendations with specific, quantified potential savings amounts Consider: - Number of dependants when evaluating household expenses - Typical spending ratios for the income level (housing 30%, food 15%, etc.) - Essential vs discretionary spending with clear separation - Seasonal spending patterns if data spans multiple months For spending categories, include ALL expenses from the user's data, ensure percentages add up to 100%, and make sure every expense is categorized. For recommendations: - Provide at least 3-5 specific, actionable recommendations with estimated savings - Explain the reasoning behind each recommendation - Consider the impact on quality of life and long-term financial health - Suggest specific implementation steps for each recommendation IMPORTANT: Store your analysis in state['budget_analysis'] for use by subsequent agents.""", output_schema=BudgetAnalysis, output_key="budget_analysis" ) self.savings_strategy_agent = LlmAgent( name="SavingsStrategyAgent", model="gemini-2.5-flash", description="Recommends optimal savings strategies based on income, expenses, and financial goals", instruction="""You are a Savings Strategy Agent specialized in creating personalized savings plans. You are the second agent in the sequence. READ the budget analysis from state['budget_analysis'] first. Your tasks: 1. Review the budget analysis results from state['budget_analysis'] 2. Recommend comprehensive savings strategies based on the analysis 3. Calculate optimal emergency fund size based on expenses and dependants 4. Suggest appropriate savings allocation across different purposes 5. Recommend practical automation techniques for saving consistently Consider: - Risk factors based on job stability and dependants - Balancing immediate needs with long-term financial health - Progressive savings rates as discretionary income increases - Multiple savings goals (emergency, retirement, specific purchases) - Areas of potential savings identified in the budget analysis IMPORTANT: Store your strategy in state['savings_strategy'] for use by the Debt Reduction Agent.""", output_schema=SavingsStrategy, output_key="savings_strategy" ) self.debt_reduction_agent = LlmAgent( name="DebtReductionAgent", model="gemini-2.5-flash", description="Creates optimized debt payoff plans to minimize interest paid and time to debt freedom", instruction="""You are a Debt Reduction Agent specialized in creating debt payoff strategies. You are the final agent in the sequence. READ both state['budget_analysis'] and state['savings_strategy'] first. Your tasks: 1. Review both budget analysis and savings strategy from the state 2. Analyze debts by interest rate, balance, and minimum payments 3. Create prioritized debt payoff plans (avalanche and snowball methods) 4. Calculate total interest paid and time to debt freedom 5. Suggest debt consolidation or refinancing opportunities 6. Provide specific recommendations to accelerate debt payoff Consider: - Cash flow constraints from the budget analysis - Emergency fund and savings goals from the savings strategy - Psychological factors (quick wins vs mathematical optimization) - Credit score impact and improvement opportunities IMPORTANT: Store your final plan in state['debt_reduction'] and ensure it aligns with the previous analyses.""", output_schema=DebtReduction, output_key="debt_reduction" ) self.coordinator_agent = SequentialAgent( name="FinanceCoordinatorAgent", description="Coordinates specialized finance agents to provide comprehensive financial advice", sub_agents=[ self.budget_analysis_agent, self.savings_strategy_agent, self.debt_reduction_agent ] ) self.runner = Runner( agent=self.coordinator_agent, app_name=APP_NAME, session_service=self.session_service ) async def analyze_finances(self, financial_data: Dict[str, Any]) -> Dict[str, Any]: session_id = f"finance_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" try: initial_state = { "monthly_income": financial_data.get("monthly_income", 0), "dependants": financial_data.get("dependants", 0), "transactions": financial_data.get("transactions", []), "manual_expenses": financial_data.get("manual_expenses", {}), "debts": financial_data.get("debts", []) } session = self.session_service.create_session( app_name=APP_NAME, user_id=USER_ID, session_id=session_id, state=initial_state ) if session.state.get("transactions"): self._preprocess_transactions(session) if session.state.get("manual_expenses"): self._preprocess_manual_expenses(session) default_results = self._create_default_results(financial_data) user_content = types.Content( role='user', parts=[types.Part(text=json.dumps(financial_data))] ) async for event in self.runner.run_async( user_id=USER_ID, session_id=session_id, new_message=user_content ): if event.is_final_response() and event.author == self.coordinator_agent.name: break updated_session = self.session_service.get_session( app_name=APP_NAME, user_id=USER_ID, session_id=session_id ) results = {} for key in ["budget_analysis", "savings_strategy", "debt_reduction"]: value = updated_session.state.get(key) results[key] = parse_json_safely(value, default_results[key]) if value else default_results[key] return results except Exception as e: logger.exception(f"Error during finance analysis: {str(e)}") raise finally: self.session_service.delete_session( app_name=APP_NAME, user_id=USER_ID, session_id=session_id ) def _preprocess_transactions(self, session): transactions = session.state.get("transactions", []) if not transactions: return df = pd.DataFrame(transactions) if 'Date' in df.columns: df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d') if 'Category' in df.columns and 'Amount' in df.columns: category_spending = df.groupby('Category')['Amount'].sum().to_dict() session.state["category_spending"] = category_spending session.state["total_spending"] = df['Amount'].sum() def _preprocess_manual_expenses(self, session): manual_expenses = session.state.get("manual_expenses", {}) if not manual_expenses or manual_expenses is None: return session.state.update({ "total_manual_spending": sum(manual_expenses.values()), "manual_category_spending": manual_expenses }) def _create_default_results(self, financial_data: Dict[str, Any]) -> Dict[str, Any]: monthly_income = financial_data.get("monthly_income", 0) expenses = financial_data.get("manual_expenses", {}) # Ensure expenses is not None if expenses is None: expenses = {} if not expenses and financial_data.get("transactions"): expenses = {} for transaction in financial_data["transactions"]: category = transaction.get("Category", "Uncategorized") amount = transaction.get("Amount", 0) expenses[category] = expenses.get(category, 0) + amount total_expenses = sum(expenses.values()) return { "budget_analysis": { "total_expenses": total_expenses, "monthly_income": monthly_income, "spending_categories": [ {"category": cat, "amount": amt, "percentage": (amt / total_expenses * 100) if total_expenses > 0 else 0} for cat, amt in expenses.items() ], "recommendations": [ {"category": "General", "recommendation": "Consider reviewing your expenses carefully", "potential_savings": total_expenses * 0.1} ] }, "savings_strategy": { "emergency_fund": { "recommended_amount": total_expenses * 6, "current_amount": 0, "current_status": "Not started" }, "recommendations": [ {"category": "Emergency Fund", "amount": total_expenses * 0.1, "rationale": "Build emergency fund first"}, {"category": "Retirement", "amount": monthly_income * 0.15, "rationale": "Long-term savings"} ], "automation_techniques": [ {"name": "Automatic Transfer", "description": "Set up automatic transfers on payday"} ] }, "debt_reduction": { "total_debt": sum(debt.get("amount", 0) for debt in financial_data.get("debts", [])), "debts": financial_data.get("debts", []), "payoff_plans": { "avalanche": { "total_interest": sum(debt.get("amount", 0) for debt in financial_data.get("debts", [])) * 0.2, "months_to_payoff": 24, "monthly_payment": sum(debt.get("amount", 0) for debt in financial_data.get("debts", [])) / 24 }, "snowball": { "total_interest": sum(debt.get("amount", 0) for debt in financial_data.get("debts", [])) * 0.25, "months_to_payoff": 24, "monthly_payment": sum(debt.get("amount", 0) for debt in financial_data.get("debts", [])) / 24 } }, "recommendations": [ {"title": "Increase Payments", "description": "Increase your monthly payments", "impact": "Reduces total interest paid"} ] } } def display_budget_analysis(analysis: Dict[str, Any]): if isinstance(analysis, str): try: analysis = json.loads(analysis) except json.JSONDecodeError: st.error("Failed to parse budget analysis results") return if not isinstance(analysis, dict): st.error("Invalid budget analysis format") return if "spending_categories" in analysis: st.subheader("Spending by Category") fig = px.pie( values=[cat["amount"] for cat in analysis["spending_categories"]], names=[cat["category"] for cat in analysis["spending_categories"]], title="Your Spending Breakdown" ) st.plotly_chart(fig) if "total_expenses" in analysis: st.subheader("Income vs. Expenses") income = analysis.get("monthly_income", 0) expenses = analysis["total_expenses"] surplus_deficit = income - expenses fig = go.Figure() fig.add_trace(go.Bar(x=["Income", "Expenses"], y=[income, expenses], marker_color=["green", "red"])) fig.update_layout(title="Monthly Income vs. Expenses") st.plotly_chart(fig) st.metric("Monthly Surplus/Deficit", f"${surplus_deficit:.2f}", delta=f"{surplus_deficit:.2f}") if "recommendations" in analysis: st.subheader("Spending Reduction Recommendations") for rec in analysis["recommendations"]: st.markdown(f"**{rec['category']}**: {rec['recommendation']}") if "potential_savings" in rec: st.metric(f"Potential Monthly Savings", f"${rec['potential_savings']:.2f}") def display_savings_strategy(strategy: Dict[str, Any]): if isinstance(strategy, str): try: strategy = json.loads(strategy) except json.JSONDecodeError: st.error("Failed to parse savings strategy results") return if not isinstance(strategy, dict): st.error("Invalid savings strategy format") return st.subheader("Savings Recommendations") if "emergency_fund" in strategy: ef = strategy["emergency_fund"] st.markdown(f"### Emergency Fund") st.markdown(f"**Recommended Size**: ${ef['recommended_amount']:.2f}") st.markdown(f"**Current Status**: {ef['current_status']}") if "current_amount" in ef and "recommended_amount" in ef: progress = ef["current_amount"] / ef["recommended_amount"] st.progress(min(progress, 1.0)) st.markdown(f"${ef['current_amount']:.2f} of ${ef['recommended_amount']:.2f}") if "recommendations" in strategy: st.markdown("### Recommended Savings Allocations") for rec in strategy["recommendations"]: st.markdown(f"**{rec['category']}**: ${rec['amount']:.2f}/month") st.markdown(f"_{rec['rationale']}_") if "automation_techniques" in strategy: st.markdown("### Automation Techniques") for technique in strategy["automation_techniques"]: st.markdown(f"**{technique['name']}**: {technique['description']}") def display_debt_reduction(plan: Dict[str, Any]): if isinstance(plan, str): try: plan = json.loads(plan) except json.JSONDecodeError: st.error("Failed to parse debt reduction results") return if not isinstance(plan, dict): st.error("Invalid debt reduction format") return if "total_debt" in plan: st.metric("Total Debt", f"${plan['total_debt']:.2f}") if "debts" in plan: st.subheader("Your Debts") debt_df = pd.DataFrame(plan["debts"]) st.dataframe(debt_df) fig = px.bar(debt_df, x="name", y="amount", color="interest_rate", labels={"name": "Debt", "amount": "Amount ($)", "interest_rate": "Interest Rate (%)"}, title="Debt Breakdown") st.plotly_chart(fig) if "payoff_plans" in plan: st.subheader("Debt Payoff Plans") tabs = st.tabs(["Avalanche Method", "Snowball Method", "Comparison"]) with tabs[0]: st.markdown("### Avalanche Method (Highest Interest First)") if "avalanche" in plan["payoff_plans"]: avalanche = plan["payoff_plans"]["avalanche"] st.markdown(f"**Total Interest Paid**: ${avalanche['total_interest']:.2f}") st.markdown(f"**Time to Debt Freedom**: {avalanche['months_to_payoff']} months") if "monthly_payment" in avalanche: st.markdown(f"**Recommended Monthly Payment**: ${avalanche['monthly_payment']:.2f}") with tabs[1]: st.markdown("### Snowball Method (Smallest Balance First)") if "snowball" in plan["payoff_plans"]: snowball = plan["payoff_plans"]["snowball"] st.markdown(f"**Total Interest Paid**: ${snowball['total_interest']:.2f}") st.markdown(f"**Time to Debt Freedom**: {snowball['months_to_payoff']} months") if "monthly_payment" in snowball: st.markdown(f"**Recommended Monthly Payment**: ${snowball['monthly_payment']:.2f}") with tabs[2]: st.markdown("### Method Comparison") if "avalanche" in plan["payoff_plans"] and "snowball" in plan["payoff_plans"]: avalanche = plan["payoff_plans"]["avalanche"] snowball = plan["payoff_plans"]["snowball"] comparison_data = { "Method": ["Avalanche", "Snowball"], "Total Interest": [avalanche["total_interest"], snowball["total_interest"]], "Months to Payoff": [avalanche["months_to_payoff"], snowball["months_to_payoff"]] } comparison_df = pd.DataFrame(comparison_data) st.dataframe(comparison_df) fig = go.Figure(data=[ go.Bar(name="Total Interest", x=comparison_df["Method"], y=comparison_df["Total Interest"]), go.Bar(name="Months to Payoff", x=comparison_df["Method"], y=comparison_df["Months to Payoff"]) ]) fig.update_layout(barmode='group', title="Debt Payoff Method Comparison") st.plotly_chart(fig) if "recommendations" in plan: st.subheader("Debt Reduction Recommendations") for rec in plan["recommendations"]: st.markdown(f"**{rec['title']}**: {rec['description']}") if "impact" in rec: st.markdown(f"_Impact: {rec['impact']}_") def parse_csv_transactions(file_content) -> List[Dict[str, Any]]: """Parse CSV file content into a list of transactions""" try: # Read CSV content df = pd.read_csv(StringIO(file_content.decode('utf-8'))) # Validate required columns required_columns = ['Date', 'Category', 'Amount'] missing_columns = [col for col in required_columns if col not in df.columns] if missing_columns: raise ValueError(f"Missing required columns: {', '.join(missing_columns)}") # Convert date strings to datetime and then to string format YYYY-MM-DD df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d') # Convert amount strings to float, handling currency symbols and commas df['Amount'] = df['Amount'].replace('[\$,]', '', regex=True).astype(float) # Group by category and calculate totals category_totals = df.groupby('Category')['Amount'].sum().reset_index() # Convert to list of dictionaries transactions = df.to_dict('records') return { 'transactions': transactions, 'category_totals': category_totals.to_dict('records') } except Exception as e: raise ValueError(f"Error parsing CSV file: {str(e)}") def validate_csv_format(file) -> bool: """Validate CSV file format and content""" try: content = file.read().decode('utf-8') dialect = csv.Sniffer().sniff(content) has_header = csv.Sniffer().has_header(content) file.seek(0) # Reset file pointer if not has_header: return False, "CSV file must have headers" df = pd.read_csv(StringIO(content)) required_columns = ['Date', 'Category', 'Amount'] missing_columns = [col for col in required_columns if col not in df.columns] if missing_columns: return False, f"Missing required columns: {', '.join(missing_columns)}" # Validate date format try: pd.to_datetime(df['Date']) except: return False, "Invalid date format in Date column" # Validate amount format (should be numeric after removing currency symbols) try: df['Amount'].replace('[\$,]', '', regex=True).astype(float) except: return False, "Invalid amount format in Amount column" return True, "CSV format is valid" except Exception as e: return False, f"Invalid CSV format: {str(e)}" def display_csv_preview(df: pd.DataFrame): """Display a preview of the CSV data with basic statistics""" st.subheader("CSV Data Preview") # Show basic statistics total_transactions = len(df) total_amount = df['Amount'].sum() # Convert dates for display df_dates = pd.to_datetime(df['Date']) date_range = f"{df_dates.min().strftime('%Y-%m-%d')} to {df_dates.max().strftime('%Y-%m-%d')}" col1, col2, col3 = st.columns(3) with col1: st.metric("Total Transactions", total_transactions) with col2: st.metric("Total Amount", f"${total_amount:,.2f}") with col3: st.metric("Date Range", date_range) # Show category breakdown st.subheader("Spending by Category") category_totals = df.groupby('Category')['Amount'].agg(['sum', 'count']).reset_index() category_totals.columns = ['Category', 'Total Amount', 'Transaction Count'] st.dataframe(category_totals) # Show sample transactions st.subheader("Sample Transactions") st.dataframe(df.head()) def main(): st.set_page_config( page_title="AI Financial Coach with Google ADK", layout="wide", initial_sidebar_state="expanded" ) # Sidebar with API key info and CSV template with st.sidebar: st.title("🔑 Setup & Templates") st.info("📝 Please ensure you have your Gemini API key in the .env file:\n```\nGOOGLE_API_KEY=your_api_key_here\n```") st.caption("This application uses Google's ADK (Agent Development Kit) and Gemini AI to provide personalized financial advice.") st.divider() # Add CSV template download st.subheader("📊 CSV Template") st.markdown(""" Download the template CSV file with the required format: - Date (YYYY-MM-DD) - Category - Amount (numeric) """) # Create sample CSV content sample_csv = """Date,Category,Amount 2024-01-01,Housing,1200.00 2024-01-02,Food,150.50 2024-01-03,Transportation,45.00""" st.download_button( label="📥 Download CSV Template", data=sample_csv, file_name="expense_template.csv", mime="text/csv" ) if not GEMINI_API_KEY: st.error("🔑 GOOGLE_API_KEY not found in environment variables. Please add it to your .env file.") return # Main content st.title("📊 AI Financial Coach with Google ADK") st.caption("Powered by Google's Agent Development Kit (ADK) and Gemini AI") st.info("This tool analyzes your financial data and provides tailored recommendations for budgeting, savings, and debt management using multiple specialized AI agents.") st.divider() # Create tabs for different sections input_tab, about_tab = st.tabs(["💼 Financial Information", "ℹ️ About"]) with input_tab: st.header("Enter Your Financial Information") st.caption("All data is processed locally and not stored anywhere.") # Income and Dependants section in a container with st.container(): st.subheader("💰 Income & Household") income_col, dependants_col = st.columns([2, 1]) with income_col: monthly_income = st.number_input( "Monthly Income ($)", min_value=0.0, step=100.0, value=3000.0, key="income", help="Enter your total monthly income after taxes" ) with dependants_col: dependants = st.number_input( "Number of Dependants", min_value=0, step=1, value=0, key="dependants", help="Include all dependants in your household" ) st.divider() # Expenses section with st.container(): st.subheader("💳 Expenses") expense_option = st.radio( "How would you like to enter your expenses?", ("📤 Upload CSV Transactions", "✍️ Enter Manually"), key="expense_option", horizontal=True ) transaction_file = None manual_expenses = {} use_manual_expenses = False transactions_df = None if expense_option == "📤 Upload CSV Transactions": col1, col2 = st.columns([2, 1]) with col1: st.markdown(""" #### Upload your transaction data Your CSV file should have these columns: - 📅 Date (YYYY-MM-DD) - 📝 Category - 💲 Amount """) transaction_file = st.file_uploader( "Choose your CSV file", type=["csv"], key="transaction_file", help="Upload a CSV file containing your transactions" ) if transaction_file is not None: # Validate CSV format is_valid, message = validate_csv_format(transaction_file) if is_valid: try: # Parse CSV content transaction_file.seek(0) file_content = transaction_file.read() parsed_data = parse_csv_transactions(file_content) # Create DataFrame transactions_df = pd.DataFrame(parsed_data['transactions']) # Display preview display_csv_preview(transactions_df) st.success("✅ Transaction file uploaded and validated successfully!") except Exception as e: st.error(f"❌ Error processing CSV file: {str(e)}") transactions_df = None else: st.error(message) transactions_df = None else: use_manual_expenses = True st.markdown("#### Enter your monthly expenses by category") # Define expense categories with emojis categories = [ ("🏠 Housing", "Housing"), ("🔌 Utilities", "Utilities"), ("🍽️ Food", "Food"), ("🚗 Transportation", "Transportation"), ("🏥 Healthcare", "Healthcare"),
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
true
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/main.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/main.py
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel from agents.coordinator_agent import coordinator_agent from agno.agent import RunResponse from dotenv import load_dotenv # Load environment variables load_dotenv() # Initialize FastAPI app app = FastAPI() # Configure CORS to allow requests from your frontend app.add_middleware( CORSMiddleware, allow_origins=["*"], # To be replaced with the frontend's origin in production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Define the request body model class AnalysisRequest(BaseModel): video_url: str # Define the entry point @app.get("/") async def root(): return {"message": "Welcome to the video analysis API!"} # Define the analysis endpoint @app.post("/analyze") async def analyze(request: AnalysisRequest): video_url = request.video_url prompt = f"Analyze the following video: {video_url}" response: RunResponse = coordinator_agent.run(prompt) # Assuming response.content is a Pydantic model or a dictionary json_compatible_response = jsonable_encoder(response.content) return JSONResponse(content=json_compatible_response)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/feedback_agent.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/feedback_agent.py
from agno.agent import Agent from agno.models.together import Together from dotenv import load_dotenv import os load_dotenv() # Define the content analysis agent feedback_agent = Agent( name="feedback-agent", model=Together( id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY") ), description=""" You are a feedback agent that evaluates presentation based on the analysis results from all agents. You will provide feedback on the overall effectiveness of the presentation. """, instructions=[ "You are a public speaking coach that evaluates a speaker's performance based on a detailed scoring rubric.", "You will be provided with analysis results from the facial expression agent, voice analysis agent, and content analysis agent.", "You will be given a criteria to evaluate the performance of the speaker based on the analysis results.", "Your task is to evaluate the speaker on the following 5 criteria, scoring each from 1 (Poor) to 5 (Excellent):", "1. **Content & Organization** - Evaluate how logically structured and well-organized the speech content is.", "2. **Delivery & Vocal Quality** - Assess clarity, articulation, vocal variety, and use of filler words.", "3. **Body Language & Eye Contact** - Consider posture, gestures, and level of eye contact.", "4. **Audience Engagement** - Evaluate enthusiasm and ability to hold the audience's attention.", "5. **Language & Clarity** - Check for grammar, clarity, appropriateness, and impact of language.", "You will then provide a summary of the speaker's strengths and areas for improvement based on the rubric.", "Important: You MUST directly address the speaker while providing constructive feedback.", "Provide your response in the following strict JSON format:", "{", '"scores": {', ' "content_organization": [1-5],', ' "delivery_vocal_quality": [1-5],', ' "body_language_eye_contact": [1-5],', ' "audience_engagement": [1-5],', ' "language_clarity": [1-5]', '},', '"total_score": [sum of all scores from 5 to 25],', '"interpretation": "[One of: \'Needs significant improvement\', \'Developing skills\', \'Competent speaker\', \'Proficient speaker\', \'Outstanding speaker\']",', '"feedback_summary": "[Concise feedback summarizing the speaker\'s strengths and areas for improvement based on rubric.]"', "}", "DO NOT include anything outside the JSON response.", "Ensure all keys and values are properly quoted and formatted.", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # # Example usage # if __name__ == "__main__": # # Sample transcript from the Voice Analysis Agent # transcript = ( # "So, um, I was thinking that, like, we could actually start the project soon. " # "You know, it's basically ready, and, uh, we just need to finalize some details." # ) # prompt = f"Analyze the following transcript:\n\n{transcript}" # content_analysis_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = content_analysis_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/coordinator_agent.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/coordinator_agent.py
from agno.team.team import Team from agno.agent import Agent, RunResponse from agno.models.together import Together from agents.facial_expression_agent import facial_expression_agent from agents.voice_analysis_agent import voice_analysis_agent from agents.content_analysis_agent import content_analysis_agent from agents.feedback_agent import feedback_agent import os from pydantic import BaseModel, Field # Structured response class CoordinatorResponse(BaseModel): facial_expression_response: str = Field(..., description="Response from facial expression agent") voice_analysis_response: str = Field(..., description="Response from voice analysis agent") content_analysis_response: str = Field(..., description="Response from content analysis agent") feedback_response: str = Field(..., description="Response from feedback agent") strengths: list[str] = Field(..., description="List of speaker's strengths") weaknesses: list[str] = Field(..., description="List of speaker's weaknesses") suggestions: list[str] = Field(..., description="List of suggestions for speaker to improve") # Initialize a team of agents coordinator_agent = Team( name="coordinator-agent", mode="coordinate", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), members=[facial_expression_agent, voice_analysis_agent, content_analysis_agent, feedback_agent], description="You are a public speaking coach who helps individuals improve their presentation skills through feedback and analysis.", instructions=[ "You will be provided with a video file of a person speaking in a public setting.", "You will analyze the speaker's facial expressions, voice modulation, and content delivery to provide constructive feedback.", "Ask the facial expression agent to analyze the video file to detect emotions and engagement.", "Ask the voice analysis agent to analyze the audio file to detect speech rate, pitch variation, and volume consistency.", "Ask the content analysis agent to analyze the transcript given by voice analysis agent for structure, clarity, and filler words.", "Ask the feedback agent to evaluate the analysis results from the facial expression agent, voice analysis agent, and content analysis agent to provide feedback on the overall effectiveness of the presentation, highlighting strengths and areas for improvement.", "Your response MUST include the exact responses from the facial expression agent, voice analysis agent, content analysis agent, and feedback agent.", "Additionally, your response MUST provide lists of the speaker's strengths, weaknesses, and suggestions for improvement based on all the responses and feedback provided by the feedback agent.", "Important: You MUST directly address the speaker while providing strengths, weaknesses, and suggestions for improvement in a clear and constructive manner.", "The response MUST be in the following strict JSON format:", "{", '"facial_expression_response": [facial_expression_agent_response],', '"voice_analysis_response": [voice_analysis_agent_response],', '"content_analysis_response": [content_analysis_agent_response],', '"feedback_response": [feedback_agent_response]', '"strengths": [speaker_strengths_list],', '"weaknesses": [speaker_weaknesses_list],', '"suggestions": [suggestions_for_improvement_list]', "}", "The response MUST be in strict JSON format with keys and values in double quotes.", "The values in the JSON response MUST NOT be null or empty.", "The final response MUST not include any other text or anything else other than the JSON response.", "The final response MUST not include any backslashes in the JSON response.", "The final response MUST be a valid JSON object and MUST not have any unterminated strings in the JSON response." ], add_datetime_to_instructions=True, add_member_tools_to_system_message=False, # This can be tried to make the agent more consistently get the transfer tool call correct enable_agentic_context=True, # Allow the agent to maintain a shared context and send that to members. share_member_interactions=True, # Share all member responses with subsequent member requests. show_members_responses=True, response_model=CoordinatorResponse, use_json_mode=True, markdown=True, show_tool_calls=True, debug_mode=True ) # # Example usage # video = "../../videos/my_video.mp4" # prompt = f"Analyze facial expressions, voice modulation, and content delivery in the following video: {video} and provide constructive feedback." # coordinator_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = coordinator_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/voice_analysis_agent.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/voice_analysis_agent.py
from agno.agent import Agent, RunResponse from agno.agent import Agent from agno.models.together import Together from agents.tools.voice_analysis_tool import analyze_voice_attributes as voice_analysis_tool from agno.utils.pprint import pprint_run_response from dotenv import load_dotenv import os load_dotenv() # Define the voice analysis agent voice_analysis_agent = Agent( name="voice-analysis-agent", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), tools=[voice_analysis_tool], description=""" You are a voice analysis agent that evaluates vocal attributes like clarity, intonation, and pace. You will return the transcribed text, speech rate, pitch variation, and volume consistency. """, instructions=[ "You will be provided with an audio file of a person speaking.", "Your task is to analyze the vocal attributes in the audio to detect speech rate, pitch variation, and volume consistency.", "The response MUST be in the following JSON format:", "{", '"transcription": [transcription]', '"speech_rate_wpm": [speech_rate_wpm],', '"pitch_variation": [pitch_variation],', '"volume_consistency": [volume_consistency]', "}", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # audio = "../../videos/my_video.mp4" # prompt = f"Analyze vocal attributes in the audio file to detect speech rate, pitch variation, and volume consistency in the following audio: {audio}" # voice_analysis_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = voice_analysis_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/content_analysis_agent.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/content_analysis_agent.py
from agno.agent import Agent from agno.models.together import Together from dotenv import load_dotenv import os load_dotenv() # Define the content analysis agent content_analysis_agent = Agent( name="content-analysis-agent", model=Together( id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY") ), description=""" You are a content analysis agent that evaluates transcribed speech for structure, clarity, and filler words. You will return grammar corrections, identified filler words, and suggestions for content improvement. """, instructions=[ "You will be provided with a transcript of spoken content.", "Your task is to analyze the transcript and identify:", "- Grammar and syntax corrections.", "- Filler words and their frequency.", "- Suggestions for improving clarity and structure.", "The response MUST be in the following JSON format:", "{", '"grammar_corrections": [list of corrections],', '"filler_words": { "word": count, ... },', '"suggestions": [list of suggestions]', "}", "Ensure the response is in proper JSON format with keys and values in double quotes.", "Do not include any additional text outside the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # # Example usage # if __name__ == "__main__": # # Sample transcript from the Voice Analysis Agent # transcript = ( # "So, um, I was thinking that, like, we could actually start the project soon. " # "You know, it's basically ready, and, uh, we just need to finalize some details." # ) # prompt = f"Analyze the following transcript:\n\n{transcript}" # content_analysis_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = content_analysis_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/facial_expression_agent.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/facial_expression_agent.py
from agno.agent import Agent, RunResponse from agno.models.together import Together from agents.tools.facial_expression_tool import analyze_facial_expressions as facial_expression_tool from agno.utils.pprint import pprint_run_response from dotenv import load_dotenv import os load_dotenv() # Define the facial expression agent facial_expression_agent = Agent( name="facial-expression-agent", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), tools=[facial_expression_tool], description= ''' You are a facial expression agent that will analyze facial expressions in videos to detect emotions and engagement. You will return the emotion timeline and engagement metrics. ''', instructions=[ "You will be provided with a video file of a person speaking in a public setting.", "Your task is to analyze the facial expressions in the video to detect emotions and engagement.", "You will analyze the video frame by frame to detect and classify facial expressions such as happiness, sadness, anger, surprise, and neutrality.", "You will also analyze the engagement metrics such as eye contact count and smile count", "The response MUST be in the following JSON format:", "{", '"emotion_timeline": [emotion_timeline]', "engagement_metrics: {", '"eye_contact_frequency": [eye contact_frequency]', '"smile_frequency": [smile_frequency]', "}", "}", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response.", "The final response MUST not include any backslashes in the JSON response.", "The final response MUST be a valid JSON object and MUST not have any unterminated strings in the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # video = "../../videos/my_video.mp4" # prompt = f"Analyze facial expressions in the video file to detect emotions and engagement in the following video: {video}" # facial_expression_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = facial_expression_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/facial_expression_tool.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/facial_expression_tool.py
import cv2 import numpy as np import mediapipe as mp from deepface import DeepFace from agno.tools import tool import json def log_before_call(fc): """Pre-hook function that runs before the tool execution""" print(f"About to call function with arguments: {fc.arguments}") def log_after_call(fc): """Post-hook function that runs after the tool execution""" print(f"Function call completed with result: {fc.result}") @tool( name="analyze_facial_expressions", # Custom name for the tool (otherwise the function name is used) description="Analyzes facial expressions to detect emotions and engagement.", # Custom description (otherwise the function docstring is used) show_result=True, # Show result after function call stop_after_tool_call=True, # Return the result immediately after the tool call and stop the agent pre_hook=log_before_call, # Hook to run before execution post_hook=log_after_call, # Hook to run after execution cache_results=False, # Enable caching of results cache_dir="/tmp/agno_cache", # Custom cache directory cache_ttl=3600 # Cache TTL in seconds (1 hour) ) def analyze_facial_expressions(video_path: str) -> dict: """ Analyzes facial expressions in a video to detect emotions and engagement. Args: video_path: The path to the video file. Returns: A dictionary containing the emotion timeline and engagement metrics. """ mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh(static_image_mode=False, max_num_faces=1) cap = cv2.VideoCapture(video_path) emotion_timeline = [] eye_contact_count = 0 smile_count = 0 frame_count = 0 fps = cap.get(cv2.CAP_PROP_FPS) # Process every nth frame for performance optimization frame_interval = 5 while cap.isOpened(): ret, frame = cap.read() if not ret: break frame_count += 1 if frame_count % frame_interval != 0: continue # Resize frame for faster processing frame = cv2.resize(frame, (640, 480)) rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = face_mesh.process(rgb_frame) if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: # Extract landmarks landmarks = face_landmarks.landmark # Convert landmarks to pixel coordinates h, w, _ = frame.shape landmark_coords = [(int(lm.x * w), int(lm.y * h)) for lm in landmarks] # Emotion Detection using DeepFace & Smile Detection try: analysis = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False) emotion = analysis[0]['dominant_emotion'] if emotion == "happy": smile_count += 1 timestamp = frame_count / fps # convert timestamp into seconds timestamp = round(timestamp, 2) emotion_timeline.append({"timestamp": timestamp, "emotion": emotion}) except Exception as e: print(f"Error analyzing frame: {e}") continue # Engagement Metric: Eye contact estimation # Using eye landmarks: 159 (left eye upper lid), 145 (left eye lower lid), 386 (right eye upper lid), 374 (right eye lower lid) left_eye_upper_lid = landmark_coords[159] left_eye_lower_lid = landmark_coords[145] right_eye_upper_lid = landmark_coords[386] right_eye_lower_lid = landmark_coords[374] left_eye_opening = np.linalg.norm(np.array(left_eye_upper_lid) - np.array(left_eye_lower_lid)) right_eye_opening = np.linalg.norm(np.array(right_eye_upper_lid) - np.array(right_eye_lower_lid)) eye_opening_avg = (left_eye_opening + right_eye_opening) / 2 # Simple heuristic: if eyes are wide open, assume eye contact if eye_opening_avg > 5: # Threshold adjustment through experimentation eye_contact_count += 1 cap.release() face_mesh.close() total_processed_frames = frame_count // frame_interval if total_processed_frames == 0: total_processed_frames = 1 # Avoid division by zero return json.dumps({ "emotion_timeline": emotion_timeline, "engagement_metrics": { "eye_contact_frequency": eye_contact_count / total_processed_frames, "smile_frequency": smile_count / total_processed_frames } })
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/voice_analysis_tool.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/voice_analysis_tool.py
import os import json import tempfile import numpy as np import librosa from moviepy import VideoFileClip from faster_whisper import WhisperModel from agno.tools import tool from dotenv import load_dotenv load_dotenv() def extract_audio_from_video(video_path: str, output_audio_path: str) -> str: """ Extracts audio from a video file and saves it as an audio file. Args: video_path: Path to the input video file. output_audio_path: Path to save the extracted audio file. Returns: Path to the extracted audio file. """ video_clip = VideoFileClip(video_path) audio_clip = video_clip.audio audio_clip.write_audiofile(output_audio_path) audio_clip.close() video_clip.close() return output_audio_path def load_whisper_model(): try: model = WhisperModel("small", device="cpu", compute_type="int8") return model except Exception as e: print(f"Error loading Whisper model: {e}") return None def transcribe_audio(audio_file): """ Transcribe the audio file using faster-whisper. Returns: str: Transcribed text or error/fallback message. """ if not audio_file or not os.path.exists(audio_file): return "No audio file exists at the specified path." model = load_whisper_model() if not model: return "Model failed to load. Please check system resources or model path." try: print("Model loaded successfully. Transcribing audio...") segments, _ = model.transcribe(audio_file) full_text = " ".join(segment.text for segment in segments) return full_text.strip() if full_text else "I couldn't understand the audio. Please try again." except Exception as e: print(f"Error transcribing audio with faster-whisper: {e}") return "I'm having trouble transcribing your audio. Please try again or speak more clearly." def log_before_call(fc): """Pre-hook function that runs before the tool execution""" print(f"About to call function with arguments: {fc.arguments}") def log_after_call(fc): """Post-hook function that runs after the tool execution""" print(f"Function call completed with result: {fc.result}") @tool( name="analyze_voice_attributes", # Custom name for the tool (otherwise the function name is used) description="Analyzes vocal attributes like clarity, intonation, and pace.", # Custom description (otherwise the function docstring is used) show_result=True, # Show result after function call stop_after_tool_call=True, # Return the result immediately after the tool call and stop the agent pre_hook=log_before_call, # Hook to run before execution post_hook=log_after_call, # Hook to run after execution cache_results=False, # Enable caching of results cache_dir="/tmp/agno_cache", # Custom cache directory cache_ttl=3600 # Cache TTL in seconds (1 hour) ) def analyze_voice_attributes(file_path: str) -> dict: """ Analyzes vocal attributes in an audio file. Args: audio_path: The path to the audio file. Returns: A dictionary containing the transcribed text, speech rate, pitch variation, and volume consistency. """ # Determine file extension _, ext = os.path.splitext(file_path) ext = ext.lower() # If the file is a video, extract audio if ext in ['.mp4']: with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_audio_file: audio_path = extract_audio_from_video(file_path, temp_audio_file.name) else: audio_path = file_path # Transcribe audio transcription = transcribe_audio(audio_path) # Proceed with analysis using the audio_path # Load audio y, sr = librosa.load(audio_path, sr=16000) words = transcription.split() # Calculate speech rate duration = librosa.get_duration(y=y, sr=sr) speech_rate = len(words) / (duration / 60.0) # words per minute # Pitch variation pitches, magnitudes = librosa.piptrack(y=y, sr=sr) pitch_values = pitches[magnitudes > np.median(magnitudes)] pitch_variation = np.std(pitch_values) if pitch_values.size > 0 else 0 # Volume consistency rms = librosa.feature.rms(y=y)[0] volume_consistency = np.std(rms) # Clean up temporary audio file if created if ext in ['.mp4']: os.remove(audio_path) return json.dumps({ "transcription": transcription, "speech_rate_wpm": str(round(speech_rate, 2)), "pitch_variation": str(round(pitch_variation, 2)), "volume_consistency": str(round(volume_consistency, 4)) })
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/sidebar.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/sidebar.py
# Sidebar with About section import streamlit as st def render_sidebar(): st.sidebar.header("About") st.sidebar.info( """ **AI Speech Trainer** helps users improve their public speaking skills through:\ 📽️ Video Analysis\ 🗣️ Voice Analysis\ 📊 Content Analysis & Feedback\ - Upload your video to receive a detailed feedback. - Improve your public speaking skills with AI-powered analysis. - Get personalized suggestions to enhance your performance. """ )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/Home.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/Home.py
import streamlit as st import requests import tempfile import os import json import numpy as np from page_congif import render_page_config render_page_config() # Initialize session state variables if "begin" not in st.session_state: st.session_state.begin = False if "video_path" not in st.session_state: st.session_state.video_path = None if "upload_file" not in st.session_state: st.session_state.upload_file = False if "response" not in st.session_state: st.session_state.response = None if "facial_expression_response" not in st.session_state: st.session_state.facial_expression_response = None if "voice_analysis_response" not in st.session_state: st.session_state.voice_analysis_response = None if "content_analysis_response" not in st.session_state: st.session_state.content_analysis_response = None if "feedback_response" not in st.session_state: st.session_state.feedback_response = None def clear_session_response(): st.session_state.response = None st.session_state.facial_expression_response = None st.session_state.voice_analysis_response = None st.session_state.content_analysis_response = None st.session_state.feedback_response = None # Create two columns with a 70:30 width ratio col1, col2 = st.columns([0.7, 0.3]) # Left column: Video area and buttons with col1: spacer1, btn_col = st.columns([0.8, 0.2]) if st.session_state.begin: with spacer1: st.markdown("<h4>📽️ Video</h4>", unsafe_allow_html=True) with btn_col: if st.button("📤 Upload Video"): if st.session_state.video_path: os.remove(st.session_state.video_path) st.session_state.video_path = None clear_session_response() st.session_state.upload_file = True st.rerun() # Force rerun to fully reset uploader if st.session_state.get("upload_file"): uploaded_file = st.file_uploader("📤 Upload Video", type=["mp4"]) if uploaded_file is not None: temp_dir = tempfile.gettempdir() # Use a random name to avoid reuse unique_name = f"{int(np.random.rand()*1e8)}_{uploaded_file.name}" file_path = os.path.join(temp_dir, unique_name) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(uploaded_file.read()) st.session_state.video_path = file_path st.session_state.upload_file = False st.rerun() # elif not st.session_state.get("video_path"): if not st.session_state.begin: st.success(""" **Welcome to AI Speech Trainer!** Your ultimate companion to help improve your public speaking skills. """) st.info(""" 🚀 To get started: \n\t1. Record a video of yourself practicing a speech or presentation - use any video recording app. \n\t2. Upload the recorded video. \n\t3. Analyze the video to get personalized feedback. """) if st.button("👉 Let's begin!"): st.session_state.begin = True st.rerun() if st.session_state.video_path: st.video(st.session_state.video_path, autoplay=False) if not st.session_state.response: if st.button("▶️ Analyze Video"): with st.spinner("Analyzing video..."): st.warning("⚠️ This process may take some time, so please be patient and wait for the analysis to complete.") API_URL = "http://localhost:8000/analyze" response = requests.post(API_URL, json={"video_url": st.session_state.video_path}) if response.status_code == 200: st.success("Video analysis completed successfully.") response = response.json() st.session_state.response = response st.session_state.facial_expression_response = response.get("facial_expression_response") st.session_state.voice_analysis_response = response.get("voice_analysis_response") st.session_state.content_analysis_response = response.get("content_analysis_response") st.session_state.feedback_response = response.get("feedback_response") st.rerun() else: st.error("🚨 Error during video analysis. Please try again.") # Right column: Transcript and feedback with col2: st.markdown("<h4>📝 Transcript</h4>", unsafe_allow_html=True) transcript_text = "Your transcript will be displayed here." if st.session_state.response: voice_analysis_response = st.session_state.voice_analysis_response transcript = json.loads(voice_analysis_response).get("transcription") else: transcript = None st.markdown( f""" <div style="background-color:#f0f2f6; padding: 1.5rem; border-radius: 10px; border: 1px solid #ccc; font-family: 'Segoe UI', sans-serif; line-height: 1.6; color: #333; height: 400px; max-height: 400px; overflow-y: auto;"> {transcript if transcript else transcript_text} </div> <br> """, unsafe_allow_html=True ) if st.button("📝 Get Feedback"): st.switch_page("pages/1 - Feedback.py")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/page_congif.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/page_congif.py
import streamlit as st from sidebar import render_sidebar def render_page_config(): # Set page configuration st.set_page_config( page_icon="🎙️", page_title="AI Speech Trainer", initial_sidebar_state="auto", layout="wide") # Load external CSS with open("style.css") as f: st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) # Sidebar render_sidebar() # Main title with an icon st.markdown( """ <div class="custom-header"'> <span>🗣️ AI Speech Trainer</span><br> <span>Your personal coach for public speaking</span> </div> """, unsafe_allow_html=True ) # Horizontal line st.markdown("<hr class='custom-hr'>", unsafe_allow_html=True)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/pages/1 - Feedback.py
advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/pages/1 - Feedback.py
import streamlit as st import plotly.graph_objects as go import json from page_congif import render_page_config render_page_config() # Get feedback response from session state if st.session_state.feedback_response: feedback_response = json.loads(st.session_state.feedback_response) feedback_scores = feedback_response.get("scores") # Evaluation scores based on the public speaking rubric scores = { "Content & Organization": feedback_scores.get("content_organization"), "Delivery & Vocal Quality": feedback_scores.get("delivery_vocal_quality"), "Body Language & Eye Contact": feedback_scores.get("body_language_eye_contact"), "Audience Engagement": feedback_scores.get("audience_engagement"), "Language & Clarity": feedback_scores.get("language_clarity") } total_score = feedback_response.get("total_score") interpretation = feedback_response.get("interpretation") feedback_summary = feedback_response.get("feedback_summary") else: st.warning("No feedback available! Please upload a video and analyze it first.") scores = { "Content & Organization": 0, "Delivery & Vocal Quality": 0, "Body Language & Eye Contact": 0, "Audience Engagement": 0, "Language & Clarity": 0 } total_score = 0 interpretation = "" feedback_summary = "" # Calculate average score average_score = sum(scores.values()) / len(scores) # Determine strengths, weaknesses, and suggestions for improvement if st.session_state.response: strengths = st.session_state.response.get("strengths") weaknesses = st.session_state.response.get("weaknesses") suggestions = st.session_state.response.get("suggestions") else: strengths = [] weaknesses = [] suggestions = [] # Create three columns with equal width col1, col2, col3 = st.columns([0.3, 0.4, 0.3]) # Left Column: Evaluation Summary with col1: st.subheader("🧾 Evaluation Summary") st.markdown("<br>", unsafe_allow_html=True) for criterion, score in scores.items(): label_col, progress_col, score_col = st.columns([2, 3, 1]) # Adjust the ratio as needed with label_col: st.markdown(f"**{criterion}**") with progress_col: st.progress(score / 5) with score_col: st.markdown(f"<span><b>{score}/5</b></span>", unsafe_allow_html=True) st.markdown("<br>", unsafe_allow_html=True) # Display total score st.markdown(f"#### 🏆 Total Score: {total_score} / 25") # Display average score st.markdown(f"#### 🎯 Average Score: {average_score:.2f} / 5") st.markdown("""---""") st.markdown("##### 🗣️ Feedback Summary:") # Display interpretation st.markdown(f"📝 **Overall Assessment**: {interpretation}") # Display feedback summary st.info(f"{feedback_summary}") # Middle Column: Strengths, Weaknesses, and Suggestions with col2: # Display strengths st.markdown("##### 🦾 Strengths:") strengths_text = '\n'.join(f"- {item}" for item in strengths) st.success(strengths_text) # Display weaknesses st.markdown("##### ⚠️ Weaknesses:") weaknesses_text = '\n'.join(f"- {item}" for item in weaknesses) st.error(weaknesses_text) # Display suggestions st.markdown("##### 💡 Suggestions for Improvement:") suggestions_text = '\n'.join(f"- {item}" for item in suggestions) st.warning(suggestions_text) # Right Column: Performance Chart with col3: st.subheader("📊 Performance Chart") # Radar Chart radar_fig = go.Figure() radar_fig.add_trace(go.Scatterpolar( r=list(scores.values()), theta=list(scores.keys()), fill='toself', name='Scores' )) radar_fig.update_layout( polar=dict( radialaxis=dict(visible=True, range=[0, 5]) ), showlegend=False, margin=dict(t=50, b=50, l=50, r=50), # Reduced margins width=350, height=350 ) st.plotly_chart(radar_fig, use_container_width=True) st.markdown("""---""")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_Self-Evolving_agent/ai_Self-Evolving_agent.py
advanced_ai_agents/multi_agent_apps/ai_Self-Evolving_agent/ai_Self-Evolving_agent.py
import os from dotenv import load_dotenv from evoagentx.models import OpenAILLMConfig, OpenAILLM, LiteLLMConfig, LiteLLM from evoagentx.workflow import WorkFlowGenerator, WorkFlowGraph, WorkFlow from evoagentx.agents import AgentManager from evoagentx.actions.code_extraction import CodeExtraction from evoagentx.actions.code_verification import CodeVerification from evoagentx.core.module_utils import extract_code_blocks load_dotenv() # Loads environment variables from .env file OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY") def main(): # LLM configuration openai_config = OpenAILLMConfig(model="gpt-4o-mini", openai_key=OPENAI_API_KEY, stream=True, output_response=True, max_tokens=16000) # Initialize the language model llm = OpenAILLM(config=openai_config) goal = "Generate html code for the Tetris game that can be played in the browser." target_directory = "examples/output/tetris_game" wf_generator = WorkFlowGenerator(llm=llm) workflow_graph: WorkFlowGraph = wf_generator.generate_workflow(goal=goal) # [optional] display workflow workflow_graph.display() # [optional] save workflow # workflow_graph.save_module(f"{target_directory}/workflow_demo_4o_mini.json") #[optional] load saved workflow # workflow_graph: WorkFlowGraph = WorkFlowGraph.from_file(f"{target_directory}/workflow_demo_4o_mini.json") agent_manager = AgentManager() agent_manager.add_agents_from_workflow(workflow_graph, llm_config=openai_config) workflow = WorkFlow(graph=workflow_graph, agent_manager=agent_manager, llm=llm) output = workflow.execute() # verfiy the code verification_llm_config = LiteLLMConfig(model="anthropic/claude-3-7-sonnet-20250219", anthropic_key=ANTHROPIC_API_KEY, stream=True, output_response=True, max_tokens=20000) verification_llm = LiteLLM(config=verification_llm_config) code_verifier = CodeVerification() output = code_verifier.execute( llm = verification_llm, inputs={ "requirements": goal, "code": output } ).verified_code # extract the code os.makedirs(target_directory, exist_ok=True) code_blocks = extract_code_blocks(output) if len(code_blocks) == 1: file_path = os.path.join(target_directory, "index.html") with open(file_path, "w") as f: f.write(code_blocks[0]) print(f"You can open this HTML file in a browser to play the Tetris game: {file_path}") return code_extractor = CodeExtraction() results = code_extractor.execute( llm=llm, inputs={ "code_string": output, "target_directory": target_directory, } ) print(f"Extracted {len(results.extracted_files)} files:") for filename, path in results.extracted_files.items(): print(f" - {filename}: {path}") if results.main_file: print(f"\nMain file: {results.main_file}") file_type = os.path.splitext(results.main_file)[1].lower() if file_type == '.html': print(f"You can open this HTML file in a browser to play the Tetris game") else: print(f"This is the main entry point for your application") if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/bootstrap_demo.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/bootstrap_demo.py
import os import sys import tempfile import requests import zipfile from tqdm import tqdm DEMO_URL = "https://github.com/arun477/beifong/releases/download/v1.2.0/demo_content.zip" TARGET_DIRS = ["databases", "podcasts"] def ensure_empty(dir_path): """check if directory is empty (or create it). exit if not empty.""" if os.path.exists(dir_path): if os.listdir(dir_path): print(f"✗ '{dir_path}' is not empty. aborting.") sys.exit(1) else: os.makedirs(dir_path, exist_ok=True) def download_file(url, dest_path): """stream-download a file from url to dest_path with progress bar.""" print("↓ downloading demo content...") response = requests.get(url, stream=True) response.raise_for_status() total_size = int(response.headers.get('content-length', 0)) block_size = 8192 with open(dest_path, "wb") as f: with tqdm(total=total_size, unit='B', unit_scale=True, desc="Download Progress") as pbar: for chunk in response.iter_content(chunk_size=block_size): if chunk: f.write(chunk) pbar.update(len(chunk)) def extract_zip(zip_path, extract_to): """extract zip file into extract_to (project root) with progress bar.""" print("✂ extracting demo content...") with zipfile.ZipFile(zip_path, "r") as zip_ref: total_files = len(zip_ref.infolist()) with tqdm(total=total_files, desc="Extraction Progress") as pbar: for file in zip_ref.infolist(): zip_ref.extract(file, extract_to) pbar.update(1) def main(): print("populating demo folders…") for d in TARGET_DIRS: ensure_empty(d) with tempfile.TemporaryDirectory() as tmp: tmp_zip = os.path.join(tmp, "demo_content.zip") download_file(DEMO_URL, tmp_zip) extract_zip(tmp_zip, os.getcwd()) print("✓ demo folders populated successfully.") if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\n✗ Download cancelled by user.") sys.exit(1) except Exception as e: print(f"\n✗ Error: {e}") sys.exit(1)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/celery_worker.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/celery_worker.py
from services.celery_tasks import app worker_options = [ "worker", "--loglevel=INFO", "--concurrency=4", "--hostname=beifong_worker@%h", "--pool=threads", ] if __name__ == "__main__": print("Starting Beifong podcast agent workers...") app.worker_main(worker_options)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/main.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/main.py
from fastapi import FastAPI, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, StreamingResponse import uvicorn import os import aiofiles from contextlib import asynccontextmanager from routers import article_router, podcast_router, source_router, task_router, podcast_config_router, async_podcast_agent_router, social_media_router from services.db_init import init_databases from dotenv import load_dotenv load_dotenv() CLIENT_BUILD_PATH = os.environ.get( "CLIENT_BUILD_PATH", "../web/build", ) @asynccontextmanager async def lifespan(app: FastAPI): print("Starting up application...") os.makedirs("databases", exist_ok=True) os.makedirs("browsers", exist_ok=True) os.makedirs("podcasts/audio", exist_ok=True) os.makedirs("podcasts/images", exist_ok=True) os.makedirs("podcasts/recordings", exist_ok=True) await init_databases() if not os.path.exists(CLIENT_BUILD_PATH): print(f"WARNING: React client build path not found: {CLIENT_BUILD_PATH}") print("Application startup complete!") yield print("Shutting down application...") print("Shutdown complete") app = FastAPI(title="Beifong API", description="Beifong API", version="1.0.0", lifespan=lifespan) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(article_router.router, prefix="/api/articles", tags=["articles"]) app.include_router(source_router.router, prefix="/api/sources", tags=["sources"]) app.include_router(podcast_router.router, prefix="/api/podcasts", tags=["podcasts"]) app.include_router(task_router.router, prefix="/api/tasks", tags=["tasks"]) app.include_router(podcast_config_router.router, prefix="/api/podcast-configs", tags=["podcast-configs"]) app.include_router(async_podcast_agent_router.router, prefix="/api/podcast-agent", tags=["podcast-agent"]) app.include_router(social_media_router.router, prefix="/api/social-media", tags=["social-media"]) @app.get("/stream-audio/{filename}") async def stream_audio(filename: str, request: Request): audio_path = os.path.join("podcasts/audio", filename) if not os.path.exists(audio_path): return Response(status_code=404, content="Audio file not found") file_size = os.path.getsize(audio_path) range_header = request.headers.get("Range", "").strip() start = 0 end = file_size - 1 if range_header: try: range_data = range_header.replace("bytes=", "").split("-") start = int(range_data[0]) if range_data[0] else 0 end = int(range_data[1]) if len(range_data) > 1 and range_data[1] else file_size - 1 except ValueError: return Response(status_code=400, content="Invalid range header") end = min(end, file_size - 1) content_length = end - start + 1 headers = { "Accept-Ranges": "bytes", "Content-Range": f"bytes {start}-{end}/{file_size}", "Content-Length": str(content_length), "Content-Disposition": f"inline; filename={filename}", "Content-Type": "audio/wav", } async def file_streamer(): async with aiofiles.open(audio_path, "rb") as f: await f.seek(start) remaining = content_length chunk_size = 64 * 1024 while remaining > 0: chunk = await f.read(min(chunk_size, remaining)) if not chunk: break remaining -= len(chunk) yield chunk status_code = 206 if range_header else 200 return StreamingResponse(file_streamer(), status_code=status_code, headers=headers) @app.get("/stream-recording/{session_id}/{filename}") async def stream_recording(session_id: str, filename: str, request: Request): recording_path = os.path.join("podcasts/recordings", session_id, filename) if not os.path.exists(recording_path): return Response(status_code=404, content="Recording video not found") file_size = os.path.getsize(recording_path) range_header = request.headers.get("Range", "").strip() start = 0 end = file_size - 1 if range_header: try: range_data = range_header.replace("bytes=", "").split("-") start = int(range_data[0]) if range_data[0] else 0 end = int(range_data[1]) if len(range_data) > 1 and range_data[1] else file_size - 1 except ValueError: return Response(status_code=400, content="Invalid range header") end = min(end, file_size - 1) content_length = end - start + 1 headers = { "Accept-Ranges": "bytes", "Content-Range": f"bytes {start}-{end}/{file_size}", "Content-Length": str(content_length), "Content-Disposition": f"inline; filename={filename}", "Content-Type": "video/webm", } async def file_streamer(): async with aiofiles.open(recording_path, "rb") as f: await f.seek(start) remaining = content_length chunk_size = 64 * 1024 while remaining > 0: chunk = await f.read(min(chunk_size, remaining)) if not chunk: break remaining -= len(chunk) yield chunk status_code = 206 if range_header else 200 return StreamingResponse(file_streamer(), status_code=status_code, headers=headers) app.mount("/audio", StaticFiles(directory="podcasts/audio"), name="audio") app.mount("/server_static", StaticFiles(directory="static"), name="server_static") app.mount("/podcast_img", StaticFiles(directory="podcasts/images"), name="podcast_img") if os.path.exists(os.path.join(CLIENT_BUILD_PATH, "static")): app.mount("/static", StaticFiles(directory=os.path.join(CLIENT_BUILD_PATH, "static")), name="react_static") @app.get("/favicon.ico") async def favicon(): favicon_path = os.path.join(CLIENT_BUILD_PATH, "favicon.ico") if os.path.exists(favicon_path): return FileResponse(favicon_path) return {"detail": "Favicon not found"} @app.get("/manifest.json") async def manifest(): manifest_path = os.path.join(CLIENT_BUILD_PATH, "manifest.json") if os.path.exists(manifest_path): return FileResponse(manifest_path) return {"detail": "Manifest not found"} @app.get("/logo{rest_of_path:path}") async def logo(rest_of_path: str): logo_path = os.path.join(CLIENT_BUILD_PATH, f"logo{rest_of_path}") if os.path.exists(logo_path): return FileResponse(logo_path) return {"detail": "Logo not found"} @app.get("/{full_path:path}") async def serve_react(full_path: str, request: Request): if full_path.startswith("api/") or request.url.path.startswith("/api/"): return {"detail": "Not Found"} index_path = os.path.join(CLIENT_BUILD_PATH, "index.html") if os.path.exists(index_path): return FileResponse(index_path) else: return {"detail": "React client not found. Build the client or set the correct CLIENT_BUILD_PATH."} if __name__ == "__main__": port = int(os.environ.get("PORT", 7000)) uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False, timeout_keep_alive=120, timeout_graceful_shutdown=120)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/pack_demo.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/pack_demo.py
import os import zipfile SOURCE_DIRS = ["databases", "podcasts"] OUTPUT_ZIP = "demo_content.zip" def create_zip(source_dirs, output_zip): print("packing.....") """zip up each source directory into a single archive.""" with zipfile.ZipFile(output_zip, "w", zipfile.ZIP_DEFLATED) as z: for src in source_dirs: if not os.path.isdir(src): print(f"✗ source '{src}' not found, skipping.") continue for root, _, files in os.walk(src): for file in files: full_path = os.path.join(root, file) arcname = os.path.relpath(full_path, os.getcwd()) z.write(full_path, arcname) print(f"✓ created '{output_zip}' containing: {', '.join(source_dirs)}") if __name__ == "__main__": create_zip(SOURCE_DIRS, OUTPUT_ZIP)
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/__init__.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/__init__.py
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/scheduler.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/scheduler.py
import os import time import signal import subprocess from datetime import datetime import traceback from concurrent.futures import ThreadPoolExecutor from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.interval import IntervalTrigger from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from db.config import get_tasks_db_path from db.connection import db_connection from db.tasks import ( get_pending_tasks, update_task_last_run, update_task_execution, ) running = True MAX_WORKERS = 5 DEFAULT_TASK_TIMEOUT = 3600 def cleanup_stuck_tasks(): tasks_db_path = get_tasks_db_path() try: with db_connection(tasks_db_path) as conn: cursor = conn.cursor() cursor.execute( """ SELECT id FROM task_executions WHERE status = 'running' LIMIT 100 """ ) running_executions = [dict(row) for row in cursor.fetchall()] if running_executions: print(f"WARNING: Found {len(running_executions)} tasks stuck in 'running' state. Marking as failed.") for execution in running_executions: execution_id = execution["id"] error_message = "Task was interrupted by system shutdown or crash" cursor.execute( """ UPDATE task_executions SET end_time = ?, status = ?, error_message = ? WHERE id = ? """, (datetime.now().isoformat(), "failed", error_message, execution_id), ) print(f"INFO: Marked execution {execution_id} as failed") conn.commit() else: print("INFO: No stuck tasks found") except Exception as e: print(f"ERROR: Error cleaning up stuck tasks: {str(e)}") print(f"ERROR: {traceback.format_exc()}") def execute_task(task_id, command): tasks_db_path = get_tasks_db_path() with db_connection(tasks_db_path) as conn: conn.execute("BEGIN EXCLUSIVE TRANSACTION") try: cursor = conn.cursor() cursor.execute( """ SELECT 1 FROM task_executions WHERE task_id = ? AND status = 'running' LIMIT 1 """, (task_id,), ) is_running = cursor.fetchone() is not None if is_running: print(f"WARNING: Task {task_id} is already running, skipping this execution") conn.commit() return cursor.execute( """ INSERT INTO task_executions (task_id, start_time, status) VALUES (?, ?, ?) """, (task_id, datetime.now().isoformat(), "running"), ) execution_id = cursor.lastrowid conn.commit() if not execution_id: print(f"ERROR: Failed to create execution record for task {task_id}") return except Exception as e: conn.rollback() print(f"ERROR: Transaction error for task {task_id}: {str(e)}") return print(f"INFO: Starting task {task_id}: {command}") try: process = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) try: stdout, stderr = process.communicate(timeout=DEFAULT_TASK_TIMEOUT) if process.returncode == 0: status = "success" error_message = None print(f"INFO: Task {task_id} completed successfully") else: status = "failed" error_message = stderr if stderr else f"Process exited with code {process.returncode}" print(f"ERROR: Task {task_id} failed: {error_message}") except subprocess.TimeoutExpired: process.kill() stdout, stderr = process.communicate() status = "failed" error_message = f"Task timed out after {DEFAULT_TASK_TIMEOUT} seconds" print(f"ERROR: Task {task_id} timed out") output = f"STDOUT:\n{stdout}\n\nSTDERR:\n{stderr}" if stderr else stdout update_task_execution(tasks_db_path, execution_id, status, error_message, output) timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") update_task_last_run(tasks_db_path, task_id, timestamp) except Exception as e: print(f"ERROR: Error executing task {task_id}: {str(e)}") error_message = traceback.format_exc() update_task_execution(tasks_db_path, execution_id, "failed", error_message) timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") update_task_last_run(tasks_db_path, task_id, timestamp) def check_for_tasks(): tasks_db_path = get_tasks_db_path() try: print("DEBUG: Checking for pending tasks...") pending_tasks = get_pending_tasks(tasks_db_path) if not pending_tasks: print("DEBUG: No pending tasks found") return print(f"INFO: Found {len(pending_tasks)} pending tasks") with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: for task in pending_tasks: task_id = task["id"] command = task["command"] print(f"INFO: Scheduling task {task_id}: {task['name']} (Last run: {task['last_run']})") executor.submit(execute_task, task_id, command) except Exception as e: print(f"ERROR: Error in check_for_tasks: {str(e)}") print(f"ERROR: {traceback.format_exc()}") def check_missed_tasks(): tasks_db_path = get_tasks_db_path() try: print("INFO: Checking for missed tasks during downtime...") pending_tasks = get_pending_tasks(tasks_db_path) if pending_tasks: print(f"INFO: Found {len(pending_tasks)} tasks to run (including any missed during downtime)") else: print("INFO: No missed tasks found") except Exception as e: print(f"ERROR: Error checking for missed tasks: {str(e)}") def signal_handler(sig, frame): global running print("INFO: Shutdown signal received, stopping scheduler...") running = False def main(): global running signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) print("INFO: Starting task scheduler") tasks_db_path = get_tasks_db_path() cleanup_stuck_tasks() scheduler_dir = os.path.dirname(tasks_db_path) os.makedirs(scheduler_dir, exist_ok=True) scheduler_db_path = os.path.join(scheduler_dir, "scheduler.sqlite") jobstores = {"default": SQLAlchemyJobStore(url=f"sqlite:///{scheduler_db_path}")} scheduler = BackgroundScheduler(jobstores=jobstores, daemon=True) scheduler.add_job( check_for_tasks, IntervalTrigger(minutes=1), id="check_tasks", name="Check for pending tasks", replace_existing=True, ) scheduler.start() print("INFO: Scheduler started, checking for tasks every minute") check_for_tasks() check_missed_tasks() try: while running: time.sleep(1) except (KeyboardInterrupt, SystemExit): print("INFO: Scheduler interrupted") finally: scheduler.shutdown() print("INFO: Scheduler shutdown complete") if __name__ == "__main__": main()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/db_init.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/db_init.py
import os import sqlite3 import asyncio import time from contextlib import contextmanager from concurrent.futures import ThreadPoolExecutor from services.db_service import get_db_path @contextmanager def db_connection(db_path): conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA synchronous=NORMAL") conn.execute("PRAGMA cache_size=10000") conn.execute("PRAGMA temp_store=MEMORY") try: yield conn finally: conn.close() def init_sources_db(): start_time = time.time() db_path = get_db_path("sources_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS sources ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT, url TEXT, is_active BOOLEAN DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS categories ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS source_categories ( source_id INTEGER, category_id INTEGER, PRIMARY KEY (source_id, category_id), FOREIGN KEY (source_id) REFERENCES sources(id), FOREIGN KEY (category_id) REFERENCES categories(id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS source_feeds ( id INTEGER PRIMARY KEY AUTOINCREMENT, source_id INTEGER, feed_url TEXT UNIQUE, feed_type TEXT, is_active BOOLEAN DEFAULT 1, last_crawled TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (source_id) REFERENCES sources(id) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_source_feeds_source_id ON source_feeds(source_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_sources_is_active ON sources(is_active)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_source_feeds_is_active ON source_feeds(is_active)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_source_categories_source_id ON source_categories(source_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_source_categories_category_id ON source_categories(category_id)") conn.commit() elapsed = time.time() - start_time print(f"Sources database initialized in {elapsed:.3f}s") def init_tracking_db(): start_time = time.time() db_path = get_db_path("tracking_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS feed_tracking ( feed_id INTEGER PRIMARY KEY, source_id INTEGER, feed_url TEXT, last_processed TIMESTAMP, last_etag TEXT, last_modified TEXT, entry_hash TEXT ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS feed_entries ( id INTEGER PRIMARY KEY AUTOINCREMENT, feed_id INTEGER, source_id INTEGER, entry_id TEXT, title TEXT, link TEXT UNIQUE, published_date TIMESTAMP, content TEXT, summary TEXT, crawl_status TEXT DEFAULT 'pending', crawl_attempts INTEGER DEFAULT 0, processed_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(feed_id, entry_id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS crawled_articles ( id INTEGER PRIMARY KEY AUTOINCREMENT, entry_id INTEGER, source_id INTEGER, feed_id INTEGER, title TEXT, url TEXT UNIQUE, published_date TIMESTAMP, raw_content TEXT, content TEXT, summary TEXT, metadata TEXT, ai_status TEXT DEFAULT 'pending', ai_error TEXT DEFAULT NULL, ai_attempts INTEGER DEFAULT 0, crawled_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, processed BOOLEAN DEFAULT 0, embedding_status TEXT DEFAULT NULL, FOREIGN KEY (entry_id) REFERENCES feed_entries(id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS article_categories ( article_id INTEGER, category_name TEXT NOT NULL, PRIMARY KEY (article_id, category_name), FOREIGN KEY (article_id) REFERENCES crawled_articles(id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS article_embeddings ( id INTEGER PRIMARY KEY AUTOINCREMENT, article_id INTEGER NOT NULL, embedding BLOB NOT NULL, embedding_model TEXT NOT NULL, created_at TEXT NOT NULL, in_faiss_index INTEGER DEFAULT 0, FOREIGN KEY (article_id) REFERENCES crawled_articles(id) ) """) indexes = [ "CREATE INDEX IF NOT EXISTS idx_feed_entries_feed_id ON feed_entries(feed_id)", "CREATE INDEX IF NOT EXISTS idx_feed_entries_link ON feed_entries(link)", "CREATE INDEX IF NOT EXISTS idx_crawled_articles_url ON crawled_articles(url)", "CREATE INDEX IF NOT EXISTS idx_crawled_articles_entry_id ON crawled_articles(entry_id)", "CREATE INDEX IF NOT EXISTS idx_feed_entries_crawl_status ON feed_entries(crawl_status)", "CREATE INDEX IF NOT EXISTS idx_crawled_articles_processed ON crawled_articles(processed)", "CREATE INDEX IF NOT EXISTS idx_crawled_articles_ai_status ON crawled_articles(ai_status)", "CREATE INDEX IF NOT EXISTS idx_article_categories_article_id ON article_categories(article_id)", "CREATE INDEX IF NOT EXISTS idx_article_categories_category_name ON article_categories(category_name)", "CREATE INDEX IF NOT EXISTS idx_article_embeddings_article_id ON article_embeddings(article_id)", "CREATE INDEX IF NOT EXISTS idx_article_embeddings_in_faiss ON article_embeddings(in_faiss_index)", "CREATE INDEX IF NOT EXISTS idx_crawled_articles_embedding_status ON crawled_articles(embedding_status)", ] for index_sql in indexes: cursor.execute(index_sql) conn.commit() elapsed = time.time() - start_time print(f"Tracking database initialized in {elapsed:.3f}s") def init_podcasts_db(): start_time = time.time() db_path = get_db_path("podcasts_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS podcasts ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, date TEXT, content_json TEXT, audio_generated BOOLEAN DEFAULT 0, audio_path TEXT, banner_img_path TEXT, tts_engine TEXT DEFAULT 'elevenlabs', language_code TEXT DEFAULT 'en', sources_json TEXT, banner_images TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) indexes = [ "CREATE INDEX IF NOT EXISTS idx_podcasts_date ON podcasts(date)", "CREATE INDEX IF NOT EXISTS idx_podcasts_audio_generated ON podcasts(audio_generated)", "CREATE INDEX IF NOT EXISTS idx_podcasts_tts_engine ON podcasts(tts_engine)", "CREATE INDEX IF NOT EXISTS idx_podcasts_language_code ON podcasts(language_code)", ] for index_sql in indexes: cursor.execute(index_sql) conn.commit() elapsed = time.time() - start_time print(f"Podcasts database initialized in {elapsed:.3f}s") def init_tasks_db(): start_time = time.time() db_path = get_db_path("tasks_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, task_type TEXT, description TEXT, command TEXT NOT NULL, frequency INTEGER NOT NULL, frequency_unit TEXT NOT NULL, enabled BOOLEAN DEFAULT 1, last_run TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS task_executions ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, start_time TIMESTAMP NOT NULL, end_time TIMESTAMP, status TEXT NOT NULL, error_message TEXT, output TEXT, FOREIGN KEY (task_id) REFERENCES tasks(id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS podcast_configs ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT, prompt TEXT NOT NULL, time_range_hours INTEGER DEFAULT 24, limit_articles INTEGER DEFAULT 20, is_active BOOLEAN DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, tts_engine TEXT DEFAULT 'elevenlabs', language_code TEXT DEFAULT 'en', podcast_script_prompt TEXT, image_prompt TEXT ) """) indexes = [ "CREATE INDEX IF NOT EXISTS idx_tasks_enabled ON tasks(enabled)", "CREATE INDEX IF NOT EXISTS idx_tasks_frequency ON tasks(frequency, frequency_unit)", "CREATE INDEX IF NOT EXISTS idx_tasks_last_run ON tasks(last_run)", "CREATE INDEX IF NOT EXISTS idx_task_executions_task_id ON task_executions(task_id)", "CREATE INDEX IF NOT EXISTS idx_task_executions_status ON task_executions(status)", "CREATE INDEX IF NOT EXISTS idx_task_executions_start_time ON task_executions(start_time)", "CREATE INDEX IF NOT EXISTS idx_podcast_configs_is_active ON podcast_configs(is_active)", "CREATE INDEX IF NOT EXISTS idx_podcast_configs_name ON podcast_configs(name)", ] for index_sql in indexes: cursor.execute(index_sql) conn.commit() elapsed = time.time() - start_time print(f"Tasks database initialized in {elapsed:.3f}s") async def init_agent_session_db(): """Initialize the agent session database. auto generated""" pass def init_internal_sessions_db(): start_time = time.time() db_path = get_db_path("internal_sessions_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS session_state ( session_id TEXT PRIMARY KEY, state JSON, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_session_state_session_id ON session_state(session_id)") conn.commit() elapsed = time.time() - start_time print(f"Internal sessions database initialized in {elapsed:.3f}s") def init_social_media_db(): start_time = time.time() db_path = get_db_path("social_media_db") with db_connection(db_path) as conn: cursor = conn.cursor() cursor.execute("BEGIN TRANSACTION") cursor.execute(""" CREATE TABLE IF NOT EXISTS posts ( post_id TEXT PRIMARY KEY, platform TEXT, user_display_name TEXT, user_handle TEXT, user_profile_pic_url TEXT, post_timestamp TEXT, post_display_time TEXT, post_url TEXT, post_text TEXT, post_mentions TEXT, engagement_reply_count INTEGER, engagement_retweet_count INTEGER, engagement_like_count INTEGER, engagement_bookmark_count INTEGER, engagement_view_count INTEGER, media TEXT, media_count INTEGER, is_ad BOOLEAN, sentiment TEXT, categories TEXT, tags TEXT, analysis_reasoning TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) indexes = [ "CREATE INDEX IF NOT EXISTS idx_posts_platform ON posts(platform)", "CREATE INDEX IF NOT EXISTS idx_posts_user_handle ON posts(user_handle)", "CREATE INDEX IF NOT EXISTS idx_posts_post_timestamp ON posts(post_timestamp)", "CREATE INDEX IF NOT EXISTS idx_posts_sentiment ON posts(sentiment)", ] for index_sql in indexes: cursor.execute(index_sql) conn.commit() elapsed = time.time() - start_time print(f"Social media database initialized in {elapsed:.3f}s") async def init_databases(): total_start = time.time() print("Initializing all databases...") for db_name in ["sources_db", "tracking_db", "podcasts_db", "tasks_db"]: db_path = get_db_path(db_name) os.makedirs(os.path.dirname(db_path), exist_ok=True) loop = asyncio.get_event_loop() with ThreadPoolExecutor(max_workers=4) as executor: tasks = [ loop.run_in_executor(executor, init_sources_db), loop.run_in_executor(executor, init_tracking_db), loop.run_in_executor(executor, init_podcasts_db), loop.run_in_executor(executor, init_tasks_db), loop.run_in_executor(executor, init_internal_sessions_db), loop.run_in_executor(executor, init_social_media_db), ] await asyncio.gather(*tasks) total_elapsed = time.time() - total_start print(f"All databases initialized in {total_elapsed:.3f}s") def init_all_databases(): asyncio.run(init_databases())
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/source_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/source_service.py
from typing import List, Optional, Dict, Any from fastapi import HTTPException from datetime import datetime from services.db_service import sources_db, tracking_db from models.source_schemas import SourceCreate, SourceUpdate, SourceFeedCreate, PaginatedSources class SourceService: """Service for managing source operations with the new database structure.""" async def get_sources( self, page: int = 1, per_page: int = 10, category: Optional[str] = None, search: Optional[str] = None, include_inactive: bool = False ) -> PaginatedSources: """Get sources with pagination and filtering.""" try: query_parts = ["SELECT s.id, s.name, s.url, s.description, s.is_active, s.created_at", "FROM sources s", "WHERE 1=1"] query_params = [] if not include_inactive: query_parts.append("AND s.is_active = 1") if category: query_parts.append(""" AND EXISTS ( SELECT 1 FROM source_categories sc JOIN categories c ON sc.category_id = c.id WHERE sc.source_id = s.id AND c.name = ? ) """) query_params.append(category) if search: query_parts.append("AND (s.name LIKE ? OR s.description LIKE ?)") search_param = f"%{search}%" query_params.extend([search_param, search_param]) count_query = " ".join(query_parts).replace("SELECT s.id, s.name, s.url, s.description, s.is_active, s.created_at", "SELECT COUNT(*)") total_sources = await sources_db.execute_query(count_query, tuple(query_params), fetch=True, fetch_one=True) total_count = total_sources.get("COUNT(*)", 0) if total_sources else 0 query_parts.append("ORDER BY s.name") offset = (page - 1) * per_page query_parts.append("LIMIT ? OFFSET ?") query_params.extend([per_page, offset]) final_query = " ".join(query_parts) sources = await sources_db.execute_query(final_query, tuple(query_params), fetch=True) for source in sources: source["categories"] = await self.get_source_categories(source["id"]) source["last_crawled"] = await self.get_source_last_crawled(source["id"]) source["website"] = source["url"] if source["categories"] and isinstance(source["categories"], list): source["category"] = source["categories"][0] if source["categories"] else "" total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 0 has_next = page < total_pages has_prev = page > 1 return PaginatedSources( items=sources, total=total_count, page=page, per_page=per_page, total_pages=total_pages, has_next=has_next, has_prev=has_prev ) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching sources: {str(e)}") async def get_source(self, source_id: int) -> Dict[str, Any]: """Get a specific source by ID.""" query = """ SELECT id, name, url, description, is_active, created_at FROM sources WHERE id = ? """ source = await sources_db.execute_query(query, (source_id,), fetch=True, fetch_one=True) if not source: raise HTTPException(status_code=404, detail="Source not found") source["categories"] = await self.get_source_categories(source["id"]) source["last_crawled"] = await self.get_source_last_crawled(source["id"]) source["website"] = source["url"] if source["categories"] and isinstance(source["categories"], list): source["category"] = source["categories"][0] if source["categories"] else "" return source async def get_source_categories(self, source_id: int) -> List[str]: """Get all categories for a specific source.""" query = """ SELECT c.name FROM source_categories sc JOIN categories c ON sc.category_id = c.id WHERE sc.source_id = ? ORDER BY c.name """ categories = await sources_db.execute_query(query, (source_id,), fetch=True) return [category.get("name", "") for category in categories if category.get("name")] async def get_source_last_crawled(self, source_id: int) -> Optional[str]: """Get the last crawl time for a source's feeds.""" query = """ SELECT MAX(ft.last_processed) as last_crawled FROM feed_tracking ft WHERE ft.source_id = ? """ result = await tracking_db.execute_query(query, (source_id,), fetch=True, fetch_one=True) return result.get("last_crawled") if result else None async def get_source_by_name(self, name: str) -> Dict[str, Any]: """Get a specific source by name.""" query = """ SELECT id, name, url, description, is_active, created_at FROM sources WHERE name = ? """ source = await sources_db.execute_query(query, (name,), fetch=True, fetch_one=True) if not source: raise HTTPException(status_code=404, detail="Source not found") source["categories"] = await self.get_source_categories(source["id"]) source["last_crawled"] = await self.get_source_last_crawled(source["id"]) source["website"] = source["url"] if source["categories"] and isinstance(source["categories"], list): source["category"] = source["categories"][0] if source["categories"] else "" return source async def get_source_feeds(self, source_id: int) -> List[Dict[str, Any]]: """Get all feeds for a specific source.""" query = """ SELECT id, feed_url, feed_type, is_active, created_at, last_crawled FROM source_feeds WHERE source_id = ? ORDER BY feed_type """ feeds = await sources_db.execute_query(query, (source_id,), fetch=True) for feed in feeds: feed["description"] = feed.get("feed_type", "Main feed").capitalize() return feeds async def get_categories(self) -> List[Dict[str, Any]]: """Get all source categories.""" query = """ SELECT id, name FROM categories ORDER BY name """ categories = await sources_db.execute_query(query, fetch=True) for category in categories: category["description"] = f"Articles about {category.get('name', '')}" return categories async def get_source_by_category(self, category_name: str) -> List[Dict[str, Any]]: """Get sources by category using the junction table.""" query = """ SELECT s.id, s.name, s.url, s.description, s.is_active FROM sources s JOIN source_categories sc ON s.id = sc.source_id JOIN categories c ON sc.category_id = c.id WHERE c.name = ? AND s.is_active = 1 ORDER BY s.name """ sources = await sources_db.execute_query(query, (category_name,), fetch=True) for source in sources: source["categories"] = await self.get_source_categories(source["id"]) source["website"] = source["url"] if source["categories"] and isinstance(source["categories"], list): source["category"] = source["categories"][0] if source["categories"] else "" return sources async def create_source(self, source_data: SourceCreate) -> Dict[str, Any]: """Create a new source.""" try: source_query = """ INSERT INTO sources (name, url, description, is_active, created_at) VALUES (?, ?, ?, ?, ?) """ source_params = (source_data.name, source_data.url, source_data.description, source_data.is_active, datetime.now().isoformat()) source_id = await sources_db.execute_query(source_query, source_params) if source_data.categories: for category_name in source_data.categories: await self.add_source_category(source_id, category_name) elif hasattr(source_data, "category") and source_data.category: await self.add_source_category(source_id, source_data.category) if source_data.feeds: for feed in source_data.feeds: await self.add_feed_to_source(source_id, feed) return await self.get_source(source_id) except Exception as e: if isinstance(e, HTTPException): raise e if "UNIQUE constraint failed" in str(e) and "name" in str(e): raise HTTPException(status_code=409, detail="Source with this name already exists") raise HTTPException(status_code=500, detail=f"Error creating source: {str(e)}") async def add_source_category(self, source_id: int, category_name: str) -> None: """Add a category to a source, creating the category if it doesn't exist.""" category_query = """ INSERT OR IGNORE INTO categories (name, created_at) VALUES (?, ?) """ await sources_db.execute_query(category_query, (category_name, datetime.now().isoformat())) get_category_id_query = "SELECT id FROM categories WHERE name = ?" category = await sources_db.execute_query(get_category_id_query, (category_name,), fetch=True, fetch_one=True) if not category: raise HTTPException(status_code=500, detail=f"Failed to find or create category: {category_name}") link_query = """ INSERT OR IGNORE INTO source_categories (source_id, category_id) VALUES (?, ?) """ await sources_db.execute_query(link_query, (source_id, category["id"])) async def update_source(self, source_id: int, source_data: SourceUpdate) -> Dict[str, Any]: """Update an existing source.""" try: await self.get_source(source_id) update_fields = [] update_params = [] if source_data.name is not None: update_fields.append("name = ?") update_params.append(source_data.name) if source_data.url is not None: update_fields.append("url = ?") update_params.append(source_data.url) if source_data.description is not None: update_fields.append("description = ?") update_params.append(source_data.description) if source_data.is_active is not None: update_fields.append("is_active = ?") update_params.append(source_data.is_active) if update_fields: update_params.append(source_id) update_query = f""" UPDATE sources SET {", ".join(update_fields)} WHERE id = ? """ await sources_db.execute_query(update_query, tuple(update_params)) if source_data.categories is not None: delete_categories_query = "DELETE FROM source_categories WHERE source_id = ?" await sources_db.execute_query(delete_categories_query, (source_id,)) if source_data.categories: for category_name in source_data.categories: await self.add_source_category(source_id, category_name) elif hasattr(source_data, "category") and source_data.category is not None: delete_categories_query = "DELETE FROM source_categories WHERE source_id = ?" await sources_db.execute_query(delete_categories_query, (source_id,)) if source_data.category: await self.add_source_category(source_id, source_data.category) return await self.get_source(source_id) except Exception as e: if isinstance(e, HTTPException): raise e if "UNIQUE constraint failed" in str(e) and "name" in str(e): raise HTTPException(status_code=409, detail="Source with this name already exists") raise HTTPException(status_code=500, detail=f"Error updating source: {str(e)}") async def delete_source(self, source_id: int) -> Dict[str, Any]: """Delete a source (soft delete by setting is_active to false).""" try: source = await self.get_source(source_id) update_query = """ UPDATE sources SET is_active = 0 WHERE id = ? """ await sources_db.execute_query(update_query, (source_id,)) feeds_query = """ UPDATE source_feeds SET is_active = 0 WHERE source_id = ? """ await sources_db.execute_query(feeds_query, (source_id,)) return {**source, "is_active": False} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting source: {str(e)}") async def hard_delete_source(self, source_id: int) -> Dict[str, str]: """Permanently delete a source and its feeds.""" try: source = await self.get_source(source_id) delete_feeds_query = """ DELETE FROM source_feeds WHERE source_id = ? """ await sources_db.execute_query(delete_feeds_query, (source_id,)) delete_categories_query = """ DELETE FROM source_categories WHERE source_id = ? """ await sources_db.execute_query(delete_categories_query, (source_id,)) delete_source_query = """ DELETE FROM sources WHERE id = ? """ await sources_db.execute_query(delete_source_query, (source_id,)) return {"message": f"Source '{source['name']}' has been permanently deleted"} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting source: {str(e)}") async def add_feed_to_source(self, source_id: int, feed_data: SourceFeedCreate) -> Dict[str, Any]: """Add a new feed to an existing source.""" try: await self.get_source(source_id) check_query = """ SELECT id, source_id FROM source_feeds WHERE feed_url = ? """ existing_feed = await sources_db.execute_query(check_query, (feed_data.feed_url,), fetch=True, fetch_one=True) if existing_feed: source_query = """ SELECT name FROM sources WHERE id = ? """ source = await sources_db.execute_query(source_query, (existing_feed["source_id"],), fetch=True, fetch_one=True) source_name = source["name"] if source else "another source" raise HTTPException( status_code=409, detail=f"A feed with this URL already exists for {source_name}. Please edit the existing feed (ID: {existing_feed['id']}) instead.", ) feed_query = """ INSERT INTO source_feeds (source_id, feed_url, feed_type, is_active, created_at) VALUES (?, ?, ?, ?, ?) """ feed_params = (source_id, feed_data.feed_url, feed_data.feed_type, feed_data.is_active, datetime.now().isoformat()) await sources_db.execute_query(feed_query, feed_params) return await self.get_source_feeds(source_id) except Exception as e: if isinstance(e, HTTPException): raise e if "UNIQUE constraint failed" in str(e) and "feed_url" in str(e): raise HTTPException(status_code=409, detail="This feed URL already exists. Please check your existing feeds or try a different URL.") raise HTTPException(status_code=500, detail=f"Error adding feed: {str(e)}") async def update_feed(self, feed_id: int, feed_data: Dict[str, Any]) -> Dict[str, Any]: """Update an existing feed.""" try: feed_query = "SELECT id, source_id FROM source_feeds WHERE id = ?" feed = await sources_db.execute_query(feed_query, (feed_id,), fetch=True, fetch_one=True) if not feed: raise HTTPException(status_code=404, detail="Feed not found") update_fields = [] update_params = [] if "feed_url" in feed_data: update_fields.append("feed_url = ?") update_params.append(feed_data["feed_url"]) if "feed_type" in feed_data: update_fields.append("feed_type = ?") update_params.append(feed_data["feed_type"]) if "is_active" in feed_data: update_fields.append("is_active = ?") update_params.append(feed_data["is_active"]) if not update_fields: return await self.get_source_feeds(feed["source_id"]) update_params.append(feed_id) update_query = f""" UPDATE source_feeds SET {", ".join(update_fields)} WHERE id = ? """ await sources_db.execute_query(update_query, tuple(update_params)) return await self.get_source_feeds(feed["source_id"]) except Exception as e: if isinstance(e, HTTPException): raise e if "UNIQUE constraint failed" in str(e) and "feed_url" in str(e): raise HTTPException(status_code=409, detail="Feed URL already exists") raise HTTPException(status_code=500, detail=f"Error updating feed: {str(e)}") async def delete_feed(self, feed_id: int) -> Dict[str, str]: """Delete a feed.""" try: feed_query = "SELECT * FROM source_feeds WHERE id = ?" feed = await sources_db.execute_query(feed_query, (feed_id,), fetch=True, fetch_one=True) if not feed: raise HTTPException(status_code=404, detail="Feed not found") delete_query = "DELETE FROM source_feeds WHERE id = ?" await sources_db.execute_query(delete_query, (feed_id,)) return {"message": "Feed has been deleted"} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting feed: {str(e)}") source_service = SourceService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/article_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/article_service.py
from typing import List, Optional, Dict, Any from fastapi import HTTPException import json from services.db_service import tracking_db, sources_db from models.article_schemas import Article, PaginatedArticles class ArticleService: """Service for managing article operations with the new database structure.""" async def get_articles( self, page: int = 1, per_page: int = 10, source: Optional[str] = None, date_from: Optional[str] = None, date_to: Optional[str] = None, search: Optional[str] = None, category: Optional[str] = None, ) -> PaginatedArticles: """Get articles with pagination and filtering.""" try: offset = (page - 1) * per_page query_parts = [ "SELECT ca.id, ca.title, ca.url, ca.published_date, ca.summary, ca.feed_id", "FROM crawled_articles ca", "WHERE ca.processed = 1 AND ca.ai_status = 'success'", ] query_params = [] if source: source_id_query = "SELECT id FROM sources WHERE name = ?" source_id_result = await sources_db.execute_query(source_id_query, (source,), fetch=True, fetch_one=True) if source_id_result and source_id_result.get("id"): feed_ids_query = "SELECT id FROM source_feeds WHERE source_id = ?" feed_ids_result = await sources_db.execute_query(feed_ids_query, (source_id_result["id"],), fetch=True) if feed_ids_result: feed_ids = [item["id"] for item in feed_ids_result] placeholders = ",".join(["?" for _ in feed_ids]) query_parts.append(f"AND ca.feed_id IN ({placeholders})") query_params.extend(feed_ids) if category: query_parts.append(""" AND EXISTS ( SELECT 1 FROM article_categories ac WHERE ac.article_id = ca.id AND ac.category_name = ? ) """) query_params.append(category.lower()) if date_from: query_parts.append("AND datetime(ca.published_date) >= datetime(?)") query_params.append(date_from) if date_to: query_parts.append("AND datetime(ca.published_date) <= datetime(?)") query_params.append(date_to) if search: query_parts.append("AND (ca.title LIKE ? OR ca.summary LIKE ?)") search_param = f"%{search}%" query_params.extend([search_param, search_param]) count_query = " ".join(query_parts).replace( "SELECT ca.id, ca.title, ca.url, ca.published_date, ca.summary, ca.feed_id", "SELECT COUNT(*)", ) total_articles = await tracking_db.execute_query(count_query, tuple(query_params), fetch=True, fetch_one=True) total_count = total_articles.get("COUNT(*)", 0) if total_articles else 0 query_parts.append("ORDER BY datetime(ca.published_date) DESC, ca.id DESC") query_parts.append("LIMIT ? OFFSET ?") query_params.extend([per_page, offset]) articles_query = " ".join(query_parts) articles = await tracking_db.execute_query(articles_query, tuple(query_params), fetch=True) feed_ids = [article["feed_id"] for article in articles if article.get("feed_id")] source_names = {} if feed_ids: feed_ids_str = ",".join("?" for _ in feed_ids) source_query = f""" SELECT sf.id as feed_id, s.name as source_name FROM source_feeds sf JOIN sources s ON sf.source_id = s.id WHERE sf.id IN ({feed_ids_str}) """ sources_result = await sources_db.execute_query(source_query, tuple(feed_ids), fetch=True) source_names = {item["feed_id"]: item["source_name"] for item in sources_result} for article in articles: feed_id = article.get("feed_id") article["source_name"] = source_names.get(feed_id, "Unknown Source") article.pop("feed_id", None) article["categories"] = await self.get_article_categories(article["id"]) total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 0 has_next = page < total_pages has_prev = page > 1 return PaginatedArticles( items=articles, total=total_count, page=page, per_page=per_page, total_pages=total_pages, has_next=has_next, has_prev=has_prev, ) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching articles: {str(e)}") async def get_article(self, article_id: int) -> Article: """Get a specific article by ID.""" try: article_query = """ SELECT id, title, url, published_date, content, summary, feed_id, metadata, ai_status FROM crawled_articles WHERE id = ? AND processed = 1 """ article = await tracking_db.execute_query(article_query, (article_id,), fetch=True, fetch_one=True) if not article: raise HTTPException(status_code=404, detail="Article not found") if article.get("feed_id"): source_query = """ SELECT s.name as source_name FROM source_feeds sf JOIN sources s ON sf.source_id = s.id WHERE sf.id = ? """ source_result = await sources_db.execute_query(source_query, (article["feed_id"],), fetch=True, fetch_one=True) if source_result: article["source_name"] = source_result["source_name"] else: article["source_name"] = "Unknown Source" else: article["source_name"] = "Unknown Source" article.pop("feed_id", None) if article.get("metadata"): try: article["metadata"] = json.loads(article["metadata"]) except json.JSONDecodeError: article["metadata"] = {} article["categories"] = await self.get_article_categories(article_id) return article except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching article: {str(e)}") async def get_article_categories(self, article_id: int) -> List[str]: """Get categories for a specific article.""" query = """ SELECT category_name FROM article_categories WHERE article_id = ? """ categories = await tracking_db.execute_query(query, (article_id,), fetch=True) return [category.get("category_name", "") for category in categories] async def get_sources(self) -> List[str]: """Get all available active sources.""" query = """ SELECT DISTINCT name FROM sources WHERE is_active = 1 ORDER BY name """ result = await sources_db.execute_query(query, fetch=True) return [row.get("name", "") for row in result if row.get("name")] async def get_categories(self) -> List[Dict[str, Any]]: """Get all categories with article counts.""" query = """ SELECT category_name, COUNT(DISTINCT article_id) as article_count FROM article_categories GROUP BY category_name ORDER BY article_count DESC """ return await tracking_db.execute_query(query, fetch=True) article_service = ArticleService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/async_podcast_agent_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/async_podcast_agent_service.py
import os import json import uuid from fastapi import status from fastapi.responses import JSONResponse import aiosqlite import glob from redis.asyncio import ConnectionPool, Redis from db.config import get_agent_session_db_path from db.agent_config_v2 import PODCAST_DIR, PODCAST_AUIDO_DIR, PODCAST_IMG_DIR, PODCAST_RECORDINGS_DIR, AVAILABLE_LANGS from services.celery_tasks import agent_chat from dotenv import load_dotenv from services.internal_session_service import SessionService load_dotenv() class PodcastAgentService: def __init__(self): os.makedirs(PODCAST_DIR, exist_ok=True) os.makedirs(PODCAST_AUIDO_DIR, exist_ok=True) os.makedirs(PODCAST_IMG_DIR, exist_ok=True) os.makedirs(PODCAST_RECORDINGS_DIR, exist_ok=True) self.redis_host = os.environ.get("REDIS_HOST", "localhost") self.redis_port = int(os.environ.get("REDIS_PORT", 6379)) self.redis_db = int(os.environ.get("REDIS_DB", 0)) self.redis_pool = ConnectionPool.from_url(f"redis://{self.redis_host}:{self.redis_port}/{self.redis_db + 1}", max_connections=10) self.redis = Redis(connection_pool=self.redis_pool) async def get_active_task(self, session_id): try: lock_info = await self.redis.get(f"lock_info:{session_id}") if lock_info: try: lock_data = json.loads(lock_info.decode("utf-8")) task_id = lock_data.get("task_id") if task_id: return task_id except (json.JSONDecodeError, AttributeError) as e: print(f"Error parsing lock info: {e}") return None except Exception as e: print(f"Error checking active task: {e}") return None async def create_session(self, request=None): if request and request.session_id: session_id = request.session_id try: db_path = get_agent_session_db_path() async with aiosqlite.connect(db_path) as conn: async with conn.execute("SELECT 1 FROM podcast_sessions WHERE session_id = ?", (session_id,)) as cursor: row = await cursor.fetchone() exists = row is not None if exists: return {"session_id": session_id} except Exception as e: print(f"Error checking session existence: {e}") new_session_id = str(uuid.uuid4()) return {"session_id": new_session_id} async def chat(self, request): try: session_id = request.session_id task_id = await self.get_active_task(session_id) if task_id: return { "session_id": session_id, "response": "Your request is already being processed.", "stage": "processing", "session_state": "{}", "is_processing": True, "process_type": "chat", "task_id": task_id, } task = agent_chat.delay(request.session_id, request.message) return { "session_id": request.session_id, "response": "Your request is being processed.", "stage": "processing", "session_state": "{}", "is_processing": True, "process_type": "chat", "task_id": task.id, } except Exception as e: return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "session_id": request.session_id, "response": f"I encountered an error while processing your request: {str(e)}. Please try again.", "stage": "error", "session_state": "{}", "error": str(e), "is_processing": False, }, ) def _browser_recording(self, session_id): try: recordings_dir = os.path.join("podcasts/recordings", session_id) webm_files = glob.glob(os.path.join(recordings_dir, "*.webm")) if webm_files: browser_recording_path = webm_files[0] if (os.path.exists(browser_recording_path) and os.path.getsize(browser_recording_path) > 8192 and os.access(browser_recording_path, os.R_OK)): return browser_recording_path return None except Exception as _: return None async def check_result_status(self, request): try: if not request.session_id: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"error": "Session ID is required"}, ) browser_recording_path = self._browser_recording(request.session_id) task_id = getattr(request, "task_id", None) if task_id: task = agent_chat.AsyncResult(task_id) if task.state == "PENDING" or task.state == "STARTED": return { "session_id": request.session_id, "response": "Your request is still being processed.", "stage": "processing", "session_state": "{}", "is_processing": True, "process_type": "chat", "task_id": task_id, "browser_recording_path": browser_recording_path, } elif task.state == "SUCCESS": result = task.result if result and isinstance(result, dict): if result.get("session_id") != request.session_id: return { "session_id": request.session_id, "response": "Error: Received result for wrong session.", "stage": "error", "session_state": "{}", "is_processing": False, "browser_recording_path": browser_recording_path, } return result else: error_info = str(task.result) if task.result else f"Task failed with state: {task.state}" return { "session_id": request.session_id, "response": f"Error processing request: {error_info}", "stage": "error", "session_state": "{}", "is_processing": False, "browser_recording_path": browser_recording_path, } return await self.get_session_state(request.session_id) except Exception as e: return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "error": f"Error checking result status: {str(e)}", "session_id": request.session_id, "response": f"Error checking result status: {str(e)}", "stage": "error", "session_state": "{}", "is_processing": False, "browser_recording_path": browser_recording_path, }, ) async def get_session_state(self, session_id): try: db_path = get_agent_session_db_path() async with aiosqlite.connect(db_path) as conn: conn.row_factory = lambda cursor, row: {col[0]: row[idx] for idx, col in enumerate(cursor.description)} async with conn.execute("SELECT session_data FROM podcast_sessions WHERE session_id = ?", (session_id,)) as cursor: row = await cursor.fetchone() if not row: return { "session_id": session_id, "response": "No session data found.", "stage": "idle", "session_state": "{}", "is_processing": False, } session = SessionService.get_session(session_id) session_state = session.get("state", {}) return { "session_id": session_id, "response": "", "stage": session_state.get("stage", "idle"), "session_state": json.dumps(session_state), "is_processing": False, } except Exception as e: return { "session_id": session_id, "response": f"Error retrieving session state: {str(e)}", "stage": "error", "session_state": "{}", "is_processing": False, } async def list_sessions(self, page=1, per_page=10): try: db_path = get_agent_session_db_path() async with aiosqlite.connect(db_path) as conn: conn.row_factory = lambda cursor, row: {col[0]: row[idx] for idx, col in enumerate(cursor.description)} async with conn.execute( """ select name from sqlite_master where type='table' and name='podcast_sessions' """ ) as cursor: table = await cursor.fetchone() if not table: return { "sessions": [], "pagination": { "total": 0, "page": page, "per_page": per_page, "total_pages": 0, }, } async with conn.execute("SELECT COUNT(*) as count FROM podcast_sessions") as cursor: row = await cursor.fetchone() total_sessions = row["count"] if row else 0 offset = (page - 1) * per_page async with conn.execute( "SELECT session_id, session_data, updated_at FROM podcast_sessions ORDER BY updated_at DESC LIMIT ? OFFSET ?", (per_page, offset) ) as cursor: rows = await cursor.fetchall() sessions = [] for row in rows: try: session = SessionService.get_session(row["session_id"]) session_state = session.get("state", {}) title = session_state.get("title", "Untitled Podcast") stage = session_state.get("stage", "welcome") updated_at = row["updated_at"] sessions.append({"session_id": row["session_id"], "topic": title, "stage": stage, "updated_at": updated_at}) except Exception as e: print(f"Error parsing session data: {e}") return { "sessions": sessions, "pagination": { "total": total_sessions, "page": page, "per_page": per_page, "total_pages": (total_sessions + per_page - 1) // per_page, }, } except Exception as e: print(f"Error listing sessions: {e}") return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"error": f"Failed to list sessions: {str(e)}"}) async def delete_session(self, session_id: str): try: db_path = get_agent_session_db_path() async with aiosqlite.connect(db_path) as conn: conn.row_factory = lambda cursor, row: {col[0]: row[idx] for idx, col in enumerate(cursor.description)} async with conn.execute("SELECT session_data FROM podcast_sessions WHERE session_id = ?", (session_id,)) as cursor: row = await cursor.fetchone() if not row: return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"error": f"Session with ID {session_id} not found"}) try: session = SessionService.get_session(session_id) session_state = session.get("state", {}) stage = session_state.get("stage") is_completed = stage == "complete" or session_state.get("podcast_generated", False) banner_url = session_state.get("banner_url") audio_url = session_state.get("audio_url") web_search_recording = session_state.get("web_search_recording") await conn.execute("DELETE FROM podcast_sessions WHERE session_id = ?", (session_id,)) await conn.commit() if is_completed: print(f"Session {session_id} is in 'complete' stage, keeping assets but removing session record") else: if banner_url: banner_path = os.path.join(PODCAST_IMG_DIR, banner_url) if os.path.exists(banner_path): try: os.remove(banner_path) print(f"Deleted banner image: {banner_path}") except Exception as e: print(f"Error deleting banner image: {e}") if audio_url: audio_path = os.path.join(PODCAST_AUIDO_DIR, audio_url) if os.path.exists(audio_path): try: os.remove(audio_path) print(f"Deleted audio file: {audio_path}") except Exception as e: print(f"Error deleting audio file: {e}") if web_search_recording: recording_dir = os.path.join(PODCAST_RECORDINGS_DIR, session_id) if os.path.exists(recording_dir): try: import shutil shutil.rmtree(recording_dir) print(f"Deleted recordings directory: {recording_dir}") except Exception as e: print(f"Error deleting recordings directory: {e}") if is_completed: return {"success": True, "message": f"Session {session_id} deleted, but assets preserved"} else: return {"success": True, "message": f"Session {session_id} and its associated data deleted successfully"} except Exception as e: print(f"Error parsing session data for deletion: {e}") return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"error": f"Error deleting session: {str(e)}"}) except Exception as e: print(f"Error deleting session: {e}") return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"error": f"Failed to delete session: {str(e)}"}) async def _get_chat_messages(self, row, session_id): formatted_messages = [] session_state = {} if row["session_data"]: try: session = SessionService.get_session(session_id) session_state = session.get("state", {}) except Exception as e: print(f"Error parsing session_data: {e}") if row["memory"]: try: memory_data = json.loads(row["memory"]) if isinstance(row["memory"], str) else row["memory"] if "runs" in memory_data and isinstance(memory_data["runs"], list): for run in memory_data["runs"]: if "messages" in run and isinstance(run["messages"], list): for msg in run["messages"]: if msg.get("role") in ["user", "assistant"] and "content" in msg: if msg.get("role") == "assistant" and "tool_calls" in msg: if not msg.get("content"): continue if msg.get("content"): formatted_messages.append({"role": msg["role"], "content": msg["content"]}) except json.JSONDecodeError as e: print(f"Error parsing memory data: {e}") return formatted_messages, session_state async def get_session_history(self, session_id: str): try: db_path = get_agent_session_db_path() async with aiosqlite.connect(db_path) as conn: conn.row_factory = lambda cursor, row: {col[0]: row[idx] for idx, col in enumerate(cursor.description)} async with conn.execute( """ select name from sqlite_master where type='table' and name='podcast_sessions' """ ) as cursor: table = await cursor.fetchone() if not table: return {"session_id": session_id, "messages": [], "state": "{}", "is_processing": False, "process_type": None} async with conn.execute("SELECT memory, session_data FROM podcast_sessions WHERE session_id = ?", (session_id,)) as cursor: row = await cursor.fetchone() if not row: return {"session_id": session_id, "messages": [], "state": "{}", "is_processing": False, "process_type": None} formatted_messages, session_state = await self._get_chat_messages(row, session_id) task_id = await self.get_active_task(session_id) is_processing = bool(task_id) process_type = "chat" if is_processing else None browser_recording_path = self._browser_recording(session_id) return { "session_id": session_id, "messages": formatted_messages, "state": json.dumps(session_state), "is_processing": is_processing, "process_type": process_type, "task_id": task_id if task_id and is_processing else None, "browser_recording_path": browser_recording_path, } except Exception as e: return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"error": f"Error retrieving session history: {str(e)}"}) async def get_supported_languages(self): return {"languages": AVAILABLE_LANGS} podcast_agent_service = PodcastAgentService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/celery_app.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/celery_app.py
from celery import Celery, Task import redis import os import time import json from dotenv import load_dotenv load_dotenv() REDIS_HOST = os.environ.get("REDIS_HOST", "localhost") REDIS_PORT = int(os.environ.get("REDIS_PORT", 6379)) REDIS_DB = int(os.environ.get("REDIS_DB", 0)) REDIS_LOCK_EXP_TIME_SEC = 60 * 10 REDIS_LOCK_INFO_EXP_TIME_SEC = 60 * 15 STALE_LOCK_THRESHOLD_SEC = 60 * 15 redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB + 1) app = Celery("beifong_tasks", broker=f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}", backend=f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}") app.conf.update( result_expires=60 * 2, task_track_started=True, worker_concurrency=2, task_acks_late=True, task_time_limit=600, task_soft_time_limit=540, ) class SessionLockedTask(Task): def __call__(self, *args, **kwargs): session_id = args[0] if args else kwargs.get("session_id") if not session_id: return super().__call__(*args, **kwargs) lock_key = f"lock:{session_id}" lock_info = redis_client.get(f"lock_info:{session_id}") if lock_info: try: lock_data = json.loads(lock_info.decode("utf-8")) lock_time = lock_data.get("timestamp", 0) if time.time() - lock_time > STALE_LOCK_THRESHOLD_SEC: redis_client.delete(lock_key) redis_client.delete(f"lock_info:{session_id}") except (ValueError, TypeError) as e: print(f"Error checking lock time: {e}") acquired = redis_client.set(lock_key, "1", nx=True, ex=REDIS_LOCK_EXP_TIME_SEC) if acquired: lock_data = {"timestamp": time.time(), "task_id": self.request.id if hasattr(self, "request") else None} redis_client.set(f"lock_info:{session_id}", json.dumps(lock_data), ex=REDIS_LOCK_INFO_EXP_TIME_SEC) if not acquired: return { "error": "Session busy", "response": "This session is already processing a message. Please wait.", "session_id": session_id, "stage": "busy", "session_state": "{}", "is_processing": True, "process_type": "chat", } try: return super().__call__(*args, **kwargs) finally: redis_client.delete(lock_key) redis_client.delete(f"lock_info:{session_id}")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/celery_tasks.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/celery_tasks.py
from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.storage.sqlite import SqliteStorage import os from dotenv import load_dotenv from services.celery_app import app, SessionLockedTask from db.config import get_agent_session_db_path from db.agent_config_v2 import ( AGENT_DESCRIPTION, AGENT_INSTRUCTIONS, AGENT_MODEL, INITIAL_SESSION_STATE, ) from agents.search_agent import search_agent_run from agents.scrape_agent import scrape_agent_run from agents.script_agent import podcast_script_agent_run from tools.ui_manager import ui_manager_run from tools.user_source_selection import user_source_selection_run from tools.session_state_manager import update_language, update_chat_title, mark_session_finished from agents.image_generate_agent import image_generation_agent_run from agents.audio_generate_agent import audio_generate_agent_run import json load_dotenv() db_file = get_agent_session_db_path() @app.task(bind=True, max_retries=0, base=SessionLockedTask) def agent_chat(self, session_id, message): try: print(f"Processing message for session {session_id}: {message[:50]}...") db_file = get_agent_session_db_path() os.makedirs(os.path.dirname(db_file), exist_ok=True) from services.internal_session_service import SessionService session_state = SessionService.get_session(session_id).get("state", INITIAL_SESSION_STATE) _agent = Agent( model=OpenAIChat(id=AGENT_MODEL, api_key=os.getenv("OPENAI_API_KEY")), storage=SqliteStorage(table_name="podcast_sessions", db_file=db_file), add_history_to_messages=True, read_chat_history=True, add_state_in_messages=True, num_history_runs=30, instructions=AGENT_INSTRUCTIONS, description=AGENT_DESCRIPTION, session_state=session_state, session_id=session_id, tools=[ search_agent_run, scrape_agent_run, ui_manager_run, user_source_selection_run, update_language, podcast_script_agent_run, image_generation_agent_run, audio_generate_agent_run, update_chat_title, mark_session_finished, ], markdown=True, ) response = _agent.run(message, session_id=session_id) print(f"Response generated for session {session_id}") _agent.write_to_storage(session_id=session_id) session_state = SessionService.get_session(session_id).get("state", INITIAL_SESSION_STATE) return { "session_id": session_id, "response": response.content, "stage": _agent.session_state.get("stage", "unknown"), "session_state": json.dumps(session_state), "is_processing": False, "process_type": None, } except Exception as e: print(f"Error in agent_chat for session {session_id}: {str(e)}") return { "session_id": session_id, "response": f"I'm sorry, I encountered an error: {str(e)}. Please try again.", "stage": "error", "session_state": "{}", "is_processing": False, "process_type": None, }
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/social_media_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/social_media_service.py
import json from typing import List, Optional, Dict, Any from fastapi import HTTPException from services.db_service import social_media_db from models.social_media_schemas import PaginatedPosts, Post from datetime import datetime, timedelta class SocialMediaService: """Service for managing social media posts.""" async def get_posts( self, page: int = 1, per_page: int = 10, platform: Optional[str] = None, user_handle: Optional[str] = None, sentiment: Optional[str] = None, category: Optional[str] = None, date_from: Optional[str] = None, date_to: Optional[str] = None, search: Optional[str] = None, ) -> PaginatedPosts: """Get social media posts with pagination and filtering.""" try: offset = (page - 1) * per_page query_parts = [ "SELECT * FROM posts", "WHERE 1=1", ] query_params = [] if platform: query_parts.append("AND platform = ?") query_params.append(platform) if user_handle: query_parts.append("AND user_handle = ?") query_params.append(user_handle) if sentiment: query_parts.append("AND sentiment = ?") query_params.append(sentiment) if category: query_parts.append("AND categories LIKE ?") query_params.append(f'%"{category}"%') if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") query_params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") query_params.append(date_to) if search: query_parts.append("AND (post_text LIKE ? OR user_display_name LIKE ? OR user_handle LIKE ?)") search_param = f"%{search}%" query_params.extend([search_param, search_param, search_param]) count_query = " ".join(query_parts).replace("SELECT *", "SELECT COUNT(*)") total_posts = await social_media_db.execute_query(count_query, tuple(query_params), fetch=True, fetch_one=True) total_count = total_posts.get("COUNT(*)", 0) if total_posts else 0 query_parts.append("ORDER BY datetime(post_timestamp) DESC, post_id DESC") query_parts.append("LIMIT ? OFFSET ?") query_params.extend([per_page, offset]) posts_query = " ".join(query_parts) posts_data = await social_media_db.execute_query(posts_query, tuple(query_params), fetch=True) posts = [] for post in posts_data: post_dict = dict(post) if post_dict.get("media"): try: post_dict["media"] = json.loads(post_dict["media"]) except json.JSONDecodeError: post_dict["media"] = [] if post_dict.get("categories"): try: post_dict["categories"] = json.loads(post_dict["categories"]) except json.JSONDecodeError: post_dict["categories"] = [] if post_dict.get("tags"): try: post_dict["tags"] = json.loads(post_dict["tags"]) except json.JSONDecodeError: post_dict["tags"] = [] post_dict["engagement"] = { "replies": post_dict.pop("engagement_reply_count", 0), "retweets": post_dict.pop("engagement_retweet_count", 0), "likes": post_dict.pop("engagement_like_count", 0), "bookmarks": post_dict.pop("engagement_bookmark_count", 0), "views": post_dict.pop("engagement_view_count", 0), } posts.append(post_dict) total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 0 has_next = page < total_pages has_prev = page > 1 return PaginatedPosts( items=posts, total=total_count, page=page, per_page=per_page, total_pages=total_pages, has_next=has_next, has_prev=has_prev, ) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching social media posts: {str(e)}") async def get_post(self, post_id: str) -> Dict[str, Any]: """Get a specific post by ID.""" try: query = "SELECT * FROM posts WHERE post_id = ?" post = await social_media_db.execute_query(query, (post_id,), fetch=True, fetch_one=True) if not post: raise HTTPException(status_code=404, detail="Post not found") post_dict = dict(post) if post_dict.get("media"): try: post_dict["media"] = json.loads(post_dict["media"]) except json.JSONDecodeError: post_dict["media"] = [] if post_dict.get("categories"): try: post_dict["categories"] = json.loads(post_dict["categories"]) except json.JSONDecodeError: post_dict["categories"] = [] if post_dict.get("tags"): try: post_dict["tags"] = json.loads(post_dict["tags"]) except json.JSONDecodeError: post_dict["tags"] = [] post_dict["engagement"] = { "replies": post_dict.pop("engagement_reply_count", 0), "retweets": post_dict.pop("engagement_retweet_count", 0), "likes": post_dict.pop("engagement_like_count", 0), "bookmarks": post_dict.pop("engagement_bookmark_count", 0), "views": post_dict.pop("engagement_view_count", 0), } return post_dict except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching social media post: {str(e)}") async def get_platforms(self) -> List[str]: """Get all platforms that have posts.""" query = "SELECT DISTINCT platform FROM posts ORDER BY platform" result = await social_media_db.execute_query(query, fetch=True) return [row.get("platform", "") for row in result if row.get("platform")] async def get_sentiments(self, date_from: Optional[str] = None, date_to: Optional[str] = None) -> List[Dict[str, Any]]: """Get sentiment distribution with post counts.""" try: query_parts = [ """ SELECT sentiment, COUNT(*) as post_count FROM posts WHERE sentiment IS NOT NULL """ ] params = [] if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query_parts.append("GROUP BY sentiment ORDER BY post_count DESC") query = " ".join(query_parts) return await social_media_db.execute_query(query, tuple(params), fetch=True) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching sentiments: {str(e)}") async def get_top_users( self, platform: Optional[str] = None, limit: int = 10, date_from: Optional[str] = None, date_to: Optional[str] = None, ) -> List[Dict[str, Any]]: """Get top users by post count.""" query_parts = ["SELECT user_handle, user_display_name, COUNT(*) as post_count", "FROM posts", "WHERE user_handle IS NOT NULL"] params = [] if platform: query_parts.append("AND platform = ?") params.append(platform) if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query_parts.extend(["GROUP BY user_handle", "ORDER BY post_count DESC", "LIMIT ?"]) params.append(limit) query = " ".join(query_parts) return await social_media_db.execute_query(query, tuple(params), fetch=True) async def get_categories(self, date_from: Optional[str] = None, date_to: Optional[str] = None) -> List[Dict[str, Any]]: """Get all categories with post counts.""" try: query_parts = ["SELECT categories FROM posts WHERE categories IS NOT NULL"] params = [] if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True) category_counts = {} for row in result: if row.get("categories"): try: categories = json.loads(row["categories"]) for category in categories: if category in category_counts: category_counts[category] += 1 else: category_counts[category] = 1 except json.JSONDecodeError: pass return [{"category": category, "post_count": count} for category, count in sorted(category_counts.items(), key=lambda x: x[1], reverse=True)] except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching categories: {str(e)}") async def get_user_sentiment( self, limit: int = 10, platform: Optional[str] = None, date_from: Optional[str] = None, date_to: Optional[str] = None, ) -> List[Dict[str, Any]]: """Get users with their sentiment breakdown.""" try: query_parts = [ """ SELECT user_handle, user_display_name, COUNT(*) as total_posts, SUM(CASE WHEN sentiment = 'positive' THEN 1 ELSE 0 END) as positive_count, SUM(CASE WHEN sentiment = 'negative' THEN 1 ELSE 0 END) as negative_count, SUM(CASE WHEN sentiment = 'neutral' THEN 1 ELSE 0 END) as neutral_count, SUM(CASE WHEN sentiment = 'critical' THEN 1 ELSE 0 END) as critical_count FROM posts WHERE user_handle IS NOT NULL """ ] params = [] if platform: query_parts.append("AND platform = ?") params.append(platform) if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query_parts.extend(["GROUP BY user_handle, user_display_name", "ORDER BY total_posts DESC", "LIMIT ?"]) params.append(limit) query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True) for user in result: total = user["total_posts"] user["positive_percent"] = (user["positive_count"] / total) * 100 if total > 0 else 0 user["negative_percent"] = (user["negative_count"] / total) * 100 if total > 0 else 0 user["neutral_percent"] = (user["neutral_count"] / total) * 100 if total > 0 else 0 user["critical_percent"] = (user["critical_count"] / total) * 100 if total > 0 else 0 return result except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching user sentiment: {str(e)}") async def get_category_sentiment(self, date_from: Optional[str] = None, date_to: Optional[str] = None) -> List[Dict[str, Any]]: """Get sentiment distribution by category.""" try: date_filter = "" params = [] if date_from or date_to: date_filter = "WHERE " if date_from: date_filter += "datetime(p.post_timestamp) >= datetime(?)" params.append(date_from) if date_to: date_filter += " AND " if date_to: date_filter += "datetime(p.post_timestamp) <= datetime(?)" params.append(date_to) query = f""" WITH category_data AS ( SELECT json_each.value as category, sentiment, COUNT(*) as count FROM posts p, json_each(p.categories) {date_filter} GROUP BY json_each.value, sentiment ) SELECT category, SUM(count) as total_count, SUM(CASE WHEN sentiment = 'positive' THEN count ELSE 0 END) as positive_count, SUM(CASE WHEN sentiment = 'negative' THEN count ELSE 0 END) as negative_count, SUM(CASE WHEN sentiment = 'neutral' THEN count ELSE 0 END) as neutral_count, SUM(CASE WHEN sentiment = 'critical' THEN count ELSE 0 END) as critical_count FROM category_data GROUP BY category ORDER BY total_count DESC """ result = await social_media_db.execute_query(query, tuple(params), fetch=True) for category in result: total = category["total_count"] category["positive_percent"] = (category["positive_count"] / total) * 100 if total > 0 else 0 category["negative_percent"] = (category["negative_count"] / total) * 100 if total > 0 else 0 category["neutral_percent"] = (category["neutral_count"] / total) * 100 if total > 0 else 0 category["critical_percent"] = (category["critical_count"] / total) * 100 if total > 0 else 0 return result except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching category sentiment: {str(e)}") async def get_trending_topics( self, date_from: Optional[str] = None, date_to: Optional[str] = None, limit: int = 10 ) -> List[Dict[str, Any]]: """Get trending topics with sentiment breakdown.""" try: query_parts = [ """ WITH topic_data AS ( SELECT json_each.value as topic, sentiment, COUNT(*) as count FROM posts, json_each(posts.tags) WHERE tags IS NOT NULL """ ] params = [] if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query_parts.append( """ GROUP BY json_each.value, sentiment ) SELECT topic, SUM(count) as total_count, SUM(CASE WHEN sentiment = 'positive' THEN count ELSE 0 END) as positive_count, SUM(CASE WHEN sentiment = 'negative' THEN count ELSE 0 END) as negative_count, SUM(CASE WHEN sentiment = 'neutral' THEN count ELSE 0 END) as neutral_count, SUM(CASE WHEN sentiment = 'critical' THEN count ELSE 0 END) as critical_count FROM topic_data GROUP BY topic ORDER BY total_count DESC LIMIT ? """ ) params.append(limit) query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True) for topic in result: total = topic["total_count"] topic["positive_percent"] = (topic["positive_count"] / total) * 100 if total > 0 else 0 topic["negative_percent"] = (topic["negative_count"] / total) * 100 if total > 0 else 0 topic["neutral_percent"] = (topic["neutral_count"] / total) * 100 if total > 0 else 0 topic["critical_percent"] = (topic["critical_count"] / total) * 100 if total > 0 else 0 return result except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching trending topics: {str(e)}") async def get_sentiment_over_time( self, date_from: Optional[str] = None, date_to: Optional[str] = None, platform: Optional[str] = None ) -> List[Dict[str, Any]]: """Get sentiment trends over time.""" try: date_range_query = "" if date_from and date_to: date_range_query = f""" WITH RECURSIVE date_range(date) AS ( SELECT date('{date_from}') UNION ALL SELECT date(date, '+1 day') FROM date_range WHERE date < date('{date_to}') ) SELECT date as post_date FROM date_range """ else: days_ago = (datetime.now() - timedelta(days=30)).isoformat() date_range_query = f""" WITH RECURSIVE date_range(date) AS ( SELECT date('{days_ago}') UNION ALL SELECT date(date, '+1 day') FROM date_range WHERE date < date('now') ) SELECT date as post_date FROM date_range """ query_parts = [ f""" WITH dates AS ( {date_range_query} ) SELECT dates.post_date, COALESCE(SUM(CASE WHEN sentiment = 'positive' THEN 1 ELSE 0 END), 0) as positive_count, COALESCE(SUM(CASE WHEN sentiment = 'negative' THEN 1 ELSE 0 END), 0) as negative_count, COALESCE(SUM(CASE WHEN sentiment = 'neutral' THEN 1 ELSE 0 END), 0) as neutral_count, COALESCE(SUM(CASE WHEN sentiment = 'critical' THEN 1 ELSE 0 END), 0) as critical_count, COUNT(posts.post_id) as total_count FROM dates LEFT JOIN posts ON date(posts.post_timestamp) = dates.post_date """ ] params = [] if platform: query_parts.append("AND posts.platform = ?") params.append(platform) query_parts.append("GROUP BY dates.post_date ORDER BY dates.post_date") query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True) for day in result: total = day["total_count"] day["positive_percent"] = (day["positive_count"] / total) * 100 if total > 0 else 0 day["negative_percent"] = (day["negative_count"] / total) * 100 if total > 0 else 0 day["neutral_percent"] = (day["neutral_count"] / total) * 100 if total > 0 else 0 day["critical_percent"] = (day["critical_count"] / total) * 100 if total > 0 else 0 return result except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching sentiment over time: {str(e)}") async def get_influential_posts( self, sentiment: Optional[str] = None, limit: int = 5, date_from: Optional[str] = None, date_to: Optional[str] = None ) -> List[Dict[str, Any]]: """Get most influential posts by engagement, optionally filtered by sentiment.""" try: query_parts = [ """ SELECT *, (COALESCE(engagement_reply_count, 0) + COALESCE(engagement_retweet_count, 0) + COALESCE(engagement_like_count, 0) + COALESCE(engagement_bookmark_count, 0)) as total_engagement FROM posts WHERE 1=1 """ ] params = [] if sentiment: query_parts.append("AND sentiment = ?") params.append(sentiment) if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query_parts.extend(["ORDER BY total_engagement DESC", "LIMIT ?"]) params.append(limit) query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True) processed_posts = [] for post in result: post_dict = dict(post) if post_dict.get("media"): try: post_dict["media"] = json.loads(post_dict["media"]) except json.JSONDecodeError: post_dict["media"] = [] if post_dict.get("categories"): try: post_dict["categories"] = json.loads(post_dict["categories"]) except json.JSONDecodeError: post_dict["categories"] = [] if post_dict.get("tags"): try: post_dict["tags"] = json.loads(post_dict["tags"]) except json.JSONDecodeError: post_dict["tags"] = [] post_dict["engagement"] = { "replies": post_dict.pop("engagement_reply_count", 0), "retweets": post_dict.pop("engagement_retweet_count", 0), "likes": post_dict.pop("engagement_like_count", 0), "bookmarks": post_dict.pop("engagement_bookmark_count", 0), "views": post_dict.pop("engagement_view_count", 0), } processed_posts.append(post_dict) return processed_posts except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching influential posts: {str(e)}") async def get_engagement_stats( self, date_from: Optional[str] = None, date_to: Optional[str] = None ) -> Dict[str, Any]: """Get overall engagement statistics.""" try: query_parts = [ """ SELECT AVG(COALESCE(engagement_reply_count, 0)) as avg_replies, AVG(COALESCE(engagement_retweet_count, 0)) as avg_retweets, AVG(COALESCE(engagement_like_count, 0)) as avg_likes, AVG(COALESCE(engagement_bookmark_count, 0)) as avg_bookmarks, AVG(COALESCE(engagement_view_count, 0)) as avg_views, MAX(COALESCE(engagement_reply_count, 0)) as max_replies, MAX(COALESCE(engagement_retweet_count, 0)) as max_retweets, MAX(COALESCE(engagement_like_count, 0)) as max_likes, MAX(COALESCE(engagement_bookmark_count, 0)) as max_bookmarks, MAX(COALESCE(engagement_view_count, 0)) as max_views, COUNT(*) as total_posts, COUNT(DISTINCT user_handle) as unique_authors FROM posts WHERE 1=1 """ ] params = [] if date_from: query_parts.append("AND datetime(post_timestamp) >= datetime(?)") params.append(date_from) if date_to: query_parts.append("AND datetime(post_timestamp) <= datetime(?)") params.append(date_to) query = " ".join(query_parts) result = await social_media_db.execute_query(query, tuple(params), fetch=True, fetch_one=True) if not result: return {"avg_engagement": 0, "total_posts": 0, "unique_authors": 0} result_dict = dict(result) result_dict["avg_engagement"] = ( result_dict["avg_replies"] + result_dict["avg_retweets"] + result_dict["avg_likes"] + result_dict["avg_bookmarks"] ) platform_query_parts = [ """ SELECT platform, COUNT(*) as post_count FROM posts WHERE 1=1 """ ] if date_from: platform_query_parts.append("AND datetime(post_timestamp) >= datetime(?)") if date_to: platform_query_parts.append("AND datetime(post_timestamp) <= datetime(?)") platform_query_parts.extend([ "GROUP BY platform", "ORDER BY post_count DESC", "LIMIT 10" ]) platforms = await social_media_db.execute_query( " ".join(platform_query_parts), tuple(params), fetch=True ) result_dict["platforms"] = platforms return result_dict except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching engagement stats: {str(e)}") social_media_service = SocialMediaService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/task_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/task_service.py
from typing import List, Optional, Dict, Any from datetime import datetime, timedelta from fastapi import HTTPException from services.db_service import tasks_db from models.tasks_schemas import TASK_TYPES class TaskService: """Service for managing scheduled tasks.""" async def get_tasks(self, include_disabled: bool = False) -> List[Dict[str, Any]]: """Get all tasks with optional filtering.""" try: if include_disabled: query = """ SELECT id, name, description, command, task_type, frequency, frequency_unit, enabled, last_run, created_at FROM tasks ORDER BY name """ params = () else: query = """ SELECT id, name, description, command, task_type, frequency, frequency_unit, enabled, last_run, created_at FROM tasks WHERE enabled = 1 ORDER BY name """ params = () tasks = await tasks_db.execute_query(query, params, fetch=True) for task in tasks: task["enabled"] = bool(task.get("enabled", 0)) return tasks except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching tasks: {str(e)}") async def get_task(self, task_id: int) -> Dict[str, Any]: """Get a specific task by ID.""" try: query = """ SELECT id, name, description, command, task_type, frequency, frequency_unit, enabled, last_run, created_at FROM tasks WHERE id = ? """ task = await tasks_db.execute_query(query, (task_id,), fetch=True, fetch_one=True) if not task: raise HTTPException(status_code=404, detail="Task not found") task["enabled"] = bool(task.get("enabled", 0)) return task except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching task: {str(e)}") async def check_task_exists(self, task_type: str) -> Optional[Dict[str, Any]]: """Check if a task with the given type already exists.""" try: query = """ SELECT id, name, task_type FROM tasks WHERE task_type = ? LIMIT 1 """ task = await tasks_db.execute_query(query, (task_type,), fetch=True, fetch_one=True) return task except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error checking task existence: {str(e)}") async def create_task( self, name: str, task_type: str, frequency: int, frequency_unit: str, description: Optional[str] = None, enabled: bool = True, ) -> Dict[str, Any]: """Create a new task.""" try: existing_task = await self.check_task_exists(task_type) if existing_task: raise HTTPException( status_code=409, detail=f"A task with type '{task_type}' already exists (Task: '{existing_task['name']}', ID: {existing_task['id']}). Please edit the existing task instead of creating a duplicate.", ) if task_type not in TASK_TYPES: raise HTTPException( status_code=400, detail=f"Invalid task type: '{task_type}'. Please select a valid task type from the available options." ) command = TASK_TYPES[task_type]["command"] current_time = datetime.now().isoformat() query = """ INSERT INTO tasks (name, description, command, task_type, frequency, frequency_unit, enabled, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """ params = ( name, description, command, task_type, frequency, frequency_unit, 1 if enabled else 0, current_time, ) task_id = await tasks_db.execute_query(query, params) return await self.get_task(task_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error creating task: {str(e)}") async def update_task(self, task_id: int, updates: Dict[str, Any]) -> Dict[str, Any]: """Update an existing task.""" try: current_task = await self.get_task(task_id) if "task_type" in updates and updates["task_type"] != current_task["task_type"]: existing_task = await self.check_task_exists(updates["task_type"]) if existing_task and existing_task["id"] != task_id: raise HTTPException( status_code=409, detail=f"A task with type '{updates['task_type']}' already exists (Task: '{existing_task['name']}', ID: {existing_task['id']}). You cannot have duplicate task types in the system.", ) if updates["task_type"] in TASK_TYPES: updates["command"] = TASK_TYPES[updates["task_type"]]["command"] allowed_fields = [ "name", "description", "command", "task_type", "frequency", "frequency_unit", "enabled", ] set_clauses = [] params = [] for field, value in updates.items(): if field in allowed_fields: if field == "enabled": value = 1 if value else 0 set_clauses.append(f"{field} = ?") params.append(value) if not set_clauses: return await self.get_task(task_id) params.append(task_id) update_query = f""" UPDATE tasks SET {", ".join(set_clauses)} WHERE id = ? """ await tasks_db.execute_query(update_query, tuple(params)) return await self.get_task(task_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error updating task: {str(e)}") async def delete_task(self, task_id: int) -> Dict[str, str]: """Delete a task.""" try: task = await self.get_task(task_id) query = """ DELETE FROM tasks WHERE id = ? """ await tasks_db.execute_query(query, (task_id,)) return {"message": f"Task '{task['name']}' has been deleted"} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting task: {str(e)}") async def toggle_task(self, task_id: int, enable: bool) -> Dict[str, Any]: """Enable or disable a task.""" try: query = """ UPDATE tasks SET enabled = ? WHERE id = ? """ await tasks_db.execute_query(query, (1 if enable else 0, task_id)) return await self.get_task(task_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error updating task: {str(e)}") async def get_task_executions(self, task_id: Optional[int] = None, page: int = 1, per_page: int = 10) -> Dict[str, Any]: """Get paginated task executions.""" try: offset = (page - 1) * per_page if task_id: count_query = """ SELECT COUNT(*) as count FROM task_executions WHERE task_id = ? """ count_params = (task_id,) query = """ SELECT id, task_id, start_time, end_time, status, error_message, output FROM task_executions WHERE task_id = ? ORDER BY start_time DESC LIMIT ? OFFSET ? """ params = (task_id, per_page, offset) else: count_query = """ SELECT COUNT(*) as count FROM task_executions """ count_params = () query = """ SELECT id, task_id, start_time, end_time, status, error_message, output FROM task_executions ORDER BY start_time DESC LIMIT ? OFFSET ? """ params = (per_page, offset) count_result = await tasks_db.execute_query(count_query, count_params, fetch=True, fetch_one=True) total_items = count_result.get("count", 0) if count_result else 0 executions = await tasks_db.execute_query(query, params, fetch=True) for execution in executions: if execution.get("task_id"): try: task = await self.get_task(execution["task_id"]) execution["task_name"] = task.get("name", "Unknown Task") except Exception as _: execution["task_name"] = "Unknown Task" total_pages = (total_items + per_page - 1) // per_page if total_items > 0 else 0 has_next = page < total_pages has_prev = page > 1 return { "items": executions, "total": total_items, "page": page, "per_page": per_page, "total_pages": total_pages, "has_next": has_next, "has_prev": has_prev, } except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching task executions: {str(e)}") async def get_pending_tasks(self) -> List[Dict[str, Any]]: """Get tasks that are due to run.""" try: query = """ SELECT id, name, description, command, task_type, frequency, frequency_unit, enabled, last_run FROM tasks WHERE enabled = 1 AND ( last_run IS NULL OR CASE frequency_unit WHEN 'minutes' THEN datetime(last_run, '+' || frequency || ' minutes') <= datetime('now', 'localtime') WHEN 'hours' THEN datetime(last_run, '+' || frequency || ' hours') <= datetime('now', 'localtime') WHEN 'days' THEN datetime(last_run, '+' || frequency || ' days') <= datetime('now', 'localtime') ELSE datetime(last_run, '+' || frequency || ' seconds') <= datetime('now', 'localtime') END ) ORDER BY last_run """ tasks = await tasks_db.execute_query(query, fetch=True) for task in tasks: task["enabled"] = bool(task.get("enabled", 0)) return tasks except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching pending tasks: {str(e)}") async def get_stats(self) -> Dict[str, Any]: """Get task statistics.""" try: task_query = """ SELECT COUNT(*) as total_tasks, SUM(CASE WHEN enabled = 1 THEN 1 ELSE 0 END) as active_tasks, SUM(CASE WHEN enabled = 0 THEN 1 ELSE 0 END) as disabled_tasks, SUM(CASE WHEN last_run IS NULL THEN 1 ELSE 0 END) as never_run_tasks FROM tasks """ task_stats = await tasks_db.execute_query(task_query, fetch=True, fetch_one=True) cutoff_date = (datetime.now() - timedelta(days=7)).isoformat() exec_query = """ SELECT COUNT(*) as total_executions, COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) as successful_executions, COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) as failed_executions, COALESCE(SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END), 0) as running_executions, COALESCE(AVG(CASE WHEN end_time IS NOT NULL THEN (julianday(end_time) - julianday(start_time)) * 86400.0 ELSE NULL END), 0) as avg_execution_time_seconds FROM task_executions WHERE start_time >= ? """ exec_stats = await tasks_db.execute_query(exec_query, (cutoff_date,), fetch=True, fetch_one=True) return {"tasks": task_stats or {}, "executions": exec_stats or {}} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching task statistics: {str(e)}") task_service = TaskService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/__init__.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/__init__.py
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/internal_session_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/internal_session_service.py
from typing import Optional, Dict, Any from fastapi import HTTPException import json from datetime import datetime from db.config import get_db_path from db.agent_config_v2 import INITIAL_SESSION_STATE import sqlite3 from contextlib import contextmanager @contextmanager def get_db_connection(db_name: str): """Get a fresh database connection each time.""" db_path = get_db_path(db_name) conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row try: yield conn finally: conn.close() class SessionService: """Service for managing internal session operations.""" @staticmethod def get_session(session_id: str) -> Dict[str, Any]: try: with get_db_connection("internal_sessions_db") as conn: cursor = conn.cursor() query = """ SELECT session_id, state, created_at FROM session_state WHERE session_id = ? """ cursor.execute(query, (session_id,)) session = cursor.fetchone() if not session: return SessionService._initialize_session(session_id) session_dict = dict(session) if session_dict.get("state"): try: session_dict["state"] = json.loads(session_dict["state"]) except json.JSONDecodeError: session_dict["state"] = {} return session_dict except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching session: {str(e)}") @staticmethod def _initialize_session(session_id: str) -> Dict[str, Any]: try: with get_db_connection("internal_sessions_db") as conn: cursor = conn.cursor() state_json = json.dumps(INITIAL_SESSION_STATE) insert_query = """ INSERT INTO session_state (session_id, state, created_at) VALUES (?, ?, ?) """ current_time = datetime.now().isoformat() cursor.execute(insert_query, (session_id, state_json, current_time)) conn.commit() return {"session_id": session_id, "state": INITIAL_SESSION_STATE, "created_at": current_time} except Exception as e: raise HTTPException(status_code=500, detail=f"Error initializing session: {str(e)}") @staticmethod def save_session(session_id: str, state: Dict[str, Any]) -> Dict[str, Any]: try: state_json = json.dumps(state) with get_db_connection("internal_sessions_db") as conn: cursor = conn.cursor() conn.execute("BEGIN IMMEDIATE") existing_query = "SELECT session_id FROM session_state WHERE session_id = ?" cursor.execute(existing_query, (session_id,)) existing_session = cursor.fetchone() if existing_session: update_query = "UPDATE session_state SET state = ? WHERE session_id = ?" cursor.execute(update_query, (state_json, session_id)) else: insert_query = "INSERT INTO session_state (session_id, state, created_at) VALUES (?, ?, ?)" current_time = datetime.now().isoformat() cursor.execute(insert_query, (session_id, state_json, current_time)) conn.commit() return SessionService.get_session(session_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error saving session: {str(e)}") @staticmethod def delete_session(session_id: str) -> Dict[str, str]: try: with get_db_connection("internal_sessions_db") as conn: cursor = conn.cursor() existing_query = "SELECT session_id FROM session_state WHERE session_id = ?" cursor.execute(existing_query, (session_id,)) existing_session = cursor.fetchone() if not existing_session: raise HTTPException(status_code=404, detail="Session not found") delete_query = "DELETE FROM session_state WHERE session_id = ?" cursor.execute(delete_query, (session_id,)) conn.commit() return {"message": f"Session with ID {session_id} successfully deleted"} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting session: {str(e)}") @staticmethod def list_sessions(page: int = 1, per_page: int = 10, search: Optional[str] = None) -> Dict[str, Any]: try: with get_db_connection("internal_sessions_db") as conn: cursor = conn.cursor() offset = (page - 1) * per_page query_parts = [ "SELECT session_id, created_at", "FROM session_state", ] query_params = [] if search: query_parts.append("WHERE session_id LIKE ?") search_param = f"%{search}%" query_params.append(search_param) count_query = " ".join(query_parts).replace( "SELECT session_id, created_at", "SELECT COUNT(*)", ) cursor.execute(count_query, tuple(query_params)) total_count = cursor.fetchone()[0] query_parts.append("ORDER BY created_at DESC") query_parts.append("LIMIT ? OFFSET ?") query_params.extend([per_page, offset]) sessions_query = " ".join(query_parts) cursor.execute(sessions_query, tuple(query_params)) sessions = [dict(row) for row in cursor.fetchall()] total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 0 has_next = page < total_pages has_prev = page > 1 return { "items": sessions, "total": total_count, "page": page, "per_page": per_page, "total_pages": total_pages, "has_next": has_next, "has_prev": has_prev, } except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error listing sessions: {str(e)}")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/db_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/db_service.py
import os from typing import Dict, List, Any, Tuple, Union from fastapi import HTTPException from contextlib import contextmanager import sqlite3 from db.config import get_db_path @contextmanager def db_connection(db_path: str): """Context manager for database connections.""" if not os.path.exists(db_path): raise HTTPException(status_code=404, detail=f"Database {db_path} not found. Initialize the database first.") conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row try: yield conn finally: conn.close() class DatabaseService: """Service for managing database connections and operations.""" def __init__(self, db_name: str): """ Initialize the database service. Args: db_name: Name of the database (sources_db, tracking_db, etc.) """ self.db_path = get_db_path(db_name) async def execute_query( self, query: str, params: Tuple = (), fetch: bool = False, fetch_one: bool = False ) -> Union[List[Dict[str, Any]], Dict[str, Any], int]: """Execute a query with error handling for FastAPI.""" try: with db_connection(self.db_path) as conn: cursor = conn.cursor() cursor.execute(query, params) if fetch_one: result = cursor.fetchone() return dict(result) if result else None elif fetch: return [dict(row) for row in cursor.fetchall()] else: conn.commit() return cursor.lastrowid except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Database error: {str(e)}") async def execute_write_many(self, query: str, params_list: List[Tuple]) -> int: """Execute multiple write operations in a single transaction.""" try: with db_connection(self.db_path) as conn: cursor = conn.cursor() cursor.executemany(query, params_list) conn.commit() return cursor.rowcount except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Database error: {str(e)}") sources_db = DatabaseService(db_name="sources_db") tracking_db = DatabaseService(db_name="tracking_db") podcasts_db = DatabaseService(db_name="podcasts_db") tasks_db = DatabaseService(db_name="tasks_db") social_media_db = DatabaseService(db_name="social_media_db")
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_service.py
import os import json from typing import List, Dict, Optional, Any from datetime import datetime from fastapi import HTTPException, UploadFile from services.db_service import podcasts_db import math AUDIO_DIR = "podcasts/audio" IMAGE_DIR = "podcasts/images" class PodcastService: """Service for managing podcast operations with the new database structure.""" def __init__(self): """Initialize the podcast service with directories.""" os.makedirs(AUDIO_DIR, exist_ok=True) os.makedirs(IMAGE_DIR, exist_ok=True) async def get_podcasts( self, page: int = 1, per_page: int = 10, search: str = None, date_from: str = None, date_to: str = None, language_code: str = None, tts_engine: str = None, has_audio: bool = None, ) -> Dict[str, Any]: """ Get a paginated list of podcasts with optional filtering. """ try: offset = (page - 1) * per_page count_query = "SELECT COUNT(*) as count FROM podcasts" query = """ SELECT id, title, date, audio_generated, audio_path, banner_img_path, language_code, tts_engine, created_at FROM podcasts """ where_conditions = [] params = [] if search: where_conditions.append("(title LIKE ?)") search_param = f"%{search}%" params.append(search_param) if date_from: where_conditions.append("date >= ?") params.append(date_from) if date_to: where_conditions.append("date <= ?") params.append(date_to) if language_code: where_conditions.append("language_code = ?") params.append(language_code) if tts_engine: where_conditions.append("tts_engine = ?") params.append(tts_engine) if has_audio is not None: where_conditions.append("audio_generated = ?") params.append(1 if has_audio else 0) if where_conditions: where_clause = " WHERE " + " AND ".join(where_conditions) query += where_clause count_query += where_clause query += " ORDER BY date DESC, created_at DESC" query += " LIMIT ? OFFSET ?" params.extend([per_page, offset]) total_result = await podcasts_db.execute_query(count_query, tuple(params[:-2] if params else ()), fetch=True, fetch_one=True) total_items = total_result.get("count", 0) if total_result else 0 total_pages = math.ceil(total_items / per_page) if total_items > 0 else 0 podcasts = await podcasts_db.execute_query(query, tuple(params), fetch=True) for podcast in podcasts: podcast["audio_generated"] = bool(podcast.get("audio_generated", 0)) if podcast.get("banner_img_path"): podcast["banner_img"] = podcast.get("banner_img_path") else: podcast["banner_img"] = None podcast.pop("banner_img_path", None) podcast["identifier"] = str(podcast.get("id", "")) has_next = page < total_pages has_prev = page > 1 return { "items": podcasts, "total": total_items, "page": page, "per_page": per_page, "total_pages": total_pages, "has_next": has_next, "has_prev": has_prev, } except Exception as e: raise HTTPException(status_code=500, detail=f"Error loading podcasts: {str(e)}") async def get_podcast(self, podcast_id: int) -> Optional[Dict[str, Any]]: """Get a specific podcast by ID without content.""" try: query = """ SELECT id, title, date, audio_generated, audio_path, banner_img_path, language_code, tts_engine, created_at, banner_images FROM podcasts WHERE id = ? """ podcast = await podcasts_db.execute_query(query, (podcast_id,), fetch=True, fetch_one=True) if not podcast: raise HTTPException(status_code=404, detail="Podcast not found") podcast["audio_generated"] = bool(podcast.get("audio_generated", 0)) if podcast.get("banner_img_path"): podcast["banner_img"] = podcast.get("banner_img_path") else: podcast["banner_img"] = None podcast.pop("banner_img_path", None) podcast["identifier"] = str(podcast.get("id", "")) sources_query = "SELECT sources_json FROM podcasts WHERE id = ?" sources_result = await podcasts_db.execute_query(sources_query, (podcast_id,), fetch=True, fetch_one=True) sources = [] if sources_result and sources_result.get("sources_json"): try: parsed_sources = json.loads(sources_result["sources_json"]) if isinstance(parsed_sources, list): sources = parsed_sources else: sources = [parsed_sources] except json.JSONDecodeError: sources = [] podcast["sources"] = sources try: banner_images = json.loads(podcast.get("banner_images", "[]")) except json.JSONDecodeError: banner_images = [] podcast["banner_images"] = banner_images return podcast except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error loading podcast: {str(e)}") async def get_podcast_by_identifier(self, identifier: str) -> Optional[Dict[str, Any]]: """Get a specific podcast by string identifier (which is actually the ID).""" try: try: podcast_id = int(identifier) except ValueError: raise HTTPException(status_code=404, detail="Invalid podcast identifier") return await self.get_podcast(podcast_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error loading podcast: {str(e)}") async def get_podcast_content(self, podcast_id: int) -> Dict[str, Any]: """Get the content of a specific podcast.""" try: query = """ SELECT content_json FROM podcasts WHERE id = ? """ result = await podcasts_db.execute_query(query, (podcast_id,), fetch=True, fetch_one=True) if not result or not result.get("content_json"): raise HTTPException(status_code=404, detail="Podcast content not found") try: content = json.loads(result["content_json"]) return content except json.JSONDecodeError: raise HTTPException(status_code=500, detail="Invalid podcast content format") except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error loading podcast content: {str(e)}") async def get_podcast_audio_url(self, podcast: Dict[str, Any]) -> Optional[str]: """Get the URL for the podcast audio file if available.""" if podcast.get("audio_generated") and podcast.get("audio_path"): return f"/audio/{podcast.get('audio_path')}" return None async def get_podcast_formats(self) -> List[str]: """Get list of available podcast formats for filtering.""" # Note: This may need to be adapted if format field is added return ["daily", "weekly", "tech", "news"] async def get_language_codes(self) -> List[str]: try: query = """ SELECT DISTINCT language_code FROM podcasts WHERE language_code IS NOT NULL """ results = await podcasts_db.execute_query(query, (), fetch=True) language_codes = [result["language_code"] for result in results if result["language_code"]] if "en" not in language_codes: language_codes.append("en") return sorted(language_codes) except Exception as _: return ["en"] async def get_tts_engines(self) -> List[str]: """Get list of available TTS engines for filtering.""" try: query = """ SELECT DISTINCT tts_engine FROM podcasts WHERE tts_engine IS NOT NULL """ results = await podcasts_db.execute_query(query, (), fetch=True) tts_engines = [result["tts_engine"] for result in results if result["tts_engine"]] default_engines = ["elevenlabs", "openai", "kokoro"] for engine in default_engines: if engine not in tts_engines: tts_engines.append(engine) return sorted(tts_engines) except Exception as e: return ["elevenlabs", "openai", "kokoro"] async def create_podcast( self, title: str, date: str, content: Dict[str, Any], sources: List[str] = None, language_code: str = "en", tts_engine: str = "kokoro" ) -> Dict[str, Any]: """Create a new podcast in the database.""" try: content_json = json.dumps(content) sources_json = json.dumps(sources) if sources else None current_time = datetime.now().isoformat() query = """ INSERT INTO podcasts (title, date, content_json, audio_generated, sources_json, language_code, tts_engine, created_at) VALUES (?, ?, ?, 0, ?, ?, ?, ?) """ params = (title, date, content_json, sources_json, language_code, tts_engine, current_time) podcast_id = await podcasts_db.execute_query(query, params) return await self.get_podcast(podcast_id) except Exception as e: raise HTTPException(status_code=500, detail=f"Error creating podcast: {str(e)}") async def update_podcast(self, podcast_id: int, podcast_data: Dict[str, Any]) -> Dict[str, Any]: """Update podcast metadata and content.""" try: existing = await self.get_podcast(podcast_id) if not existing: raise HTTPException(status_code=404, detail="Podcast not found") fields = [] params = [] if "title" in podcast_data: fields.append("title = ?") params.append(podcast_data["title"]) if "date" in podcast_data: fields.append("date = ?") params.append(podcast_data["date"]) if "content" in podcast_data and isinstance(podcast_data["content"], dict): fields.append("content_json = ?") params.append(json.dumps(podcast_data["content"])) if "audio_generated" in podcast_data: fields.append("audio_generated = ?") params.append(1 if podcast_data["audio_generated"] else 0) if "audio_path" in podcast_data: fields.append("audio_path = ?") params.append(podcast_data["audio_path"]) if "banner_img_path" in podcast_data: fields.append("banner_img_path = ?") params.append(podcast_data["banner_img_path"]) if "sources" in podcast_data: fields.append("sources_json = ?") params.append(json.dumps(podcast_data["sources"])) if "language_code" in podcast_data: fields.append("language_code = ?") params.append(podcast_data["language_code"]) if "tts_engine" in podcast_data: fields.append("tts_engine = ?") params.append(podcast_data["tts_engine"]) if not fields: return existing params.append(podcast_id) query = f""" UPDATE podcasts SET {", ".join(fields)} WHERE id = ? """ await podcasts_db.execute_query(query, tuple(params)) return await self.get_podcast(podcast_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error updating podcast: {str(e)}") async def delete_podcast(self, podcast_id: int, delete_assets: bool = False) -> bool: """Delete a podcast from the database.""" try: existing = await self.get_podcast(podcast_id) if not existing: raise HTTPException(status_code=404, detail="Podcast not found") query = "DELETE FROM podcasts WHERE id = ?" result = await podcasts_db.execute_query(query, (podcast_id,)) if delete_assets: if existing.get("audio_path"): audio_path = os.path.join(AUDIO_DIR, existing["audio_path"]) if os.path.exists(audio_path): os.remove(audio_path) if existing.get("banner_img_path"): img_path = os.path.join(IMAGE_DIR, existing["banner_img_path"]) if os.path.exists(img_path): os.remove(img_path) return result > 0 except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting podcast: {str(e)}") async def upload_podcast_audio(self, podcast_id: int, file: UploadFile) -> Dict[str, Any]: """Upload an audio file for a podcast.""" try: await self.get_podcast(podcast_id) filename = f"podcast_{podcast_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}" if file.filename: ext = os.path.splitext(file.filename)[1] filename = f"{filename}{ext}" else: filename = f"{filename}.mp3" file_path = os.path.join(AUDIO_DIR, filename) contents = await file.read() with open(file_path, "wb") as f: f.write(contents) update_data = {"audio_generated": True, "audio_path": filename} return await self.update_podcast(podcast_id, update_data) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error uploading audio: {str(e)}") async def upload_podcast_banner(self, podcast_id: int, file: UploadFile) -> Dict[str, Any]: """Upload a banner image for a podcast.""" try: await self.get_podcast(podcast_id) filename = f"banner_{podcast_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}" if file.filename: ext = os.path.splitext(file.filename)[1] filename = f"{filename}{ext}" else: filename = f"{filename}.jpg" file_path = os.path.join(IMAGE_DIR, filename) contents = await file.read() with open(file_path, "wb") as f: f.write(contents) update_data = {"banner_img_path": filename} return await self.update_podcast(podcast_id, update_data) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error uploading banner: {str(e)}") podcast_service = PodcastService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_config_service.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_config_service.py
from typing import List, Optional, Dict, Any from datetime import datetime from fastapi import HTTPException from services.db_service import tasks_db class PodcastConfigService: """Service for managing podcast configurations.""" async def get_all_configs(self, active_only: bool = False) -> List[Dict[str, Any]]: """Get all podcast configurations with optional filtering.""" try: if active_only: query = """ SELECT id, name, description, prompt, time_range_hours, limit_articles, is_active, tts_engine, language_code, podcast_script_prompt, image_prompt, created_at, updated_at FROM podcast_configs WHERE is_active = 1 ORDER BY name """ params = () else: query = """ SELECT id, name, description, prompt, time_range_hours, limit_articles, is_active, tts_engine, language_code, podcast_script_prompt, image_prompt, created_at, updated_at FROM podcast_configs ORDER BY name """ params = () configs = await tasks_db.execute_query(query, params, fetch=True) for config in configs: config["is_active"] = bool(config.get("is_active", 0)) return configs except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching podcast configurations: {str(e)}") async def get_config(self, config_id: int) -> Dict[str, Any]: """Get a specific podcast configuration by ID.""" try: query = """ SELECT id, name, description, prompt, time_range_hours, limit_articles, is_active, tts_engine, language_code, podcast_script_prompt, image_prompt, created_at, updated_at FROM podcast_configs WHERE id = ? """ config = await tasks_db.execute_query(query, (config_id,), fetch=True, fetch_one=True) if not config: raise HTTPException(status_code=404, detail="Podcast configuration not found") config["is_active"] = bool(config.get("is_active", 0)) return config except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error fetching podcast configuration: {str(e)}") async def create_config( self, name: str, prompt: str, description: Optional[str] = None, time_range_hours: int = 24, limit_articles: int = 20, is_active: bool = True, tts_engine: str = "kokoro", language_code: str = "en", podcast_script_prompt: Optional[str] = None, image_prompt: Optional[str] = None, ) -> Dict[str, Any]: """Create a new podcast configuration.""" try: current_time = datetime.now().isoformat() query = """ INSERT INTO podcast_configs (name, description, prompt, time_range_hours, limit_articles, is_active, tts_engine, language_code, podcast_script_prompt, image_prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ params = ( name, description, prompt, time_range_hours, limit_articles, 1 if is_active else 0, tts_engine, language_code, podcast_script_prompt, image_prompt, current_time, current_time, ) config_id = await tasks_db.execute_query(query, params) return await self.get_config(config_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error creating podcast configuration: {str(e)}") async def update_config(self, config_id: int, updates: Dict[str, Any]) -> Dict[str, Any]: """Update an existing podcast configuration.""" try: allowed_fields = [ "name", "description", "prompt", "time_range_hours", "limit_articles", "is_active", "tts_engine", "language_code", "podcast_script_prompt", "image_prompt", ] set_clauses = [] params = [] set_clauses.append("updated_at = ?") params.append(datetime.now().isoformat()) for field, value in updates.items(): if field in allowed_fields: if field == "is_active": value = 1 if value else 0 set_clauses.append(f"{field} = ?") params.append(value) if not set_clauses: return await self.get_config(config_id) params.append(config_id) update_query = f""" UPDATE podcast_configs SET {", ".join(set_clauses)} WHERE id = ? """ await tasks_db.execute_query(update_query, tuple(params)) return await self.get_config(config_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error updating podcast configuration: {str(e)}") async def delete_config(self, config_id: int) -> Dict[str, str]: """Delete a podcast configuration.""" try: config = await self.get_config(config_id) query = """ DELETE FROM podcast_configs WHERE id = ? """ await tasks_db.execute_query(query, (config_id,)) return {"message": f"Podcast configuration '{config['name']}' has been deleted"} except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error deleting podcast configuration: {str(e)}") async def toggle_config(self, config_id: int, enable: bool) -> Dict[str, Any]: """Enable or disable a podcast configuration.""" try: query = """ UPDATE podcast_configs SET is_active = ?, updated_at = ? WHERE id = ? """ current_time = datetime.now().isoformat() await tasks_db.execute_query(query, (1 if enable else 0, current_time, config_id)) return await self.get_config(config_id) except Exception as e: if isinstance(e, HTTPException): raise e raise HTTPException(status_code=500, detail=f"Error updating podcast configuration: {str(e)}") podcast_config_service = PodcastConfigService()
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/browser_crawler.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/browser_crawler.py
from playwright.sync_api import sync_playwright import newspaper import time from typing import Dict, List from datetime import datetime class PlaywrightScraper: def __init__( self, headless: bool = True, timeout: int = 20000, fresh_context_per_url: bool = False, ): self.headless = headless self.timeout = timeout self.fresh_context_per_url = fresh_context_per_url def scrape_urls(self, urls: List[str]) -> List[Dict]: with sync_playwright() as playwright: browser = playwright.chromium.launch( headless=self.headless, args=["--no-sandbox", "--disable-setuid-sandbox"], ) if self.fresh_context_per_url: results = [] for url in urls: result = self._scrape_single_with_new_context(browser, url) results.append(result) else: results = self._scrape_with_reused_page(browser, urls) browser.close() return results def _scrape_with_reused_page(self, browser, urls: List[str]) -> List[Dict]: context = browser.new_context( user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", viewport={"width": 1920, "height": 1080}, ) page = context.new_page() page.set_extra_http_headers( { "Accept-Language": "en-US,en;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", } ) results = [] try: for i, url in enumerate(urls): print(f"Scraping {i+1}/{len(urls)}") result = self._scrape_single_url(page, url) results.append(result) if i < len(urls) - 1: time.sleep(1) finally: context.close() return results def _scrape_single_url(self, page, url: str) -> Dict: max_retries = 0 for attempt in range(max_retries + 1): try: page.goto(url, wait_until="load", timeout=self.timeout) page.wait_for_selector("body", timeout=5000) page.wait_for_timeout(2000) final_url = page.url return self._parse_with_newspaper(url, final_url) except Exception as e: if attempt < max_retries: print(f"Retry {attempt + 1} for {url}") time.sleep(2**attempt) continue else: return { "originalUrl": url, "error": str(e), "success": False, "timestamp": datetime.now().isoformat(), } def _scrape_single_with_new_context(self, browser, url: str) -> Dict: max_retries = 0 for attempt in range(max_retries + 1): context = None try: context = browser.new_context( user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", viewport={"width": 1920, "height": 1080}, ) page = context.new_page() page.set_extra_http_headers( { "Accept-Language": "en-US,en;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", } ) page.goto(url, wait_until="load", timeout=self.timeout) page.wait_for_selector("body", timeout=5000) page.wait_for_timeout(2000) final_url = page.url return self._parse_with_newspaper(url, final_url) except Exception as e: if attempt < max_retries: time.sleep(2**attempt) continue else: return { "originalUrl": url, "error": str(e), "success": False, "timestamp": datetime.now().isoformat(), } finally: if context: context.close() def _parse_with_newspaper(self, original_url: str, final_url: str) -> Dict: try: article = newspaper.article(final_url) return { "original_url": original_url, "final_url": final_url, "title": article.title or "", "authors": article.authors or [], "published_date": article.publish_date.isoformat() if article.publish_date else None, "full_text": article.text or "", "success": True, } except Exception as e: return { "original_url": original_url, "final_url": final_url, "error": f"Newspaper4k parsing failed: {str(e)}", "success": False, } def create_browser_crawler(headless=True, timeout=20000, fresh_context_per_url=False): """Factory function to create a new PlaywrightScraper instance.""" return PlaywrightScraper( headless=headless, timeout=timeout, fresh_context_per_url=fresh_context_per_url )
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/jikan_search.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/jikan_search.py
from agno.agent import Agent import requests import time from typing import List, Dict, Any, Optional import html import json def jikan_search(agent: Agent, query: str) -> str: """ Search for anime information using the Jikan API (MyAnimeList API). This provides anime data, reviews, and recommendations to enhance podcast content. Jikan scrapes public MyAnimeList pages. The service consists of two core parts Args: agent: The agent instance query: The search query Returns: Search results """ print("Jikan Search:", query) try: formatted_query = query.replace(" ", "%20") anime_results = _search_anime(formatted_query) if not anime_results: return "No relevant anime found for this topic. Continuing with other search methods." results = [] for anime in anime_results[:5]: anime_id = anime.get("mal_id") if not anime_id: continue anime_details = _get_anime_details(anime_id) if anime_details: results.append(anime_details) time.sleep(0.5) if not results: return "No detailed anime information could be retrieved. Continuing with other search methods." return f"Found {len(results)} anime titles related to your topic. results {json.dumps(results, indent=2)}." except Exception as e: return f"Error in anime search: {str(e)}. Continuing with other search methods." def _search_anime(query: str) -> List[Dict[str, Any]]: try: search_url = f"https://api.jikan.moe/v4/anime?q={query}&sfw=true&order_by=popularity&sort=asc&limit=10" response = requests.get(search_url) if response.status_code == 429: time.sleep(0.5) response = requests.get(search_url) if response.status_code != 200: return [] data = response.json() if "data" not in data: return [] return data["data"] except Exception as _: return [] def _get_anime_details(anime_id: int) -> Optional[Dict[str, Any]]: try: details_url = f"https://api.jikan.moe/v4/anime/{anime_id}/full" details_response = requests.get(details_url) if details_response.status_code == 429: time.sleep(0.5) details_response = requests.get(details_url) if details_response.status_code != 200: return None details_data = details_response.json() if "data" not in details_data: return None anime = details_data["data"] return _format_anime_info(anime) except Exception as _: return None def _get_anime_recommendations(anime_id: int) -> List[Dict[str, Any]]: try: recs_url = f"https://api.jikan.moe/v4/anime/{anime_id}/recommendations" recs_response = requests.get(recs_url) if recs_response.status_code == 429: time.sleep(0.5) recs_response = requests.get(recs_url) if recs_response.status_code != 200: return [] recs_data = recs_response.json() if "data" not in recs_data: return [] recommendations = [] for rec in recs_data["data"][:5]: if "entry" in rec: title = rec["entry"].get("title", "") if title: recommendations.append(title) return recommendations except Exception as _: return [] def _format_anime_info(anime: Dict[str, Any]) -> Dict[str, Any]: try: mal_id = anime.get("mal_id") title = anime.get("title", "Unknown Anime") title_english = anime.get("title_english") if title_english and title_english != title: title_display = f"{title} ({title_english})" else: title_display = title url = anime.get("url", f"https://myanimelist.net/anime/{mal_id}") synopsis = anime.get("synopsis", "No synopsis available.") synopsis = html.unescape(synopsis) episodes = anime.get("episodes", "Unknown") status = anime.get("status", "Unknown") aired_string = anime.get("aired", {}).get("string", "Unknown") score = anime.get("score", "N/A") scored_by = anime.get("scored_by", 0) rank = anime.get("rank", "N/A") popularity = anime.get("popularity", "N/A") studios = [] for studio in anime.get("studios", []): if "name" in studio: studios.append(studio["name"]) studio_text = ", ".join(studios) if studios else "Unknown" genres = [] for genre in anime.get("genres", []): if "name" in genre: genres.append(genre["name"]) genre_text = ", ".join(genres) if genres else "Unknown" themes = [] for theme in anime.get("themes", []): if "name" in theme: themes.append(theme["name"]) demographics = [] for demo in anime.get("demographics", []): if "name" in demo: demographics.append(demo["name"]) content = f"Title: {title_display}\n" content += f"Score: {score} (rated by {scored_by:,} users)\n" content += f"Rank: {rank}, Popularity: {popularity}\n" content += f"Episodes: {episodes}\n" content += f"Status: {status}\n" content += f"Aired: {aired_string}\n" content += f"Studio: {studio_text}\n" content += f"Genres: {genre_text}\n" if themes: content += f"Themes: {', '.join(themes)}\n" if demographics: content += f"Demographics: {', '.join(demographics)}\n" content += f"\nSynopsis:\n{synopsis}\n" if mal_id: recommendations = _get_anime_recommendations(mal_id) if recommendations: content += f"\nSimilar Anime: {', '.join(recommendations)}\n" summary = f"{title_display} - {genre_text} anime with {episodes} episodes. " summary += f"Rating: {score}/10. " if synopsis: short_synopsis = synopsis[:150] + "..." if len(synopsis) > 150 else synopsis summary += short_synopsis categories = ["anime", "japanese animation", "entertainment"] if genres: categories.extend(genres[:5]) if themes: categories.extend(themes[:2]) return { "id": f"jikan_{mal_id}", "title": f"{title_display} (Anime)", "url": url, "published_date": aired_string.split(" to ")[0] if " to " in aired_string else aired_string, "description": content, "source_id": "jikan", "source_name": "MyAnimeList", "categories": categories, "is_scrapping_required": False, } except Exception as _: return { "id": f"jikan_{anime.get('mal_id', 'unknown')}", "title": f"{anime.get('title', 'Unknown Anime')} (Anime)", "url": anime.get("url", "https://myanimelist.net"), "published_date": None, "description": anime.get("synopsis", "No information available."), "source_id": "jikan", "source_name": "MyAnimeList", "categories": ["anime", "japanese animation", "entertainment"], "is_scrapping_required": False, } if __name__ == "__main__": print(jikan_search({}, "One Piece anime overview and details"))
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false
Shubhamsaboo/awesome-llm-apps
https://github.com/Shubhamsaboo/awesome-llm-apps/blob/44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/web_search.py
advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/web_search.py
import os import asyncio from typing import List from pydantic import BaseModel, Field from browser_use import Agent as BrowserAgent, Controller, BrowserSession, BrowserProfile from langchain_openai import ChatOpenAI from dotenv import load_dotenv from agno.agent import Agent import json load_dotenv() BROWSER_AGENT_MODEL = "gpt-4o" USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" MAX_STEPS = 15 MAX_ACTIONS_PER_STEP = 5 USER_DATA_DIR = "browsers/playwright_persistent_profile_web" class WebSearchResult(BaseModel): title: str = Field(..., description="The title of the search result") url: str = Field(..., description="The URL of the search result") content: str = Field(..., description="Full content of the source, be elaborate at the same time be concise") class WebSearchResults(BaseModel): results: List[WebSearchResult] = Field(..., description="List of search results") def run_browser_search(agent: Agent, instruction: str) -> str: """ Run browser search to get the results. Args: agent: The agent instance instruction: The instruction to run the browser search, give detailed step by step prompt on how to collect the information. Returns: The results of the browser search """ print("Browser Search Input:", instruction) try: controller = Controller(output_model=WebSearchResults) session_id = agent.session_id recordings_dir = os.path.join("podcasts/recordings", session_id) os.makedirs(recordings_dir, exist_ok=True) headless = True browser_profile = BrowserProfile( user_data_dir=USER_DATA_DIR, headless=headless, viewport={"width": 1280, "height": 800}, record_video_dir=recordings_dir, downloads_path="podcasts/browseruse_downloads", ) browser_session = BrowserSession( browser_profile=browser_profile, headless=headless, disable_security=False, record_video=True, record_video_dir=recordings_dir, ) browser_agent = BrowserAgent( browser_session=browser_session, task=instruction, llm=ChatOpenAI(model=BROWSER_AGENT_MODEL, api_key=os.getenv("OPENAI_API_KEY")), use_vision=False, controller=controller, max_actions_per_step=MAX_ACTIONS_PER_STEP, ) try: try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) history = loop.run_until_complete(browser_agent.run(max_steps=MAX_STEPS)) except RuntimeError: history = asyncio.run(browser_agent.run(max_steps=MAX_STEPS)) result = history.final_result() if result: parsed: WebSearchResults = WebSearchResults.model_validate_json(result) results_list = [ {"title": post.title, "url": post.url, "description": post.content, "is_scrapping_required": False} for post in parsed.results ] return f"is_scrapping_required: False, results: {json.dumps(results_list)}" else: return "No results found, something went wrong with browser based search." except Exception as e: return f"Error running browser search: {e}" finally: pass def main(): return run_browser_search(agent={"session_id": "123"}, instruction="gene therapy") if __name__ == "__main__": print(main())
python
Apache-2.0
44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335
2026-01-04T14:38:15.481187Z
false