code: import streamlit as st
  from llama_hub.youtube_transcript import YoutubeTranscriptReader
  from llama_hub.youtube_transcript import is_youtube_video
  from llama_index import (
      VectorStoreIndex,
      StorageContext,
      load_index_from_storage,
  )
  from llama_index.prompts import ChatMessage, MessageRole
  
  from llama_index.tools import QueryEngineTool, ToolMetadata
  import os
  # import openai
  
  from llama_hub.tools.wikipedia import WikipediaToolSpec
  
  from llama_index.agent import OpenAIAgent
  from fetch_yt_metadata import fetch_youtube_metadata
  
  video_url = None
  
  with st.sidebar:
      openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
      if openai_api_key:
          os.environ["OPENAI_API_KEY"] = openai_api_key
      "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
      video_url = st.text_input("'Enter your video url here:", key="video_url")
      if video_url:
          st.video(video_url)
          if is_youtube_video(video_url):
              metadata = fetch_youtube_metadata(video_url)
              st.session_state["metadata"] = metadata
              st.header("Metadata:")
              for k, v in metadata.items():
                  if k == "video_description":
                      st.text_area("Description:", height=200, value=v, disabled=True)
                  else:
                      st.write(f"{k}: {v}")
          st.text_area("Transcript:", height=200, value=st.session_state.get("transcript", ""))
  
  if st.session_state.get("video_url"):
      url = st.session_state.get("video_url")
      st.write(f"Chat with {url}")
  
  
  
  if "counter" not in st.session_state:
      st.session_state.counter = 0
  
  st.session_state.counter += 1
  
  st.header(f"This page has run {st.session_state.counter} times.")
  st.button("Run it again")
  
  query_engine = None
  transcript = None
  if video_url:
      video_id = video_url.split('=')[1].split('&')[0]
      # check if storage already exists
      PERSIST_DIR = f"./storage/{video_id}"
      if not os.path.exists(PERSIST_DIR):
          # load the documents and create the index
          # documents = SimpleDirectoryReader("data").load_data()
          loader = YoutubeTranscriptReader()
          documents = loader.load_data(ytlinks=[url])
          # save the documents to disk using the video_id.sbt
  
          index = VectorStoreIndex.from_documents(documents)
          # store it for later
          index.storage_context.persist(persist_dir=PERSIST_DIR)
          with open(f"{PERSIST_DIR}/transcript.txt", "w") as f:
              for doc in documents:
                      f.write(doc.text)
      else:
          # load the existing index
          storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
          index = load_index_from_storage(storage_context)
      # either way we can now query the index
      query_engine = index.as_query_engine()
      if not st.session_state.get("summary"):
          summary = query_engine.query("What's the video about?").response
          st.session_state["summary"] = summary
      if not st.session_state.get("transcript"):
          transcript = open(f"{PERSIST_DIR}/transcript.txt").read()
          st.session_state["transcript"] = transcript
      
  
  
  
  st.title('💬 Talk2YouTube')
  st.write(st.session_state.get("summary",'Load a youtube video and chat with it'))
  
  if "messages" not in st.session_state:
      st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
  
  for msg in st.session_state.messages:
      st.chat_message(msg["role"]).write(msg["content"])
  
  if prompt := st.chat_input():
      if not openai_api_key:
          st.info("Please add your OpenAI API key to continue.")
          st.stop()
  
      
      vector_tool = QueryEngineTool(
          query_engine=query_engine,
          metadata=ToolMetadata(
              name=f"VideoTranscript",
              description=f"useful for when you want to answer queries about the content of the video.",
          ),
      )
      
      wiki_tool_spec = WikipediaToolSpec()
      tools = wiki_tool_spec.to_tool_list() #+ query_engine_tools
      st.session_state.messages.append({"role": "user", "content": prompt})
      st.chat_message("user").write(prompt)
      agent = OpenAIAgent.from_tools([vector_tool], verbose=True, openai_api_key=st.session_state.get("chatbot_api_key"))
      chat_history = [ChatMessage(role=MessageRole.USER if x.get("role","assistant") == "user" else "assistant", content=x.get("content","")) for x in st.session_state.messages]
      response = agent.chat(prompt, chat_history=chat_history)
      msg = {"role":"assistant", "content":response.response}
      st.session_state.messages.append(msg)
      st.chat_message("assistant").write(msg.get("content"))
      
  
