code: """
  Module for setting up a Streamlit application that searches and summarizes content
  from the Huberman Lab Podcast. Uses llama_index for data indexing and retrieval, and
  OpenAI for text embedding and generation.
  """
  
  import streamlit as st
  import openai
  from llama_index.core import (
      StorageContext,
      load_index_from_storage,
      get_response_synthesizer,
      Settings
  )
  from llama_index.core.retrievers import VectorIndexRetriever
  from llama_index.core.query_engine import RetrieverQueryEngine
  from llama_index.core.postprocessor import SimilarityPostprocessor
  from llama_index.llms.openai import OpenAI
  from llama_index.embeddings.openai import OpenAIEmbedding
  
  # Configuration of the Streamlit page
  st.set_page_config(
      page_title="TLDHubeR",
      page_icon="🧠",
      layout="centered",
      initial_sidebar_state="auto",
      menu_items=None
  )
  
  # Markdown file path
  MARKDOWN_FILE_PATH = 'docs/tldhuber_side_page.md'
  
  def read_markdown_file(path):
      """
      Reads the content of a markdown file and returns it.
      
      Parameters:
          path (str): The path to the markdown file.
          
      Returns:
          str: The content of the markdown file.
      """
      with open(path, 'r', encoding='utf-8') as file:
          return file.read()
  
  # Displaying the content in the sidebar
  with st.sidebar:
      openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
      st.markdown("[Get an OpenAI API key](https://platform.openai.com/account/api-keys)")
      st.markdown("[View the source code](https://github.com/apeled/TLDhubeR)")
      st.markdown(read_markdown_file(MARKDOWN_FILE_PATH), unsafe_allow_html=True)
  
  openai.api_key = openai_api_key
  st.title("TLDHubeR: Search and Summarize the Huberman Lab")
  st.info("Hint: Are you a Hubernoob? If so, try searching for sleep!")
  
  if "messages" not in st.session_state:
      st.session_state["messages"] = [
          {"role": "assistant", "content": "Ask me a question about my podcasts."}
      ]
  
  def clear_session_state():
      """
      Clears the Streamlit session state.
      """
      for key in list(st.session_state.keys()):
          del st.session_state[key]
  
  @st.cache_resource(show_spinner=False)
  def load_data():
      """
      Loads and indexes the Huberman Lab Podcast data, initializing settings for keyword
      extraction and text embedding.
      
      Returns:
          VectorStoreIndex: The loaded and indexed podcast data.
      """
      with st.spinner("Loading and indexing the Huberman Lab Podcast!"):
          Settings.llm = OpenAI(temperature=0.2, model="gpt-3.5-turbo-0125")
          Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
  
          storage_context_load = StorageContext.from_defaults(persist_dir="data")
          loaded_index = load_index_from_storage(storage_context_load)
  
          return loaded_index
  
  def set_up_engine(loaded_index):
      """
      Creates a retriever and query engine using the loaded index.
      
      Parameters:
          loaded_index (VectorStoreIndex): The loaded and indexed podcast data.
          
      Returns:
          RetrieverQueryEngine: The assembled query engine.
      """
      retriever = VectorIndexRetriever(index=loaded_index, similarity_top_k=10)
      response_synthesizer = get_response_synthesizer(response_mode="no_text")
  
      simple_hube_engine = RetrieverQueryEngine.from_args(
          retriever=retriever,
          response_synthesizer=response_synthesizer,
          node_postprocessors=[SimilarityPostprocessor(similarity_cutoff=0.25)]
      )
      return simple_hube_engine
  
  def get_mid_video_link(link, time_stamp):
      """
      Modifies a YouTube link to start at a specified time.
      
      Parameters:
          link (str): The original YouTube video link.
          t (int): The start time in seconds.
          
      Returns:
          str: The modified YouTube link with the start time parameter.
      """
      base_url = link.replace("www.youtube.com/watch?v=", "youtu.be/")
      return f"{base_url}?t={time_stamp}"
  
  def extract_metadata(query_response):
      """
      Extracts and transforms metadata from source nodes in a query response.
      
      Parameters:
          query_response (QueryResponse): The response from a query engine.
          
      Returns:
          list[dict]: A list of transformed metadata dictionaries with modified YouTube links.
      """
      metadata_list = [node.metadata for node in query_response.source_nodes]
      for metadata in metadata_list:
          base_link = metadata["youtube_link"]
          start_time = metadata["timestamp"]
          metadata["youtube_link"] = get_mid_video_link(base_link, start_time)
      return metadata_list
  
  # Main application logic
  try:
      if openai.api_key:
          index = load_data()
          engine = set_up_engine(index)
          if "chat_engine" not in st.session_state:
              st.session_state["chat_engine"] = index.as_chat_engine(
                  chat_mode="context",
                  system_prompt="""Respond as if you are Andrew Huberman. You should answer by
                                  summarizing the topic from your context. Always
                                  include a direct quote from your podcast related to
                                  the response."""
              )
  
          if prompt := st.chat_input("Search Query"):
              st.session_state["messages"].append({"role": "user", "content": prompt})
              vector_response = engine.query(prompt)
              meta_data = extract_metadata(vector_response)
              youtube_links = [episode['youtube_link'] for episode in meta_data]
              timestamps = [episode['timestamp'] for episode in meta_data]
  
          for i, message in enumerate(st.session_state["messages"]):
              with st.chat_message(message["role"], avatar="docs/andrew.jpeg" if i == 0 else None):
                  st.write(message["content"])
  
          if st.session_state["messages"][-1]["role"] != "assistant":
              with st.chat_message("assistant", avatar="docs/andrew.jpeg"):
                  with st.spinner("Thinking..."):
                      response = st.session_state["chat_engine"].chat(prompt)
                      st.write(response.response)
                      message = {"role": "assistant", "content": response.response}
                      st.session_state["messages"].append(message)
                      st.video(youtube_links[0], start_time=timestamps[0])
  
                      with st.expander("See additional clips"):
                          unique_youtube_links = set(youtube_links[1:])
                          for episode in unique_youtube_links:
                              st.write(episode)
  
          # Button to clear the session state
          if st.button("Clear Chat History"):
              clear_session_state()
  
  except ValueError as e:
      if openai.api_key:
          st.error(f"An error occurred: {e}. Please check your OpenAPI key and try again.")
      else:
          st.warning("Enter your OpenAPI key in the sidebar.")
  
