code: import streamlit as st
  import os
  import sys
  import logging
  from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext
  from llama_index.llms import OpenAI, ChatMessage
  from llama_index.query_engine import RetrieverQueryEngine
  from llama_index.text_splitter import CodeSplitter
  from llama_index.node_parser import SimpleNodeParser
  import openai
  import json
  import nest_asyncio
  
  nest_asyncio.apply()
  logging.basicConfig(stream=sys.stdout, level=logging.INFO)
  
  logger = logging.getLogger()
  
  if not logger.handlers:
      logger.addHandler(logging.StreamHandler(stream=sys.stdout))
  # API key setup
  openai.api_key = st.secrets.openai_key
  
  # Get folder path from command-line arguments
  folder_path = sys.argv[-1] if len(sys.argv) > 1 else './results'
  
  # Get index name from folder name
  index_name = os.path.basename(os.path.normpath(folder_path))
  
      
  @st.cache_resource(show_spinner=False)
  def load_data():
  
  	index = None
  	try:
  		# Rebuild storage context
  		storage_context = StorageContext.from_defaults(persist_dir=f'./storage/{index_name}')
  		# Load index
  		index = load_index_from_storage(storage_context, index_id=index_name)
  		logging.info(f"Loaded index: {index}")
  		return index
  	except Exception as e:
  		logging.info(f"Could not load index: {e}\nCreating new index")# with summary query: {SUMMARY_QUERY}")
  
  		documents = SimpleDirectoryReader(folder_path, recursive=True).load_data()
  		service_context = ServiceContext.from_defaults(llm=OpenAI(temperature=0, model="gpt-4"))#, temperature=0.5, system_prompt="You are an expert on the LLama index Python library and your job is to answer technical questions. Assume that all questions are related to the LLama index Python library. Keep your answers technical and based on facts – do not hallucinate features."))
  
  		text_splitter = CodeSplitter(
  		language="python",
  		chunk_lines=40,
  		chunk_lines_overlap=15,
  		max_chars=1500,
  		)
  
  		node_parser = SimpleNodeParser.from_defaults(text_splitter=text_splitter)
  		service_context = ServiceContext.from_defaults(node_parser=node_parser)
  
  		index = TreeIndex.from_documents(documents, service_context=service_context)
  		index.set_index_id(index_name)
  		index.storage_context.persist(f"./storage/{index_name}")
  		logging.info(f"Created index: {index}")
  		return index
  
  index = load_data()
  
  
  # Define chat engine
  #mode = st.selectbox("Select query mode", ["condense_question", "best", "context", "simple", "react", "openai"])
  #chat_engine = index.as_chat_engine(chat_mode=mode, verbose=True)
  
  response_mode = st.selectbox("Select chat mode", ["best", "context", "condense_question", "simple", "react", "openai"])
  
  include_history = st.checkbox("Include chat history", value=True)
  
  # assemble query engine
  chat_engine = index.as_chat_engine(chat_mode=response_mode, verbose=True)
  
  st.subheader("Chat with {0} index".format(index_name))
  
  # Initialize session state
  if "messages" not in st.session_state.keys():
      st.session_state.messages = []
  
  # Chat UI
  if prompt := st.chat_input("Your question"):
      st.session_state.messages.append({"role": "user", "content": prompt})
  
  # Display chat
  for message in st.session_state.messages:
      with st.chat_message(message["role"]):
          st.write(message["content"])
  
  # Perform and display the query
  if len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] != "assistant":
  	with st.chat_message("assistant"):
  		response = None
  		with st.spinner("Thinking..."):
  			
  			logging.info(prompt)
  			# Initialize an empty string to hold the concatenated tokens
  			concatenated_response = ""
  
  			chat_history = [ChatMessage(content=message["content"], role=message["role"]) for message in st.session_state.messages]
  			response = chat_engine.stream_chat(prompt, chat_history=chat_history if include_history else None)
  
  		message_placeholder = st.empty()
  		full_response = ""
  
  		for token in response.response_gen:
  			full_response += token
  			message_placeholder.write(full_response + "▌")
  		message_placeholder.write(full_response)
  		st.session_state.messages.append({"role": "assistant", "content": full_response})
  
  # Button to export chat log
  if len(st.session_state.messages) > 0 and st.button('Export Chat Log'):
      chat_log_str = json.dumps(st.session_state.messages, indent=4)
      st.download_button(
          label="Download Chat Log",
          data=chat_log_str,
          file_name="chat_log.json",
          mime="application/json",
      )
