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/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/user_source_selection.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/user_source_selection.py | from agno.agent import Agent
from dotenv import load_dotenv
from typing import List
load_dotenv()
def user_source_selection_run(
agent: Agent,
selected_sources: List[int],
) -> str:
"""
User Source Selection that takes the selected sources indices as input and updates the final confirmed sources.
Args:
agent: The agent instance
selected_sources: The selected sources indices
Returns:
Response status
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
for i, src in enumerate(session_state["search_results"]):
if (i+1) in selected_sources:
src["confirmed"] = True
else:
src["confirmed"] = False
SessionService.save_session(session_id, session_state)
return f"Updated selected sources to {selected_sources}."
| 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/session_state_manager.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/session_state_manager.py | from agno.agent import Agent
from datetime import datetime
from db.config import get_podcasts_db_path, DB_PATH
import os
import sqlite3
import json
def _save_podcast_to_database_sync(session_state: dict) -> tuple[bool, str, int]:
try:
if session_state.get("podcast_id"):
return (
True,
f"Podcast already saved with ID: {session_state['podcast_id']}",
session_state["podcast_id"],
)
tts_engine = session_state.get("tts_engine", "openai")
podcast_info = session_state.get("podcast_info", {})
generated_script = session_state.get("generated_script", {})
banner_url = session_state.get("banner_url")
banner_images = json.dumps(session_state.get("banner_images", []))
audio_url = session_state.get("audio_url")
selected_language = session_state.get("selected_language", {"code": "en", "name": "English"})
language_code = selected_language.get("code", "en")
if not generated_script or not isinstance(generated_script, dict):
return (
False,
"Cannot complete podcast: Generated script is missing or invalid.",
None,
)
if "title" not in generated_script:
generated_script["title"] = podcast_info.get("topic", "Untitled Podcast")
if "sections" not in generated_script or not isinstance(generated_script["sections"], list):
return (
False,
"Cannot complete podcast: Generated script is missing required 'sections' array.",
None,
)
sources = []
if "sources" in generated_script and generated_script["sources"]:
for source in generated_script["sources"]:
if isinstance(source, str):
sources.append(source)
elif isinstance(source, dict) and "url" in source:
sources.append(source["url"])
elif isinstance(source, dict) and "link" in source:
sources.append(source["link"])
generated_script["sources"] = sources
db_path = get_podcasts_db_path()
db_directory = DB_PATH
os.makedirs(db_directory, exist_ok=True)
conn = sqlite3.connect(db_path)
content_json = json.dumps(generated_script)
sources_json = json.dumps(sources) if sources else None
current_time = datetime.now().isoformat()
query = """
INSERT INTO podcasts (
title,
date,
content_json,
audio_generated,
audio_path,
banner_img_path,
tts_engine,
language_code,
sources_json,
created_at,
banner_images
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
conn.execute(
query,
(
generated_script.get("title", "Untitled Podcast"),
datetime.now().strftime("%Y-%m-%d"),
content_json,
1 if audio_url else 0,
audio_url,
banner_url,
tts_engine,
language_code,
sources_json,
current_time,
banner_images,
),
)
conn.commit()
cursor = conn.execute("SELECT last_insert_rowid()")
podcast_id = cursor.fetchone()
podcast_id = podcast_id[0] if podcast_id else None
cursor.close()
conn.close()
session_state["podcast_id"] = podcast_id
return True, f"Podcast successfully saved with ID: {podcast_id}", podcast_id
except Exception as e:
print(f"Error saving podcast to database: {e}")
return False, f"Error saving podcast to database: {str(e)}", None
def update_language(agent: Agent, language_code: str) -> str:
"""
Update the podcast language with the specified language code.
This ensures the language is properly tracked for generating content and audio.
Args:
agent: The agent instance
language_code: The language code (e.g., 'en', 'es', 'fr', etc..)
Returns:
Confirmation message
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
language_name = "English"
for lang in session_state.get("available_languages", []):
if lang.get("code") == language_code:
language_name = lang.get("name")
break
session_state["selected_language"] = {
"code": language_code,
"name": language_name,
}
SessionService.save_session(session_id, session_state)
return f"Podcast language set to: {language_name} ({language_code})"
def update_chat_title(agent: Agent, title: str) -> str:
"""
Update the chat title with the specified short title.
Args:
agent: The agent instance
title: The short title to set for the chat
Returns:
Confirmation message
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
current_state = session["state"]
current_state["title"] = title
current_state["created_at"] = datetime.now().isoformat()
SessionService.save_session(session_id, current_state)
return f"Chat title updated to: {title}"
def toggle_podcast_generated(session_state: dict, status: bool = False) -> str:
"""
Toggle the podcast_generated flag.
When set to true, this indicates the podcast creation process is complete and
the UI should show the final presentation view with all components.
If status is True, also saves the podcast to the podcasts database.
"""
if status:
session_state["podcast_generated"] = status
session_state["stage"] = "complete" if status else session_state.get("stage")
if status:
try:
success, message, podcast_id = _save_podcast_to_database_sync(session_state)
if success and podcast_id:
session_state["podcast_id"] = podcast_id
return f"Podcast generated and saved to database with ID: {podcast_id}. You can now access it from the Podcasts section."
else:
return f"Podcast generated, but there was an issue with saving: {message}"
except Exception as e:
print(f"Error saving podcast to database: {e}")
return f"Podcast generated, but there was an error saving it to the database: {str(e)}"
else:
session_state["podcast_generated"] = status
session_state["stage"] = "complete" if status else session_state.get("stage")
return f"Podcast generated status changed to: {status}"
def mark_session_finished(agent: Agent) -> str:
"""
Mark the session as finished.
Args:
agent: The agent instance
Returns:
Confirmation message
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
if not session_state.get("generated_script"):
return "Podcast Script is not generated yet."
if not session_state.get("banner_url"):
return "Banner is not generated yet."
if not session_state.get("audio_url"):
return "Audio is not generated yet."
session_state["finished"] = True
session_state["stage"] = "complete"
toggle_podcast_generated(session_state, True)
SessionService.save_session(session_id, session_state)
return "Session marked as finished and generated podcast stored into podcasts database and No further conversation are allowed and only new session can be started."
| 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/search_articles.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/search_articles.py | import sqlite3
from typing import List, Union
from agno.agent import Agent
from db.config import get_tracking_db_path
import json
def search_articles(agent: Agent, terms: Union[str, List[str]]) -> str:
"""
Search for articles related to a podcast topic using direct SQL queries.
The agent can pass either a string topic or a list of search terms.
Args:
agent: The agent instance
terms: Either a single topic string or a list of search terms
Returns:
A formatted string response with the search results
"""
print(f"Search Internal Articles terms: {terms}")
search_terms = terms if isinstance(terms, list) else [terms]
limit = 3
db_path = get_tracking_db_path()
try:
with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
conn.row_factory = lambda cursor, row: {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
results = execute_simple_search(conn, search_terms, limit)
if not results:
return "No relevant articles found in our database. Would you like to try a different topic or provide specific URLs?"
for article in results:
article["categories"] = get_article_categories(conn, article["id"])
article["source_name"] = article.get("source_id", "Unknown Source")
return f"is_scrapping_required: False, Found {len(results)}, {json.dumps(results, indent=2)} potential sources that might be relevant to your topic careful my search is text bassed do quality check and ignore invalid resutls."
except Exception as e:
print(f"Error searching articles: {e}")
return "I encountered a database error while searching. Would you like to try a different approach?"
def execute_simple_search(conn, terms, limit):
base_query = """
SELECT DISTINCT ca.id, ca.title, ca.url, ca.published_date,
COALESCE(ca.summary, ca.content) as content,
ca.source_id, ca.feed_id
FROM crawled_articles ca
WHERE ca.processed = 1
AND (
"""
clauses = []
params = []
for term in terms:
like_term = f"%{term}%"
clauses.append("(ca.title LIKE ? OR ca.content LIKE ? OR ca.summary LIKE ?)")
params.extend([like_term, like_term, like_term])
query = base_query + " OR ".join(clauses) + ") ORDER BY ca.published_date DESC LIMIT ?"
params.append(limit)
cursor = conn.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def get_article_categories(conn, article_id):
try:
cursor = conn.execute("SELECT category_name FROM article_categories WHERE article_id = ?", (article_id,))
return [row["category_name"] for row in cursor.fetchall()]
except Exception as e:
print(f"Error fetching article categories: {e}")
return [] | 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/google_news_discovery.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/google_news_discovery.py |
def search_news(google_news, keyword):
resutls = google_news.get_news(keyword)
return resutls
def get_top_news(google_news):
resutls = google_news.get_top_news()
return resutls
def get_news_by_topic(google_news, topic):
resutls = google_news.get_news_by_topic(topic)
return resutls
def google_news_discovery_run(
keyword: str = None,
max_results: int = 5,
top_news: bool = False,
) -> str:
from gnews import GNews
import json
"""
This is a wrapper function for the google news.
Args:
keyword: The search query for specific news
top_news: Whether to get top news instead of keyword search (default: False)
max_results: The maximum number of results to return (default: 20)
Returns:
List of news results
Note:
Either set top_news=True for top headlines or provide a keyword for search.
If both are provided, top_news takes precedence.
"""
print("Google News Discovery:", keyword)
google_news = GNews(
language=None,
country=None,
period=None,
max_results=max_results,
exclude_websites=[],
)
if top_news:
results = get_top_news(google_news)
if keyword:
results = search_news(google_news, keyword)
print('google news search found:', len(results))
return f"for all results is_scrapping_required: True, results: {json.dumps(results)}"
| 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/ui_manager.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/ui_manager.py | from agno.agent import Agent
from dotenv import load_dotenv
from db.agent_config_v2 import TOGGLE_UI_STATES
load_dotenv()
def ui_manager_run(
agent: Agent,
state_type: str,
active: bool,
) -> str:
"""
UI Manager that takes the state_type and active as input and updates the sessions UI state.
Args:
agent: The agent instance
state_type: The state type to update
active: The active state
Returns:
Response status
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
current_state = session["state"]
current_state[state_type] = active
all_ui_states = TOGGLE_UI_STATES
for ui_state in all_ui_states:
if ui_state != state_type:
current_state[ui_state] = False
SessionService.save_session(session_id, current_state)
return f"Updated {state_type} to {active}{' and all other UI states to False' if all_ui_states else ''}." | 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/social_media_search.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social_media_search.py | import sqlite3
import json
from datetime import datetime, timedelta
from contextlib import contextmanager
from agno.agent import Agent
from db.config import get_db_path
@contextmanager
def get_social_media_db():
db_path = get_db_path("social_media_db")
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def social_media_search(agent: Agent, topic: str, limit: int = 10) -> str:
"""
Search social media database for the given topic on social media post texts, so topic needs to be extact keyword or phrase.
Returns minimal fields required for source selection.
Args:
agent: The agent instance
topic: The search topic
limit: Maximum number of results to return (default: 10)
Returns:
Search results matching agent's expected format
"""
print(f"Social Media News Search: {topic}")
try:
days_back: int = 7
date_from = (datetime.now() - timedelta(days=days_back)).isoformat()
with get_social_media_db() as conn:
cursor = conn.cursor()
sql_query = """
SELECT
post_id,
user_display_name,
post_timestamp,
post_url,
post_text,
platform
FROM posts
WHERE
categories LIKE '%"news"%'
AND sentiment = 'positive'
AND datetime(post_timestamp) >= datetime(?)
AND (post_text LIKE ? OR user_display_name LIKE ?)
ORDER BY datetime(post_timestamp) DESC
LIMIT ?
"""
search_term = f"%{topic}%"
cursor.execute(sql_query, (date_from, search_term, search_term, limit))
rows = cursor.fetchall()
if not rows:
return f"No positive news posts found for '{topic}' in the last {days_back} days."
results = []
for row in rows:
result = {
"id": f"social_{row['post_id']}",
"url": row["post_url"] or f"https://{row['platform']}/post/{row['post_id']}",
"published_date": row["post_timestamp"],
"description": row["post_text"][:200] + "..." if len(row["post_text"]) > 200 else row["post_text"],
"source_id": "social_media_db",
"source_name": f"{row['platform'].title()}",
"categories": ["news"],
"is_scrapping_required": False,
}
results.append(result)
return f"Found {len(results)} positive news posts. {json.dumps({'results': results}, indent=2)}"
except Exception as e:
return f"Error searching social media database: {str(e)}"
def social_media_trending_search(agent: Agent, limit: int = 10) -> str:
"""
Get trending positive news posts from social media.
Returns trending news posts in standard results format.
Args:
agent: The agent instance
limit: Maximum number of trending results (default: 10)
Returns:
Trending positive news posts
"""
print(f"Social Media Trending Search: {limit}")
days_back = 3
try:
date_from = (datetime.now() - timedelta(days=days_back)).isoformat()
with get_social_media_db() as conn:
cursor = conn.cursor()
trending_sql = """
SELECT
post_id,
user_display_name,
post_timestamp,
post_url,
post_text,
platform
FROM posts
WHERE
categories LIKE '%"news"%'
AND sentiment = 'positive'
AND datetime(post_timestamp) >= datetime(?)
ORDER BY
(COALESCE(engagement_like_count, 0) +
COALESCE(engagement_retweet_count, 0) +
COALESCE(engagement_reply_count, 0)) DESC,
datetime(post_timestamp) DESC
LIMIT ?
"""
cursor.execute(trending_sql, (date_from, limit))
rows = cursor.fetchall()
if not rows:
return f"No trending positive news found in the last {days_back} days."
results = []
for row in rows:
result = {
"id": f"social_{row['post_id']}",
"url": row["post_url"] or f"https://{row['platform']}/post/{row['post_id']}",
"published_date": row["post_timestamp"],
"description": row["post_text"],
"source_id": "social_media_trending",
"source_name": f"{row['platform'].title()} Trending",
"categories": ["news"],
"is_scrapping_required": False,
}
results.append(result)
return f"Found {len(results)} trending positive news posts. {json.dumps({'results': results}, indent=2)}"
except Exception as e:
return f"Error getting trending news: {str(e)}"
if __name__ == "__main__":
print("here...")
print(social_media_trending_search(None, 5)) | 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/embedding_search.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/embedding_search.py | from agno.agent import Agent
import os
import numpy as np
import faiss
from openai import OpenAI
from db.config import get_tracking_db_path, get_faiss_db_path, get_sources_db_path
from db.connection import execute_query
from utils.load_api_keys import load_api_key
import traceback
import json
EMBEDDING_MODEL = "text-embedding-3-small"
def generate_query_embedding(query_text, model=EMBEDDING_MODEL):
try:
api_key = load_api_key("OPENAI_API_KEY")
if not api_key:
return None, "OpenAI API key not found"
client = OpenAI(api_key=api_key)
response = client.embeddings.create(input=query_text, model=model)
return response.data[0].embedding, None
except Exception as e:
return None, str(e)
def load_faiss_index(index_path):
if not os.path.exists(index_path):
return None, f"FAISS index not found at {index_path}"
try:
return faiss.read_index(index_path), None
except Exception as e:
return None, f"Error loading FAISS index: {str(e)}"
def load_id_mapping(mapping_path):
if not os.path.exists(mapping_path):
return None, f"ID mapping not found at {mapping_path}"
try:
return np.load(mapping_path).tolist(), None
except Exception as e:
return None, f"Error loading ID mapping: {str(e)}"
def get_article_details(tracking_db_path, article_ids):
if not article_ids:
return []
placeholders = ",".join(["?"] * len(article_ids))
query = f"""
SELECT id, title, url, published_date, summary, source_id, feed_id, content
FROM crawled_articles
WHERE id IN ({placeholders})
"""
return execute_query(tracking_db_path, query, article_ids, fetch=True)
def get_source_names(source_ids):
if not source_ids:
return {}
unique_ids = list(set([src_id for src_id in source_ids if src_id]))
if not unique_ids:
return {}
try:
sources_db_path = get_sources_db_path()
check_query = """
SELECT name FROM sqlite_master
WHERE type='table' AND name='sources'
"""
table_exists = execute_query(sources_db_path, check_query, fetch=True)
if not table_exists:
return {}
placeholders = ",".join(["?"] * len(unique_ids))
query = f"""
SELECT id, name FROM sources
WHERE id IN ({placeholders})
"""
results = execute_query(sources_db_path, query, unique_ids, fetch=True)
return {str(row["id"]): row["name"] for row in results} if results else {}
except Exception as _:
return {}
def embedding_search(agent: Agent, prompt: str) -> str:
"""
Perform a semantic search using embeddings to find articles related to the query on internal articles databse which are crawled from preselected user rss feeds.
This search uses vector representations to find semantically similar content,
filtering for only high-quality matches (similarity score ≥ 85%).
Args:
agent: The Agno agent instance
prompt: The search query
Returns:
Search results
"""
print("Embedding Search Input:", prompt)
tracking_db_path = get_tracking_db_path()
index_path, mapping_path = get_faiss_db_path()
top_k = 20
similarity_threshold = 0.85
if not os.path.exists(index_path) or not os.path.exists(mapping_path):
return "Embedding search not available: index files not found. Continuing with other search methods."
query_embedding, error = generate_query_embedding(prompt)
if not query_embedding:
return f"Semantic search unavailable: {error}. Continuing with other search methods."
query_vector = np.array([query_embedding]).astype(np.float32)
try:
faiss_index, error = load_faiss_index(index_path)
if error:
return f"Semantic search unavailable: {error}. Continuing with other search methods."
id_map, error = load_id_mapping(mapping_path)
if error:
return f"Semantic search unavailable: {error}. Continuing with other search methods."
distances, indices = faiss_index.search(query_vector, top_k)
results_with_metrics = []
for i, idx in enumerate(indices[0]):
if idx >= 0 and idx < len(id_map):
distance = float(distances[0][i])
similarity = float(np.exp(-distance)) if distance > 0 else 0
if similarity >= similarity_threshold:
article_id = id_map[idx]
results_with_metrics.append((idx, distance, similarity, article_id))
results_with_metrics.sort(key=lambda x: x[2], reverse=True)
result_article_ids = [item[3] for item in results_with_metrics]
if not result_article_ids:
return "No high-quality semantic matches found (threshold: 85%). Continuing with other search methods."
results = get_article_details(tracking_db_path, result_article_ids)
source_ids = [result.get("source_id") for result in results if result.get("source_id")]
source_names = get_source_names(source_ids)
formatted_results = []
for i, result in enumerate(results):
article_id = result.get("id")
similarity = next((item[2] for item in results_with_metrics if item[3] == article_id), 0)
similarity_percent = int(similarity * 100)
source_id = str(result.get("source_id", "unknown"))
source_name = source_names.get(source_id, source_id)
formatted_result = {
"id": article_id,
"title": f"{result.get('title', 'Untitled')} (Relevance: {similarity_percent}%)",
"url": result.get("url", "#"),
"published_date": result.get("published_date"),
"description": result.get("summary", result.get("content", "")),
"source_id": source_id,
"source_name": source_name,
"similarity": similarity,
"categories": ["semantic"],
"is_scrapping_required": False,
}
formatted_results.append(formatted_result)
return f"Found {len(formatted_results)}, results: {json.dumps(formatted_results, indent=2)}"
except Exception as e:
traceback.print_exc()
return f"Error in semantic search: {str(e)}. Continuing with other search methods." | 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/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/__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/tools/wikipedia_search.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/wikipedia_search.py | from agno.agent import Agent
def wikipedia_search(agent: Agent, query: str, srlimit: int = 5) -> str:
"""
Search Wikipedia for articles using Wikipedia API.
Returns only links and short summaries without fetching full content.
Args:
agent: The agent instance
query: The search query
srlimit: The number of results to return
Returns:
A formatted string response with the search results (link and gist only)
"""
import requests
import html
import json
print("Wikipedia Search Input:", query)
try:
search_url = "https://en.wikipedia.org/w/api.php"
search_params = {
"action": "query",
"format": "json",
"list": "search",
"srsearch": query,
"srlimit": srlimit,
"utf8": 1,
}
search_response = requests.get(search_url, params=search_params)
search_data = search_response.json()
if (
"query" not in search_data
or "search" not in search_data["query"]
or not search_data["query"]["search"]
):
print(f"No Wikipedia results found for query: {query}")
return "No relevant Wikipedia articles found for this topic."
results = []
for item in search_data["query"]["search"]:
title = item["title"]
snippet = html.unescape(
item["snippet"]
.replace('<span class="searchmatch">', "")
.replace("</span>", "")
)
url = f"https://en.wikipedia.org/wiki/{title.replace(' ', '_')}"
result = {
"title": title,
"url": url,
"gist": snippet,
"source": "Wikipedia",
}
results.append(result)
if not results:
return "No Wikipedia search results found."
return f"for all results is_scrapping_required: True, results: {json.dumps(results, ensure_ascii=False, indent=2)}"
except Exception as e:
print(f"Error during Wikipedia search: {str(e)}")
return f"Error in Wikipedia search: {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/tools/social/x_scraper.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/x_scraper.py | import time
from tools.social.browser import create_browser_context
from tools.social.x_post_extractor import x_post_extractor
from tools.social.x_agent import analyze_posts_sentiment
from tools.social.db import create_connection, setup_database, check_and_store_post, update_posts_with_analysis
def crawl_x_profile(profile_url, db_file="x_posts.db"):
if not profile_url.startswith("http"):
profile_url = f"https://x.com/{profile_url}"
conn = create_connection(db_file)
setup_database(conn)
seen_post_ids = set()
analysis_queue = []
queue_post_ids = []
post_count = 0
batch_size = 5
scroll_count = 0
with create_browser_context() as (browser_context, page):
page.goto(profile_url)
time.sleep(5)
try:
while True:
tweet_articles = page.query_selector_all('article[role="article"]')
for article in tweet_articles:
article_id = article.evaluate('(element) => element.getAttribute("id")')
if article_id in seen_post_ids:
continue
show_more = article.query_selector('button[data-testid="tweet-text-show-more-link"]')
if show_more:
try:
show_more.click()
time.sleep(1)
except Exception as e:
pass
tweet_html = article.evaluate("(element) => element.outerHTML")
post_data = x_post_extractor(tweet_html)
post_id = post_data.get("post_id")
if not post_id or post_data.get("is_ad", False):
continue
seen_post_ids.add(post_id)
post_count += 1
needs_analysis = check_and_store_post(conn, post_data)
if needs_analysis and post_data.get("post_text"):
analysis_queue.append(post_data)
queue_post_ids.append(post_id)
if len(analysis_queue) >= batch_size:
analysis_batch = analysis_queue[:batch_size]
batch_post_ids = queue_post_ids[:batch_size]
analysis_queue = analysis_queue[batch_size:]
queue_post_ids = queue_post_ids[batch_size:]
try:
analysis_results = analyze_posts_sentiment(analysis_batch)
update_posts_with_analysis(conn, batch_post_ids, analysis_results)
except Exception:
pass
page.evaluate("window.scrollBy(0, 800)")
time.sleep(3)
scroll_count += 1
if scroll_count >= 30:
break
except KeyboardInterrupt:
if analysis_queue:
try:
analysis_results = analyze_posts_sentiment(analysis_queue)
update_posts_with_analysis(conn, queue_post_ids, analysis_results)
except Exception:
pass
conn.close()
return post_count
return post_count | 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/social/x_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/x_agent.py | from typing import List
from pydantic import BaseModel, Field
from enum import Enum
from textwrap import dedent
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from dotenv import load_dotenv
import uuid
load_dotenv()
class SentimentType(str, Enum):
POSITIVE = "positive"
NEGATIVE = "negative"
NEUTRAL = "neutral"
CRITICAL = "critical"
class Category(str, Enum):
POLITICS = "politics"
TECHNOLOGY = "technology"
ENTERTAINMENT = "entertainment"
SPORTS = "sports"
BUSINESS = "business"
HEALTH = "health"
SCIENCE = "science"
EDUCATION = "education"
ENVIRONMENT = "environment"
SOCIAL_ISSUES = "social_issues"
PERSONAL = "personal"
NEWS = "news"
OTHER = "other"
class AnalyzedPost(BaseModel):
post_id: str = Field(..., description="The unique identifier for the post")
sentiment: SentimentType = Field(..., description="The sentiment of the post")
categories: List[Category] = Field(..., description="List of categories that best describe this post")
tags: List[str] = Field(..., description="List of relevant tags or keywords extracted from the post")
reasoning: str = Field(..., description="Brief explanation of why these sentiments and categories were assigned")
class AnalysisResponse(BaseModel):
analyzed_posts: List[AnalyzedPost] = Field(..., description="List of analyzed posts with sentiment and categorization")
SENTIMENT_AGENT_DESCRIPTION = "Expert sentiment analyzer and content categorizer for social media posts."
SENTIMENT_AGENT_INSTRUCTIONS = dedent("""
You are an expert sentiment analyzer and content categorizer for social media posts.
You will receive a batch of social media posts, each with a unique post_id. Your task is to analyze each post and return:
1. The EXACT same post_id that was provided (this is critical for matching)
2. The sentiment (positive, negative, neutral, or critical)
3. Relevant categories from the predefined list
4. Generated tags or keywords
5. Brief reasoning for your analysis
Guidelines for sentiment classification:
- POSITIVE: Expresses joy, gratitude, excitement, optimism, or other positive emotions
- NEGATIVE: Expresses sadness, anger, disappointment, fear, or other negative emotions
- NEUTRAL: Factual, objective, or balanced without strong emotional tone
- CRITICAL: Contains criticism, skepticism, or questioning, but in a constructive or analytical way
IMPORTANT: You MUST maintain the exact post_id provided for each post in your analysis.
IMPORTANT: Categories must be chosen ONLY from the predefined list.
IMPORTANT: Return analysis for ALL posts provided in the input.
IMPORTANT: You can add news tag if you think that could you be used to write news articles.
""")
def analyze_posts_sentiment(posts_data):
session_id = str(uuid.uuid4())
analysis_agent = Agent(
model=OpenAIChat(id="gpt-4o"),
instructions=SENTIMENT_AGENT_INSTRUCTIONS,
description=SENTIMENT_AGENT_DESCRIPTION,
use_json_mode=True,
response_model=AnalysisResponse,
session_id=session_id,
)
posts_prompt = "Analyze the sentiment and categorize the following social media posts:\n\n"
valid_posts = []
for post in posts_data:
post_text = post.get("post_text", "")
post_id = post.get("post_id", "")
if post_text and post_id:
valid_posts.append(post)
posts_prompt += f"POST (ID: {post_id}):\n{post_text}\n\n"
if not valid_posts:
return []
response = analysis_agent.run(posts_prompt, session_id=session_id)
analysis_results = response.to_dict()["content"]["analyzed_posts"]
validated_results = []
valid_post_ids = {post.get("post_id") for post in valid_posts}
for analysis in analysis_results:
if analysis.get("post_id") in valid_post_ids:
validated_results.append(analysis)
else:
print(f"Warning: Analysis returned with invalid post_id: {analysis.get('post_id')}")
return validated_results | 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/social/db.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/db.py | import sqlite3
import json
def create_connection(db_file="x_posts.db"):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
return conn
def setup_database(conn):
create_posts_table = """
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, -- Stored as JSON
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
)
"""
conn.execute(create_posts_table)
conn.execute("CREATE INDEX IF NOT EXISTS idx_posts_platform ON posts(platform)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_posts_user_handle ON posts(user_handle)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_posts_post_timestamp ON posts(post_timestamp)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_posts_sentiment ON posts(sentiment)")
conn.commit()
def parse_engagement_count(count_str):
if not count_str:
return 0
count_str = str(count_str).strip()
if not count_str:
return 0
multiplier = 1
if "K" in count_str:
multiplier = 1000
count_str = count_str.replace("K", "")
elif "M" in count_str:
multiplier = 1000000
count_str = count_str.replace("M", "")
elif "B" in count_str:
multiplier = 1000000000
count_str = count_str.replace("B", "")
try:
return int(float(count_str) * multiplier)
except (ValueError, TypeError):
return 0
def process_post_data(post_data):
data = post_data.copy()
metrics = ["engagement_reply_count", "engagement_retweet_count", "engagement_like_count", "engagement_bookmark_count", "engagement_view_count"]
for metric in metrics:
if metric in data:
data[metric] = parse_engagement_count(data[metric])
if "media" in data and isinstance(data["media"], list):
data["media"] = json.dumps(data["media"])
if "categories" in data and isinstance(data["categories"], list):
data["categories"] = json.dumps(data["categories"])
if "tags" in data and isinstance(data["tags"], list):
data["tags"] = json.dumps(data["tags"])
if "is_ad" in data:
data["is_ad"] = 1 if data["is_ad"] else 0
return data
def get_post(conn, post_id):
cursor = conn.cursor()
cursor.execute("SELECT * FROM posts WHERE post_id = ?", (post_id,))
return cursor.fetchone()
def insert_post(conn, post_data):
data = process_post_data(post_data)
columns = ", ".join(data.keys())
placeholders = ", ".join(["?"] * len(data))
values = list(data.values())
sql = f"INSERT INTO posts ({columns}) VALUES ({placeholders})"
conn.execute(sql, values)
conn.commit()
def check_and_store_post(conn, post_data):
post_id = post_data.get("post_id")
if not post_id:
return False
if post_data.get("is_ad", False):
return False
data = process_post_data(post_data)
existing_post = get_post(conn, post_id)
if not existing_post:
needs_analysis = bool(data.get("post_text"))
insert_post(conn, data)
return needs_analysis
else:
update_changed_metrics(conn, existing_post, data)
return False
def update_changed_metrics(conn, existing_post, new_data):
metrics = ["engagement_reply_count", "engagement_retweet_count", "engagement_like_count", "engagement_bookmark_count", "engagement_view_count"]
changes = {}
for metric in metrics:
if metric in new_data and metric in existing_post:
if new_data[metric] != existing_post[metric]:
changes[metric] = new_data[metric]
if changes:
set_clauses = [f"{metric} = ?" for metric in changes]
set_sql = ", ".join(set_clauses)
set_sql += ", updated_at = CURRENT_TIMESTAMP"
sql = f"UPDATE posts SET {set_sql} WHERE post_id = ?"
params = list(changes.values()) + [existing_post["post_id"]]
conn.execute(sql, params)
conn.commit()
def update_posts_with_analysis(conn, post_ids, analysis_results):
if not analysis_results:
return
analysis_by_id = {}
for analysis in analysis_results:
post_id = analysis.get("post_id")
if post_id:
analysis_by_id[post_id] = analysis
for post_id in post_ids:
if post_id in analysis_by_id:
analysis = analysis_by_id[post_id]
categories = json.dumps(analysis.get("categories", []))
tags = json.dumps(analysis.get("tags", []))
conn.execute(
"""UPDATE posts SET
sentiment = ?,
categories = ?,
tags = ?,
analysis_reasoning = ?,
updated_at = CURRENT_TIMESTAMP
WHERE post_id = ?""",
(analysis.get("sentiment"), categories, tags, analysis.get("reasoning"), post_id),
)
conn.commit() | 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/social/x_post_extractor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/x_post_extractor.py | import os
from bs4 import BeautifulSoup
import re
import json
def check_ad(soup):
is_ad = False
ad_label = soup.find(
lambda tag: tag.name and tag.text and tag.text.strip() == "Ad" and "r-bcqeeo" in tag.get("class", []) if hasattr(tag, "get") else False
)
if ad_label:
is_ad = True
username_element = soup.select_one("div[data-testid='User-Name'] a[role='link'] span")
if username_element and username_element.text.strip() in [
"Premium",
"Twitter",
"X",
]:
is_ad = True
handle_element = soup.select_one("div[data-testid='User-Name'] div[dir='ltr'] span")
if handle_element and "@premium" in handle_element.text:
is_ad = True
ad_tracking_links = soup.select("a[href*='referring_page=ad_'], a[href*='twclid=']")
if ad_tracking_links:
is_ad = True
return is_ad
def x_post_extractor(html_content):
soup = BeautifulSoup(html_content, "html.parser")
data = {"platform": "x.com"}
data["media"] = []
data["is_ad"] = check_ad(soup)
user_element = soup.find("div", {"data-testid": "User-Name"})
if user_element:
display_name_element = user_element.find(lambda tag: tag.name and (tag.name == "span" or tag.name == "div") and "Henrik" in tag.text)
if display_name_element:
data["user_display_name"] = display_name_element.text.strip()
username_element = user_element.find(lambda tag: tag.name == "a" and "@" in tag.text)
if username_element:
data["user_handle"] = username_element.text.strip()
profile_pic = soup.select_one("[data-testid='UserAvatar-Container-HenrikTaro'] img")
if profile_pic and profile_pic.has_attr("src"):
data["user_profile_pic_url"] = profile_pic["src"]
time_element = soup.find("time")
if time_element:
if time_element.has_attr("datetime"):
data["post_timestamp"] = time_element["datetime"]
data["post_display_time"] = time_element.text.strip()
post_link = soup.select_one("a[href*='/status/']")
if post_link and post_link.has_attr("href"):
status_url = post_link["href"]
post_id_match = re.search(r"/status/(\d+)", status_url)
if post_id_match:
data["post_id"] = post_id_match.group(1)
data["post_url"] = f"https://twitter.com{status_url}"
text_element = soup.find("div", {"data-testid": "tweetText"})
if text_element:
data["post_text"] = text_element.get_text(strip=True)
mentions = []
mention_elements = text_element.select("a[href^='/'][role='link']")
for mention in mention_elements:
mention_text = mention.text.strip()
if mention_text.startswith("@"):
mentions.append(mention_text)
if mentions:
data["post_mentions"] = ",".join(mentions)
reply_button = soup.find("button", {"data-testid": "reply"})
if reply_button:
count_span = reply_button.select_one("span[data-testid='app-text-transition-container'] span span")
if count_span:
data["engagement_reply_count"] = count_span.text.strip()
retweet_button = soup.find("button", {"data-testid": "retweet"})
if retweet_button:
count_span = retweet_button.select_one("span[data-testid='app-text-transition-container'] span span")
if count_span:
data["engagement_retweet_count"] = count_span.text.strip()
like_button = soup.find("button", {"data-testid": "like"})
if like_button:
count_span = like_button.select_one("span[data-testid='app-text-transition-container'] span span")
if count_span:
data["engagement_like_count"] = count_span.text.strip()
bookmark_button = soup.find("button", {"data-testid": "bookmark"})
if bookmark_button:
count_span = bookmark_button.select_one("span[data-testid='app-text-transition-container'] span span")
if count_span:
data["engagement_bookmark_count"] = count_span.text.strip()
views_element = soup.select_one("a[href*='/analytics']")
if views_element:
views_span = views_element.select_one("span[data-testid='app-text-transition-container'] span span")
if views_span:
data["engagement_view_count"] = views_span.text.strip()
media_elements = soup.find_all("div", {"data-testid": "tweetPhoto"})
for media in media_elements:
img = media.find("img")
if img and img.has_attr("src"):
data["media"].append({"type": "image", "url": img["src"]})
data["media_count"] = len(data["media"])
return 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_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/session_setup.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/session_setup.py | from tools.social.browser import setup_session_multi
target_sites = [
"https://x.com",
"https://facebook.com"
]
if __name__ == "__main__":
setup_session_multi(target_sites) | 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/social/fb_post_extractor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/fb_post_extractor.py | import json
from datetime import datetime
from typing import Dict, Any
import re
def parse_facebook_posts(data):
posts = []
try:
for post in data["data"]["viewer"]["news_feed"]["edges"]:
posts.append(parse_facebook_post(post["node"]))
except Exception as e:
print(f"Error parsing post data: {e}")
return posts
def parse_facebook_post(story_node: Dict[str, Any]) -> Dict[str, Any]:
try:
post_info = {
"post_id": story_node.get("post_id"),
"story_id": story_node.get("id"),
"creation_time": None,
"creation_time_formatted": None,
"url": None,
}
creation_time_sources = [
story_node.get("creation_time"),
(story_node.get("comet_sections") or {}).get("context_layout", {}).get("story", {}).get("creation_time"),
(story_node.get("comet_sections") or {}).get("timestamp", {}).get("story", {}).get("creation_time"),
]
for source in creation_time_sources:
if source:
post_info["creation_time"] = source
post_info["creation_time_formatted"] = datetime.fromtimestamp(source).strftime("%Y-%m-%d %H:%M:%S")
break
url_sources = [
(story_node.get("comet_sections") or {}).get("content", {}).get("story", {}).get("wwwURL"),
(story_node.get("comet_sections") or {}).get("feedback", {}).get("story", {}).get("story_ufi_container", {}).get("story", {}).get("url"),
(story_node.get("comet_sections") or {})
.get("feedback", {})
.get("story", {})
.get("story_ufi_container", {})
.get("story", {})
.get("shareable_from_perspective_of_feed_ufi", {})
.get("url"),
story_node.get("wwwURL"),
story_node.get("url"),
]
for source in url_sources:
if source:
post_info["url"] = source
break
message_info = extract_message_content(story_node)
post_info.update(message_info)
actors_info = extract_actors_info(story_node)
post_info.update(actors_info)
attachments_info = extract_attachments(story_node)
post_info.update(attachments_info)
engagement_info = extract_engagement_data(story_node)
post_info.update(engagement_info)
privacy_info = extract_privacy_info(story_node)
post_info.update(privacy_info)
return post_info
except (KeyError, IndexError, TypeError) as e:
print(f"Error parsing post data: {e}")
return {}
def extract_message_content(story_node: Dict[str, Any]) -> Dict[str, Any]:
message_info = {"message_text": "", "hashtags": [], "mentions": [], "links": []}
try:
message_sources = [
(story_node.get("message") or {}).get("text", ""),
((((story_node.get("comet_sections") or {}).get("content") or {}).get("story") or {}).get("message") or {}).get("text", ""),
]
for source in message_sources:
if source:
message_info["message_text"] = source
break
message_data = story_node.get("message", {})
if "ranges" in message_data:
for range_item in message_data["ranges"]:
entity = range_item.get("entity", {})
entity_type = entity.get("__typename")
if entity_type == "Hashtag":
hashtag_text = message_info["message_text"][range_item["offset"] : range_item["offset"] + range_item["length"]]
message_info["hashtags"].append(
{
"text": hashtag_text,
"url": entity.get("url"),
"id": entity.get("id"),
}
)
elif entity_type == "User":
mention_text = message_info["message_text"][range_item["offset"] : range_item["offset"] + range_item["length"]]
message_info["mentions"].append(
{
"text": mention_text,
"url": entity.get("url"),
"id": entity.get("id"),
}
)
except (KeyError, TypeError):
pass
return message_info
def extract_actors_info(story_node: Dict[str, Any]) -> Dict[str, Any]:
actors_info = {
"author_name": "",
"author_id": "",
"author_url": "",
"author_profile_picture": "",
"is_verified": False,
"page_info": {},
}
try:
actors = story_node.get("actors", [])
if actors:
main_actor = actors[0]
actors_info.update(
{
"author_name": main_actor.get("name", ""),
"author_id": main_actor.get("id", ""),
"author_url": main_actor.get("url", ""),
}
)
context_sections = (story_node.get("comet_sections") or {}).get("context_layout", {})
if context_sections:
actor_photo = (context_sections.get("story") or {}).get("comet_sections", {}).get("actor_photo", {})
if actor_photo:
story_actors = (actor_photo.get("story") or {}).get("actors", [])
if story_actors:
profile_pic = story_actors[0].get("profile_picture", {})
actors_info["author_profile_picture"] = profile_pic.get("uri", "")
except (KeyError, TypeError, IndexError):
pass
return actors_info
def extract_attachments(story_node: Dict[str, Any]) -> Dict[str, Any]:
attachments_info = {"attachments": [], "photos": [], "videos": [], "links": []}
try:
attachments = story_node.get("attachments", [])
for attachment in attachments:
attachment_data = {
"type": attachment.get("__typename", ""),
"style_list": attachment.get("style_list", []),
}
if "photo" in attachment.get("style_list", []):
target = attachment.get("target", {})
if target.get("__typename") == "Photo":
styles = attachment.get("styles", {})
if styles:
media = (styles.get("attachment") or {}).get("media", {})
photo_info = {
"id": target.get("id"),
"url": media.get("url", ""),
"width": (media.get("viewer_image") or {}).get("width"),
"height": (media.get("viewer_image") or {}).get("height"),
"image_uri": "",
"accessibility_caption": media.get("accessibility_caption", ""),
}
resolution_renderer = media.get("comet_photo_attachment_resolution_renderer", {})
if resolution_renderer:
image = resolution_renderer.get("image", {})
photo_info["image_uri"] = image.get("uri", "")
attachments_info["photos"].append(photo_info)
attachments_info["attachments"].append(attachment_data)
except (KeyError, TypeError):
pass
return attachments_info
def extract_engagement_data(story_node: Dict[str, Any]) -> Dict[str, Any]:
"""Extract likes, comments, shares, and other engagement metrics"""
engagement_info = {
"reaction_count": 0,
"comment_count": 0,
"share_count": 0,
"reactions_breakdown": {},
"top_reactions": [],
}
try:
feedback_story = (story_node.get("comet_sections") or {}).get("feedback", {}).get("story", {})
if feedback_story:
ufi_container = (feedback_story.get("story_ufi_container") or {}).get("story", {})
if ufi_container:
feedback_context = ufi_container.get("feedback_context", {})
feedback_target = feedback_context.get("feedback_target_with_context", {})
if feedback_target:
summary_renderer = feedback_target.get("comet_ufi_summary_and_actions_renderer", {})
if summary_renderer:
feedback_data = summary_renderer.get("feedback", {})
if "i18n_reaction_count" in feedback_data:
engagement_info["reaction_count"] = int(feedback_data["i18n_reaction_count"])
elif "reaction_count" in feedback_data and isinstance(feedback_data["reaction_count"], dict):
engagement_info["reaction_count"] = feedback_data["reaction_count"].get("count", 0)
if "i18n_share_count" in feedback_data:
engagement_info["share_count"] = int(feedback_data["i18n_share_count"])
elif "share_count" in feedback_data and isinstance(feedback_data["share_count"], dict):
engagement_info["share_count"] = feedback_data["share_count"].get("count", 0)
top_reactions = feedback_data.get("top_reactions", {})
if "edges" in top_reactions:
for edge in top_reactions["edges"]:
reaction_node = edge.get("node", {})
engagement_info["top_reactions"].append(
{
"reaction_id": reaction_node.get("id"),
"name": reaction_node.get("localized_name"),
"count": edge.get("reaction_count", 0),
}
)
comment_rendering = feedback_target.get("comment_rendering_instance", {})
if comment_rendering:
comments = comment_rendering.get("comments", {})
engagement_info["comment_count"] = comments.get("total_count", 0)
except (KeyError, TypeError, ValueError):
pass
return engagement_info
def extract_privacy_info(story_node: Dict[str, Any]) -> Dict[str, Any]:
privacy_info = {"privacy_scope": "", "audience": ""}
try:
privacy_sources = [
(story_node.get("comet_sections") or {}).get("context_layout", {}).get("story", {}).get("privacy_scope", {}),
story_node.get("privacy_scope", {}),
next(
(
(meta.get("story") or {}).get("privacy_scope", {})
for meta in (story_node.get("comet_sections") or {})
.get("context_layout", {})
.get("story", {})
.get("comet_sections", {})
.get("metadata", [])
if isinstance(meta, dict) and meta.get("__typename") == "CometFeedStoryAudienceStrategy"
),
{},
),
]
for privacy_scope in privacy_sources:
if privacy_scope and "description" in privacy_scope:
privacy_info["privacy_scope"] = privacy_scope["description"]
break
if not privacy_info["privacy_scope"]:
context_layout = (story_node.get("comet_sections") or {}).get("context_layout", {})
if context_layout:
story = context_layout.get("story", {})
comet_sections = story.get("comet_sections", {})
metadata = comet_sections.get("metadata", [])
for meta_item in metadata:
if isinstance(meta_item, dict) and meta_item.get("__typename") == "CometFeedStoryAudienceStrategy":
story_data = meta_item.get("story", {})
privacy_scope = story_data.get("privacy_scope", {})
if privacy_scope:
privacy_info["privacy_scope"] = privacy_scope.get("description", "")
break
except (KeyError, TypeError):
pass
return privacy_info
def normalize_facebook_post(fb_post_data):
normalized = {
"platform": "facebook.com",
"post_id": fb_post_data.get("post_id", ""),
"user_display_name": fb_post_data.get("author_name", ""),
"user_handle": extract_handle_from_url(fb_post_data.get("author_url", "")),
"user_profile_pic_url": fb_post_data.get("author_profile_picture", ""),
"post_timestamp": format_timestamp(fb_post_data.get("creation_time")),
"post_display_time": fb_post_data.get("creation_time_formatted", ""),
"post_url": fb_post_data.get("url", ""),
"post_text": fb_post_data.get("message_text", ""),
"post_mentions": format_mentions(fb_post_data.get("mentions", [])),
"engagement_reply_count": fb_post_data.get("comment_count", 0),
"engagement_retweet_count": fb_post_data.get("share_count", 0),
"engagement_like_count": fb_post_data.get("reaction_count", 0),
"engagement_bookmark_count": 0,
"engagement_view_count": 0,
"media": format_media(fb_post_data),
"media_count": calculate_media_count(fb_post_data),
"is_ad": False,
"sentiment": None,
"categories": None,
"tags": None,
"analysis_reasoning": None,
}
return normalized
def extract_handle_from_url(author_url: str) -> str:
if not author_url:
return ""
patterns = [
r"facebook\.com/([^/?]+)",
r"facebook\.com/profile\.php\?id=(\d+)",
r"facebook\.com/pages/[^/]+/(\d+)",
]
for pattern in patterns:
match = re.search(pattern, author_url)
if match:
return match.group(1)
return ""
def format_timestamp(creation_time) -> str:
if not creation_time:
return ""
try:
if isinstance(creation_time, (int, float)):
dt = datetime.fromtimestamp(creation_time)
return dt.isoformat()
elif isinstance(creation_time, str):
return creation_time
except (ValueError, TypeError):
pass
return ""
def format_mentions(mentions):
if not mentions:
return ""
mention_texts = []
for mention in mentions:
if isinstance(mention, dict):
text = mention.get("text", "")
if text and not text.startswith("@"):
text = f"@{text}"
mention_texts.append(text)
elif isinstance(mention, str):
if not mention.startswith("@"):
mention = f"@{mention}"
mention_texts.append(mention)
return ",".join(mention_texts)
def format_media(fb_post_data: Dict[str, Any]) -> str:
media_items = []
photos = fb_post_data.get("photos", [])
for photo in photos:
if isinstance(photo, dict):
media_item = {
"type": "image",
"url": photo.get("image_uri") or photo.get("url", ""),
"width": photo.get("width"),
"height": photo.get("height"),
"id": photo.get("id"),
"accessibility_caption": photo.get("accessibility_caption", ""),
}
media_item = {k: v for k, v in media_item.items() if v is not None}
media_items.append(media_item)
videos = fb_post_data.get("videos", [])
for video in videos:
if isinstance(video, dict):
media_item = {
"type": "video",
"url": video.get("url", ""),
"id": video.get("id"),
}
media_item = {k: v for k, v in media_item.items() if v is not None}
media_items.append(media_item)
attachments = fb_post_data.get("attachments", [])
for attachment in attachments:
if isinstance(attachment, dict):
attachment_type = attachment.get("type", "")
style_list = attachment.get("style_list", [])
if "photo" in style_list:
media_item = {"type": "image", "attachment_type": attachment_type}
media_items.append(media_item)
elif "video" in style_list:
media_item = {"type": "video", "attachment_type": attachment_type}
media_items.append(media_item)
return media_items or []
def calculate_media_count(fb_post_data):
count = 0
count += len(fb_post_data.get("photos", []))
count += len(fb_post_data.get("videos", []))
attachments = fb_post_data.get("attachments", [])
for attachment in attachments:
if isinstance(attachment, dict):
style_list = attachment.get("style_list", [])
if any(style in style_list for style in ["photo", "video"]):
count += 1
return count
def normalize_facebook_posts_batch(fb_posts_data):
normalized_posts = []
for fb_post in fb_posts_data:
try:
normalized_post = normalize_facebook_post(fb_post)
if normalized_post.get("post_id"):
normalized_posts.append(normalized_post)
except Exception as e:
print(f"Error normalizing Facebook post: {e}")
continue
return normalized_posts
if __name__ == "__main__":
with open("fb_post_input.json", "r", encoding="utf-8") as f:
facebook_data = json.load(f)
parsed_post = parse_facebook_posts(facebook_data)
normalized_post = normalize_facebook_posts_batch(parsed_post)
print(normalized_post)
| 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/social/browser.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/browser.py | import os
from playwright.sync_api import sync_playwright
from tools.social.config import USER_DATA_DIR
from contextlib import contextmanager
def setup_session(TARGET_SITE):
print("🔐 SESSION SETUP MODE")
print(f"Opening browser with persistent profile at: {USER_DATA_DIR}")
print(f"Please log in {TARGET_SITE} manually to establish your session")
with sync_playwright() as playwright:
os.makedirs(USER_DATA_DIR, exist_ok=True)
browser_context = playwright.chromium.launch_persistent_context(
user_data_dir=USER_DATA_DIR,
headless=False,
viewport={"width": 1280, "height": 800},
)
try:
if browser_context.pages:
page = browser_context.pages[0]
else:
page = browser_context.new_page()
page.goto(TARGET_SITE)
print("\n✅ Browser is now open. Please:")
print("1. Log in to your account manually")
print("2. Navigate through the site as needed")
print("3. Press Ctrl+C in this terminal when you're done\n")
try:
while True:
page.wait_for_timeout(1000)
except KeyboardInterrupt:
print("\n🔑 Session saved! You can now run monitoring tasks with this session.")
finally:
browser_context.close()
def setup_session_multi(TARGET_SITES):
print("🔐 MULTI-SITE SESSION SETUP MODE")
print(f"Opening browser with persistent profile at: {USER_DATA_DIR}")
print(f"Setting up sessions for {len(TARGET_SITES)} sites:")
for i, site in enumerate(TARGET_SITES, 1):
print(f" {i}. {site}")
with sync_playwright() as playwright:
os.makedirs(USER_DATA_DIR, exist_ok=True)
browser_context = playwright.chromium.launch_persistent_context(
user_data_dir=USER_DATA_DIR,
headless=False,
viewport={"width": 1280, "height": 800},
)
try:
pages = []
for i, site in enumerate(TARGET_SITES):
if i == 0 and browser_context.pages:
page = browser_context.pages[0]
else:
page = browser_context.new_page()
print(f"📂 Opening: {site}")
page.goto(site)
pages.append(page)
print("\n✅ All sites opened in separate tabs. Please:")
print("1. Log in to your accounts manually in each tab")
print("2. Navigate through the sites as needed")
print("3. Press Ctrl+C in this terminal when you're done\n")
print("💡 Tip: Use Ctrl+Tab to switch between tabs")
try:
while True:
pages[0].wait_for_timeout(1000)
except KeyboardInterrupt:
print(f"\n🔑 Sessions saved for all {len(TARGET_SITES)} sites! " "You can now run monitoring tasks with these sessions.")
finally:
browser_context.close()
@contextmanager
def create_browser_context():
with sync_playwright() as playwright:
browser_context = playwright.chromium.launch_persistent_context(
user_data_dir=USER_DATA_DIR,
headless=False,
viewport={"width": 1280, "height": 800},
)
try:
if browser_context.pages:
page = browser_context.pages[0]
else:
page = browser_context.new_page()
yield browser_context, page
finally:
browser_context.close() | 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/social/config.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/config.py | from db.config import get_browser_session_path
USER_DATA_DIR = get_browser_session_path()
| 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/social/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/__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/tools/social/fb_scraper.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/social/fb_scraper.py | import time
import json
from tools.social.browser import create_browser_context
from tools.social.fb_post_extractor import parse_facebook_posts, normalize_facebook_posts_batch
from tools.social.x_agent import analyze_posts_sentiment
from tools.social.db import create_connection, setup_database, check_and_store_post, update_posts_with_analysis
def contains_facebook_posts(json_obj):
if not isinstance(json_obj, dict):
return False
try:
data = json_obj.get("data", {})
viewer = data.get("viewer", {})
news_feed = viewer.get("news_feed", {})
edges = news_feed.get("edges", [])
if isinstance(edges, list) and len(edges) > 0:
for edge in edges:
if isinstance(edge, dict) and "node" in edge:
node = edge["node"]
if isinstance(node, dict) and node.get("__typename") == "Story":
return True
return False
except (KeyError, TypeError, AttributeError):
return False
def process_facebook_graphql_response(response_text, seen_post_ids, analysis_queue, queue_post_ids, conn):
posts_processed = 0
if not response_text:
return posts_processed
lines = response_text.split("\n")
for line in lines:
line = line.strip()
if not line:
continue
try:
json_obj = json.loads(line)
if contains_facebook_posts(json_obj):
parsed_posts = parse_facebook_posts(json_obj)
if not parsed_posts:
continue
normalized_posts = normalize_facebook_posts_batch(parsed_posts)
for post_data in normalized_posts:
post_id = post_data.get("post_id")
if not post_id or post_id in seen_post_ids:
continue
seen_post_ids.add(post_id)
posts_processed += 1
needs_analysis = check_and_store_post(conn, post_data)
if needs_analysis and post_data.get("post_text"):
analysis_queue.append(post_data)
queue_post_ids.append(post_id)
except json.JSONDecodeError:
continue
except Exception as e:
print(f"Error processing Facebook post: {e}")
continue
return posts_processed
def crawl_facebook_feed(target_url="https://facebook.com", db_file="fb_posts.db"):
conn = create_connection(db_file)
setup_database(conn)
seen_post_ids = set()
analysis_queue = []
queue_post_ids = []
post_count = 0
batch_size = 5
scroll_count = 0
with create_browser_context() as (browser_context, page):
def handle_response(response):
nonlocal post_count, analysis_queue, queue_post_ids
url = response.url
if "/api/graphql/" not in url:
return
try:
content_type = response.headers.get("content-type", "")
if 'text/html; charset="utf-8"' not in content_type:
return
response_text = response.text()
posts_found = process_facebook_graphql_response(response_text, seen_post_ids, analysis_queue, queue_post_ids, conn)
if posts_found > 0:
post_count += posts_found
if len(analysis_queue) >= batch_size:
analysis_batch = analysis_queue[:batch_size]
batch_post_ids = queue_post_ids[:batch_size]
analysis_queue = analysis_queue[batch_size:]
queue_post_ids = queue_post_ids[batch_size:]
try:
analysis_results = analyze_posts_sentiment(analysis_batch)
update_posts_with_analysis(conn, batch_post_ids, analysis_results)
except Exception:
pass
except Exception:
pass
page.on("response", handle_response)
page.goto(target_url)
time.sleep(5)
def scroll_page():
page.evaluate("window.scrollBy(0, window.innerHeight)")
try:
while True:
scroll_page()
time.sleep(3)
scroll_count += 1
if scroll_count >= 50:
break
except KeyboardInterrupt:
pass
if analysis_queue:
try:
analysis_results = analyze_posts_sentiment(analysis_queue)
update_posts_with_analysis(conn, queue_post_ids, analysis_results)
except Exception:
pass
conn.close()
return post_count
| 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/pipeline/script_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/pipeline/script_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from typing import List, Optional
from dotenv import load_dotenv
from textwrap import dedent
from datetime import datetime
import uuid
load_dotenv()
class Dialog(BaseModel):
speaker: str = Field(..., description="The speaker name (SHOULD BE 'ALEX' OR 'MORGAN')")
text: str = Field(
...,
description="The spoken text content for this speaker based on the requested langauge, default is English",
)
class Section(BaseModel):
type: str = Field(..., description="The section type (intro, headlines, article, outro)")
title: Optional[str] = Field(None, description="Optional title for the section (required for article type)")
dialog: List[Dialog] = Field(..., description="List of dialog exchanges between speakers")
class PodcastScript(BaseModel):
title: str = Field(..., description="The podcast episode title with date")
sections: List[Section] = Field(..., description="List of podcast sections (intro, headlines, articles, outro)")
PODCAST_AGENT_DESCRIPTION = "You are a helpful assistant that can generate engaging podcast scripts for the given sources."
PODCAST_AGENT_INSTRUCTIONS = dedent("""
You are a helpful assistant that can generate engaging podcast scripts for the given source content and query.
For given content, create an engaging podcast script that should be at least 15 minutes worth of content and your allowed enhance the script beyond given sources if you know something additional info will be interesting to the discussion or not enough conents available.
You use the provided sources to ground your podcast script generation process. Keep it engaging and interesting.
IMPORTANT: Generate the entire script in the provided language. basically only text field needs to be in requested language,
CONTENT GUIDELINES [THIS IS EXAMPLE YOU CAN CHANGE THE GUIDELINES ANYWAY BASED ON THE QUERY OR TOPIC DISCUSSED]:
- Provide insightful analysis that helps the audience understand the significance
- Include discussions on potential implications and broader context of each story
- Explain complex concepts in an accessible but thorough manner
- Make connections between current and relevant historical developments when applicable
- Provide comparisons and contrasts with similar stories or trends when relevant
PERSONALITY NOTES [THIS IS EXAMPLE YOU CAN CHANGE THE PERSONALITY OF ALEX AND MORGAN ANYWAY BASED ON THE QUERY OR TOPIC DISCUSSED]:
- Alex is more analytical and fact-focused
* Should reference specific details and data points
* Should explain complex topics clearly
* Should identify key implications of stories
- Morgan is more focused on human impact, social context, and practical applications
* Should analyze broader implications
* Should consider ethical implications and real-world applications
- Include natural, conversational banter and smooth transitions between topics
- Each article discussion should go beyond the basic summary to provide valuable insights
- Maintain a conversational but informed tone that would appeal to a general audience
IMPORTNAT:
- MAKE SURE PODCAST SCRIPS ARE AT LEAST 15 MINUTES LONG WHICH MEANS YOU NEED TO HAVE DETAILED DISCUSSIONS OFFCOURSE KEEP IT INTERESTING AND ENGAGING.
""")
def format_search_results_for_podcast(
search_results: List[dict],
) -> tuple[str, List[str]]:
created_at = datetime.now().strftime("%B %d, %Y at %I:%M %p")
structured_content = []
structured_content.append(f"PODCAST CREATION: {created_at}\n")
sources = []
for idx, search_result in enumerate(search_results):
try:
if search_result.get("confirmed", False):
sources.append(search_result["url"])
structured_content.append(
f"""
SOURCE {idx + 1}:
Title: {search_result['title']}
URL: {search_result['url']}
Content: {search_result.get('full_text') or search_result.get('description', '')}
---END OF SOURCE {idx + 1}---
""".strip()
)
except Exception as e:
print(f"Error processing search result: {e}")
content_texts = "\n\n".join(structured_content)
return content_texts, sources
def script_agent_run(
query: str,
search_results: List[dict],
language_name: str,
) -> str:
try:
session_id = str(uuid.uuid4())
content_texts, sources = format_search_results_for_podcast(search_results)
if not content_texts:
return {}
podcast_script_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=PODCAST_AGENT_INSTRUCTIONS,
description=PODCAST_AGENT_DESCRIPTION,
use_json_mode=True,
response_model=PodcastScript,
session_id=session_id,
)
response = podcast_script_agent.run(
f"query: {query}\n language_name: {language_name}\n content_texts: {content_texts}\n, IMPORTANT: texts should be in {language_name} language.",
session_id=session_id,
)
response_dict = response.to_dict()
response_dict = response_dict["content"]
response_dict["sources"] = sources
return response_dict
except Exception as _:
import traceback
traceback.print_exc()
return {} | 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/pipeline/search_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/pipeline/search_agent.py | from typing import List
import uuid
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from agno.tools.duckduckgo import DuckDuckGoTools
from textwrap import dedent
from tools.wikipedia_search import wikipedia_search
from tools.google_news_discovery import google_news_discovery_run
from tools.jikan_search import jikan_search
from tools.embedding_search import embedding_search
from tools.social_media_search import social_media_search, social_media_trending_search
load_dotenv()
class ReturnItem(BaseModel):
url: str = Field(..., description="The URL of the search result")
title: str = Field(..., description="The title of the search result")
description: str = Field(..., description="A brief description or summary of the search result content")
source_name: str = Field(
...,
description="The name/type of the source (e.g., 'wikipedia', 'general', or any reputable source tag)",
)
tool_used: str = Field(
...,
description="The tools used to generate the search results, unknown if not used or not applicable",
)
published_date: str = Field(
...,
description="The published date of the content in ISO format, if not available keep it empty",
)
is_scrapping_required: bool = Field(
...,
description="Set to True if the content need scraping, False otherwise, default keep it True if not sure",
)
class SearchResults(BaseModel):
items: List[ReturnItem] = Field(..., description="A list of search result items")
SEARCH_AGENT_DESCRIPTION = "You are a helpful assistant that can search the web for information."
SEARCH_AGENT_INSTRUCTIONS = dedent("""
You are a helpful assistant that can search the web or any other sources for information.
You should create topic for the search from the given query instead of blindly apply the query to the search tools.
For a given topic, your job is to search the web or any other sources and return the top 5 to 10 sources about the topic.
Keep the search sources of high quality and reputable, and sources should be relevant to the asked topic.
Sources should be from diverse platforms with no duplicates.
IMPORTANT: User queries might be fuzzy or misspelled. Understand the user's intent and act accordingly.
IMPORTANT: The output source_name field can be one of ["wikipedia", "general", or any source tag used"].
IMPORTANT: You have access to different search tools use them when appropriate which one is best for the given search query. Don't use particular tool if not required.
IMPORTANT: Make sure you are able to detect what tool to use and use it available tool tags = ["google_news_discovery", "duckduckgo", "wikipedia_search", "jikan_search", "social_media_search", "social_media_trending_search", "unknown"].
IMPORTANT: If query is news related please prefere google news over other news tools.
IMPORTANT: If returned sources are not of high quality or not relevant to the asked topic, don't include them in the returned sources.
IMPORTANT: Never include dates to the search query unless user explicitly asks for it.
IMPORTANT: You are allowed to use appropriate tools to get the best results even the single tool return enough results diverse check is better.
""")
def search_agent_run(query: str) -> str:
try:
session_id = str(uuid.uuid4())
search_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=SEARCH_AGENT_INSTRUCTIONS,
description=SEARCH_AGENT_DESCRIPTION,
use_json_mode=True,
response_model=SearchResults,
tools=[
google_news_discovery_run,
DuckDuckGoTools(),
wikipedia_search,
jikan_search,
embedding_search,
social_media_search,
social_media_trending_search,
],
session_id=session_id,
)
response = search_agent.run(query, session_id=session_id)
response_dict = response.to_dict()
return response_dict["content"]["items"]
except Exception as _:
import traceback
traceback.print_exc()
return []
| 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/pipeline/scrape_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/pipeline/scrape_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from tools.browser_crawler import create_browser_crawler
from textwrap import dedent
import uuid
load_dotenv()
class ScrapedContent(BaseModel):
url: str = Field(..., description="The URL of the search result")
description: str = Field(description="The description of the search result")
full_text: str = Field(
...,
description="The full text of the given source URL, if not available or not applicable keep it empty",
)
published_date: str = Field(
...,
description="The published date of the content in ISO format, if not available keep it empty",
)
SCRAPE_AGENT_DESCRIPTION = "You are a helpful assistant that can scrape the URL for full content."
SCRAPE_AGENT_INSTRUCTIONS = dedent("""
You are a content verification and formatting assistant.
You will receive a batch of pre-scraped content from various URLs along with a search query.
Your job is to:
1. VERIFY RELEVANCE: Ensure each piece of content is relevant to the given query
2. QUALITY CONTROL: Filter out low-quality, duplicate, or irrelevant content
3. FORMAT CONSISTENCY: Ensure all content follows a consistent format
4. LENGTH OPTIMIZATION: Keep content at reasonable length - not too long, not too short
5. CLEAN TEXT: Remove any formatting artifacts, ads, or navigation elements from scraped content
For each piece of content, return:
- full_text: The cleaned, relevant text content (or empty if not relevant/low quality)
- published_date: The publication date in ISO format (or empty if not available)
Note: Some content may be fallback descriptions (when scraping failed) - treat these appropriately and don't penalize them for being shorter.
IMPORTANT: Focus on quality over quantity. It's better to return fewer high-quality, relevant pieces than many low-quality ones.
""")
def crawl_urls_batch(search_results):
url_to_search_results = {}
unique_urls = []
for search_result in search_results:
if not search_result.get("url", False):
continue
if not search_result.get("is_scrapping_required", True):
continue
if not search_result.get('original_url'):
search_result['original_url'] = search_result['url']
url = search_result["url"]
if url not in url_to_search_results:
url_to_search_results[url] = []
unique_urls.append(url)
url_to_search_results[url].append(search_result)
browser_crawler = create_browser_crawler()
scraped_results = browser_crawler.scrape_urls(unique_urls)
url_to_scraped = {result["original_url"]: result for result in scraped_results}
updated_search_results = []
successful_scrapes = 0
failed_scrapes = 0
for search_result in search_results:
original_url = search_result["url"]
scraped = url_to_scraped.get(original_url, {})
updated_result = search_result.copy()
updated_result["original_url"] = original_url
if scraped.get("success", False):
updated_result["url"] = scraped.get("final_url", original_url)
updated_result["full_text"] = scraped.get("full_text", "")
updated_result["published_date"] = scraped.get("published_date", "")
successful_scrapes += 1
else:
updated_result["url"] = original_url
updated_result["full_text"] = search_result.get("description", "")
updated_result["published_date"] = ""
failed_scrapes += 1
updated_search_results.append(updated_result)
return updated_search_results, successful_scrapes, failed_scrapes
def verify_content_with_agent(query, search_results, use_agent=True):
if not use_agent:
return search_results
verified_search_results = []
for _, search_result in enumerate(search_results):
content_for_verification = {
"url": search_result["url"],
"description": search_result.get("description", ""),
"full_text": search_result["full_text"],
"published_date": search_result["published_date"],
}
search_result["agent_verified"] = False
try:
session_id = str(uuid.uuid4())
scrape_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=SCRAPE_AGENT_INSTRUCTIONS,
description=SCRAPE_AGENT_DESCRIPTION,
use_json_mode=True,
session_id=session_id,
response_model=ScrapedContent,
)
response = scrape_agent.run(
f"Query: {query}\n"
f"Verify and format this scraped content. "
f"Keep content relevant to the query and ensure quality: {content_for_verification}",
session_id=session_id,
)
verified_item = response.to_dict()["content"]
search_result["full_text"] = verified_item.get("full_text", search_result["full_text"])
search_result["published_date"] = verified_item.get("published_date", search_result["published_date"])
search_result["agent_verified"] = True
except Exception as _:
pass
verified_search_results.append(search_result)
return verified_search_results
def scrape_agent_run(query: str, search_results) -> str:
try:
updated_results, _, _ = crawl_urls_batch(search_results)
verified_results = verify_content_with_agent(query, updated_results, use_agent=False)
return verified_results
except Exception as _:
import traceback
traceback.print_exc()
return []
| 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/pipeline/image_generate_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/pipeline/image_generate_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.dalle import DalleTools
from textwrap import dedent
import json
from dotenv import load_dotenv
import uuid
from db.agent_config_v2 import PODCAST_IMG_DIR
import os
import requests
from typing import Any
load_dotenv()
IMAGE_GENERATION_AGENT_DESCRIPTION = "You are an AI agent that can generate images using DALL-E."
IMAGE_GENERATION_AGENT_INSTRUCTIONS = dedent("""
When the user asks you to create an image, use the `create_image` tool to create the image.
Create a modern, eye-catching podcast cover images that represents a podcast given podcast topic.
Create 3 images for the given podcast topic.
IMPORTANT INSTRUCTIONS:
- DO NOT include ANY text in the image
- DO NOT include any words, titles, or lettering
- Create a purely visual and symbolic representation
- Use imagery that represents the specific topics mentioned
- I like Studio Ghibli flavor if possible
- The image should work well as a podcast cover thumbnail
- Create a clean, professional design suitable for a podcast
- AGAIN, DO NOT INCLUDE ANY TEXT
""")
def download_images(image_urls):
local_image_filenames = []
try:
if image_urls:
for image_url in image_urls:
unique_id = str(uuid.uuid4())
filename = f"podcast_banner_{unique_id}.png"
os.makedirs(PODCAST_IMG_DIR, exist_ok=True)
print(f"Downloading image: {filename}")
response = requests.get(image_url, timeout=30)
response.raise_for_status()
image_path = os.path.join(PODCAST_IMG_DIR, filename)
with open(image_path, "wb") as f:
f.write(response.content)
local_image_filenames.append(filename)
print(f"Successfully downloaded: {filename}")
except requests.exceptions.RequestException as e:
print(f"Error downloading images (network): {e}")
except Exception as e:
print(f"Error downloading images: {e}")
return local_image_filenames
def image_generation_agent_run(query: str, generated_script: Any) -> str:
session_id = str(uuid.uuid4())
try:
image_agent = Agent(
model=OpenAIChat(id="gpt-4o"),
tools=[DalleTools()],
description=IMAGE_GENERATION_AGENT_DESCRIPTION,
instructions=IMAGE_GENERATION_AGENT_INSTRUCTIONS,
markdown=True,
show_tool_calls=True,
session_id=session_id,
)
image_agent.run(f"query: {query},\n podcast script: {json.dumps(generated_script)}", session_id=session_id)
images = image_agent.get_images()
image_urls = []
if images and isinstance(images, list):
for image_response in images:
image_url = image_response.url
image_urls.append(image_url)
local_image_filenames = download_images(image_urls)
return {"banner_images": local_image_filenames, "banner_url": local_image_filenames[0] if local_image_filenames else None}
except Exception as e:
print(f"Error in Image Generation Agent: {e}")
return {}
| 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/integrations/slack/chat.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/integrations/slack/chat.py | import os
import re
import sqlite3
import asyncio
import aiohttp
import json
from concurrent.futures import ThreadPoolExecutor
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from dotenv import load_dotenv
from typing import Dict, List
from datetime import datetime
from db.config import get_slack_sessions_db_path
load_dotenv()
app = App(token=os.environ["SLACK_BOT_TOKEN"])
# local url works but banner images won't work in slack unless it's https with proper domain
# you can use ngrok to port forward local url to https and replace this local url with ngrok url
API_BASE_URL = os.environ.get("API_BASE_URL", "http://localhost:7000")
executor = ThreadPoolExecutor(max_workers=10)
active_sessions: Dict[str, Dict] = {}
DB_PATH = get_slack_sessions_db_path()
def send_error_message(thread_key: str, error_message: str):
print(f"Error for {thread_key}: {error_message}")
asyncio.create_task(send_slack_message(thread_key, f"❌ {error_message}"))
def init_db():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS thread_sessions (
thread_key TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
user_id TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS session_state (
session_id TEXT PRIMARY KEY,
state_data TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def save_session_mapping(thread_key: str, session_id: str, channel_id: str, user_id: str = None):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO thread_sessions (thread_key, session_id, channel_id, user_id, updated_at) VALUES (?, ?, ?, ?, ?)",
(thread_key, session_id, channel_id, user_id, datetime.now().isoformat()),
)
conn.commit()
conn.close()
def get_session_info(thread_key: str):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"SELECT session_id, channel_id, user_id FROM thread_sessions WHERE thread_key = ?",
(thread_key,),
)
result = cursor.fetchone()
conn.close()
return result if result else None
def save_session_state(session_id: str, state_data):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
if isinstance(state_data, str):
json_data = state_data
else:
json_data = json.dumps(state_data)
cursor.execute(
"INSERT OR REPLACE INTO session_state (session_id, state_data, updated_at) VALUES (?, ?, ?)",
(session_id, json_data, datetime.now().isoformat()),
)
conn.commit()
conn.close()
def get_session_state(session_id: str):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT state_data FROM session_state WHERE session_id = ?", (session_id,))
result = cursor.fetchone()
conn.close()
if result:
try:
return json.loads(result[0])
except:
return {}
return {}
class PodcastAgentClient:
def __init__(self, base_url: str):
self.base_url = base_url
self.timeout = aiohttp.ClientTimeout(total=30)
async def create_session(self, session_id=None):
try:
async with aiohttp.ClientSession(timeout=self.timeout) as session:
payload = {"session_id": session_id} if session_id else {}
async with session.post(f"{self.base_url}/api/podcast-agent/session", json=payload) as resp:
resp.raise_for_status()
return await resp.json()
except Exception as e:
print(f"API create_session error: {e}")
raise
async def chat(self, session_id: str, message: str):
try:
async with aiohttp.ClientSession(timeout=self.timeout) as session:
payload = {"session_id": session_id, "message": message}
async with session.post(f"{self.base_url}/api/podcast-agent/chat", json=payload) as resp:
resp.raise_for_status()
return await resp.json()
except Exception as e:
print(f"API chat error: {e}")
raise
async def check_status(self, session_id: str, task_id=None):
try:
async with aiohttp.ClientSession(timeout=self.timeout) as session:
payload = {"session_id": session_id}
if task_id:
payload["task_id"] = task_id
async with session.post(f"{self.base_url}/api/podcast-agent/status", json=payload) as resp:
resp.raise_for_status()
return await resp.json()
except Exception as e:
print(f"API check_status error: {e}")
raise
api_client = PodcastAgentClient(API_BASE_URL)
def get_thread_key(message, is_dm=False):
if is_dm:
return f"dm_{message['channel']}_{message['user']}"
else:
return message.get("thread_ts", message["ts"])
async def get_or_create_session(thread_key: str, channel_id: str, user_id: str = None):
session_info = get_session_info(thread_key)
if not session_info:
response = await api_client.create_session(thread_key)
session_id = response["session_id"]
save_session_mapping(thread_key, session_id, channel_id, user_id)
print(f"Created new session: {session_id} for thread: {thread_key}")
return session_id
else:
return session_info[0]
def run_async_in_thread(coro):
def run():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
future = executor.submit(run)
return future
async def poll_for_completion(session_id: str, thread_key: str, task_id=None):
print(f"Starting polling for session: {session_id}, task: {task_id}")
max_polls = 60
poll_count = 0
active_sessions[session_id] = {
"thread_key": thread_key,
"task_id": task_id,
"start_time": datetime.now(),
}
try:
while poll_count < max_polls:
try:
status_response = await api_client.check_status(session_id, task_id)
if status_response.get("session_state"):
save_session_state(session_id, status_response.get("session_state"))
if not status_response.get("is_processing", True):
await send_completion_message(thread_key, status_response)
break
if poll_count % 10 == 0 and poll_count > 0:
process_type = status_response.get("process_type", "request")
await send_slack_message(
thread_key,
f"🔄 Still processing {process_type}... ({poll_count * 3}s elapsed)",
)
await asyncio.sleep(3)
poll_count += 1
except Exception as e:
print(f"Polling error: {e}")
await send_slack_message(
thread_key,
"❌ Something went wrong while processing your request. Please try again.",
)
break
finally:
if session_id in active_sessions:
del active_sessions[session_id]
def start_background_polling(session_id: str, thread_key: str, task_id=None):
if session_id in active_sessions:
print(f"Replacing existing poll for session: {session_id}")
future = run_async_in_thread(poll_for_completion(session_id, thread_key, task_id))
active_sessions[session_id] = {
"thread_key": thread_key,
"task_id": task_id,
"future": future,
"start_time": datetime.now(),
}
async def send_completion_message(thread_key: str, status_response):
response_text = status_response.get("response", "Task completed!")
session_state = status_response.get("session_state")
if session_state:
try:
state_data = json.loads(session_state) if isinstance(session_state, str) else session_state
if state_data.get("show_sources_for_selection") and state_data.get("search_results"):
await send_source_selection_blocks(thread_key, state_data, response_text)
elif state_data.get("show_script_for_confirmation") and state_data.get("generated_script"):
await send_script_confirmation_blocks(thread_key, state_data, response_text)
elif state_data.get("show_banner_for_confirmation") and state_data.get("banner_url"):
await send_banner_confirmation_blocks(thread_key, state_data, response_text)
elif state_data.get("show_audio_for_confirmation") and state_data.get("audio_url"):
await send_audio_confirmation_blocks(thread_key, state_data, response_text)
elif state_data.get("podcast_generated"):
await send_final_presentation_blocks(thread_key, state_data, response_text)
else:
await send_slack_message(thread_key, response_text)
except Exception as e:
print(f"Error parsing session state: {e}")
await send_slack_message(thread_key, response_text)
else:
await send_slack_message(thread_key, response_text)
async def send_source_selection_blocks(thread_key: str, state_data: dict, response_text: str):
sources = state_data.get("search_results", [])
languages = state_data.get("available_languages", [{"code": "en", "name": "English"}])
session_info = get_session_info(thread_key)
if session_info:
save_session_state(session_info[0], state_data)
source_options = []
for i, source in enumerate(sources[:10]):
title = source.get("title", f"Source {i + 1}")
if len(title) > 70:
title = title[:67] + "..."
source_options.append(
{
"text": {"type": "plain_text", "text": f"{i + 1}. {title}"},
"value": str(i),
}
)
language_options = []
for lang in languages:
language_options.append(
{
"text": {"type": "plain_text", "text": lang["name"]},
"value": lang["code"],
}
)
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*📋 Source Selection*\n{response_text}",
},
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"Found *{len(sources)}* sources. Select the ones you'd like to use for your podcast:",
},
},
]
if source_options:
blocks.append(
{
"type": "section",
"block_id": "source_selection_block",
"text": {"type": "mrkdwn", "text": "*Select Sources:*"},
"accessory": {
"type": "checkboxes",
"action_id": "source_selection",
"options": source_options,
"initial_options": source_options,
},
}
)
if len(sources) > 10:
blocks.append(
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"_Showing first 10 sources. {len(sources) - 10} more available._",
}
],
}
)
blocks.extend(
[
{
"type": "section",
"block_id": "language_selection_block",
"text": {"type": "mrkdwn", "text": "*Select Language:*"},
"accessory": {
"type": "static_select",
"action_id": "language_selection",
"placeholder": {"type": "plain_text", "text": "Choose language"},
"options": language_options,
"initial_option": language_options[0] if language_options else None,
},
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "✅ Confirm Selection"},
"style": "primary",
"action_id": "confirm_sources",
"value": thread_key,
}
],
},
]
)
await send_slack_blocks(thread_key, blocks, "📋 Source Selection")
def format_script_for_slack_snippet(script_data) -> str:
if isinstance(script_data, dict):
lines = []
title = script_data.get("title", "Podcast Script")
lines.append(f"PODCAST: {title}")
lines.append("=" * (len(title) + 10))
lines.append("")
sections = script_data.get("sections", [])
for i, section in enumerate(sections):
section_type = section.get("type", "Unknown").upper()
section_title = section.get("title", "")
if section_title:
lines.append(f"SECTION [{section_type}] {section_title}")
else:
lines.append(f"SECTION [{section_type}]")
lines.append("-" * 50)
lines.append("")
if section.get("dialog"):
for j, dialog in enumerate(section["dialog"]):
speaker = dialog.get("speaker", "SPEAKER")
text = dialog.get("text", "")
lines.append(f"SPEAKER {speaker}:")
if len(text) > 70:
words = text.split()
current_line = " "
for word in words:
if len(current_line + word) > 70:
lines.append(current_line)
current_line = " " + word
else:
current_line += " " + word if current_line != " " else word
if current_line.strip():
lines.append(current_line)
else:
lines.append(f" {text}")
lines.append("")
if i < len(sections) - 1:
lines.append("")
return "\n".join(lines)
return str(script_data) if script_data else "Script content not available"
async def send_script_confirmation_blocks(thread_key: str, state_data: dict, response_text: str):
script = state_data.get("generated_script", {})
title = script.get("title", "Podcast Script") if isinstance(script, dict) else "Podcast Script"
full_script_text = format_script_for_slack_snippet(script)
if len(full_script_text) > 2500:
full_script_text = full_script_text[:2400] + "\n\n... (script continues)\n\nFull script will be available after approval."
section_count = len(script.get("sections", [])) if isinstance(script, dict) else 0
dialog_count = 0
if isinstance(script, dict) and script.get("sections"):
for section in script["sections"]:
dialog_count += len(section.get("dialog", []))
header_text = f"*📝 Script Review*\n{response_text}\n\n*{title}*\nGenerated {section_count} sections with {dialog_count} dialogue exchanges"
blocks = [
{
"type": "section",
"text": {"type": "mrkdwn", "text": header_text},
},
{"type": "section", "text": {"type": "mrkdwn", "text": f"```{full_script_text}```"}},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "✅ Approve Script"},
"style": "primary",
"action_id": "approve_script",
"value": thread_key,
},
{
"type": "button",
"text": {"type": "plain_text", "text": "🔄 Request Changes"},
"action_id": "request_script_changes",
"value": thread_key,
},
],
},
]
await send_slack_blocks(thread_key, blocks, "📝 Script Review")
async def send_banner_confirmation_blocks(thread_key: str, state_data: dict, response_text: str):
banner_url = state_data.get("banner_url")
banner_images = state_data.get("banner_images", [])
image_url = None
if banner_images:
image_url = f"{API_BASE_URL}/podcast_img/{banner_images[0]}"
elif banner_url:
image_url = f"{API_BASE_URL}/podcast_img/{banner_url}"
blocks = [
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*🎨 Banner Review*\n{response_text}"},
}
]
if image_url:
blocks.append({"type": "image", "image_url": image_url, "alt_text": "Podcast Banner"})
if len(banner_images) > 1:
blocks.append(
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"_Showing 1 of {len(banner_images)} generated banners_",
}
],
}
)
blocks.append(
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "✅ Approve Banner"},
"style": "primary",
"action_id": "approve_banner",
"value": thread_key,
}
],
}
)
await send_slack_blocks(thread_key, blocks, "🎨 Banner Review")
async def send_audio_confirmation_blocks(thread_key: str, state_data: dict, response_text: str):
audio_url = state_data.get("audio_url")
full_audio_url = f"{API_BASE_URL}/audio/{audio_url}" if audio_url else None
blocks = [
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*🎵 Audio Review*\n{response_text}"},
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Your podcast audio has been generated! 🎧\n\n_Note: Click the download link to listen to your podcast audio._",
},
},
]
action_elements = []
if full_audio_url:
action_elements.append(
{
"type": "button",
"text": {"type": "plain_text", "text": "⬇️ Download Audio"},
"url": full_audio_url,
"action_id": "download_audio",
}
)
action_elements.append(
{
"type": "button",
"text": {"type": "plain_text", "text": "✅ Sounds Great!"},
"style": "primary",
"action_id": "approve_audio",
"value": thread_key,
}
)
blocks.append({"type": "actions", "elements": action_elements})
await send_slack_blocks(thread_key, blocks, f"🎵 Audio Review")
async def send_final_presentation_blocks(thread_key: str, state_data: dict, response_text: str):
script = state_data.get("generated_script", {})
podcast_title = script.get("title") if isinstance(script, dict) else None
if not podcast_title:
podcast_title = state_data.get("podcast_info", {}).get("topic", "Your Podcast")
audio_url = state_data.get("audio_url")
banner_url = state_data.get("banner_url")
banner_images = state_data.get("banner_images", [])
full_audio_url = f"{API_BASE_URL}/audio/{audio_url}" if audio_url else None
full_banner_url = None
if banner_images:
full_banner_url = f"{API_BASE_URL}/podcast_img/{banner_images[0]}"
elif banner_url:
full_banner_url = f"{API_BASE_URL}/podcast_img/{banner_url}"
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*🎉 Podcast Complete!*\n{response_text}",
},
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*{podcast_title}*\n\nYour podcast has been successfully created with all assets! 🎊",
},
},
]
if full_banner_url:
blocks.append(
{
"type": "image",
"image_url": full_banner_url,
"alt_text": f"Banner for {podcast_title}",
}
)
action_elements = []
if full_audio_url:
action_elements.append(
{
"type": "button",
"text": {"type": "plain_text", "text": "🎵 Download Audio"},
"url": full_audio_url,
"action_id": "download_final_audio",
}
)
action_elements.append(
{
"type": "button",
"text": {"type": "plain_text", "text": "🎙️ Create New Podcast"},
"style": "primary",
"action_id": "new_podcast",
"value": thread_key,
}
)
blocks.append({"type": "actions", "elements": action_elements})
await send_slack_blocks(thread_key, blocks, "🎉 Podcast Complete!")
async def send_slack_blocks(thread_key: str, blocks: list, fallback_text: str = "Interactive elements loaded"):
try:
session_info = get_session_info(thread_key)
if not session_info:
print(f"No session info found for thread: {thread_key}")
return
session_id, channel_id, user_id = session_info
if thread_key.startswith("dm_"):
app.client.chat_postMessage(channel=channel_id, blocks=blocks, text=fallback_text)
else:
app.client.chat_postMessage(
channel=channel_id,
blocks=blocks,
text=fallback_text,
thread_ts=thread_key,
)
print(f"Sent interactive blocks to {thread_key}")
except Exception as e:
print(f"Error sending Slack blocks: {e}")
await send_slack_message(
thread_key,
"Interactive elements failed to load. Please continue with text responses.",
)
async def send_slack_message(thread_key: str, text: str):
try:
session_info = get_session_info(thread_key)
if not session_info:
print(f"No session info found for thread: {thread_key}")
return
session_id, channel_id, user_id = session_info
if len(text) > 3800:
chunks = [text[i : i + 3800] for i in range(0, len(text), 3800)]
for i, chunk in enumerate(chunks):
if i == 0:
if thread_key.startswith("dm_"):
app.client.chat_postMessage(channel=channel_id, text=chunk)
else:
app.client.chat_postMessage(channel=channel_id, text=chunk, thread_ts=thread_key)
else:
if thread_key.startswith("dm_"):
app.client.chat_postMessage(channel=channel_id, text=f"...continued:\n{chunk}")
else:
app.client.chat_postMessage(
channel=channel_id,
text=f"...continued:\n{chunk}",
thread_ts=thread_key,
)
else:
if thread_key.startswith("dm_"):
app.client.chat_postMessage(channel=channel_id, text=text)
else:
app.client.chat_postMessage(channel=channel_id, text=text, thread_ts=thread_key)
print(f"Sent message to {thread_key}: {text[:50]}...")
except Exception as e:
print(f"Error sending Slack message: {e}")
def clean_text(text, bot_id):
text = re.sub(f"<@{bot_id}>", "", text).strip()
return text
def format_script_for_slack(script_data) -> List[str]:
if isinstance(script_data, dict):
chunks = []
current_chunk = ""
title = script_data.get("title", "Podcast Script")
current_chunk += f"*{title}*\n\n"
sections = script_data.get("sections", [])
for i, section in enumerate(sections):
section_text = f"*Section {i + 1}: {section.get('type', 'Unknown').title()}*"
if section.get("title"):
section_text += f" - {section['title']}"
section_text += "\n\n"
if section.get("dialog"):
for dialog in section["dialog"]:
speaker = dialog.get("speaker", "Speaker")
text = dialog.get("text", "")
dialog_text = f"*{speaker}:* {text}\n\n"
if len(current_chunk + section_text + dialog_text) > 3500:
if current_chunk.strip():
chunks.append(current_chunk.strip())
current_chunk = section_text + dialog_text
else:
current_chunk += section_text + dialog_text
section_text = ""
else:
current_chunk += section_text
current_chunk += "\n---\n\n"
if current_chunk.strip():
chunks.append(current_chunk.strip())
return chunks if chunks else ["Script content could not be formatted."]
elif isinstance(script_data, str):
try:
parsed_data = json.loads(script_data)
if isinstance(parsed_data, dict):
return format_script_for_slack(parsed_data)
except (json.JSONDecodeError, TypeError):
pass
text = script_data
if len(text) <= 3500:
return [text]
else:
return [text[i : i + 3500] for i in range(0, len(text), 3500)]
else:
try:
text = str(script_data)
if len(text) <= 3500:
return [text]
else:
return [text[i : i + 3500] for i in range(0, len(text), 3500)]
except Exception as e:
print(f"Error converting script data to string: {e}")
return ["Error: Could not format script data for display."]
@app.action("source_selection")
def handle_source_selection(ack, body, logger):
ack()
@app.action("language_selection")
def handle_language_selection(ack, body, logger):
ack()
@app.action("confirm_sources")
def handle_confirm_sources(ack, body, client):
ack()
def process_confirmation():
try:
thread_key = body["actions"][0]["value"]
user_id = body["user"]["id"]
selected_sources = []
selected_language = "en"
if "state" in body and "values" in body["state"]:
values = body["state"]["values"]
if "source_selection_block" in values and "source_selection" in values["source_selection_block"]:
source_data = values["source_selection_block"]["source_selection"]
if "selected_options" in source_data and source_data["selected_options"]:
selected_sources = [int(opt["value"]) for opt in source_data["selected_options"]]
if "language_selection_block" in values and "language_selection" in values["language_selection_block"]:
lang_data = values["language_selection_block"]["language_selection"]
if "selected_option" in lang_data and lang_data["selected_option"]:
selected_language = lang_data["selected_option"]["value"]
session_info = get_session_info(thread_key)
if not session_info:
client.chat_postMessage(
channel=body["channel"]["id"],
thread_ts=thread_key if not thread_key.startswith("dm_") else None,
text="❌ Session not found. Please start a new conversation.",
)
return
session_id = session_info[0]
state_data = get_session_state(session_id)
languages = state_data.get("available_languages", [{"code": "en", "name": "English"}])
language_name = next(
(lang["name"] for lang in languages if lang["code"] == selected_language),
"English",
)
sources = state_data.get("search_results", [])
if selected_sources:
source_indices = [str(i + 1) for i in selected_sources]
selected_source_titles = [sources[i].get("title", f"Source {i + 1}") for i in selected_sources if i < len(sources)]
message = f"I've selected sources {', '.join(source_indices)} and I want the podcast in {language_name}."
else:
source_indices = [str(i + 1) for i in range(len(sources))]
selected_source_titles = [source.get("title", f"Source {i + 1}") for i, source in enumerate(sources)]
message = f"I want the podcast in {language_name} using all available sources."
try:
confirmation_blocks = create_confirmation_blocks(
selected_sources,
selected_source_titles,
language_name,
len(sources),
)
client.chat_update(
channel=body["channel"]["id"],
ts=body["message"]["ts"],
blocks=confirmation_blocks,
text="✅ Selection Confirmed",
)
print(f"Updated interactive message to confirmation state for {thread_key}")
except Exception as e:
print(f"Error updating message: {e}")
client.chat_postMessage(
channel=body["channel"]["id"],
thread_ts=thread_key if not thread_key.startswith("dm_") else None,
text=f"🔄 Processing your selection: {message}\n\n_Generating podcast script..._",
)
asyncio.run(process_source_confirmation(thread_key, message))
except Exception as e:
print(f"Error in confirm_sources: {e}")
client.chat_postMessage(
channel=body["channel"]["id"],
thread_ts=thread_key if not thread_key.startswith("dm_") else None,
text="❌ Error processing your selection. Please try again.",
)
executor.submit(process_confirmation)
def create_confirmation_blocks(selected_sources, selected_source_titles, language_name, total_sources):
if selected_sources:
source_text = ""
for i, (idx, title) in enumerate(zip(selected_sources, selected_source_titles)):
if i < 3:
short_title = title[:50] + "..." if len(title) > 50 else title
source_text += f"• *{idx}.* {short_title}\n"
elif i == 3:
remaining = len(selected_sources) - 3
source_text += f"• _...and {remaining} more sources_\n"
break
source_summary = f"*Selected {len(selected_sources)} of {total_sources} sources:*\n{source_text}"
else:
source_summary = f"*Selected all {total_sources} sources*"
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*✅ Selection Confirmed*\n_Your preferences have been saved and processing has started._",
},
},
{"type": "section", "text": {"type": "mrkdwn", "text": source_summary}},
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*Language:* {language_name} 🌐"},
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"_Confirmed at {datetime.now().strftime('%H:%M')} • Processing script generation..._",
}
],
},
]
return blocks
| 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_news_and_podcast_agents/beifong/agents/script_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/agents/script_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from typing import List, Optional
from dotenv import load_dotenv
from textwrap import dedent
from datetime import datetime
load_dotenv()
class Dialog(BaseModel):
speaker: str = Field(..., description="The speaker name (SHOULD BE 'ALEX' OR 'MORGAN')")
text: str = Field(
...,
description="The spoken text content for this speaker based on the requested langauge, default is English",
)
class Section(BaseModel):
type: str = Field(..., description="The section type (intro, headlines, article, outro)")
title: Optional[str] = Field(None, description="Optional title for the section (required for article type)")
dialog: List[Dialog] = Field(..., description="List of dialog exchanges between speakers")
class PodcastScript(BaseModel):
title: str = Field(..., description="The podcast episode title with date")
sections: List[Section] = Field(..., description="List of podcast sections (intro, headlines, articles, outro)")
PODCAST_AGENT_DESCRIPTION = "You are a helpful assistant that can generate engaging podcast scripts for the given sources."
PODCAST_AGENT_INSTRUCTIONS = dedent("""
You are a helpful assistant that can generate engaging podcast scripts for the given source content and query.
For given content, create an engaging podcast script that should be at least 15 minutes worth of content and your allowed enhance the script beyond given sources if you know something additional info will be interesting to the discussion or not enough conents available.
You use the provided sources to ground your podcast script generation process. Keep it engaging and interesting.
IMPORTANT: Generate the entire script in the provided language. basically only text field needs to be in requested language,
CONTENT GUIDELINES [THIS IS EXAMPLE YOU CAN CHANGE THE GUIDELINES ANYWAY BASED ON THE QUERY OR TOPIC DISCUSSED]:
- Provide insightful analysis that helps the audience understand the significance
- Include discussions on potential implications and broader context of each story
- Explain complex concepts in an accessible but thorough manner
- Make connections between current and relevant historical developments when applicable
- Provide comparisons and contrasts with similar stories or trends when relevant
PERSONALITY NOTES [THIS IS EXAMPLE YOU CAN CHANGE THE PERSONALITY OF ALEX AND MORGAN ANYWAY BASED ON THE QUERY OR TOPIC DISCUSSED]:
- Alex is more analytical and fact-focused
* Should reference specific details and data points
* Should explain complex topics clearly
* Should identify key implications of stories
- Morgan is more focused on human impact, social context, and practical applications
* Should analyze broader implications
* Should consider ethical implications and real-world applications
- Include natural, conversational banter and smooth transitions between topics
- Each article discussion should go beyond the basic summary to provide valuable insights
- Maintain a conversational but informed tone that would appeal to a general audience
IMPORTNAT:
- MAKE SURE PODCAST SCRIPS ARE AT LEAST 15 MINUTES LONG WHICH MEANS YOU NEED TO HAVE DETAILED DISCUSSIONS OFFCOURSE KEEP IT INTERESTING AND ENGAGING.
""")
def format_search_results_for_podcast(
search_results: List[dict],
) -> tuple[str, List[str]]:
created_at = datetime.now().strftime("%B %d, %Y at %I:%M %p")
structured_content = []
structured_content.append(f"PODCAST CREATION: {created_at}\n")
sources = []
for idx, search_result in enumerate(search_results):
try:
if search_result.get("confirmed", False):
sources.append(search_result["url"])
structured_content.append(
f"""
SOURCE {idx + 1}:
Title: {search_result['title']}
URL: {search_result['url']}
Content: {search_result.get('full_text') or search_result.get('description', '')}
---END OF SOURCE {idx + 1}---
""".strip()
)
except Exception as e:
print(f"Error processing search result: {e}")
content_texts = "\n\n".join(structured_content)
return content_texts, sources
def podcast_script_agent_run(
agent: Agent,
query: str,
language_name: str,
) -> str:
"""
Podcast Script Agent that takes the search_results (internally from search_results) and creates a podcast script for the given query and language.
Args:
agent: The agent instance
query: The search query
language_name: The language the podcast script should be.
Returns:
Response status
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
print("Podcast Script Agent Input:", query)
content_texts, sources = format_search_results_for_podcast(session_state.get("search_results", []))
if not content_texts:
return "No confirmed sources found to generate podcast script."
podcast_script_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=PODCAST_AGENT_INSTRUCTIONS,
description=PODCAST_AGENT_DESCRIPTION,
use_json_mode=True,
response_model=PodcastScript,
session_id=agent.session_id,
)
response = podcast_script_agent.run(
f"query: {query}\n language_name: {language_name}\n content_texts: {content_texts}\n, IMPORTANT: texts should be in {language_name} language.",
session_id=agent.session_id,
)
response_dict = response.to_dict()
response_dict = response_dict["content"]
response_dict["sources"] = sources
session_state["generated_script"] = response_dict
session_state['stage'] = 'script'
SessionService.save_session(session_id, session_state)
if not session_state["generated_script"] and not session_state["generated_script"].get("sections"):
return "Failed to generate podcast script."
return f"Generated podcast script for '{query}' with {len(sources)} confirmed sources." | 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/agents/search_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/agents/search_agent.py | from typing import List
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from agno.tools.duckduckgo import DuckDuckGoTools
from textwrap import dedent
from tools.wikipedia_search import wikipedia_search
from tools.google_news_discovery import google_news_discovery_run
from tools.jikan_search import jikan_search
from tools.embedding_search import embedding_search
from tools.social_media_search import social_media_search, social_media_trending_search
from tools.search_articles import search_articles
from tools.web_search import run_browser_search
load_dotenv()
class ReturnItem(BaseModel):
url: str = Field(..., description="The URL of the search result")
title: str = Field(..., description="The title of the search result")
description: str = Field(..., description="A brief description or summary of the search result content")
source_name: str = Field(
...,
description="The name/type of the source (e.g., 'wikipedia', 'general', or any reputable source tag)",
)
tool_used: str = Field(
...,
description="The tools used to generate the search results, unknown if not used or not applicable",
)
published_date: str = Field(
...,
description="The published date of the content in ISO format, if not available keep it empty",
)
is_scrapping_required: bool = Field(
...,
description="Set to True if the content need scraping, False otherwise, default keep it True if not sure",
)
class SearchResults(BaseModel):
items: List[ReturnItem] = Field(..., description="A list of search result items")
SEARCH_AGENT_DESCRIPTION = "You are a helpful assistant that can search the web for information."
SEARCH_AGENT_INSTRUCTIONS = dedent("""
You are a helpful assistant that can search the web or any other sources for information.
You should create topic for the search from the given query instead of blindly apply the query to the search tools.
For a given topic, your job is to search the web or any other sources and return the top 5 to 10 sources about the topic.
Keep the search sources of high quality and reputable, and sources should be relevant to the asked topic.
Sources should be from diverse platforms with no duplicates.
IMPORTANT: User queries might be fuzzy or misspelled. Understand the user's intent and act accordingly.
IMPORTANT: The output source_name field can be one of ["wikipedia", "general", or any source tag used"].
IMPORTANT: You have access to different search tools use them when appropriate which one is best for the given search query. Don't use particular tool if not required.
IMPORTANT: Make sure you are able to detect what tool to use and use it available tool tags = ["google_news_discovery", "duckduckgo", "wikipedia_search", "jikan_search", "social_media_search", "social_media_trending_search", "browser_search", "unknown"].
IMPORTANT: If query is news related please prefere google news over other news tools.
IMPORTANT: If returned sources are not of high quality or not relevant to the asked topic, don't include them in the returned sources.
IMPORTANT: Never include dates to the search query unless user explicitly asks for it.
IMPORTANT: You are allowed to use appropriate tools to get the best results even the single tool return enough results diverse check is better.
IMPORTANT: You have access to browser agent for searching as well use it when other source can't suitable for the given tasks but input should detailed instruction to the run_browser_search agent to get the best results and also use it conservatively because it's expensive process.
""")
def search_agent_run(agent: Agent, query: str) -> str:
"""
Search Agent which searches the web and other sources for relevant sources about the given topic or query.
Args:
agent: The agent instance
query: The search query
Returns:
A formatted string response with the search results (link and gist only)
"""
print("Search Agent Input:", query)
session_id = agent.session_id
from services.internal_session_service import SessionService
session = SessionService.get_session(session_id)
current_state = session["state"]
search_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=SEARCH_AGENT_INSTRUCTIONS,
description=SEARCH_AGENT_DESCRIPTION,
use_json_mode=True,
response_model=SearchResults,
tools=[
google_news_discovery_run,
DuckDuckGoTools(),
wikipedia_search,
jikan_search,
embedding_search,
social_media_search,
social_media_trending_search,
search_articles,
run_browser_search,
],
session_id=session_id,
)
response = search_agent.run(query, session_id=session_id)
response_dict = response.to_dict()
current_state["stage"] = "search"
current_state["search_results"] = response_dict["content"]["items"]
SessionService.save_session(session_id, current_state)
has_results = "search_results" in current_state and current_state["search_results"]
return f"Found {len(response_dict['content']['items'])} sources about {query} {'and added to the search_results' if has_results else ''}" | 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/agents/audio_generate_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/agents/audio_generate_agent.py | from agno.agent import Agent
import os
from datetime import datetime
import tempfile
import numpy as np
import soundfile as sf
from typing import Any, Dict, List, Optional, Tuple
from utils.load_api_keys import load_api_key
from openai import OpenAI
from scipy import signal
PODCASTS_FOLDER = "podcasts"
PODCAST_AUDIO_FOLDER = os.path.join(PODCASTS_FOLDER, "audio")
PODCAST_MUSIC_FOLDER = os.path.join('static', "musics")
OPENAI_VOICES = {1: "alloy", 2: "echo", 3: "fable", 4: "onyx", 5: "nova", 6: "shimmer"}
DEFAULT_VOICE_MAP = {1: "alloy", 2: "nova"}
TTS_MODEL = "gpt-4o-mini-tts"
INTRO_MUSIC_FILE = os.path.join(PODCAST_MUSIC_FOLDER, "intro_audio.mp3")
OUTRO_MUSIC_FILE = os.path.join(PODCAST_MUSIC_FOLDER, "intro_audio.mp3")
def resample_audio_scipy(audio, original_sr, target_sr):
if original_sr == target_sr:
return audio
resampling_ratio = target_sr / original_sr
num_samples = int(len(audio) * resampling_ratio)
resampled = signal.resample(audio, num_samples)
return resampled
def create_silence_audio(silence_duration: float, sampling_rate: int) -> np.ndarray:
if sampling_rate <= 0:
print(f"Invalid sampling rate ({sampling_rate}) for silence generation")
return np.zeros(0, dtype=np.float32)
return np.zeros(int(sampling_rate * silence_duration), dtype=np.float32)
def combine_audio_segments(audio_segments: List[np.ndarray], silence_duration: float, sampling_rate: int) -> np.ndarray:
if not audio_segments:
return np.zeros(0, dtype=np.float32)
silence = create_silence_audio(silence_duration, sampling_rate)
combined_segments = []
for i, segment in enumerate(audio_segments):
combined_segments.append(segment)
if i < len(audio_segments) - 1:
combined_segments.append(silence)
combined = np.concatenate(combined_segments)
max_amp = np.max(np.abs(combined))
if max_amp > 0:
combined = combined / max_amp * 0.95
return combined
def process_audio_file(temp_path: str) -> Optional[Tuple[np.ndarray, int]]:
try:
from pydub import AudioSegment
audio_segment = AudioSegment.from_mp3(temp_path)
channels = audio_segment.channels
sample_width = audio_segment.sample_width
frame_rate = audio_segment.frame_rate
samples = np.array(audio_segment.get_array_of_samples())
if channels == 2:
samples = samples.reshape(-1, 2).mean(axis=1)
max_possible_value = float(2 ** (8 * sample_width - 1))
samples = samples.astype(np.float32) / max_possible_value
return samples, frame_rate
except ImportError:
print("Pydub not available, falling back to soundfile")
except Exception as e:
print(f"Pydub processing failed: {e}")
try:
audio_np, samplerate = sf.read(temp_path)
return audio_np, samplerate
except Exception as e:
print(f"Failed to process audio with soundfile: {e}")
try:
from pydub import AudioSegment
sound = AudioSegment.from_mp3(temp_path)
wav_path = temp_path.replace(".mp3", ".wav")
sound.export(wav_path, format="wav")
audio_np, samplerate = sf.read(wav_path)
os.unlink(wav_path)
return audio_np, samplerate
except Exception as e:
print(f"All audio processing methods failed: {e}")
return None
def resample_audio(audio, orig_sr, target_sr):
try:
import librosa
return librosa.resample(audio, orig_sr=orig_sr, target_sr=target_sr)
except ImportError:
print("Librosa not available for resampling")
return audio
except Exception as e:
print(f"Resampling failed: {e}")
return audio
def text_to_speech_openai(
client: OpenAI,
text: str,
speaker_id: int,
voice_map: Dict[int, str] = None,
model: str = TTS_MODEL,
) -> Optional[Tuple[np.ndarray, int]]:
if not text.strip():
print("Empty text provided, skipping TTS generation")
return None
voice_map = voice_map or DEFAULT_VOICE_MAP
voice = voice_map.get(speaker_id)
if not voice:
if speaker_id in OPENAI_VOICES:
voice = OPENAI_VOICES[speaker_id]
else:
voice = next(iter(voice_map.values()), "alloy")
print(f"No voice mapping for speaker {speaker_id}, using {voice}")
try:
print(f"Generating TTS for speaker {speaker_id} using voice '{voice}'")
response = client.audio.speech.create(
model=model,
voice=voice,
input=text,
response_format="mp3",
)
audio_data = response.content
if not audio_data:
print("OpenAI TTS returned empty response")
return None
print(f"Received {len(audio_data)} bytes from OpenAI TTS")
temp_file = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)
temp_path = temp_file.name
temp_file.close()
with open(temp_path, "wb") as f:
f.write(audio_data)
try:
return process_audio_file(temp_path)
finally:
if os.path.exists(temp_path):
os.unlink(temp_path)
except Exception as e:
print(f"OpenAI TTS API error: {e}")
import traceback
traceback.print_exc()
return None
def create_podcast(
script: Any,
output_path: str,
tts_engine: str = "openai",
language_code: str = "en",
silence_duration: float = 0.7,
voice_map: Dict[int, str] = None,
model: str = TTS_MODEL,
) -> Optional[str]:
if tts_engine.lower() != "openai":
print(f"Only OpenAI TTS engine is available in this standalone version. Requested: {tts_engine}")
return None
try:
api_key = load_api_key("OPENAI_API_KEY")
if not api_key:
print("No OpenAI API key provided")
return None
client = OpenAI(api_key=api_key)
print("OpenAI client initialized")
except Exception as e:
print(f"Failed to initialize OpenAI client: {e}")
return None
output_path = os.path.abspath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
if voice_map is None:
voice_map = DEFAULT_VOICE_MAP.copy()
model_to_use = model
if model == "tts-1" and language_code == "en":
model_to_use = "tts-1-hd"
print(f"Using high-definition TTS model for English: {model_to_use}")
generated_segments = []
sampling_rate_detected = None
if hasattr(script, "entries"):
entries = script.entries
else:
entries = script
print(f"Processing {len(entries)} script entries")
for i, entry in enumerate(entries):
if hasattr(entry, "speaker"):
speaker_id = entry.speaker
entry_text = entry.text
else:
speaker_id = entry["speaker"]
entry_text = entry["text"]
print(f"Processing entry {i + 1}/{len(entries)}: Speaker {speaker_id}")
result = text_to_speech_openai(
client=client,
text=entry_text,
speaker_id=speaker_id,
voice_map=voice_map,
model=model_to_use,
)
if result:
segment_audio, segment_rate = result
if sampling_rate_detected is None:
sampling_rate_detected = segment_rate
print(f"Using sample rate: {sampling_rate_detected} Hz")
elif sampling_rate_detected != segment_rate:
print(f"Sample rate mismatch: {sampling_rate_detected} vs {segment_rate}")
try:
segment_audio = resample_audio(segment_audio, segment_rate, sampling_rate_detected)
print(f"Resampled to {sampling_rate_detected} Hz")
except Exception as e:
sampling_rate_detected = segment_rate
print(f"Resampling failed: {e}")
generated_segments.append(segment_audio)
else:
print(f"Failed to generate audio for entry {i + 1}")
if not generated_segments:
print("No audio segments were generated")
return None
if sampling_rate_detected is None:
print("Could not determine sample rate")
return None
print(f"Combining {len(generated_segments)} audio segments")
full_audio = combine_audio_segments(generated_segments, silence_duration, sampling_rate_detected)
if full_audio.size == 0:
print("Combined audio is empty")
return None
try:
if os.path.exists(INTRO_MUSIC_FILE):
intro_music, intro_sr = sf.read(INTRO_MUSIC_FILE)
print(f"Loaded intro music: {len(intro_music) / intro_sr:.1f} seconds")
if intro_music.ndim == 2:
intro_music = np.mean(intro_music, axis=1)
if intro_sr != sampling_rate_detected:
intro_music = resample_audio_scipy(intro_music, intro_sr, sampling_rate_detected)
full_audio = np.concatenate([intro_music, full_audio])
print("Added intro music")
if os.path.exists(OUTRO_MUSIC_FILE):
outro_music, outro_sr = sf.read(OUTRO_MUSIC_FILE)
print(f"Loaded outro music: {len(outro_music) / outro_sr:.1f} seconds")
if outro_music.ndim == 2:
outro_music = np.mean(outro_music, axis=1)
if outro_sr != sampling_rate_detected:
outro_music = resample_audio_scipy(outro_music, outro_sr, sampling_rate_detected)
full_audio = np.concatenate([full_audio, outro_music])
print("Added outro music")
except Exception as e:
print(f"Could not add intro/outro music: {e}")
print("Continuing without background music")
print(f"Writing audio to {output_path}")
try:
sf.write(output_path, full_audio, sampling_rate_detected)
except Exception as e:
print(f"Failed to write audio file: {e}")
return None
if os.path.exists(output_path):
file_size = os.path.getsize(output_path)
print(f"Audio file created: {output_path} ({file_size / 1024:.1f} KB)")
return output_path
else:
print(f"Failed to create audio file at {output_path}")
return None
def audio_generate_agent_run(agent: Agent) -> str:
"""
Generate an audio file for the podcast using the selected TTS engine.
Args:
agent: The agent instance
Returns:
A message with the result of audio generation
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
script_data = session_state.get("generated_script", {})
if not script_data or (isinstance(script_data, dict) and not script_data.get("sections")):
error_msg = "Cannot generate audio: No podcast script data found. Please generate a script first."
print(error_msg)
return error_msg
if isinstance(script_data, dict):
podcast_title = script_data.get("title", "Your Podcast")
else:
podcast_title = "Your Podcast"
session_state["stage"] = "audio"
audio_dir = PODCAST_AUDIO_FOLDER
audio_filename = f"podcast_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
audio_path = os.path.join(audio_dir, audio_filename)
try:
if isinstance(script_data, dict) and "sections" in script_data:
speaker_map = {"ALEX": 1, "MORGAN": 2}
script_entries = []
for section in script_data.get("sections", []):
for dialog in section.get("dialog", []):
speaker = dialog.get("speaker", "ALEX")
text = dialog.get("text", "")
if text and speaker in speaker_map:
script_entries.append({"text": text, "speaker": speaker_map[speaker]})
if not script_entries:
error_msg = "Cannot generate audio: No dialog found in the script."
print(error_msg)
return error_msg
selected_language = session_state.get("selected_language", {"code": "en", "name": "English"})
language_code = selected_language.get("code", "en")
language_name = selected_language.get("name", "English")
tts_engine = "openai"
if tts_engine == "openai" and not load_api_key("OPENAI_API_KEY"):
error_msg = "Cannot generate audio: OpenAI API key not found."
print(error_msg)
return error_msg
print(f"Generating podcast audio using {tts_engine} TTS engine in {language_name} language")
full_audio_path = create_podcast(
script=script_entries,
output_path=audio_path,
tts_engine=tts_engine,
language_code=language_code,
)
if not full_audio_path:
error_msg = f"Failed to generate podcast audio with {tts_engine} TTS engine."
print(error_msg)
return error_msg
audio_url = f"{os.path.basename(full_audio_path)}"
session_state["audio_url"] = audio_url
session_state["show_audio_for_confirmation"] = True
SessionService.save_session(session_id, session_state)
print(f"Successfully generated podcast audio: {full_audio_path}")
return f"I've generated the audio for your '{podcast_title}' podcast using {tts_engine.capitalize()} voices in {language_name}. You can listen to it in the player below. What do you think? If it sounds good, click 'Sounds Great!' to complete your podcast."
else:
error_msg = "Cannot generate audio: Script is not in the expected format."
print(error_msg)
return error_msg
except Exception as e:
error_msg = f"Error generating podcast audio: {str(e)}"
print(error_msg)
return f"I encountered an error while generating the podcast audio: {str(e)}. Please try again or let me know if you'd like to proceed without audio." | 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/agents/scrape_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/agents/scrape_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from tools.browser_crawler import create_browser_crawler
from textwrap import dedent
load_dotenv()
class ScrapedContent(BaseModel):
url: str = Field(..., description="The URL of the search result")
description: str = Field(description="The description of the search result")
full_text: str = Field(
...,
description="The full text of the given source URL, if not available or not applicable keep it empty",
)
published_date: str = Field(
...,
description="The published date of the content in ISO format, if not available keep it empty",
)
SCRAPE_AGENT_DESCRIPTION = "You are a helpful assistant that can scrape the URL for full content."
SCRAPE_AGENT_INSTRUCTIONS = dedent("""
You are a content verification and formatting assistant.
You will receive a batch of pre-scraped content from various URLs along with a search query.
Your job is to:
1. VERIFY RELEVANCE: Ensure each piece of content is relevant to the given query
2. QUALITY CONTROL: Filter out low-quality, duplicate, or irrelevant content
3. FORMAT CONSISTENCY: Ensure all content follows a consistent format
4. LENGTH OPTIMIZATION: Keep content at reasonable length - not too long, not too short
5. CLEAN TEXT: Remove any formatting artifacts, ads, or navigation elements from scraped content
For each piece of content, return:
- full_text: The cleaned, relevant text content (or empty if not relevant/low quality)
- published_date: The publication date in ISO format (or empty if not available)
Note: Some content may be fallback descriptions (when scraping failed) - treat these appropriately and don't penalize them for being shorter.
IMPORTANT: Focus on quality over quantity. It's better to return fewer high-quality, relevant pieces than many low-quality ones.
""")
def crawl_urls_batch(search_results):
url_to_search_results = {}
unique_urls = []
for search_result in search_results:
if not search_result.get("url", False):
continue
if not search_result.get("is_scrapping_required", True):
continue
if not search_result.get('original_url'):
search_result['original_url'] = search_result['url']
url = search_result["url"]
if url not in url_to_search_results:
url_to_search_results[url] = []
unique_urls.append(url)
url_to_search_results[url].append(search_result)
browser_crawler = create_browser_crawler()
scraped_results = browser_crawler.scrape_urls(unique_urls)
url_to_scraped = {result["original_url"]: result for result in scraped_results}
updated_search_results = []
successful_scrapes = 0
failed_scrapes = 0
for search_result in search_results:
original_url = search_result["url"]
scraped = url_to_scraped.get(original_url, {})
updated_result = search_result.copy()
updated_result["original_url"] = original_url
if scraped.get("success", False):
updated_result["url"] = scraped.get("final_url", original_url)
updated_result["full_text"] = scraped.get("full_text", "")
updated_result["published_date"] = scraped.get("published_date", "")
successful_scrapes += 1
else:
updated_result["url"] = original_url
updated_result["full_text"] = search_result.get("description", "")
updated_result["published_date"] = ""
failed_scrapes += 1
updated_search_results.append(updated_result)
return updated_search_results, successful_scrapes, failed_scrapes
def verify_content_with_agent(agent, query, search_results, use_agent=True):
if not use_agent:
return search_results
verified_search_results = []
for _, search_result in enumerate(search_results):
content_for_verification = {
"url": search_result["url"],
"description": search_result.get("description", ""),
"full_text": search_result["full_text"],
"published_date": search_result["published_date"],
}
search_result["agent_verified"] = False
try:
scrape_agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
instructions=SCRAPE_AGENT_INSTRUCTIONS,
description=SCRAPE_AGENT_DESCRIPTION,
use_json_mode=True,
session_id=agent.session_id,
response_model=ScrapedContent,
)
response = scrape_agent.run(
f"Query: {query}\n"
f"Verify and format this scraped content. "
f"Keep content relevant to the query and ensure quality: {content_for_verification}",
session_id=agent.session_id,
)
verified_item = response.to_dict()["content"]
search_result["full_text"] = verified_item.get("full_text", search_result["full_text"])
search_result["published_date"] = verified_item.get("published_date", search_result["published_date"])
search_result["agent_verified"] = True
except Exception as _:
pass
verified_search_results.append(search_result)
return verified_search_results
def scrape_agent_run(
agent: Agent,
query: str,
) -> str:
"""
Scrape Agent that takes the search_results (internaly from search_results) and scrapes each URL for full content, making sure those contents are of high quality and relevant to the topic.
Args:
agent: The agent instance
query: The search query
Returns:
Response status
"""
print("Scrape Agent Input:", query)
session_id = agent.session_id
from services.internal_session_service import SessionService
session = SessionService.get_session(session_id)
current_state = session["state"]
updated_results, _, _ = crawl_urls_batch(current_state["search_results"])
verified_results = verify_content_with_agent(agent, query, updated_results, use_agent=False)
current_state["search_results"] = verified_results
SessionService.save_session(session_id, current_state)
has_results = "search_results" in current_state and current_state["search_results"]
return f"Scraped {len(current_state['search_results'])} sources with full content relevant to '{query}'{' and updated the full text and published date in the search_results items' if has_results else ''}." | 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/agents/image_generate_agent.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/agents/image_generate_agent.py | from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.dalle import DalleTools
from textwrap import dedent
import json
from dotenv import load_dotenv
import uuid
from db.agent_config_v2 import PODCAST_IMG_DIR
import os
import requests
load_dotenv()
IMAGE_GENERATION_AGENT_DESCRIPTION = "You are an AI agent that can generate images using DALL-E."
IMAGE_GENERATION_AGENT_INSTRUCTIONS = dedent("""
When the user asks you to create an image, use the `create_image` tool to create the image.
Create a modern, eye-catching podcast cover images that represents a podcast given podcast topic.
Create 3 images for the given podcast topic.
IMPORTANT INSTRUCTIONS:
- DO NOT include ANY text in the image
- DO NOT include any words, titles, or lettering
- Create a purely visual and symbolic representation
- Use imagery that represents the specific topics mentioned
- I like Studio Ghibli flavor if possible
- The image should work well as a podcast cover thumbnail
- Create a clean, professional design suitable for a podcast
- AGAIN, DO NOT INCLUDE ANY TEXT
""")
def download_images(image_urls):
local_image_filenames = []
try:
if image_urls:
for image_url in image_urls:
unique_id = str(uuid.uuid4())
filename = f"podcast_banner_{unique_id}.png"
os.makedirs(PODCAST_IMG_DIR, exist_ok=True)
print(f"Downloading image: {filename}")
response = requests.get(image_url, timeout=30)
response.raise_for_status()
image_path = os.path.join(PODCAST_IMG_DIR, filename)
with open(image_path, "wb") as f:
f.write(response.content)
local_image_filenames.append(filename)
print(f"Successfully downloaded: {filename}")
except requests.exceptions.RequestException as e:
print(f"Error downloading images (network): {e}")
except Exception as e:
print(f"Error downloading images: {e}")
return local_image_filenames
def image_generation_agent_run(agent: Agent, query: str) -> str:
"""
Image Generation Agent that takes the generated_script (internally from session_state) and creates a images for the given podcast script.
Args:
agent: The agent instance
query: any custom preferences for the image generation
Returns:
Response status
"""
from services.internal_session_service import SessionService
session_id = agent.session_id
session = SessionService.get_session(session_id)
session_state = session["state"]
print("Image Generation Agent input: ", query)
try:
image_agent = Agent(
model=OpenAIChat(id="gpt-4o"),
tools=[DalleTools()],
description=IMAGE_GENERATION_AGENT_DESCRIPTION,
instructions=IMAGE_GENERATION_AGENT_INSTRUCTIONS,
markdown=True,
show_tool_calls=True,
session_id=agent.session_id,
)
image_agent.run(f"query: {query},\n podcast script: {json.dumps(session_state['generated_script'])}", session_id=agent.session_id)
images = image_agent.get_images()
image_urls = []
if images and isinstance(images, list):
for image_response in images:
image_url = image_response.url
image_urls.append(image_url)
local_image_filenames = download_images(image_urls)
session_state["banner_images"] = local_image_filenames
if local_image_filenames:
session_state["banner_url"] = local_image_filenames[0]
except Exception as e:
print(f"Error in Image Generation Agent: {e}")
return "Error in Image Generation Agent"
session_state["stage"] = "image"
SessionService.save_session(session_id, session_state)
return "Required banner images for the podcast are generated successfully." | 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/db/podcasts.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/podcasts.py | import json
from datetime import datetime
from typing import Dict, Any, Optional
from .connection import execute_query
def store_podcast(
podcasts_db_path: str,
podcast_data: Dict[str, Any],
audio_path: Optional[str],
banner_path: Optional[str],
tts_engine: str = "kokoro",
language_code: str = "en",
) -> int:
today = datetime.now().strftime("%Y-%m-%d")
podcast_json = json.dumps(podcast_data)
audio_generated = 1 if audio_path else 0
sources_json = json.dumps(podcast_data.get("sources", []))
query = """
INSERT INTO podcasts
(title, date, content_json, audio_generated, audio_path, banner_img_path,
tts_engine, language_code, sources_json, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
params = (
podcast_data.get("title", f"Podcast {today}"),
today,
podcast_json,
audio_generated,
audio_path,
banner_path,
tts_engine,
language_code,
sources_json,
datetime.now().isoformat(),
)
return execute_query(podcasts_db_path, query, params)
def get_podcast(podcasts_db_path: str, podcast_id: int) -> Optional[Dict[str, Any]]:
query = """
SELECT id, title, date, content_json, audio_generated, audio_path, banner_img_path,
tts_engine, language_code, sources_json, created_at
FROM podcasts
WHERE id = ?
"""
podcast = execute_query(podcasts_db_path, query, (podcast_id,), fetch=True, fetch_one=True)
if podcast:
if podcast.get("content_json"):
try:
podcast["content"] = json.loads(podcast["content_json"])
except json.JSONDecodeError:
podcast["content"] = {}
if podcast.get("sources_json"):
try:
podcast["sources"] = json.loads(podcast["sources_json"])
except json.JSONDecodeError:
podcast["sources"] = []
return podcast
def get_recent_podcasts(podcasts_db_path: str, limit: int = 10) -> list:
query = """
SELECT id, title, date, audio_generated, audio_path, banner_img_path,
tts_engine, language_code, sources_json, created_at
FROM podcasts
ORDER BY date DESC, created_at DESC
LIMIT ?
"""
podcasts = execute_query(podcasts_db_path, query, (limit,), fetch=True)
for podcast in podcasts:
if podcast.get("sources_json"):
try:
podcast["sources"] = json.loads(podcast["sources_json"])
except json.JSONDecodeError:
podcast["sources"] = []
return podcasts
def update_podcast_audio(podcasts_db_path: str, podcast_id: int, audio_path: str) -> bool:
query = """
UPDATE podcasts
SET audio_path = ?, audio_generated = 1
WHERE id = ?
"""
rows_affected = execute_query(podcasts_db_path, query, (audio_path, podcast_id))
return rows_affected > 0
def update_podcast_banner(podcasts_db_path: str, podcast_id: int, banner_path: str) -> bool:
query = """
UPDATE podcasts
SET banner_img_path = ?
WHERE id = ?
"""
rows_affected = execute_query(podcasts_db_path, query, (banner_path, podcast_id))
return rows_affected > 0
def update_podcast_metadata(
podcasts_db_path: str, podcast_id: int, tts_engine: Optional[str] = None, language_code: Optional[str] = None, sources_json: Optional[str] = None
) -> bool:
update_parts = []
params = []
if tts_engine is not None:
update_parts.append("tts_engine = ?")
params.append(tts_engine)
if language_code is not None:
update_parts.append("language_code = ?")
params.append(language_code)
if sources_json is not None:
update_parts.append("sources_json = ?")
params.append(sources_json)
if not update_parts:
return False
query = f"""
UPDATE podcasts
SET {", ".join(update_parts)}
WHERE id = ?
"""
params.append(podcast_id)
rows_affected = execute_query(podcasts_db_path, query, tuple(params))
return rows_affected > 0
| 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/db/tasks.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/tasks.py | from datetime import datetime, timedelta
from .connection import execute_query, db_connection
def create_task(
tasks_db_path,
name,
command,
frequency,
frequency_unit,
description=None,
enabled=True,
):
query = """
INSERT INTO tasks
(name, description, command, frequency, frequency_unit, enabled, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
"""
params = (
name,
description,
command,
frequency,
frequency_unit,
1 if enabled else 0,
datetime.now().isoformat(),
)
return execute_query(tasks_db_path, query, params)
def is_task_running(tasks_db_path, task_id):
query = """
SELECT 1
FROM task_executions
WHERE task_id = ? AND status = 'running'
LIMIT 1
"""
try:
result = execute_query(tasks_db_path, query, (task_id,), fetch=True, fetch_one=True)
return result is not None # True if a running entry exists
except Exception as e:
print(f"Database error checking running status for task {task_id}: {e}")
return True
def get_task(tasks_db_path, task_id):
query = """
SELECT id, name, description, command, frequency, frequency_unit, enabled, last_run, created_at
FROM tasks
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (task_id,), fetch=True, fetch_one=True)
def get_all_tasks(tasks_db_path, include_disabled=False):
if include_disabled:
query = """
SELECT id, name, description, command, frequency, frequency_unit, enabled, last_run, created_at
FROM tasks
ORDER BY name
"""
return execute_query(tasks_db_path, query, fetch=True)
else:
query = """
SELECT id, name, description, command, frequency, frequency_unit, enabled, last_run, created_at
FROM tasks
WHERE enabled = 1
ORDER BY name
"""
return execute_query(tasks_db_path, query, fetch=True)
def update_task(tasks_db_path, task_id, updates):
allowed_fields = [
"name",
"description",
"command",
"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 0
query = f"""
UPDATE tasks
SET {", ".join(set_clauses)}
WHERE id = ?
"""
params.append(task_id)
return execute_query(tasks_db_path, query, tuple(params))
def delete_task(tasks_db_path, task_id):
query = """
DELETE FROM tasks
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (task_id,))
def update_task_last_run(tasks_db_path, task_id, timestamp=None):
if timestamp is None:
timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
query = """
UPDATE tasks
SET last_run = ?
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (timestamp, task_id))
def create_task_execution(tasks_db_path, task_id, status, error_message=None, output=None):
start_time = datetime.now().isoformat()
query = """
INSERT INTO task_executions
(task_id, start_time, status, error_message, output)
VALUES (?, ?, ?, ?, ?)
"""
params = (task_id, start_time, status, error_message, output)
execute_query(tasks_db_path, query, params)
try:
with db_connection(tasks_db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, params)
conn.commit()
return cursor.lastrowid # Return the ID of the inserted row
except Exception as e:
print(f"Database error in create_task_execution: {e}")
return None #
def update_task_execution(tasks_db_path, execution_id, status, error_message=None, output=None):
end_time = datetime.now().isoformat()
query = """
UPDATE task_executions
SET end_time = ?, status = ?, error_message = ?, output = ?
WHERE id = ?
"""
params = (end_time, status, error_message, output, execution_id)
return execute_query(tasks_db_path, query, params)
def get_recent_task_executions(tasks_db_path, task_id=None, limit=10):
if 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 ?
"""
params = (task_id, limit)
else:
query = """
SELECT id, task_id, start_time, end_time, status, error_message, output
FROM task_executions
ORDER BY start_time DESC
LIMIT ?
"""
params = (limit,)
return execute_query(tasks_db_path, query, params, fetch=True)
def get_task_execution(tasks_db_path, execution_id):
query = """
SELECT id, task_id, start_time, end_time, status, error_message, output
FROM task_executions
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (execution_id,), fetch=True, fetch_one=True)
def mark_task_disabled(tasks_db_path, task_id):
query = """
UPDATE tasks
SET enabled = 0
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (task_id,))
def mark_task_enabled(tasks_db_path, task_id):
query = """
UPDATE tasks
SET enabled = 1
WHERE id = ?
"""
return execute_query(tasks_db_path, query, (task_id,))
def get_task_stats(tasks_db_path):
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
"""
return execute_query(tasks_db_path, query, fetch=True, fetch_one=True)
def get_execution_stats(tasks_db_path, days=7):
cutoff_date = (datetime.now() - timedelta(days=days)).isoformat()
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 >= ?
"""
return execute_query(tasks_db_path, query, (cutoff_date,), fetch=True, fetch_one=True)
def get_pending_tasks(tasks_db_path):
query = """
SELECT id, name, description, command, 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 = execute_query(tasks_db_path, query, fetch=True)
return tasks
| 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/db/agent_config_v2.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/agent_config_v2.py | from agno.storage.sqlite import SqliteStorage
from db.config import get_agent_session_db_path
import json
AGENT_MODEL = "gpt-4o"
AVAILABLE_LANGS = [
{"code": "en", "name": "English"},
{"code": "zh", "name": "Chinese"},
{"code": "de", "name": "German"},
{"code": "es", "name": "Spanish"},
{"code": "ru", "name": "Russian"},
{"code": "ko", "name": "Korean"},
{"code": "fr", "name": "French"},
{"code": "ja", "name": "Japanese"},
{"code": "pt", "name": "Portuguese"},
{"code": "tr", "name": "Turkish"},
{"code": "pl", "name": "Polish"},
{"code": "ca", "name": "Catalan"},
{"code": "nl", "name": "Dutch"},
{"code": "ar", "name": "Arabic"},
{"code": "sv", "name": "Swedish"},
{"code": "it", "name": "Italian"},
{"code": "id", "name": "Indonesian"},
{"code": "hi", "name": "Hindi"},
{"code": "fi", "name": "Finnish"},
{"code": "vi", "name": "Vietnamese"},
{"code": "he", "name": "Hebrew"},
{"code": "uk", "name": "Ukrainian"},
{"code": "el", "name": "Greek"},
{"code": "ms", "name": "Malay"},
{"code": "cs", "name": "Czech"},
{"code": "ro", "name": "Romanian"},
{"code": "da", "name": "Danish"},
{"code": "hu", "name": "Hungarian"},
{"code": "ta", "name": "Tamil"},
{"code": "no", "name": "Norwegian"},
{"code": "th", "name": "Thai"},
{"code": "ur", "name": "Urdu"},
{"code": "hr", "name": "Croatian"},
{"code": "bg", "name": "Bulgarian"},
{"code": "lt", "name": "Lithuanian"},
{"code": "la", "name": "Latin"},
{"code": "mi", "name": "Maori"},
{"code": "ml", "name": "Malayalam"},
{"code": "cy", "name": "Welsh"},
{"code": "sk", "name": "Slovak"},
{"code": "te", "name": "Telugu"},
{"code": "fa", "name": "Persian"},
{"code": "lv", "name": "Latvian"},
{"code": "bn", "name": "Bengali"},
{"code": "sr", "name": "Serbian"},
{"code": "az", "name": "Azerbaijani"},
{"code": "sl", "name": "Slovenian"},
{"code": "kn", "name": "Kannada"},
{"code": "et", "name": "Estonian"},
{"code": "mk", "name": "Macedonian"},
{"code": "br", "name": "Breton"},
{"code": "eu", "name": "Basque"},
{"code": "is", "name": "Icelandic"},
{"code": "hy", "name": "Armenian"},
{"code": "ne", "name": "Nepali"},
{"code": "mn", "name": "Mongolian"},
{"code": "bs", "name": "Bosnian"},
{"code": "kk", "name": "Kazakh"},
{"code": "sq", "name": "Albanian"},
{"code": "sw", "name": "Swahili"},
{"code": "gl", "name": "Galician"},
{"code": "mr", "name": "Marathi"},
{"code": "pa", "name": "Punjabi"},
{"code": "si", "name": "Sinhala"},
{"code": "km", "name": "Khmer"},
{"code": "sn", "name": "Shona"},
{"code": "yo", "name": "Yoruba"},
{"code": "so", "name": "Somali"},
{"code": "af", "name": "Afrikaans"},
{"code": "oc", "name": "Occitan"},
{"code": "ka", "name": "Georgian"},
{"code": "be", "name": "Belarusian"},
{"code": "tg", "name": "Tajik"},
{"code": "sd", "name": "Sindhi"},
{"code": "gu", "name": "Gujarati"},
{"code": "am", "name": "Amharic"},
{"code": "yi", "name": "Yiddish"},
{"code": "lo", "name": "Lao"},
{"code": "uz", "name": "Uzbek"},
{"code": "fo", "name": "Faroese"},
{"code": "ht", "name": "Haitian creole"},
{"code": "ps", "name": "Pashto"},
{"code": "tk", "name": "Turkmen"},
{"code": "nn", "name": "Nynorsk"},
{"code": "mt", "name": "Maltese"},
{"code": "sa", "name": "Sanskrit"},
{"code": "lb", "name": "Luxembourgish"},
{"code": "my", "name": "Myanmar"},
{"code": "bo", "name": "Tibetan"},
{"code": "tl", "name": "Tagalog"},
{"code": "mg", "name": "Malagasy"},
{"code": "as", "name": "Assamese"},
{"code": "tt", "name": "Tatar"},
{"code": "haw", "name": "Hawaiian"},
{"code": "ln", "name": "Lingala"},
{"code": "ha", "name": "Hausa"},
{"code": "ba", "name": "Bashkir"},
{"code": "jw", "name": "Javanese"},
{"code": "su", "name": "Sundanese"},
{"code": "yue", "name": "Cantonese"},
]
TOGGLE_UI_STATES = [
"show_sources_for_selection",
"show_script_for_confirmation",
"show_banner_for_confirmation",
"show_audio_for_confirmation",
]
AGENT_DESCRIPTION = "You are name is Beifong, a helpful assistant that guides users to choose best sources for the podcast and allow them to generate the podcast script."
# sacred commandments, touch these with devotion.
AGENT_INSTRUCTIONS = [
"Guide users to choose the best sources for the podcast and allow them to generate the podcast script and images for the podcast and audio for the podcast.",
"1. Make sure you get the intent of the topic from the user. It can be fuzzy and contain spelling mistakes from the user, so act as intent detection and get clarification only if needed.",
"1a. Keep this phase as quick as possible. Try to avoid too many back and forth conversations. Try to infer the intent if you're confident you can go right to the next search phase without confirming with the user. The less back and forth, the better for the user experience.",
"2. Once you understand the intent of the topic, use the available search tools (we have search agent where you can pass the query and along with appropriate prompt search agent has lot of search tools and api access which you don't have so you can instruct if needed) to get diverse and high-quality sources for the topic. and also make sure give appropriate short title for the chat and update the chat title using update_chat_title tool",
"2a. Once we receive the search results. do the full scraping using appropriate scraping tool to get the full text of the each source.",
"2b. Don't do back and forth during this source collection process with the user. Either you have the results or not, then inform the user and ask the user if they want to try again or give more details about the topic.",
"3. Once you have the results, ask the user to pick which sources they want to use for the podcast. You don't have to list out the found sources; just tell them to pick from the list of sources that will be visible in the UI.",
"4. User do the selection by selecting the index of sources from the list of sources that will be visible in the UI. so response will be a list of indices of sources selected by the user. sometime user will also send prefered language for the podcast along with the selection."
"4a. You have to use user_source_selection tool to update the user selection. and after this point immediately switch off any UI states.",
"4b. If user sends prefered language for the podcast along with the selection, you have to use update_language tool to update the user language if not leave it default is english. and after this point immediately switch off any UI states.",
"5. Once you we have the confimed selection from the user let's immediatly call the podcast script agent to generate the podcast script for the given sources and query and perfered language (pass full lanage name).",
"5a. Once podcast script is ready switch on the podcast_script UI state and so user will see if the generated podcast script is fine or not, you dont' have to show the script active podasshow_script_for_confirmation will take care of it.",
"6. Once you got the confirmation from the user (throug UI) let's immediatly call the image generation agent to generate the image for the given podcast script.",
"6a. Once image generation successfully generated switch on the image UI state and so user will see if the generated image is fine or not, you just ask user to confirm the image through UI. show_banner_for_confirmation will take care of it."
"7. Once you got the confirmation from the user (throug UI) let's immediatly call the audio generation agent to generate the audio for the given podcast script.",
"7a. Once audio generation successfully generated switch on the audio UI state and so user will see if the generated audio is fine or not, you just ask user to confirm the audio through UI. show_audio_for_confirmation will take care of it."
"8. Once you got the confirmation from the user for audio (throug UI) let's immediatly call the mark_session_finished tool to mark the session as finished and if finish is successful then no further conversation are allowed and only new session can be started.",
"8a. It's important mark_session_finished should be called only when we have all the stages search->selection->script->image->audio are completed."
"APPENDIX:",
"1. You can enable appropriate UI states using the ui_manager tool, which takes [state_type, active] as input, and it takes care of the appropriate UI state for activating appropriate UI state.",
f"1a. Available UI state types: {TOGGLE_UI_STATES}",
"1b. During the conversation, at any place you feel a UI state is not necessary, you can disable it using the ui_manager tool by setting active to False. For switching off all states, pass all to False.",
f"2. Supported Languges: {json.dumps(AVAILABLE_LANGS)}",
"3. Search Agent has a lot off tools, so you can instruct the search query as prompt to get the best results as because search agent has lot of tools you can instruct instead of directly passing the query to search agent when required.",
"4. You are not allowed to include year or date in your seach query construction for the search agent unless that request explicilty with yeear or date come for the users.",
]
DB_PATH = "databases"
PODCAST_DIR = "podcasts"
PODCAST_IMG_DIR = PODCAST_DIR + "/images"
PODCAST_AUIDO_DIR = PODCAST_DIR + "/audio"
PODCAST_RECORDINGS_DIR = PODCAST_DIR + "/recordings"
INITIAL_SESSION_STATE = {
"search_results": [],
"show_sources_for_selection": False,
"show_script_for_confirmation": False,
"generated_script": {},
"selected_language": {"code": "en", "name": "English"},
"available_languages": AVAILABLE_LANGS,
"banner_images": [],
"banner_url": "",
"audio_url": "",
"title": "Untitled",
"created_at": "",
"finished": False,
"show_banner_for_confirmation": False,
"show_audio_for_confirmation": False,
}
STORAGE = SqliteStorage(table_name="podcast_sessions", db_file=get_agent_session_db_path())
| 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/db/articles.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/articles.py | import json
from datetime import datetime
from .connection import db_connection, execute_query
def store_crawled_article(tracking_db_path, entry, raw_content, metadata):
metadata_json = json.dumps(metadata)
query = """
INSERT INTO crawled_articles
(entry_id, source_id, feed_id, title, url, published_date, raw_content, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
"""
try:
params = (
entry["id"],
entry.get("source_id"),
entry.get("feed_id"),
entry.get("title", ""),
entry.get("link", ""),
entry.get("published_date", datetime.now().isoformat()),
raw_content,
metadata_json,
)
execute_query(tracking_db_path, query, params)
return True
except Exception:
return False
def update_entry_status(tracking_db_path, entry_id, status):
query = """
UPDATE feed_entries
SET crawl_attempts = crawl_attempts + 1, crawl_status = ?
WHERE id = ?
"""
return execute_query(tracking_db_path, query, (status, entry_id))
def get_unprocessed_articles(tracking_db_path, limit=5, max_attempts=1):
reset_stuck_articles(tracking_db_path)
query = """
SELECT id, entry_id, source_id, feed_id, title, url, published_date, raw_content, metadata, ai_attempts
FROM crawled_articles
WHERE (ai_status = 'pending' OR ai_status = 'error')
AND ai_attempts < ?
AND processed = 0
ORDER BY published_date DESC
LIMIT ?
"""
articles = execute_query(tracking_db_path, query, (max_attempts, limit), fetch=True)
for article in articles:
if article.get("metadata"):
try:
article["metadata"] = json.loads(article["metadata"])
except json.JSONDecodeError:
article["metadata"] = {}
if articles:
article_ids = [a["id"] for a in articles]
mark_articles_as_processing(tracking_db_path, article_ids)
return articles
def reset_stuck_articles(tracking_db_path):
query = """
UPDATE crawled_articles
SET ai_status = 'pending'
WHERE ai_status = 'processing'
"""
return execute_query(tracking_db_path, query)
def mark_articles_as_processing(tracking_db_path, article_ids):
if not article_ids:
return 0
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
placeholders = ",".join(["?"] * len(article_ids))
query = f"""
UPDATE crawled_articles
SET ai_status = 'processing'
WHERE id IN ({placeholders})
"""
cursor.execute(query, article_ids)
conn.commit()
return cursor.rowcount
def save_article_categories(tracking_db_path, article_id, categories):
if not categories:
return 0
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
DELETE FROM article_categories
WHERE article_id = ?
""",
(article_id,),
)
count = 0
for category in categories:
try:
cursor.execute(
"""
INSERT INTO article_categories (article_id, category_name)
VALUES (?, ?)
""",
(article_id, category.lower().strip()),
)
count += 1
except Exception as _:
pass
conn.commit()
return count
def get_article_categories(tracking_db_path, article_id):
query = """
SELECT category_name
FROM article_categories
WHERE article_id = ?
"""
results = execute_query(tracking_db_path, query, (article_id,), fetch=True)
return [row["category_name"] for row in results]
def update_article_status(tracking_db_path, article_id, results=None, success=False, error_message=None):
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
UPDATE crawled_articles
SET ai_attempts = ai_attempts + 1
WHERE id = ?
""",
(article_id,),
)
if success and results:
categories = []
if "categories" in results:
if isinstance(results["categories"], str):
try:
categories = json.loads(results["categories"])
except json.JSONDecodeError:
categories = [c.strip() for c in results["categories"].split(",") if c.strip()]
elif isinstance(results["categories"], list):
categories = results["categories"]
cursor.execute(
"""
UPDATE crawled_articles
SET summary = ?, content = ?, processed = 1, ai_status = 'success'
WHERE id = ?
""",
(results.get("summary", ""), results.get("content", ""), article_id),
)
conn.commit()
if categories:
save_article_categories(tracking_db_path, article_id, categories)
else:
cursor.execute(
"""
UPDATE crawled_articles
SET ai_status = 'error', ai_error = ?
WHERE id = ?
""",
(error_message, article_id),
)
cursor.execute(
"""
UPDATE crawled_articles
SET ai_status = 'failed'
WHERE id = ? AND ai_attempts >= 3
""",
(article_id,),
)
conn.commit()
return cursor.rowcount
def get_articles_by_date_range(tracking_db_path, start_date=None, end_date=None, limit=None, offset=0):
query_parts = [
"SELECT ca.id, ca.feed_id, ca.source_id, ca.title, ca.url, ca.published_date,",
"ca.summary, ca.content",
"FROM crawled_articles ca",
"WHERE ca.processed = 1",
"AND ca.ai_status = 'success'",
]
query_params = []
if start_date:
query_parts.append("AND ca.published_date >= ?")
query_params.append(start_date)
if end_date:
query_parts.append("AND ca.published_date <= ?")
query_params.append(end_date)
query_parts.append("ORDER BY ca.published_date DESC")
if limit is not None:
query_parts.append("LIMIT ? OFFSET ?")
query_params.append(limit)
query_params.append(offset)
query = " ".join(query_parts)
return execute_query(tracking_db_path, query, tuple(query_params), fetch=True)
def get_article_by_id(tracking_db_path, article_id):
query = """
SELECT id, entry_id, source_id, feed_id, title, url, published_date,
raw_content, content, summary, metadata, ai_status, ai_error,
ai_attempts, crawled_date, processed
FROM crawled_articles
WHERE id = ?
"""
article = execute_query(tracking_db_path, query, (article_id,), fetch=True, fetch_one=True)
if article:
if article.get("metadata"):
try:
article["metadata"] = json.loads(article["metadata"])
except json.JSONDecodeError:
article["metadata"] = {}
article["categories"] = get_article_categories(tracking_db_path, article_id)
return article
def get_articles_by_category(tracking_db_path, category, limit=20, offset=0):
query = """
SELECT ca.id, ca.title, ca.url, ca.published_date, ca.summary
FROM crawled_articles ca
JOIN article_categories ac ON ca.id = ac.article_id
WHERE ac.category_name = ?
AND ca.processed = 1
AND ca.ai_status = 'success'
ORDER BY ca.published_date DESC
LIMIT ? OFFSET ?
"""
return execute_query(tracking_db_path, query, (category, limit, offset), fetch=True)
def get_article_stats(tracking_db_path):
query = """
SELECT
COUNT(*) as total_articles,
SUM(CASE WHEN processed = 1 THEN 1 ELSE 0 END) as processed_articles,
SUM(CASE WHEN ai_status = 'pending' THEN 1 ELSE 0 END) as pending_articles,
SUM(CASE WHEN ai_status = 'processing' THEN 1 ELSE 0 END) as processing_articles,
SUM(CASE WHEN ai_status = 'success' THEN 1 ELSE 0 END) as success_articles,
SUM(CASE WHEN ai_status = 'error' THEN 1 ELSE 0 END) as error_articles,
SUM(CASE WHEN ai_status = 'failed' THEN 1 ELSE 0 END) as failed_articles
FROM crawled_articles
"""
return execute_query(tracking_db_path, query, fetch=True, fetch_one=True)
def get_categories_with_counts(tracking_db_path, limit=20):
query = """
SELECT category_name, COUNT(*) as article_count
FROM article_categories
GROUP BY category_name
ORDER BY article_count DESC
LIMIT ?
"""
return execute_query(tracking_db_path, query, (limit,), fetch=True)
def get_articles_with_source_info(tracking_db_path, limit=20, offset=0):
query = """
SELECT ca.id, ca.title, ca.url, ca.published_date, ca.summary,
ft.feed_url, s.name as source_name
FROM crawled_articles ca
LEFT JOIN feed_tracking ft ON ca.feed_id = ft.feed_id
LEFT JOIN source_feeds sf ON ca.feed_id = sf.id
LEFT JOIN sources s ON sf.source_id = s.id
WHERE ca.processed = 1
AND ca.ai_status = 'success'
ORDER BY ca.published_date DESC
LIMIT ? OFFSET ?
"""
return execute_query(tracking_db_path, query, (limit, offset), fetch=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_news_and_podcast_agents/beifong/db/podcast_configs.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/podcast_configs.py | import sqlite3
from typing import List, Dict, Any, Optional
from datetime import datetime
def get_podcast_config(db_path: str, config_id: int) -> Optional[Dict[str, Any]]:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
cursor = conn.cursor()
cursor.execute(
"""
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_id,),
)
row = cursor.fetchone()
if not row:
return None
config = dict(row)
config["is_active"] = bool(config.get("is_active", 0))
return config
except Exception as e:
print(f"Error fetching podcast config: {e}")
return None
finally:
conn.close()
def get_all_podcast_configs(db_path: str, active_only: bool = False) -> List[Dict[str, Any]]:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
cursor = conn.cursor()
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
"""
cursor.execute(query)
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
"""
cursor.execute(query)
configs = []
for row in cursor.fetchall():
config = dict(row)
config["is_active"] = bool(config.get("is_active", 0))
configs.append(config)
return configs
except Exception as e:
print(f"Error fetching podcast configs: {e}")
return []
finally:
conn.close()
def create_podcast_config(
db_path: str,
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,
) -> Optional[int]:
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute(
"""
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
name,
description,
prompt,
time_range_hours,
limit_articles,
1 if is_active else 0,
tts_engine,
language_code,
podcast_script_prompt,
image_prompt,
now,
now,
),
)
conn.commit()
return cursor.lastrowid
except Exception as e:
conn.rollback()
print(f"Error creating podcast config: {e}")
return None
finally:
conn.close()
def update_podcast_config(db_path: str, config_id: int, updates: Dict[str, Any]) -> bool:
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM podcast_configs WHERE id = ?", (config_id,))
if not cursor.fetchone():
return False
if not updates:
return True
set_clauses = []
params = []
set_clauses.append("updated_at = ?")
params.append(datetime.now().isoformat())
allowed_fields = [
"name",
"description",
"prompt",
"time_range_hours",
"limit_articles",
"is_active",
"tts_engine",
"language_code",
"podcast_script_prompt",
"image_prompt",
]
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)
params.append(config_id)
query = f"""
UPDATE podcast_configs
SET {", ".join(set_clauses)}
WHERE id = ?
"""
cursor.execute(query, tuple(params))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(f"Error updating podcast config: {e}")
return False
finally:
conn.close()
def delete_podcast_config(db_path: str, config_id: int) -> bool:
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
cursor.execute("DELETE FROM podcast_configs WHERE id = ?", (config_id,))
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
print(f"Error deleting podcast config: {e}")
return False
finally:
conn.close()
def toggle_podcast_config(db_path: str, config_id: int, is_active: bool) -> bool:
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute(
"""
UPDATE podcast_configs
SET is_active = ?, updated_at = ?
WHERE id = ?
""",
(1 if is_active else 0, now, config_id),
)
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
print(f"Error toggling podcast config: {e}")
return False
finally:
conn.close()
| 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/db/config.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/config.py | import os
from pathlib import Path
from dotenv import load_dotenv
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)
DEFAULT_DB_PATHS = {
"sources_db": "databases/sources.db",
"tracking_db": "databases/feed_tracking.db",
"podcasts_db": "databases/podcasts.db",
"tasks_db": "databases/tasks.db",
"agent_session_db": "databases/agent_sessions.db",
"faiss_index_db": "databases/faiss/article_index.faiss",
"faiss_mapping_file": "databases/faiss/article_id_map.npy",
"internal_sessions_db": "databases/internal_sessions.db",
"social_media_db": "databases/social_media.db",
"slack_sessions_db": "databases/slack_sessions.db",
}
def get_db_path(db_name):
env_var = f"{db_name.upper()}_PATH"
path = os.environ.get(env_var, DEFAULT_DB_PATHS.get(db_name))
db_dir = os.path.dirname(path)
os.makedirs(db_dir, exist_ok=True)
return path
def get_sources_db_path():
return get_db_path("sources_db")
def get_tracking_db_path():
return get_db_path("tracking_db")
def get_podcasts_db_path():
return get_db_path("podcasts_db")
def get_tasks_db_path():
return get_db_path("tasks_db")
def get_agent_session_db_path():
return get_db_path("agent_session_db")
def get_faiss_db_path():
return get_db_path("faiss_index_db"), get_db_path("faiss_mapping_file")
def get_internal_sessions_db_path():
return get_db_path("internal_sessions_db")
def get_social_media_db_path():
return get_db_path("social_media_db")
def get_browser_session_path():
return "browsers/playwright_persistent_profile"
def get_slack_sessions_db_path():
return get_db_path("slack_sessions_db")
DB_PATH = "databases"
PODCAST_DIR = "podcasts"
PODCAST_IMG_DIR = PODCAST_DIR + "/images"
PODCAST_AUIDO_DIR = PODCAST_DIR + "/audio"
PODCAST_RECORDINGS_DIR = PODCAST_DIR + "/recordings"
| 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/db/connection.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/connection.py | import sqlite3
from contextlib import contextmanager
@contextmanager
def db_connection(db_path):
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def execute_query(db_path, query, params=(), fetch=False, fetch_one=False):
with db_connection(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
| 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/db/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/__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/db/feeds.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/db/feeds.py | from datetime import datetime
import sqlite3
from .connection import db_connection, execute_query
def get_active_feeds(sources_db_path, limit=None, offset=0):
if limit:
query = """
SELECT sf.id, sf.source_id, sf.feed_url, sf.feed_type, sf.last_crawled,
s.name as source_name
FROM source_feeds sf
JOIN sources s ON sf.source_id = s.id
WHERE sf.is_active = 1 AND s.is_active = 1
LIMIT ? OFFSET ?
"""
return execute_query(sources_db_path, query, (limit, offset), fetch=True)
else:
query = """
SELECT sf.id, sf.source_id, sf.feed_url, sf.feed_type, sf.last_crawled,
s.name as source_name
FROM source_feeds sf
JOIN sources s ON sf.source_id = s.id
WHERE sf.is_active = 1 AND s.is_active = 1
"""
return execute_query(sources_db_path, query, fetch=True)
def count_active_feeds(sources_db_path):
query = """
SELECT COUNT(*) as count
FROM source_feeds sf
JOIN sources s ON sf.source_id = s.id
WHERE sf.is_active = 1 AND s.is_active = 1
"""
result = execute_query(sources_db_path, query, fetch=True, fetch_one=True)
return result["count"] if result else 0
def get_feed_tracking_info(tracking_db_path, feed_id):
query = "SELECT * FROM feed_tracking WHERE feed_id = ?"
return execute_query(tracking_db_path, query, (feed_id,), fetch=True, fetch_one=True)
def update_feed_tracking(tracking_db_path, feed_id, etag, modified, entry_hash):
query = """
UPDATE feed_tracking
SET last_processed = ?, last_etag = ?, last_modified = ?, entry_hash = ?
WHERE feed_id = ?
"""
params = (datetime.now().isoformat(), etag, modified, entry_hash, feed_id)
return execute_query(tracking_db_path, query, params)
def store_feed_entries(tracking_db_path, feed_id, source_id, entries):
count = 0
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
for entry in entries:
try:
cursor.execute(
"""
INSERT INTO feed_entries
(feed_id, source_id, entry_id, title, link, published_date, content, summary)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
feed_id,
source_id,
entry.get("entry_id", ""),
entry.get("title", ""),
entry.get("link", ""),
entry.get("published_date", datetime.now().isoformat()),
entry.get("content", ""),
entry.get("summary", ""),
),
)
count += 1
except sqlite3.IntegrityError:
pass
conn.commit()
return count
def update_tracking_info(tracking_db_path, feeds):
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
for feed in feeds:
cursor.execute(
"""
INSERT OR IGNORE INTO feed_tracking
(feed_id, source_id, feed_url, last_processed)
VALUES (?, ?, ?, NULL)
""",
(feed["id"], feed["source_id"], feed["feed_url"]),
)
conn.commit()
def get_uncrawled_entries(tracking_db_path, limit=20, max_attempts=3):
reset_stuck_entries(tracking_db_path)
query = """
SELECT e.id, e.feed_id, e.source_id, e.title, e.link, e.published_date,
e.crawl_attempts, e.entry_id as original_entry_id
FROM feed_entries e
WHERE (e.crawl_status = 'pending' OR e.crawl_status = 'failed')
AND e.crawl_attempts < ?
AND e.link IS NOT NULL
AND e.link != ''
AND NOT EXISTS (
SELECT 1 FROM crawled_articles ca WHERE ca.url = e.link
)
ORDER BY e.published_date DESC
LIMIT ?
"""
entries = execute_query(tracking_db_path, query, (max_attempts, limit), fetch=True)
if entries:
entry_ids = [e["id"] for e in entries]
mark_entries_as_processing(tracking_db_path, entry_ids)
return entries
def reset_stuck_entries(tracking_db_path):
query = """
UPDATE feed_entries
SET crawl_status = 'pending'
WHERE crawl_status = 'processing'
"""
return execute_query(tracking_db_path, query)
def mark_entries_as_processing(tracking_db_path, entry_ids):
if not entry_ids:
return 0
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
placeholders = ",".join(["?"] * len(entry_ids))
query = f"""
UPDATE feed_entries
SET crawl_status = 'processing'
WHERE id IN ({placeholders})
"""
cursor.execute(query, entry_ids)
conn.commit()
return cursor.rowcount
def ensure_feed_tracking_exists(tracking_db_path, feed_id, source_id, feed_url):
query = """
INSERT OR IGNORE INTO feed_tracking
(feed_id, source_id, feed_url, last_processed)
VALUES (?, ?, ?, NULL)
"""
return execute_query(tracking_db_path, query, (feed_id, source_id, feed_url))
def get_feed_sources_with_categories(sources_db_path):
query = """
SELECT sf.id, sf.source_id, sf.feed_url, sf.feed_type, sf.last_crawled,
s.name as source_name, c.name as category_name
FROM source_feeds sf
JOIN sources s ON sf.source_id = s.id
LEFT JOIN source_categories sc ON s.id = sc.source_id
LEFT JOIN categories c ON sc.category_id = c.id
WHERE sf.is_active = 1 AND s.is_active = 1
"""
return execute_query(sources_db_path, query, fetch=True)
def get_feed_stats(tracking_db_path):
query = """
SELECT
COUNT(*) as total_entries,
SUM(CASE WHEN crawl_status = 'pending' THEN 1 ELSE 0 END) as pending_entries,
SUM(CASE WHEN crawl_status = 'processing' THEN 1 ELSE 0 END) as processing_entries,
SUM(CASE WHEN crawl_status = 'success' THEN 1 ELSE 0 END) as success_entries,
SUM(CASE WHEN crawl_status = 'failed' THEN 1 ELSE 0 END) as failed_entries
FROM feed_entries
"""
return execute_query(tracking_db_path, query, fetch=True, fetch_one=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_news_and_podcast_agents/beifong/tests/tts_kokoro_test.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/tts_kokoro_test.py | import os
import soundfile as sf
import platform
import time
import warnings
os.environ["PYTHONWARNINGS"] = "ignore"
os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
warnings.filterwarnings("ignore")
from kokoro import KPipeline
def play_audio(file_path):
system = platform.system()
try:
if system == "Darwin":
os.system(f"afplay {file_path}")
elif system == "Linux":
os.system(f"aplay {file_path}")
elif system == "Windows":
os.system(f'start "" "{file_path}"')
else:
print(f"Audio saved to {file_path} (auto-play not supported on this system)")
except Exception as e:
print(f"Failed to auto-play audio: {e}")
print(f"Audio saved to {file_path}")
print("Testing Kokoro TTS in English and Hindi...")
print("\n=== Testing English ===")
pipeline_en = KPipeline(lang_code="a")
english_text = "This is a test of the Kokoro text-to-speech system in English."
generator_en = pipeline_en(english_text, voice="af_heart")
for i, (gs, ps, audio) in enumerate(generator_en):
output_file = f"english_sample_{i}.wav"
sf.write(output_file, audio, 24000)
print(f"Generated English audio: {output_file}")
print(f"Text: {gs}")
play_audio(output_file)
time.sleep(2)
print("\n=== Testing Hindi ===")
pipeline_hi = KPipeline(lang_code="h")
hindi_text = "यह हिंदी में कोकोरो टेक्स्ट-टू-स्पीच सिस्टम का एक परीक्षण है।"
generator_hi = pipeline_hi(hindi_text, voice="af_heart")
for i, (gs, ps, audio) in enumerate(generator_hi):
output_file = f"hindi_sample_{i}.wav"
sf.write(output_file, audio, 24000)
print(f"Generated Hindi audio: {output_file}")
print(f"Text: {gs}")
play_audio(output_file)
time.sleep(2)
print("\nTest completed. Audio files have been generated and should have auto-played.")
| 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/tests/embedding_search_test.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/embedding_search_test.py | import argparse
import os
import numpy as np
import faiss
from openai import OpenAI
from db.config import get_tracking_db_path
from db.connection import execute_query
from utils.load_api_keys import load_api_key
from db.config import get_faiss_db_path
EMBEDDING_MODEL = "text-embedding-3-small"
FAISS_INDEX_PATH, FAIS_MAPPING_PATH = get_faiss_db_path()
def generate_query_embedding(client, query_text, model=EMBEDDING_MODEL):
try:
response = client.embeddings.create(input=query_text, model=model)
return response.data[0].embedding, model
except Exception as e:
print(f"Error generating query embedding: {str(e)}")
return None, None
def load_faiss_index(index_path=FAISS_INDEX_PATH):
if not os.path.exists(index_path):
raise FileNotFoundError(f"FAISS index not found at {index_path}")
return faiss.read_index(index_path)
def load_id_mapping(mapping_path=FAIS_MAPPING_PATH):
if not os.path.exists(mapping_path):
raise FileNotFoundError(f"ID mapping not found at {mapping_path}")
return np.load(mapping_path).tolist()
def get_article_details(tracking_db_path, article_ids):
if not article_ids:
return []
placeholders = ",".join(["?"] * len(article_ids))
query = f"""
SELECT id, title, url, published_date, summary
FROM crawled_articles
WHERE id IN ({placeholders})
"""
return execute_query(tracking_db_path, query, article_ids, fetch=True)
def search_articles(
query_text,
tracking_db_path=None,
openai_api_key=None,
index_path="databases/faiss/article_index.faiss",
mapping_path="databases/faiss/article_id_map.npy",
top_k=5,
search_params=None,
):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if openai_api_key is None:
openai_api_key = load_api_key()
if not openai_api_key:
raise ValueError("OpenAI API key is required")
client = OpenAI(api_key=openai_api_key)
query_embedding, _ = generate_query_embedding(client, query_text)
if not query_embedding:
raise ValueError("Failed to generate query embedding")
query_vector = np.array([query_embedding]).astype(np.float32)
try:
faiss_index = load_faiss_index(index_path)
id_map = load_id_mapping(mapping_path)
if search_params:
if isinstance(faiss_index, faiss.IndexIVF) and "nprobe" in search_params:
faiss_index.nprobe = search_params["nprobe"]
print(f"Set nprobe to {faiss_index.nprobe}")
if hasattr(faiss_index, "hnsw") and "ef" in search_params:
faiss_index.hnsw.efSearch = search_params["ef"]
print(f"Set efSearch to {faiss_index.hnsw.efSearch}")
index_type = "unknown"
if isinstance(faiss_index, faiss.IndexFlatL2):
index_type = "flat"
elif isinstance(faiss_index, faiss.IndexIVFFlat):
index_type = "ivfflat"
print(f"Using IVF index with nprobe = {faiss_index.nprobe}")
elif isinstance(faiss_index, faiss.IndexIVFPQ):
index_type = "ivfpq"
print(f"Using IVF-PQ index with nprobe = {faiss_index.nprobe}")
elif hasattr(faiss_index, "hnsw"):
index_type = "hnsw"
print(f"Using HNSW index with efSearch = {faiss_index.hnsw.efSearch}")
print(f"Searching {index_type} FAISS index with {len(id_map)} articles...")
distances, indices = faiss_index.search(query_vector, top_k)
result_article_ids = [id_map[idx] for idx in indices[0] if idx < len(id_map)]
results = get_article_details(tracking_db_path, result_article_ids)
for i, result in enumerate(results):
distance = float(distances[0][i])
similarity = float(np.exp(-distance))
result["distance"] = distance
result["similarity"] = similarity
result["score"] = similarity
return results
except Exception as e:
print(f"Error during search: {str(e)}")
import traceback
traceback.print_exc()
return []
def print_search_results(results):
if not results:
print("No results found.")
return
print(f"\nFound {len(results)} results:\n")
for i, result in enumerate(results):
similarity_pct = result.get("similarity", 0) * 100
print(f"{i + 1}. {result['title']}")
print(f" Relevance: {similarity_pct:.1f}%")
if "distance" in result:
print(f" Vector distance: {result['distance']:.4f}")
print(f" Published: {result['published_date']}")
print(f" URL: {result['url']}")
if len(result["summary"]) > 150:
print(f" Summary: {result['summary'][:150]}...")
else:
print(f" Summary: {result['summary']}")
print()
def parse_arguments():
parser = argparse.ArgumentParser(description="Search for articles using FAISS")
parser.add_argument(
"query",
help="Search query text",
)
parser.add_argument(
"--api_key",
help="OpenAI API Key (overrides environment variables)",
)
parser.add_argument(
"--top_k",
type=int,
default=5,
help="Number of results to return",
)
parser.add_argument(
"--nprobe",
type=int,
help="Number of clusters to search (for IVF indexes)",
)
parser.add_argument(
"--ef",
type=int,
help="Search depth (for HNSW indexes)",
)
parser.add_argument(
"--index_path",
default=FAISS_INDEX_PATH,
help="Path to the FAISS index file",
)
parser.add_argument(
"--mapping_path",
default=FAIS_MAPPING_PATH,
help="Path to the ID mapping file",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
api_key = args.api_key or load_api_key()
if not api_key:
print("Error: No OpenAI API key provided. Please provide via --api_key or set OPENAI_API_KEY in .env file")
exit(1)
search_params = {}
if args.nprobe:
search_params["nprobe"] = args.nprobe
if args.ef:
search_params["ef"] = args.ef
try:
results = search_articles(
query_text=args.query,
openai_api_key=api_key,
top_k=args.top_k,
index_path=args.index_path,
mapping_path=args.mapping_path,
search_params=search_params,
)
print_search_results(results)
except Exception as e:
print(f"Error: {str(e)}")
import traceback
traceback.print_exc()
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/tests/agent_agno_test.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/agent_agno_test.py | from typing import Iterator
from agno.agent import Agent, RunResponse
from agno.models.openai import OpenAIChat
from agno.utils.pprint import pprint_run_response
from dotenv import load_dotenv
load_dotenv()
agent = Agent(model=OpenAIChat(id="gpt-4o-mini"))
response: RunResponse = agent.run("Tell me a 5 second short story about a robot")
response_stream: Iterator[RunResponse] = agent.run("Tell me a 5 second short story about a lion", stream=True)
pprint_run_response(response, markdown=True)
pprint_run_response(response_stream, 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_news_and_podcast_agents/beifong/tests/index_faiss_test.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/index_faiss_test.py | import numpy as np
import faiss
import time
dimension = 128
nb_vectors = 10000
np.random.seed(42)
database = np.random.random((nb_vectors, dimension)).astype("float32")
query = np.random.random((1, dimension)).astype("float32")
start_time = time.time()
index = faiss.IndexFlatL2(dimension)
index.add(database)
print(f"Index built in {time.time() - start_time:.4f} seconds")
print(f"Index contains {index.ntotal} vectors")
k = 5
start_time = time.time()
distances, indices = index.search(query, k)
print(f"Search completed in {time.time() - start_time:.4f} seconds")
print("\nSearch Results:")
print("Query vector finds these nearest neighbors (indices):", indices[0])
print("With these distances:", distances[0])
print("\nFAISS is working correctly!")
| 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/tests/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/__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/tests/tool_browseruse_test.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tests/tool_browseruse_test.py | from langchain_openai import ChatOpenAI
from browser_use import Agent
from dotenv import load_dotenv
import asyncio
load_dotenv()
llm = ChatOpenAI(model="gpt-4o")
async def main():
agent = Agent(
task="Compare the price of gpt-4o and DeepSeek-V3",
llm=llm,
)
result = await agent.run()
print(result)
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/advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/schemas.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/models/article_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/article_schemas.py | from pydantic import BaseModel, ConfigDict
from typing import Optional, List, Dict, Any
class ArticleBase(BaseModel):
title: str
url: Optional[str] = None
published_date: str
summary: Optional[str] = None
content: Optional[str] = None
categories: Optional[List[str]] = []
source_name: Optional[str] = None
class Article(ArticleBase):
id: int
metadata: Optional[Dict[str, Any]] = {}
model_config = ConfigDict(from_attributes=True)
class PaginatedArticles(BaseModel):
items: List[Article]
total: int
page: int
per_page: int
total_pages: int
has_next: bool
has_prev: bool | 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/models/podcast_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/podcast_schemas.py | from pydantic import BaseModel
from typing import Optional, List, Dict, Any, Union
class PodcastBase(BaseModel):
title: str
date: str
audio_generated: bool = False
banner_img: Optional[str] = None
identifier: str
language_code: Optional[str] = "en"
tts_engine: Optional[str] = "kokoro"
class Podcast(PodcastBase):
id: int
created_at: Optional[str] = None
audio_path: Optional[str] = None
class Config:
from_attributes = True
class PodcastContent(BaseModel):
title: str
sections: List[Dict[str, Any]]
class PodcastSource(BaseModel):
title: Optional[str] = None
url: Optional[str] = None
source: Optional[str] = None
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
if isinstance(v, str):
return cls(url=v)
if isinstance(v, dict):
return cls(**v)
raise ValueError("Source must be a string or a dict")
class PodcastDetail(BaseModel):
podcast: Podcast
content: PodcastContent
audio_url: Optional[str] = None
sources: Optional[List[Union[PodcastSource, str]]] = None
banner_images: Optional[List[str]] = None
class PodcastCreate(BaseModel):
title: str
date: Optional[str] = None
content: Dict[str, Any]
sources: Optional[List[Union[Dict[str, str], str]]] = None
language_code: Optional[str] = "en"
tts_engine: Optional[str] = "kokoro"
class PodcastUpdate(BaseModel):
title: Optional[str] = None
date: Optional[str] = None
content: Optional[Dict[str, Any]] = None
audio_generated: Optional[bool] = None
sources: Optional[List[Union[Dict[str, str], str]]] = None
language_code: Optional[str] = None
tts_engine: Optional[str] = None
class PaginatedPodcasts(BaseModel):
items: List[Podcast]
total: int
page: int
per_page: int
total_pages: int
has_next: bool
has_prev: bool
| 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/models/social_media_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/social_media_schemas.py | from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime
class PostBase(BaseModel):
post_id: str
platform: str
user_display_name: Optional[str] = None
user_handle: Optional[str] = None
user_profile_pic_url: Optional[str] = None
post_timestamp: Optional[str] = None
post_display_time: Optional[str] = None
post_url: Optional[str] = None
post_text: Optional[str] = None
post_mentions: Optional[str] = None
class PostEngagement(BaseModel):
replies: Optional[int] = None
retweets: Optional[int] = None
likes: Optional[int] = None
bookmarks: Optional[int] = None
views: Optional[int] = None
class MediaItem(BaseModel):
type: str
url: str
class Post(PostBase):
engagement: Optional[PostEngagement] = None
media: Optional[List[MediaItem]] = None
media_count: Optional[int] = 0
is_ad: Optional[bool] = False
sentiment: Optional[str] = None
categories: Optional[List[str]] = None
tags: Optional[List[str]] = None
analysis_reasoning: Optional[str] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
class PaginatedPosts(BaseModel):
items: List[Post]
total: int
page: int
per_page: int
total_pages: int
has_next: bool
has_prev: bool
class PostFilterParams(BaseModel):
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 | 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/models/podcast_config_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/podcast_config_schemas.py | from pydantic import BaseModel, Field
from typing import Optional
class PodcastConfigBase(BaseModel):
name: str
prompt: str
description: Optional[str] = None
time_range_hours: int = Field(24, ge=1, le=168)
limit_articles: int = Field(20, ge=5, le=50)
is_active: bool = True
tts_engine: str = "kokoro"
language_code: str = "en"
podcast_script_prompt: Optional[str] = None
image_prompt: Optional[str] = None
class PodcastConfig(PodcastConfigBase):
id: int
created_at: Optional[str] = None
updated_at: Optional[str] = None
class Config:
from_attributes = True
class PodcastConfigCreate(PodcastConfigBase):
pass
class PodcastConfigUpdate(BaseModel):
name: Optional[str] = None
prompt: Optional[str] = None
description: Optional[str] = None
time_range_hours: Optional[int] = Field(None, ge=1, le=168)
limit_articles: Optional[int] = Field(None, ge=5, le=50)
is_active: Optional[bool] = None
tts_engine: Optional[str] = None
language_code: Optional[str] = None
podcast_script_prompt: Optional[str] = None
image_prompt: Optional[str] = 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/models/source_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/source_schemas.py | from pydantic import BaseModel
from typing import Optional, List
class SourceFeed(BaseModel):
id: int
feed_url: str
feed_type: str
description: Optional[str] = None
is_active: bool
created_at: str
last_crawled: Optional[str] = None
class SourceFeedCreate(BaseModel):
feed_url: str
feed_type: str = "main"
description: Optional[str] = None
is_active: bool = True
class SourceBase(BaseModel):
name: str
url: Optional[str] = None
categories: Optional[List[str]] = []
description: Optional[str] = None
is_active: bool = True
class Source(SourceBase):
id: int
created_at: Optional[str] = None
last_crawled: Optional[str] = None
class Config:
from_attributes = True
class SourceCreate(SourceBase):
feeds: Optional[List[SourceFeedCreate]] = []
class SourceUpdate(BaseModel):
name: Optional[str] = None
url: Optional[str] = None
categories: Optional[List[str]] = None
description: Optional[str] = None
is_active: Optional[bool] = None
class SourceWithFeeds(Source):
feeds: List[SourceFeed] = []
class PaginatedSources(BaseModel):
items: List[Source]
total: int
page: int
per_page: int
total_pages: int
has_next: bool
has_prev: bool
class Category(BaseModel):
id: int
name: str
description: Optional[str] = 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/models/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/__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/models/tasks_schemas.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/models/tasks_schemas.py | from pydantic import BaseModel, validator
from typing import Optional, List, Dict, Any
from enum import Enum
class TaskType(str, Enum):
feed_processor = "feed_processor"
url_crawler = "url_crawler"
ai_analyzer = "ai_analyzer"
podcast_generator = "podcast_generator"
embedding_processor = "embedding_processor"
faiss_indexer = "faiss_indexer"
social_x_scraper = "social_x_scraper"
social_fb_scraper = "social_fb_scraper"
TASK_TYPES = {
"feed_processor": {
"name": "Feed Processor",
"command": "python -m processors.feed_processor",
"description": "Processes RSS feeds and stores new entries",
},
"url_crawler": {"name": "URL Crawler", "command": "python -m processors.url_processor", "description": "Crawls URLs and extracts content"},
"ai_analyzer": {
"name": "AI Analyzer",
"command": "python -m processors.ai_analysis_processor",
"description": "Analyzes article content using AI",
},
"podcast_generator": {
"name": "Podcast Generator",
"command": "python -m processors.podcast_generator_processor",
"description": "Generates podcasts from articles",
},
"embedding_processor": {
"name": "Embedding Processor",
"command": "python -m processors.embedding_processor",
"description": "Generates embeddings for processed articles using OpenAI",
},
"faiss_indexer": {
"name": "FAISS Indexer",
"command": "python -m processors.faiss_indexing_processor",
"description": "Updates FAISS vector index with new article embeddings",
},
"social_x_scraper": {
"name": "X.com Scraper",
"command": "python -m processors.x_scraper_processor",
"description": "Scrapes X.com profiles and analyzes sentiment",
},
"social_fb_scraper": {
"name": "Facebook.com Scraper",
"command": "python -m processors.fb_scraper_processor",
"description": "Scrapes Facebook.com profiles and analyzes sentiment",
},
}
class TaskBase(BaseModel):
name: str
task_type: TaskType
frequency: int
frequency_unit: str
description: Optional[str] = None
enabled: bool = True
@validator("task_type")
def set_command_from_type(cls, v):
if v not in TASK_TYPES:
raise ValueError(f"Invalid task type: {v}")
return v
class Task(TaskBase):
id: int
command: str
last_run: Optional[str] = None
created_at: Optional[str] = None
class Config:
from_attributes = True
class TaskCreate(TaskBase):
pass
class TaskUpdate(BaseModel):
name: Optional[str] = None
task_type: Optional[TaskType] = None
frequency: Optional[int] = None
frequency_unit: Optional[str] = None
description: Optional[str] = None
enabled: Optional[bool] = None
class TaskExecution(BaseModel):
id: int
task_id: int
task_name: Optional[str] = None
start_time: str
end_time: Optional[str] = None
status: str
error_message: Optional[str] = None
output: Optional[str] = None
class PaginatedTaskExecutions(BaseModel):
items: List[TaskExecution]
total: int
page: int
per_page: int
total_pages: int
has_next: bool
has_prev: bool
class TaskStats(BaseModel):
tasks: Dict[str, int]
executions: Dict[str, Any]
| 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/utils/load_api_keys.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/load_api_keys.py | import os
from pathlib import Path
from dotenv import load_dotenv
def load_api_key(key_name="OPENAI_API_KEY"):
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)
return os.environ.get(key_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_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/tts_engine_selector.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/tts_engine_selector.py | import os
from typing import Any, Callable, Optional
from utils.load_api_keys import load_api_key
_TTS_ENGINES = {}
TTS_OPENAI_MODEL = "gpt-4o-mini-tts"
TTS_ELEVENLABS_MODEL = "eleven_multilingual_v2"
def register_tts_engine(name: str, generator_func: Callable):
_TTS_ENGINES[name.lower()] = generator_func
def generate_podcast_audio(
script: Any, output_path: str, tts_engine: str = "kokoro", language_code: str = "en", silence_duration: float = 0.7, voice_map=None
) -> Optional[str]:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
engine_name = tts_engine.lower()
if engine_name not in _TTS_ENGINES:
print(f"Unsupported TTS engine: {tts_engine}")
return None
try:
return _TTS_ENGINES[engine_name](
script=script, output_path=output_path, language_code=language_code, silence_duration=silence_duration, voice_map=voice_map
)
except Exception as e:
import traceback
print(f"Error generating audio with {tts_engine}: {e}")
traceback.print_exc()
return None
def register_default_engines():
def elevenlabs_generator(script, output_path, language_code, silence_duration, voice_map):
from utils.text_to_audio_elevenslab import create_podcast as elevenlabs_create_podcast
if voice_map is None:
voice_map = {1: "Rachel", 2: "Adam"}
if language_code == "hi":
voice_map = {1: "Rachel", 2: "Adam"}
return elevenlabs_create_podcast(
script=script,
output_path=output_path,
silence_duration=silence_duration,
voice_map=voice_map,
elevenlabs_model=TTS_ELEVENLABS_MODEL,
api_key=load_api_key("ELEVENSLAB_API_KEY"),
)
def kokoro_generator(script, output_path, language_code, silence_duration, voice_map):
from utils.text_to_audio_kokoro import create_podcast as kokoro_create_podcast
kokoro_lang_code = "b"
if language_code == "hi":
kokoro_lang_code = "h"
return kokoro_create_podcast(
script=script, output_path=output_path, silence_duration=silence_duration, sampling_rate=24_000, lang_code=kokoro_lang_code
)
def openai_generator(script, output_path, language_code, silence_duration, voice_map):
from utils.text_to_audio_openai import create_podcast as openai_create_podcast
if voice_map is None:
voice_map = {1: "alloy", 2: "nova"}
if language_code == "hi":
voice_map = {1: "alloy", 2: "nova"}
model = TTS_OPENAI_MODEL
return openai_create_podcast(
script=script,
output_path=output_path,
silence_duration=silence_duration,
lang_code=language_code,
model=model,
voice_map=voice_map,
api_key=load_api_key("OPENAI_API_KEY"),
)
register_tts_engine("elevenlabs", elevenlabs_generator)
register_tts_engine("kokoro", kokoro_generator)
register_tts_engine("openai", openai_generator)
register_default_engines()
| 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/utils/get_articles.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/get_articles.py | import sqlite3
import openai
import json
from datetime import datetime, timedelta
from typing import List, Dict, Any
TOPIC_EXTRACTION_MODEL = "gpt-4o-mini"
def extract_search_terms(prompt: str, api_key: str, max_terms: int = 10) -> list:
client = openai.OpenAI(api_key=api_key)
system_msg = (
"analyze the user's request and extract up to "
f"{max_terms} key search terms or phrases (focus on nouns and concepts). "
"Include broad variations and synonyms to increase match chances. "
"For very specific topics, add general category terms too. "
"output only a json object following this exact schema: "
"{'terms': ['term1','term2',...]}. no additional keys or text."
)
try:
resp = client.chat.completions.create(
model=TOPIC_EXTRACTION_MODEL,
messages=[
{"role": "system", "content": system_msg},
{"role": "user", "content": prompt},
],
temperature=0.3,
response_format={"type": "json_object"},
)
parsed = json.loads(resp.choices[0].message.content.strip())
if isinstance(parsed, dict) and isinstance(parsed.get("terms"), list):
return parsed["terms"]
except Exception as e:
print(f"Error extracting search terms: {e}")
return [prompt.strip()]
def search_articles(
prompt: str,
db_path: str,
api_key: str,
operator: str = "OR",
limit: int = 20,
from_date: str = None,
use_categories: bool = True,
fallback_to_broader: bool = True,
) -> List[Dict[str, Any]]:
if from_date is None:
from_date = (datetime.now() - timedelta(hours=48)).isoformat()
terms = extract_search_terms(prompt, api_key)
if not terms:
return []
print(f"Search terms: {terms}")
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
results = []
try:
results = _execute_search(cursor, terms, from_date, operator, limit, use_categories)
if fallback_to_broader and len(results) < min(5, limit):
print(f"Initial search returned only {len(results)} results. Trying broader search...")
if operator == "AND":
broader_results = _execute_search(
cursor,
terms,
from_date,
"OR",
limit,
use_categories=True,
)
if len(broader_results) > len(results):
print(f"Broader search found {len(broader_results)} results")
results = broader_results
if results:
_add_source_names(cursor, results)
for article in results:
article["categories"] = _get_article_categories(cursor, article["id"])
except Exception as e:
print(f"Error searching articles: {e}")
finally:
conn.close()
return results
def _execute_search(
cursor,
terms,
from_date,
operator,
limit,
use_categories=True,
partial_match=False,
days_fallback=0,
):
if days_fallback > 0:
try:
from_date_obj = datetime.fromisoformat(from_date.replace("Z", "").split("+")[0])
adjusted_date = (from_date_obj - timedelta(days=days_fallback)).isoformat()
from_date = adjusted_date
except Exception as e:
print(f"Warning: Could not adjust date with fallback: {e}")
base_query = """
SELECT DISTINCT ca.id, ca.title, ca.url, ca.published_date, ca.summary as content,
ca.source_id, ca.feed_id
FROM crawled_articles ca
WHERE ca.processed = 1 AND ca.published_date >= ?
"""
if use_categories:
base_query = """
SELECT DISTINCT ca.id, ca.title, ca.url, ca.published_date, ca.summary as content,
ca.source_id, ca.feed_id
FROM crawled_articles ca
LEFT JOIN article_categories ac ON ca.id = ac.article_id
WHERE ca.processed = 1 AND ca.published_date >= ?
"""
clauses, params = [], [from_date]
for term in terms:
term_clauses = []
like = f"%{term}%"
term_clauses.append("(ca.title LIKE ? OR ca.content LIKE ? OR ca.summary LIKE ?)")
params.extend([like, like, like])
if use_categories:
term_clauses.append("(ac.category_name LIKE ?)")
params.append(like)
if term_clauses:
clauses.append(f"({' OR '.join(term_clauses)})")
where = f" {operator} ".join(clauses)
sql = f"{base_query} AND ({where}) ORDER BY ca.published_date DESC LIMIT {limit}"
cursor.execute(sql, params)
return [dict(row) for row in cursor.fetchall()]
def _add_source_names(cursor, articles):
source_ids = {a.get("source_id") for a in articles if a.get("source_id")}
feed_ids = {a.get("feed_id") for a in articles if a.get("feed_id")}
if not source_ids and not feed_ids:
return
source_names = {}
if source_ids:
source_ids = [id for id in source_ids if id is not None]
if source_ids:
placeholders = ",".join(["?"] * len(source_ids))
try:
cursor.execute(
f"SELECT id, name FROM sources WHERE id IN ({placeholders})",
list(source_ids),
)
for row in cursor.fetchall():
source_names[row["id"]] = row["name"]
except Exception as e:
print(f"Error fetching source names: {e}")
if feed_ids:
feed_ids = [id for id in feed_ids if id is not None]
if feed_ids:
placeholders = ",".join(["?"] * len(feed_ids))
try:
cursor.execute(
f"""
SELECT sf.id, s.name
FROM source_feeds sf
JOIN sources s ON sf.source_id = s.id
WHERE sf.id IN ({placeholders})
""",
list(feed_ids),
)
for row in cursor.fetchall():
source_names[row["id"]] = row["name"]
except Exception as e:
print(f"Error fetching feed source names: {e}")
for article in articles:
source_id = article.get("source_id")
feed_id = article.get("feed_id")
if source_id and source_id in source_names:
article["source_name"] = source_names[source_id]
elif feed_id and feed_id in source_names:
article["source_name"] = source_names[feed_id]
else:
article["source_name"] = "Unknown Source"
def _get_article_categories(cursor, article_id):
try:
cursor.execute(
"SELECT category_name FROM article_categories WHERE article_id = ?",
(article_id,),
)
return [row["category_name"] for row in cursor.fetchall()]
except Exception as e:
print(f"Error fetching article categories: {e}")
return []
| 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/utils/rss_feed_parser.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/rss_feed_parser.py | import feedparser
from datetime import datetime
import hashlib
from typing import List, Dict, Any, Optional
def get_hash(entries: List[Dict[str, str]]) -> str:
texts = ""
for entry in entries:
texts += (
str(entry.get("id", ""))
+ str(entry.get("title", ""))
+ str(entry.get("published_date", ""))
)
return hashlib.md5(texts.encode()).hexdigest()
def parse_feed_entries(entries: List[Dict[str, Any]]) -> List[Dict[str, str]]:
parsed_entries = []
for entry in entries:
content = entry.get("content") or entry.get("description") or ""
published = (
entry.get("published")
or entry.get("updated")
or entry.get("pubDate")
or entry.get("created")
or datetime.now().isoformat()
)
entry_id = entry.get("id") or entry.get("link", "")
link = entry.get("link", "")
summary = entry.get("summary", "")
title = entry.get("title", "")
parsed_entries.append(
{
"title": title,
"link": link,
"summary": summary,
"content": content,
"published_date": published,
"entry_id": entry_id,
}
)
return parsed_entries
def is_rss_feed(feed_data: Any) -> bool:
return feed_data.bozo and hasattr(feed_data, "bozo_exception")
def get_feed_data(
feed_url: str, etag: Optional[str] = None, modified: Optional[Any] = None
) -> Dict[str, Any]:
feed_data = feedparser.parse(feed_url, etag=etag, modified=modified)
if is_rss_feed(feed_data):
return {
"is_rss_feed": False,
"parsed_entries": None,
"modified": None,
"status": None,
"current_hash": None,
"etag": None,
}
status = feed_data.get("status", 200)
etag = feed_data.get("etag", None)
modified = feed_data.get("modified")
entries = feed_data.get("entries", [])
parsed_entries = parse_feed_entries(entries)
current_hash = get_hash(parsed_entries)
return {
"parsed_entries": parsed_entries,
"modified": modified,
"status": status,
"current_hash": current_hash,
"etag": etag,
"is_rss_feed": 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_news_and_podcast_agents/beifong/utils/text_to_audio_kokoro.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/text_to_audio_kokoro.py | # ruff: noqa: E402
import os
import warnings
from typing import List, Any
import numpy as np
import soundfile as sf
from .translate_podcast import translate_script
os.environ["PYTHONWARNINGS"] = "ignore"
os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
warnings.filterwarnings("ignore")
from kokoro import KPipeline
class ScriptEntry:
def __init__(self, text: str, speaker: int):
self.text = text
self.speaker = speaker
def create_slience_audio(silence_duration: float, sampling_rate: int) -> np.ndarray:
return np.zeros(int(sampling_rate * silence_duration), dtype=np.float32)
def text_to_speech(pipeline: KPipeline, text: str, speaker_id: int, sampling_rate: int, lang_code: str) -> np.ndarray:
if lang_code == "h":
voices = {1: "hf_alpha", 2: "hm_omega"}
else:
voices = {1: "af_heart", 2: "bm_lewis"}
voice = voices[speaker_id]
audio_chunks = []
for _, _, audio in pipeline(text, voice=voice, speed=1.0):
if audio is not None:
audio_chunk = np.array(audio, dtype=np.float32)
if np.max(np.abs(audio_chunk)) > 0:
audio_chunk = audio_chunk / np.max(np.abs(audio_chunk)) * 0.9
audio_chunks.append(audio_chunk)
if audio_chunks:
return np.concatenate(audio_chunks)
else:
return np.zeros(0, dtype=np.float32)
def create_audio_segments(
pipeline: KPipeline,
script: Any,
silence_duration: float,
sampling_rate: int,
lang_code: str,
) -> List[np.ndarray]:
audio_segments = []
silence = create_slience_audio(silence_duration, sampling_rate)
entries = script if isinstance(script, list) else script.entries
for entry in entries:
text = entry["text"] if isinstance(entry, dict) else entry.text
speaker = entry["speaker"] if isinstance(entry, dict) else entry.speaker
segment_audio = text_to_speech(
pipeline,
text,
speaker,
sampling_rate=sampling_rate,
lang_code=lang_code,
)
if len(segment_audio) > 0:
try:
audio_segments.append(segment_audio)
except Exception:
fallback_silence = create_slience_audio(len(text) * 0.1, sampling_rate)
audio_segments.append(fallback_silence)
audio_segments.append(silence)
return audio_segments
def combine_full_segments(audio_segments: List[np.ndarray]) -> np.ndarray:
full_audio = np.concatenate(audio_segments)
max_amp = np.max(np.abs(full_audio))
if max_amp > 0:
full_audio = full_audio / max_amp * 0.9
return full_audio
def write_to_disk(output_path: str, full_audio: np.ndarray, sampling_rate: int) -> None:
return sf.write(output_path, full_audio, sampling_rate, subtype="PCM_16")
def create_podcast(
script: Any,
output_path: str,
silence_duration: float = 0.7,
sampling_rate: int = 24_000,
lang_code: str = "b",
) -> str:
pipeline = KPipeline(lang_code=lang_code)
if lang_code != "b":
if isinstance(script, list):
script = translate_script(script, lang_code)
else:
script = translate_script(script.entries, lang_code)
output_path = os.path.abspath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
audio_segments = create_audio_segments(pipeline, script, silence_duration, sampling_rate, lang_code)
full_audio = combine_full_segments(audio_segments)
write_to_disk(output_path, full_audio, sampling_rate)
return output_path
if __name__ == "__main__":
create_podcast("", "output.wav") | 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/utils/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/__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/utils/translate_podcast.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/translate_podcast.py | import json
from typing import List, Dict, Any
from openai import OpenAI
from utils.load_api_keys import load_api_key
TRANSLATION_MODEL = "gpt-4o"
LANG_CODE_TO_NAME = {
"en": "English",
"h": "Hindi",
"b": None,
"es": "Spanish",
"fr": "French",
"de": "German",
"ru": "Russian",
"ja": "Japanese",
"zh": "Chinese",
"it": "Italian",
"pt": "Portuguese",
"ar": "Arabic",
}
def translate_script(script: List[Dict[str, Any]], lang_code: str = "b") -> List[Dict[str, Any]]:
script = [{"text": e["text"], "speaker": e["speaker"]} for e in script]
target_lang = LANG_CODE_TO_NAME.get(lang_code)
if target_lang is None:
return script
api_key = load_api_key("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable not set")
client = OpenAI(api_key=api_key)
prompt = f"""Translate the following podcast script from English to {target_lang} also keep the characters espeak compatible.
Maintain the exact same structure and keep the 'speaker' values identical.
Only translate the text in each entry's 'text' field. and return the json output with translated json format (keys also will be in english only text value will be translated).
Input script:
{json.dumps(script, indent=2)}
"""
response = client.chat.completions.create(
model=TRANSLATION_MODEL,
messages=[
{"role": "system", "content": "You are a professional translator specializing in podcast content."},
{"role": "user", "content": prompt},
],
response_format={"type": "json_object"},
temperature=0.3,
)
response_content = response.choices[0].message.content
response_data = json.loads(response_content)
if "script" in response_data:
translated_script = response_data["script"]
else:
translated_script = response_data
if not isinstance(translated_script, list):
raise ValueError("Unexpected response format: not a list")
if len(translated_script) != len(script):
raise ValueError(f"Translation returned {len(translated_script)} entries, expected {len(script)}")
return translated_script
| 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/utils/text_to_audio_elevenslab.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/text_to_audio_elevenslab.py | import os
from typing import List, Tuple, Optional, Any
import tempfile
import numpy as np
import soundfile as sf
from elevenlabs.client import ElevenLabs
TEXT_TO_SPEECH_MODEL = "eleven_multilingual_v2"
def create_silence_audio(silence_duration: float, sampling_rate: int) -> np.ndarray:
if sampling_rate <= 0:
print(f"Warning: Invalid sampling rate ({sampling_rate}) for silence generation")
return np.zeros(0, dtype=np.float32)
return np.zeros(int(sampling_rate * silence_duration), dtype=np.float32)
def combine_audio_segments(audio_segments: List[np.ndarray], silence_duration: float, sampling_rate: int) -> np.ndarray:
if not audio_segments:
return np.zeros(0, dtype=np.float32)
if sampling_rate <= 0:
combined = np.concatenate(audio_segments) if audio_segments else np.zeros(0, dtype=np.float32)
else:
silence = create_silence_audio(silence_duration, sampling_rate)
combined_with_silence = []
for i, segment in enumerate(audio_segments):
combined_with_silence.append(segment)
if i < len(audio_segments) - 1:
combined_with_silence.append(silence)
combined = np.concatenate(combined_with_silence)
max_amp = np.max(np.abs(combined))
if max_amp > 0:
combined = combined / max_amp * 0.95
return combined
def write_to_disk(output_path: str, audio_data: np.ndarray, sampling_rate: int) -> None:
if sampling_rate <= 0:
print(f"Error: Cannot write audio file with invalid sampling rate ({sampling_rate})")
return
try:
sf.write(output_path, audio_data, sampling_rate)
except Exception as e:
print(f"Error writing audio file '{output_path}': {e}")
def text_to_speech_elevenlabs(
client: ElevenLabs,
text: str,
speaker_id: int,
voice_map={1: "Rachel", 2: "Adam"},
model_id: str = TEXT_TO_SPEECH_MODEL,
) -> Optional[Tuple[np.ndarray, int]]:
if not text.strip():
return None
voice_name_or_id = voice_map.get(speaker_id)
if not voice_name_or_id:
print(f"No voice found for speaker_id {speaker_id}")
return None
try:
from pydub import AudioSegment
pydub_available = True
except ImportError:
pydub_available = False
try:
audio_generator = client.generate(
text=text,
voice=voice_name_or_id,
model=model_id,
stream=True,
)
audio_chunks = []
for chunk in audio_generator:
if chunk:
audio_chunks.append(chunk)
if not audio_chunks:
return None
audio_data = b"".join(audio_chunks)
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
temp_path = temp_file.name
temp_file.write(audio_data)
if pydub_available:
try:
audio_segment = AudioSegment.from_mp3(temp_path)
channels = audio_segment.channels
sample_width = audio_segment.sample_width
frame_rate = audio_segment.frame_rate
samples = np.array(audio_segment.get_array_of_samples())
if channels == 2:
samples = samples.reshape(-1, 2).mean(axis=1)
max_possible_value = float(2 ** (8 * sample_width - 1))
samples = samples.astype(np.float32) / max_possible_value
os.unlink(temp_path)
return samples, frame_rate
except Exception as pydub_error:
print(f"Pydub processing failed: {pydub_error}")
try:
audio_np, samplerate = sf.read(temp_path)
os.unlink(temp_path)
return audio_np, samplerate
except Exception as _:
if pydub_available:
try:
sound = AudioSegment.from_mp3(temp_path)
wav_path = temp_path.replace(".mp3", ".wav")
sound.export(wav_path, format="wav")
audio_np, samplerate = sf.read(wav_path)
os.unlink(temp_path)
os.unlink(wav_path)
return audio_np, samplerate
except Exception:
pass
if os.path.exists(temp_path):
os.unlink(temp_path)
return None
except Exception as e:
print(f"Error during ElevenLabs API call: {e}")
import traceback
traceback.print_exc()
return None
def create_podcast(
script: Any,
output_path: str,
silence_duration: float = 0.7,
sampling_rate: int = 24_000,
lang_code: str = "en",
elevenlabs_model: str = "eleven_multilingual_v2",
voice_map: dict = {1: "Rachel", 2: "Adam"},
api_key: str = None,
) -> str:
if not api_key:
print("Warning: Using hardcoded API key")
try:
client = ElevenLabs(api_key=api_key)
try:
voices = client.voices.get_all()
print(f"API connection successful. Found {len(voices)} available voices.")
except Exception as voice_error:
print(f"Warning: Could not retrieve voices: {voice_error}")
except Exception as e:
print(f"Fatal Error: Failed to initialize ElevenLabs client: {e}")
return None
output_path = os.path.abspath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
generated_segments = []
determined_sampling_rate = -1
entries = script.entries if hasattr(script, "entries") else script
for i, entry in enumerate(entries):
if hasattr(entry, "speaker"):
speaker_id = entry.speaker
entry_text = entry.text
else:
speaker_id = entry["speaker"]
entry_text = entry["text"]
result = text_to_speech_elevenlabs(
client=client,
text=entry_text,
speaker_id=speaker_id,
voice_map=voice_map,
model_id=elevenlabs_model,
)
if result:
segment_audio, segment_rate = result
if determined_sampling_rate == -1:
determined_sampling_rate = segment_rate
elif determined_sampling_rate != segment_rate:
try:
import librosa
segment_audio = librosa.resample(
segment_audio,
orig_sr=segment_rate,
target_sr=determined_sampling_rate,
)
except ImportError:
determined_sampling_rate = segment_rate
except Exception:
pass
generated_segments.append(segment_audio)
if not generated_segments or determined_sampling_rate <= 0:
return None
full_audio = combine_audio_segments(generated_segments, silence_duration, determined_sampling_rate)
if full_audio.size == 0:
return None
write_to_disk(output_path, full_audio, determined_sampling_rate)
if os.path.exists(output_path):
return output_path
else:
return 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/utils/text_to_audio_openai.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/text_to_audio_openai.py | import os
from typing import List, Optional, Tuple, Dict, Any
import tempfile
import numpy as np
import soundfile as sf
from openai import OpenAI
from utils.load_api_keys import load_api_key
OPENAI_VOICES = {1: "alloy", 2: "echo", 3: "fable", 4: "onyx", 5: "nova", 6: "shimmer"}
DEFAULT_VOICE_MAP = {1: "alloy", 2: "nova"}
TEXT_TO_SPEECH_MODEL = "gpt-4o-mini-tts"
def create_silence_audio(silence_duration: float, sampling_rate: int) -> np.ndarray:
if sampling_rate <= 0:
print(f"WARNING: Invalid sampling rate ({sampling_rate}) for silence generation")
return np.zeros(0, dtype=np.float32)
return np.zeros(int(sampling_rate * silence_duration), dtype=np.float32)
def combine_audio_segments(audio_segments: List[np.ndarray], silence_duration: float, sampling_rate: int) -> np.ndarray:
if not audio_segments:
return np.zeros(0, dtype=np.float32)
silence = create_silence_audio(silence_duration, sampling_rate)
combined_segments = []
for i, segment in enumerate(audio_segments):
combined_segments.append(segment)
if i < len(audio_segments) - 1:
combined_segments.append(silence)
combined = np.concatenate(combined_segments)
max_amp = np.max(np.abs(combined))
if max_amp > 0:
combined = combined / max_amp * 0.95
return combined
def text_to_speech_openai(
client: OpenAI,
text: str,
speaker_id: int,
voice_map: Dict[int, str] = None,
model: str = TEXT_TO_SPEECH_MODEL,
) -> Optional[Tuple[np.ndarray, int]]:
if not text.strip():
print("WARNING: Empty text provided, skipping TTS generation")
return None
voice_map = voice_map or DEFAULT_VOICE_MAP
voice = voice_map.get(speaker_id)
if not voice:
if speaker_id in OPENAI_VOICES:
voice = OPENAI_VOICES[speaker_id]
else:
voice = next(iter(voice_map.values()), "alloy")
print(f"WARNING: No voice mapping for speaker {speaker_id}, using {voice}")
try:
print(f"INFO: Generating TTS for speaker {speaker_id} using voice '{voice}'")
response = client.audio.speech.create(
model=model,
voice=voice,
input=text,
response_format="mp3",
)
audio_data = response.content
if not audio_data:
print("ERROR: OpenAI TTS returned empty response")
return None
print(f"INFO: Received {len(audio_data)} bytes from OpenAI TTS")
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
temp_path = temp_file.name
temp_file.write(audio_data)
try:
from pydub import AudioSegment
audio_segment = AudioSegment.from_mp3(temp_path)
channels = audio_segment.channels
sample_width = audio_segment.sample_width
frame_rate = audio_segment.frame_rate
samples = np.array(audio_segment.get_array_of_samples())
if channels == 2:
samples = samples.reshape(-1, 2).mean(axis=1)
max_possible_value = float(2 ** (8 * sample_width - 1))
samples = samples.astype(np.float32) / max_possible_value
os.unlink(temp_path)
return samples, frame_rate
except ImportError:
print("WARNING: Pydub not available, falling back to soundfile")
except Exception as e:
print(f"ERROR: Pydub processing failed: {e}")
try:
audio_np, samplerate = sf.read(temp_path)
os.unlink(temp_path)
return audio_np, samplerate
except Exception as e:
print(f"ERROR: Failed to process audio with soundfile: {e}")
try:
from pydub import AudioSegment
sound = AudioSegment.from_mp3(temp_path)
wav_path = temp_path.replace(".mp3", ".wav")
sound.export(wav_path, format="wav")
audio_np, samplerate = sf.read(wav_path)
os.unlink(temp_path)
os.unlink(wav_path)
return audio_np, samplerate
except Exception as e:
print(f"ERROR: All audio processing methods failed: {e}")
if os.path.exists(temp_path):
os.unlink(temp_path)
return None
except Exception as e:
print(f"ERROR: OpenAI TTS API error: {e}")
import traceback
traceback.print_exc()
return None
def create_podcast(
script: Any,
output_path: str,
silence_duration: float = 0.7,
sampling_rate: int = 24000,
lang_code: str = "en",
model: str = TEXT_TO_SPEECH_MODEL,
voice_map: Dict[int, str] = None,
api_key: str = None,
) -> Optional[str]:
try:
if not api_key:
api_key = load_api_key()
if not api_key:
print("ERROR: No OpenAI API key provided")
return None
client = OpenAI(api_key=api_key)
print("INFO: OpenAI client initialized")
except Exception as e:
print(f"ERROR: Failed to initialize OpenAI client: {e}")
return None
output_path = os.path.abspath(output_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
if voice_map is None:
voice_map = DEFAULT_VOICE_MAP.copy()
model_to_use = model
if model == "tts-1" and lang_code == "en":
model_to_use = "tts-1-hd"
print(f"INFO: Using high-definition TTS model for English: {model_to_use}")
generated_segments = []
sampling_rate_detected = None
entries = script.entries if hasattr(script, "entries") else script
print(f"INFO: Processing {len(entries)} script entries")
for i, entry in enumerate(entries):
if hasattr(entry, "speaker"):
speaker_id = entry.speaker
entry_text = entry.text
else:
speaker_id = entry["speaker"]
entry_text = entry["text"]
print(f"INFO: Processing entry {i + 1}/{len(entries)}: Speaker {speaker_id}")
result = text_to_speech_openai(
client=client,
text=entry_text,
speaker_id=speaker_id,
voice_map=voice_map,
model=model_to_use,
)
if result:
segment_audio, segment_rate = result
if sampling_rate_detected is None:
sampling_rate_detected = segment_rate
print(f"INFO: Using sample rate: {sampling_rate_detected} Hz")
elif sampling_rate_detected != segment_rate:
print(f"WARNING: Sample rate mismatch: {sampling_rate_detected} vs {segment_rate}")
try:
import librosa
segment_audio = librosa.resample(segment_audio, orig_sr=segment_rate, target_sr=sampling_rate_detected)
print(f"INFO: Resampled to {sampling_rate_detected} Hz")
except ImportError:
sampling_rate_detected = segment_rate
print(f"WARNING: Librosa not available for resampling, using {segment_rate} Hz")
except Exception as e:
print(f"ERROR: Resampling failed: {e}")
generated_segments.append(segment_audio)
else:
print(f"WARNING: Failed to generate audio for entry {i + 1}")
if not generated_segments:
print("ERROR: No audio segments were generated")
return None
if sampling_rate_detected is None:
print("ERROR: Could not determine sample rate")
return None
print(f"INFO: Combining {len(generated_segments)} audio segments")
full_audio = combine_audio_segments(generated_segments, silence_duration, sampling_rate_detected)
if full_audio.size == 0:
print("ERROR: Combined audio is empty")
return None
print(f"INFO: Writing audio to {output_path}")
try:
sf.write(output_path, full_audio, sampling_rate_detected)
except Exception as e:
print(f"ERROR: Failed to write audio file: {e}")
return None
if os.path.exists(output_path):
file_size = os.path.getsize(output_path)
print(f"INFO: Audio file created: {output_path} ({file_size / 1024:.1f} KB)")
return output_path
else:
print(f"ERROR: Failed to create audio file at {output_path}")
return 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/utils/crawl_url.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/utils/crawl_url.py | import requests
from bs4 import BeautifulSoup
import random
from typing import Dict, List, TypedDict
class MetadataDict(TypedDict):
title: str
description: str
og: Dict[str, str]
twitter: Dict[str, str]
other_meta: Dict[str, str]
class WebData(TypedDict):
raw_html: str
metadata: MetadataDict
USER_AGENTS: List[str] = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
]
HEADERS: Dict[str, str] = {
"User-Agent": random.choice(USER_AGENTS),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
}
def extract_meta_tags(soup: BeautifulSoup) -> MetadataDict:
metadata: MetadataDict = {
"title": "",
"description": "",
"og": {},
"twitter": {},
"other_meta": {},
}
title_tag = soup.find("title")
if title_tag:
metadata["title"] = title_tag.text.strip()
for meta in soup.find_all("meta"):
name = meta.get("name", "").lower()
prop = meta.get("property", "").lower()
content = meta.get("content", "")
if prop.startswith("ogg:"):
og_key = prop[3:]
metadata["og"][og_key] = content
elif prop.startswith("twitter:") or name.startswith("twitter:"):
twitter_key = prop[8:] if prop.startswith("twitter:") else name[8:]
metadata["twitter"][twitter_key] = content
elif name in ["description", "keywords", "author", "robots", "viewport"]:
metadata["other_meta"][name] = content
if name == "description":
metadata["description"] = content
return metadata
def get_web_data(url: str) -> WebData:
HEADERS["User-Agent"] = random.choice(USER_AGENTS)
response = requests.get(url, headers=HEADERS, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
metadata = extract_meta_tags(soup)
body = str(soup.find("body"))
return {"raw_html": body, "metadata": metadata}
| 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/routers/task_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/task_router.py | from fastapi import APIRouter, Query, Path, Body, status
from typing import List, Optional, Dict
from models.tasks_schemas import Task, TaskCreate, TaskUpdate, TaskStats, TASK_TYPES
from services.task_service import task_service
router = APIRouter()
@router.get("/", response_model=List[Task])
async def get_tasks(
include_disabled: bool = Query(False, description="Include disabled tasks"),
):
"""
Get all tasks with optional filtering.
- **include_disabled**: If true, includes disabled tasks
"""
return await task_service.get_tasks(include_disabled=include_disabled)
@router.get("/pending", response_model=List[Task])
async def get_pending_tasks():
"""
Get tasks that are due to run.
"""
return await task_service.get_pending_tasks()
@router.get("/stats", response_model=TaskStats)
async def get_task_stats():
"""
Get task statistics.
"""
return await task_service.get_stats()
@router.get("/executions")
async def get_task_executions(
task_id: Optional[int] = Query(None, description="Filter by task ID"),
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(10, ge=1, le=100, description="Items per page"),
):
"""
Get paginated task executions.
- **task_id**: Filter by task ID
- **page**: Page number (starting from 1)
- **per_page**: Number of items per page (max 100)
"""
return await task_service.get_task_executions(task_id=task_id, page=page, per_page=per_page)
@router.get("/types", response_model=Dict[str, Dict[str, str]])
async def get_task_types():
"""
Get all available task types.
"""
return TASK_TYPES
@router.get("/{task_id}", response_model=Task)
async def get_task(
task_id: int = Path(..., description="The ID of the task to retrieve"),
):
"""
Get a specific task by ID.
- **task_id**: The ID of the task to retrieve
"""
return await task_service.get_task(task_id=task_id)
@router.post("/", response_model=Task, status_code=status.HTTP_201_CREATED)
async def create_task(task_data: TaskCreate = Body(...)):
"""
Create a new task.
- **task_data**: Data for the new task
"""
return await task_service.create_task(
name=task_data.name,
task_type=task_data.task_type,
frequency=task_data.frequency,
frequency_unit=task_data.frequency_unit,
description=task_data.description,
enabled=task_data.enabled,
)
@router.put("/{task_id}", response_model=Task)
async def update_task(
task_id: int = Path(..., description="The ID of the task to update"),
task_data: TaskUpdate = Body(...),
):
"""
Update an existing task.
- **task_id**: The ID of the task to update
- **task_data**: Updated data for the task
"""
updates = {k: v for k, v in task_data.dict().items() if v is not None}
return await task_service.update_task(task_id=task_id, updates=updates)
@router.delete("/{task_id}")
async def delete_task(
task_id: int = Path(..., description="The ID of the task to delete"),
):
"""
Delete a task.
- **task_id**: The ID of the task to delete
"""
return await task_service.delete_task(task_id=task_id)
@router.post("/{task_id}/enable", response_model=Task)
async def enable_task(
task_id: int = Path(..., description="The ID of the task to enable"),
):
"""
Enable a task.
- **task_id**: The ID of the task to enable
"""
return await task_service.toggle_task(task_id=task_id, enable=True)
@router.post("/{task_id}/disable", response_model=Task)
async def disable_task(
task_id: int = Path(..., description="The ID of the task to disable"),
):
"""
Disable a task.
- **task_id**: The ID of the task to disable
"""
return await task_service.toggle_task(task_id=task_id, enable=False)
| 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/routers/social_media_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/social_media_router.py | from fastapi import APIRouter, Query
from typing import List, Optional, Dict, Any
from services.social_media_service import social_media_service
from models.social_media_schemas import PaginatedPosts, Post
import threading
from tools.social.browser import setup_session_multi
router = APIRouter()
@router.get("/", response_model=PaginatedPosts)
async def read_posts(
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(10, ge=1, le=100, description="Items per page"),
platform: Optional[str] = Query(None, description="Filter by platform (e.g., x.com, instagram)"),
user_handle: Optional[str] = Query(None, description="Filter by user handle"),
sentiment: Optional[str] = Query(None, description="Filter by sentiment"),
category: Optional[str] = Query(None, description="Filter by category"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
search: Optional[str] = Query(None, description="Search in post text, user display name, or handle"),
):
"""
Get all social media posts with pagination and filtering.
"""
return await social_media_service.get_posts(
page=page,
per_page=per_page,
platform=platform,
user_handle=user_handle,
sentiment=sentiment,
category=category,
date_from=date_from,
date_to=date_to,
search=search,
)
@router.get("/{post_id}", response_model=Post)
async def read_post(post_id: str):
"""
Get a specific social media post by ID.
"""
return await social_media_service.get_post(post_id=post_id)
@router.get("/platforms/list", response_model=List[str])
async def read_platforms():
"""Get all available platforms."""
return await social_media_service.get_platforms()
@router.get("/sentiments/list", response_model=List[Dict[str, Any]])
async def read_sentiments(
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get sentiment distribution with post counts."""
return await social_media_service.get_sentiments(date_from=date_from, date_to=date_to)
@router.get("/users/top", response_model=List[Dict[str, Any]])
async def read_top_users(
platform: Optional[str] = Query(None, description="Filter by platform"),
limit: int = Query(10, ge=1, le=50, description="Number of top users to return"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get top users by post count."""
return await social_media_service.get_top_users(platform=platform, limit=limit, date_from=date_from, date_to=date_to)
@router.get("/categories/list", response_model=List[Dict[str, Any]])
async def read_categories(
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get all categories with post counts."""
return await social_media_service.get_categories(date_from=date_from, date_to=date_to)
@router.get("/users/sentiment", response_model=List[Dict[str, Any]])
async def read_user_sentiment(
limit: int = Query(10, ge=1, le=50, description="Number of users to return"),
platform: Optional[str] = Query(None, description="Filter by platform"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get users with their sentiment breakdown."""
return await social_media_service.get_user_sentiment(limit=limit, platform=platform, date_from=date_from, date_to=date_to)
@router.get("/categories/sentiment", response_model=List[Dict[str, Any]])
async def read_category_sentiment(
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get sentiment distribution by category."""
return await social_media_service.get_category_sentiment(date_from=date_from, date_to=date_to)
@router.get("/topic/trends", response_model=List[Dict[str, Any]])
async def read_trending_topics(
limit: int = Query(10, ge=1, le=50, description="Number of topics to return"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get trending topics with sentiment breakdown."""
return await social_media_service.get_trending_topics(date_from=date_from, date_to=date_to, limit=limit)
@router.get("/trends/time", response_model=List[Dict[str, Any]])
async def read_sentiment_over_time(
platform: Optional[str] = Query(None, description="Filter by platform"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get sentiment trends over time."""
return await social_media_service.get_sentiment_over_time(date_from=date_from, date_to=date_to, platform=platform)
@router.get("/posts/influential", response_model=List[Dict[str, Any]])
async def read_influential_posts(
sentiment: Optional[str] = Query(None, description="Filter by sentiment"),
limit: int = Query(5, ge=1, le=20, description="Number of posts to return"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get most influential posts by engagement, optionally filtered by sentiment."""
return await social_media_service.get_influential_posts(sentiment=sentiment, limit=limit, date_from=date_from, date_to=date_to)
@router.get("/engagement/stats", response_model=Dict[str, Any])
async def read_engagement_stats(
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
):
"""Get overall engagement statistics."""
return await social_media_service.get_engagement_stats(date_from=date_from, date_to=date_to)
def _run_browser_setup_background(sites: Optional[List[str]] = None):
"""Background task to run browser session setup in separate thread."""
try:
if sites and len(sites) > 1:
setup_session_multi(sites)
elif sites and len(sites) > 0:
setup_session_multi(sites)
else:
default_sites = ["https://x.com", "https://facebook.com"]
setup_session_multi(default_sites)
except Exception as e:
print(f"Browser setup error: {e}")
@router.post("/session/setup")
async def setup_browser_session(sites: Optional[List[str]] = Query(None, description="List of sites to setup sessions for")):
"""
Trigger browser session setup in a completely separate thread.
This will open a browser window for manual login to social media platforms.
The API immediately returns while the browser setup runs independently.
"""
thread = threading.Thread(
target=_run_browser_setup_background,
args=(sites,),
daemon=True,
)
thread.start()
return {
"status": "ok",
"message": "Browser session setup triggered successfully",
"note": "Browser window will open shortly for manual authentication",
} | 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/routers/article_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/article_router.py | from fastapi import APIRouter, Query
from typing import List, Optional, Dict, Any
from models.article_schemas import Article, PaginatedArticles
from services.article_service import article_service
router = APIRouter()
@router.get("/", response_model=PaginatedArticles)
async def read_articles(
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(10, ge=1, le=100, description="Items per page"),
source: Optional[str] = Query(None, description="Filter by source name"),
category: Optional[str] = Query(None, description="Filter by category"),
date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"),
search: Optional[str] = Query(None, description="Search in title and summary"),
):
"""
Get all articles with pagination and filtering.
- **page**: Page number (starting from 1)
- **per_page**: Number of items per page (max 100)
- **source**: Filter by source name
- **category**: Filter by category
- **date_from**: Filter by start date (format: YYYY-MM-DD)
- **date_to**: Filter by end date (format: YYYY-MM-DD)
- **search**: Search in title and summary
"""
return await article_service.get_articles(
page=page, per_page=per_page, source=source, category=category, date_from=date_from, date_to=date_to, search=search
)
@router.get("/{article_id}", response_model=Article)
async def read_article(article_id: int):
"""
Get a specific article by ID.
- **article_id**: ID of the article to retrieve
"""
return await article_service.get_article(article_id=article_id)
@router.get("/sources/list", response_model=List[str])
async def read_sources():
"""Get all available sources."""
return await article_service.get_sources()
@router.get("/categories/list", response_model=List[Dict[str, Any]])
async def read_categories():
"""Get all available categories with article counts."""
return await article_service.get_categories()
| 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/routers/podcast_config_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/podcast_config_router.py | from fastapi import APIRouter, Query, Path, Body, status
from typing import List
from models.podcast_config_schemas import PodcastConfig, PodcastConfigCreate, PodcastConfigUpdate
from services.podcast_config_service import podcast_config_service
router = APIRouter()
@router.get("/", response_model=List[PodcastConfig])
async def get_podcast_configs(
active_only: bool = Query(False, description="Include only active podcast configs"),
):
"""
Get all podcast configurations with optional filtering.
- **active_only**: If true, includes only active podcast configurations
"""
return await podcast_config_service.get_all_configs(active_only=active_only)
@router.get("/{config_id}", response_model=PodcastConfig)
async def get_podcast_config(
config_id: int = Path(..., description="The ID of the podcast config to retrieve"),
):
"""
Get a specific podcast configuration by ID.
- **config_id**: The ID of the podcast configuration to retrieve
"""
return await podcast_config_service.get_config(config_id=config_id)
@router.post("/", response_model=PodcastConfig, status_code=status.HTTP_201_CREATED)
async def create_podcast_config(config_data: PodcastConfigCreate = Body(...)):
"""
Create a new podcast configuration.
- **config_data**: Data for the new podcast configuration
"""
return await podcast_config_service.create_config(
name=config_data.name,
prompt=config_data.prompt,
description=config_data.description,
time_range_hours=config_data.time_range_hours,
limit_articles=config_data.limit_articles,
is_active=config_data.is_active,
tts_engine=config_data.tts_engine,
language_code=config_data.language_code,
podcast_script_prompt=config_data.podcast_script_prompt,
image_prompt=config_data.image_prompt,
)
@router.put("/{config_id}", response_model=PodcastConfig)
async def update_podcast_config(
config_id: int = Path(..., description="The ID of the podcast config to update"),
config_data: PodcastConfigUpdate = Body(...),
):
"""
Update an existing podcast configuration.
- **config_id**: The ID of the podcast configuration to update
- **config_data**: Updated data for the podcast configuration
"""
updates = {k: v for k, v in config_data.dict().items() if v is not None}
return await podcast_config_service.update_config(config_id=config_id, updates=updates)
@router.delete("/{config_id}")
async def delete_podcast_config(
config_id: int = Path(..., description="The ID of the podcast config to delete"),
):
"""
Delete a podcast configuration.
- **config_id**: The ID of the podcast configuration to delete
"""
return await podcast_config_service.delete_config(config_id=config_id)
@router.post("/{config_id}/enable", response_model=PodcastConfig)
async def enable_podcast_config(
config_id: int = Path(..., description="The ID of the podcast config to enable"),
):
"""
Enable a podcast configuration.
- **config_id**: The ID of the podcast configuration to enable
"""
return await podcast_config_service.toggle_config(config_id=config_id, enable=True)
@router.post("/{config_id}/disable", response_model=PodcastConfig)
async def disable_podcast_config(
config_id: int = Path(..., description="The ID of the podcast config to disable"),
):
"""
Disable a podcast configuration.
- **config_id**: The ID of the podcast configuration to disable
"""
return await podcast_config_service.toggle_config(config_id=config_id, enable=False)
| 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/routers/source_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/source_router.py | from fastapi import APIRouter, Body, Path, status
from typing import List, Optional, Dict, Any
from models.source_schemas import Source, SourceWithFeeds, Category, PaginatedSources, SourceCreate, SourceUpdate, SourceFeedCreate
from services.source_service import source_service
router = APIRouter()
@router.get("/", response_model=PaginatedSources)
async def read_sources(
page: int = 1, per_page: int = 10, category: Optional[str] = None, search: Optional[str] = None, include_inactive: bool = False
):
"""
Get sources with pagination and filtering.
- **page**: Page number (starting from 1)
- **per_page**: Number of items per page
- **category**: Filter by source category
- **search**: Search in name and description
- **include_inactive**: Include inactive sources
"""
return await source_service.get_sources(page=page, per_page=per_page, category=category, search=search, include_inactive=include_inactive)
@router.get("/categories", response_model=List[Category])
async def read_categories():
"""Get all available source categories."""
return await source_service.get_categories()
@router.get("/by-category/{category_name}", response_model=List[Source])
async def read_sources_by_category(category_name: str):
"""
Get sources by category name.
- **category_name**: Name of the category to filter by
"""
return await source_service.get_source_by_category(category_name=category_name)
@router.get("/{source_id}", response_model=SourceWithFeeds)
async def read_source(source_id: int = Path(..., gt=0)):
"""
Get detailed information about a specific source.
- **source_id**: ID of the source to retrieve
"""
source = await source_service.get_source(source_id=source_id)
feeds = await source_service.get_source_feeds(source_id=source_id)
source_with_feeds = {**source, "feeds": feeds}
return source_with_feeds
@router.get("/by-name/{name}", response_model=SourceWithFeeds)
async def read_source_by_name(name: str):
"""
Get detailed information about a specific source by name.
- **name**: Name of the source to retrieve
"""
source = await source_service.get_source_by_name(name=name)
feeds = await source_service.get_source_feeds(source_id=source["id"])
source_with_feeds = {**source, "feeds": feeds}
return source_with_feeds
@router.post("/", response_model=SourceWithFeeds, status_code=status.HTTP_201_CREATED)
async def create_source(source_data: SourceCreate):
"""
Create a new source.
- **source_data**: Data for the new source
"""
source = await source_service.create_source(source_data)
feeds = await source_service.get_source_feeds(source_id=source["id"])
source_with_feeds = {**source, "feeds": feeds}
return source_with_feeds
@router.put("/{source_id}", response_model=SourceWithFeeds)
async def update_source(source_data: SourceUpdate, source_id: int = Path(..., gt=0)):
"""
Update an existing source.
- **source_id**: ID of the source to update
- **source_data**: Updated data for the source
"""
source = await source_service.update_source(source_id, source_data)
feeds = await source_service.get_source_feeds(source_id=source["id"])
source_with_feeds = {**source, "feeds": feeds}
return source_with_feeds
@router.delete("/{source_id}", response_model=Dict[str, Any])
async def delete_source(source_id: int = Path(..., gt=0), permanent: bool = False):
"""
Delete a source.
- **source_id**: ID of the source to delete
- **permanent**: If true, permanently deletes the source; otherwise, performs a soft delete
"""
if permanent:
return await source_service.hard_delete_source(source_id)
return await source_service.delete_source(source_id)
@router.post("/{source_id}/feeds", response_model=List[Dict[str, Any]])
async def add_feed(feed_data: SourceFeedCreate, source_id: int = Path(..., gt=0)):
"""
Add a new feed to a source.
- **source_id**: ID of the source to add the feed to
- **feed_data**: Data for the new feed
"""
return await source_service.add_feed_to_source(source_id, feed_data)
@router.put("/feeds/{feed_id}", response_model=Dict[str, Any])
async def update_feed(feed_data: Dict[str, Any] = Body(...), feed_id: int = Path(..., gt=0)):
"""
Update an existing feed.
- **feed_id**: ID of the feed to update
- **feed_data**: Updated data for the feed
"""
return await source_service.update_feed(feed_id, feed_data)
@router.delete("/feeds/{feed_id}", response_model=Dict[str, str])
async def delete_feed(feed_id: int = Path(..., gt=0)):
"""
Delete a feed.
- **feed_id**: ID of the feed to delete
"""
return await source_service.delete_feed(feed_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/routers/podcast_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/podcast_router.py | from fastapi import APIRouter, HTTPException, File, UploadFile, Body, Query, Path
from fastapi.responses import FileResponse
from typing import List, Optional
import os
from datetime import datetime
from models.podcast_schemas import Podcast, PodcastDetail, PodcastCreate, PodcastUpdate, PaginatedPodcasts
from services.podcast_service import podcast_service
router = APIRouter()
@router.get("/", response_model=PaginatedPodcasts)
async def get_podcasts(
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(10, ge=1, le=100, description="Items per page"),
search: Optional[str] = Query(None, description="Search in title"),
date_from: Optional[str] = Query(None, description="Filter by date from (YYYY-MM-DD)"),
date_to: Optional[str] = Query(None, description="Filter by date to (YYYY-MM-DD)"),
language_code: Optional[str] = Query(None, description="Filter by language code"),
tts_engine: Optional[str] = Query(None, description="Filter by TTS engine"),
has_audio: Optional[bool] = Query(None, description="Filter by audio availability"),
):
"""
Get a paginated list of podcasts with optional filtering.
"""
return await podcast_service.get_podcasts(
page=page,
per_page=per_page,
search=search,
date_from=date_from,
date_to=date_to,
language_code=language_code,
tts_engine=tts_engine,
has_audio=has_audio,
)
@router.get("/formats", response_model=List[str])
async def get_podcast_formats():
"""
Get a list of available podcast formats for filtering.
"""
return await podcast_service.get_podcast_formats()
@router.get("/language-codes", response_model=List[str])
async def get_language_codes():
"""
Get a list of available language codes for filtering.
"""
return await podcast_service.get_language_codes()
@router.get("/tts-engines", response_model=List[str])
async def get_tts_engines():
"""
Get a list of available TTS engines for filtering.
"""
return await podcast_service.get_tts_engines()
@router.get("/{podcast_id}", response_model=PodcastDetail)
async def get_podcast(podcast_id: int = Path(..., description="The ID of the podcast to retrieve")):
"""
Get detailed information about a specific podcast.
Parameters:
- **podcast_id**: The ID of the podcast to retrieve
Returns the podcast metadata and content.
"""
podcast = await podcast_service.get_podcast(podcast_id)
content = await podcast_service.get_podcast_content(podcast_id)
audio_url = await podcast_service.get_podcast_audio_url(podcast)
sources = podcast.get("sources", [])
if "sources" in podcast:
del podcast["sources"]
banner_images = podcast.get("banner_images", [])
if "banner_images" in podcast:
del podcast["banner_images"]
return {"podcast": podcast, "content": content, "audio_url": audio_url, "sources": sources, "banner_images": banner_images}
@router.get("/by-identifier/{identifier}", response_model=PodcastDetail)
async def get_podcast_by_identifier(identifier: str = Path(..., description="The unique identifier of the podcast")):
"""
Get detailed information about a specific podcast using string identifier.
Parameters:
- **identifier**: The unique identifier of the podcast to retrieve
Returns the podcast metadata and content.
"""
podcast = await podcast_service.get_podcast_by_identifier(identifier)
podcast_id = int(podcast["id"])
content = await podcast_service.get_podcast_content(podcast_id)
audio_url = await podcast_service.get_podcast_audio_url(podcast)
sources = podcast.get("sources", [])
if "sources" in podcast:
del podcast["sources"]
banner_images = podcast.get("banner_images", [])
if "banner_images" in podcast:
del podcast["banner_images"]
return {"podcast": podcast, "content": content, "audio_url": audio_url, "sources": sources, "banner_images": banner_images}
@router.post("/", response_model=Podcast)
async def create_podcast(podcast_data: PodcastCreate = Body(...)):
"""
Create a new podcast.
Parameters:
- **podcast_data**: Podcast data including title, date, content, sources, language_code, and tts_engine
Returns the created podcast metadata.
"""
date = podcast_data.date or datetime.now().strftime("%Y-%m-%d")
return await podcast_service.create_podcast(
title=podcast_data.title,
date=date,
content=podcast_data.content,
sources=podcast_data.sources,
language_code=podcast_data.language_code,
tts_engine=podcast_data.tts_engine,
)
@router.put("/{podcast_id}", response_model=Podcast)
async def update_podcast(podcast_id: int = Path(..., description="The ID of the podcast to update"), podcast_data: PodcastUpdate = Body(...)):
"""
Update an existing podcast's metadata and/or content.
Parameters:
- **podcast_id**: The ID of the podcast to update
- **podcast_data**: Updated data for the podcast
Returns the updated podcast metadata.
"""
update_data = {k: v for k, v in podcast_data.dict().items() if v is not None}
return await podcast_service.update_podcast(podcast_id, update_data)
@router.delete("/{podcast_id}")
async def delete_podcast(podcast_id: int = Path(..., description="The ID of the podcast to delete")):
"""
Delete a podcast.
Parameters:
- **podcast_id**: The ID of the podcast to delete
Returns a success message.
"""
success = await podcast_service.delete_podcast(podcast_id)
if success:
return {"message": f"Podcast {podcast_id} deleted successfully"}
return {"message": "No podcast was deleted"}
@router.post("/{podcast_id}/audio", response_model=Podcast)
async def upload_audio(podcast_id: int = Path(..., description="The ID of the podcast"), file: UploadFile = File(...)):
"""
Upload an audio file for a podcast.
Parameters:
- **podcast_id**: The ID of the podcast to attach the audio to
- **file**: The audio file to upload
Returns the updated podcast.
"""
return await podcast_service.upload_podcast_audio(podcast_id, file)
@router.post("/{podcast_id}/banner", response_model=Podcast)
async def upload_banner(podcast_id: int = Path(..., description="The ID of the podcast"), file: UploadFile = File(...)):
"""
Upload a banner image for a podcast.
Parameters:
- **podcast_id**: The ID of the podcast to attach the banner to
- **file**: The image file to upload
Returns the updated podcast.
"""
return await podcast_service.upload_podcast_banner(podcast_id, file)
@router.get("/audio/{filename}")
async def get_audio_file(filename: str = Path(..., description="The filename of the audio file")):
"""
Get the audio file for a podcast.
Parameters:
- **filename**: The filename of the audio file to retrieve
Returns the audio file as a download.
"""
audio_path = os.path.join("podcasts", "audio", filename)
if not os.path.exists(audio_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(audio_path)
| 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/routers/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/__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/routers/async_podcast_agent_router.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/async_podcast_agent_router.py | from fastapi import APIRouter
from typing import Optional
from pydantic import BaseModel
from services.async_podcast_agent_service import podcast_agent_service
router = APIRouter()
class SessionRequest(BaseModel):
session_id: Optional[str] = None
class ChatRequest(BaseModel):
session_id: str
message: str
class ChatResponse(BaseModel):
session_id: str
response: str
stage: str
session_state: str
is_processing: bool = False
process_type: Optional[str] = None
task_id: Optional[str] = None
browser_recording_path: Optional[str] = None
class StatusRequest(BaseModel):
session_id: str
task_id: Optional[str] = None
@router.post("/session")
async def create_session(request: SessionRequest = None):
"""Create or reuse a session with the podcast agent"""
return await podcast_agent_service.create_session(request)
@router.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""Send a message to the podcast agent and get a response"""
return await podcast_agent_service.chat(request)
@router.post("/status", response_model=ChatResponse)
async def check_status(request: StatusRequest):
"""Check if a result is available for the session"""
return await podcast_agent_service.check_result_status(request)
@router.get("/sessions")
async def list_sessions(page: int = 1, per_page: int = 10):
"""List all saved podcast sessions with pagination"""
return await podcast_agent_service.list_sessions(page, per_page)
@router.get("/session_history")
async def get_session_history(session_id: str):
"""Get the complete message history for a session"""
return await podcast_agent_service.get_session_history(session_id)
@router.delete("/session/{session_id}")
async def delete_session(session_id: str):
"""Delete a podcast session and all its data"""
return await podcast_agent_service.delete_session(session_id)
@router.get("/languages")
async def get_supported_languages():
"""Get the list of supported languages"""
return await podcast_agent_service.get_supported_languages()
| 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/processors/faiss_indexing_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/faiss_indexing_processor.py | import os
import time
import argparse
import numpy as np
import faiss
from db.config import get_tracking_db_path, get_faiss_db_path
from db.connection import db_connection, execute_query
def initialize_faiss_index(dimension=1536, index_path=None, index_type="hnsw", n_list=100):
if index_path and os.path.exists(index_path):
print(f"Loading existing FAISS index from {index_path}")
try:
index = faiss.read_index(index_path)
print(f"Loaded index with {index.ntotal} vectors")
return index
except Exception as e:
print(f"Error loading FAISS index: {str(e)}")
print("Creating a new index instead")
print(f"Creating new FAISS index with dimension {dimension}, type: {index_type}")
if index_type == "flat":
return faiss.IndexFlatL2(dimension)
elif index_type == "ivfflat":
quantizer = faiss.IndexFlatL2(dimension)
index = faiss.IndexIVFFlat(quantizer, dimension, n_list)
print("Training IVF index with random vectors...")
train_size = max(10000, n_list * 10)
train_vectors = np.random.random((train_size, dimension)).astype(np.float32)
index.train(train_vectors)
index.nprobe = min(10, n_list // 10)
return index
elif index_type == "ivfpq":
quantizer = faiss.IndexFlatL2(dimension)
m = 16
bits = 8
index = faiss.IndexIVFPQ(quantizer, dimension, n_list, m, bits)
print("Training IVF-PQ index with random vectors...")
train_size = max(10000, n_list * 10)
train_vectors = np.random.random((train_size, dimension)).astype(np.float32)
index.train(train_vectors)
index.nprobe = min(10, n_list // 10)
return index
elif index_type == "hnsw":
m = 32
ef_construction = 100
index = faiss.IndexHNSWFlat(dimension, m)
index.hnsw.efConstruction = ef_construction
index.hnsw.efSearch = 64
return index
else:
print(f"Unknown index type '{index_type}', falling back to IVF Flat")
quantizer = faiss.IndexFlatL2(dimension)
index = faiss.IndexIVFFlat(quantizer, dimension, n_list)
print("Training IVF index with random vectors...")
train_size = max(10000, n_list * 10)
train_vectors = np.random.random((train_size, dimension)).astype(np.float32)
index.train(train_vectors)
index.nprobe = min(10, n_list // 10)
return index
def save_faiss_index(index, index_path):
try:
index_dir = os.path.dirname(index_path)
os.makedirs(index_dir, exist_ok=True)
temp_path = f"{index_path}.tmp"
faiss.write_index(index, temp_path)
os.replace(temp_path, index_path)
print(f"FAISS index saved to {index_path}")
return True
except Exception as e:
print(f"Error saving FAISS index: {str(e)}")
return False
def save_id_mapping(id_map, mapping_path):
try:
mapping_dir = os.path.dirname(mapping_path)
os.makedirs(mapping_dir, exist_ok=True)
np.save(mapping_path, np.array(id_map))
print(f"ID mapping saved to {mapping_path}")
return True
except Exception as e:
print(f"Error saving ID mapping: {str(e)}")
try:
print("Trying alternative save method...")
simple_path = os.path.join(mapping_dir, "article_id_map.npy")
np.save(simple_path, np.array(id_map))
print(f"ID mapping saved to {simple_path} (alternative path)")
return True
except Exception as e:
print(f"Alternative save method also failed: {str(e)}")
return False
def load_id_mapping(mapping_path):
if os.path.exists(mapping_path):
try:
return np.load(mapping_path).tolist()
except Exception as e:
print(f"Error loading ID mapping: {str(e)}")
return []
def get_embeddings_not_in_index(tracking_db_path, limit=100):
query = """
SELECT ae.id, ae.article_id, ae.embedding, ae.embedding_model
FROM article_embeddings ae
WHERE ae.in_faiss_index = 0
LIMIT ?
"""
return execute_query(tracking_db_path, query, (limit,), fetch=True)
def mark_embeddings_as_indexed(tracking_db_path, embedding_ids):
if not embedding_ids:
return 0
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
placeholders = ",".join(["?"] * len(embedding_ids))
query = f"""
UPDATE article_embeddings
SET in_faiss_index = 1
WHERE id IN ({placeholders})
"""
cursor.execute(query, embedding_ids)
conn.commit()
return cursor.rowcount
def add_embeddings_to_index(embeddings_data, faiss_index, id_map):
if not embeddings_data:
return 0, []
embeddings = []
article_ids = []
embedding_ids = []
for data in embeddings_data:
try:
embedding_blob = data["embedding"]
embedding = np.frombuffer(embedding_blob, dtype=np.float32)
if embedding.shape[0] != faiss_index.d:
print(f"Embedding dimension mismatch: expected {faiss_index.d}, got {embedding.shape[0]}")
continue
embeddings.append(embedding)
article_ids.append(data["article_id"])
embedding_ids.append(data["id"])
except Exception as e:
print(f"Error processing embedding {data['id']}: {str(e)}")
if not embeddings:
return 0, []
try:
embeddings_array = np.vstack(embeddings).astype(np.float32)
faiss_index.add(embeddings_array)
for article_id in article_ids:
id_map.append(article_id)
print(f"Added {len(embeddings)} embeddings to FAISS index")
return len(embeddings), embedding_ids
except Exception as e:
print(f"Error adding embeddings to FAISS index: {str(e)}")
return 0, []
def process_embeddings_for_indexing(
tracking_db_path=None,
index_path=None,
mapping_path=None,
batch_size=100,
index_type="ivfflat",
n_list=100,
):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
index_dir = os.path.dirname(index_path)
os.makedirs(index_dir, exist_ok=True)
id_map = load_id_mapping(mapping_path)
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='article_embeddings'
""")
table_exists = cursor.fetchone() is not None
if not table_exists:
print("article_embeddings table does not exist. Please run embedding_processor first.")
return {"processed": 0, "added": 0, "errors": 0, "total_vectors": 0, "status": "table_missing"}
sample_query = """
SELECT embedding FROM article_embeddings LIMIT 1
"""
sample = execute_query(tracking_db_path, sample_query, fetch=True, fetch_one=True)
if not sample:
print("No embeddings found in the database")
default_dimension = 1536
print(f"Using default dimension: {default_dimension}")
faiss_index = initialize_faiss_index(
dimension=default_dimension, index_path=index_path if os.path.exists(index_path) else None, index_type=index_type, n_list=n_list
)
return {
"processed": 0,
"added": 0,
"errors": 0,
"total_vectors": faiss_index.ntotal if hasattr(faiss_index, "ntotal") else 0,
"status": "no_embeddings",
}
embedding_dimension = len(np.frombuffer(sample["embedding"], dtype=np.float32))
print(f"Detected embedding dimension: {embedding_dimension}")
faiss_index = initialize_faiss_index(dimension=embedding_dimension, index_path=index_path, index_type=index_type, n_list=n_list)
embeddings_data = get_embeddings_not_in_index(tracking_db_path, limit=batch_size)
if not embeddings_data:
print("No new embeddings to add to the index")
return {"processed": 0, "added": 0, "errors": 0, "total_vectors": faiss_index.ntotal, "status": "no_new_embeddings"}
added_count, embedding_ids = add_embeddings_to_index(embeddings_data, faiss_index, id_map)
if added_count > 0:
save_faiss_index(faiss_index, index_path)
save_id_mapping(id_map, mapping_path)
marked_count = mark_embeddings_as_indexed(tracking_db_path, embedding_ids)
print(f"Marked {marked_count} embeddings as indexed in the database")
stats = {
"processed": len(embeddings_data),
"added": added_count,
"errors": len(embeddings_data) - added_count,
"total_vectors": faiss_index.ntotal,
"index_type": index_type,
"status": "success",
}
return stats
def process_in_batches(
tracking_db_path=None,
index_path=None,
mapping_path=None,
batch_size=100,
total_batches=5,
delay_between_batches=2,
index_type="ivfflat",
n_list=100,
):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
total_stats = {"processed": 0, "added": 0, "errors": 0, "index_type": index_type}
for i in range(total_batches):
print(f"\nProcessing batch {i + 1}/{total_batches}")
batch_stats = process_embeddings_for_indexing(
tracking_db_path=tracking_db_path,
index_path=index_path,
mapping_path=mapping_path,
batch_size=batch_size,
index_type=index_type,
n_list=n_list,
)
total_stats["processed"] += batch_stats["processed"]
total_stats["added"] += batch_stats["added"]
total_stats["errors"] += batch_stats["errors"]
if "total_vectors" in batch_stats:
total_stats["total_vectors"] = batch_stats["total_vectors"]
if batch_stats["processed"] == 0:
print("No more embeddings to process")
break
if i < total_batches - 1:
print(f"Waiting {delay_between_batches} seconds before next batch...")
time.sleep(delay_between_batches)
return total_stats
def print_stats(stats):
print("\nFAISS Indexing Statistics:")
print(f"Total embeddings processed: {stats['processed']}")
print(f"Successfully added to index: {stats['added']}")
print(f"Errors: {stats['errors']}")
if "total_vectors" in stats:
print(f"Total vectors in index: {stats['total_vectors']}")
if "index_type" in stats:
print(f"Index type: {stats['index_type']}")
if stats["index_type"] == "flat":
print("Index performance: Most accurate but slowest for large datasets")
elif stats["index_type"] == "ivfflat":
print("Index performance: Good balance of accuracy and speed")
elif stats["index_type"] == "ivfpq":
print("Index performance: Memory efficient, good for very large datasets")
elif stats["index_type"] == "hnsw":
print("Index performance: Excellent search speed with good accuracy")
def parse_arguments():
parser = argparse.ArgumentParser(description="Process embeddings and add to FAISS index")
parser.add_argument(
"--batch_size",
type=int,
default=100,
help="Number of embeddings to process in each batch",
)
parser.add_argument(
"--index_path",
default="databases/faiss/article_index.faiss",
help="Path to save the FAISS index",
)
parser.add_argument(
"--mapping_path",
default="databases/faiss/article_id_map.npy",
help="Path to save the ID mapping file",
)
parser.add_argument(
"--index_type",
choices=["flat", "ivfflat", "ivfpq", "hnsw"],
default="hnsw",
help="Type of FAISS index to create",
)
parser.add_argument(
"--n_list",
type=int,
default=100,
help="Number of clusters for IVF-based indexes",
)
parser.add_argument(
"--total_batches",
type=int,
default=5,
help="Total number of batches to process",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
index_path, mapping_path = get_faiss_db_path()
index_path = args.index_path or index_path
mapping_path = args.mapping_path or mapping_path
stats = process_in_batches(
batch_size=args.batch_size,
index_path=index_path,
mapping_path=mapping_path,
total_batches=args.total_batches,
index_type=args.index_type,
n_list=args.n_list,
)
| 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/processors/podcast_generator_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/podcast_generator_processor.py | import os
import json
from datetime import datetime
from typing import List, Dict, Any, Optional
from tools.pipeline.search_agent import search_agent_run
from tools.pipeline.scrape_agent import scrape_agent_run
from tools.pipeline.script_agent import script_agent_run
from tools.pipeline.image_generate_agent import image_generation_agent_run
from db.config import get_tracking_db_path, get_podcasts_db_path, get_tasks_db_path
from db.podcast_configs import get_podcast_config, get_all_podcast_configs
from db.agent_config_v2 import AVAILABLE_LANGS
from utils.tts_engine_selector import generate_podcast_audio
from utils.load_api_keys import load_api_key
from tools.session_state_manager import _save_podcast_to_database_sync
PODCAST_ASSETS_DIR = "podcasts"
def get_language_name(language_code: str) -> str:
language_map = {lang["code"]: lang["name"] for lang in AVAILABLE_LANGS}
return language_map.get(language_code, "English")
def convert_script_to_audio_format(podcast_data: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
speaker_map = {"ALEX": 1, "MORGAN": 2}
dict_entries = []
for section in podcast_data.get("sections", []):
for dialog in section.get("dialog", []):
speaker = dialog.get("speaker", "ALEX")
text = dialog.get("text", "")
if text and speaker in speaker_map:
dict_entries.append({"text": text, "speaker": speaker_map[speaker]})
return {"entries": dict_entries}
def generate_podcast_from_prompt_v2(
prompt: str,
openai_api_key: str,
tracking_db_path: Optional[str] = None,
podcasts_db_path: Optional[str] = None,
output_dir: str = PODCAST_ASSETS_DIR,
tts_engine: str = "kokoro",
language_code: str = "en",
podcast_script_prompt: Optional[str] = None,
image_prompt: Optional[str] = None,
debug: bool = False,
) -> Dict[str, Any]:
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if podcasts_db_path is None:
podcasts_db_path = get_podcasts_db_path()
os.makedirs(output_dir, exist_ok=True)
images_dir = os.path.join(output_dir, "images")
os.makedirs(images_dir, exist_ok=True)
print(f"Starting enhanced podcast generation for prompt: {prompt}")
try:
search_results = search_agent_run(prompt)
if not search_results:
print(f"WARNING: No search results found for prompt: {prompt}")
return {"error": "No search results found"}
print(f"Found {len(search_results)} search results")
if debug:
print("Search results:", json.dumps(search_results[:2], indent=2))
except Exception as e:
print(f"ERROR: Search agent failed: {e}")
return {"error": f"Search agent failed: {str(e)}"}
try:
scraped_results = scrape_agent_run(prompt, search_results)
if not scraped_results:
print("WARNING: No content could be scraped")
return {"error": "No content could be scraped"}
confirmed_results = []
for result in scraped_results:
if result.get("full_text") and len(result["full_text"].strip()) > 100:
result["confirmed"] = True
confirmed_results.append(result)
if not confirmed_results:
print("WARNING: No high-quality content available after scraping")
return {"error": "No high-quality content available"}
print(f"Successfully scraped {len(confirmed_results)} high-quality articles")
if debug:
print("Sample scraped content:", confirmed_results[0].get("full_text", "")[:200])
except Exception as e:
print(f"ERROR: Scrape agent failed: {e}")
return {"error": f"Scrape agent failed: {str(e)}"}
try:
language_name = get_language_name(language_code)
podcast_data = script_agent_run(query=prompt, search_results=confirmed_results, language_name=language_name)
if not podcast_data or not isinstance(podcast_data, dict):
print("ERROR: Failed to generate podcast script")
return {"error": "Failed to generate podcast script"}
if not podcast_data.get("sections"):
print("ERROR: Generated podcast script is missing required sections")
return {"error": "Invalid podcast script structure"}
print(f"Generated script with {len(podcast_data['sections'])} sections")
if debug:
print("Script title:", podcast_data.get("title", "No title"))
except Exception as e:
print(f"ERROR: Script agent failed: {e}")
return {"error": f"Script agent failed: {str(e)}"}
banner_filenames = []
banner_url = None
try:
image_query = image_prompt if image_prompt else prompt
image_result = image_generation_agent_run(image_query, podcast_data)
if image_result and image_result.get("banner_images"):
banner_filenames = image_result["banner_images"]
banner_url = image_result.get("banner_url")
print(f"Generated {len(banner_filenames)} banner images")
else:
print("WARNING: No images were generated")
except Exception as e:
print(f"ERROR: Image generation failed: {e}")
audio_filename = None
full_audio_path = None
try:
audio_format = convert_script_to_audio_format(podcast_data)
audio_filename = f"podcast_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
audio_path = os.path.join(output_dir, "audio", audio_filename)
class DictPodcastScript:
def __init__(self, entries):
self.entries = entries
def __iter__(self):
return iter(self.entries)
script_obj = DictPodcastScript(audio_format["entries"])
full_audio_path = generate_podcast_audio(
script=script_obj,
output_path=audio_path,
tts_engine=tts_engine,
language_code=language_code,
)
if full_audio_path:
print(f"Generated podcast audio: {full_audio_path}")
else:
print("ERROR: Failed to generate audio")
audio_filename = None
except Exception as e:
print(f"ERROR: Error generating audio: {e}")
import traceback
traceback.print_exc()
audio_filename = None
try:
session_state = {
"generated_script": podcast_data,
"banner_url": banner_url,
"banner_images": banner_filenames,
"audio_url": full_audio_path,
"tts_engine": tts_engine,
"selected_language": {"code": language_code, "name": get_language_name(language_code)},
"podcast_info": {"topic": prompt},
}
success, message, podcast_id = _save_podcast_to_database_sync(session_state)
if success:
print(f"Stored podcast data with ID: {podcast_id}")
else:
print(f"ERROR: Failed to save to database: {message}")
podcast_id = 0
except Exception as e:
print(f"ERROR: Error storing podcast data: {e}")
podcast_id = 0
if audio_filename:
frontend_audio_path = os.path.join(output_dir, audio_filename).replace("\\", "/")
else:
frontend_audio_path = None
if banner_url:
frontend_banner_path = banner_url.replace("\\", "/")
else:
frontend_banner_path = None
return {
"podcast_id": podcast_id,
"title": podcast_data.get("title", "Podcast"),
"audio_path": frontend_audio_path,
"banner_path": frontend_banner_path,
"banner_images": banner_filenames,
"script": podcast_data,
"tts_engine": tts_engine,
"language": language_code,
"sources_count": len(confirmed_results),
"processing_stats": {
"search_results": len(search_results),
"scraped_results": len(scraped_results),
"confirmed_results": len(confirmed_results),
"images_generated": len(banner_filenames),
"audio_generated": bool(audio_filename),
},
}
def generate_podcast_from_config_v2(
config_id: int,
openai_api_key: str,
tracking_db_path: Optional[str] = None,
podcasts_db_path: Optional[str] = None,
tasks_db_path: Optional[str] = None,
output_dir: str = PODCAST_ASSETS_DIR,
debug: bool = False,
) -> Dict[str, Any]:
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if podcasts_db_path is None:
podcasts_db_path = get_podcasts_db_path()
if tasks_db_path is None:
tasks_db_path = get_tasks_db_path()
config = get_podcast_config(tasks_db_path, config_id)
if not config:
print(f"ERROR: Podcast configuration not found: {config_id}")
return {"error": f"Podcast configuration not found: {config_id}"}
prompt = config.get("prompt", "")
time_range_hours = config.get("time_range_hours", 24)
limit_articles = config.get("limit_articles", 20)
tts_engine = config.get("tts_engine", "elevenlabs")
language_code = config.get("language_code", "en")
podcast_script_prompt = config.get("podcast_script_prompt")
image_prompt = config.get("image_prompt")
print(f"Generating podcast with enhanced config: {config.get('name', 'Unnamed')}")
print(f"Prompt: {prompt}")
print(f"Time range: {time_range_hours} hours")
print(f"Limit: {limit_articles} articles")
print(f"TTS Engine: {tts_engine}")
print(f"Language: {language_code}")
return generate_podcast_from_prompt_v2(
prompt=prompt,
openai_api_key=openai_api_key,
tracking_db_path=tracking_db_path,
podcasts_db_path=podcasts_db_path,
output_dir=output_dir,
tts_engine=tts_engine,
language_code=language_code,
podcast_script_prompt=podcast_script_prompt,
image_prompt=image_prompt,
debug=debug,
)
def process_all_active_configs_v2(
openai_api_key: str,
tracking_db_path: Optional[str] = None,
podcasts_db_path: Optional[str] = None,
tasks_db_path: Optional[str] = None,
output_dir: str = PODCAST_ASSETS_DIR,
debug: bool = False,
) -> List[Dict[str, Any]]:
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if podcasts_db_path is None:
podcasts_db_path = get_podcasts_db_path()
if tasks_db_path is None:
tasks_db_path = get_tasks_db_path()
configs = get_all_podcast_configs(tasks_db_path, active_only=True)
if not configs:
print("WARNING: No active podcast configurations found")
return [{"error": "No active podcast configurations found"}]
results = []
total_configs = len(configs)
print(f"Processing {total_configs} active podcast configurations with enhanced pipeline...")
for i, config in enumerate(configs, 1):
config_id = config["id"]
config_name = config["name"]
print(f"\n[{i}/{total_configs}] Processing podcast configuration {config_id}: {config_name}")
try:
result = generate_podcast_from_config_v2(
config_id=config_id,
openai_api_key=openai_api_key,
tracking_db_path=tracking_db_path,
podcasts_db_path=podcasts_db_path,
tasks_db_path=tasks_db_path,
output_dir=output_dir,
debug=debug,
)
result["config_id"] = config_id
result["config_name"] = config_name
results.append(result)
if "error" not in result:
stats = result.get("processing_stats", {})
print(f"Success - Podcast ID: {result.get('podcast_id', 'Unknown')}")
print(f"Sources: {stats.get('confirmed_results', 0)} articles processed")
print(f"Images: {stats.get('images_generated', 0)} generated")
print(f"Audio: {'Yes' if stats.get('audio_generated') else 'No'}")
else:
print(f"Failed: {result['error']}")
except Exception as e:
print(f"ERROR: Error generating podcast for config {config_id}: {e}")
results.append({"config_id": config_id, "config_name": config_name, "error": str(e)})
return results
def main():
openai_api_key = load_api_key()
tasks_db_path = get_tasks_db_path()
if not openai_api_key:
print("ERROR: No OpenAI API key provided. Please set OPENAI_API_KEY environment variable.")
return 1
output_dir = PODCAST_ASSETS_DIR
debug = False
print("Starting Enhanced Agent-Based Podcast Generation System")
print("=" * 60)
results = process_all_active_configs_v2(
openai_api_key=openai_api_key,
tasks_db_path=tasks_db_path,
output_dir=output_dir,
debug=debug,
)
print("\n" + "=" * 60)
print("PODCAST GENERATION RESULTS SUMMARY")
print("=" * 60)
successful = 0
failed = 0
for result in results:
config_id = result.get("config_id", "Unknown")
config_name = result.get("config_name", "Unknown")
if "error" in result:
print(f"Config {config_id} ({config_name}): {result['error']}")
failed += 1
else:
podcast_id = result.get("podcast_id", "Unknown")
stats = result.get("processing_stats", {})
print(f"Config {config_id} ({config_name}): Success")
print(f"Podcast ID: {podcast_id}")
print(f"Sources: {stats.get('confirmed_results', 0)} articles")
print(f"Images: {stats.get('images_generated', 0)} generated")
successful += 1
print("=" * 60)
print(f"FINAL STATS: {successful} successful, {failed} failed out of {len(results)} total")
print("=" * 60)
return 0
if __name__ == "__main__":
exit(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/processors/feed_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/feed_processor.py | import time
import random
from utils.rss_feed_parser import get_feed_data
from db.config import get_sources_db_path, get_tracking_db_path
from db.feeds import (
get_active_feeds,
count_active_feeds,
get_feed_tracking_info,
update_feed_tracking,
store_feed_entries,
update_tracking_info,
)
def fetch_and_process_feeds(sources_db_path=None, tracking_db_path=None, delay_between_feeds=2, batch_size=100):
if sources_db_path is None:
sources_db_path = get_sources_db_path()
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
total_feeds = count_active_feeds(sources_db_path)
stats = {
"total_feeds": total_feeds,
"processed_feeds": 0,
"new_entries": 0,
"unchanged_feeds": 0,
"failed_feeds": 0,
}
offset = 0
while offset < total_feeds:
feeds = get_active_feeds(sources_db_path, limit=batch_size, offset=offset)
if not feeds:
break
update_tracking_info(tracking_db_path, feeds)
for feed in feeds:
feed_id = feed["id"]
source_id = feed["source_id"]
feed_url = feed["feed_url"]
tracking_info = get_feed_tracking_info(tracking_db_path, feed_id)
etag = tracking_info.get("last_etag") if tracking_info else None
modified = tracking_info.get("last_modified") if tracking_info else None
last_hash = tracking_info.get("entry_hash") if tracking_info else None
try:
feed_data = get_feed_data(feed_url, etag=etag, modified=modified)
if not feed_data["is_rss_feed"]:
print(f"Feed {feed_url} is not a valid RSS feed")
stats["failed_feeds"] += 1
continue
if feed_data["status"] == 304:
print(f"Feed {feed_url} not modified since last check")
stats["unchanged_feeds"] += 1
continue
current_hash = feed_data["current_hash"]
if last_hash and current_hash == last_hash:
print(f"Feed {feed_url} content unchanged based on hash")
stats["unchanged_feeds"] += 1
continue
parsed_entries = feed_data["parsed_entries"]
if parsed_entries:
new_entries = store_feed_entries(tracking_db_path, feed_id, source_id, parsed_entries)
stats["new_entries"] += new_entries
print(f"Stored {new_entries} new entries from {feed_url}")
update_feed_tracking(
tracking_db_path,
feed_id,
feed_data["etag"],
feed_data["modified"],
current_hash,
)
stats["processed_feeds"] += 1
except Exception as e:
print(f"Error processing feed {feed_url}: {str(e)}")
stats["failed_feeds"] += 1
time.sleep(random.uniform(1, delay_between_feeds))
offset += batch_size
return stats
def print_stats(stats):
print("\nFeed Processing Statistics:")
print(f"Total feeds: {stats['total_feeds']}")
print(f"Processed feeds: {stats['processed_feeds']}")
print(f"Unchanged feeds: {stats['unchanged_feeds']}")
print(f"Failed feeds: {stats['failed_feeds']}")
print(f"New entries: {stats['new_entries']}")
if __name__ == "__main__":
stats = fetch_and_process_feeds()
print_stats(stats)
| 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/processors/fb_scraper_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/fb_scraper_processor.py |
import sys
from datetime import datetime
from db.config import get_social_media_db_path
from tools.social.fb_scraper import crawl_facebook_feed
def main():
print(f"Starting facebook.com feed scraping at {datetime.now().isoformat()}")
db_path = get_social_media_db_path()
try:
print("Running facebook.com feed scraper")
posts = crawl_facebook_feed("https://facebook.com", db_file=db_path)
print(f"facebook.com scraping completed at {datetime.now().isoformat()}")
print(f"Collected {posts} posts from feed")
except Exception as e:
print(f"Error executing facebook.com feed scraper: {str(e)}")
sys.exit(1)
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/processors/ai_analysis_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/ai_analysis_processor.py | import json
import time
import random
import argparse
from bs4 import BeautifulSoup
from openai import OpenAI
from db.config import get_tracking_db_path
from db.articles import get_unprocessed_articles, update_article_status
from utils.load_api_keys import load_api_key
WEB_PAGE_ANALYSE_MODEL = "gpt-4o"
MODEL_INSTRUCTION = "You are a helpful assistant that analyzes articles and extracts structured information."
def extract_clean_text(raw_html, max_tokens=8000):
soup = BeautifulSoup(raw_html, "html.parser")
for element in soup(["script", "style", "nav", "header", "footer", "aside"]):
element.decompose()
text = soup.get_text(separator="\n", strip=True)
lines = [line.strip() for line in text.splitlines() if line.strip()]
text = "\n".join(lines)
approx_tokens = len(text) / 4
if approx_tokens > max_tokens:
text = text[: max_tokens * 4]
return text
def process_article_with_ai(client, article, max_tokens=8000):
clean_text = extract_clean_text(article["raw_content"], max_tokens)
metadata = article.get("metadata", {})
title = article["title"]
url = article["url"]
description = ""
if metadata and isinstance(metadata, dict):
if "description" in metadata:
description = metadata["description"]
elif "og" in metadata and "description" in metadata["og"]:
description = metadata["og"]["description"]
try:
response = client.chat.completions.create(
model=WEB_PAGE_ANALYSE_MODEL,
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": MODEL_INSTRUCTION,
},
{
"role": "user",
"content": f"""
Analyze this article and provide a structured output with three components:
1. A list of 3-5 relevant categories for this article
2. A concise 2-3 sentence summary of the article
3. The extracted main article content, removing any navigation, ads, or irrelevant elements
Article Title: {title}
Article URL: {url}
Description: {description}
Article Text:
{clean_text}
Provide your response as a JSON object with these keys:
- categories: an array of 3-5 relevant categories (as strings)
- summary: a 2-3 sentence summary of the article
- content: the cleaned main article content
""",
},
],
temperature=0.3,
max_tokens=1500,
)
response_json = json.loads(response.choices[0].message.content)
categories = response_json.get("categories", [])
if isinstance(categories, str):
categories = [cat.strip() for cat in categories.split(",") if cat.strip()]
results = {
"categories": categories,
"summary": response_json.get("summary", ""),
"content": response_json.get("content", ""),
}
return results, True, None
except Exception as e:
error_message = str(e)
print(f"Error processing article with AI: {error_message}")
return None, False, error_message
def analyze_articles(tracking_db_path=None, openai_api_key=None, batch_size=5, delay_range=(1, 3)):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if openai_api_key is None:
raise ValueError("OpenAI API key is required")
client = OpenAI(api_key=openai_api_key)
articles = get_unprocessed_articles(tracking_db_path, limit=batch_size)
stats = {"total_articles": len(articles), "success_count": 0, "failed_count": 0}
for i, article in enumerate(articles):
article_id = article["id"]
title = article["title"]
attempt = article.get("ai_attempts", 0) + 1
print(f"[{i + 1}/{len(articles)}] Processing article: {title} (Attempt {attempt})")
results, success, error_message = process_article_with_ai(client, article)
update_article_status(tracking_db_path, article_id, results, success, error_message)
if success:
categories_display = ", ".join(results["categories"])
print(f"Successfully processed article ID {article_id}")
print(f"Categories: {categories_display}")
print(f"Summary: {results['summary'][:100]}..." if len(results["summary"]) > 100 else f"Summary: {results['summary']}")
stats["success_count"] += 1
else:
print(f"Failed to process article ID {article_id}: {error_message}")
stats["failed_count"] += 1
if i < len(articles) - 1:
delay = random.uniform(delay_range[0], delay_range[1])
time.sleep(delay)
return stats
def print_stats(stats):
print("\nAI Analysis Statistics:")
print(f"Total articles processed: {stats['total_articles']}")
print(f"Successfully analyzed: {stats['success_count']}")
print(f"Failed: {stats['failed_count']}")
def analyze_in_batches(
tracking_db_path=None,
openai_api_key=None,
batch_size=20,
total_batches=1,
delay_between_batches=10,
):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if openai_api_key is None:
raise ValueError("OpenAI API key is required")
total_stats = {"total_articles": 0, "success_count": 0, "failed_count": 0}
for i in range(total_batches):
print(f"\nProcessing batch {i + 1}/{total_batches}")
batch_stats = analyze_articles(
tracking_db_path=tracking_db_path,
openai_api_key=openai_api_key,
batch_size=batch_size,
)
total_stats["total_articles"] += batch_stats["total_articles"]
total_stats["success_count"] += batch_stats["success_count"]
total_stats["failed_count"] += batch_stats["failed_count"]
if batch_stats["total_articles"] == 0:
print("No more articles to process")
break
if i < total_batches - 1:
print(f"Waiting {delay_between_batches} seconds before next batch...")
time.sleep(delay_between_batches)
return total_stats
def parse_arguments():
parser = argparse.ArgumentParser(description="Process articles with AI analysis")
parser.add_argument("--api_key", help="OpenAI API Key (overrides environment variables)")
parser.add_argument(
"--batch_size",
type=int,
default=10,
help="Number of articles to process in each batch",
)
parser.add_argument(
"--total_batches",
type=int,
default=1,
help="Total number of batches to process",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
api_key = args.api_key or load_api_key()
if not api_key:
print("Error: No OpenAI API key provided. Please provide via --api_key or set OPENAI_API_KEY in .env file")
exit(1)
stats = analyze_in_batches(
openai_api_key=api_key,
batch_size=args.batch_size,
total_batches=args.total_batches,
)
print_stats(stats)
| 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/processors/embedding_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/embedding_processor.py | import time
import argparse
import random
import numpy as np
from openai import OpenAI
from db.config import get_tracking_db_path
from db.connection import db_connection, execute_query
from utils.load_api_keys import load_api_key
EMBEDDING_MODEL = "text-embedding-3-small"
def create_embedding_table(tracking_db_path):
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='article_embeddings'
""")
table_exists = cursor.fetchone() is not None
if not table_exists:
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)
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_article_embeddings_article_id
ON article_embeddings(article_id)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_article_embeddings_in_faiss
ON article_embeddings(in_faiss_index)
""")
conn.commit()
print("Article embeddings table created successfully.")
else:
print("Article embeddings table already exists.")
def get_articles_without_embeddings(tracking_db_path, limit=20):
query = """
SELECT ca.id, ca.title, ca.summary, ca.content
FROM crawled_articles ca
WHERE ca.processed = 1
AND ca.ai_status = 'success'
AND NOT EXISTS (
SELECT 1 FROM article_embeddings ae
WHERE ae.article_id = ca.id
)
ORDER BY ca.published_date DESC
LIMIT ?
"""
return execute_query(tracking_db_path, query, (limit,), fetch=True)
def mark_articles_as_processing(tracking_db_path, article_ids):
if not article_ids:
return 0
try:
with db_connection(tracking_db_path) as conn:
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(crawled_articles)")
columns = [col[1] for col in cursor.fetchall()]
if "embedding_status" in columns:
placeholders = ",".join(["?"] * len(article_ids))
query = f"""
UPDATE crawled_articles
SET embedding_status = 'processing'
WHERE id IN ({placeholders})
"""
cursor.execute(query, article_ids)
conn.commit()
return cursor.rowcount
else:
print("Note: embedding_status column doesn't exist in crawled_articles table.")
print("Skipping article marking step (this is non-critical).")
return len(article_ids)
except Exception as e:
print(f"Error marking articles as processing: {str(e)}")
print("Continuing without marking articles (this is non-critical).")
return 0
def generate_embedding(client, text, model=EMBEDDING_MODEL):
try:
response = client.embeddings.create(input=text, model=model)
return response.data[0].embedding, model
except Exception as e:
print(f"Error generating embedding: {str(e)}")
return None, None
def prepare_article_text(article):
title = article.get("title", "")
summary = article.get("summary", "")
content = article.get("content", "")
full_text = f"Title: {title}\n\nSummary: {summary}\n\nContent: {content}"
return full_text
def store_embedding(tracking_db_path, article_id, embedding, model):
from datetime import datetime
import sqlite3
embedding_blob = np.array(embedding, dtype=np.float32).tobytes()
query = """
INSERT INTO article_embeddings
(article_id, embedding, embedding_model, created_at, in_faiss_index)
VALUES (?, ?, ?, ?, 0)
"""
params = (article_id, embedding_blob, model, datetime.now().isoformat())
try:
execute_query(tracking_db_path, query, params)
return True
except sqlite3.IntegrityError:
print(f"Warning: Embedding already exists for article {article_id}")
return False
except Exception as e:
print(f"Error storing embedding: {str(e)}")
return False
def process_articles_for_embedding(tracking_db_path=None, openai_api_key=None, batch_size=20, delay_range=(1, 3)):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if openai_api_key is None:
raise ValueError("OpenAI API key is required")
create_embedding_table(tracking_db_path)
client = OpenAI(api_key=openai_api_key)
articles = get_articles_without_embeddings(tracking_db_path, limit=batch_size)
if not articles:
print("No articles found that need embeddings")
return {"total_articles": 0, "success_count": 0, "failed_count": 0}
article_ids = [article["id"] for article in articles]
mark_articles_as_processing(tracking_db_path, article_ids)
stats = {"total_articles": len(articles), "success_count": 0, "failed_count": 0}
for i, article in enumerate(articles):
article_id = article["id"]
try:
print(f"[{i + 1}/{len(articles)}] Generating embedding for article {article_id}: {article['title']}")
text = prepare_article_text(article)
embedding, model = generate_embedding(client, text)
if embedding:
success = store_embedding(tracking_db_path, article_id, embedding, model)
if success:
print(f"Successfully stored embedding for article {article_id}")
stats["success_count"] += 1
else:
print(f"Failed to store embedding for article {article_id}")
stats["failed_count"] += 1
else:
print(f"Failed to generate embedding for article {article_id}")
stats["failed_count"] += 1
except Exception as e:
print(f"Error processing article {article_id}: {str(e)}")
stats["failed_count"] += 1
if i < len(articles) - 1:
delay = random.uniform(delay_range[0], delay_range[1])
time.sleep(delay)
return stats
def print_stats(stats):
print("\nEmbedding Generation Statistics:")
print(f"Total articles processed: {stats['total_articles']}")
print(f"Successfully embedded: {stats['success_count']}")
print(f"Failed: {stats['failed_count']}")
def parse_arguments():
parser = argparse.ArgumentParser(description="Generate embeddings for processed articles")
parser.add_argument("--api_key", help="OpenAI API Key (overrides environment variables)")
parser.add_argument(
"--batch_size",
type=int,
default=20,
help="Number of articles to process in each batch",
)
return parser.parse_args()
def process_in_batches(
tracking_db_path=None,
openai_api_key=None,
batch_size=20,
total_batches=1,
delay_between_batches=10,
):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
if openai_api_key is None:
raise ValueError("OpenAI API key is required")
total_stats = {"total_articles": 0, "success_count": 0, "failed_count": 0}
for i in range(total_batches):
print(f"\nProcessing batch {i + 1}/{total_batches}")
batch_stats = process_articles_for_embedding(
tracking_db_path=tracking_db_path,
openai_api_key=openai_api_key,
batch_size=batch_size,
)
total_stats["total_articles"] += batch_stats["total_articles"]
total_stats["success_count"] += batch_stats["success_count"]
total_stats["failed_count"] += batch_stats["failed_count"]
if batch_stats["total_articles"] == 0:
print("No more articles to process")
break
if i < total_batches - 1:
print(f"Waiting {delay_between_batches} seconds before next batch...")
time.sleep(delay_between_batches)
return total_stats
if __name__ == "__main__":
args = parse_arguments()
api_key = args.api_key or load_api_key()
if not api_key:
print("Error: No OpenAI API key provided. Please provide via --api_key or set OPENAI_API_KEY in .env file")
exit(1)
stats = process_in_batches(
openai_api_key=api_key,
batch_size=args.batch_size,
total_batches=3,
)
print_stats(stats)
| 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/processors/__init__.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/__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/processors/x_scraper_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/x_scraper_processor.py |
import sys
from datetime import datetime
from db.config import get_social_media_db_path
from tools.social.x_scraper import crawl_x_profile
def main():
print(f"Starting X.com feed scraping at {datetime.now().isoformat()}")
db_path = get_social_media_db_path()
try:
print("Running X.com feed scraper")
posts = crawl_x_profile("home", db_file=db_path)
print(f"X.com feed scraping completed at {datetime.now().isoformat()}")
print(f"Collected {posts} posts from feed")
except Exception as e:
print(f"Error executing X.com feed scraper: {str(e)}")
sys.exit(1)
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/processors/url_processor.py | advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/processors/url_processor.py | from db.config import get_tracking_db_path
from db.feeds import get_uncrawled_entries
from db.articles import store_crawled_article, update_entry_status
from utils.crawl_url import get_web_data
def crawl_pending_entries(tracking_db_path=None, batch_size=20, delay_range=(1, 3), max_attempts=3):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
entries = get_uncrawled_entries(tracking_db_path, limit=batch_size, max_attempts=max_attempts)
stats = {
"total_entries": len(entries),
"success_count": 0,
"failed_count": 0,
"skipped_count": 0,
}
for entry in entries:
entry_id = entry["id"]
url = entry["link"]
if not url or url.strip() == "":
update_entry_status(tracking_db_path, entry_id, "skipped")
stats["skipped_count"] += 1
continue
print(f"Crawling URL: {url}")
try:
web_data = get_web_data(url)
if not web_data or not web_data["raw_html"]:
print(f"No content retrieved for {url}")
update_entry_status(tracking_db_path, entry_id, "failed")
stats["failed_count"] += 1
continue
success = store_crawled_article(tracking_db_path, entry, web_data["raw_html"], web_data["metadata"])
if success:
update_entry_status(tracking_db_path, entry_id, "success")
stats["success_count"] += 1
print(f"Successfully crawled: {url}")
else:
update_entry_status(tracking_db_path, entry_id, "failed")
stats["failed_count"] += 1
print(f"Failed to store: {url} (likely duplicate)")
except Exception as e:
print(f"Error crawling {url}: {str(e)}")
update_entry_status(tracking_db_path, entry_id, "failed")
stats["failed_count"] += 1
return stats
def print_stats(stats):
print("\nCrawl Statistics:")
print(f"Total entries processed: {stats['total_entries']}")
print(f"Successfully crawled: {stats['success_count']}")
print(f"Failed: {stats['failed_count']}")
print(f"Skipped (no URL): {stats['skipped_count']}")
def crawl_in_batches(tracking_db_path=None, batch_size=20, total_batches=5, delay_between_batches=10):
if tracking_db_path is None:
tracking_db_path = get_tracking_db_path()
total_stats = {
"total_entries": 0,
"success_count": 0,
"failed_count": 0,
"skipped_count": 0,
}
for i in range(total_batches):
print(f"\nProcessing batch {i + 1}/{total_batches}")
batch_stats = crawl_pending_entries(tracking_db_path=tracking_db_path, batch_size=batch_size)
total_stats["total_entries"] += batch_stats["total_entries"]
total_stats["success_count"] += batch_stats["success_count"]
total_stats["failed_count"] += batch_stats["failed_count"]
total_stats["skipped_count"] += batch_stats["skipped_count"]
if batch_stats["total_entries"] == 0:
print("No more entries to process")
break
if i < total_batches - 1:
print(f"Waiting {delay_between_batches} seconds before next batch...")
return total_stats
if __name__ == "__main__":
stats = crawl_in_batches(batch_size=20, total_batches=50)
print_stats(stats)
| 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/agent_teams/ai_teaching_agent_team/teaching_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_teaching_agent_team/teaching_agent_team.py | import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.models.openai import OpenAIChat
from composio_phidata import Action, ComposioToolSet
import os
from agno.tools.arxiv import ArxivTools
from agno.utils.pprint import pprint_run_response
from agno.tools.serpapi import SerpApiTools
# Set page configuration
st.set_page_config(page_title="👨🏫 AI Teaching Agent Team", layout="centered")
# Initialize session state for API keys and topic
if 'openai_api_key' not in st.session_state:
st.session_state['openai_api_key'] = ''
if 'composio_api_key' not in st.session_state:
st.session_state['composio_api_key'] = ''
if 'serpapi_api_key' not in st.session_state:
st.session_state['serpapi_api_key'] = ''
if 'topic' not in st.session_state:
st.session_state['topic'] = ''
# Streamlit sidebar for API keys
with st.sidebar:
st.title("API Keys Configuration")
st.session_state['openai_api_key'] = st.text_input("Enter your OpenAI API Key", type="password").strip()
st.session_state['composio_api_key'] = st.text_input("Enter your Composio API Key", type="password").strip()
st.session_state['serpapi_api_key'] = st.text_input("Enter your SerpAPI Key", type="password").strip()
# Add info about terminal responses
st.info("Note: You can also view detailed agent responses\nin your terminal after execution.")
# Validate API keys
if not st.session_state['openai_api_key'] or not st.session_state['composio_api_key'] or not st.session_state['serpapi_api_key']:
st.error("Please enter OpenAI, Composio, and SerpAPI keys in the sidebar.")
st.stop()
# Set the OpenAI API key and Composio API key from session state
os.environ["OPENAI_API_KEY"] = st.session_state['openai_api_key']
try:
composio_toolset = ComposioToolSet(api_key=st.session_state['composio_api_key'])
google_docs_tool = composio_toolset.get_tools(actions=[Action.GOOGLEDOCS_CREATE_DOCUMENT])[0]
google_docs_tool_update = composio_toolset.get_tools(actions=[Action.GOOGLEDOCS_UPDATE_EXISTING_DOCUMENT])[0]
except Exception as e:
st.error(f"Error initializing ComposioToolSet: {e}")
st.stop()
# Create the Professor agent (formerly KnowledgeBuilder)
professor_agent = Agent(
name="Professor",
role="Research and Knowledge Specialist",
model=OpenAIChat(id="gpt-4o-mini", api_key=st.session_state['openai_api_key']),
tools=[google_docs_tool],
instructions=[
"Create a comprehensive knowledge base that covers fundamental concepts, advanced topics, and current developments of the given topic.",
"Exlain the topic from first principles first. Include key terminology, core principles, and practical applications and make it as a detailed report that anyone who's starting out can read and get maximum value out of it.",
"Make sure it is formatted in a way that is easy to read and understand. DONT FORGET TO CREATE THE GOOGLE DOCUMENT.",
"Open a new Google Doc and write down the response of the agent neatly with great formatting and structure in it. **Include the Google Doc link in your response.**",
],
debug_mode=True,
markdown=True,
)
# Create the Academic Advisor agent (formerly RoadmapArchitect)
academic_advisor_agent = Agent(
name="Academic Advisor",
role="Learning Path Designer",
model=OpenAIChat(id="gpt-4o-mini", api_key=st.session_state['openai_api_key']),
tools=[google_docs_tool],
instructions=[
"Using the knowledge base for the given topic, create a detailed learning roadmap.",
"Break down the topic into logical subtopics and arrange them in order of progression, a detailed report of roadmap that includes all the subtopics in order to be an expert in this topic.",
"Include estimated time commitments for each section.",
"Present the roadmap in a clear, structured format. DONT FORGET TO CREATE THE GOOGLE DOCUMENT.",
"Open a new Google Doc and write down the response of the agent neatly with great formatting and structure in it. **Include the Google Doc link in your response.**",
],
debug_mode=True,
markdown=True
)
# Create the Research Librarian agent (formerly ResourceCurator)
research_librarian_agent = Agent(
name="Research Librarian",
role="Learning Resource Specialist",
model=OpenAIChat(id="gpt-4o-mini", api_key=st.session_state['openai_api_key']),
tools=[google_docs_tool, SerpApiTools(api_key=st.session_state['serpapi_api_key']) ],
instructions=[
"Make a list of high-quality learning resources for the given topic.",
"Use the SerpApi search tool to find current and relevant learning materials.",
"Using SerpApi search tool, Include technical blogs, GitHub repositories, official documentation, video tutorials, and courses.",
"Present the resources in a curated list with descriptions and quality assessments. DONT FORGET TO CREATE THE GOOGLE DOCUMENT.",
"Open a new Google Doc and write down the response of the agent neatly with great formatting and structure in it. **Include the Google Doc link in your response.**",
],
debug_mode=True,
markdown=True,
)
# Create the Teaching Assistant agent (formerly PracticeDesigner)
teaching_assistant_agent = Agent(
name="Teaching Assistant",
role="Exercise Creator",
model=OpenAIChat(id="gpt-4o-mini", api_key=st.session_state['openai_api_key']),
tools=[google_docs_tool, SerpApiTools(api_key=st.session_state['serpapi_api_key'])],
instructions=[
"Create comprehensive practice materials for the given topic.",
"Use the SerpApi search tool to find example problems and real-world applications.",
"Include progressive exercises, quizzes, hands-on projects, and real-world application scenarios.",
"Ensure the materials align with the roadmap progression.",
"Provide detailed solutions and explanations for all practice materials.DONT FORGET TO CREATE THE GOOGLE DOCUMENT.",
"Open a new Google Doc and write down the response of the agent neatly with great formatting and structure in it. **Include the Google Doc link in your response.**",
],
debug_mode=True,
markdown=True,
)
# Streamlit main UI
st.title("👨🏫 AI Teaching Agent Team")
st.markdown("Enter a topic to generate a detailed learning path and resources")
# Add info message about Google Docs
st.info("📝 The agents will create detailed Google Docs for each section (Professor, Academic Advisor, Research Librarian, and Teaching Assistant). The links to these documents will be displayed below after processing.")
# Query bar for topic input
st.session_state['topic'] = st.text_input("Enter the topic you want to learn about:", placeholder="e.g., Machine Learning, LoRA, etc.")
# Start button
if st.button("Start"):
if not st.session_state['topic']:
st.error("Please enter a topic.")
else:
# Display loading animations while generating responses
with st.spinner("Generating Knowledge Base..."):
professor_response: RunOutput = professor_agent.run(
f"the topic is: {st.session_state['topic']},Don't forget to add the Google Doc link in your response."
)
with st.spinner("Generating Learning Roadmap..."):
academic_advisor_response: RunOutput = academic_advisor_agent.run(
f"the topic is: {st.session_state['topic']},Don't forget to add the Google Doc link in your response."
)
with st.spinner("Curating Learning Resources..."):
research_librarian_response: RunOutput = research_librarian_agent.run(
f"the topic is: {st.session_state['topic']},Don't forget to add the Google Doc link in your response."
)
with st.spinner("Creating Practice Materials..."):
teaching_assistant_response: RunOutput = teaching_assistant_agent.run(
f"the topic is: {st.session_state['topic']},Don't forget to add the Google Doc link in your response."
)
# Extract Google Doc links from the responses
def extract_google_doc_link(response_content):
# Assuming the Google Doc link is embedded in the response content
# You may need to adjust this logic based on the actual response format
if "https://docs.google.com" in response_content:
return response_content.split("https://docs.google.com")[1].split()[0]
return None
professor_doc_link = extract_google_doc_link(professor_response.content)
academic_advisor_doc_link = extract_google_doc_link(academic_advisor_response.content)
research_librarian_doc_link = extract_google_doc_link(research_librarian_response.content)
teaching_assistant_doc_link = extract_google_doc_link(teaching_assistant_response.content)
# Display Google Doc links at the top of the Streamlit UI
st.markdown("### Google Doc Links:")
if professor_doc_link:
st.markdown(f"- **Professor Document:** [View Document](https://docs.google.com{professor_doc_link})")
if academic_advisor_doc_link:
st.markdown(f"- **Academic Advisor Document:** [View Document](https://docs.google.com{academic_advisor_doc_link})")
if research_librarian_doc_link:
st.markdown(f"- **Research Librarian Document:** [View Document](https://docs.google.com{research_librarian_doc_link})")
if teaching_assistant_doc_link:
st.markdown(f"- **Teaching Assistant Document:** [View Document](https://docs.google.com{teaching_assistant_doc_link})")
# Display responses in the Streamlit UI using pprint_run_response
st.markdown("### Professor Response:")
st.markdown(professor_response.content)
pprint_run_response(professor_response, markdown=True)
st.divider()
st.markdown("### Academic Advisor Response:")
st.markdown(academic_advisor_response.content)
pprint_run_response(academic_advisor_response, markdown=True)
st.divider()
st.markdown("### Research Librarian Response:")
st.markdown(research_librarian_response.content)
pprint_run_response(research_librarian_response, markdown=True)
st.divider()
st.markdown("### Teaching Assistant Response:")
st.markdown(teaching_assistant_response.content)
pprint_run_response(teaching_assistant_response, markdown=True)
st.divider()
# Information about the agents
st.markdown("---")
st.markdown("### About the Agents:")
st.markdown("""
- **Professor**: Researches the topic and creates a detailed knowledge base.
- **Academic Advisor**: Designs a structured learning roadmap for the topic.
- **Research Librarian**: Curates high-quality learning resources.
- **Teaching Assistant**: Creates practice materials, exercises, and projects.
""")
| 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/agent_teams/ai_finance_agent_team/finance_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_finance_agent_team/finance_agent_team.py | from agno.agent import Agent
from agno.team import Team
from agno.models.openai import OpenAIChat
from agno.db.sqlite import SqliteDb
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.tools.yfinance import YFinanceTools
from agno.os import AgentOS
# Setup database for storage
db = SqliteDb(db_file="agents.db")
web_agent = Agent(
name="Web Agent",
role="Search the web for information",
model=OpenAIChat(id="gpt-4o"),
tools=[DuckDuckGoTools()],
db=db,
add_history_to_context=True,
markdown=True,
)
finance_agent = Agent(
name="Finance Agent",
role="Get financial data",
model=OpenAIChat(id="gpt-4o"),
tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
instructions=["Always use tables to display data"],
db=db,
add_history_to_context=True,
markdown=True,
)
agent_team = Team(
name="Agent Team (Web+Finance)",
model=OpenAIChat(id="gpt-4o"),
members=[web_agent, finance_agent],
debug_mode=True,
markdown=True,
)
agent_os = AgentOS(agents=[agent_team])
app = agent_os.get_app()
if __name__ == "__main__":
agent_os.serve(app="finance_agent_team: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/advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_coding_agent_team/ai_coding_agent_o3.py | advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_coding_agent_team/ai_coding_agent_o3.py | from typing import Optional, Dict, Any
import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.models.openai import OpenAIChat
from agno.models.google import Gemini
from agno.media import Image as AgnoImage
from e2b_code_interpreter import Sandbox
import os
from PIL import Image
from io import BytesIO
import base64
from pathlib import Path
def initialize_session_state() -> None:
if 'openai_key' not in st.session_state:
st.session_state.openai_key = ''
if 'gemini_key' not in st.session_state:
st.session_state.gemini_key = ''
if 'e2b_key' not in st.session_state:
st.session_state.e2b_key = ''
if 'sandbox' not in st.session_state:
st.session_state.sandbox = None
def setup_sidebar() -> None:
with st.sidebar:
st.title("API Configuration")
st.session_state.openai_key = st.text_input("OpenAI API Key",
value=st.session_state.openai_key,
type="password")
st.session_state.gemini_key = st.text_input("Gemini API Key",
value=st.session_state.gemini_key,
type="password")
st.session_state.e2b_key = st.text_input("E2B API Key",
value=st.session_state.e2b_key,
type="password")
def create_agents() -> tuple[Agent, Agent, Agent]:
vision_agent = Agent(
model=Gemini(id="gemini-2.0-flash", api_key=st.session_state.gemini_key),
markdown=True,
)
coding_agent = Agent(
model=OpenAIChat(
id="o3-mini",
api_key=st.session_state.openai_key,
system_prompt="""You are an expert Python programmer. You will receive coding problems similar to LeetCode questions,
which may include problem statements, sample inputs, and examples. Your task is to:
1. Analyze the problem carefully and Optimally with best possible time and space complexities.
2. Write clean, efficient Python code to solve it
3. Include proper documentation and type hints
4. The code will be executed in an e2b sandbox environment
Please ensure your code is complete and handles edge cases appropriately."""
),
markdown=True
)
execution_agent = Agent(
model=OpenAIChat(
id="o3-mini",
api_key=st.session_state.openai_key,
system_prompt="""You are an expert at executing Python code in sandbox environments.
Your task is to:
1. Take the provided Python code
2. Execute it in the e2b sandbox
3. Format and explain the results clearly
4. Handle any execution errors gracefully
Always ensure proper error handling and clear output formatting."""
),
markdown=True
)
return vision_agent, coding_agent, execution_agent
def initialize_sandbox() -> None:
try:
if st.session_state.sandbox:
try:
st.session_state.sandbox.close()
except:
pass
os.environ['E2B_API_KEY'] = st.session_state.e2b_key
# Initialize sandbox with 60 second timeout
st.session_state.sandbox = Sandbox(timeout=60)
except Exception as e:
st.error(f"Failed to initialize sandbox: {str(e)}")
st.session_state.sandbox = None
def run_code_in_sandbox(code: str) -> Dict[str, Any]:
if not st.session_state.sandbox:
initialize_sandbox()
execution = st.session_state.sandbox.run_code(code)
return {
"logs": execution.logs,
"files": st.session_state.sandbox.files.list("/")
}
def process_image_with_gemini(vision_agent: Agent, image: Image) -> str:
prompt = """Analyze this image and extract any coding problem or code snippet shown.
Describe it in clear natural language, including any:
1. Problem statement
2. Input/output examples
3. Constraints or requirements
Format it as a proper coding problem description."""
# Save image to a temporary file
temp_path = "temp_image.png"
try:
# Convert to RGB if needed
if image.mode != 'RGB':
image = image.convert('RGB')
image.save(temp_path, format="PNG")
# Create Agno Image object
agno_image = AgnoImage(filepath=Path(temp_path))
# Pass image to Gemini
response: RunOutput = vision_agent.run(
prompt,
images=[agno_image]
)
return response.content
except Exception as e:
st.error(f"Error processing image: {str(e)}")
return "Failed to process the image. Please try again or use text input instead."
finally:
# Clean up temporary file
if os.path.exists(temp_path):
os.remove(temp_path)
def execute_code_with_agent(execution_agent: Agent, code: str, sandbox: Sandbox) -> str:
try:
# Set timeout to 30 seconds for code execution
sandbox.set_timeout(30)
execution = sandbox.run_code(code)
# Handle execution errors
if execution.error:
if "TimeoutException" in str(execution.error):
return "⚠️ Execution Timeout: The code took too long to execute (>30 seconds). Please optimize your solution or try a smaller input."
error_prompt = f"""The code execution resulted in an error:
Error: {execution.error}
Please analyze the error and provide a clear explanation of what went wrong."""
response: RunOutput = execution_agent.run(error_prompt)
return f"⚠️ Execution Error:\n{response.content}"
# Get files list safely
try:
files = sandbox.files.list("/")
except:
files = []
prompt = f"""Here is the code execution result:
Logs: {execution.logs}
Files: {str(files)}
Please provide a clear explanation of the results and any outputs."""
response: RunOutput = execution_agent.run(prompt)
return response.content
except Exception as e:
# Reinitialize sandbox on error
try:
initialize_sandbox()
except:
pass
return f"⚠️ Sandbox Error: {str(e)}"
def main() -> None:
st.title("O3-Mini Coding Agent")
# Add timeout info in sidebar
initialize_session_state()
setup_sidebar()
with st.sidebar:
st.info("⏱️ Code execution timeout: 30 seconds")
# Check all required API keys
if not (st.session_state.openai_key and
st.session_state.gemini_key and
st.session_state.e2b_key):
st.warning("Please enter all required API keys in the sidebar.")
return
vision_agent, coding_agent, execution_agent = create_agents()
# Clean, single-column layout
uploaded_image = st.file_uploader(
"Upload an image of your coding problem (optional)",
type=['png', 'jpg', 'jpeg']
)
if uploaded_image:
st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
user_query = st.text_area(
"Or type your coding problem here:",
placeholder="Example: Write a function to find the sum of two numbers. Include sample input/output cases.",
height=100
)
# Process button
if st.button("Generate & Execute Solution", type="primary"):
if uploaded_image and not user_query:
# Process image with Gemini
with st.spinner("Processing image..."):
try:
# Save uploaded file to temporary location
image = Image.open(uploaded_image)
extracted_query = process_image_with_gemini(vision_agent, image)
if extracted_query.startswith("Failed to process"):
st.error(extracted_query)
return
st.info("📝 Extracted Problem:")
st.write(extracted_query)
# Pass extracted query to coding agent
with st.spinner("Generating solution..."):
response: RunOutput = coding_agent.run(extracted_query)
except Exception as e:
st.error(f"Error processing image: {str(e)}")
return
elif user_query and not uploaded_image:
# Direct text input processing
with st.spinner("Generating solution..."):
response: RunOutput = coding_agent.run(user_query)
elif user_query and uploaded_image:
st.error("Please use either image upload OR text input, not both.")
return
else:
st.warning("Please provide either an image or text description of your coding problem.")
return
# Display and execute solution
if 'response' in locals():
st.divider()
st.subheader("💻 Solution")
# Extract code from markdown response
code_blocks = response.content.split("```python")
if len(code_blocks) > 1:
code = code_blocks[1].split("```")[0].strip()
# Display the code
st.code(code, language="python")
# Execute code with execution agent
with st.spinner("Executing code..."):
# Always initialize a fresh sandbox for each execution
initialize_sandbox()
if st.session_state.sandbox:
execution_results = execute_code_with_agent(
execution_agent,
code,
st.session_state.sandbox
)
# Display execution results
st.divider()
st.subheader("🚀 Execution Results")
st.markdown(execution_results)
# Try to display files if available
try:
files = st.session_state.sandbox.files.list("/")
if files:
st.markdown("📁 **Generated Files:**")
st.json(files)
except:
pass
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/agent_teams/ai_recruitment_agent_team/ai_recruitment_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_recruitment_agent_team/ai_recruitment_agent_team.py | from typing import Literal, Tuple, Dict, Optional
import os
import time
import json
import requests
import PyPDF2
from datetime import datetime, timedelta
import pytz
import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.models.openai import OpenAIChat
from agno.tools.email import EmailTools
from phi.tools.zoom import ZoomTool
from phi.utils.log import logger
from streamlit_pdf_viewer import pdf_viewer
class CustomZoomTool(ZoomTool):
def __init__(self, *, account_id: Optional[str] = None, client_id: Optional[str] = None, client_secret: Optional[str] = None, name: str = "zoom_tool"):
super().__init__(account_id=account_id, client_id=client_id, client_secret=client_secret, name=name)
self.token_url = "https://zoom.us/oauth/token"
self.access_token = None
self.token_expires_at = 0
def get_access_token(self) -> str:
if self.access_token and time.time() < self.token_expires_at:
return str(self.access_token)
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = {"grant_type": "account_credentials", "account_id": self.account_id}
try:
response = requests.post(self.token_url, headers=headers, data=data, auth=(self.client_id, self.client_secret))
response.raise_for_status()
token_info = response.json()
self.access_token = token_info["access_token"]
expires_in = token_info["expires_in"]
self.token_expires_at = time.time() + expires_in - 60
self._set_parent_token(str(self.access_token))
return str(self.access_token)
except requests.RequestException as e:
logger.error(f"Error fetching access token: {e}")
return ""
def _set_parent_token(self, token: str) -> None:
"""Helper method to set the token in the parent ZoomTool class"""
if token:
self._ZoomTool__access_token = token
# Role requirements as a constant dictionary
ROLE_REQUIREMENTS: Dict[str, str] = {
"ai_ml_engineer": """
Required Skills:
- Python, PyTorch/TensorFlow
- Machine Learning algorithms and frameworks
- Deep Learning and Neural Networks
- Data preprocessing and analysis
- MLOps and model deployment
- RAG, LLM, Finetuning and Prompt Engineering
""",
"frontend_engineer": """
Required Skills:
- React/Vue.js/Angular
- HTML5, CSS3, JavaScript/TypeScript
- Responsive design
- State management
- Frontend testing
""",
"backend_engineer": """
Required Skills:
- Python/Java/Node.js
- REST APIs
- Database design and management
- System architecture
- Cloud services (AWS/GCP/Azure)
- Kubernetes, Docker, CI/CD
"""
}
def init_session_state() -> None:
"""Initialize only necessary session state variables."""
defaults = {
'candidate_email': "", 'openai_api_key': "", 'resume_text': "", 'analysis_complete': False,
'is_selected': False, 'zoom_account_id': "", 'zoom_client_id': "", 'zoom_client_secret': "",
'email_sender': "", 'email_passkey': "", 'company_name': "", 'current_pdf': None
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
def create_resume_analyzer() -> Agent:
"""Creates and returns a resume analysis agent."""
if not st.session_state.openai_api_key:
st.error("Please enter your OpenAI API key first.")
return None
return Agent(
model=OpenAIChat(
id="gpt-4o",
api_key=st.session_state.openai_api_key
),
description="You are an expert technical recruiter who analyzes resumes.",
instructions=[
"Analyze the resume against the provided job requirements",
"Be lenient with AI/ML candidates who show strong potential",
"Consider project experience as valid experience",
"Value hands-on experience with key technologies",
"Return a JSON response with selection decision and feedback"
],
markdown=True
)
def create_email_agent() -> Agent:
return Agent(
model=OpenAIChat(
id="gpt-4o",
api_key=st.session_state.openai_api_key
),
tools=[EmailTools(
receiver_email=st.session_state.candidate_email,
sender_email=st.session_state.email_sender,
sender_name=st.session_state.company_name,
sender_passkey=st.session_state.email_passkey
)],
description="You are a professional recruitment coordinator handling email communications.",
instructions=[
"Draft and send professional recruitment emails",
"Act like a human writing an email and use all lowercase letters",
"Maintain a friendly yet professional tone",
"Always end emails with exactly: 'best,\nthe ai recruiting team'",
"Never include the sender's or receiver's name in the signature",
f"The name of the company is '{st.session_state.company_name}'"
],
markdown=True,
debug_mode=True
)
def create_scheduler_agent() -> Agent:
zoom_tools = CustomZoomTool(
account_id=st.session_state.zoom_account_id,
client_id=st.session_state.zoom_client_id,
client_secret=st.session_state.zoom_client_secret
)
return Agent(
name="Interview Scheduler",
model=OpenAIChat(
id="gpt-4o",
api_key=st.session_state.openai_api_key
),
tools=[zoom_tools],
description="You are an interview scheduling coordinator.",
instructions=[
"You are an expert at scheduling technical interviews using Zoom.",
"Schedule interviews during business hours (9 AM - 5 PM EST)",
"Create meetings with proper titles and descriptions",
"Ensure all meeting details are included in responses",
"Use ISO 8601 format for dates",
"Handle scheduling errors gracefully"
],
markdown=True,
debug_mode=True
)
def extract_text_from_pdf(pdf_file) -> str:
try:
pdf_reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text()
return text
except Exception as e:
st.error(f"Error extracting PDF text: {str(e)}")
return ""
def analyze_resume(
resume_text: str,
role: Literal["ai_ml_engineer", "frontend_engineer", "backend_engineer"],
analyzer: Agent
) -> Tuple[bool, str]:
try:
response: RunOutput = analyzer.run(
f"""Please analyze this resume against the following requirements and provide your response in valid JSON format:
Role Requirements:
{ROLE_REQUIREMENTS[role]}
Resume Text:
{resume_text}
Your response must be a valid JSON object like this:
{{
"selected": true/false,
"feedback": "Detailed feedback explaining the decision",
"matching_skills": ["skill1", "skill2"],
"missing_skills": ["skill3", "skill4"],
"experience_level": "junior/mid/senior"
}}
Evaluation criteria:
1. Match at least 70% of required skills
2. Consider both theoretical knowledge and practical experience
3. Value project experience and real-world applications
4. Consider transferable skills from similar technologies
5. Look for evidence of continuous learning and adaptability
Important: Return ONLY the JSON object without any markdown formatting or backticks.
"""
)
assistant_message = next((msg.content for msg in response.messages if msg.role == 'assistant'), None)
if not assistant_message:
raise ValueError("No assistant message found in response.")
result = json.loads(assistant_message.strip())
if not isinstance(result, dict) or not all(k in result for k in ["selected", "feedback"]):
raise ValueError("Invalid response format")
return result["selected"], result["feedback"]
except (json.JSONDecodeError, ValueError) as e:
st.error(f"Error processing response: {str(e)}")
return False, f"Error analyzing resume: {str(e)}"
def send_selection_email(email_agent: Agent, to_email: str, role: str) -> None:
email_agent.run(
f"""
Send an email to {to_email} regarding their selection for the {role} position.
The email should:
1. Congratulate them on being selected
2. Explain the next steps in the process
3. Mention that they will receive interview details shortly
4. The name of the company is 'AI Recruiting Team'
"""
)
def send_rejection_email(email_agent: Agent, to_email: str, role: str, feedback: str) -> None:
"""
Send a rejection email with constructive feedback.
"""
email_agent.run(
f"""
Send an email to {to_email} regarding their application for the {role} position.
Use this specific style:
1. use all lowercase letters
2. be empathetic and human
3. mention specific feedback from: {feedback}
4. encourage them to upskill and try again
5. suggest some learning resources based on missing skills
6. end the email with exactly:
best,
the ai recruiting team
Do not include any names in the signature.
The tone should be like a human writing a quick but thoughtful email.
"""
)
def schedule_interview(scheduler: Agent, candidate_email: str, email_agent: Agent, role: str) -> None:
"""
Schedule interviews during business hours (9 AM - 5 PM IST).
"""
try:
# Get current time in IST
ist_tz = pytz.timezone('Asia/Kolkata')
current_time_ist = datetime.now(ist_tz)
tomorrow_ist = current_time_ist + timedelta(days=1)
interview_time = tomorrow_ist.replace(hour=11, minute=0, second=0, microsecond=0)
formatted_time = interview_time.strftime('%Y-%m-%dT%H:%M:%S')
meeting_response = scheduler.run(
f"""Schedule a 60-minute technical interview with these specifications:
- Title: '{role} Technical Interview'
- Date: {formatted_time}
- Timezone: IST (India Standard Time)
- Attendee: {candidate_email}
Important Notes:
- The meeting must be between 9 AM - 5 PM IST
- Use IST (UTC+5:30) timezone for all communications
- Include timezone information in the meeting details
"""
)
email_agent.run(
f"""Send an interview confirmation email with these details:
- Role: {role} position
- Meeting Details: {meeting_response}
Important:
- Clearly specify that the time is in IST (India Standard Time)
- Ask the candidate to join 5 minutes early
- Include timezone conversion link if possible
- Ask him to be confident and not so nervous and prepare well for the interview
"""
)
st.success("Interview scheduled successfully! Check your email for details.")
except Exception as e:
logger.error(f"Error scheduling interview: {str(e)}")
st.error("Unable to schedule interview. Please try again.")
def main() -> None:
st.title("AI Recruitment System")
init_session_state()
with st.sidebar:
st.header("Configuration")
# OpenAI Configuration
st.subheader("OpenAI Settings")
api_key = st.text_input("OpenAI API Key", type="password", value=st.session_state.openai_api_key, help="Get your API key from platform.openai.com")
if api_key: st.session_state.openai_api_key = api_key
st.subheader("Zoom Settings")
zoom_account_id = st.text_input("Zoom Account ID", type="password", value=st.session_state.zoom_account_id)
zoom_client_id = st.text_input("Zoom Client ID", type="password", value=st.session_state.zoom_client_id)
zoom_client_secret = st.text_input("Zoom Client Secret", type="password", value=st.session_state.zoom_client_secret)
st.subheader("Email Settings")
email_sender = st.text_input("Sender Email", value=st.session_state.email_sender, help="Email address to send from")
email_passkey = st.text_input("Email App Password", type="password", value=st.session_state.email_passkey, help="App-specific password for email")
company_name = st.text_input("Company Name", value=st.session_state.company_name, help="Name to use in email communications")
if zoom_account_id: st.session_state.zoom_account_id = zoom_account_id
if zoom_client_id: st.session_state.zoom_client_id = zoom_client_id
if zoom_client_secret: st.session_state.zoom_client_secret = zoom_client_secret
if email_sender: st.session_state.email_sender = email_sender
if email_passkey: st.session_state.email_passkey = email_passkey
if company_name: st.session_state.company_name = company_name
required_configs = {'OpenAI API Key': st.session_state.openai_api_key, 'Zoom Account ID': st.session_state.zoom_account_id,
'Zoom Client ID': st.session_state.zoom_client_id, 'Zoom Client Secret': st.session_state.zoom_client_secret,
'Email Sender': st.session_state.email_sender, 'Email Password': st.session_state.email_passkey,
'Company Name': st.session_state.company_name}
missing_configs = [k for k, v in required_configs.items() if not v]
if missing_configs:
st.warning(f"Please configure the following in the sidebar: {', '.join(missing_configs)}")
return
if not st.session_state.openai_api_key:
st.warning("Please enter your OpenAI API key in the sidebar to continue.")
return
role = st.selectbox("Select the role you're applying for:", ["ai_ml_engineer", "frontend_engineer", "backend_engineer"])
with st.expander("View Required Skills", expanded=True): st.markdown(ROLE_REQUIREMENTS[role])
# Add a "New Application" button before the resume upload
if st.button("📝 New Application"):
# Clear only the application-related states
keys_to_clear = ['resume_text', 'analysis_complete', 'is_selected', 'candidate_email', 'current_pdf']
for key in keys_to_clear:
if key in st.session_state:
st.session_state[key] = None if key == 'current_pdf' else ""
st.rerun()
resume_file = st.file_uploader("Upload your resume (PDF)", type=["pdf"], key="resume_uploader")
if resume_file is not None and resume_file != st.session_state.get('current_pdf'):
st.session_state.current_pdf = resume_file
st.session_state.resume_text = ""
st.session_state.analysis_complete = False
st.session_state.is_selected = False
st.rerun()
if resume_file:
st.subheader("Uploaded Resume")
col1, col2 = st.columns([4, 1])
with col1:
import tempfile, os
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
tmp_file.write(resume_file.read())
tmp_file_path = tmp_file.name
resume_file.seek(0)
try: pdf_viewer(tmp_file_path)
finally: os.unlink(tmp_file_path)
with col2:
st.download_button(label="📥 Download", data=resume_file, file_name=resume_file.name, mime="application/pdf")
# Process the resume text
if not st.session_state.resume_text:
with st.spinner("Processing your resume..."):
resume_text = extract_text_from_pdf(resume_file)
if resume_text:
st.session_state.resume_text = resume_text
st.success("Resume processed successfully!")
else:
st.error("Could not process the PDF. Please try again.")
# Email input with session state
email = st.text_input(
"Candidate's email address",
value=st.session_state.candidate_email,
key="email_input"
)
st.session_state.candidate_email = email
# Analysis and next steps
if st.session_state.resume_text and email and not st.session_state.analysis_complete:
if st.button("Analyze Resume"):
with st.spinner("Analyzing your resume..."):
resume_analyzer = create_resume_analyzer()
email_agent = create_email_agent() # Create email agent here
if resume_analyzer and email_agent:
print("DEBUG: Starting resume analysis")
is_selected, feedback = analyze_resume(
st.session_state.resume_text,
role,
resume_analyzer
)
print(f"DEBUG: Analysis complete - Selected: {is_selected}, Feedback: {feedback}")
if is_selected:
st.success("Congratulations! Your skills match our requirements.")
st.session_state.analysis_complete = True
st.session_state.is_selected = True
st.rerun()
else:
st.warning("Unfortunately, your skills don't match our requirements.")
st.write(f"Feedback: {feedback}")
# Send rejection email
with st.spinner("Sending feedback email..."):
try:
send_rejection_email(
email_agent=email_agent,
to_email=email,
role=role,
feedback=feedback
)
st.info("We've sent you an email with detailed feedback.")
except Exception as e:
logger.error(f"Error sending rejection email: {e}")
st.error("Could not send feedback email. Please try again.")
if st.session_state.get('analysis_complete') and st.session_state.get('is_selected', False):
st.success("Congratulations! Your skills match our requirements.")
st.info("Click 'Proceed with Application' to continue with the interview process.")
if st.button("Proceed with Application", key="proceed_button"):
print("DEBUG: Proceed button clicked") # Debug
with st.spinner("🔄 Processing your application..."):
try:
print("DEBUG: Creating email agent") # Debug
email_agent = create_email_agent()
print(f"DEBUG: Email agent created: {email_agent}") # Debug
print("DEBUG: Creating scheduler agent") # Debug
scheduler_agent = create_scheduler_agent()
print(f"DEBUG: Scheduler agent created: {scheduler_agent}") # Debug
# 3. Send selection email
with st.status("📧 Sending confirmation email...", expanded=True) as status:
print(f"DEBUG: Attempting to send email to {st.session_state.candidate_email}") # Debug
send_selection_email(
email_agent,
st.session_state.candidate_email,
role
)
print("DEBUG: Email sent successfully") # Debug
status.update(label="✅ Confirmation email sent!")
# 4. Schedule interview
with st.status("📅 Scheduling interview...", expanded=True) as status:
print("DEBUG: Attempting to schedule interview") # Debug
schedule_interview(
scheduler_agent,
st.session_state.candidate_email,
email_agent,
role
)
print("DEBUG: Interview scheduled successfully") # Debug
status.update(label="✅ Interview scheduled!")
print("DEBUG: All processes completed successfully") # Debug
st.success("""
🎉 Application Successfully Processed!
Please check your email for:
1. Selection confirmation ✅
2. Interview details with Zoom link 🔗
Next steps:
1. Review the role requirements
2. Prepare for your technical interview
3. Join the interview 5 minutes early
""")
except Exception as e:
print(f"DEBUG: Error occurred: {str(e)}") # Debug
print(f"DEBUG: Error type: {type(e)}") # Debug
import traceback
print(f"DEBUG: Full traceback: {traceback.format_exc()}") # Debug
st.error(f"An error occurred: {str(e)}")
st.error("Please try again or contact support.")
# Reset button
if st.sidebar.button("Reset Application"):
for key in st.session_state.keys():
if key != 'openai_api_key':
del st.session_state[key]
st.rerun()
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/agent_teams/ai_seo_audit_team/__init__.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_seo_audit_team/__init__.py | """AI SEO Audit Team package."""
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/agent_teams/ai_seo_audit_team/agent.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_seo_audit_team/agent.py | """
On-Page SEO Audit & Optimization Team built with Google ADK.
The workflow runs three specialized agents in sequence:
1. Page Auditor → scrapes the target URL with Firecrawl and extracts the structural audit + keyword focus.
2. SERP Analyst → performs competitive analysis with Google Search using the discovered primary keyword.
3. Optimization Advisor → synthesizes the audit and SERP insights into a prioritized optimization report.
"""
from __future__ import annotations
import os
from typing import List, Optional
from pydantic import BaseModel, Field
from google.adk.agents import LlmAgent, SequentialAgent
from google.adk.tools import google_search
from google.adk.tools.agent_tool import AgentTool
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
# =============================================================================
# Output Schemas
# =============================================================================
class HeadingItem(BaseModel):
tag: str = Field(..., description="Heading tag such as h1, h2, h3.")
text: str = Field(..., description="Text content of the heading.")
class LinkCounts(BaseModel):
internal: Optional[int] = Field(None, description="Number of internal links on the page.")
external: Optional[int] = Field(None, description="Number of external links on the page.")
broken: Optional[int] = Field(None, description="Number of broken links detected.")
notes: Optional[str] = Field(
None, description="Additional qualitative observations about linking."
)
class AuditResults(BaseModel):
title_tag: str = Field(..., description="Full title tag text.")
meta_description: str = Field(..., description="Meta description text.")
primary_heading: str = Field(..., description="Primary H1 heading on the page.")
secondary_headings: List[HeadingItem] = Field(
default_factory=list, description="Secondary headings (H2-H4) in reading order."
)
word_count: Optional[int] = Field(
None, description="Approximate number of words in the main content."
)
content_summary: str = Field(
..., description="Summary of the main topics and structure of the content."
)
link_counts: LinkCounts = Field(
...,
description="Quantitative snapshot of internal/external/broken links.",
)
technical_findings: List[str] = Field(
default_factory=list,
description="List of notable technical SEO issues (e.g., missing alt text, slow LCP).",
)
content_opportunities: List[str] = Field(
default_factory=list,
description="Observed content gaps or opportunities for improvement.",
)
class TargetKeywords(BaseModel):
primary_keyword: str = Field(..., description="Most likely primary keyword target.")
secondary_keywords: List[str] = Field(
default_factory=list, description="Related secondary or supporting keywords."
)
search_intent: str = Field(
...,
description="Dominant search intent inferred from the page (informational, transactional, etc.).",
)
supporting_topics: List[str] = Field(
default_factory=list,
description="Cluster of supporting topics or entities that reinforce the keyword strategy.",
)
class PageAuditOutput(BaseModel):
audit_results: AuditResults = Field(..., description="Structured on-page audit findings.")
target_keywords: TargetKeywords = Field(
..., description="Keyword focus derived from page content."
)
class SerpResult(BaseModel):
rank: int = Field(..., description="Organic ranking position.")
title: str = Field(..., description="Title of the search result.")
url: str = Field(..., description="Landing page URL.")
snippet: str = Field(..., description="SERP snippet or summary.")
content_type: str = Field(
..., description="Content format (blog post, landing page, tool, video, etc.)."
)
class SerpAnalysis(BaseModel):
primary_keyword: str = Field(..., description="Keyword used for SERP research.")
top_10_results: List[SerpResult] = Field(
..., description="Top organic competitors for the keyword."
)
title_patterns: List[str] = Field(
default_factory=list,
description="Common patterns or phrases used in competitor titles.",
)
content_formats: List[str] = Field(
default_factory=list,
description="Typical content formats found (guides, listicles, comparison pages, etc.).",
)
people_also_ask: List[str] = Field(
default_factory=list,
description="Representative questions surfaced in People Also Ask.",
)
key_themes: List[str] = Field(
default_factory=list,
description="Notable recurring themes, features, or angles competitors emphasize.",
)
differentiation_opportunities: List[str] = Field(
default_factory=list,
description="Opportunities to stand out versus competitors.",
)
class OptimizationRecommendation(BaseModel):
priority: str = Field(..., description="Priority level (P0, P1, P2).")
area: str = Field(..., description="Optimization focus area (content, technical, UX, etc.).")
recommendation: str = Field(..., description="Recommended action.")
rationale: str = Field(..., description="Why this change matters, referencing audit/SERP data.")
expected_impact: str = Field(..., description="Anticipated impact on SEO or user metrics.")
effort: str = Field(..., description="Relative effort required (low/medium/high).")
# =============================================================================
# Tools
# =============================================================================
# Firecrawl MCP Toolset - connects to Firecrawl's MCP server for web scraping
firecrawl_toolset = MCPToolset(
connection_params=StdioServerParameters(
command='npx',
args=[
"-y", # Auto-confirm npm package installation
"firecrawl-mcp", # The Firecrawl MCP server package
],
env={
"FIRECRAWL_API_KEY": os.getenv("FIRECRAWL_API_KEY", "")
}
),
# Filter to use only the scrape tool for this agent
tool_filter=['firecrawl_scrape']
)
# =============================================================================
# Helper Agents
# =============================================================================
search_executor_agent = LlmAgent(
name="perform_google_search",
model="gemini-2.5-flash",
description="Executes Google searches for provided queries and returns structured results.",
instruction="""The latest user message contains the keyword to search.
- Call google_search with that exact query and fetch the top organic results (aim for 10).
- Respond with JSON text containing the query and an array of result objects (title, url, snippet). Use an empty array when nothing is returned.
- No additional commentary—return JSON text only.""",
tools=[google_search],
)
google_search_tool = AgentTool(search_executor_agent)
# =============================================================================
# Agent Definitions
# =============================================================================
page_auditor_agent = LlmAgent(
name="PageAuditorAgent",
model="gemini-2.5-flash",
description=(
"Scrapes the target URL, performs a structural on-page SEO audit, and extracts keyword signals."
),
instruction="""You are Agent 1 in a sequential SEO workflow. Your role is to gather data silently for the next agents.
STEP 1: Extract the URL
- Look for a URL in the user's message (it will start with http:// or https://)
- Example: If user says "Audit https://theunwindai.com", extract "https://theunwindai.com"
STEP 2: Call firecrawl_scrape
- Call `firecrawl_scrape` with these exact parameters:
url: <the URL you extracted>
formats: ["markdown", "html", "links"]
onlyMainContent: true
timeout: 90000
- Note: timeout is 90 seconds (90000ms)
STEP 3: Analyze the scraped data
- Parse the markdown content to find title tag, meta description, H1, H2-H4 headings
- Count words in the main content
- Count internal and external links
- Identify technical SEO issues
- Identify content opportunities
STEP 4: Infer keywords
- Based on the page content, determine the primary keyword (1-3 words)
- Identify 2-5 secondary keywords
- Determine search intent (informational, transactional, navigational, commercial)
- List 3-5 supporting topics
STEP 5: Return JSON
- Populate EVERY field in the PageAuditOutput schema with actual data
- Use "Not available" only if truly missing from scraped data
- Return ONLY valid JSON, no extra text before or after""",
tools=[firecrawl_toolset],
output_schema=PageAuditOutput,
output_key="page_audit",
)
serp_analyst_agent = LlmAgent(
name="SerpAnalystAgent",
model="gemini-2.5-flash",
description=(
"Researches the live SERP for the discovered primary keyword and summarizes the competitive landscape."
),
instruction="""You are Agent 2 in the workflow. Your role is to silently gather SERP data for the final report agent.
STEP 1: Get the primary keyword
- Read `state['page_audit']['target_keywords']['primary_keyword']`
- Example: if it's "AI tools", you'll use that for search
STEP 2: Call perform_google_search
- IMPORTANT: You MUST call the `perform_google_search` tool
- Pass the primary keyword as the request parameter
- Example: if primary_keyword is "AI tools", call perform_google_search with request="AI tools"
STEP 3: Parse search results
- You should receive 10+ search results with title, url, snippet
- For each result (up to 10):
* Assign rank (1-10)
* Extract title
* Extract URL
* Extract snippet
* Infer content_type (blog post, landing page, tool, directory, video, etc.)
STEP 4: Analyze patterns
- title_patterns: Common words/phrases in titles (e.g., "Best", "Top 10", "Free", year)
- content_formats: Types you see (guides, listicles, comparison pages, tool directories)
- people_also_ask: Related questions (infer from snippets if not explicit)
- key_themes: Recurring topics across results
- differentiation_opportunities: Gaps or unique angles not covered by competitors
STEP 5: Return JSON
- Populate ALL fields in SerpAnalysis schema
- top_10_results MUST have 10 items (or as many as you found)
- DO NOT return empty arrays unless search truly failed
- Return ONLY valid JSON, no extra text""",
tools=[google_search_tool],
output_schema=SerpAnalysis,
output_key="serp_analysis",
)
optimization_advisor_agent = LlmAgent(
name="OptimizationAdvisorAgent",
model="gemini-2.5-flash",
description="Synthesizes the audit and SERP findings into a prioritized optimization roadmap.",
instruction="""You are Agent 3 and the final expert in the workflow. You create the user-facing report.
STEP 1: Review the data
- Read `state['page_audit']` for:
* Title tag, meta description, H1
* Word count, headings structure
* Link counts
* Technical findings
* Content opportunities
* Primary and secondary keywords
- Read `state['serp_analysis']` for:
* Top 10 competitors
* Title patterns
* Content formats
* Key themes
* Differentiation opportunities
STEP 2: Create the report
Start with "# SEO Audit Report" and include these sections:
1. **Executive Summary** (2-3 paragraphs)
- Page being audited
- Primary keyword focus
- Key strengths and weaknesses
2. **Technical & On-Page Findings**
- Current title tag and suggestions
- Current meta description and suggestions
- H1 and heading structure analysis
- Word count and content depth
- Link profile (internal/external counts)
- Technical issues found
3. **Keyword Analysis**
- Primary keyword: [from state]
- Secondary keywords: [list from state]
- Search intent: [from state]
- Supporting topics: [list from state]
4. **Competitive SERP Analysis**
- What top competitors are doing
- Common title patterns
- Dominant content formats
- Key themes in top results
- Content gaps/opportunities
5. **Prioritized Recommendations**
Group by P0/P1/P2 with:
- Specific action
- Rationale (cite data)
- Expected impact
- Effort level
6. **Next Steps**
- Measurement plan
- Timeline suggestions
STEP 3: Output
- Return ONLY Markdown
- NO JSON
- NO preamble text
- Start directly with "# SEO Audit Report"
- Be specific with data points (e.g., "Current title is X characters, recommend Y"
""",
)
seo_audit_team = SequentialAgent(
name="SeoAuditTeam",
description=(
"Runs a three-agent sequential pipeline that audits a page, researches SERP competitors, "
"and produces an optimization plan."
),
sub_agents=[
page_auditor_agent,
serp_analyst_agent,
optimization_advisor_agent,
],
)
# Expose the root agent for the ADK runtime and Dev UI.
root_agent = seo_audit_team
| 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/agent_teams/ai_legal_agent_team/legal_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_legal_agent_team/legal_agent_team.py | import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.team import Team
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.qdrant import Qdrant
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.models.openai import OpenAIChat
from agno.knowledge.embedder.openai import OpenAIEmbedder
import tempfile
import os
def init_session_state():
"""Initialize session state variables"""
if 'openai_api_key' not in st.session_state:
st.session_state.openai_api_key = None
if 'qdrant_api_key' not in st.session_state:
st.session_state.qdrant_api_key = None
if 'qdrant_url' not in st.session_state:
st.session_state.qdrant_url = None
if 'vector_db' not in st.session_state:
st.session_state.vector_db = None
if 'legal_team' not in st.session_state:
st.session_state.legal_team = None
if 'knowledge_base' not in st.session_state:
st.session_state.knowledge_base = None
# Add a new state variable to track processed files
if 'processed_files' not in st.session_state:
st.session_state.processed_files = set()
COLLECTION_NAME = "legal_documents" # Define your collection name
def init_qdrant():
"""Initialize Qdrant client with configured settings."""
if not all([st.session_state.qdrant_api_key, st.session_state.qdrant_url]):
return None
try:
# Create Agno's Qdrant instance which implements VectorDb
vector_db = Qdrant(
collection=COLLECTION_NAME,
url=st.session_state.qdrant_url,
api_key=st.session_state.qdrant_api_key,
embedder=OpenAIEmbedder(
id="text-embedding-3-small",
api_key=st.session_state.openai_api_key
)
)
return vector_db
except Exception as e:
st.error(f"🔴 Qdrant connection failed: {str(e)}")
return None
def process_document(uploaded_file, vector_db: Qdrant):
"""
Process document, create embeddings and store in Qdrant vector database
Args:
uploaded_file: Streamlit uploaded file object
vector_db (Qdrant): Initialized Qdrant instance from Agno
Returns:
Knowledge: Initialized knowledge base with processed documents
"""
if not st.session_state.openai_api_key:
raise ValueError("OpenAI API key not provided")
os.environ['OPENAI_API_KEY'] = st.session_state.openai_api_key
try:
# Save the uploaded file to a temporary location
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
temp_file.write(uploaded_file.getvalue())
temp_file_path = temp_file.name
st.info("Loading and processing document...")
# Create a Knowledge base with the vector_db
knowledge_base = Knowledge(
vector_db=vector_db
)
# Add the document to the knowledge base
with st.spinner('📤 Loading documents into knowledge base...'):
try:
knowledge_base.add_content(path=temp_file_path)
st.success("✅ Documents stored successfully!")
except Exception as e:
st.error(f"Error loading documents: {str(e)}")
raise
# Clean up the temporary file
try:
os.unlink(temp_file_path)
except Exception:
pass
return knowledge_base
except Exception as e:
st.error(f"Document processing error: {str(e)}")
raise Exception(f"Error processing document: {str(e)}")
def main():
st.set_page_config(page_title="Legal Document Analyzer", layout="wide")
init_session_state()
st.title("AI Legal Agent Team 👨⚖️")
with st.sidebar:
st.header("🔑 API Configuration")
openai_key = st.text_input(
"OpenAI API Key",
type="password",
value=st.session_state.openai_api_key if st.session_state.openai_api_key else "",
help="Enter your OpenAI API key"
)
if openai_key:
st.session_state.openai_api_key = openai_key
qdrant_key = st.text_input(
"Qdrant API Key",
type="password",
value=st.session_state.qdrant_api_key if st.session_state.qdrant_api_key else "",
help="Enter your Qdrant API key"
)
if qdrant_key:
st.session_state.qdrant_api_key = qdrant_key
qdrant_url = st.text_input(
"Qdrant URL",
value=st.session_state.qdrant_url if st.session_state.qdrant_url else "",
help="Enter your Qdrant instance URL"
)
if qdrant_url:
st.session_state.qdrant_url = qdrant_url
if all([st.session_state.qdrant_api_key, st.session_state.qdrant_url]):
try:
if not st.session_state.vector_db:
# Make sure we're initializing a QdrantClient here
st.session_state.vector_db = init_qdrant()
if st.session_state.vector_db:
st.success("Successfully connected to Qdrant!")
except Exception as e:
st.error(f"Failed to connect to Qdrant: {str(e)}")
st.divider()
if all([st.session_state.openai_api_key, st.session_state.vector_db]):
st.header("📄 Document Upload")
uploaded_file = st.file_uploader("Upload Legal Document", type=['pdf'])
if uploaded_file:
# Check if this file has already been processed
if uploaded_file.name not in st.session_state.processed_files:
with st.spinner("Processing document..."):
try:
# Process the document and get the knowledge base
knowledge_base = process_document(uploaded_file, st.session_state.vector_db)
if knowledge_base:
st.session_state.knowledge_base = knowledge_base
# Add the file to processed files
st.session_state.processed_files.add(uploaded_file.name)
# Initialize agents
legal_researcher = Agent(
name="Legal Researcher",
role="Legal research specialist",
model=OpenAIChat(id="gpt-5"),
tools=[DuckDuckGoTools()],
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Find and cite relevant legal cases and precedents",
"Provide detailed research summaries with sources",
"Reference specific sections from the uploaded document",
"Always search the knowledge base for relevant information"
],
debug_mode=True,
markdown=True
)
contract_analyst = Agent(
name="Contract Analyst",
role="Contract analysis specialist",
model=OpenAIChat(id="gpt-5"),
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Review contracts thoroughly",
"Identify key terms and potential issues",
"Reference specific clauses from the document"
],
markdown=True
)
legal_strategist = Agent(
name="Legal Strategist",
role="Legal strategy specialist",
model=OpenAIChat(id="gpt-5"),
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Develop comprehensive legal strategies",
"Provide actionable recommendations",
"Consider both risks and opportunities"
],
markdown=True
)
# Legal Agent Team
st.session_state.legal_team = Team(
name="Legal Team Lead",
model=OpenAIChat(id="gpt-5"),
members=[legal_researcher, contract_analyst, legal_strategist],
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Coordinate analysis between team members",
"Provide comprehensive responses",
"Ensure all recommendations are properly sourced",
"Reference specific parts of the uploaded document",
"Always search the knowledge base before delegating tasks"
],
debug_mode=True,
markdown=True
)
st.success("✅ Document processed and team initialized!")
except Exception as e:
st.error(f"Error processing document: {str(e)}")
else:
# File already processed, just show a message
st.success("✅ Document already processed and team ready!")
st.divider()
st.header("🔍 Analysis Options")
analysis_type = st.selectbox(
"Select Analysis Type",
[
"Contract Review",
"Legal Research",
"Risk Assessment",
"Compliance Check",
"Custom Query"
]
)
else:
st.warning("Please configure all API credentials to proceed")
# Main content area
if not all([st.session_state.openai_api_key, st.session_state.vector_db]):
st.info("👈 Please configure your API credentials in the sidebar to begin")
elif not uploaded_file:
st.info("👈 Please upload a legal document to begin analysis")
elif st.session_state.legal_team:
# Create a dictionary for analysis type icons
analysis_icons = {
"Contract Review": "📑",
"Legal Research": "🔍",
"Risk Assessment": "⚠️",
"Compliance Check": "✅",
"Custom Query": "💭"
}
# Dynamic header with icon
st.header(f"{analysis_icons[analysis_type]} {analysis_type} Analysis")
analysis_configs = {
"Contract Review": {
"query": "Review this contract and identify key terms, obligations, and potential issues.",
"agents": ["Contract Analyst"],
"description": "Detailed contract analysis focusing on terms and obligations"
},
"Legal Research": {
"query": "Research relevant cases and precedents related to this document.",
"agents": ["Legal Researcher"],
"description": "Research on relevant legal cases and precedents"
},
"Risk Assessment": {
"query": "Analyze potential legal risks and liabilities in this document.",
"agents": ["Contract Analyst", "Legal Strategist"],
"description": "Combined risk analysis and strategic assessment"
},
"Compliance Check": {
"query": "Check this document for regulatory compliance issues.",
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Comprehensive compliance analysis"
},
"Custom Query": {
"query": None,
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Custom analysis using all available agents"
}
}
st.info(f"📋 {analysis_configs[analysis_type]['description']}")
st.write(f"🤖 Active Legal AI Agents: {', '.join(analysis_configs[analysis_type]['agents'])}") #dictionary!!
# Replace the existing user_query section with this:
if analysis_type == "Custom Query":
user_query = st.text_area(
"Enter your specific query:",
help="Add any specific questions or points you want to analyze"
)
else:
user_query = None # Set to None for non-custom queries
if st.button("Analyze"):
if analysis_type == "Custom Query" and not user_query:
st.warning("Please enter a query")
else:
with st.spinner("Analyzing document..."):
try:
# Ensure OpenAI API key is set
os.environ['OPENAI_API_KEY'] = st.session_state.openai_api_key
# Combine predefined and user queries
if analysis_type != "Custom Query":
combined_query = f"""
Using the uploaded document as reference:
Primary Analysis Task: {analysis_configs[analysis_type]['query']}
Focus Areas: {', '.join(analysis_configs[analysis_type]['agents'])}
Please search the knowledge base and provide specific references from the document.
"""
else:
combined_query = f"""
Using the uploaded document as reference:
{user_query}
Please search the knowledge base and provide specific references from the document.
Focus Areas: {', '.join(analysis_configs[analysis_type]['agents'])}
"""
response: RunOutput = st.session_state.legal_team.run(combined_query)
# Display results in tabs
tabs = st.tabs(["Analysis", "Key Points", "Recommendations"])
with tabs[0]:
st.markdown("### Detailed Analysis")
if response.content:
st.markdown(response.content)
else:
for message in response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
with tabs[1]:
st.markdown("### Key Points")
key_points_response: RunOutput = st.session_state.legal_team.run(
f"""Based on this previous analysis:
{response.content}
Please summarize the key points in bullet points.
Focus on insights from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
)
if key_points_response.content:
st.markdown(key_points_response.content)
else:
for message in key_points_response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
with tabs[2]:
st.markdown("### Recommendations")
recommendations_response: RunOutput = st.session_state.legal_team.run(
f"""Based on this previous analysis:
{response.content}
What are your key recommendations based on the analysis, the best course of action?
Provide specific recommendations from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
)
if recommendations_response.content:
st.markdown(recommendations_response.content)
else:
for message in recommendations_response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
else:
st.info("Please upload a legal document to begin analysis")
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/agent_teams/ai_legal_agent_team/local_ai_legal_agent_team/local_legal_agent.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_legal_agent_team/local_ai_legal_agent_team/local_legal_agent.py | import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.team import Team
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.qdrant import Qdrant
from agno.models.ollama import Ollama
from agno.knowledge.embedder.ollama import OllamaEmbedder
import tempfile
import os
def init_session_state():
if 'vector_db' not in st.session_state:
st.session_state.vector_db = None
if 'legal_team' not in st.session_state:
st.session_state.legal_team = None
if 'knowledge_base' not in st.session_state:
st.session_state.knowledge_base = None
def init_qdrant():
"""Initialize local Qdrant vector database"""
return Qdrant(
collection="legal_knowledge",
url="http://localhost:6333",
embedder=OllamaEmbedder(model="openhermes")
)
def process_document(uploaded_file, vector_db: Qdrant):
"""Process document using local resources"""
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, uploaded_file.name)
with open(temp_file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
try:
st.write("Processing document...")
# Create knowledge base with local embedder
knowledge_base = Knowledge(
vector_db=vector_db
)
st.write("Loading knowledge base...")
knowledge_base.add_content(path=temp_file_path)
st.write("Knowledge base ready!")
return knowledge_base
except Exception as e:
raise Exception(f"Error processing document: {str(e)}")
def main():
st.set_page_config(page_title="Local Legal Document Analyzer", layout="wide")
init_session_state()
st.title("Local AI Legal Agent Team")
# Initialize local Qdrant
if not st.session_state.vector_db:
try:
st.session_state.vector_db = init_qdrant()
st.success("Connected to local Qdrant!")
except Exception as e:
st.error(f"Failed to connect to Qdrant: {str(e)}")
return
# Document upload section
st.header("📄 Document Upload")
uploaded_file = st.file_uploader("Upload Legal Document", type=['pdf'])
if uploaded_file:
with st.spinner("Processing document..."):
try:
knowledge_base = process_document(uploaded_file, st.session_state.vector_db)
st.session_state.knowledge_base = knowledge_base
# Initialize agents with Llama model
legal_researcher = Agent(
name="Legal Researcher",
role="Legal research specialist",
model=Ollama(id="llama3.1:8b"),
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Find and cite relevant legal cases and precedents",
"Provide detailed research summaries with sources",
"Reference specific sections from the uploaded document"
],
markdown=True
)
contract_analyst = Agent(
name="Contract Analyst",
role="Contract analysis specialist",
model=Ollama(id="llama3.1:8b"),
knowledge=knowledge_base,
search_knowledge=True,
instructions=[
"Review contracts thoroughly",
"Identify key terms and potential issues",
"Reference specific clauses from the document"
],
markdown=True
)
legal_strategist = Agent(
name="Legal Strategist",
role="Legal strategy specialist",
model=Ollama(id="llama3.1:8b"),
knowledge=knowledge_base,
search_knowledge=True,
instructions=[
"Develop comprehensive legal strategies",
"Provide actionable recommendations",
"Consider both risks and opportunities"
],
markdown=True
)
# Legal Agent Team
st.session_state.legal_team = Team(
name="Legal Team Lead",
model=Ollama(id="llama3.1:8b"),
members=[legal_researcher, contract_analyst, legal_strategist],
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Coordinate analysis between team members",
"Provide comprehensive responses",
"Ensure all recommendations are properly sourced",
"Reference specific parts of the uploaded document"
],
markdown=True
)
st.success("✅ Document processed and team initialized!")
except Exception as e:
st.error(f"Error processing document: {str(e)}")
st.divider()
st.header("🔍 Analysis Options")
analysis_type = st.selectbox(
"Select Analysis Type",
[
"Contract Review",
"Legal Research",
"Risk Assessment",
"Compliance Check",
"Custom Query"
]
)
# Main content area
if not st.session_state.vector_db:
st.info("👈 Waiting for Qdrant connection...")
elif not uploaded_file:
st.info("👈 Please upload a legal document to begin analysis")
elif st.session_state.legal_team:
st.header("Document Analysis")
analysis_configs = {
"Contract Review": {
"query": "Review this contract and identify key terms, obligations, and potential issues.",
"agents": ["Contract Analyst"],
"description": "Detailed contract analysis focusing on terms and obligations"
},
"Legal Research": {
"query": "Research relevant cases and precedents related to this document.",
"agents": ["Legal Researcher"],
"description": "Research on relevant legal cases and precedents"
},
"Risk Assessment": {
"query": "Analyze potential legal risks and liabilities in this document.",
"agents": ["Contract Analyst", "Legal Strategist"],
"description": "Combined risk analysis and strategic assessment"
},
"Compliance Check": {
"query": "Check this document for regulatory compliance issues.",
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Comprehensive compliance analysis"
},
"Custom Query": {
"query": None,
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Custom analysis using all available agents"
}
}
st.info(f"📋 {analysis_configs[analysis_type]['description']}")
st.write(f"🤖 Active Agents: {', '.join(analysis_configs[analysis_type]['agents'])}")
user_query = st.text_area(
"Enter your specific query:",
help="Add any specific questions or points you want to analyze"
)
if st.button("Analyze"):
if user_query or analysis_type != "Custom Query":
with st.spinner("Analyzing document..."):
try:
# Combine predefined and user queries
if analysis_type != "Custom Query":
combined_query = f"""
Using the uploaded document as reference:
Primary Analysis Task: {analysis_configs[analysis_type]['query']}
Additional User Query: {user_query if user_query else 'None'}
Focus Areas: {', '.join(analysis_configs[analysis_type]['agents'])}
Please search the knowledge base and provide specific references from the document.
"""
else:
combined_query = user_query
response: RunOutput = st.session_state.legal_team.run(combined_query)
# Display results in tabs
tabs = st.tabs(["Analysis", "Key Points", "Recommendations"])
with tabs[0]:
st.markdown("### Detailed Analysis")
if response.content:
st.markdown(response.content)
else:
for message in response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
with tabs[1]:
st.markdown("### Key Points")
key_points_response: RunOutput = st.session_state.legal_team.run(
f"""Based on this previous analysis:
{response.content}
Please summarize the key points in bullet points.
Focus on insights from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
)
if key_points_response.content:
st.markdown(key_points_response.content)
else:
for message in key_points_response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
with tabs[2]:
st.markdown("### Recommendations")
recommendations_response: RunOutput = st.session_state.legal_team.run(
f"""Based on this previous analysis:
{response.content}
What are your key recommendations based on the analysis, the best course of action?
Provide specific recommendations from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
)
if recommendations_response.content:
st.markdown(recommendations_response.content)
else:
for message in recommendations_response.messages:
if message.role == 'assistant' and message.content:
st.markdown(message.content)
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
else:
st.warning("Please enter a query or select an analysis type")
else:
st.info("Please upload a legal document to begin analysis")
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/agent_teams/ai_services_agency/agency.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_services_agency/agency.py | from typing import List, Literal, Dict, Optional
from agency_swarm import Agent, Agency, set_openai_key, BaseTool
from pydantic import Field, BaseModel
import streamlit as st
class AnalyzeProjectRequirements(BaseTool):
project_name: str = Field(..., description="Name of the project")
project_description: str = Field(..., description="Project description and goals")
project_type: Literal["Web Application", "Mobile App", "API Development",
"Data Analytics", "AI/ML Solution", "Other"] = Field(...,
description="Type of project")
budget_range: Literal["$10k-$25k", "$25k-$50k", "$50k-$100k", "$100k+"] = Field(...,
description="Budget range for the project")
class ToolConfig:
name = "analyze_project"
description = "Analyzes project requirements and feasibility"
one_call_at_a_time = True
def run(self) -> str:
"""Analyzes project and stores results in shared state"""
if self._shared_state.get("project_analysis", None) is not None:
raise ValueError("Project analysis already exists. Please proceed with technical specification.")
analysis = {
"name": self.project_name,
"type": self.project_type,
"complexity": "high",
"timeline": "6 months",
"budget_feasibility": "within range",
"requirements": ["Scalable architecture", "Security", "API integration"]
}
self._shared_state.set("project_analysis", analysis)
return "Project analysis completed. Please proceed with technical specification."
class CreateTechnicalSpecification(BaseTool):
architecture_type: Literal["monolithic", "microservices", "serverless", "hybrid"] = Field(
...,
description="Proposed architecture type"
)
core_technologies: str = Field(
...,
description="Comma-separated list of main technologies and frameworks"
)
scalability_requirements: Literal["high", "medium", "low"] = Field(
...,
description="Scalability needs"
)
class ToolConfig:
name = "create_technical_spec"
description = "Creates technical specifications based on project analysis"
one_call_at_a_time = True
def run(self) -> str:
"""Creates technical specification based on analysis"""
project_analysis = self._shared_state.get("project_analysis", None)
if project_analysis is None:
raise ValueError("Please analyze project requirements first using AnalyzeProjectRequirements tool.")
spec = {
"project_name": project_analysis["name"],
"architecture": self.architecture_type,
"technologies": self.core_technologies.split(","),
"scalability": self.scalability_requirements
}
self._shared_state.set("technical_specification", spec)
return f"Technical specification created for {project_analysis['name']}."
def init_session_state() -> None:
"""Initialize session state variables"""
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'api_key' not in st.session_state:
st.session_state.api_key = None
def main() -> None:
st.set_page_config(page_title="AI Services Agency", layout="wide")
init_session_state()
st.title("🚀 AI Services Agency")
# API Configuration
with st.sidebar:
st.header("🔑 API Configuration")
openai_api_key = st.text_input(
"OpenAI API Key",
type="password",
help="Enter your OpenAI API key to continue"
)
if openai_api_key:
st.session_state.api_key = openai_api_key
st.success("API Key accepted!")
else:
st.warning("⚠️ Please enter your OpenAI API Key to proceed")
st.markdown("[Get your API key here](https://platform.openai.com/api-keys)")
return
# Initialize agents with the provided API key
set_openai_key(st.session_state.api_key)
api_headers = {"Authorization": f"Bearer {st.session_state.api_key}"}
# Project Input Form
with st.form("project_form"):
st.subheader("Project Details")
project_name = st.text_input("Project Name")
project_description = st.text_area(
"Project Description",
help="Describe the project, its goals, and any specific requirements"
)
col1, col2 = st.columns(2)
with col1:
project_type = st.selectbox(
"Project Type",
["Web Application", "Mobile App", "API Development",
"Data Analytics", "AI/ML Solution", "Other"]
)
timeline = st.selectbox(
"Expected Timeline",
["1-2 months", "3-4 months", "5-6 months", "6+ months"]
)
with col2:
budget_range = st.selectbox(
"Budget Range",
["$10k-$25k", "$25k-$50k", "$50k-$100k", "$100k+"]
)
priority = st.selectbox(
"Project Priority",
["High", "Medium", "Low"]
)
tech_requirements = st.text_area(
"Technical Requirements (optional)",
help="Any specific technical requirements or preferences"
)
special_considerations = st.text_area(
"Special Considerations (optional)",
help="Any additional information or special requirements"
)
submitted = st.form_submit_button("Analyze Project")
if submitted and project_name and project_description:
try:
# Set OpenAI key
set_openai_key(st.session_state.api_key)
# Create agents
ceo = Agent(
name="Project Director",
description="You are a CEO of multiple companies in the past and have a lot of experience in evaluating projects and making strategic decisions.",
instructions="""
You are an experienced CEO who evaluates projects. Follow these steps strictly:
1. FIRST, use the AnalyzeProjectRequirements tool with:
- project_name: The name from the project details
- project_description: The full project description
- project_type: The type of project (Web Application, Mobile App, etc)
- budget_range: The specified budget range
2. WAIT for the analysis to complete before proceeding.
3. Review the analysis results and provide strategic recommendations.
""",
tools=[AnalyzeProjectRequirements],
api_headers=api_headers,
temperature=0.7,
max_prompt_tokens=25000
)
cto = Agent(
name="Technical Architect",
description="Senior technical architect with deep expertise in system design.",
instructions="""
You are a technical architect. Follow these steps strictly:
1. WAIT for the project analysis to be completed by the CEO.
2. Use the CreateTechnicalSpecification tool with:
- architecture_type: Choose from monolithic/microservices/serverless/hybrid
- core_technologies: List main technologies as comma-separated values
- scalability_requirements: Choose high/medium/low based on project needs
3. Review the technical specification and provide additional recommendations.
""",
tools=[CreateTechnicalSpecification],
api_headers=api_headers,
temperature=0.5,
max_prompt_tokens=25000
)
product_manager = Agent(
name="Product Manager",
description="Experienced product manager focused on delivery excellence.",
instructions="""
- Manage project scope and timeline giving the roadmap of the project
- Define product requirements and you should give potential products and features that can be built for the startup
""",
api_headers=api_headers,
temperature=0.4,
max_prompt_tokens=25000
)
developer = Agent(
name="Lead Developer",
description="Senior developer with full-stack expertise.",
instructions="""
- Plan technical implementation
- Provide effort estimates
- Review technical feasibility
""",
api_headers=api_headers,
temperature=0.3,
max_prompt_tokens=25000
)
client_manager = Agent(
name="Client Success Manager",
description="Experienced client manager focused on project delivery.",
instructions="""
- Ensure client satisfaction
- Manage expectations
- Handle feedback
""",
api_headers=api_headers,
temperature=0.6,
max_prompt_tokens=25000
)
# Create agency
agency = Agency(
[
ceo, cto, product_manager, developer, client_manager,
[ceo, cto],
[ceo, product_manager],
[ceo, developer],
[ceo, client_manager],
[cto, developer],
[product_manager, developer],
[product_manager, client_manager]
],
async_mode='threading',
shared_files='shared_files'
)
# Prepare project info
project_info = {
"name": project_name,
"description": project_description,
"type": project_type,
"timeline": timeline,
"budget": budget_range,
"priority": priority,
"technical_requirements": tech_requirements,
"special_considerations": special_considerations
}
st.session_state.messages.append({"role": "user", "content": str(project_info)})
# Create tabs and run analysis
with st.spinner("AI Services Agency is analyzing your project..."):
try:
# Get analysis from each agent using agency.get_completion()
ceo_response = agency.get_completion(
message=f"""Analyze this project using the AnalyzeProjectRequirements tool:
Project Name: {project_name}
Project Description: {project_description}
Project Type: {project_type}
Budget Range: {budget_range}
Use these exact values with the tool and wait for the analysis results.""",
recipient_agent=ceo
)
cto_response = agency.get_completion(
message=f"""Review the project analysis and create technical specifications using the CreateTechnicalSpecification tool.
Choose the most appropriate:
- architecture_type (monolithic/microservices/serverless/hybrid)
- core_technologies (comma-separated list)
- scalability_requirements (high/medium/low)
Base your choices on the project requirements and analysis.""",
recipient_agent=cto
)
pm_response = agency.get_completion(
message=f"Analyze project management aspects: {str(project_info)}",
recipient_agent=product_manager,
additional_instructions="Focus on product-market fit and roadmap development, and coordinate with technical and marketing teams."
)
developer_response = agency.get_completion(
message=f"Analyze technical implementation based on CTO's specifications: {str(project_info)}",
recipient_agent=developer,
additional_instructions="Provide technical implementation details, optimal tech stack you would be using including the costs of cloud services (if any) and feasibility feedback, and coordinate with product manager and CTO to build the required products for the startup."
)
client_response = agency.get_completion(
message=f"Analyze client success aspects: {str(project_info)}",
recipient_agent=client_manager,
additional_instructions="Provide detailed go-to-market strategy and customer acquisition plan, and coordinate with product manager."
)
# Create tabs for different analyses
tabs = st.tabs([
"CEO's Project Analysis",
"CTO's Technical Specification",
"Product Manager's Plan",
"Developer's Implementation",
"Client Success Strategy"
])
with tabs[0]:
st.markdown("## CEO's Strategic Analysis")
st.markdown(ceo_response)
st.session_state.messages.append({"role": "assistant", "content": ceo_response})
with tabs[1]:
st.markdown("## CTO's Technical Specification")
st.markdown(cto_response)
st.session_state.messages.append({"role": "assistant", "content": cto_response})
with tabs[2]:
st.markdown("## Product Manager's Plan")
st.markdown(pm_response)
st.session_state.messages.append({"role": "assistant", "content": pm_response})
with tabs[3]:
st.markdown("## Lead Developer's Development Plan")
st.markdown(developer_response)
st.session_state.messages.append({"role": "assistant", "content": developer_response})
with tabs[4]:
st.markdown("## Client Success Strategy")
st.markdown(client_response)
st.session_state.messages.append({"role": "assistant", "content": client_response})
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
st.error("Please check your inputs and API key and try again.")
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
st.error("Please check your API key and try again.")
# Add history management in sidebar
with st.sidebar:
st.subheader("Options")
if st.checkbox("Show Analysis History"):
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if st.button("Clear History"):
st.session_state.messages = []
st.rerun()
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/agent_teams/multimodal_design_agent_team/design_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_design_agent_team/design_agent_team.py | from agno.agent import Agent
from agno.run.agent import RunOutput
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]:
try:
model = Gemini(id="gemini-2.0-flash-exp", api_key=api_key)
vision_agent = Agent(
model=model,
instructions=[
"You are a visual analysis expert that:",
"1. Identifies design elements, patterns, and visual hierarchy",
"2. Analyzes color schemes, typography, and layouts",
"3. Detects UI components and their relationships",
"4. Evaluates visual consistency and branding",
"Be specific and technical in your analysis"
],
markdown=True
)
ux_agent = Agent(
model=model,
instructions=[
"You are a UX analysis expert that:",
"1. Evaluates user flows and interaction patterns",
"2. Identifies usability issues and opportunities",
"3. Suggests UX improvements based on best practices",
"4. Analyzes accessibility and inclusive design",
"Focus on user-centric insights and practical improvements"
],
markdown=True
)
market_agent = Agent(
model=model,
tools=[DuckDuckGoTools()],
instructions=[
"You are a market research expert that:",
"1. Identifies market trends and competitor patterns",
"2. Analyzes similar products and features",
"3. Suggests market positioning and opportunities",
"4. Provides industry-specific insights",
"Focus on actionable market intelligence"
],
markdown=True
)
return vision_agent, ux_agent, market_agent
except Exception as e:
st.error(f"Error initializing agents: {str(e)}")
return None, None, None
# Set page config and UI elements
st.set_page_config(page_title="Multimodal AI Design Agent Team", 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)
""")
st.title("Multimodal AI Design Agent Team")
if st.session_state.api_key_input:
vision_agent, ux_agent, market_agent = initialize_agents(st.session_state.api_key_input)
if all([vision_agent, ux_agent, market_agent]):
# File Upload Section
st.header("📤 Upload Content")
col1, space, col2 = st.columns([1, 0.1, 1])
with col1:
design_files = st.file_uploader(
"Upload UI/UX Designs",
type=["jpg", "jpeg", "png"],
accept_multiple_files=True,
key="designs"
)
if design_files:
for file in design_files:
st.image(file, caption=file.name, use_container_width=True)
with col2:
competitor_files = st.file_uploader(
"Upload Competitor Designs (Optional)",
type=["jpg", "jpeg", "png"],
accept_multiple_files=True,
key="competitors"
)
if competitor_files:
for file in competitor_files:
st.image(file, caption=f"Competitor: {file.name}", use_container_width=True)
# Analysis Configuration
st.header("🎯 Analysis Configuration")
analysis_types = st.multiselect(
"Select Analysis Types",
["Visual Design", "User Experience", "Market Analysis"],
default=["Visual Design"]
)
specific_elements = st.multiselect(
"Focus Areas",
["Color Scheme", "Typography", "Layout", "Navigation",
"Interactions", "Accessibility", "Branding", "Market Fit"]
)
context = st.text_area(
"Additional Context",
placeholder="Describe your product, target audience, or specific concerns..."
)
# Analysis Process
if st.button("🚀 Run Analysis", type="primary"):
if design_files:
try:
st.header("📊 Analysis Results")
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
design_images = process_images(design_files)
competitor_images = process_images(competitor_files) if competitor_files else []
all_images = design_images + competitor_images
# Visual Design Analysis
if "Visual Design" in analysis_types and design_files:
with st.spinner("🎨 Analyzing visual design..."):
if all_images:
vision_prompt = f"""
Analyze these designs focusing on: {', '.join(specific_elements)}
Additional context: {context}
Provide specific insights about visual design elements.
Please format your response with clear headers and bullet points.
Focus on concrete observations and actionable insights.
"""
response: RunOutput = vision_agent.run(
message=vision_prompt,
images=all_images
)
st.subheader("🎨 Visual Design Analysis")
st.markdown(response.content)
# UX Analysis
if "User Experience" in analysis_types:
with st.spinner("🔄 Analyzing user experience..."):
if all_images:
ux_prompt = f"""
Evaluate the user experience considering: {', '.join(specific_elements)}
Additional context: {context}
Focus on user flows, interactions, and accessibility.
Please format your response with clear headers and bullet points.
Focus on concrete observations and actionable improvements.
"""
response: RunOutput = ux_agent.run(
message=ux_prompt,
images=all_images
)
st.subheader("🔄 UX Analysis")
st.markdown(response.content)
# Market Analysis
if "Market Analysis" in analysis_types:
with st.spinner("📊 Conducting market analysis..."):
market_prompt = f"""
Analyze market positioning and trends based on these designs.
Context: {context}
Compare with competitor designs if provided.
Suggest market opportunities and positioning.
Please format your response with clear headers and bullet points.
Focus on concrete market insights and actionable recommendations.
"""
response: RunOutput = market_agent.run(
message=market_prompt,
images=all_images
)
st.subheader("📊 Market Analysis")
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 upload at least one design to analyze.")
else:
st.info("👈 Please enter your API key in the sidebar to get started")
else:
st.info("👈 Please enter your API key in the sidebar to get started")
# Footer with usage tips
st.markdown("---")
st.markdown("""
<div style='text-align: center'>
<h4>Tips for Best Results</h4>
<p>
• Upload clear, high-resolution images<br>
• Include multiple views/screens for better context<br>
• Add competitor designs for comparative analysis<br>
• Provide specific context about your target audience
</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/advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_uiux_feedback_agent_team/tools.py | advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_uiux_feedback_agent_team/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
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}"
async def load_landing_page_image(tool_context: ToolContext, filename: str):
"""Load a landing page image artifact by filename."""
try:
loaded_part = await tool_context.load_artifact(filename)
if loaded_part:
logger.info(f"Successfully loaded landing page image: {filename}")
return loaded_part
else:
logger.warning(f"Landing page image not found: {filename}")
return None
except Exception as e:
logger.error(f"Error loading landing page image {filename}: {e}")
return None
# ============================================================================
# Pydantic Input Models
# ============================================================================
class EditLandingPageInput(BaseModel):
artifact_filename: str = Field(..., description="The filename of the landing page artifact to edit.")
prompt: str = Field(..., description="Detailed description of UI/UX improvements to apply.")
asset_name: str = Field(default=None, description="Optional: specify asset name for the new version.")
class GenerateImprovedLandingPageInput(BaseModel):
prompt: str = Field(..., description="A detailed description of the improved landing page based on feedback.")
aspect_ratio: str = Field(default="16:9", description="The desired aspect ratio. Default is 16:9.")
asset_name: str = Field(default="landing_page_improved", description="Base name for the improved design.")
reference_image: str = Field(default=None, description="Optional: filename of the original landing page to use as reference.")
# ============================================================================
# NOTE: Image Analysis is handled directly by agents with vision capabilities
# Agents with gemini-2.5-flash can see and analyze uploaded images automatically
# No separate image analysis tool is needed
# ============================================================================
# ============================================================================
# Image Editing Tool
# ============================================================================
async def edit_landing_page_image(tool_context: ToolContext, inputs: EditLandingPageInput) -> str:
"""
Edits a landing page image by applying UI/UX improvements.
This tool uses Gemini 2.5 Flash's image generation capabilities to create
an improved version of the landing page based on feedback.
"""
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 landing page image editing")
try:
client = genai.Client()
inputs = EditLandingPageInput(**inputs)
# Load the existing landing page image
logger.info(f"Loading artifact: {inputs.artifact_filename}")
try:
loaded_image_part = await tool_context.load_artifact(inputs.artifact_filename)
if not loaded_image_part:
return f"❌ Could not find landing page artifact: {inputs.artifact_filename}"
except Exception as e:
logger.error(f"Error loading artifact: {e}")
return f"Error loading landing page artifact: {e}"
model = "gemini-2.5-flash-image"
# Build edit prompt with UI/UX best practices
enhanced_prompt = f"""
{inputs.prompt}
**Apply these UI/UX best practices while editing:**
- Maintain visual hierarchy (size, color, spacing)
- Ensure sufficient whitespace for breathing room
- Use consistent alignment and grid system
- Make CTAs prominent with contrasting colors
- Improve readability (font size, line height, contrast)
- Follow modern web design principles
- Keep the overall brand aesthetic
Make the improvements look natural and professional.
"""
# Build content parts
content_parts = [loaded_image_part, types.Part.from_text(text=enhanced_prompt)]
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:
base_name = inputs.artifact_filename.split('_v')[0] if '_v' in inputs.artifact_filename else "landing_page"
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 landing page 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
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_edited_landing_page"] = edited_artifact_filename
tool_context.state["current_asset_name"] = asset_name
logger.info(f"Saved edited landing page as artifact '{edited_artifact_filename}' (version {version})")
return f"✅ **Landing page edited successfully!**\n\nSaved as: **{edited_artifact_filename}** (version {version} of {asset_name})\n\nThe landing page has been improved with the UI/UX enhancements."
except Exception as e:
logger.error(f"Error saving edited artifact: {e}")
return f"Error saving edited landing page as artifact: {e}"
else:
if hasattr(chunk, 'text') and chunk.text:
logger.info(f"Model response: {chunk.text}")
return "No edited landing page was generated. Please try again."
except Exception as e:
logger.error(f"Error in edit_landing_page_image: {e}")
return f"An error occurred while editing the landing page: {e}"
# ============================================================================
# Generate Improved Landing Page Tool
# ============================================================================
async def generate_improved_landing_page(tool_context: ToolContext, inputs: GenerateImprovedLandingPageInput) -> str:
"""
Generates an improved landing page based on the analysis and feedback.
This tool creates a new landing page design incorporating all the recommended
UI/UX improvements. Can work with or without a reference image.
"""
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 improved landing page generation")
try:
client = genai.Client()
inputs = GenerateImprovedLandingPageInput(**inputs)
# Note: Reference images from the conversation are automatically available to agents
# This parameter is kept for backwards compatibility with saved artifacts
reference_part = None
if inputs.reference_image:
try:
reference_part = await load_landing_page_image(tool_context, inputs.reference_image)
if reference_part:
logger.info(f"Using reference image artifact: {inputs.reference_image}")
except Exception as e:
logger.warning(f"Could not load reference image, proceeding without it: {e}")
# Get the analysis from state to incorporate feedback
latest_analysis = tool_context.state.get("latest_analysis", "")
# Build enhanced prompt
enhancement_prompt = f"""
Create a professional landing page design that incorporates these improvements:
{inputs.prompt}
**Previous Analysis Insights:**
{latest_analysis[:500] if latest_analysis else "No previous analysis available"}
**Design Requirements:**
- Modern, clean aesthetic
- Clear visual hierarchy
- Prominent, well-designed CTAs
- Proper whitespace and breathing room
- Professional typography with clear hierarchy
- Accessible color contrast (WCAG AA)
- Mobile-first responsive considerations
- Follow the latest UI/UX best practices
- High-quality, photorealistic rendering
Aspect ratio: {inputs.aspect_ratio}
Create a professional UI/UX design that would be magazine-quality.
"""
# Prepare content parts
content_parts = [types.Part.from_text(text=enhancement_prompt)]
if reference_part:
content_parts.append(reference_part)
# Generate enhanced prompt first
rewritten_prompt_response = client.models.generate_content(
model="gemini-2.5-flash",
contents=enhancement_prompt
)
rewritten_prompt = rewritten_prompt_response.text
logger.info(f"Enhanced prompt: {rewritten_prompt}")
model = "gemini-2.5-flash-image"
contents = [
types.Content(
role="user",
parts=[types.Part.from_text(text=rewritten_prompt)] + ([reference_part] if reference_part else []),
),
]
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 improved landing page with 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
image_part = types.Part(inline_data=inline_data)
try:
version = await tool_context.save_artifact(
filename=artifact_filename,
artifact=image_part
)
update_asset_version(tool_context, inputs.asset_name, version, artifact_filename)
tool_context.state["last_generated_landing_page"] = artifact_filename
tool_context.state["current_asset_name"] = inputs.asset_name
logger.info(f"Saved improved landing page as artifact '{artifact_filename}' (version {version})")
return f"✅ **Improved landing page generated successfully!**\n\nSaved as: **{artifact_filename}** (version {version} of {inputs.asset_name})\n\nThis design incorporates all the recommended UI/UX improvements."
except Exception as e:
logger.error(f"Error saving artifact: {e}")
return f"Error saving improved landing page as artifact: {e}"
else:
if hasattr(chunk, 'text') and chunk.text:
logger.info(f"Model response: {chunk.text}")
return "No improved landing page was generated. Please try again with a more detailed prompt."
except Exception as e:
logger.error(f"Error in generate_improved_landing_page: {e}")
return f"An error occurred while generating the improved landing page: {e}"
# ============================================================================
# Note: No utility tools needed - agents handle everything directly
# ============================================================================
| 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/agent_teams/multimodal_uiux_feedback_agent_team/__init__.py | advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_uiux_feedback_agent_team/__init__.py | """AI UI/UX Feedback Team
A multi-agent system for analyzing landing pages and providing actionable feedback.
"""
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/agent_teams/multimodal_uiux_feedback_agent_team/agent.py | advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_uiux_feedback_agent_team/agent.py | 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 (
edit_landing_page_image,
generate_improved_landing_page,
)
# ============================================================================
# Helper Tool Agent (wraps google_search)
# ============================================================================
search_agent = LlmAgent(
name="SearchAgent",
model="gemini-2.5-flash",
description="Searches for UI/UX best practices, design trends, and accessibility guidelines",
instruction="Use google_search to find current UI/UX trends, design principles, WCAG guidelines, and industry best practices. Be concise and cite authoritative sources.",
tools=[google_search],
)
# ============================================================================
# Specialist Agent 1: Info Agent (for general inquiries)
# ============================================================================
info_agent = LlmAgent(
name="InfoAgent",
model="gemini-2.5-flash",
description="Handles general questions and provides system information about the UI/UX feedback team",
instruction="""
You are the Info Agent for the AI UI/UX Feedback Team.
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 analyzes landing pages using AI vision
- Mention capabilities: image analysis, constructive feedback, automatic improvements, comprehensive reports
- Ask them to upload a landing page screenshot for analysis
EXAMPLE:
"Hi! I'm part of the AI UI/UX Feedback Team. We analyze landing page designs using advanced AI vision, provide detailed constructive feedback on layout, typography, colors, and CTAs, then automatically generate improved versions with our recommendations applied. Upload a screenshot of your landing page and I'll get our expert team to review it!"
Be enthusiastic about design and helpful!
""",
)
# ============================================================================
# Specialist Agent 2: Design Editor (for iterative refinements)
# ============================================================================
design_editor = LlmAgent(
name="DesignEditor",
model="gemini-2.5-flash",
description="Edits existing landing page designs based on specific feedback or refinement requests",
instruction="""
You refine existing landing page designs based on user feedback.
**TASK**: User wants to modify an existing design (e.g., "make the CTA button larger", "use a different color scheme", "improve the hero section").
**CRITICAL**: Find the most recent design filename from conversation history!
Look for: "Saved as artifact: [filename]" or "landing_page_v1.png" type references.
Use **edit_landing_page_image** tool:
Parameters:
1. artifact_filename: The exact filename of the most recent design
2. prompt: Very specific edit instruction with UI/UX context
3. asset_name: Base name without _vX (e.g., "landing_page_improved")
**Example:**
User: "Make the CTA button more prominent"
Last design: "landing_page_improved_v1.png"
Call: edit_landing_page_image(
artifact_filename="landing_page_improved_v1.png",
prompt="Increase the CTA button size by 20%, use a high-contrast color (vibrant orange #FF6B35) to make it stand out more against the background. Add subtle shadow for depth. Ensure the button text is bold and clearly readable. Keep all other design elements unchanged.",
asset_name="landing_page_improved"
)
Be SPECIFIC in prompts and apply UI/UX best practices:
- Visual hierarchy (size, color, contrast)
- Whitespace and breathing room
- Typography hierarchy
- Color psychology
- Accessibility (WCAG)
After editing, briefly explain the UI/UX rationale for the changes.
""",
tools=[edit_landing_page_image],
)
# ============================================================================
# Specialist Agents 3-5: Full Analysis Pipeline (SequentialAgent)
# ============================================================================
ui_critic = LlmAgent(
name="UICritic",
model="gemini-2.5-flash",
description="Analyzes landing page design and provides comprehensive UI/UX feedback using visual AI",
instruction="""
You are a Senior UI/UX Designer with expertise in conversion optimization and accessibility.
**YOUR ROLE**: Analyze uploaded landing page images and provide expert, actionable feedback.
**IMPORTANT**: You can SEE and ANALYZE uploaded images directly using your vision capabilities.
The images are automatically visible to you in the conversation - no tools needed.
Focus on providing detailed analysis and specific recommendations.
## Analysis Framework
When you see a landing page image, examine it across these dimensions:
### 1. First Impression (1-10 rating)
- Visual appeal and professionalism
- Brand perception and trust signals
- Emotional impact
### 2. Layout & Visual Hierarchy ⭐ HIGH PRIORITY
- Hero section effectiveness (headline, subheadline, imagery)
- F-pattern or Z-pattern adherence
- Element sizing and positioning
- Above-the-fold content quality
- Alignment and grid usage
- Section spacing and flow
### 3. Typography
- Font choices (modern, professional, readable?)
- Heading hierarchy (H1, H2, H3 distinction)
- Body text readability (size 16px+, line height 1.5+, line length)
- Font pairing harmony
- Text contrast with background
### 4. Color Scheme & Contrast
- Brand color consistency
- Color psychology alignment with purpose
- Sufficient contrast for readability (WCAG AA: 4.5:1 for text)
- Color harmony (complementary, analogous, triadic?)
- Emotional response appropriateness
### 5. Call-to-Action (CTA) ⭐ CRITICAL
- CTA visibility and prominence (size, color, placement)
- Action-oriented copy ("Get Started" vs "Submit")
- Button design (contrast, hover states implied)
- Multiple CTAs coordination (primary vs secondary)
- Above-the-fold CTA presence
### 6. Whitespace & Balance
- Adequate breathing room around elements
- Cluttered vs clean sections
- Visual weight distribution
- Margins and padding consistency
### 7. Content Structure
- Information architecture clarity
- Content scanability
- Social proof placement (testimonials, logos, stats)
- Trust elements (security badges, guarantees)
### 8. Mobile Responsiveness Considerations
- Elements that may not translate well to mobile
- Touch target sizes
- Mobile-first design principles
## Output Structure
Provide feedback in this format:
**🎯 OVERALL IMPRESSION**
[Rating and 2-3 sentence summary]
**✅ WHAT WORKS WELL**
[List 3-5 strengths]
**⚠️ CRITICAL ISSUES** (High Priority)
1. [Issue with severity and specific location]
2. [Issue with severity and specific location]
3. [Issue with severity and specific location]
**📋 ADDITIONAL IMPROVEMENTS** (Medium/Low Priority)
[4-6 additional suggestions]
**🚀 TOP 3 IMPACT PRIORITIES**
1. [Most impactful change]
2. [Second most impactful change]
3. [Third most impactful change]
**📊 DETAILED SCORES**
- Layout & Hierarchy: X/10
- Typography: X/10
- Color & Contrast: X/10
- CTA Effectiveness: X/10
- Whitespace & Balance: X/10
**IMPORTANT**: At the end of your analysis, output a structured summary:
```
ANALYSIS COMPLETE
Images Analyzed: [Yes/No - describe what you see]
Key Issues Identified: [number]
Critical Priority: [main issue]
Target Audience: [detected or general]
```
Be DETAILED and SPECIFIC in your analysis - this drives the quality of the improvement plan and generated design.
**IF NO IMAGE IS VISIBLE**: Ask the user to upload a landing page screenshot so you can provide analysis.
""",
tools=[AgentTool(search_agent)],
)
design_strategist = LlmAgent(
name="DesignStrategist",
model="gemini-2.5-flash",
description="Creates detailed improvement plan based on UI/UX analysis",
instruction="""
Read from state: latest_analysis, key issues, priorities
You are a Design Strategist who creates actionable improvement plans.
**YOUR TASK**: Based on the UI Critic's analysis, create a SPECIFIC, DETAILED plan for improvements.
## Improvement Plan Structure
### 🎯 Design Strategy Overview
- Primary goal: [conversion optimization/brand awareness/user engagement]
- Target user: [persona]
- Key improvement theme: [modernization/simplification/boldness/etc.]
### 📐 Layout & Structure Improvements
**Changes to make:**
- Hero section: [specific modifications to headline, subheadline, imagery, CTA]
- Visual hierarchy: [size adjustments, reordering, emphasis changes]
- Grid system: [alignment fixes, column structure]
- Whitespace: [specific areas to add/reduce space]
### 🎨 Visual Design Improvements
**Color Palette:**
- Primary: [specific color with hex code and usage]
- Secondary: [specific color with hex code and usage]
- Accent (CTA): [high-contrast color with hex code]
- Background: [specific shade]
- Text colors: [with contrast ratios]
**Typography:**
- Heading font: [font name, size, weight]
- Body font: [font name, size, line height]
- CTA text: [font treatment]
- Hierarchy: [H1: Xpx, H2: Xpx, Body: 16-18px]
### 🎯 CTA Optimization
- Primary CTA: [exact text, color, size, placement]
- Secondary CTA: [if applicable]
- Button design: [shape, padding, shadow, hover effect]
### ♿ Accessibility Enhancements
- Contrast improvements needed: [specific areas]
- Font size increases: [where]
- Alt text considerations
- Focus states for interactive elements
### 📱 Mobile Considerations
- Elements to stack vertically
- Font size adjustments for mobile
- Touch target sizes (minimum 44x44px)
### 🔤 Content Recommendations
- Headline improvements: [more compelling/clearer]
- Subheadline clarity
- CTA copy: [action-oriented language]
- Trust signals to add/improve
**IMPORTANT: At the end, provide:**
```
DESIGN PLAN COMPLETE
Improvement Categories: [Layout, Color, Typography, CTA, Accessibility]
Estimated Impact: [High/Medium/Low]
Implementation Complexity: [Simple/Moderate/Complex]
Ready for visual implementation.
```
Be ULTRA-SPECIFIC with colors (hex codes), sizes (px), and placements. This drives the image generation quality.
""",
tools=[AgentTool(search_agent)],
)
visual_implementer = LlmAgent(
name="VisualImplementer",
model="gemini-2.5-flash",
description="Generates improved landing page design and creates comprehensive report",
instruction="""
Read conversation history to extract:
- UI Critic's detailed analysis
- Design Strategist's improvement plan
- Original landing page image (if visible in conversation)
**IMPORTANT**: You have VISION CAPABILITIES and can see images in the conversation.
If there's an original landing page image visible, use it as inspiration for the improved version.
**YOUR TASK**: Generate an improved landing page implementing ALL recommendations
Use **generate_improved_landing_page** tool with an EXTREMELY DETAILED prompt.
**Build the prompt by incorporating:**
From UI Critic:
- Critical issues to fix
- Top 3 priorities
- What currently works well (preserve these)
From Design Strategist:
- Exact color palette (with hex codes)
- Typography specifications (fonts, sizes, weights)
- Layout structure and hierarchy
- CTA design details
- Whitespace improvements
**Prompt Structure:**
"Professional landing page design with modern UI/UX best practices applied.
**Layout & Hierarchy:**
[Detailed description of hero section, content structure, visual flow]
**Color Palette:**
- Primary: [color name + hex code]
- Secondary: [color name + hex code]
- CTA/Accent: [high-contrast color + hex code]
- Background: [color + hex code]
- Text: [color with contrast ratio]
**Typography:**
- Headlines: [font, size, weight, color] - Clear hierarchy with [X]px for H1
- Body text: [font, 16-18px, line-height 1.6, color] - Highly readable
- CTA text: [font, size, weight] - Action-oriented
**Call-to-Action:**
[Detailed CTA button design: size, color, text, placement, shadow/effects]
**Visual Elements:**
- Hero image/graphic: [description]
- Section images: [description]
- Icons: [style and placement]
- Social proof: [testimonials, logos, stats placement]
**Whitespace & Balance:**
[Specific spacing between sections, margins, padding]
**Accessibility:**
- WCAG AA compliant contrast ratios
- Readable font sizes (16px minimum)
- Clear focus states
**Style:**
- Modern, clean, professional
- [Additional style keywords from analysis]
- High-quality UI design, Dribbble/Behance quality
Camera/Quality: Desktop web design screenshot, 16:9 aspect ratio, professional UI/UX portfolio quality"
Parameters:
- prompt: [your ultra-detailed prompt above]
- aspect_ratio: "16:9"
- asset_name: "landing_page_improved"
- reference_image: [filename of original if available]
**After generating the improved design, provide a brief summary:**
Describe the key improvements in 3-4 sentences:
- What critical issues were addressed
- Main visual/design changes applied
- Expected impact on user experience and conversion
**Example:**
"✅ **Improved Landing Page Generated!**
**Key Improvements Applied:**
- ✨ Enhanced visual hierarchy with larger hero headline (48px) and prominent CTA
- 🎨 Implemented high-contrast color scheme (#FF6B35 accent) with WCAG AA compliance
- 📝 Improved typography with clear heading hierarchy and 18px readable body text
- 🎯 Redesigned CTA button with vibrant accent color and better placement above-the-fold
- 💨 Optimized whitespace for better content flow and readability
The new design addresses all critical issues identified in the analysis and follows modern UI/UX best practices."
""",
tools=[generate_improved_landing_page],
)
# Create the analysis pipeline (runs only when coordinator routes analysis requests here)
analysis_pipeline = SequentialAgent(
name="AnalysisPipeline",
description="Full UI/UX analysis pipeline: Image Analysis → Design Strategy → Visual Implementation",
sub_agents=[
ui_critic,
design_strategist,
visual_implementer,
],
)
# ============================================================================
# Coordinator/Dispatcher (Root Agent)
# ============================================================================
root_agent = LlmAgent(
name="UIUXFeedbackTeam",
model="gemini-2.5-flash",
description="Intelligent coordinator that routes UI/UX feedback requests to the appropriate specialist or analysis pipeline. Supports landing page image analysis!",
instruction="""
You are the Coordinator for the AI UI/UX Feedback Team.
YOUR ROLE: Analyze the user's request and route it to the right specialist using transfer_to_agent.
**IMPORTANT**: You have VISION CAPABILITIES. If you see an image in the conversation, route to AnalysisPipeline immediately.
ROUTING LOGIC:
1. **For general questions/greetings** (NO images present):
→ transfer_to_agent to "InfoAgent"
→ Examples: "hi", "what can you do?", "how does this work?", "what is UI/UX?"
2. **For editing EXISTING designs** (only if a design was already generated):
→ transfer_to_agent to "DesignEditor"
→ Examples: "make the CTA bigger", "change the color scheme", "improve the hero section", "make it more modern"
→ User wants to MODIFY an existing improved design
→ Check: Was an improved design generated earlier in this conversation?
3. **For NEW landing page analysis** (PRIORITY ROUTE):
→ transfer_to_agent to "AnalysisPipeline"
→ Examples: "analyze this landing page", "review my design", "give me feedback"
→ **CRITICAL**: If you SEE an image in the conversation → ALWAYS route here!
→ First-time analysis or new project
→ This runs the full pipeline: UI Critic → Design Strategist → Visual Implementer
CRITICAL: You MUST use transfer_to_agent - don't answer directly!
Decision flow:
- **Image visible in conversation** → IMMEDIATELY transfer to AnalysisPipeline
- Design exists + wants changes → DesignEditor
- No image + asking questions → InfoAgent
Be a smart router - prioritize image analysis!
""",
sub_agents=[
info_agent,
design_editor,
analysis_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/agent_teams/ai_game_design_agent_team/game_design_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_game_design_agent_team/game_design_agent_team.py | import asyncio
import streamlit as st
from autogen import (
SwarmAgent,
SwarmResult,
initiate_swarm_chat,
OpenAIWrapper,
AFTER_WORK,
UPDATE_SYSTEM_MESSAGE
)
# Initialize session state
if 'output' not in st.session_state:
st.session_state.output = {'story': '', 'gameplay': '', 'visuals': '', 'tech': ''}
# Sidebar for API key input
st.sidebar.title("API Key")
api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
# Add guidance in sidebar
st.sidebar.success("""
✨ **Getting Started**
Please provide inputs and features for your dream game! Consider:
- The overall vibe and setting
- Core gameplay elements
- Target audience and platforms
- Visual style preferences
- Technical requirements
The AI agents will collaborate to develop a comprehensive game concept based on your specifications.
""")
# Main app UI
st.title("🎮 AI Game Design Agent Team")
# Add agent information below title
st.info("""
**Meet Your AI Game Design Team:**
🎭 **Story Agent** - Crafts compelling narratives and rich worlds
🎮 **Gameplay Agent** - Creates engaging mechanics and systems
🎨 **Visuals Agent** - Shapes the artistic vision and style
⚙️ **Tech Agent** - Provides technical direction and solutions
These agents collaborate to create a comprehensive game concept based on your inputs.
""")
# User inputs
st.subheader("Game Details")
col1, col2 = st.columns(2)
with col1:
background_vibe = st.text_input("Background Vibe", "Epic fantasy with dragons")
game_type = st.selectbox("Game Type", ["RPG", "Action", "Adventure", "Puzzle", "Strategy", "Simulation", "Platform", "Horror"])
target_audience = st.selectbox("Target Audience", ["Kids (7-12)", "Teens (13-17)", "Young Adults (18-25)", "Adults (26+)", "All Ages"])
player_perspective = st.selectbox("Player Perspective", ["First Person", "Third Person", "Top Down", "Side View", "Isometric"])
multiplayer = st.selectbox("Multiplayer Support", ["Single Player Only", "Local Co-op", "Online Multiplayer", "Both Local and Online"])
with col2:
game_goal = st.text_input("Game Goal", "Save the kingdom from eternal winter")
art_style = st.selectbox("Art Style", ["Realistic", "Cartoon", "Pixel Art", "Stylized", "Low Poly", "Anime", "Hand-drawn"])
platform = st.multiselect("Target Platforms", ["PC", "Mobile", "PlayStation", "Xbox", "Nintendo Switch", "Web Browser"])
development_time = st.slider("Development Time (months)", 1, 36, 12)
cost = st.number_input("Budget (USD)", min_value=0, value=10000, step=5000)
# Additional details
st.subheader("Detailed Preferences")
col3, col4 = st.columns(2)
with col3:
core_mechanics = st.multiselect(
"Core Gameplay Mechanics",
["Combat", "Exploration", "Puzzle Solving", "Resource Management", "Base Building", "Stealth", "Racing", "Crafting"]
)
mood = st.multiselect(
"Game Mood/Atmosphere",
["Epic", "Mysterious", "Peaceful", "Tense", "Humorous", "Dark", "Whimsical", "Scary"]
)
with col4:
inspiration = st.text_area("Games for Inspiration (comma-separated)", "")
unique_features = st.text_area("Unique Features or Requirements", "")
depth = st.selectbox("Level of Detail in Response", ["Low", "Medium", "High"])
# Button to start the agent collaboration
if st.button("Generate Game Concept"):
# Check if API key is provided
if not api_key:
st.error("Please enter your OpenAI API key.")
else:
with st.spinner('🤖 AI Agents are collaborating on your game concept...'):
# Prepare the task based on user inputs
task = f"""
Create a game concept with the following details:
- Background Vibe: {background_vibe}
- Game Type: {game_type}
- Game Goal: {game_goal}
- Target Audience: {target_audience}
- Player Perspective: {player_perspective}
- Multiplayer Support: {multiplayer}
- Art Style: {art_style}
- Target Platforms: {', '.join(platform)}
- Development Time: {development_time} months
- Budget: ${cost:,}
- Core Mechanics: {', '.join(core_mechanics)}
- Mood/Atmosphere: {', '.join(mood)}
- Inspiration: {inspiration}
- Unique Features: {unique_features}
- Detail Level: {depth}
"""
llm_config = {"config_list": [{"model": "gpt-4o-mini","api_key": api_key}]}
# initialize context variables
context_variables = {
"story": None,
"gameplay": None,
"visuals": None,
"tech": None,
}
# define functions to be called by the agents
def update_story_overview(story_summary:str, context_variables:dict) -> SwarmResult:
"""Keep the summary as short as possible."""
context_variables["story"] = story_summary
st.sidebar.success('Story overview: ' + story_summary)
return SwarmResult(agent="gameplay_agent", context_variables=context_variables)
def update_gameplay_overview(gameplay_summary:str, context_variables:dict) -> SwarmResult:
"""Keep the summary as short as possible."""
context_variables["gameplay"] = gameplay_summary
st.sidebar.success('Gameplay overview: ' + gameplay_summary)
return SwarmResult(agent="visuals_agent", context_variables=context_variables)
def update_visuals_overview(visuals_summary:str, context_variables:dict) -> SwarmResult:
"""Keep the summary as short as possible."""
context_variables["visuals"] = visuals_summary
st.sidebar.success('Visuals overview: ' + visuals_summary)
return SwarmResult(agent="tech_agent", context_variables=context_variables)
def update_tech_overview(tech_summary:str, context_variables:dict) -> SwarmResult:
"""Keep the summary as short as possible."""
context_variables["tech"] = tech_summary
st.sidebar.success('Tech overview: ' + tech_summary)
return SwarmResult(agent="story_agent", context_variables=context_variables)
system_messages = {
"story_agent": """
You are an experienced game story designer specializing in narrative design and world-building. Your task is to:
1. Create a compelling narrative that aligns with the specified game type and target audience.
2. Design memorable characters with clear motivations and character arcs.
3. Develop the game's world, including its history, culture, and key locations.
4. Plan story progression and major plot points.
5. Integrate the narrative with the specified mood/atmosphere.
6. Consider how the story supports the core gameplay mechanics.
""",
"gameplay_agent": """
You are a senior game mechanics designer with expertise in player engagement and systems design. Your task is to:
1. Design core gameplay loops that match the specified game type and mechanics.
2. Create progression systems (character development, skills, abilities).
3. Define player interactions and control schemes for the chosen perspective.
4. Balance gameplay elements for the target audience.
5. Design multiplayer interactions if applicable.
6. Specify game modes and difficulty settings.
7. Consider the budget and development time constraints.
""",
"visuals_agent": """
You are a creative art director with expertise in game visual and audio design. Your task is to:
1. Define the visual style guide matching the specified art style.
2. Design character and environment aesthetics.
3. Plan visual effects and animations.
4. Create the audio direction including music style, sound effects, and ambient sound.
5. Consider technical constraints of chosen platforms.
6. Align visual elements with the game's mood/atmosphere.
7. Work within the specified budget constraints.
""",
"tech_agent": """
You are a technical director with extensive game development experience. Your task is to:
1. Recommend appropriate game engine and development tools.
2. Define technical requirements for all target platforms.
3. Plan the development pipeline and asset workflow.
4. Identify potential technical challenges and solutions.
5. Estimate resource requirements within the budget.
6. Consider scalability and performance optimization.
7. Plan for multiplayer infrastructure if applicable.
"""
}
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"}}
agent.client = OpenAIWrapper(**agent.llm_config)
else:
# remove the tools to avoid the agent from using it and reduce cost
agent.llm_config["tools"] = None
agent.llm_config['tool_choice'] = None
agent.client = OpenAIWrapper(**agent.llm_config)
# the agent has given a summary, now it should generate a detailed response
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 response with: '## {current_gen.capitalize()} Design'."
# Remove all messages except the first one with less cost
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:"
# Add context variables to the prompt
for k, v in agent._context_variables.items():
if v is not None:
system_prompt += f"\n{k.capitalize()} Summary:\n{v}"
return system_prompt
state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func)
# Define agents
story_agent = SwarmAgent(
"story_agent",
llm_config=llm_config,
functions=update_story_overview,
update_agent_state_before_reply=[state_update]
)
gameplay_agent = SwarmAgent(
"gameplay_agent",
llm_config= llm_config,
functions=update_gameplay_overview,
update_agent_state_before_reply=[state_update]
)
visuals_agent = SwarmAgent(
"visuals_agent",
llm_config=llm_config,
functions=update_visuals_overview,
update_agent_state_before_reply=[state_update]
)
tech_agent = SwarmAgent(
name="tech_agent",
llm_config=llm_config,
functions=update_tech_overview,
update_agent_state_before_reply=[state_update]
)
story_agent.register_hand_off(AFTER_WORK(gameplay_agent))
gameplay_agent.register_hand_off(AFTER_WORK(visuals_agent))
visuals_agent.register_hand_off(AFTER_WORK(tech_agent))
tech_agent.register_hand_off(AFTER_WORK(story_agent))
result, _, _ = initiate_swarm_chat(
initial_agent=story_agent,
agents=[story_agent, gameplay_agent, visuals_agent, tech_agent],
user_agent=None,
messages=task,
max_rounds=13,
)
# Update session state with the individual responses
st.session_state.output = {
'story': result.chat_history[-4]['content'],
'gameplay': result.chat_history[-3]['content'],
'visuals': result.chat_history[-2]['content'],
'tech': result.chat_history[-1]['content']
}
# Display success message after completion
st.success('✨ Game concept generated successfully!')
# Display the individual outputs in expanders
with st.expander("Story Design"):
st.markdown(st.session_state.output['story'])
with st.expander("Gameplay Mechanics"):
st.markdown(st.session_state.output['gameplay'])
with st.expander("Visual and Audio Design"):
st.markdown(st.session_state.output['visuals'])
with st.expander("Technical Recommendations"):
st.markdown(st.session_state.output['tech'])
| 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/agent_teams/ai_competitor_intelligence_agent_team/competitor_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_competitor_intelligence_agent_team/competitor_agent_team.py | import streamlit as st
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.tools.exa import ExaTools
from agno.tools.firecrawl import FirecrawlTools
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
import pandas as pd
import requests
from firecrawl import FirecrawlApp
from pydantic import BaseModel, Field
from typing import List, Optional
import json
# Streamlit UI
st.set_page_config(page_title="AI Competitor Intelligence Agent Team", layout="wide")
# Sidebar for API keys
st.sidebar.title("API Keys")
openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")
firecrawl_api_key = st.sidebar.text_input("Firecrawl API Key", type="password")
# Add search engine selection before API keys
search_engine = st.sidebar.selectbox(
"Select Search Endpoint",
options=["Perplexity AI - Sonar Pro", "Exa AI"],
help="Choose which AI service to use for finding competitor URLs"
)
# Show relevant API key input based on selection
if search_engine == "Perplexity AI - Sonar Pro":
perplexity_api_key = st.sidebar.text_input("Perplexity API Key", type="password")
# Store API keys in session state
if openai_api_key and firecrawl_api_key and perplexity_api_key:
st.session_state.openai_api_key = openai_api_key
st.session_state.firecrawl_api_key = firecrawl_api_key
st.session_state.perplexity_api_key = perplexity_api_key
else:
st.sidebar.warning("Please enter all required API keys to proceed.")
else: # Exa AI
exa_api_key = st.sidebar.text_input("Exa API Key", type="password")
# Store API keys in session state
if openai_api_key and firecrawl_api_key and exa_api_key:
st.session_state.openai_api_key = openai_api_key
st.session_state.firecrawl_api_key = firecrawl_api_key
st.session_state.exa_api_key = exa_api_key
else:
st.sidebar.warning("Please enter all required API keys to proceed.")
# Main UI
st.title("🧲 AI Competitor Intelligence Agent Team")
st.info(
"""
This app helps businesses analyze their competitors by extracting structured data from competitor websites and generating insights using AI.
- Provide a **URL** or a **description** of your company.
- The app will fetch competitor URLs, extract relevant information, and generate a detailed analysis report.
"""
)
st.success("For better results, provide both URL and a 5-6 word description of your company!")
# Input fields for URL and description
url = st.text_input("Enter your company URL :")
description = st.text_area("Enter a description of your company (if URL is not available):")
# Initialize API keys and tools
if "openai_api_key" in st.session_state and "firecrawl_api_key" in st.session_state:
if (search_engine == "Perplexity AI - Sonar Pro" and "perplexity_api_key" in st.session_state) or \
(search_engine == "Exa AI" and "exa_api_key" in st.session_state):
firecrawl_tools = FirecrawlTools(
api_key=st.session_state.firecrawl_api_key,
scrape=False,
crawl=True,
limit=5
)
# Create ExaTools agent for finding competitor URLs
if search_engine == "Exa AI":
exa_tools = ExaTools(
api_key=st.session_state.exa_api_key,
category="company",
num_results=3
)
competitor_finder_agent = Agent(
model=OpenAIChat(id="gpt-4o", api_key=st.session_state.openai_api_key),
tools=[exa_tools],
debug_mode=True,
markdown=True,
instructions=[
"You are a competitor finder agent. Use ExaTools to find competitor company URLs.",
"When given a URL, find similar companies. When given a description, search for companies matching that description.",
"Return ONLY the URLs, one per line, with no additional text."
]
)
firecrawl_agent = Agent(
model=OpenAIChat(id="gpt-4o", api_key=st.session_state.openai_api_key),
tools=[firecrawl_tools, DuckDuckGoTools()],
debug_mode=True,
markdown=True
)
analysis_agent = Agent(
model=OpenAIChat(id="gpt-4o", api_key=st.session_state.openai_api_key),
debug_mode=True,
markdown=True
)
# New agent for comparing competitor data
comparison_agent = Agent(
model=OpenAIChat(id="gpt-4o", api_key=st.session_state.openai_api_key),
debug_mode=True,
markdown=True
)
def get_competitor_urls(url: str = None, description: str = None) -> list[str]:
if not url and not description:
raise ValueError("Please provide either a URL or a description.")
if search_engine == "Perplexity AI - Sonar Pro":
perplexity_url = "https://api.perplexity.ai/chat/completions"
content = "Find me 3 competitor company URLs similar to the company with "
if url and description:
content += f"URL: {url} and description: {description}"
elif url:
content += f"URL: {url}"
else:
content += f"description: {description}"
content += ". ONLY RESPOND WITH THE URLS, NO OTHER TEXT."
payload = {
"model": "sonar-pro",
"messages": [
{
"role": "system",
"content": "Be precise and only return 3 company URLs ONLY."
},
{
"role": "user",
"content": content
}
],
"max_tokens": 1000,
"temperature": 0.2,
}
headers = {
"Authorization": f"Bearer {st.session_state.perplexity_api_key}",
"Content-Type": "application/json"
}
try:
response = requests.post(perplexity_url, json=payload, headers=headers)
response.raise_for_status()
urls = response.json()['choices'][0]['message']['content'].strip().split('\n')
return [url.strip() for url in urls if url.strip()]
except Exception as e:
st.error(f"Error fetching competitor URLs from Perplexity: {str(e)}")
return []
else: # Exa AI
try:
# Use ExaTools agent to find competitor URLs
if url:
prompt = f"Find 3 competitor company URLs similar to: {url}. Return ONLY the URLs, one per line."
else:
prompt = f"Find 3 competitor company URLs matching this description: {description}. Return ONLY the URLs, one per line."
response: RunOutput = competitor_finder_agent.run(prompt)
# Extract URLs from the response
urls = [line.strip() for line in response.content.strip().split('\n') if line.strip() and line.strip().startswith('http')]
return urls[:3] # Return up to 3 URLs
except Exception as e:
st.error(f"Error fetching competitor URLs from Exa: {str(e)}")
return []
class CompetitorDataSchema(BaseModel):
company_name: str = Field(description="Name of the company")
pricing: str = Field(description="Pricing details, tiers, and plans")
key_features: List[str] = Field(description="Main features and capabilities of the product/service")
tech_stack: List[str] = Field(description="Technologies, frameworks, and tools used")
marketing_focus: str = Field(description="Main marketing angles and target audience")
customer_feedback: str = Field(description="Customer testimonials, reviews, and feedback")
def extract_competitor_info(competitor_url: str) -> Optional[dict]:
try:
# Initialize FirecrawlApp with API key
app = FirecrawlApp(api_key=st.session_state.firecrawl_api_key)
# Add wildcard to crawl subpages
url_pattern = f"{competitor_url}/*"
extraction_prompt = """
Extract detailed information about the company's offerings, including:
- Company name and basic information
- Pricing details, plans, and tiers
- Key features and main capabilities
- Technology stack and technical details
- Marketing focus and target audience
- Customer feedback and testimonials
Analyze the entire website content to provide comprehensive information for each field.
"""
response = app.extract(
[url_pattern],
prompt=extraction_prompt,
schema=CompetitorDataSchema.model_json_schema()
)
# Handle ExtractResponse object
try:
if hasattr(response, 'success') and response.success:
if hasattr(response, 'data') and response.data:
extracted_info = response.data
# Create JSON structure
competitor_json = {
"competitor_url": competitor_url,
"company_name": extracted_info.get('company_name', 'N/A') if isinstance(extracted_info, dict) else getattr(extracted_info, 'company_name', 'N/A'),
"pricing": extracted_info.get('pricing', 'N/A') if isinstance(extracted_info, dict) else getattr(extracted_info, 'pricing', 'N/A'),
"key_features": extracted_info.get('key_features', [])[:5] if isinstance(extracted_info, dict) and extracted_info.get('key_features') else getattr(extracted_info, 'key_features', [])[:5] if hasattr(extracted_info, 'key_features') else ['N/A'],
"tech_stack": extracted_info.get('tech_stack', [])[:5] if isinstance(extracted_info, dict) and extracted_info.get('tech_stack') else getattr(extracted_info, 'tech_stack', [])[:5] if hasattr(extracted_info, 'tech_stack') else ['N/A'],
"marketing_focus": extracted_info.get('marketing_focus', 'N/A') if isinstance(extracted_info, dict) else getattr(extracted_info, 'marketing_focus', 'N/A'),
"customer_feedback": extracted_info.get('customer_feedback', 'N/A') if isinstance(extracted_info, dict) else getattr(extracted_info, 'customer_feedback', 'N/A')
}
return competitor_json
else:
return None
else:
return None
except Exception as response_error:
return None
except Exception as e:
return None
def generate_comparison_report(competitor_data: list) -> None:
# Create DataFrame directly from competitor data
if not competitor_data:
st.error("No competitor data available for comparison")
return
# Prepare data for DataFrame
table_data = []
for competitor in competitor_data:
row = {
'Company': f"{competitor.get('company_name', 'N/A')} ({competitor.get('competitor_url', 'N/A')})",
'Pricing': competitor.get('pricing', 'N/A')[:100] + '...' if len(competitor.get('pricing', '')) > 100 else competitor.get('pricing', 'N/A'),
'Key Features': ', '.join(competitor.get('key_features', [])[:3]) if competitor.get('key_features') else 'N/A',
'Tech Stack': ', '.join(competitor.get('tech_stack', [])[:3]) if competitor.get('tech_stack') else 'N/A',
'Marketing Focus': competitor.get('marketing_focus', 'N/A')[:100] + '...' if len(competitor.get('marketing_focus', '')) > 100 else competitor.get('marketing_focus', 'N/A'),
'Customer Feedback': competitor.get('customer_feedback', 'N/A')[:100] + '...' if len(competitor.get('customer_feedback', '')) > 100 else competitor.get('customer_feedback', 'N/A')
}
table_data.append(row)
# Create DataFrame
df = pd.DataFrame(table_data)
# Display the table
st.subheader("Competitor Comparison")
st.dataframe(df, use_container_width=True)
# Also show raw data for debugging
with st.expander("View Raw Competitor Data"):
st.json(competitor_data)
def generate_analysis_report(competitor_data: list):
# Format the competitor data for the prompt
formatted_data = json.dumps(competitor_data, indent=2)
print("Analysis Data:", formatted_data) # For debugging
report: RunOutput = analysis_agent.run(
f"""Analyze the following competitor data in JSON format and identify market opportunities to improve my own company:
{formatted_data}
Tasks:
1. Identify market gaps and opportunities based on competitor offerings
2. Analyze competitor weaknesses that we can capitalize on
3. Recommend unique features or capabilities we should develop
4. Suggest pricing and positioning strategies to gain competitive advantage
5. Outline specific growth opportunities in underserved market segments
6. Provide actionable recommendations for product development and go-to-market strategy
Focus on finding opportunities where we can differentiate and do better than competitors.
Highlight any unmet customer needs or pain points we can address.
"""
)
return report.content
# Run analysis when the user clicks the button
if st.button("Analyze Competitors"):
if url or description:
with st.spinner("Fetching competitor URLs..."):
competitor_urls = get_competitor_urls(url=url, description=description)
st.write(f"Found {len(competitor_urls)} competitor URLs")
if not competitor_urls:
st.error("No competitor URLs found!")
st.stop()
competitor_data = []
successful_extractions = 0
failed_extractions = 0
for i, comp_url in enumerate(competitor_urls):
with st.spinner(f"Analyzing Competitor {i+1}/{len(competitor_urls)}: {comp_url}"):
competitor_info = extract_competitor_info(comp_url)
if competitor_info is not None:
competitor_data.append(competitor_info)
successful_extractions += 1
st.success(f"✓ Successfully analyzed {comp_url}")
else:
failed_extractions += 1
st.error(f"✗ Failed to analyze {comp_url}")
if competitor_data:
st.success(f"Successfully analyzed {successful_extractions}/{len(competitor_urls)} competitors!")
# Generate and display comparison report
with st.spinner("Generating comparison table..."):
generate_comparison_report(competitor_data)
# Generate and display final analysis report
with st.spinner("Generating analysis report..."):
analysis_report = generate_analysis_report(competitor_data)
st.subheader("Competitor Analysis Report")
st.markdown(analysis_report)
st.success("Analysis complete!")
else:
st.error("Could not extract data from any competitor URLs")
st.write("This might be due to:")
st.write("- API rate limits (try again in a few minutes)")
st.write("- Website access issues (some sites block automated access)")
st.write("- Invalid URLs (try with a different company description)")
else:
st.error("Please provide either a URL or a description.") | 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/agent_teams/ai_real_estate_agent_team/ai_real_estate_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_real_estate_agent_team/ai_real_estate_agent_team.py | import os
import streamlit as st
import json
import time
import re
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.models.google import Gemini
from dotenv import load_dotenv
from firecrawl import FirecrawlApp
from pydantic import BaseModel, Field
from typing import List, Optional
# Load environment variables
load_dotenv()
# API keys - must be set in environment variables
DEFAULT_GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
DEFAULT_FIRECRAWL_API_KEY = os.getenv("FIRECRAWL_API_KEY")
# Pydantic schemas
class PropertyDetails(BaseModel):
address: str = Field(description="Full property address")
price: Optional[str] = Field(description="Property price")
bedrooms: Optional[str] = Field(description="Number of bedrooms")
bathrooms: Optional[str] = Field(description="Number of bathrooms")
square_feet: Optional[str] = Field(description="Square footage")
property_type: Optional[str] = Field(description="Type of property")
description: Optional[str] = Field(description="Property description")
features: Optional[List[str]] = Field(description="Property features")
images: Optional[List[str]] = Field(description="Property image URLs")
agent_contact: Optional[str] = Field(description="Agent contact information")
listing_url: Optional[str] = Field(description="Original listing URL")
class PropertyListing(BaseModel):
properties: List[PropertyDetails] = Field(description="List of properties found")
total_count: int = Field(description="Total number of properties found")
source_website: str = Field(description="Website where properties were found")
class DirectFirecrawlAgent:
"""Agent with direct Firecrawl integration for property search"""
def __init__(self, firecrawl_api_key: str, google_api_key: str, model_id: str = "gemini-2.5-flash"):
self.agent = Agent(
model=Gemini(id=model_id, api_key=google_api_key),
markdown=True,
description="I am a real estate expert who helps find and analyze properties based on user preferences."
)
self.firecrawl = FirecrawlApp(api_key=firecrawl_api_key)
def find_properties_direct(self, city: str, state: str, user_criteria: dict, selected_websites: list) -> dict:
"""Direct Firecrawl integration for property search"""
city_formatted = city.replace(' ', '-').lower()
state_upper = state.upper() if state else ''
# Create URLs for selected websites
state_lower = state.lower() if state else ''
city_trulia = city.replace(' ', '_') # Trulia uses underscores for spaces
search_urls = {
"Zillow": f"https://www.zillow.com/homes/for_sale/{city_formatted}-{state_upper}/",
"Realtor.com": f"https://www.realtor.com/realestateandhomes-search/{city_formatted}_{state_upper}/pg-1",
"Trulia": f"https://www.trulia.com/{state_upper}/{city_trulia}/",
"Homes.com": f"https://www.homes.com/homes-for-sale/{city_formatted}-{state_lower}/"
}
# Filter URLs based on selected websites
urls_to_search = [url for site, url in search_urls.items() if site in selected_websites]
print(f"Selected websites: {selected_websites}")
print(f"URLs to search: {urls_to_search}")
if not urls_to_search:
return {"error": "No websites selected"}
# Create comprehensive prompt with specific schema guidance
prompt = f"""You are extracting property listings from real estate websites. Extract EVERY property listing you can find on the page.
USER SEARCH CRITERIA:
- Budget: {user_criteria.get('budget_range', 'Any')}
- Property Type: {user_criteria.get('property_type', 'Any')}
- Bedrooms: {user_criteria.get('bedrooms', 'Any')}
- Bathrooms: {user_criteria.get('bathrooms', 'Any')}
- Min Square Feet: {user_criteria.get('min_sqft', 'Any')}
- Special Features: {user_criteria.get('special_features', 'Any')}
EXTRACTION INSTRUCTIONS:
1. Find ALL property listings on the page (usually 20-40 per page)
2. For EACH property, extract these fields:
- address: Full street address (required)
- price: Listed price with $ symbol (required)
- bedrooms: Number of bedrooms (required)
- bathrooms: Number of bathrooms (required)
- square_feet: Square footage if available
- property_type: House/Condo/Townhouse/Apartment etc.
- description: Brief property description if available
- listing_url: Direct link to property details if available
- agent_contact: Agent name/phone if visible
3. CRITICAL REQUIREMENTS:
- Extract AT LEAST 10 properties if they exist on the page
- Do NOT skip properties even if some fields are missing
- Use "Not specified" for missing optional fields
- Ensure address and price are always filled
- Look for property cards, listings, search results
4. RETURN FORMAT:
- Return JSON with "properties" array containing all extracted properties
- Each property should be a complete object with all available fields
- Set "total_count" to the number of properties extracted
- Set "source_website" to the main website name (Zillow/Realtor/Trulia/Homes)
EXTRACT EVERY VISIBLE PROPERTY LISTING - DO NOT LIMIT TO JUST A FEW!
"""
try:
# Direct Firecrawl call - using correct API format
print(f"Calling Firecrawl with {len(urls_to_search)} URLs")
raw_response = self.firecrawl.extract(
urls_to_search,
prompt=prompt,
schema=PropertyListing.model_json_schema()
)
print("Raw Firecrawl Response:", raw_response)
if hasattr(raw_response, 'success') and raw_response.success:
# Handle Firecrawl response object
properties = raw_response.data.get('properties', []) if hasattr(raw_response, 'data') else []
total_count = raw_response.data.get('total_count', 0) if hasattr(raw_response, 'data') else 0
print(f"Response data keys: {list(raw_response.data.keys()) if hasattr(raw_response, 'data') else 'No data'}")
elif isinstance(raw_response, dict) and raw_response.get('success'):
# Handle dictionary response
properties = raw_response['data'].get('properties', [])
total_count = raw_response['data'].get('total_count', 0)
print(f"Response data keys: {list(raw_response['data'].keys())}")
else:
properties = []
total_count = 0
print(f"Response failed or unexpected format: {type(raw_response)}")
print(f"Extracted {len(properties)} properties from {total_count} total found")
# Debug: Print first property if available
if properties:
print(f"First property sample: {properties[0]}")
return {
'success': True,
'properties': properties,
'total_count': len(properties),
'source_websites': selected_websites
}
else:
# Enhanced error message with debugging info
error_msg = f"""No properties extracted despite finding {total_count} listings.
POSSIBLE CAUSES:
1. Website structure changed - extraction schema doesn't match
2. Website blocking or requiring interaction (captcha, login)
3. Properties don't match specified criteria too strictly
4. Extraction prompt needs refinement for this website
SUGGESTIONS:
- Try different websites (Zillow, Realtor.com, Trulia, Homes.com)
- Broaden search criteria (Any bedrooms, Any type, etc.)
- Check if website requires specific user interaction
Debug Info: Found {total_count} listings but extraction returned empty array."""
return {"error": error_msg}
except Exception as e:
return {"error": f"Firecrawl extraction failed: {str(e)}"}
def create_sequential_agents(llm, user_criteria):
"""Create agents for sequential manual execution"""
property_search_agent = Agent(
name="Property Search Agent",
model=llm,
instructions="""
You are a property search expert. Your role is to find and extract property listings.
WORKFLOW:
1. SEARCH FOR PROPERTIES:
- Use the provided Firecrawl data to extract property listings
- Focus on properties matching user criteria
- Extract detailed property information
2. EXTRACT PROPERTY DATA:
- Address, price, bedrooms, bathrooms, square footage
- Property type, features, listing URLs
- Agent contact information
3. PROVIDE STRUCTURED OUTPUT:
- List properties with complete details
- Include all listing URLs
- Rank by match quality to user criteria
IMPORTANT:
- Focus ONLY on finding and extracting property data
- Do NOT provide market analysis or valuations
- Your output will be used by other agents for analysis
""",
)
market_analysis_agent = Agent(
name="Market Analysis Agent",
model=llm,
instructions="""
You are a market analysis expert. Provide CONCISE market insights.
REQUIREMENTS:
- Keep analysis brief and to the point
- Focus on key market trends only
- Provide 2-3 bullet points per area
- Avoid repetition and lengthy explanations
COVER:
1. Market Condition: Buyer's/seller's market, price trends
2. Key Neighborhoods: Brief overview of areas where properties are located
3. Investment Outlook: 2-3 key points about investment potential
FORMAT: Use bullet points and keep each section under 100 words.
""",
)
property_valuation_agent = Agent(
name="Property Valuation Agent",
model=llm,
instructions="""
You are a property valuation expert. Provide CONCISE property assessments.
REQUIREMENTS:
- Keep each property assessment brief (2-3 sentences max)
- Focus on key points only: value, investment potential, recommendation
- Avoid lengthy analysis and repetition
- Use bullet points for clarity
FOR EACH PROPERTY, PROVIDE:
1. Value Assessment: Fair price, over/under priced
2. Investment Potential: High/Medium/Low with brief reason
3. Key Recommendation: One actionable insight
FORMAT:
- Use bullet points
- Keep each property under 50 words
- Focus on actionable insights only
""",
)
return property_search_agent, market_analysis_agent, property_valuation_agent
def run_sequential_analysis(city, state, user_criteria, selected_websites, firecrawl_api_key, google_api_key, update_callback):
"""Run agents sequentially with manual coordination"""
# Initialize agents
llm = Gemini(id="gemini-2.5-flash", api_key=google_api_key)
property_search_agent, market_analysis_agent, property_valuation_agent = create_sequential_agents(llm, user_criteria)
# Step 1: Property Search with Direct Firecrawl Integration
update_callback(0.2, "Searching properties...", "🔍 Property Search Agent: Finding properties...")
direct_agent = DirectFirecrawlAgent(
firecrawl_api_key=firecrawl_api_key,
google_api_key=google_api_key,
model_id="gemini-2.5-flash"
)
properties_data = direct_agent.find_properties_direct(
city=city,
state=state,
user_criteria=user_criteria,
selected_websites=selected_websites
)
if "error" in properties_data:
return f"Error in property search: {properties_data['error']}"
properties = properties_data.get('properties', [])
if not properties:
return "No properties found matching your criteria."
update_callback(0.4, "Properties found", f"✅ Found {len(properties)} properties")
# Step 2: Market Analysis
update_callback(0.5, "Analyzing market...", "📊 Market Analysis Agent: Analyzing market trends...")
market_analysis_prompt = f"""
Provide CONCISE market analysis for these properties:
PROPERTIES: {len(properties)} properties in {city}, {state}
BUDGET: {user_criteria.get('budget_range', 'Any')}
Give BRIEF insights on:
• Market condition (buyer's/seller's market)
• Key neighborhoods where properties are located
• Investment outlook (2-3 bullet points max)
Keep each section under 100 words. Use bullet points.
"""
market_result: RunOutput = market_analysis_agent.run(market_analysis_prompt)
market_analysis = market_result.content
update_callback(0.7, "Market analysis complete", "✅ Market analysis completed")
# Step 3: Property Valuation
update_callback(0.8, "Evaluating properties...", "💰 Property Valuation Agent: Evaluating properties...")
# Create detailed property list for valuation
properties_for_valuation = []
for i, prop in enumerate(properties, 1):
if isinstance(prop, dict):
prop_data = {
'number': i,
'address': prop.get('address', 'Address not available'),
'price': prop.get('price', 'Price not available'),
'property_type': prop.get('property_type', 'Type not available'),
'bedrooms': prop.get('bedrooms', 'Not specified'),
'bathrooms': prop.get('bathrooms', 'Not specified'),
'square_feet': prop.get('square_feet', 'Not specified')
}
else:
prop_data = {
'number': i,
'address': getattr(prop, 'address', 'Address not available'),
'price': getattr(prop, 'price', 'Price not available'),
'property_type': getattr(prop, 'property_type', 'Type not available'),
'bedrooms': getattr(prop, 'bedrooms', 'Not specified'),
'bathrooms': getattr(prop, 'bathrooms', 'Not specified'),
'square_feet': getattr(prop, 'square_feet', 'Not specified')
}
properties_for_valuation.append(prop_data)
valuation_prompt = f"""
Provide CONCISE property assessments for each property. Use the EXACT format shown below:
USER BUDGET: {user_criteria.get('budget_range', 'Any')}
PROPERTIES TO EVALUATE:
{json.dumps(properties_for_valuation, indent=2)}
For EACH property, provide assessment in this EXACT format:
**Property [NUMBER]: [ADDRESS]**
• Value: [Fair price/Over priced/Under priced] - [brief reason]
• Investment Potential: [High/Medium/Low] - [brief reason]
• Recommendation: [One actionable insight]
REQUIREMENTS:
- Start each assessment with "**Property [NUMBER]:**"
- Keep each property assessment under 50 words
- Analyze ALL {len(properties)} properties individually
- Use bullet points as shown
"""
valuation_result: RunOutput = property_valuation_agent.run(valuation_prompt)
property_valuations = valuation_result.content
update_callback(0.9, "Valuation complete", "✅ Property valuations completed")
# Step 4: Final Synthesis
update_callback(0.95, "Synthesizing results...", "🤖 Synthesizing final recommendations...")
# Debug: Check properties structure
print(f"Properties type: {type(properties)}")
print(f"Properties length: {len(properties)}")
if properties:
print(f"First property type: {type(properties[0])}")
print(f"First property: {properties[0]}")
# Format properties for better display
properties_display = ""
for i, prop in enumerate(properties, 1):
# Handle both dict and object access
if isinstance(prop, dict):
address = prop.get('address', 'Address not available')
price = prop.get('price', 'Price not available')
prop_type = prop.get('property_type', 'Type not available')
bedrooms = prop.get('bedrooms', 'Not specified')
bathrooms = prop.get('bathrooms', 'Not specified')
square_feet = prop.get('square_feet', 'Not specified')
agent_contact = prop.get('agent_contact', 'Contact not available')
description = prop.get('description', 'No description available')
listing_url = prop.get('listing_url', '#')
else:
# Handle object access
address = getattr(prop, 'address', 'Address not available')
price = getattr(prop, 'price', 'Price not available')
prop_type = getattr(prop, 'property_type', 'Type not available')
bedrooms = getattr(prop, 'bedrooms', 'Not specified')
bathrooms = getattr(prop, 'bathrooms', 'Not specified')
square_feet = getattr(prop, 'square_feet', 'Not specified')
agent_contact = getattr(prop, 'agent_contact', 'Contact not available')
description = getattr(prop, 'description', 'No description available')
listing_url = getattr(prop, 'listing_url', '#')
properties_display += f"""
### Property {i}: {address}
**Price:** {price}
**Type:** {prop_type}
**Bedrooms:** {bedrooms} | **Bathrooms:** {bathrooms}
**Square Feet:** {square_feet}
**Agent Contact:** {agent_contact}
**Description:** {description}
**Listing URL:** [View Property]({listing_url})
---
"""
final_synthesis = f"""
# 🏠 Property Listings Found
**Total Properties:** {len(properties)} properties matching your criteria
{properties_display}
---
# 📊 Market Analysis & Investment Insights
{market_analysis}
---
# 💰 Property Valuations & Recommendations
{property_valuations}
---
# 🔗 All Property Links
"""
# Extract and add property links
all_text = f"{json.dumps(properties, indent=2)} {market_analysis} {property_valuations}"
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', all_text)
if urls:
final_synthesis += "\n### Available Property Links:\n"
for i, url in enumerate(set(urls), 1):
final_synthesis += f"{i}. {url}\n"
update_callback(1.0, "Analysis complete", "🎉 Complete analysis ready!")
# Return structured data for better UI display
return {
'properties': properties,
'market_analysis': market_analysis,
'property_valuations': property_valuations,
'markdown_synthesis': final_synthesis,
'total_properties': len(properties)
}
def extract_property_valuation(property_valuations, property_number, property_address):
"""Extract valuation for a specific property from the full analysis"""
if not property_valuations:
return None
# Split by property sections - look for the formatted property headers
sections = property_valuations.split('**Property')
# Look for the specific property number
for section in sections:
if section.strip().startswith(f"{property_number}:"):
# Add back the "**Property" prefix and clean up
clean_section = f"**Property{section}".strip()
# Remove any extra asterisks at the end
clean_section = clean_section.replace('**', '**').replace('***', '**')
return clean_section
# Fallback: look for property number mentions in any format
all_sections = property_valuations.split('\n\n')
for section in all_sections:
if (f"Property {property_number}" in section or
f"#{property_number}" in section):
return section
# Last resort: try to match by address
for section in all_sections:
if any(word in section.lower() for word in property_address.lower().split()[:3] if len(word) > 2):
return section
# If no specific match found, return indication that analysis is not available
return f"**Property {property_number} Analysis**\n• Analysis: Individual assessment not available\n• Recommendation: Review general market analysis in the Market Analysis tab"
def display_properties_professionally(properties, market_analysis, property_valuations, total_properties):
"""Display properties in a clean, professional UI using Streamlit components"""
# Header with key metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Properties Found", total_properties)
with col2:
# Calculate average price
prices = []
for p in properties:
price_str = p.get('price', '') if isinstance(p, dict) else getattr(p, 'price', '')
if price_str and price_str != 'Price not available':
try:
price_num = ''.join(filter(str.isdigit, str(price_str)))
if price_num:
prices.append(int(price_num))
except:
pass
avg_price = f"${sum(prices) // len(prices):,}" if prices else "N/A"
st.metric("Average Price", avg_price)
with col3:
types = {}
for p in properties:
t = p.get('property_type', 'Unknown') if isinstance(p, dict) else getattr(p, 'property_type', 'Unknown')
types[t] = types.get(t, 0) + 1
most_common = max(types.items(), key=lambda x: x[1])[0] if types else "N/A"
st.metric("Most Common Type", most_common)
# Create tabs for different views
tab1, tab2, tab3 = st.tabs(["🏠 Properties", "📊 Market Analysis", "💰 Valuations"])
with tab1:
for i, prop in enumerate(properties, 1):
# Extract property data
data = {k: prop.get(k, '') if isinstance(prop, dict) else getattr(prop, k, '')
for k in ['address', 'price', 'property_type', 'bedrooms', 'bathrooms', 'square_feet', 'description', 'listing_url']}
with st.container():
# Property header with number and price
col1, col2 = st.columns([3, 1])
with col1:
st.subheader(f"#{i} 🏠 {data['address']}")
with col2:
st.metric("Price", data['price'])
# Property details with right-aligned button
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
st.markdown(f"**Type:** {data['property_type']}")
st.markdown(f"**Beds/Baths:** {data['bedrooms']}/{data['bathrooms']}")
st.markdown(f"**Area:** {data['square_feet']}")
with col2:
with st.expander("💰 Investment Analysis"):
# Extract property-specific valuation from the full analysis
property_valuation = extract_property_valuation(property_valuations, i, data['address'])
if property_valuation:
st.markdown(property_valuation)
else:
st.info("Investment analysis not available for this property")
with col3:
if data['listing_url'] and data['listing_url'] != '#':
st.markdown(
f"""
<div style="height: 100%; display: flex; align-items: center; justify-content: flex-end;">
<a href="{data['listing_url']}" target="_blank"
style="text-decoration: none; padding: 0.5rem 1rem;
background-color: #0066cc; color: white;
border-radius: 6px; font-size: 0.9em; font-weight: 500;">
Property Link
</a>
</div>
""",
unsafe_allow_html=True
)
st.divider()
with tab2:
st.subheader("📊 Market Analysis")
if market_analysis:
for section in market_analysis.split('\n\n'):
if section.strip():
st.markdown(section)
else:
st.info("No market analysis available")
with tab3:
st.subheader("💰 Investment Analysis")
if property_valuations:
for section in property_valuations.split('\n\n'):
if section.strip():
st.markdown(section)
else:
st.info("No valuation data available")
def main():
st.set_page_config(
page_title="AI Real Estate Agent Team",
page_icon="🏠",
layout="wide",
initial_sidebar_state="expanded"
)
# Clean header
st.title("🏠 AI Real Estate Agent Team")
st.caption("Find Your Dream Home with Specialized AI Agents")
# Sidebar configuration
with st.sidebar:
st.header("⚙️ Configuration")
# API Key inputs with validation
with st.expander("🔑 API Keys", expanded=True):
google_key = st.text_input(
"Google AI API Key",
value=DEFAULT_GOOGLE_API_KEY,
type="password",
help="Get your API key from https://aistudio.google.com/app/apikey",
placeholder="AIza..."
)
firecrawl_key = st.text_input(
"Firecrawl API Key",
value=DEFAULT_FIRECRAWL_API_KEY,
type="password",
help="Get your API key from https://firecrawl.dev",
placeholder="fc_..."
)
# Update environment variables
if google_key: os.environ["GOOGLE_API_KEY"] = google_key
if firecrawl_key: os.environ["FIRECRAWL_API_KEY"] = firecrawl_key
# Website selection
with st.expander("🌐 Search Sources", expanded=True):
st.markdown("**Select real estate websites to search:**")
available_websites = ["Zillow", "Realtor.com", "Trulia", "Homes.com"]
selected_websites = [site for site in available_websites if st.checkbox(site, value=site in ["Zillow", "Realtor.com"])]
if selected_websites:
st.markdown(f'✅ {len(selected_websites)} sources selected</div>', unsafe_allow_html=True)
else:
st.markdown('<div class="status-error">⚠️ Please select at least one website</div>', unsafe_allow_html=True)
# How it works
with st.expander("🤖 How It Works", expanded=False):
st.markdown("**🔍 Property Search Agent**")
st.markdown("Uses direct Firecrawl integration to find properties")
st.markdown("**📊 Market Analysis Agent**")
st.markdown("Analyzes market trends and neighborhood insights")
st.markdown("**💰 Property Valuation Agent**")
st.markdown("Evaluates properties and provides investment analysis")
# Main form
st.header("Your Property Requirements")
st.info("Please provide the location, budget, and property details to help us find your ideal home.")
with st.form("property_preferences"):
# Location and Budget Section
st.markdown("### 📍 Location & Budget")
col1, col2 = st.columns(2)
with col1:
city = st.text_input(
"🏙️ City",
placeholder="e.g., San Francisco",
help="Enter the city where you want to buy property"
)
state = st.text_input(
"🗺️ State/Province (optional)",
placeholder="e.g., CA",
help="Enter the state or province (optional)"
)
with col2:
min_price = st.number_input(
"💰 Minimum Price ($)",
min_value=0,
value=500000,
step=50000,
help="Your minimum budget for the property"
)
max_price = st.number_input(
"💰 Maximum Price ($)",
min_value=0,
value=1500000,
step=50000,
help="Your maximum budget for the property"
)
# Property Details Section
st.markdown("### 🏡 Property Details")
col1, col2, col3 = st.columns(3)
with col1:
property_type = st.selectbox(
"🏠 Property Type",
["Any", "House", "Condo", "Townhouse", "Apartment"],
help="Type of property you're looking for"
)
bedrooms = st.selectbox(
"🛏️ Bedrooms",
["Any", "1", "2", "3", "4", "5+"],
help="Number of bedrooms required"
)
with col2:
bathrooms = st.selectbox(
"🚿 Bathrooms",
["Any", "1", "1.5", "2", "2.5", "3", "3.5", "4+"],
help="Number of bathrooms required"
)
min_sqft = st.number_input(
"📏 Minimum Square Feet",
min_value=0,
value=1000,
step=100,
help="Minimum square footage required"
)
with col3:
timeline = st.selectbox(
"⏰ Timeline",
["Flexible", "1-3 months", "3-6 months", "6+ months"],
help="When do you plan to buy?"
)
urgency = st.selectbox(
"🚨 Urgency",
["Not urgent", "Somewhat urgent", "Very urgent"],
help="How urgent is your purchase?"
)
# Special Features
st.markdown("### ✨ Special Features")
special_features = st.text_area(
"🎯 Special Features & Requirements",
placeholder="e.g., Parking, Yard, View, Near public transport, Good schools, Walkable neighborhood, etc.",
help="Any specific features or requirements you're looking for"
)
# Submit button with custom styling
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
submitted = st.form_submit_button(
"🚀 Start Property Analysis",
type="primary",
use_container_width=True
)
# Process form submission
if submitted:
# Validate all required inputs
missing_items = []
if not google_key:
missing_items.append("Google AI API Key")
if not firecrawl_key:
missing_items.append("Firecrawl API Key")
if not city:
missing_items.append("City")
if not selected_websites:
missing_items.append("At least one website selection")
if missing_items:
st.markdown(f"""
<div class="status-error" style="text-align: center; margin: 2rem 0;">
⚠️ Please provide: {', '.join(missing_items)}
</div>
""", unsafe_allow_html=True)
return
try:
user_criteria = {
'budget_range': f"${min_price:,} - ${max_price:,}",
'property_type': property_type,
'bedrooms': bedrooms,
'bathrooms': bathrooms,
'min_sqft': min_sqft,
'special_features': special_features if special_features else 'None specified'
}
except Exception as e:
st.markdown(f"""
<div class="status-error" style="text-align: center; margin: 2rem 0;">
❌ Error initializing: {str(e)}
</div>
""", unsafe_allow_html=True)
return
# Display progress
| 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/agent_teams/ai_real_estate_agent_team/local_ai_real_estate_agent_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_real_estate_agent_team/local_ai_real_estate_agent_team.py | import os
import streamlit as st
import json
import time
import re
from agno.agent import Agent
from agno.run.agent import RunOutput
from agno.models.ollama import Ollama
from dotenv import load_dotenv
from firecrawl import FirecrawlApp
from pydantic import BaseModel, Field
from typing import List, Optional
# Load environment variables
load_dotenv()
# API keys - must be set in environment variables
DEFAULT_FIRECRAWL_API_KEY = os.getenv("FIRECRAWL_API_KEY", "")
# Pydantic schemas
class PropertyDetails(BaseModel):
address: str = Field(description="Full property address")
price: Optional[str] = Field(description="Property price")
bedrooms: Optional[str] = Field(description="Number of bedrooms")
bathrooms: Optional[str] = Field(description="Number of bathrooms")
square_feet: Optional[str] = Field(description="Square footage")
property_type: Optional[str] = Field(description="Type of property")
description: Optional[str] = Field(description="Property description")
features: Optional[List[str]] = Field(description="Property features")
images: Optional[List[str]] = Field(description="Property image URLs")
agent_contact: Optional[str] = Field(description="Agent contact information")
listing_url: Optional[str] = Field(description="Original listing URL")
class PropertyListing(BaseModel):
properties: List[PropertyDetails] = Field(description="List of properties found")
total_count: int = Field(description="Total number of properties found")
source_website: str = Field(description="Website where properties were found")
class DirectFirecrawlAgent:
"""Agent with direct Firecrawl integration for property search"""
def __init__(self, firecrawl_api_key: str, model_id: str = "gpt-oss:20b"):
self.agent = Agent(
model=Ollama(id=model_id),
markdown=True,
description="I am a real estate expert who helps find and analyze properties based on user preferences."
)
self.firecrawl = FirecrawlApp(api_key=firecrawl_api_key)
def find_properties_direct(self, city: str, state: str, user_criteria: dict, selected_websites: list) -> dict:
"""Direct Firecrawl integration for property search"""
city_formatted = city.replace(' ', '-').lower()
state_upper = state.upper() if state else ''
# Create URLs for selected websites
state_lower = state.lower() if state else ''
city_trulia = city.replace(' ', '_') # Trulia uses underscores for spaces
search_urls = {
"Zillow": f"https://www.zillow.com/homes/for_sale/{city_formatted}-{state_upper}/",
"Realtor.com": f"https://www.realtor.com/realestateandhomes-search/{city_formatted}_{state_upper}/pg-1",
"Trulia": f"https://www.trulia.com/{state_upper}/{city_trulia}/",
"Homes.com": f"https://www.homes.com/homes-for-sale/{city_formatted}-{state_lower}/"
}
# Filter URLs based on selected websites
urls_to_search = [url for site, url in search_urls.items() if site in selected_websites]
print(f"Selected websites: {selected_websites}")
print(f"URLs to search: {urls_to_search}")
if not urls_to_search:
return {"error": "No websites selected"}
# Create comprehensive prompt with specific schema guidance
prompt = f"""You are extracting property listings from real estate websites. Extract EVERY property listing you can find on the page.
USER SEARCH CRITERIA:
- Budget: {user_criteria.get('budget_range', 'Any')}
- Property Type: {user_criteria.get('property_type', 'Any')}
- Bedrooms: {user_criteria.get('bedrooms', 'Any')}
- Bathrooms: {user_criteria.get('bathrooms', 'Any')}
- Min Square Feet: {user_criteria.get('min_sqft', 'Any')}
- Special Features: {user_criteria.get('special_features', 'Any')}
EXTRACTION INSTRUCTIONS:
1. Find ALL property listings on the page (usually 20-40 per page)
2. For EACH property, extract these fields:
- address: Full street address (required)
- price: Listed price with $ symbol (required)
- bedrooms: Number of bedrooms (required)
- bathrooms: Number of bathrooms (required)
- square_feet: Square footage if available
- property_type: House/Condo/Townhouse/Apartment etc.
- description: Brief property description if available
- listing_url: Direct link to property details if available
- agent_contact: Agent name/phone if visible
3. CRITICAL REQUIREMENTS:
- Extract AT LEAST 10 properties if they exist on the page
- Do NOT skip properties even if some fields are missing
- Use "Not specified" for missing optional fields
- Ensure address and price are always filled
- Look for property cards, listings, search results
4. RETURN FORMAT:
- Return JSON with "properties" array containing all extracted properties
- Each property should be a complete object with all available fields
- Set "total_count" to the number of properties extracted
- Set "source_website" to the main website name (Zillow/Realtor/Trulia/Homes)
EXTRACT EVERY VISIBLE PROPERTY LISTING - DO NOT LIMIT TO JUST A FEW!
"""
try:
# Direct Firecrawl call - using correct API format
print(f"Calling Firecrawl with {len(urls_to_search)} URLs")
raw_response = self.firecrawl.extract(
urls_to_search,
prompt=prompt,
schema=PropertyListing.model_json_schema()
)
print("Raw Firecrawl Response:", raw_response)
if hasattr(raw_response, 'success') and raw_response.success:
# Handle Firecrawl response object
properties = raw_response.data.get('properties', []) if hasattr(raw_response, 'data') else []
total_count = raw_response.data.get('total_count', 0) if hasattr(raw_response, 'data') else 0
print(f"Response data keys: {list(raw_response.data.keys()) if hasattr(raw_response, 'data') else 'No data'}")
elif isinstance(raw_response, dict) and raw_response.get('success'):
# Handle dictionary response
properties = raw_response['data'].get('properties', [])
total_count = raw_response['data'].get('total_count', 0)
print(f"Response data keys: {list(raw_response['data'].keys())}")
else:
properties = []
total_count = 0
print(f"Response failed or unexpected format: {type(raw_response)}")
print(f"Extracted {len(properties)} properties from {total_count} total found")
# Debug: Print first property if available
if properties:
print(f"First property sample: {properties[0]}")
return {
'success': True,
'properties': properties,
'total_count': len(properties),
'source_websites': selected_websites
}
else:
# Enhanced error message with debugging info
error_msg = f"""No properties extracted despite finding {total_count} listings.
POSSIBLE CAUSES:
1. Website structure changed - extraction schema doesn't match
2. Website blocking or requiring interaction (captcha, login)
3. Properties don't match specified criteria too strictly
4. Extraction prompt needs refinement for this website
SUGGESTIONS:
- Try different websites (Zillow, Realtor.com, Trulia, Homes.com)
- Broaden search criteria (Any bedrooms, Any type, etc.)
- Check if website requires specific user interaction
Debug Info: Found {total_count} listings but extraction returned empty array."""
return {"error": error_msg}
except Exception as e:
return {"error": f"Firecrawl extraction failed: {str(e)}"}
def create_sequential_agents(llm, user_criteria):
"""Create agents for sequential manual execution"""
property_search_agent = Agent(
name="Property Search Agent",
model=llm,
instructions="""
You are a property search expert. Your role is to find and extract property listings.
WORKFLOW:
1. SEARCH FOR PROPERTIES:
- Use the provided Firecrawl data to extract property listings
- Focus on properties matching user criteria
- Extract detailed property information
2. EXTRACT PROPERTY DATA:
- Address, price, bedrooms, bathrooms, square footage
- Property type, features, listing URLs
- Agent contact information
3. PROVIDE STRUCTURED OUTPUT:
- List properties with complete details
- Include all listing URLs
- Rank by match quality to user criteria
IMPORTANT:
- Focus ONLY on finding and extracting property data
- Do NOT provide market analysis or valuations
- Your output will be used by other agents for analysis
""",
)
market_analysis_agent = Agent(
name="Market Analysis Agent",
model=llm,
instructions="""
You are a market analysis expert. Provide CONCISE market insights.
REQUIREMENTS:
- Keep analysis brief and to the point
- Focus on key market trends only
- Provide 2-3 bullet points per area
- Avoid repetition and lengthy explanations
COVER:
1. Market Condition: Buyer's/seller's market, price trends
2. Key Neighborhoods: Brief overview of areas where properties are located
3. Investment Outlook: 2-3 key points about investment potential
FORMAT: Use bullet points and keep each section under 100 words.
""",
)
property_valuation_agent = Agent(
name="Property Valuation Agent",
model=llm,
instructions="""
You are a property valuation expert. Provide CONCISE property assessments.
REQUIREMENTS:
- Keep each property assessment brief (2-3 sentences max)
- Focus on key points only: value, investment potential, recommendation
- Avoid lengthy analysis and repetition
- Use bullet points for clarity
FOR EACH PROPERTY, PROVIDE:
1. Value Assessment: Fair price, over/under priced
2. Investment Potential: High/Medium/Low with brief reason
3. Key Recommendation: One actionable insight
FORMAT:
- Use bullet points
- Keep each property under 50 words
- Focus on actionable insights only
""",
)
return property_search_agent, market_analysis_agent, property_valuation_agent
def run_sequential_analysis(city, state, user_criteria, selected_websites, firecrawl_api_key, update_callback):
"""Run agents sequentially with manual coordination"""
# Initialize agents
llm = Ollama(id="gpt-oss:20b")
property_search_agent, market_analysis_agent, property_valuation_agent = create_sequential_agents(llm, user_criteria)
# Step 1: Property Search with Direct Firecrawl Integration
update_callback(0.2, "Searching properties...", "🔍 Property Search Agent: Finding properties...")
direct_agent = DirectFirecrawlAgent(
firecrawl_api_key=firecrawl_api_key,
model_id="gpt-oss:20b"
)
properties_data = direct_agent.find_properties_direct(
city=city,
state=state,
user_criteria=user_criteria,
selected_websites=selected_websites
)
if "error" in properties_data:
return f"Error in property search: {properties_data['error']}"
properties = properties_data.get('properties', [])
if not properties:
return "No properties found matching your criteria."
update_callback(0.4, "Properties found", f"✅ Found {len(properties)} properties")
# Step 2: Market Analysis
update_callback(0.5, "Analyzing market...", "📊 Market Analysis Agent: Analyzing market trends...")
market_analysis_prompt = f"""
Provide CONCISE market analysis for these properties:
PROPERTIES: {len(properties)} properties in {city}, {state}
BUDGET: {user_criteria.get('budget_range', 'Any')}
Give BRIEF insights on:
• Market condition (buyer's/seller's market)
• Key neighborhoods where properties are located
• Investment outlook (2-3 bullet points max)
Keep each section under 100 words. Use bullet points.
"""
market_result: RunOutput = market_analysis_agent.run(market_analysis_prompt)
market_analysis = market_result.content
update_callback(0.7, "Market analysis complete", "✅ Market analysis completed")
# Step 3: Property Valuation
update_callback(0.8, "Evaluating properties...", "💰 Property Valuation Agent: Evaluating properties...")
# Create detailed property list for valuation
properties_for_valuation = []
for i, prop in enumerate(properties, 1):
if isinstance(prop, dict):
prop_data = {
'number': i,
'address': prop.get('address', 'Address not available'),
'price': prop.get('price', 'Price not available'),
'property_type': prop.get('property_type', 'Type not available'),
'bedrooms': prop.get('bedrooms', 'Not specified'),
'bathrooms': prop.get('bathrooms', 'Not specified'),
'square_feet': prop.get('square_feet', 'Not specified')
}
else:
prop_data = {
'number': i,
'address': getattr(prop, 'address', 'Address not available'),
'price': getattr(prop, 'price', 'Price not available'),
'property_type': getattr(prop, 'property_type', 'Type not available'),
'bedrooms': getattr(prop, 'bedrooms', 'Not specified'),
'bathrooms': getattr(prop, 'bathrooms', 'Not specified'),
'square_feet': getattr(prop, 'square_feet', 'Not specified')
}
properties_for_valuation.append(prop_data)
valuation_prompt = f"""
Provide CONCISE property assessments for each property. Use the EXACT format shown below:
USER BUDGET: {user_criteria.get('budget_range', 'Any')}
PROPERTIES TO EVALUATE:
{json.dumps(properties_for_valuation, indent=2)}
For EACH property, provide assessment in this EXACT format:
**Property [NUMBER]: [ADDRESS]**
• Value: [Fair price/Over priced/Under priced] - [brief reason]
• Investment Potential: [High/Medium/Low] - [brief reason]
• Recommendation: [One actionable insight]
REQUIREMENTS:
- Start each assessment with "**Property [NUMBER]:**"
- Keep each property assessment under 50 words
- Analyze ALL {len(properties)} properties individually
- Use bullet points as shown
"""
valuation_result: RunOutput = property_valuation_agent.run(valuation_prompt)
property_valuations = valuation_result.content
update_callback(0.9, "Valuation complete", "✅ Property valuations completed")
# Step 4: Final Synthesis
update_callback(0.95, "Synthesizing results...", "🤖 Synthesizing final recommendations...")
# Debug: Check properties structure
print(f"Properties type: {type(properties)}")
print(f"Properties length: {len(properties)}")
if properties:
print(f"First property type: {type(properties[0])}")
print(f"First property: {properties[0]}")
# Format properties for better display
properties_display = ""
for i, prop in enumerate(properties, 1):
# Handle both dict and object access
if isinstance(prop, dict):
address = prop.get('address', 'Address not available')
price = prop.get('price', 'Price not available')
prop_type = prop.get('property_type', 'Type not available')
bedrooms = prop.get('bedrooms', 'Not specified')
bathrooms = prop.get('bathrooms', 'Not specified')
square_feet = prop.get('square_feet', 'Not specified')
agent_contact = prop.get('agent_contact', 'Contact not available')
description = prop.get('description', 'No description available')
listing_url = prop.get('listing_url', '#')
else:
# Handle object access
address = getattr(prop, 'address', 'Address not available')
price = getattr(prop, 'price', 'Price not available')
prop_type = getattr(prop, 'property_type', 'Type not available')
bedrooms = getattr(prop, 'bedrooms', 'Not specified')
bathrooms = getattr(prop, 'bathrooms', 'Not specified')
square_feet = getattr(prop, 'square_feet', 'Not specified')
agent_contact = getattr(prop, 'agent_contact', 'Contact not available')
description = getattr(prop, 'description', 'No description available')
listing_url = getattr(prop, 'listing_url', '#')
properties_display += f"""
### Property {i}: {address}
**Price:** {price}
**Type:** {prop_type}
**Bedrooms:** {bedrooms} | **Bathrooms:** {bathrooms}
**Square Feet:** {square_feet}
**Agent Contact:** {agent_contact}
**Description:** {description}
**Listing URL:** [View Property]({listing_url})
---
"""
final_synthesis = f"""
# 🏠 Property Listings Found
**Total Properties:** {len(properties)} properties matching your criteria
{properties_display}
---
# 📊 Market Analysis & Investment Insights
{market_analysis}
---
# 💰 Property Valuations & Recommendations
{property_valuations}
---
# 🔗 All Property Links
"""
# Extract and add property links
all_text = f"{json.dumps(properties, indent=2)} {market_analysis} {property_valuations}"
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', all_text)
if urls:
final_synthesis += "\n### Available Property Links:\n"
for i, url in enumerate(set(urls), 1):
final_synthesis += f"{i}. {url}\n"
update_callback(1.0, "Analysis complete", "🎉 Complete analysis ready!")
# Return structured data for better UI display
return {
'properties': properties,
'market_analysis': market_analysis,
'property_valuations': property_valuations,
'markdown_synthesis': final_synthesis,
'total_properties': len(properties)
}
def extract_property_valuation(property_valuations, property_number, property_address):
"""Extract valuation for a specific property from the full analysis"""
if not property_valuations:
return None
# Split by property sections - look for the formatted property headers
sections = property_valuations.split('**Property')
# Look for the specific property number
for section in sections:
if section.strip().startswith(f"{property_number}:"):
# Add back the "**Property" prefix and clean up
clean_section = f"**Property{section}".strip()
# Remove any extra asterisks at the end
clean_section = clean_section.replace('**', '**').replace('***', '**')
return clean_section
# Fallback: look for property number mentions in any format
all_sections = property_valuations.split('\n\n')
for section in all_sections:
if (f"Property {property_number}" in section or
f"#{property_number}" in section):
return section
# Last resort: try to match by address
for section in all_sections:
if any(word in section.lower() for word in property_address.lower().split()[:3] if len(word) > 2):
return section
# If no specific match found, return indication that analysis is not available
return f"**Property {property_number} Analysis**\n• Analysis: Individual assessment not available\n• Recommendation: Review general market analysis in the Market Analysis tab"
def display_properties_professionally(properties, market_analysis, property_valuations, total_properties):
"""Display properties in a clean, professional UI using Streamlit components"""
# Header with key metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Properties Found", total_properties)
with col2:
# Calculate average price
prices = []
for p in properties:
price_str = p.get('price', '') if isinstance(p, dict) else getattr(p, 'price', '')
if price_str and price_str != 'Price not available':
try:
price_num = ''.join(filter(str.isdigit, str(price_str)))
if price_num:
prices.append(int(price_num))
except:
pass
avg_price = f"${sum(prices) // len(prices):,}" if prices else "N/A"
st.metric("Average Price", avg_price)
with col3:
types = {}
for p in properties:
t = p.get('property_type', 'Unknown') if isinstance(p, dict) else getattr(p, 'property_type', 'Unknown')
types[t] = types.get(t, 0) + 1
most_common = max(types.items(), key=lambda x: x[1])[0] if types else "N/A"
st.metric("Most Common Type", most_common)
# Create tabs for different views
tab1, tab2, tab3 = st.tabs(["🏠 Properties", "📊 Market Analysis", "💰 Valuations"])
with tab1:
for i, prop in enumerate(properties, 1):
# Extract property data
data = {k: prop.get(k, '') if isinstance(prop, dict) else getattr(prop, k, '')
for k in ['address', 'price', 'property_type', 'bedrooms', 'bathrooms', 'square_feet', 'description', 'listing_url']}
with st.container():
# Property header with number and price
col1, col2 = st.columns([3, 1])
with col1:
st.subheader(f"#{i} 🏠 {data['address']}")
with col2:
st.metric("Price", data['price'])
# Property details with right-aligned button
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
st.markdown(f"**Type:** {data['property_type']}")
st.markdown(f"**Beds/Baths:** {data['bedrooms']}/{data['bathrooms']}")
st.markdown(f"**Area:** {data['square_feet']}")
with col2:
with st.expander("💰 Investment Analysis"):
# Extract property-specific valuation from the full analysis
property_valuation = extract_property_valuation(property_valuations, i, data['address'])
if property_valuation:
st.markdown(property_valuation)
else:
st.info("Investment analysis not available for this property")
with col3:
if data['listing_url'] and data['listing_url'] != '#':
st.markdown(
f"""
<div style="height: 100%; display: flex; align-items: center; justify-content: flex-end;">
<a href="{data['listing_url']}" target="_blank"
style="text-decoration: none; padding: 0.5rem 1rem;
background-color: #0066cc; color: white;
border-radius: 6px; font-size: 0.9em; font-weight: 500;">
Property Link
</a>
</div>
""",
unsafe_allow_html=True
)
st.divider()
with tab2:
st.subheader("📊 Market Analysis")
if market_analysis:
for section in market_analysis.split('\n\n'):
if section.strip():
st.markdown(section)
else:
st.info("No market analysis available")
with tab3:
st.subheader("💰 Investment Analysis")
if property_valuations:
for section in property_valuations.split('\n\n'):
if section.strip():
st.markdown(section)
else:
st.info("No valuation data available")
def main():
st.set_page_config(
page_title="Local AI Real Estate Agent Team",
page_icon="🏠",
layout="wide",
initial_sidebar_state="expanded"
)
# Clean header
st.title("🏠 Local AI Real Estate Agent Team")
st.caption("Find Your Dream Home with Local Ollama AI Agents")
# Sidebar configuration
with st.sidebar:
st.header("⚙️ Configuration")
# API Key inputs with validation
with st.expander("🔑 API Keys", expanded=True):
firecrawl_key = st.text_input(
"Firecrawl API Key",
value=DEFAULT_FIRECRAWL_API_KEY,
type="password",
help="Get your API key from https://firecrawl.dev",
placeholder="fc_..."
)
# Update environment variables
if firecrawl_key: os.environ["FIRECRAWL_API_KEY"] = firecrawl_key
# Ollama model info
st.info("🤖 Using Ollama model: gpt-oss:20b (local)")
st.markdown("Make sure Ollama is running with: `ollama run gpt-oss:20b`")
# Website selection
with st.expander("🌐 Search Sources", expanded=True):
st.markdown("**Select real estate websites to search:**")
available_websites = ["Zillow", "Realtor.com", "Trulia", "Homes.com"]
selected_websites = [site for site in available_websites if st.checkbox(site, value=site in ["Zillow", "Realtor.com"])]
if selected_websites:
st.markdown(f'✅ {len(selected_websites)} sources selected')
else:
st.markdown('⚠️ Please select at least one website')
# How it works
with st.expander("🤖 How It Works", expanded=False):
st.markdown("**🔍 Property Search Agent**")
st.markdown("Uses direct Firecrawl integration to find properties")
st.markdown("**📊 Market Analysis Agent**")
st.markdown("Analyzes market trends and neighborhood insights")
st.markdown("**💰 Property Valuation Agent**")
st.markdown("Evaluates properties and provides investment analysis")
# Main form
st.header("Your Property Requirements")
st.info("Please provide the location, budget, and property details to help us find your ideal home.")
with st.form("property_preferences"):
# Location and Budget Section
st.markdown("### 📍 Location & Budget")
col1, col2 = st.columns(2)
with col1:
city = st.text_input(
"🏙️ City",
placeholder="e.g., San Francisco",
help="Enter the city where you want to buy property"
)
state = st.text_input(
"🗺️ State/Province (optional)",
placeholder="e.g., CA",
help="Enter the state or province (optional)"
)
with col2:
min_price = st.number_input(
"💰 Minimum Price ($)",
min_value=0,
value=500000,
step=50000,
help="Your minimum budget for the property"
)
max_price = st.number_input(
"💰 Maximum Price ($)",
min_value=0,
value=1500000,
step=50000,
help="Your maximum budget for the property"
)
# Property Details Section
st.markdown("### 🏡 Property Details")
col1, col2, col3 = st.columns(3)
with col1:
property_type = st.selectbox(
"🏠 Property Type",
["Any", "House", "Condo", "Townhouse", "Apartment"],
help="Type of property you're looking for"
)
bedrooms = st.selectbox(
"🛏️ Bedrooms",
["Any", "1", "2", "3", "4", "5+"],
help="Number of bedrooms required"
)
with col2:
bathrooms = st.selectbox(
"🚿 Bathrooms",
["Any", "1", "1.5", "2", "2.5", "3", "3.5", "4+"],
help="Number of bathrooms required"
)
min_sqft = st.number_input(
"📏 Minimum Square Feet",
min_value=0,
value=1000,
step=100,
help="Minimum square footage required"
)
with col3:
timeline = st.selectbox(
"⏰ Timeline",
["Flexible", "1-3 months", "3-6 months", "6+ months"],
help="When do you plan to buy?"
)
urgency = st.selectbox(
"🚨 Urgency",
["Not urgent", "Somewhat urgent", "Very urgent"],
help="How urgent is your purchase?"
)
# Special Features
st.markdown("### ✨ Special Features")
special_features = st.text_area(
"🎯 Special Features & Requirements",
placeholder="e.g., Parking, Yard, View, Near public transport, Good schools, Walkable neighborhood, etc.",
help="Any specific features or requirements you're looking for"
)
# Submit button with custom styling
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
submitted = st.form_submit_button(
"🚀 Start Property Analysis",
type="primary",
use_container_width=True
)
# Process form submission
if submitted:
# Validate all required inputs
missing_items = []
if not firecrawl_key:
missing_items.append("Firecrawl API Key")
if not city:
missing_items.append("City")
if not selected_websites:
missing_items.append("At least one website selection")
if missing_items:
st.error(f"⚠️ Please provide: {', '.join(missing_items)}")
return
try:
user_criteria = {
'budget_range': f"${min_price:,} - ${max_price:,}",
'property_type': property_type,
'bedrooms': bedrooms,
'bathrooms': bathrooms,
'min_sqft': min_sqft,
'special_features': special_features if special_features else 'None specified'
}
except Exception as e:
st.error(f"❌ Error initializing: {str(e)}")
return
# Display progress
st.markdown("#### Property Analysis in Progress")
st.info("AI Agents are searching for your perfect home...")
status_container = st.container()
with status_container:
st.markdown("### 📊 Current Activity")
progress_bar = st.progress(0)
current_activity = st.empty()
def update_progress(progress, status, activity=None):
if activity:
progress_bar.progress(progress)
current_activity.text(activity)
try:
start_time = time.time()
update_progress(0.1, "Initializing...", "Starting sequential property analysis")
# Run sequential analysis with manual coordination
final_result = run_sequential_analysis(
city=city,
state=state,
| 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/agent_teams/ai_travel_planner_agent_team/backend/main.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/backend/main.py | from dotenv import load_dotenv
from loguru import logger
# Load environment variables
logger.info("Loading environment variables")
load_dotenv()
logger.info("Environment variables loaded")
# Import and setup logging configuration
from config.logger import setup_logging
# Configure logging with loguru
setup_logging(console_level="INFO")
from api.app import app
if __name__ == "__main__":
logger.info("Starting TripCraft AI API server")
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
| 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/agent_teams/ai_travel_planner_agent_team/backend/broswer.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/backend/broswer.py |
from config.logger import setup_logging
setup_logging(console_level="INFO")
from loguru import logger
logger.info("Starting the application")
logger.info("Loading environment variables")
from dotenv import load_dotenv
load_dotenv()
logger.info("Loaded environment variables")
logger.info("Loading agents")
from agents.flight import flight_search_agent
from agents.hotel import hotel_search_agent
logger.info("Loaded agents")
# structured_output_agent = Agent(
# name="Structured Output Generator",
# model=model2,
# instructions="Generate structured output in the specified schema format. Parse input data and format according to schema requirements. DO NOT include any other text in your response.",
# expected_output=dedent("""\
# A JSON object with the following fields:
# - status (str): Success or error status of the request (success or error)
# - message (str): Status message or error description
# - data: Object containing the flight results
# - flights: A list of flight results
# Each flight has the following fields:
# - flight_number (str): The flight number of the flight
# - price (str): The price of the flight
# - airline (str): The airline of the flight
# - departure_time (str): The departure time of the flight
# - arrival_time (str): The arrival time of the flight
# - duration (str): The duration of the flight
# - stops (int): The number of stops of the flight
# **DO NOT include any other text in your response.**
# }"""),
# markdown=True,
# show_tool_calls=True,
# debug_mode=True,
# response_model=FlightResults,
# )
# response = flight_search_agent.run("""
# Give me flights from Mumbai to Singapore for premium economy on 1 july 2025 for 2 adults and 1 child and sort by cheapest
# """)
# print(response.content)
response = hotel_search_agent.run("""
Give me hotels in Singapore for 2 adults and 1 child on 1 july 2025 to 10 july 2025 and sort by cheapest
""")
print(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_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/backend/travel_planning_team.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/backend/travel_planning_team.py | from fast_flights import FlightData, Passengers, Result, get_flights
result: Result = get_flights(
flight_data=[FlightData(date="2025-07-01", from_airport="BOM", to_airport="DEL")],
trip="one-way",
seat="economy",
passengers=Passengers(adults=2, children=1, infants_in_seat=0, infants_on_lap=0),
fetch_mode="fallback",
)
print(result)
# The price is currently... low/typical/high
print("The price is currently", result.flights)
| 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/agent_teams/ai_travel_planner_agent_team/backend/services/plan_service.py | advanced_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/backend/services/plan_service.py | from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from models.trip_db import TripPlanStatus, TripPlanOutput
from models.travel_plan import (
TravelPlanAgentRequest,
TravelPlanRequest,
TravelPlanTeamResponse,
)
from loguru import logger
from agents.team import trip_planning_team
import json
import time
from agents.structured_output import convert_to_model
from repository.trip_plan_repository import (
create_trip_plan_status,
update_trip_plan_status,
get_trip_plan_status,
create_trip_plan_output,
delete_trip_plan_outputs,
)
from agents.destination import destination_agent
from agents.itinerary import itinerary_agent
from agents.flight import flight_search_agent
from agents.hotel import hotel_search_agent
from agents.food import dining_agent
from agents.budget import budget_agent
def travel_request_to_markdown(data: TravelPlanRequest) -> str:
# Map of travel vibes to their descriptions
travel_vibes = {
"relaxing": "a peaceful retreat focused on wellness, spa experiences, and leisurely activities",
"adventure": "thrilling experiences including hiking, water sports, and adrenaline activities",
"romantic": "intimate experiences with private dining, couples activities, and scenic spots",
"cultural": "immersive experiences with local traditions, museums, and historical sites",
"food-focused": "culinary experiences including cooking classes, food tours, and local cuisine",
"nature": "outdoor experiences with national parks, wildlife, and scenic landscapes",
"photography": "photogenic locations with scenic viewpoints, cultural sites, and natural wonders",
}
# Map of travel styles to their descriptions
travel_styles = {
"backpacker": "budget-friendly accommodations, local transportation, and authentic experiences",
"comfort": "mid-range hotels, convenient transportation, and balanced comfort-value ratio",
"luxury": "premium accommodations, private transfers, and exclusive experiences",
"eco-conscious": "sustainable accommodations, eco-friendly activities, and responsible tourism",
}
# Map of pace levels (0-5) to their descriptions
pace_levels = {
0: "1-2 activities per day with plenty of free time and flexibility",
1: "2-3 activities per day with significant downtime between activities",
2: "3-4 activities per day with balanced activity and rest periods",
3: "4-5 activities per day with moderate breaks between activities",
4: "5-6 activities per day with minimal downtime",
5: "6+ activities per day with back-to-back scheduling",
}
def format_date(date_str: str, is_picker: bool) -> str:
if not date_str:
return "Not specified"
if is_picker:
try:
dt = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
return dt.strftime("%B %d, %Y")
except ValueError:
return date_str
return date_str.strip()
date_type = data.date_input_type
is_picker = date_type == "picker"
start_date = format_date(data.travel_dates.start, is_picker)
end_date = format_date(data.travel_dates.end, is_picker)
date_range = (
f"between {start_date} and {end_date}"
if end_date and end_date != "Not specified"
else start_date
)
vibes = data.vibes
vibes_descriptions = [travel_vibes.get(v, v) for v in vibes]
lines = [
f"# 🧳 Travel Plan Request",
"",
"## 📍 Trip Overview",
f"- **Traveler:** {data.name.title() if data.name else 'Unnamed Traveler'}",
f"- **Route:** {data.starting_location.title()} → {data.destination.title()}",
f"- **Duration:** {data.duration} days ({date_range})",
"",
"## 👥 Travel Group",
f"- **Group Size:** {data.adults} adults, {data.children} children",
f"- **Traveling With:** {data.traveling_with or 'Not specified'}",
f"- **Age Groups:** {', '.join(data.age_groups) or 'Not specified'}",
f"- **Rooms Needed:** {data.rooms or 'Not specified'}",
"",
"## 💰 Budget & Preferences",
f"- **Budget per person:** {data.budget} {data.budget_currency} ({'Flexible' if data.budget_flexible else 'Fixed'})",
f"- **Travel Style:** {travel_styles.get(data.travel_style, data.travel_style or 'Not specified')}",
f"- **Preferred Pace:** {', '.join([pace_levels.get(p, str(p)) for p in data.pace]) or 'Not specified'}",
"",
"## ✨ Trip Preferences",
]
if vibes_descriptions:
lines.append("- **Travel Vibes:**")
for vibe in vibes_descriptions:
lines.append(f" - {vibe}")
else:
lines.append("- **Travel Vibes:** Not specified")
if data.priorities:
lines.append(f"- **Top Priorities:** {', '.join(data.priorities)}")
if data.interests:
lines.append(f"- **Interests:** {data.interests}")
lines.extend(
[
"",
"## 🗺️ Destination Context",
f"- **Previous Visit:** {data.been_there_before.capitalize() if data.been_there_before else 'Not specified'}",
f"- **Loved Places:** {data.loved_places or 'Not specified'}",
f"- **Additional Notes:** {data.additional_info or 'Not specified'}",
]
)
return "\n".join(lines)
async def generate_travel_plan(request: TravelPlanAgentRequest) -> str:
"""Generate a travel plan based on the request and log status/output to database."""
trip_plan_id = request.trip_plan_id
logger.info(f"Generating travel plan for tripPlanId: {trip_plan_id}")
# Get or create status entry using repository functions
status_entry = await get_trip_plan_status(trip_plan_id)
if not status_entry:
status_entry = await create_trip_plan_status(
trip_plan_id=trip_plan_id, status="pending"
)
# Update status to processing
status_entry = await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Initializing travel plan generation",
started_at=datetime.now(timezone.utc),
)
try:
travel_request_md = travel_request_to_markdown(request.travel_plan)
logger.info(f"Travel request markdown: {travel_request_md}")
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Generating plan with TripCraft AI agents",
)
last_response_content = ""
time_start = time.time()
# Team Collaboration
# prompt = f"""
# Below is my travel plan request. Please generate a travel plan for the request.
# {travel_request_md}
# """
# time_start = time.time()
# ai_response = await trip_planning_team.arun(prompt)
# time_end = time.time()
# logger.info(f"AI team processing time: {time_end - time_start:.2f} seconds")
# last_response_content = ai_response.messages[-1].content
# logger.info(
# f"Last AI Response for conversion: {last_response_content[:500]}..."
# )
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Researching about the destination",
)
# Destination Research
destionation_research_response = await destination_agent.arun(
f"""
Please research about the destination {request.travel_plan.destination}
Below are user's travel request:
{travel_request_md}
Provide a very detailed research about the destination, its attractions, activities, and other relevant information that user might be interested in.
Give 10 attractions/activities that user might be interested in.
"""
)
logger.info(
f"Destination research response: {destionation_research_response.messages[-1].content}"
)
last_response_content = f"""
## Destination Attractions:
---
{destionation_research_response.messages[-1].content}
---
"""
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Searching for the best flights",
)
# Flight Search
flight_search_response = await flight_search_agent.arun(
f"""
Please find flights according to the user's travel request:
{travel_request_md}
If user has not specified the exact flight date, please consider it by yourself based on the user's travel request.
Provide a very detailed research about the flights, its price, duration, and other relevant information that user might be interested in.
Give top 5 flights.
"""
)
logger.info(
f"Flight search response: {flight_search_response.messages[-1].content}"
)
last_response_content += f"""
## Flight recommendations:
---
{flight_search_response.messages[-1].content}
---
"""
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Searching for the best hotels",
)
# Hotel Search
hotel_search_response = await hotel_search_agent.arun(
f"""
Please find hotels according to the user's travel request:
{travel_request_md}
If user has not specified the exact hotel dates, please consider it by yourself based on the user's travel request.
Provide a very detailed research about the hotels, its price, amenities, and other relevant information that user might be interested in.
Give top 5 hotels.
"""
)
last_response_content += f"""
## Hotel recommendations:
---
{hotel_search_response.messages[-1].content}
---
"""
logger.info(
f"Hotel search response: {hotel_search_response.messages[-1].content}"
)
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Searching for the best restaurants",
)
# Restaurant Search
restaurant_search_response = await dining_agent.arun(
f"""
Please find restaurants according to the user's travel request:
{travel_request_md}
If user has not specified the exact restaurant dates, please consider it by yourself based on the user's travel request.
Provide a very detailed research about the restaurants, its price, menu, and other relevant information that user might be interested in.
Give top 5 restaurants.
"""
)
last_response_content += f"""
## Restaurant recommendations:
---
{restaurant_search_response.messages[-1].content}
---
"""
logger.info(
f"Restaurant search response: {restaurant_search_response.messages[-1].content}"
)
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Creating the day-by-day itinerary",
)
# Itinerary
itinerary_response = await itinerary_agent.arun(
f"""
Please create a detailed day-by-day itinerary for a trip to {request.travel_plan.destination} for user's travel request:
{travel_request_md}
Based on the following information:
{last_response_content}
"""
)
logger.info(f"Itinerary response: {itinerary_response.messages[-1].content}")
last_response_content += f"""
## Day-by-day itinerary:
---
{itinerary_response.messages[-1].content}
---
"""
# Update status for AI team generation
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Optimizing the budget",
)
# Budget
budget_response = await budget_agent.arun(
f"""
Please optimize the budget according to the user's travel request:
{travel_request_md}
Based on the following information:
{last_response_content}
"""
)
logger.info(f"Budget response: {budget_response.messages[-1].content}")
time_end = time.time()
logger.info(f"Total time taken: {time_end - time_start:.2f} seconds")
# Update status for response conversion
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="processing",
current_step="Adding finishing touches",
)
json_response_output = await convert_to_model(
last_response_content, TravelPlanTeamResponse
)
logger.info(f"Converted Structured Response: {json_response_output[:500]}...")
# Delete any existing output entries for this trip plan
await delete_trip_plan_outputs(trip_plan_id=trip_plan_id)
final_response = json.dumps(
{
"itinerary": json_response_output,
"budget_agent_response": budget_response.messages[-1].content,
"destination_agent_response": destionation_research_response.messages[
-1
].content,
"flight_agent_response": flight_search_response.messages[-1].content,
"hotel_agent_response": hotel_search_response.messages[-1].content,
"restaurant_agent_response": restaurant_search_response.messages[
-1
].content,
"itinerary_agent_response": itinerary_response.messages[-1].content,
},
indent=2,
)
# Create new output entry
await create_trip_plan_output(
trip_plan_id=trip_plan_id,
itinerary=final_response,
summary="",
)
# Update status to completed
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="completed",
current_step="Plan generated and saved",
completed_at=datetime.now(timezone.utc),
)
return final_response
except Exception as e:
logger.error(
f"Error generating travel plan for {trip_plan_id}: {str(e)}", exc_info=True
)
# Update status to failed
await update_trip_plan_status(
trip_plan_id=trip_plan_id,
status="failed",
error=str(e),
completed_at=datetime.now(timezone.utc),
)
raise
| python | Apache-2.0 | 44efabeac69a8bd1f7cfbf8fddd8fde5ce32b335 | 2026-01-04T14:38:15.481187Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.