apis: llama_index.core.StorageContext.from_defaults llama_index.core.retrievers.VectorIndexRetriever llama_index.llms.openai.OpenAI llama_index.core.get_response_synthesizer llama_index.core.postprocessor.SimilarityPostprocessor llama_index.core.load_index_from_storage llama_index.embeddings.openai.OpenAIEmbedding
extract_api: [((712, 838), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""TLDHubeR"""', 'page_icon': '"""🧠"""', 'layout': '"""centered"""', 'initial_sidebar_state': '"""auto"""', 'menu_items': 'None'}), "(page_title='TLDHubeR', page_icon='🧠', layout='centered',\n    initial_sidebar_state='auto', menu_items=None)\n", (730, 838), True, 'import streamlit as st\n'), ((1684, 1743), 'streamlit.title', 'st.title', (['"""TLDHubeR: Search and Summarize the Huberman Lab"""'], {}), "('TLDHubeR: Search and Summarize the Huberman Lab')\n", (1692, 1743), True, 'import streamlit as st\n'), ((1744, 1813), 'streamlit.info', 'st.info', (['"""Hint: Are you a Hubernoob? If so, try searching for sleep!"""'], {}), "('Hint: Are you a Hubernoob? If so, try searching for sleep!')\n", (1751, 1813), True, 'import streamlit as st\n'), ((2144, 2181), 'streamlit.cache_resource', 'st.cache_resource', ([], {'show_spinner': '(False)'}), '(show_spinner=False)\n', (2161, 2181), True, 'import streamlit as st\n'), ((1332, 1403), '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", (1345, 1403), True, 'import streamlit as st\n'), ((1408, 1497), 'streamlit.markdown', 'st.markdown', (['"""[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"""'], {}), "(\n    '[Get an OpenAI API key](https://platform.openai.com/account/api-keys)')\n", (1419, 1497), True, 'import streamlit as st\n'), ((1497, 1570), 'streamlit.markdown', 'st.markdown', (['"""[View the source code](https://github.com/apeled/TLDhubeR)"""'], {}), "('[View the source code](https://github.com/apeled/TLDhubeR)')\n", (1508, 1570), True, 'import streamlit as st\n'), ((3132, 3193), 'llama_index.core.retrievers.VectorIndexRetriever', 'VectorIndexRetriever', ([], {'index': 'loaded_index', 'similarity_top_k': '(10)'}), '(index=loaded_index, similarity_top_k=10)\n', (3152, 3193), False, 'from llama_index.core.retrievers import VectorIndexRetriever\n'), ((3221, 3270), 'llama_index.core.get_response_synthesizer', 'get_response_synthesizer', ([], {'response_mode': '"""no_text"""'}), "(response_mode='no_text')\n", (3245, 3270), False, 'from llama_index.core import StorageContext, load_index_from_storage, get_response_synthesizer, Settings\n'), ((2082, 2105), 'streamlit.session_state.keys', 'st.session_state.keys', ([], {}), '()\n', (2103, 2105), True, 'import streamlit as st\n'), ((2427, 2487), 'streamlit.spinner', 'st.spinner', (['"""Loading and indexing the Huberman Lab Podcast!"""'], {}), "('Loading and indexing the Huberman Lab Podcast!')\n", (2437, 2487), True, 'import streamlit as st\n'), ((2512, 2563), 'llama_index.llms.openai.OpenAI', 'OpenAI', ([], {'temperature': '(0.2)', 'model': '"""gpt-3.5-turbo-0125"""'}), "(temperature=0.2, model='gpt-3.5-turbo-0125')\n", (2518, 2563), False, 'from llama_index.llms.openai import OpenAI\n'), ((2595, 2642), 'llama_index.embeddings.openai.OpenAIEmbedding', 'OpenAIEmbedding', ([], {'model': '"""text-embedding-3-small"""'}), "(model='text-embedding-3-small')\n", (2610, 2642), False, 'from llama_index.embeddings.openai import OpenAIEmbedding\n'), ((2675, 2723), 'llama_index.core.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': '"""data"""'}), "(persist_dir='data')\n", (2703, 2723), False, 'from llama_index.core import StorageContext, load_index_from_storage, get_response_synthesizer, Settings\n'), ((2747, 2792), 'llama_index.core.load_index_from_storage', 'load_index_from_storage', (['storage_context_load'], {}), '(storage_context_load)\n', (2770, 2792), False, 'from llama_index.core import StorageContext, load_index_from_storage, get_response_synthesizer, Settings\n'), ((6637, 6668), 'streamlit.button', 'st.button', (['"""Clear Chat History"""'], {}), "('Clear Chat History')\n", (6646, 6668), True, 'import streamlit as st\n'), ((5218, 5247), 'streamlit.chat_input', 'st.chat_input', (['"""Search Query"""'], {}), "('Search Query')\n", (5231, 5247), True, 'import streamlit as st\n'), ((6760, 6846), 'streamlit.error', 'st.error', (['f"""An error occurred: {e}. Please check your OpenAPI key and try again."""'], {}), "(\n    f'An error occurred: {e}. Please check your OpenAPI key and try again.')\n", (6768, 6846), True, 'import streamlit as st\n'), ((6860, 6912), 'streamlit.warning', 'st.warning', (['"""Enter your OpenAPI key in the sidebar."""'], {}), "('Enter your OpenAPI key in the sidebar.')\n", (6870, 6912), True, 'import streamlit as st\n'), ((3438, 3485), 'llama_index.core.postprocessor.SimilarityPostprocessor', 'SimilarityPostprocessor', ([], {'similarity_cutoff': '(0.25)'}), '(similarity_cutoff=0.25)\n', (3461, 3485), False, 'from llama_index.core.postprocessor import SimilarityPostprocessor\n'), ((5680, 5759), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {'avatar': "('docs/andrew.jpeg' if i == 0 else None)"}), "(message['role'], avatar='docs/andrew.jpeg' if i == 0 else None)\n", (5695, 5759), True, 'import streamlit as st\n'), ((5777, 5805), 'streamlit.write', 'st.write', (["message['content']"], {}), "(message['content'])\n", (5785, 5805), True, 'import streamlit as st\n'), ((5892, 5947), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {'avatar': '"""docs/andrew.jpeg"""'}), "('assistant', avatar='docs/andrew.jpeg')\n", (5907, 5947), True, 'import streamlit as st\n'), ((5970, 5995), 'streamlit.spinner', 'st.spinner', (['"""Thinking..."""'], {}), "('Thinking...')\n", (5980, 5995), True, 'import streamlit as st\n'), ((6093, 6120), 'streamlit.write', 'st.write', (['response.response'], {}), '(response.response)\n', (6101, 6120), True, 'import streamlit as st\n'), ((6288, 6340), 'streamlit.video', 'st.video', (['youtube_links[0]'], {'start_time': 'timestamps[0]'}), '(youtube_links[0], start_time=timestamps[0])\n', (6296, 6340), True, 'import streamlit as st\n'), ((6367, 6402), 'streamlit.expander', 'st.expander', (['"""See additional clips"""'], {}), "('See additional clips')\n", (6378, 6402), True, 'import streamlit as st\n'), ((6563, 6580), 'streamlit.write', 'st.write', (['episode'], {}), '(episode)\n', (6571, 6580), True, 'import streamlit as st\n')]