File size: 2,095 Bytes
52cdd17
508ee70
 
52cdd17
508ee70
 
52cdd17
508ee70
 
 
 
52cdd17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508ee70
 
 
 
 
 
 
52cdd17
508ee70
 
 
 
 
 
 
 
 
52cdd17
508ee70
52cdd17
 
 
508ee70
52cdd17
508ee70
 
52cdd17
508ee70
 
 
52cdd17
508ee70
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain_community.utilities import GoogleSerperAPIWrapper
import os

def generate_script(prompt, video_length, creativity, openai_api_key, serper_api_key):
    """
    Generate a YouTube video title and script based on the provided prompt, duration, and creativity level.
    """

    # Ensure the OpenAI API key is set
    if not openai_api_key:
        raise ValueError("OpenAI API Key is missing.")
    os.environ["OPENAI_API_KEY"] = openai_api_key

    # Ensure the Serper API key is set
    if not serper_api_key:
        raise ValueError("Serper API Key is missing.")
    os.environ["SERPER_API_KEY"] = serper_api_key

    # Initialize the LLM
    llm = ChatOpenAI(
        model='gpt-4o-mini',
        temperature=creativity,
        max_tokens=None,
        timeout=None,
        max_retries=2
    )

    # Define the title generation prompt
    title_template = PromptTemplate(
        input_variables=["topic"],
        template="Generate a YouTube video title for the topic '{topic}'."
    )
    title_chain = LLMChain(llm=llm, prompt=title_template, verbose=False)

    # Define the script generation prompt
    script_template = PromptTemplate(
        input_variables=["title", "duration", "search_data"],
        template=(
            "Create a YouTube script with the title '{title}' that lasts approximately {duration} minutes. "
            "Incorporate the following research information: {search_data}."
        )
    )
    script_chain = LLMChain(llm=llm, prompt=script_template, verbose=False)

    # Fetch relevant search data using Google Serper
    search_tool = GoogleSerperAPIWrapper()
    search_data = search_tool.results(prompt)

    # Generate the video title ONCE
    title = title_chain.run({"topic": prompt})

    # Generate the video script using the title
    script = script_chain.run({
        "title": title,
        "duration": video_length,
        "search_data": search_data,
    })

    return title, script, search_data