# Build an AI YouTube Script Generator That Analyzes Top Performing Videos

Build an AI YouTube script generator that analyzes top-performing videos and uses their transcripts to draft a script.

Author: Vladislav Guzey
Published: 2026-10-21
Canonical: https://proflead.dev/posts/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/


*Sponsored by SearchApi*

I create content on YouTube and research part always takes more time. I usually search YouTube for the topic and look at videos that are doing well, before I start writing a script.

I want to know:

- What topics do they cover?
    
- How is the video structured?
    
- What examples do they use?
    
- What do several successful videos have in common?
    
- What did they miss?
    

There are a lot of paid AI tools that can help with YouTube research and script generation.

I don’t want another subscription. I wanted to see how much of this I can build myself using Python.

The idea: **Topic -> YouTube Search -> Top Videos -> Transcripts -> Analysis -> Original Script**

I will use [SearchApi](https://www.searchapi.io/?utm_source=dev&utm_medium=ambassador&utm_campaign=proflead.dev) to find relevant YouTube videos. Then I will  retrieve their transcripts and use the ChatGPT API to analyze them before generating my own video script.

I do not want to download competitor transcripts and ask AI to rewrite it. The main idea is to look across several videos, understand what works and use those findings to plan my script.

## Before We Start

We need:

- Python
    
- a [SearchApi API key](https://www.searchapi.io/?utm_source=dev&utm_medium=ambassador&utm_campaign=proflead.dev)
    
- an OpenAI API key
    

First, install the packages:

```bash
pip install requests openai python-dotenv
```
  

Then go to [SearchApi](https://www.searchapi.io/?utm_source=dev&utm_medium=ambassador&utm_campaign=proflead.dev) website, register there, and get an API key.

![SearchApi website, register there, and get an API key](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-6.png)

Then create a `.env` file:

```python
SEARCHAPI_API_KEY="your_searchapi_key"
OPENAI_API_KEY="your_openai_key"
```
  

My Python file will be called:
```bash
youtube_script_generator.py
```
  

We will be using SearchApi YouTube endpoints.
![SearchApi YouTube endpoints](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-5.png)

Start with the imports and configuration:

```python
import os
import requests

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()


SEARCHAPI_API_KEY = os.getenv("SEARCHAPI_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

if not SEARCHAPI_API_KEY:
    raise ValueError("SEARCHAPI_API_KEY is missing")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is missing")

SEARCHAPI_URL = "https://www.searchapi.io/api/v1/search"
OPENAI_MODEL = "gpt-5.5"
openai_client = OpenAI(api_key=OPENAI_API_KEY)
```

Keep the model name in one variable so you can easily replace it later.

All the code after this point goes into the same youtube_script_generator.py file. Simply keep adding each function below the previous code.

First, let’s add a helper function for SearchApi requests:

```python
def searchapi_request(params):
    response = requests.get(
        SEARCHAPI_URL,
        params=params,
        headers={
            "Authorization": f"Bearer {SEARCHAPI_API_KEY}"
        },
        timeout=60,
    )


    response.raise_for_status()
    data = response.json()

    if "error" in data:
        raise RuntimeError(data["error"])

    return data
```

This keeps the rest of the code cleaner, because we do not need to repeat the request and authentication part every time.

So, at this point, I only have two files:
```bash
.env
youtube_script_generator.py
```

The `.env` file contains my API keys, while all the Python code in `youtube_script_generator.py`.

## Find Top YouTube Videos

Let's say I am planning a YouTube video about:

```bash
how to build an AI agent in Python
```

I can send that topic to an LLM and ask it to write a script, but that skips the research part that I would normally do before writing a script.

So instead, let’s first search what is on YouTube.

SearchApi has a YouTube Search API that gives us normal YouTube search results together with useful data such as the video ID, title, position, channel, publish time, view count, etc.

I add this function below the previous code:

```python
def search_youtube(topic):
    data = searchapi_request({
        "engine": "youtube",
        "q": topic,
    })

    return data.get("videos", [])
```

Now I can search for my topic:

```python
videos = search_youtube(
    "how to build an AI agent in Python"
)
```

At this point, we have a list of videos related to our topic.

### Which Videos Should We Analyze?

I don't want to analyze every result because that will make the project slower,  and more expensive because we will spend more API credits. I only want three examples.

So I use a very simple rule: Take the first 10 relevant search results and prioritize the ones with the most views.

Here is the function:

```python
def get_view_count(video):
    # SearchAPI may return an already extracted numeric value
    extracted = video.get("extracted_views")

    if isinstance(extracted, (int, float)):
        return int(extracted)

    # Fall back to the regular views field
    views = video.get("views")

    if isinstance(views, (int, float)):
        return int(views)

    if not isinstance(views, str):
        return 0

    text = (
        views.lower()
        .replace(",", "")
        .replace("views", "")
        .strip()
    )

    multiplier = 1

    if text.endswith("k"):
        multiplier = 1_000
        text = text[:-1]
    elif text.endswith("m"):
        multiplier = 1_000_000
        text = text[:-1]
    elif text.endswith("b"):
        multiplier = 1_000_000_000
        text = text[:-1]

    try:
        return int(float(text) * multiplier)
    except ValueError:
        return 0

def pick_top_videos(videos, limit=6):
    candidates = [
        video
        for video in videos[:10]
        if video.get("id") and not video.get("live")
    ]

    candidates.sort(
      key=get_view_count,
      reverse=True,
    )

    return candidates[:limit]
```

The function returns six videos even though we only want to analyze three. The reason is that some videos may not have a transcript available. If one doesn't work, I can move to the next result.

![SearchApi ](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-3.png)

It’s simple rules and for our use case, we just need a small group of relevant videos that already have some evidence of interest.

Later, we can make this smarter by adding things such as upload date or views per day. For now, let’s keep the logic simple.

## How to Get the Video Transcripts

At this point we know which videos we want to inspect. The next problem is getting the actual content. SearchApi has a YouTube Transcripts API, so we can use the video ID from the search results and retrieve the transcript.

![How to Get the Video Transcripts ](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-1.png)

Let’s add this functionto the code:

```python
def get_transcript(video_id):
    data = searchapi_request({
        "engine": "youtube_transcripts",
        "video_id": video_id,
        "lang": "en",
        "only_available": "true",

    })

    segments = data.get("transcripts", [])

    if not segments:
        return ""

    lines = []

    for segment in segments:
        start = int(segment.get("start", 0))
        text = segment.get("text", "").strip()

        if text:
            lines.append(f"[{start}s] {text}")


    return "\n".join(lines)

```

We keep the timestamps instead of turning the transcript into one giant paragraph. 

```bash
[0s] Today I'm going to show you...
[8s] By the end of this video...
[24s] First, let's look at...
```

It’s important because we want LLM to understand what happens during, for example, the first 30 seconds of the video because that is usually where the hook is.

Now, let’s collect three videos with usable transcripts:

  
```python
def collect_videos_with_transcripts(candidates, limit=3):
    results = []

    for video in candidates:
        try:
            transcript = get_transcript(video["id"])
        except Exception as error:
            print(
                f"Skipping {video['title']}: {error}"
            )
            continue
  
        if not transcript:
            continue

        video["transcript"] = transcript
        results.append(video)
  
        if len(results) == limit:
            break

    return results
```
## Analyze What Works

This is the most important part. I could send each transcript to an LLM and ask it to summarize this video. But it won’t be enough. We want to understand why the video performs well. It would also be nice to know what happens at the beginning and end of the video, and to understand the structure and potential gaps.

Now, let’s create a small helper for the LLM:

```python
def ask_ai(prompt):
    response = openai_client.responses.create(
        model=OPENAI_MODEL,
        input=prompt,
    )

    return response.output_text
```

Then build the research prompt:

```python
MAX_TRANSCRIPT_CHARS = 30000

def analyze_videos(topic, videos):
    video_blocks = []

    for index, video in enumerate(videos, start=1):
        transcript = video["transcript"][
            :MAX_TRANSCRIPT_CHARS
        ]
        video_blocks.append(
            f"""
          VIDEO {index}

          Title: {video.get("title")}

          Views: {get_view_count(video)}

          Published: {video.get("published_time", "Unknown")}


          Transcript:

          {transcript}

          """

        )

    research_data = "\n\n".join(video_blocks)

    prompt = f"""

You are helping me research successful YouTube videos

before I write my own video.
My topic:

{topic}

  

Below are transcripts from relevant, strong-performing

videos about this topic.

  

{research_data}

  

Analyze them as a group.

  

I do NOT want you to rewrite or copy these videos.

  

Create a concise content research brief with these sections:

  

1. HOOKS

Explain how the videos get attention in the first

30-60 seconds. Find common patterns.

  

2. COMMON STRUCTURE

Show the common way these videos organize the topic.

  

3. KEY TOPICS

List the important ideas that appear across multiple

videos.

  

4. WHAT WORKS

Identify useful patterns in examples, explanations,

demos, pacing, or presentation.

  

5. CONTENT GAPS

Find useful questions, problems, or angles that the

videos do not explain well.

  

6. RECOMMENDED VIDEO

Create a short brief for my new original video:

- recommended hook

- must-cover topics

- differentiating angle

- suggested section order

  

Keep the analysis practical and specific.

Do not copy sentences from the transcripts.

"""

  

    return ask_ai(prompt)
```
Another important thing: we need to analyze the video transcripts together. We do not care about getting three separate summaries, we want to see patterns and gaps.

![Research example](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-4.png)

After this step, we should have a possible angle for our own script

### Why I Limit Transcript Size

I limit every transcript to:

```python
MAX_TRANSCRIPT_CHARS = 30000
```

I am doing this mostly to avoid sending unnecessarily large prompts, but you definitely can increase it based on your niche and needs.

## Let’s Generate a Script

After the research is finished, we can generate the actual script. 

Use this function so:

```python
def generate_script(topic, research):

    prompt = f"""

Write an original YouTube script for me about:

  

{topic}

  

Use this competitor research as planning input:

  

{research}

  

Requirements:

  

- Write an original script. Do not copy wording from

  competitors.

- Start with a strong, short hook.

- Get to the useful content quickly.

- Use simple, natural language.

- Cover the important topics found in the research.

- Use relevant content gaps to make the video more useful.

- Keep the structure easy to follow.

- Avoid generic filler and unnecessary hype.

- Target roughly 1,200 to 1,500 words.

- Finish with a short natural conclusion and CTA.

  

Return only the finished script.

"""

  

    return ask_ai(prompt)
```

![Script example](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-2.png)

You can change these instructions to match your own style.


## Put Everything Together

Now we have every part to complete the code.

Add this at the bottom of the same youtube_script_generator.py file:

```python
def main():

    topic = input(

        "What YouTube video do you want to create? "

    ).strip()

  

    if not topic:

        print("Please enter a topic.")

        return

  

    print("\nSearching YouTube...")

  

    search_results = search_youtube(topic)

  

    if not search_results:

        print("No YouTube videos found.")

        return

  

    candidates = pick_top_videos(search_results)

  

    print("\nGetting transcripts...")

  

    videos = collect_videos_with_transcripts(

        candidates,

        limit=3,

    )

  

    if not videos:

        print("Could not find usable transcripts.")

        return

  

    print("\nVideos selected for research:")

  

    for video in videos:

        print(

            f"- {video['title']} "

            f"({get_view_count(video):,} views)"

        )

  
  

    print("\nAnalyzing videos...")

  

    research = analyze_videos(topic, videos)

  

    with open(

        "research.md",

        "w",

        encoding="utf-8",

    ) as file:

        file.write(research)

  

    print("\nGenerating script...")

  

    script = generate_script(topic, research)

  

    with open(

        "script.md",

        "w",

        encoding="utf-8",

    ) as file:

        file.write(script)

  

    print("\nDone.")

    print("Research saved to research.md")

    print("Script saved to script.md")

  
  

if __name__ == "__main__":

    main()

```

Then run it:

```bash

python youtube_script_generator.py
```

And enter the topic:
```bash

What YouTube video do you want to create?

> how to build an AI agent in Python
```
  

So the project will then look like this:
```bash

.env

youtube_script_generator.py

research.md

script.md
```

Now you can run the script. It will create `research.md` and `script.md` files.

`research.md `shows you what the model discovered before producing the script.

Then `script.md` contains the final script. It doesn’t mean you have to use it without polishing, but it’s a great starting point and your first draft.

There are plenty of ways you can improve the script further. You can start editing instructions, add more videos to your research, and so on.

You can download this project from my [GitHub - YouTube Script Generator](https://github.com/proflead/youtube-script-generator), and if you have any questions, please feel free to reach out.

![GitHub Repository](/assets/blog/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos/build-an-ai-youtube-script-generator-that-analyzes-top-performing-videos-7.png)

If you want to try SearchApi and my code in action, [sign up today and get 100 free searches](https://www.searchapi.io/users/sign_up?utm_source=dev&utm_medium=ambassador&utm_campaign=proflead.dev).

Give it a shot and share feedback with me in the comments below if you found it useful. And if you want to see more tutorials like this, let me know.

Cheers, proflead! ;)