apis: llama_index.VectorStoreIndex.from_documents llama_index.StorageContext.from_defaults llama_index.load_index_from_storage llama_index.tools.ToolMetadata
extract_api: [((1466, 1499), 'streamlit.session_state.get', 'st.session_state.get', (['"""video_url"""'], {}), "('video_url')\n", (1486, 1499), True, 'import streamlit as st\n'), ((1684, 1749), 'streamlit.header', 'st.header', (['f"""This page has run {st.session_state.counter} times."""'], {}), "(f'This page has run {st.session_state.counter} times.')\n", (1693, 1749), True, 'import streamlit as st\n'), ((1750, 1775), 'streamlit.button', 'st.button', (['"""Run it again"""'], {}), "('Run it again')\n", (1759, 1775), True, 'import streamlit as st\n'), ((3161, 3187), 'streamlit.title', 'st.title', (['"""💬 Talk2YouTube"""'], {}), "('💬 Talk2YouTube')\n", (3169, 3187), True, 'import streamlit as st\n'), ((599, 670), 'streamlit.text_input', 'st.text_input', (['"""OpenAI API Key"""'], {'key': '"""chatbot_api_key"""', 'type': '"""password"""'}), "('OpenAI API Key', key='chatbot_api_key', type='password')\n", (612, 670), True, 'import streamlit as st\n'), ((840, 901), 'streamlit.text_input', 'st.text_input', (['"""\'Enter your video url here:"""'], {'key': '"""video_url"""'}), '("\'Enter your video url here:", key=\'video_url\')\n', (853, 901), True, 'import streamlit as st\n'), ((1511, 1544), 'streamlit.session_state.get', 'st.session_state.get', (['"""video_url"""'], {}), "('video_url')\n", (1531, 1544), True, 'import streamlit as st\n'), ((1549, 1577), 'streamlit.write', 'st.write', (['f"""Chat with {url}"""'], {}), "(f'Chat with {url}')\n", (1557, 1577), True, 'import streamlit as st\n'), ((3197, 3269), 'streamlit.session_state.get', 'st.session_state.get', (['"""summary"""', '"""Load a youtube video and chat with it"""'], {}), "('summary', 'Load a youtube video and chat with it')\n", (3217, 3269), True, 'import streamlit as st\n'), ((3511, 3526), 'streamlit.chat_input', 'st.chat_input', ([], {}), '()\n', (3524, 3526), True, 'import streamlit as st\n'), ((3926, 3945), 'llama_hub.tools.wikipedia.WikipediaToolSpec', 'WikipediaToolSpec', ([], {}), '()\n', (3943, 3945), False, 'from llama_hub.tools.wikipedia import WikipediaToolSpec\n'), ((4014, 4083), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (4046, 4083), True, 'import streamlit as st\n'), ((4547, 4584), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (['msg'], {}), '(msg)\n', (4579, 4584), True, 'import streamlit as st\n'), ((928, 947), 'streamlit.video', 'st.video', (['video_url'], {}), '(video_url)\n', (936, 947), True, 'import streamlit as st\n'), ((959, 986), 'llama_hub.youtube_transcript.is_youtube_video', 'is_youtube_video', (['video_url'], {}), '(video_url)\n', (975, 986), False, 'from llama_hub.youtube_transcript import is_youtube_video\n'), ((1973, 2000), 'os.path.exists', 'os.path.exists', (['PERSIST_DIR'], {}), '(PERSIST_DIR)\n', (1987, 2000), False, 'import os\n'), ((2133, 2158), 'llama_hub.youtube_transcript.YoutubeTranscriptReader', 'YoutubeTranscriptReader', ([], {}), '()\n', (2156, 2158), False, 'from llama_hub.youtube_transcript import YoutubeTranscriptReader\n'), ((2288, 2330), 'llama_index.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', (['documents'], {}), '(documents)\n', (2319, 2330), False, 'from llama_index import VectorStoreIndex, StorageContext, load_index_from_storage\n'), ((2627, 2680), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'PERSIST_DIR'}), '(persist_dir=PERSIST_DIR)\n', (2655, 2680), False, 'from llama_index import VectorStoreIndex, StorageContext, load_index_from_storage\n'), ((2697, 2737), 'llama_index.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (2720, 2737), False, 'from llama_index import VectorStoreIndex, StorageContext, load_index_from_storage\n'), ((2836, 2867), 'streamlit.session_state.get', 'st.session_state.get', (['"""summary"""'], {}), "('summary')\n", (2856, 2867), True, 'import streamlit as st\n'), ((2999, 3033), 'streamlit.session_state.get', 'st.session_state.get', (['"""transcript"""'], {}), "('transcript')\n", (3019, 3033), True, 'import streamlit as st\n'), ((3563, 3617), 'streamlit.info', 'st.info', (['"""Please add your OpenAI API key to continue."""'], {}), "('Please add your OpenAI API key to continue.')\n", (3570, 3617), True, 'import streamlit as st\n'), ((3626, 3635), 'streamlit.stop', 'st.stop', ([], {}), '()\n', (3633, 3635), True, 'import streamlit as st\n'), ((1011, 1044), 'fetch_yt_metadata.fetch_youtube_metadata', 'fetch_youtube_metadata', (['video_url'], {}), '(video_url)\n', (1033, 1044), False, 'from fetch_yt_metadata import fetch_youtube_metadata\n'), ((1109, 1131), 'streamlit.header', 'st.header', (['"""Metadata:"""'], {}), "('Metadata:')\n", (1118, 1131), True, 'import streamlit as st\n'), ((3446, 3474), 'streamlit.chat_message', 'st.chat_message', (["msg['role']"], {}), "(msg['role'])\n", (3461, 3474), True, 'import streamlit as st\n'), ((3729, 3867), 'llama_index.tools.ToolMetadata', 'ToolMetadata', ([], {'name': 'f"""VideoTranscript"""', 'description': 'f"""useful for when you want to answer queries about the content of the video."""'}), "(name=f'VideoTranscript', description=\n    f'useful for when you want to answer queries about the content of the video.'\n    )\n", (3741, 3867), False, 'from llama_index.tools import QueryEngineTool, ToolMetadata\n'), ((4088, 4111), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (4103, 4111), True, 'import streamlit as st\n'), ((4205, 4244), 'streamlit.session_state.get', 'st.session_state.get', (['"""chatbot_api_key"""'], {}), "('chatbot_api_key')\n", (4225, 4244), True, 'import streamlit as st\n'), ((4589, 4617), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (4604, 4617), True, 'import streamlit as st\n'), ((1422, 1460), 'streamlit.session_state.get', 'st.session_state.get', (['"""transcript"""', '""""""'], {}), "('transcript', '')\n", (1442, 1460), True, 'import streamlit as st\n'), ((1239, 1303), 'streamlit.text_area', 'st.text_area', (['"""Description:"""'], {'height': '(200)', 'value': 'v', 'disabled': '(True)'}), "('Description:', height=200, value=v, disabled=True)\n", (1251, 1303), True, 'import streamlit as st\n'), ((1346, 1367), 'streamlit.write', 'st.write', (['f"""{k}: {v}"""'], {}), "(f'{k}: {v}')\n", (1354, 1367), True, 'import streamlit as st\n')]