youtube_trends / src /llm_service.py
molehh's picture
created project
eec3758
import os
import json
from openai import OpenAI
from dotenv import load_dotenv
from pytube import Search
from query import sql_query_agent
from tools import TOOLS
from pytube import Search, YouTube
DOWNLOAD_FOLDER = "downloads"
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
# Load environment variables
load_dotenv()
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def chat_with_groq(user_input):
"""
Processes user input using OpenAI API and executes tools when needed.
Args:
user_input (str): The user's query.
Returns:
str: Response from the chatbot.
"""
try:
# Initial system message with schema
messages = [
{
"role": "system",
"content": """
You are a helpful assistant specializing in the Youtube video songs dataset. Provide accurate and relevant responses within this domain.
Schema: youtube
Columns: video_id (text), category_name (text), category_id (int), likes (numeric),
Popularity (bigint), Danceability (double), Energy (double), etc.
"""
},
{"role": "user", "content": user_input}
]
# First API call to determine if tools are needed
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=TOOLS,
tool_choice="auto"
)
choice = response.choices[0]
tool_calls = getattr(choice.message, 'tool_calls', None)
message_content = getattr(choice.message, 'content', None)
if tool_calls:
messages.append(choice.message) # Add the assistant's tool-calling message
for tool_call in tool_calls:
func_name = tool_call.function.name
json_args = json.loads(tool_call.function.arguments)
if func_name == "sql_query_agent":
sql_response = sql_query_agent(json_args.get("query"))
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": sql_response
})
elif func_name == "download_youtube_videos":
download_response = download_youtube_videos(json_args.get("video_id"))
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": download_response
})
# Second API call to interpret tool results
second_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return second_response.choices[0].message.content.strip()
# Fallback for no tool calls
if message_content:
return message_content.strip()
return "I'm sorry, I couldn't process your request."
except Exception as e:
print(f"Error in chat_with_groq: {e}")
return f"⚠️ Error: {str(e)}"
def download_youtube_videos(video_ids: list):
"""Searches and downloads YouTube videos by name."""
downloaded = []
for video_id in video_ids:
print(f"πŸ” Searching for: {video_id}...")
try:
# Search for the video
search = Search(video_id)
if search.results:
video = search.results[0] # Get the first result
video_url = video.watch_url
print(f"βœ… Found: {video.title} ({video_url})")
# Download the video
yt = YouTube(video_url)
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by(
"resolution").desc().first()
if stream:
print(f"⬇️ Downloading: {video.title}...")
stream.download(DOWNLOAD_FOLDER)
downloaded.append(video.title)
print(f"βœ”οΈ Downloaded: {video.title}")
else:
print(f"❌ No valid stream for: {video_id}")
else:
print(f"❌ No results for: {video_id}")
except Exception as e:
print(f"⚠️ Error downloading {video_id}: {e}")
if downloaded:
print(f"\nπŸŽ‰ Downloaded: {', '.join(downloaded)}")
else:
print("\n❌ No videos were downloaded.")
x = chat_with_groq("download Psycho Villa II Ep 1 The Family II Comedy Video II")
print(x)