apis: llama_index.ServiceContext.from_defaults llama_index.text_splitter.CodeSplitter llama_index.StorageContext.from_defaults llama_index.SimpleDirectoryReader llama_index.llms.ChatMessage llama_index.llms.OpenAI llama_index.load_index_from_storage llama_index.node_parser.SimpleNodeParser.from_defaults llama_index.TreeIndex.from_documents
extract_api: [((457, 477), 'nest_asyncio.apply', 'nest_asyncio.apply', ([], {}), '()\n', (475, 477), False, 'import nest_asyncio\n'), ((478, 536), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (497, 536), False, 'import logging\n'), ((547, 566), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (564, 566), False, 'import logging\n'), ((926, 963), 'streamlit.cache_resource', 'st.cache_resource', ([], {'show_spinner': '(False)'}), '(show_spinner=False)\n', (943, 963), True, 'import streamlit as st\n'), ((2585, 2692), 'streamlit.selectbox', 'st.selectbox', (['"""Select chat mode"""', "['best', 'context', 'condense_question', 'simple', 'react', 'openai']"], {}), "('Select chat mode', ['best', 'context', 'condense_question',\n    'simple', 'react', 'openai'])\n", (2597, 2692), True, 'import streamlit as st\n'), ((2708, 2755), 'streamlit.checkbox', 'st.checkbox', (['"""Include chat history"""'], {'value': '(True)'}), "('Include chat history', value=True)\n", (2719, 2755), True, 'import streamlit as st\n'), ((888, 917), 'os.path.normpath', 'os.path.normpath', (['folder_path'], {}), '(folder_path)\n', (904, 917), False, 'import os\n'), ((2960, 2983), 'streamlit.session_state.keys', 'st.session_state.keys', ([], {}), '()\n', (2981, 2983), True, 'import streamlit as st\n'), ((3044, 3074), 'streamlit.chat_input', 'st.chat_input', (['"""Your question"""'], {}), "('Your question')\n", (3057, 3074), True, 'import streamlit as st\n'), ((3080, 3149), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (3112, 3149), True, 'import streamlit as st\n'), ((4223, 4251), 'streamlit.button', 'st.button', (['"""Export Chat Log"""'], {}), "('Export Chat Log')\n", (4232, 4251), True, 'import streamlit as st\n'), ((4272, 4319), 'json.dumps', 'json.dumps', (['st.session_state.messages'], {'indent': '(4)'}), '(st.session_state.messages, indent=4)\n', (4282, 4319), False, 'import json\n'), ((4324, 4445), 'streamlit.download_button', 'st.download_button', ([], {'label': '"""Download Chat Log"""', 'data': 'chat_log_str', 'file_name': '"""chat_log.json"""', 'mime': '"""application/json"""'}), "(label='Download Chat Log', data=chat_log_str, file_name=\n    'chat_log.json', mime='application/json')\n", (4342, 4445), True, 'import streamlit as st\n'), ((614, 654), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\n', (635, 654), False, 'import logging\n'), ((1050, 1117), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'f"""./storage/{index_name}"""'}), "(persist_dir=f'./storage/{index_name}')\n", (1078, 1117), False, 'from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext\n'), ((1143, 1204), 'llama_index.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {'index_id': 'index_name'}), '(storage_context, index_id=index_name)\n', (1166, 1204), False, 'from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext\n'), ((1207, 1245), 'logging.info', 'logging.info', (['f"""Loaded index: {index}"""'], {}), "(f'Loaded index: {index}')\n", (1219, 1245), False, 'import logging\n'), ((3217, 3249), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (3232, 3249), True, 'import streamlit as st\n'), ((3259, 3287), 'streamlit.write', 'st.write', (["message['content']"], {}), "(message['content'])\n", (3267, 3287), True, 'import streamlit as st\n'), ((3423, 3451), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (3438, 3451), True, 'import streamlit as st\n'), ((3878, 3888), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (3886, 3888), True, 'import streamlit as st\n'), ((4070, 4155), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content':\n    full_response})\n", (4102, 4155), True, 'import streamlit as st\n'), ((1287, 1352), 'logging.info', 'logging.info', (['f"""Could not load index: {e}\nCreating new index"""'], {}), '(f"""Could not load index: {e}\nCreating new index""")\n', (1299, 1352), False, 'import logging\n'), ((1864, 1955), 'llama_index.text_splitter.CodeSplitter', 'CodeSplitter', ([], {'language': '"""python"""', 'chunk_lines': '(40)', 'chunk_lines_overlap': '(15)', 'max_chars': '(1500)'}), "(language='python', chunk_lines=40, chunk_lines_overlap=15,\n    max_chars=1500)\n", (1876, 1955), False, 'from llama_index.text_splitter import CodeSplitter\n'), ((1982, 2041), 'llama_index.node_parser.SimpleNodeParser.from_defaults', 'SimpleNodeParser.from_defaults', ([], {'text_splitter': 'text_splitter'}), '(text_splitter=text_splitter)\n', (2012, 2041), False, 'from llama_index.node_parser import SimpleNodeParser\n'), ((2062, 2115), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'node_parser': 'node_parser'}), '(node_parser=node_parser)\n', (2090, 2115), False, 'from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext\n'), ((2127, 2195), 'llama_index.TreeIndex.from_documents', 'TreeIndex.from_documents', (['documents'], {'service_context': 'service_context'}), '(documents, service_context=service_context)\n', (2151, 2195), False, 'from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext\n'), ((2290, 2329), 'logging.info', 'logging.info', (['f"""Created index: {index}"""'], {}), "(f'Created index: {index}')\n", (2302, 2329), False, 'import logging\n'), ((3478, 3503), 'streamlit.spinner', 'st.spinner', (['"""Thinking..."""'], {}), "('Thinking...')\n", (3488, 3503), True, 'import streamlit as st\n'), ((3512, 3532), 'logging.info', 'logging.info', (['prompt'], {}), '(prompt)\n', (3524, 3532), False, 'import logging\n'), ((3647, 3708), 'llama_index.llms.ChatMessage', 'ChatMessage', ([], {'content': "message['content']", 'role': "message['role']"}), "(content=message['content'], role=message['role'])\n", (3658, 3708), False, 'from llama_index.llms import OpenAI, ChatMessage\n'), ((1404, 1454), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryReader', (['folder_path'], {'recursive': '(True)'}), '(folder_path, recursive=True)\n', (1425, 1454), False, 'from llama_index import TreeIndex, SimpleDirectoryReader, StorageContext, get_response_synthesizer, load_index_from_storage, ServiceContext\n'), ((1520, 1556), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-4"""'}), "(temperature=0, model='gpt-4')\n", (1526, 1556), False, 'from llama_index.llms import OpenAI, ChatMessage\n')]