import os from langchain_google_genai import ChatGoogleGenerativeAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from serpapi import GoogleSearch def generate_script(prompt, video_length, creativity, serpapi_key): # Setup Gemini using the provided API key chat = ChatGoogleGenerativeAI( model="gemini-1.5-flash", google_api_key=serpapi_key # This key is for SerpAPI, not Google API ) # Prompt template for generating video title title_template = PromptTemplate( input_variables=["topic"], template="Generate a YouTube video title based on the following topic: {topic}" ) title_chain = LLMChain(llm=chat, prompt=title_template, verbose=True) # Prompt template for generating video script script_template = PromptTemplate( input_variables=["title", "duration", "search_data"], template="Create a YouTube script with the title '{title}' that lasts {duration} minutes. Use the following search data: {search_data}" ) script_chain = LLMChain(llm=chat, prompt=script_template, verbose=True) # Get search data from Google Search using SerpAPI search_data = None try: search = GoogleSearch({"q": prompt, "api_key": serpapi_key}) # Pass SerpAPI key here results = search.get_dict() # Fetch the search results search_data = results['organic_results'] # You can modify this to include specific data if needed except Exception as e: print(f"Error fetching search results: {e}") # If no search data is retrieved, handle the error if not search_data: raise Exception("Failed to fetch search data from Google Search.") # Generate the title title = title_chain.run({"topic": prompt}) # Generate the script script = script_chain.run({ "title": title, "duration": video_length, "search_data": search_data }) return title, script, search_data