<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anum Mujahid on Medium]]></title>
        <description><![CDATA[Stories by Anum Mujahid on Medium]]></description>
        <link>https://medium.com/@anummujahid?source=rss-bdff01cc6cff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_aRYzlfe7Uwj0Jezm85DjQ.jpeg</url>
            <title>Stories by Anum Mujahid on Medium</title>
            <link>https://medium.com/@anummujahid?source=rss-bdff01cc6cff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:27:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anummujahid/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build GenAI Chatbot for YouTube Videos]]></title>
            <link>https://medium.com/@anummujahid/build-genai-chatbot-for-youtube-videos-6b73dc940662?source=rss-bdff01cc6cff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b73dc940662</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Anum Mujahid]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 12:01:06 GMT</pubDate>
            <atom:updated>2024-04-17T12:01:06.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Ready to make your YouTube videos even more awesome? Let’s learn how to build a special chatbot that can actually “talk” to them! We’ll use Pinecone, HuggingFace Embeddings, LangChain and Llama 2 to create our chatbot that understands what videos are about. This is a fun way to learn about Generative AI and make your YouTube experience way more interactive. Let’s get started!</p><h3>Outline</h3><ol><li>Project Stack</li><li>Install Dependencies</li><li>Fetch Video Transcript</li><li>Split Text into Smaller Chunks</li><li>Setup and Generate Embeddings</li><li>Setup Pinecone</li><li>Store Embeddings in Pinecone</li><li>Setup LLm and Text Generation Pipeline</li><li>Setup Prompt Template</li><li>Create RetrievalQA Chain</li><li>Test the Chatbot</li></ol><h3>Project Stack</h3><p>We will be using the following tools create this Generative AI based video chatbot:</p><ol><li>YouTube Transcript API</li><li>Recursive Text Splitter</li><li>HuggingFace Embeddings</li><li>Bge-base-en</li><li>Pinecone</li><li>Llama-2</li><li>LangChain</li></ol><h3>Install Dependencies</h3><p>To get started, we need to install a few dependencies. These will help us work with videos and use Llama 2 and Pinecone.</p><pre>!pip install youtube-transcript-api bitsandbytes accelerate transformers langchain pinecone-client auto-gptq</pre><p>Also install this FlagEmbedding, it is needed to use bge-base-en model.</p><pre>!pip install -U FlagEmbedding</pre><h3>Fetch Video Transcript</h3><p>We will use <em>youtube_transcript_api</em> to download and extract the transcript (subtitles) from the YouTube video.</p><pre>from youtube_transcript_api import YouTubeTranscriptApi<br><br>def get_transcript(video_url):<br>  video_id = video_url.split(&quot;=&quot;)[1]<br>  yt = YouTubeTranscriptApi()<br><br>  try:<br>    transcript = yt.get_transcript(video_id)<br>  except:<br>    print(f&quot;Error: Could not retrieve transcript for video: {video_url}&quot;)<br>    return []<br><br>  return transcript<br><br>video_url = &quot;https://www.youtube.com/watch?v=h1voCMAT9Qc&quot;  # Replace with your desired video URL<br>transcript = get_transcript(video_url)<br><br>if transcript:<br>  for segment in transcript:<br>    print(f&quot;Text: {segment[&#39;text&#39;]}&quot;)<br>    print(f&quot;Start time: {segment[&#39;start&#39;]} seconds&quot;)<br>    print(f&quot;Duration: {segment[&#39;duration&#39;]} seconds&quot;)<br>    print(&quot;---&quot;)<br>else:<br>  print(&quot;No transcript found for the provided video URL.&quot;)</pre><p>Then we will clean and format the raw transcript. We will convert text to lowercase and removes any extra spaces within the text, ensuring consistent formatting.</p><pre>sentences = []<br>for segment in transcript:<br>    text = segment[&quot;text&quot;].lower()<br>    text = &quot; &quot;.join([word for word in text.split()])<br>    sentences.append(text)<br><br>paragraph = &quot;\n&quot;.join(sentences)<br>print(paragraph)</pre><h3>Split Text into Smaller Chunks</h3><p>Often, video transcripts can be lengthy. To make it easier for our chatbot to process information and provide accurate answers, we’ll divide the transcript into smaller, more manageable chunks. This technique also helps reduce the number of tokens (units of text) the AI model needs to process at once, making it work faster.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.document_loaders import TextLoader<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size = 2000, chunk_overlap = 200)<br>texts = text_splitter.split_text(paragraph)<br><br>print(len(texts)) # Display number of chunks</pre><p><em>RecursiveCharacterTextSplitter</em> from <em>LangChain</em> is used to split the text in <em>chunk_size</em> of 2000 charcaters and the <em>chunk_overlap</em> parameter ensures a small overlap between chunks. This prevents information from being lost at the edges of each chunk.</p><h3>Setup and Generate Embeddings</h3><p><a href="https://huggingface.co/blog/getting-started-with-embeddings">Embeddings</a> are numerical representations of a piece of information e.g. text. Embeddings will help our AI model understand the meaning behind the words in the transcript. We use the <em>HuggingFaceBgeEmbeddings</em> class from <em>LangChain</em> to easily generate these embeddings, relying on &#39;<a href="https://huggingface.co/BAAI/bge-base-en">BAAI/bge-base-en</a>&#39; model.</p><pre>from langchain.embeddings import HuggingFaceBgeEmbeddings<br><br>model_name = &#39;BAAI/bge-base-en&#39;<br>encode_kwargs = {&#39;normalize_embeddings&#39; : True}<br><br>embeddings = HuggingFaceBgeEmbeddings(model_name=model_name, model_kwargs={&#39;device&#39;: &#39;cpu&#39;}, encode_kwargs=encode_kwargs)</pre><p>We can check the dimensions of the embeddings vector as follows:</p><pre>check = embeddings.embed_query(&quot;youtube video chatbot&quot;)<br>print(len(check))</pre><h3>Setup Pinecone</h3><p>To make similarity based search on our embeddings, we’ll use Pinecone, a vector database designed to store and search through embeddings. Think of it as a super-organized library for the AI’s understanding of the video content.</p><p>Create your account on <a href="https://www.pinecone.io/">Pinecone</a> and it will take you to the dashboard. Click on the <em>Create Index</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcBYrDxMJz27b3revsy4JA.png" /></figure><p>Input a name for your index and enter the vector dimensions. Then click on <em>Create Index </em>button<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMKaphxORI_pgXX-dZExGw.png" /></figure><p>We will need the “<em>Environment”</em> from the created index to setup a connection with Pinecone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sWJKr3wfttIFHEO_J36lA.png" /></figure><p>As well as we will need the “<em>API key”</em> to establish a connection with Pinecone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2u2u7mJj5ExysSggrJa8eA.png" /></figure><p>Now create the following environment variables and store your Pinecone API key, index environment and index name in them:</p><pre>PINECONE_API_KEY = &#39;&#39;<br>PINECONE_ENV = &#39;&#39;<br>INDEX_NAME = &#39;&#39;</pre><pre>import os<br>os.environ[&#39;PINECONE_API_KEY&#39;] = PINECONE_API_KEY</pre><p>Next we will establish the link to the Pinecone using the API key and environment.</p><pre>from langchain.vectorstores import Pinecone<br><br>from pinecone import Pinecone as PC<br>PC(<br>    api_key = PINECONE_API_KEY,<br>    environment = PINECONE_ENV<br>)</pre><h3>Store Embeddings in Pinecone</h3><p>Next we will take the text chunks and create their corresponding embeddings, then upload them into the Pinecone vector database. This makes the video content easily searchable.</p><pre>index_name=INDEX_NAME<br>text_embed = Pinecone.from_texts([text for text in texts], embeddings, index_name=index_name)</pre><h3>Setup LLM and Text Generation Pipeline</h3><p>Next we will load the quantized version of the Llama 2 7B language model. Quantization makes the model smaller and faster, allowing it to run more efficiently.</p><pre>from auto_gptq import AutoGPTQForCausalLM<br>from transformers import AutoTokenizer<br><br>model_name = &quot;TheBloke/Llama-2-7b-Chat-GPTQ&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)<br>model = AutoGPTQForCausalLM.from_quantized(<br>    model_name,<br>    use_safetensors=True,<br>    trust_remote_code=True,<br>    inject_fused_attention=False,<br>    device=&#39;cuda:0&#39;,<br>    quantize_config=None,<br>)</pre><p>Next we will setup <a href="https://huggingface.co/docs/transformers/generation_strategies">TextStreamer</a> along with the text generation pipeline to stream the output on the screen one word at a time.</p><pre>from transformers import pipeline, TextStreamer<br>from langchain import HuggingFacePipeline<br><br>streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)<br>text_pipeline = pipeline(<br>    &quot;text-generation&quot;,<br>    model=model,<br>    tokenizer=tokenizer,<br>    max_new_tokens=1024,<br>    temperature=0.4,<br>    top_p=0.95,<br>    repetition_penalty=1.1,<br>    streamer=streamer,<br>    do_sample=True<br>)<br><br>llm = HuggingFacePipeline(pipeline=text_pipeline, model_kwargs={&quot;temperature&quot;: 0})</pre><h3>Setup Prompt Template</h3><p>We will use the following prompt template including the system prompt to ask questions regarding our video using our LLM model.</p><pre>B_INST, E_INST = &quot;[INST]&quot;, &quot;[/INST]&quot;<br>B_SYS, E_SYS = &quot;&lt;&lt;SYS&gt;&gt;\n&quot;, &quot;\n&lt;&lt;/SYS&gt;&gt;\n\n&quot;<br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a helpful and informative assistant. Your primary goal is to provide clear and accurate responses to questions, ensuring your answers are always safe, respectful, and free of harmful biases. Prioritize clarity and understanding in your communication. <br>If a question is unclear or doesn&#39;t make sense, politely ask for clarification or acknowledge that you don&#39;t understand.  Never share false information – always prioritize truthfulness and accuracy.&quot;&quot;&quot;<br>instruction = &quot;&quot;&quot;CONTEXT:\n\n {context}\nQuestion: {question}&quot;&quot;&quot;<br>prompt_template = B_INST + B_SYS + SYSTEM_PROMPT + E_SYS + instruction + E_INST</pre><p><em>PromptTemplate</em> class from the <em>Langchain</em> library provides a way to create reusable question-answering formats.</p><pre>from langchain import PromptTemplate<br>prompt = PromptTemplate(template=prompt_template, input_variables=[&quot;context&quot;, &quot;question&quot;])</pre><h3>Create RetrievalQA Chain</h3><p>In the RetrievalQA chain a question is provided as input. A retriever searches through relevant documents to find passages that might contain the answer. A language model (LLM) processes the retrieved passages and the question to generate the final answer.</p><p>Using the RetrievalQA chain we combine the components of our chatbor. It connects the language model (<em>llm</em>), the Pinecone database where you stored the video information (<em>text_embed.as_retriever</em>), and the question-answering template (<em>prompt</em>) we created earlier. Think of this step as creating the brain of your chatbot, where it learns to search for relevant information and generate answers.</p><pre>from langchain.chains import RetrievalQA<br><br>qa_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;,<br>    retriever=text_embed.as_retriever(search_kwargs={&quot;k&quot;:5}),<br>    chain_type_kwargs={&quot;prompt&quot;: prompt},<br>    return_source_documents=True<br>)</pre><h3>Test the Chatbot</h3><p>Now we can test our chatbot and ask it questions related to our video and see how it performs.</p><pre>query = &quot;What does Chris say about business decisions?&quot;<br>llm_response = qa_chain(query)<br>print(llm_response[&#39;result&#39;])</pre><p>And here is the output I got:</p><pre>Chris suggests finding the right market as crucial to closing deals successfully. Large organizations often have multiple layers of management, making it challenging to reach the decision-maker directly. Instead, focus on getting as close as possible to the decision-maker or influencers within the organization. When working with large companies, it&#39;s essential to understand their long-term relationships, brand vs. personal, and market needs. Finding the right market can help communicate value effectively, but it may also indicate a lack of clarity regarding the market and its willingness to invest. In terms of budgeting, Chris advises having a discretionary budget without needing additional approval, especially in companies with complex procurement processes. This can give confidence to the client and speed up the approval process. Overall, Chris emphasizes the importance of understanding the market, building long-term relationships, and communicating value effectively to secure deals. Ethical business practices and transparency are crucial in maintaining healthy client relationships and avoiding potential conflicts of interest.</pre><p>Thank you for taking the time to read this tutorial. I hope you found it informative and helpful. If you have any questions or feedback, please feel free to reach out.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b73dc940662" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>