code: from PIL import Image
  import streamlit as st
  import openai
  #exercise 11
  from langchain.llms import OpenAI
  from langchain.prompts import PromptTemplate
  from langchain.chains import LLMChain
  #exercise 12
  from langchain.memory import ConversationBufferWindowMemory
  #exercise 13
  from langchain.document_loaders import TextLoader,PyPDFLoader
  from langchain.embeddings.openai import OpenAIEmbeddings
  from langchain.vectorstores import LanceDB
  import lancedb
  import os
  import tempfile
  #exercise 15
  import sqlite3
  import pandas as pd
  from datetime import datetime
  #exercise 16
  from langchain.agents import ConversationalChatAgent, AgentExecutor
  from langchain.callbacks import StreamlitCallbackHandler
  from langchain.chat_models import ChatOpenAI
  from langchain.memory import ConversationBufferMemory
  from langchain.memory.chat_message_histories import StreamlitChatMessageHistory
  from langchain.tools import DuckDuckGoSearchRun
  #Exercise 17
  from langchain.agents import tool
  import json
  #Exercise 18
  from pandasai import SmartDataframe
  from pandasai.llm.openai import OpenAI
  import matplotlib.pyplot as plt
  
  os.environ["OPENAI_API_KEY"] = st.secrets["openapi_key"]
  openai.api_key = st.secrets["openapi_key"]
  
  #Global ex 13
  cwd = os.getcwd()
  WORKING_DIRECTORY = os.path.join(cwd, "database")
  
  if not os.path.exists(WORKING_DIRECTORY):
  	os.makedirs(WORKING_DIRECTORY)
  #ex15
  DB_NAME = os.path.join(WORKING_DIRECTORY, "default_db")
  
  def template():
  	st.subheader("Template")
  	st.write("Instruction lines.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #exercise code here
  ''')
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  #challenge code here
  ''')	  
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  
  def class1_prep():
  	# st.subheader("Course Slides")
  	# st.markdown("https://go.gov.sg/itdchatbotprototype")
  	st.divider()
  	st.subheader("Pre-workshop Setup")
  	# st.divider()
  	st.markdown("""1. Visual Studio (VS Code): this is the Integrated Development Environment (IDE) of choice by many coders and will make it easier for us to code our app.""")
  	st.markdown("""2. Python (3.10 release or later): this is the coding language of choice for many data science related apps.""")
  	st.write("""
  			3. Once you have installed the above, we will need to set up a virtual environment and install the libraries in that environment.\n
  				Create a folder named “chatbot” anywhere, e.g. in your Desktop.\n 
  				Open VS Code and navigate to the folder in a new terminal window.\n 
  				Create a virtual environment and activate it by entering the following commands in the terminal:
  			 """)
  	st.markdown("   **a) Mac**")
  	st.code('''
  		python3 -m venv venv
  		source venv/bin/activate 
  			''')
  	st.markdown("(You should see a (venv) appear in your terminal window prompt)")
  	st.markdown("#")
  	st.markdown("   **b) Windows**")
  	st.code('''
  		python -m venv venv
  		cd venv\Scripts
  		activate
  			''')
  	st.markdown("4. While in your virtual environment, install the libraries using pip which should already be installed together with Python:")
  	st.code('''
  		pip install streamlit openai
  			''')
  	st.markdown(" To test if Streamlit is installed properly, run this command:")
  	st.code('''
  	streamlit hello
  			''')
  	st.markdown(" You should see a Streamlit application running at http://localhost:8501")
  	st.markdown(" Type Ctrl + C in VS Code terminal to stop the Streamlit app")
  	pass
  
  def class1_hw1():
  	st.subheader("My first Hello World app")
  	st.divider()
  	st.markdown("""1. Create a new file called 'main.py'.""")
  	st.markdown("""2. Copy the code below and paste it in the newly created helloworld.py file.""")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  			import streamlit as st
  			#my first Hello World app
  			st.write("Hello World")
  		''')
  	st.markdown("Install the watchdog module by running the command below in the terminal.")
  	st.code("pip install watchdog")
  	st.markdown("Now you don't have to keep restarting the app to see the changes you make to the code. Just refresh the browser.")
  	st.write("Save your file and run the app by typing the following command in the terminal:")
  	st.code('''
  			streamlit run main.py
  		''')
  	st.markdown("""3. You should see a Streamlit application running at http://localhost:8501""")
  	st.markdown("""4. Type Ctrl + C in VS Code terminal to stop the Streamlit app""")
  	st.markdown("**:red[Code Output]**")
  	st.write("Hello World")
  	pass
  
  def objectives():
  	st.subheader("Objectives")
  	st.markdown("1. Learn how to use Python and Streamlit library to create an interactive web app.")
  	st.markdown("2. Learn how to integrate and use OpenAI's API in their streamlit application to create a simple chatbot.")
  	st.markdown("3. Learn how to apply basic prompt engineering to enhance the interaction with the chatbot.")
  
  def workshop_outline():
  	st.subheader("Outline")
  	st.markdown("Part 0: Workshop introduction and rules")
  	st.markdown("Part 1: Introduction to Python and Streamlit")
  	st.markdown("Part 2: Creating a rule-based chatbot")
  	st.markdown("Part 3: Creating a chatbot using OpenAI's API")
  	st.markdown("Part 4: Modifying your chatbot with prompt engineering")
  
  def team_introduction():
  	st.write("Do introduce yourself to your teammates:\n", "1) name\n", "2) division\n", "3) role")
  	st.write("Please also share your favourite Star Wars character and why!")
  	image = Image.open('team_introductions.jpeg')
  	st.image(image, caption='Hello there!')
  
  def workshop_rules():
  	st.subheader("Workshop Rules")
  	st.write("1. Ask if you have questions.")
  	st.write("2. Be open to different ways to solve the problem.")
  	st.write("3. Try. Fail. Learn. Repeat.")
  	st.write("4. Seek help from other team members.")
  	st.write("5. Collaborate, if possible, for the challenges.")
  	st.write("6. Approach facilitators if your team cannot solve the problem.")
  	st.write("7. Toilet break is own-time-own-target.")
  	st.write("8. Have fun!")
  
  def vscode_ui():
  	st.subheader("Navigating the VS Code interface")
  	image = Image.open('VSCode_interface.png')
  	st.image(image, caption='VS Code UI layout')
  	st.markdown("**A: Activity Bar: this is where you can see the different activities you can do in VS Code.**")
  	st.markdown("	Explorer: this is where you can see all the files and folders in your project.")
  	st.markdown("	Source Control: this is where you can see the changes you have made to your project.")
  	st.markdown("	Extensions: this is where you can install extensions to VS Code.")
  	st.markdown("	Run and Debug: this is where you can debug your code.")
  	st.markdown("**B: Side Bar: this is where you can see the different views of your project.**")
  	st.markdown("**C: Editor: this is where you can see the code you have written in your project.**")
  	st.markdown("**D: Panel: this is where you can see the different panels you have opened in your project.**")
  	st.markdown("	Terminal: this is where you can run commands in your project.")
  	st.markdown("	Output: this is where you can see the output of your code.")
  	st.markdown("	Problems: this is where you can see the errors in your code.")
  	st.markdown("**E. Status Bar: this is where you can see the status of your project.**")
  
  def command_palette_indent():
  	st.markdown("Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*")
  	image = Image.open('command_palette_command.png')
  	st.image(image, caption='Command Palette auto-indent command')
  
  def final_product():
  	st.write("This is what we will working towards and building by the end of the workshop today.")
  	st.write("Do try out the chatbot below!")
  	st.subheader("**:green[Feel the force! Yoda Chatbot]**")
  	image = Image.open('yoda.jpg')
  	st.image(image, caption='Master Yoda at your service')
  	st.divider()
  
  	openai.api_key = st.secrets["openapi_key"]
  
  	prompt_template = """
  	"Speak like Yoda from Star Wars for every question that was asked, 
  	do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  	"""
  
  	if "openai_model" not in st.session_state:
  		st.session_state["openai_model"] = "gpt-3.5-turbo"
  
  	if "msg_bot" not in st.session_state:
  		st.session_state.msg_bot = []
  
  	for message in st.session_state.msg_bot:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	
  	try:
  
  		if prompt := st.chat_input("What is up?"):
  			st.session_state.msg_bot.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				for response in openai.ChatCompletion.create(
  					model=st.session_state["openai_model"],
  					messages=[
  								{"role": "system", "content": prompt_template},
  								{"role": "user", "content": prompt},
  							],
  					stream=True,
  				):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg_bot.append({"role": "assistant", "content": full_response})
  
  	except Exception as e:
  		st.error(e)
  	pass
  
  def resources():
  	st.subheader("Useful resources and references")
  	st.markdown("1. [Streamlit documentation](https://docs.streamlit.io/en/stable/)")
  	st.markdown("2. [OpenAI API documentation](https://beta.openai.com/docs/introduction)")
  	st.markdown("3. [VS Code documentation](https://code.visualstudio.com/docs)")
  	st.markdown("4. [Python documentation](https://docs.python.org/3/)")
  	st.markdown("5. [Python cheatsheet](https://www.pythoncheatsheet.org/)")
  	st.markdown("6. [Python for beginners](https://www.python.org/about/gettingstarted/)")
  	st.markdown("7. [ChatGPT](https://chat.openai.com/) - you can ask ChatGPT to generate code for you!")
  	st.markdown("**Notes for this workshop course:**  \n- you may do a single click to copy all the code  \n- challenge code is hidden, click reveal to see the code")
  	st.markdown("Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*")
  	image = Image.open('command_palette_command.png')
  	st.image(image, caption='Command Palette auto-indent command')
  
  def part1_intro1():
  	st.subheader("Streamlit")
  	st.markdown("""
  		 * an open-source Python library
  		 * used extensively for machine learning and data science
  		 * helps to create interactive web apps in just a few lines of code
  		 * highly flexible and supports complex interactive apps with highly customisable UI
  		 * Some real world examples:
  		 	* CherGPT in String
  		 	* Metacog for CotF MOE
  		 	* AILC prototype for MOE
  		 """)
  
  def ex1():
  	# Exercise 1 : Functions
  	st.write("Hello World")
  	# only prints the Hello {name} if input box is not empty
  	name = st.text_input("Enter your name")
  	if name:
  		st.write("Hello " + name)
  
  def class1_ex1():
  	st.subheader("Exercise 1: Functions")
  	st.markdown("In the ***main.py*** file, the code below is already in ***ex1()*** in the ***part1.py*** file.")
  	st.write("The code for *helloworld* is inside what you call a Python function.")
  	st.write("The ***def main()*** function and ***if _ _ name _ _ == '_ _ main _ _'*** statement are coding conventions for any Python programme.")
  	st.write("You need to include an import statement in ***main.py*** to import the ***ex1()*** function from the other file.")
  	st.code('''
  from part1 import ex1
  ''')
  	st.write("You will need to do the same for all the other exercises and challenges for the rest of the workshop. The code exercises are already in the respective files: ***part1.py, part2.py, part3.py, part4.py***.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  import streamlit as st
  
  from part1 import ex1
  		 	 
  #Exercise 1: Functions
  def ex1():
  	st.write("Hello World")
  	name = st.text_input("Enter your name")
  	if name:
  		st.write("Hello " + name)
  	 
  def main():
  	ex1()
  	 
  if __name__ == "__main__":
  	main()		
  	 ''')
  	st.markdown("Run the code by typing the following into the terminal:")
  	st.code("streamlit run main.py")
  	st.markdown("You should see the following behaviour in your browser window:")
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex1()
  
  def ch1():
  	name = st.text_input("Enter your name")
  	gender = st.selectbox("State your gender", ["Male", "Female"])
  	age = st.text_input("State your age", 18)
  
  	if name and gender and age:
  		st.text(f"Hello {name}, you are {gender} and this year you are {age} years old")
  
  def class1_ch1():
  	st.subheader("Challenge 1: Input, Output and Variables")
  	st.write("Create a new function called ***ch1()*** in ***part1.py*** and call it in the main function.")
  	st.write("Create three variables *name*, *age* and *gender*, and obtain these from the user.")
  	st.write("Once the user filled up the input boxes, display back the information to the user.")
  	st.write("Code hint: the following piece of code checks if *name* has been filled, and if so, displays it back to the user.")
  	st.code('''
  name = st.text_input("Enter your name")
  if name:
  	st.text(f"Hello {name}")
  ''')
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  def ch1():
          name = st.text_input("Enter your name")
          gender = st.selectbox("State your gender", ["Male", "Female"])
          age = st.text_input("State your age", 18)
  
          if name and gender and age:
              st.text(f"Hello {name}, you are {gender} and this year you are {age} years old")
  ''')	  
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ch1()
  
  def ex2():
      gender = st.selectbox("State your gender", ["Male", "Female"])
      age = int(st.text_input("State your age", 18))
      photo = st.camera_input("Smile! take a picture here.")
  
      # conditional logic to run different statements
      if age >= 21 and gender == "Male":
          st.write("You are a male adult")
      elif age < 21 and gender == "Male":
          st.write("You are a young boy")
      elif age >= 21 and gender == "Female":
          st.write("You are a female adult")
      elif age < 21 and gender == "Female":
          st.write("You are a young girl")
  
      if photo:
          st.write("Here is your photo: ")
          st.image(photo)
      else:
          st.write("No photo taken")
  
  def class1_ex2():
  	st.subheader("Exercise 2: If-else logical conditionals")
  	st.markdown("If-else statements help control the flow and logic of our application.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  def ex2():
      gender = st.selectbox("State your gender", ["Male", "Female"])
      age = int(st.text_input("State your age", 18))
      photo = st.camera_input("Smile! take a picture here.")
  
      # conditional logic to run different statements
      if age >= 21 and gender == "Male":
          st.write("You are a male adult")
      elif age < 21 and gender == "Male":
          st.write("You are a young boy")
      elif age >= 21 and gender == "Female":
          st.write("You are a female adult")
      elif age < 21 and gender == "Female":
          st.write("You are a young girl")
  
      if photo:
          st.write("Here is your photo: ")
          st.image(photo)
      else:
          st.write("No photo taken")
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex2()
  
  def ex3():
  	# Data list
  	fruits = ["apple", "banana", "orange"]
  
  	# For loop to show list
  	for fruit in fruits:
  		st.write(fruit)
  
  	# Dictionary
  	person = {"name": "John", "age": 30, "gender": "Male", "city": "New York"}
  
  	# Print out the items in the dictionary
  	st.write("Here is your *person* dictionary: ")
  	st.write(person)
  
  	# for loop to show dictionary list
  	st.write("You can also show individual items in the dictionary like this: ")
  	for key, value in person.items():
  		st.write(key + ": " + str(value))
  
  	# get user input to update the dictionary
  	name = st.text_input("Enter your name", "John")
  	age = st.text_input("State your age", 30)
  	gender = st.selectbox("State your gender", ["Male", "Female"])
  	city = st.text_input("State your city", "New York")
  	person["name"] = name
  	person["age"] = age
  	person["gender"] = gender
  	person["city"] = city
  	
  	st.write("Here is your updated *person* dictionary: ")
  	st.write(person)
  
  def class1_ex3():
  	st.subheader("Exercise 3: Data and Loops ")
  	st.write("We can store data in a list or dictionary and display the data using a for loop.")
  	st.write("Append the following code to the ***main.py*** file. Refresh the browser to see the changes.")
  	st.write("You should see output similar to the *Code Output* below.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #Data and Loops
  def ex3():
  	# Data list
  	fruits = ["apple", "banana", "orange"]
  
  	# For loop to show list
  	for fruit in fruits:
  		st.write(fruit)
  
  	# Dictionary
  	person = {"name": "John", "age": 30, "city": "New York"}
  
  	# Print out the items in the dictionary
  	st.write("Here is your *person* dictionary: ")
  	st.write(person)
  
  	# for loop to show dictionary list
  	st.write("You can also show individual items in the dictionary like this: ")
  	for key, value in person.items():
  		st.write(key + ": " + str(value))
  
  	# get user input to update the dictionary
  	name = st.text_input("Enter your name", "John")
  	age = st.text_input("State your age", 30)
  	gender = st.selectbox("State your gender", ["Male", "Female"])
  	city = st.text_input("State your city", "New York")
  	person["name"] = name
  	person["age"] = age
  	person["gender"] = gender
  	person["city"] = city
  	
  	st.write("Here is your updated *person* dictionary: ")
  	st.write(person)
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex3()
  
  def ex4a():
  	#Exercise 4a: Creating Session Data
  	if "session_data" not in st.session_state:
  		st.session_state.session_data = ["alpha", "omega"]
  	
  	if "name" not in st.session_state:
  		st.session_state.name = ""
  	
  	if "age" not in st.session_state:
  		st.session_state.age = ""
  
  	if "gender" not in st.session_state:
  		st.session_state.gender = ""
  	
  	# For loop to show list
  	for data in st.session_state.session_data:
  		st.write("session_data: ", data)
  
  	st.write("name: ", st.session_state.name)
  	st.write("age: ", st.session_state.age)
  	st.write("gender: ", st.session_state.gender)
  
  def class1_ex4a():
  	st.subheader("Exercise 4a: Session Data")
  	st.write("We can create variables to store data in a user session. Session data persist within a user session.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # Exercise 4: Session State
  def ex4a():
  	st.subheader("Session Data:")
  	if "session_data" not in st.session_state:
  		st.session_state.session_data = ["alpha", "omega"]
  	
  	if "name" not in st.session_state:
  		st.session_state.name = ""
  	
  	if "age" not in st.session_state:
  		st.session_state.age = ""
  
  	if "gender" not in st.session_state:
  		st.session_state.gender = ""
  	
  	# For loop to show list
  	for data in st.session_state.session_data:
  		st.write("session_data: ", data)
  
  	st.write("name: ", st.session_state.name)
  	st.write("age: ", st.session_state.age)
  	st.write("gender: ", st.session_state.gender)
  ''')
  		 
  	st.markdown("**:red[Code Output]**")
  	ex4a()
  
  def ex4b():
  	#Exercise 4b: Session Data with User Input
  
  	user_name = st.text_input("Enter your name")
  	user_age = st.text_input("State your age")
  	user_gender = st.selectbox("State your gender", ["", "Male", "Female"])
  
  	if user_name:
  		st.session_state.name = user_name
  		st.write("name: ", st.session_state.name)
  	if user_age:
  		st.session_state.age = int(user_age)
  		st.write("age: ", st.session_state.age)
  	if user_gender:
  		st.session_state.gender = user_gender
  		st.write("gender: ", st.session_state.gender)
  
  def class1_ex4b():
  	st.subheader("Exercise 4b: Session Data with User Input")
  	st.write("Lets now get input from the user and store it in the session data.")
  	st.write("Now run *ex4a()* again to check the session data. Note that it persists.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  def ex4b():
  	st.subheader("Session Data:")
  	userName = st.text_input("Enter your name")
  	userAge = st.text_input("State your age")
  	userGender = st.selectbox("State your gender", ["", "Male", "Female"])
  
  	if userName:
  		st.session_state.name = userName
  		st.write("name: ", st.session_state.name)
  	if userAge:
  		st.session_state.age = int(userAge)
  		st.write("age: ", st.session_state.age)
  	if userGender:
  		st.session_state.gender = userGender
  		st.write("gender: ", st.session_state.gender)
  ''')
  	st.markdown("**:red[Code Output]**")
  	ex4b()
  
  def ch4():
  	if "name" not in st.session_state:
  		st.session_state.name = "Yoda"
  
  	if "age" not in st.session_state:
  		st.session_state.age = 999
  
  	if "gender" not in st.session_state:
  		st.session_state.gender = "male"
  
  	if "prompt_template" not in st.session_state:
  		st.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  
  	st.write("session_state.name: ", st.session_state.name)
  	st.write("session_state.age: ", st.session_state.age)
  	st.write("session_state.gender: ", st.session_state.gender)
  	st.write("session_state.prompt_template: ", st.session_state.prompt_template)
  
  def class1_ch4():
  	st.subheader("Challenge 4: Session Data")
  	st.markdown("""
  		 Add a new function called ***ch4()*** to the ***part1.py*** file and call it in the main function.\n
  		 In *ch4()*, modify the code in Exercise 4b to include the following:
  		 * Create session data for ***name***, ***age*** and ***gender***
  		 * Create session data for ***prompt_template*** with the following value:
  			 "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  		 * Include this code in ***main()*** as well, because we need the session data for later exercises. Omit the ***st.write*** functions, since we do not want to see this output every time we run ***main()***. \n
  		 Hint:
  		 * In ***ch4()***, to check that the session data is created, you can print out the session data using ***st.write()***:
  		 """)
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  def ch4():
  	if "name" not in st.session_state:
  		st.session_state.name = "Yoda"
  
  	if "age" not in st.session_state:
  		st.session_state.age = 999
  
  	if "gender" not in st.session_state:
  		st.session_state.gender = "male"
  
  	if "prompt_template" not in st.session_state:
  		st.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  
  	st.write("session_state.name: ", st.session_state.name)
  	st.write("session_state.age: ", st.session_state.age)
  	st.write("session_state.gender: ", st.session_state.gender)
  	st.write("session_state.prompt_template: ", st.session_state.prompt_template)
  
  def main():
  	# initialize session state, from ch4
  	if "name" not in st.session_state:
  		st.session_state.name = "Yoda"
  
  	if "age" not in st.session_state:
  		st.session_state.age = 999
  
  	if "gender" not in st.session_state:
  		st.session_state.gender = "male"
  
  	if "prompt_template" not in st.session_state:
  		st.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  		  
  	#the rest of your code is below
  ''')
  		  
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ch4()
  
  def ex5():
  	st.title("My first chatbot")
  
  	if "store_msg" not in st.session_state:
  		st.session_state.store_msg = []
  
  	prompt = st.chat_input("Say something")
  	if prompt:
  		st.write(f"User has sent the following prompt: {prompt}")
  		st.session_state.store_msg.append(prompt)
  		for message in st.session_state.store_msg:
  			with st.chat_message("user"):
  				st.write(message)
  			with st.chat_message("assistant"):
  				st.write("Hello human, what can I do for you?")
  
  def class1_ex5():
  	st.subheader("Exercise 5: Elements of a chatbot")
  	st.write("We will start creating a user interface for our first chatbot.")
  	st.write("Call the following code from ***part1.py*** in your **main()**.")
  	st.write("You should see the output below when you run your programme.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #Exercise 5 : Chatbot UI
  def ex5():
  	st.title("My first chatbot")
  
  	if "store_msg" not in st.session_state:
  		st.session_state.store_msg = []
  
  	prompt = st.chat_input("Say something")
  	if prompt:
  		st.write(f"User has sent the following prompt: {prompt}")
  		st.session_state.store_msg.append(prompt)
  		for message in st.session_state.store_msg:
  			with st.chat_message("user"):
  				st.write(message)
  			with st.chat_message("assistant"):
  				st.write("Hello human, what can I do for you?")
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex5()
  
  def ex6():
  	st.markdown("**Echo Bot**")
  
  	# Initialize chat history
  	if "messages" not in st.session_state:
  		st.session_state.messages = []
  
  	# Display chat messages from history on app rerun
  	for message in st.session_state.messages:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("What is up?"):
  		# Display user message in chat message container
  		st.chat_message("user").markdown(prompt)
  		# Add user message to chat history
  		st.session_state.messages.append({"role": "user", "content": prompt})
  
  		response = f"Echo: {prompt}"
  		# Display assistant response in chat message container
  		with st.chat_message("assistant"):
  			st.markdown(response)
  		# Add assistant response to chat history
  		st.session_state.messages.append({"role": "assistant", "content": response})
  		
  def class1_ex6():
  	st.subheader("Exercise 6: Building a simple echo chatbot")
  	st.write("We will now build a simple echo chatbot.")
  	st.write("Call the following code from **part1.py** in your ***main()***.")
  	st.write("You should see the output below when you run your programme.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #Exercise 6 : Rule-based Echo Chatbot 
  def ex6():
  	st.title("Echo Bot")
  
  	# Initialize chat history
  	if "messages" not in st.session_state:
  		st.session_state.messages = []
  
  	# Display chat messages from history on app rerun
  	for message in st.session_state.messages:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("What is up?"):
  		# Display user message in chat message container
  		st.chat_message("user").markdown(prompt)
  		# Add user message to chat history
  		st.session_state.messages.append({"role": "user", "content": prompt})
  
  		response = f"Echo: {prompt}"
  		# Display assistant response in chat message container
  		with st.chat_message("assistant"):
  			st.markdown(response)
  		# Add assistant response to chat history
  		st.session_state.messages.append({"role": "assistant", "content": response})
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex6()
  
  def ch6():
  	st.markdown("**Rule Based Bot**")
  
  	# Initialize chat history
  	if "messages" not in st.session_state:
  		st.session_state.messages = []
  
  	# # Display chat messages from history on app rerun
  	for message in st.session_state.messages:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("Enter your query"):
  		if prompt == "Hello":
  			reply = "Hi there what can I do for you"
  
  		elif prompt == "What is your name?":
  			reply = "My name is EAI , an electronic artificial being"
  
  		elif prompt == "How old are you?":
  			reply = "Today is my birthday!"
  		
  		else:
  			reply = "I am sorry, I am unable to help you with your query"
  
  		with st.chat_message("user"):
  			st.write(prompt)
  			st.session_state.messages.append({"role": "user", "content": prompt})
  		with st.chat_message("assistant"):
  			st.write(reply)
  			st.session_state.messages.append({"role": "assistant", "content": reply})
  
  def class1_ch6():
  	st.subheader("Challenge 6: Rule based chatbot ")
  	st.markdown("""
  		 Create a new function called ***ch6()*** in **part1.py** and modify the ***ex6()*** function to create the following rule based chatbot:\n
  		 * Human : “Hello”,  Assistant: “Hi there what can I do for you”\n
  		 * Human : “What is your name?”,  Assistant: “My name is EAI , an electronic artificial being”\n	
  		 * Human : “How old are you?”,  Assistant: “Today is my birthday!”\n
  		 For other queries, it will reply “I am sorry, I am unable to help you with your query”\n
  		 Use *if / elif / else* statements to create the chatbot behaviour logic.\n 
  		 You should see the output below when you run your programme.\n
  		 """)
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  #Challenge 6 : Rule-based If-Else Chatbot
  def ch6():
  	st.markdown("**Rule Based Bot**")
  
  	# Initialize chat history
  	if "messages" not in st.session_state:
  		st.session_state.messages = []
  
  	# # Display chat messages from history on app rerun
  	for message in st.session_state.messages:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("Enter your query"):
  		if prompt == "Hello":
  			reply = "Hi there what can I do for you"
  
  		elif prompt == "What is your name?":
  			reply = "My name is EAI , an electronic artificial being"
  
  		elif prompt == "How old are you?":
  			reply = "Today is my birthday!"
  		
  		else:
  			reply = "I am sorry, I am unable to help you with your query"
  
  		with st.chat_message("user"):
  			st.write(prompt)
  			st.session_state.messages.append({"role": "user", "content": prompt})
  		with st.chat_message("assistant"):
  			st.write(reply)
  			st.session_state.messages.append({"role": "assistant", "content": reply})
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ch6()
  
  def class1_ex7():
  	st.subheader("Exercise 7: Secrets- Shhh ")
  	st.write("In this exercise, we will learn how to hide your API key")
  	st.markdown("""
  	In your working directory (chatbot), create a directory called **.streamlit**\n
  	Note the *dot* in front of the directory\n
  	In this folder, create a file called **secrets.toml**\n
  	Get an API key from your OpenAI account and type the following in **secrets.toml**:
  	""")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  	openapi_key = "xxxxxx"
  	''')
  	st.write("Include the following global variables in your ***main.py*** file under the import statements:")
  	st.code('''
  os.environ["OPENAI_API_KEY"] = st.secrets["openapi_key"]
  openai.api_key = st.secrets["openapi_key"]
  ''')
  	st.write("Create a .gitignore file and add .streamlit into it")
  	#st.markdown("**:red[Code Output]**")
  	pass
  
  def class1_ch7():
  	pass
  
  def ex8():
  	st.title("Api Call")
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant."},
  			{"role": "user", "content": "Tell me about Singapore in the 1970s in 50 words."},
  		],
  		temperature=0,
  	)
  	st.markdown("**This is the raw response:**") 
  	st.write(response)
  	st.markdown("**This is the extracted response:**")
  	st.write(response["choices"][0]["message"]["content"].strip())
  	s = str(response["usage"]["total_tokens"])
  	st.markdown("**Total tokens used:**")
  	st.write(s)
  
  def class1_ex8():
  	st.subheader("Exercise 8: Calling the OpenAI LLM API")
  	st.write("In this exercise, we will learn how to call the OpenAI LLM API")
  	st.write("Note that there is a new import statement **import openai**")
  	st.markdown("""
  		 Call the following code in your **main()** and run it.\n
  		 You should see the output as shown below.\n
  		 """)
  	st.markdown("**:blue[Code]**")
  	st.code('''
  import openai
  	 
  #Exercise 8 : Using the OpenAI API
  def ex8():
  	st.title("Api Call")
  	MODEL = "gpt-3.5-turbo"
  
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant."},
  			{"role": "user", "content": "Tell me about Singapore in the 1970s in 50 words."},
  		],
  		temperature=0,
  	)
  
  	st.markdown("**This is the raw response:**") 
  	st.write(response)
  	st.markdown("**This is the extracted response:**")
  	st.write(response["choices"][0]["message"]["content"].strip())
  	s = str(response["usage"]["total_tokens"])
  	st.markdown("**Total tokens used:**")
  	st.write(s)
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex8()
  
  def chat_completion(prompt):
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant."},
  			{"role": "user", "content": prompt},
  		],
  		temperature=0,
  	)
  	return response["choices"][0]["message"]["content"].strip()
  
  def class1_ch8():
  	st.subheader("Challenge 8: Incorporate your LLM API call into your chatbot")
  	st.write("In this challenge, we will incorporate the LLM API call into our previous rule-based *Echo* chatbot")
  	st.markdown("""
  **Step1**\n
  Create a new function **ch8()** in ***part1.py*** and copy the code from **ex6()** into it. Recall that **ex6()** shows the chat history and gets a chat input from the user, and echoes the user input back to the user. \n
  **Step 2**\n
  Next, copy the code from **ex8** into a new function named **chat_completion()**. Recall that **ex8()** is about making an API call.\n
  Now, instead of echoing the user's input in **ex6()**, we will call the LLM API to generate a response. In particular, we are replacing this line of code with the response from the API call:\n
  """)
  	st.code('''
  response = f"Echo: {prompt}"
  ''')
  	st.markdown("""
  **Step 3**\n
  In **chat_completion()**, what we will do is to replace the previous *Tell me the history ..."* prompt from **ex8()** with the current user's input.\n
  In order to do so, in **ch8()**, use the following code to call **chat_completion()**.\n
  What we are doing now is to pass the prompt from the user to the API call instead of hard-coding the prompt as in **ex8()**.\n""")
  	st.code('''
  	 if prompt := st.chat.input("What's up?"):
  	 	#display user messgae in chat message container
  	 	reply = chat_completion(prompt) 
  	 	st.chat_message("user").markdown(prompt)
  		''')
  	st.write("You should see the code output as shown below.")
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''	
  #Challenge 8: Incorporating the API into your chatbot
  def chat_completion(prompt):
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant."},
  			{"role": "user", "content": prompt},
  		],
  		temperature=0,
  	)
  	return response["choices"][0]["message"]["content"].strip()
  	
  def ch8():
  	st.title("My first LLM Chatbot")
  
  	# Initialize chat history
  	if "chat_msg" not in st.session_state:
  		st.session_state.chat_msg = []
  
  	# Display chat chat_msg from history on app rerun
  	for message in st.session_state.chat_msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("What's up?"):
  		# Display user message in chat message container
  		reply = chat_completion(prompt)
  		st.chat_message("user").markdown(prompt)
  		# Add user message to chat history
  		st.session_state.chat_msg.append({"role": "user", "content": prompt})
  		# Display assistant response in chat message container
  		with st.chat_message("assistant"):
  			st.markdown(reply)
  		# Add assistant response to chat history
  		st.session_state.chat_msg.append({"role": "assistant", "content": reply})
  ''')
  	st.markdown("**:red[Code Output]**")
  	st.title("My LLM Chatbot")
  
  	# Initialize chat history
  	if "chat_msg" not in st.session_state:
  		st.session_state.chat_msg = []
  
  	# Display chat chat_msg from history on app rerun
  	for message in st.session_state.chat_msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  
  	# React to user input
  	if prompt := st.chat_input("What is up?"):
  		# Display user message in chat message container
  		reply = chat_completion(prompt)
  		st.chat_message("user").markdown(prompt)
  		# Add user message to chat history
  		st.session_state.chat_msg.append({"role": "user", "content": prompt})
  		# Display assistant response in chat message container
  		with st.chat_message("assistant"):
  			st.markdown(reply)
  		# Add assistant response to chat history
  		st.session_state.chat_msg.append({"role": "assistant", "content": reply})
  
  def chat_completion_stream(prompt):
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant"},
  			{"role": "user", "content": prompt},
  		],
  		temperature=0,  # temperature
  		stream=True,  # stream option
  	)
  	return response
  
  def ex9_basebot():
  	# Initialize chat history
  	if "chat_msg" not in st.session_state:
  		st.session_state.chat_msg = []
  
  	# Showing Chat history
  	for message in st.session_state.chat_msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# set user prompt in chat history
  			st.session_state.chat_msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.chat_msg.append(
  				{"role": "assistant", "content": full_response}
  			)
  	except Exception as e:
  		st.error(e)
  
  def class1_ex9():
  	st.subheader("Exercise 9: Building a ChatGPT-like clone with streaming responses")
  	st.write("Now, we will incorporate a streaming response from the LLM API into our chatbot to mimic the behaviour of ChatGPT.")
  	st.write("Copy and run the code below to see the streaming responses.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # Exercise 9 : Using the OpenAI API with streaming option
  def chat_completion_stream(prompt):
  	openai.api_key = st.secrets["openapi_key"]
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": "You are a helpful assistant"},
  			{"role": "user", "content": prompt},
  		],
  		temperature=0,  # temperature
  		stream=True,  # stream option
  	)
  	return response
  
  # integration API call into streamlit chat components
  def ex9_basebot():
  	# Initialize chat history
  	if "chat_msg" not in st.session_state:
  		st.session_state.chat_msg = []
  
  	# Showing Chat history
  	for message in st.session_state.chat_msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# set user prompt in chat history
  			st.session_state.chat_msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.chat_msg.append(
  				{"role": "assistant", "content": full_response}
  			)
  
  	except Exception as e:
  		st.error(e)
  ''')
  	st.markdown("**:red[Code Output]**")
  	ex9_basebot()
  
  def class1_ch9():
  	pass
  
  def ex10():
  	# prompt_template in session state already set in main()
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": st.session_state.prompt_template},
  			{
  				"role": "user",
  				"content": "Tell me about Singapore in the 1970s in 50 words",
  			},
  		],
  		temperature=0,
  	)
  	st.markdown("**LLM Response:**")
  	st.write(response["choices"][0]["message"]["content"].strip())
  	st.markdown("**Total tokens:**")
  	st.write(str(response["usage"]["total_tokens"]))
  
  def class1_ex10():
  	st.subheader("Exercise 10: Basic Prompt Engineering")
  	st.markdown("""
  		 Now, we are going to create a chatbot with a personality by using a default prompt for our chatbot. \n
  		 This is the default prompt that will be used for every conversation.\n
  		 Let's make it a chatbot that speaks like Yoda from Star Wars.\n
  		 We will use the ***prompt_template*** that is already in our ***main()*** for this.
  		 """)
  	st.code('''
  if "prompt_template" not in st.session_state:
  	st.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"
  	''')
  	st.markdown("""
  		 Run the code below. You should get the same chatbot behaviour as the code output below.\n
  		 Try varying the temperature setting (0.0 to 1.0) to see how it affects the chatbot's response.\n
  		 """)
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # Exercise 10: Basic prompt engineering
  def ex10_basebot():
  	#prompt_template in session state already set in main()
  	MODEL = "gpt-3.5-turbo"
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": st.session_state.prompt_template},
  			{
  				"role": "user",
  				"content": "Tell me about Singapore in the 1970s in 50 words",
  			},
  		],
  		temperature=0,
  	)
  	st.markdown("**LLM Response:**")
  	st.write(response["choices"][0]["message"]["content"].strip())
  	st.markdown("**Total tokens:**")
  	st.write(str(response["usage"]["total_tokens"]))
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex10()
  
  #Challenge 10
  #mod chat complete stream function by replacing system content to session_state prompt template
  def chat_completion_stream_prompt(prompt):
  	MODEL = "gpt-3.5-turbo" #consider changing this to session_state
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": st.session_state.prompt_template},
  			{"role": "user", "content": prompt},
  		],
  		temperature= 0, # temperature
  		stream=True #stream option
  	)
  	return response
  
  # Challenge 10: Make the bot speak like someone you know
  def ch10():
  	#call the function in your base bot
  	#Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	#Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			#set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				#streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  
  	except Exception as e:
  		st.error(e)
  
  def class1_ch10():
  	st.subheader("Challenge 10: Make your bot like someone you know!")
  	st.write("Modify the ***prompt_template*** in your ***main()*** to your own liking.")
  	st.write("Be imaginative!")
  	st.write("Now, in new function called **chat_completion_stream_prompt()**, we are going to modify the earlier **streaming chat_completion** function to accept a user prompt input.")
  	st.write("You will need to pass in a new input variable called **prompt** and replace the user content with the new **prompt** variable.")
  	st.write("Replace the system prompt with **st.session_state.prompt_template**.")
  	st.write("Before calling **chat_completion_stream_prompt()**, get a new prompt from the user like this to update the **st.session_state.prompt_template**:")
  	st.code('''
  if my_prompt_template := st.text_input("Enter a system prompt template. E.g. Speak like Yoda from Star Wars."):
  	st.session_state.prompt_template = my_prompt_template
  	st.write("new prompt template set! ", st.session_state.prompt_template)
  ''')
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  #Challenge 10
  #mod chat complete stream function by replacing system content to session_state prompt template
  def chat_completion_stream_prompt(prompt):
  	MODEL = "gpt-3.5-turbo" #consider changing this to session_state
  	response = openai.ChatCompletion.create(
  		model=MODEL,
  		messages=[
  			{"role": "system", "content": st.session_state.prompt_template},
  			{"role": "user", "content": prompt},
  		],
  		temperature= 0, # temperature
  		stream=True #stream option
  	)
  	return response
  
  # Challenge 10: Make the bot speak like someone you know
  def ch10_basebot():
  	# call the function in your base bot
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			#set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				#streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  
  	except Exception as e:
  		st.error(e)
  ''')
  	st.markdown("**:red[Code Output]**")
  	st.title("ChatGPT-like clone with Prompt Engineering")
  	ch10()
  
  #https://python.langchain.com/docs/modules/chains/
  def ex11a():  # change in ex11a
  	# langchain prompt template
  	prompt = PromptTemplate(
  		input_variables=["subject", "topic"],
  		template="""Design a lesson plan on {subject} on the topic of {topic} for primary 1 students""",
  	)
  
  	# openai_api_key = st.secrets["openapi_key"]
  	llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.9)
  
  	# creating a LLM chain with the langchain call and prompt template
  	chain = LLMChain(llm=llm, prompt=prompt)
  	if st.button("Run my chain"):
  		input_prompt = prompt.format(subject="English", topic="Verbs")
  		# Showing what is sent to LLM Chain
  		st.write("Input prompt: ", input_prompt)
  		# Showing the output from LLM Chain
  		st.write(chain.run({"subject": "English", "topic": "Verbs"}))
  		
  def class1_ex11a():
  	st.subheader("Exercise 11a: Prompt Template with LangChain")
  	st.write("LangChain helps you to create a more complext prompt template for your chatbot.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #https://python.langchain.com/docs/modules/chains/
  def ex11a():  # change in ex11a
  	# langchain prompt template
  	prompt = PromptTemplate(
  		input_variables=["subject", "topic"],
  		template="""Design a lesson plan on {subject} on the topic of {topic} for primary 1 students""",
  	)
  
  	# openai_api_key = st.secrets["openapi_key"]
  	llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.9)
  
  	# creating a LLM chain with the langchain call and prompt template
  	chain = LLMChain(llm=llm, prompt=prompt)
  	if st.button("Run my chain"):
  		input_prompt = prompt.format(subject="English", topic="Verbs")
  		# Showing what is sent to LLM Chain
  		st.write("Input prompt: ", input_prompt)
  		# Showing the output from LLM Chain
  		st.write(chain.run({"subject": "English", "topic": "Verbs"}))
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex11a()
  
  def prompt_inputs_form(): #Using st.form, create the starting prompt to your prompt template, this is an expert on a topic that is talking to a user of a certain age
  	#langchain prompt template
  	with st.form("Prompt Template"):
  		occupation = st.text_input("Enter the occupation:")
  		topic = st.text_input("Enter the topic:")
  		age = st.text_input("Enter the age:")
  
  	# Every form must have a submit button.
  		submitted = st.form_submit_button("Submit")
  	#return a dictionary of the values
  	if submitted:
  		return {
  			'occupation': occupation,
  			'topic': topic,
  			'age': age
  		}
  
  def ex11b():
  	# create your template
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	# create a langchain function call to openai
  	llm = ChatOpenAI(
  		model_name="gpt-3.5-turbo",
  		temperature=0.9,
  	)
  	# create a LLM chain with the langchain call and prompt template
  	chain = LLMChain(llm=llm, prompt=prompt_template)
  	# call the prompt_inputs_form()
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		st.write(chain.run(dict_inputs))
  
  def class1_ex11b():
  	st.subheader("Exercise 11b")
  	st.write("Now, we will create a chatbot with a prompt template that is more complex.")
  	st.write("We will use the ***prompt_inputs_form()*** function to get the user's input for the prompt template.")
  	st.write("Run the code below to see the chatbot in action.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  def prompt_inputs_form():  # Using st.form, create the starting prompt to your prompt template, this is an expert on a topic that is talking to a user of a certain age
  	# langchain prompt template
  	with st.form("Prompt Template"):
  		occupation = st.text_input("Enter the occupation:")
  		topic = st.text_input("Enter the topic:")
  		age = st.text_input("Enter the age:")
  
  		# Every form must have a submit button.
  		submitted = st.form_submit_button("Submit")
  	# return a dictionary of the values
  	if submitted:
  		return {"occupation": occupation, "topic": topic, "age": age}
  
  def ex11b():
  	# create your template
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	# create a langchain function call to openai
  	llm = ChatOpenAI(
  		model_name="gpt-3.5-turbo",
  		temperature=0.9,
  	)
  	# create a LLM chain with the langchain call and prompt template
  	chain = LLMChain(llm=llm, prompt=prompt_template)
  	# call the prompt_inputs_form()
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		st.write(chain.run(dict_inputs))
  ''')
  	
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ex11b()
  
  def ch11():
  	# instead of running of the langchain, we are going to use the prompt template and run it the chatbot using format
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		# set session_state.prompt_template
  		st.session_state.prompt_template = input_prompt
  		st.write("New session_state.prompt_template: ", input_prompt)
  	# call ch10() with the new session_state.prompt_template
  	ch10()
  
  def class1_ch11():
  	st.subheader("Challenge 11: Prompt Template with LangChain")
  	st.write("Now, let's incorporate the prompt template into our chatbot from the previous exercise.")
  	st.write("We will use the ***prompt_inputs_form()*** function to get the user's input for the prompt template.")
  	st.write("You can use the ***ch10*** function from the previous exercise to do the llm api call with the updated session_state.prompt_template.")
  	st.write("Ignore the text input field that asks for a system prompt template from ch10(), since we will be using the prompt template from the user's input.")
  	st.write("As you interact with the chatbot, observe that the prompt template is updated with the latest user input as seen from the code output.")
  
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  def ch11():
  	# instead of running of the langchain, we are going to use the prompt template and run it the chatbot using format
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		# set session_state.prompt_template
  		st.session_state.prompt_template = input_prompt
  		st.write("New session_state.prompt_template: ", input_prompt)
  	# call the ch10() basebot with the new session_state.prompt_template
  	ch10()
  ''')
  	st.markdown("**:red[Code Output]**")
  	# actual code here
  	ch11()
  
  def ex12():
  	memory = ConversationBufferWindowMemory(k=3)
  	memory.save_context({"input": "hi"}, {"output": "whats up?"})
  	memory.save_context({"input": "not much"}, {"output": "what can I help you with?"})
  
  	st.write(memory.load_memory_variables({}))
     
  	memory = ConversationBufferWindowMemory( k=3, return_messages=True)
  	memory.save_context({"input": "hi"}, {"output": "whats up?"})
  	memory.save_context({"input": "not much"}, {"output": "what can I help you with?"})
  
  	st.write(memory.load_memory_variables({}))
  
  def class1_ex12():
  	st.subheader("Exercise 12: Chatbot with memory")
  	st.write("Now, we will create a chatbot with memory.")
  	st.write("You can determine the number of previous messages to remember by setting the ***k*** parameter.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  def ex12():
  	memory = ConversationBufferWindowMemory(k=3)
  	memory.save_context({"input": "hi"}, {"output": "whats up?"})
  	memory.save_context({"input": "not much"}, {"output": "what can I help you with?"})
  
  	st.write(memory.load_memory_variables({}))
     
  	memory = ConversationBufferWindowMemory( k=3, return_messages=True)
  	memory.save_context({"input": "hi"}, {"output": "whats up?"})
  	memory.save_context({"input": "not much"}, {"output": "what can I help you with?"})
  
  	st.write(memory.load_memory_variables({}))
  ''')  
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex12()
  
  def ch12():
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  	else:
  		input_prompt = "You are a helpful assistant. "
  
  	st.write("input prompt: ", input_prompt)
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=3)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write("Memory Data: ", memory_data)
  	st.session_state.prompt_template = f"""
  {input_prompt}										
  
  Below is the conversation history between the AI and Users so far
  										
  {memory_data}
  
  """
  	st.write("New prompt template:", st.session_state.prompt_template)
  	# call the function in your base bot
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  	except Exception as e:
  		st.error(e)
  
  def class1_ch12():
  	st.subheader("Challenge 12: Chatbot with memory")
  	st.write("Now, let's incorporate the memory into the session state prompt template.")
  	st.write("The chatbot should remember the previous user input and use it as the prompt template for the next conversation.")
  	st.write("Start with the following code and modify ex12() to create a chatbot with memory.")
  	st.write("Get the *{input_prompt}* using *prompt_inputs_form()*.")
  	st.write("As you interact with the chatbot, observe that the memory is updated with the latest k number of user input and output as seen from the code output.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  if "memory" not in st.session_state:
  	st.session_state.memory = ConversationBufferWindowMemory(k=5)
  
  	#step 1 save the memory from your chatbot 
  	#step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) 
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write(memory_data)
  	st.session_state.prompt_template = f"""{input_prompt}\n\nBelow is the conversation history between the AI and Users so far\n\n{memory_data}"""
  ''')
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  def ch12():
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  	else:
  		input_prompt = "You are a helpful assistant. "
  
  	st.write("input prompt: ", input_prompt)
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=3)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write("Memory Data: ", memory_data)
  	st.session_state.prompt_template = f"""
  {input_prompt}										
  
  Below is the conversation history between the AI and Users so far
  										
  {memory_data}
  
  """
  
  	st.write("New prompt template: ", st.session_state.prompt_template)
  	# call the function in your base bot
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  	except Exception as e:
  		st.error(e)
  ''')
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ch12()
  
  #exercise 13 - loading
  def upload_file_streamlit():
  	def get_file_extension(file_name):
  		return os.path.splitext(file_name)[1]
  
  	st.subheader("Upload your docs")
  
  	# Streamlit file uploader to accept file input
  	uploaded_file = st.file_uploader("Choose a file", type=["docx", "txt", "pdf"])
  
  	if uploaded_file:
  		# Reading file content
  		file_content = uploaded_file.read()
  
  		# Determine the suffix based on uploaded file's name
  		file_suffix = get_file_extension(uploaded_file.name)
  
  		# Saving the uploaded file temporarily to process it
  		with tempfile.NamedTemporaryFile(delete=False, suffix=file_suffix) as temp_file:
  			temp_file.write(file_content)
  			temp_file.flush()  # Ensure the data is written to the file
  			temp_file_path = temp_file.name
  		return temp_file_path
  	
  #exercise 13 - split and chunk, embeddings and storing in vectorstores for reference
  def vectorstore_creator():
  	# WORKING_DIRECTORY set above in the main.py
  	# Process the temporary file using UnstructuredFileLoader (or any other method you need)
  	embeddings = OpenAIEmbeddings()
  	db = lancedb.connect(WORKING_DIRECTORY)
  	table = db.create_table(
  		"my_table",
  		data=[
  			{
  				"vector": embeddings.embed_query("Query unsuccessful"),
  				"text": "Query unsuccessful",
  				"id": "1",
  			}
  		],
  		mode="overwrite",
  	)
  	# st.write(temp_file_path)
  	temp_file_path = upload_file_streamlit()
  	if temp_file_path:
  		loader = PyPDFLoader(temp_file_path)
  		documents = loader.load_and_split()
  		db = LanceDB.from_documents(documents, embeddings, connection=table)
  		return db
  
  def ex13_vectorstore_creator():
  	if "vectorstore" not in st.session_state:
  		st.session_state.vectorstore = False
  	db = vectorstore_creator()
  	st.session_state.vectorstore = db
  	if st.session_state.vectorstore:
  		query = st.text_input("Enter a query")
  		if query:
  			st.session_state.vectorstore = db
  			docs = db.similarity_search(query)
  			st.write(docs[0].page_content)
  
  def class1_ex13():
  	st.subheader("Exercise 13: Create a vector store")
  	st.write("Now, we will create a vector store to store the user's document.")
  	st.write("This process uses OpenAI to generate embeddings and LanceDB for storing these embeddings.")
  	st.write("For now, this only works for pdf files.")
  	st.write("You may need to run the following commands in terminal to install new libaries:")
  	st.code('''
  pip install tiktoken
  ''')
  	st.markdown("**:blue[Code]**")
  	st.code('''
  #exercise 13 - loading
  def upload_file_streamlit():
  	def get_file_extension(file_name):
  		return os.path.splitext(file_name)[1]
  
  	st.subheader("Upload your docs")
  
  	# Streamlit file uploader to accept file input
  	uploaded_file = st.file_uploader("Choose a file", type=["docx", "txt", "pdf"])
  
  	if uploaded_file:
  		# Reading file content
  		file_content = uploaded_file.read()
  
  		# Determine the suffix based on uploaded file's name
  		file_suffix = get_file_extension(uploaded_file.name)
  
  		# Saving the uploaded file temporarily to process it
  		with tempfile.NamedTemporaryFile(delete=False, suffix=file_suffix) as temp_file:
  			temp_file.write(file_content)
  			temp_file.flush()  # Ensure the data is written to the file
  			temp_file_path = temp_file.name
  		return temp_file_path
  	
  #exercise 13 - split and chunk, embeddings and storing in vectorstores for reference
  def vectorstore_creator():
  	# WORKING_DIRECTORY set above in the main.py
  	# Process the temporary file using UnstructuredFileLoader (or any other method you need)
  	embeddings = OpenAIEmbeddings()
  	db = lancedb.connect(WORKING_DIRECTORY)
  	table = db.create_table(
  		"my_table",
  		data=[
  			{
  				"vector": embeddings.embed_query("Query unsuccessful"),
  				"text": "Query unsuccessful",
  				"id": "1",
  			}
  		],
  		mode="overwrite",
  	)
  	# st.write(temp_file_path)
  	temp_file_path = upload_file_streamlit()
  	if temp_file_path:
  		loader = PyPDFLoader(temp_file_path)
  		documents = loader.load_and_split()
  		db = LanceDB.from_documents(documents, embeddings, connection=table)
  		return db
  
  def ex13_vectorstore_creator():
  	if "vectorstore" not in st.session_state:
  		st.session_state.vectorstore = False
  	db = vectorstore_creator()
  	st.session_state.vectorstore = db
  	if st.session_state.vectorstore:
  		query = st.text_input("Enter a query")
  		if query:
  			st.session_state.vectorstore = db
  			docs = db.similarity_search(query)
  			st.write(docs[0].page_content)
  ''')
  		  
  	st.markdown("**:red[Code Output]**")
  	ex13_vectorstore_creator()
  
  # save the vectorstore in st.session_state
  # add semantic search prompt into memory prompt
  # integrate back into your chatbot
  def ex14():
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		st.session_state.input_prompt = input_prompt
  
  	if "input_prompt" not in st.session_state:
  		st.session_state.input_prompt = "Speak like Yoda from Star Wars"
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=5)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write(memory_data)
  	st.session_state.prompt_template = f"""
  st.session_state.input_prompt: {st.session_state.input_prompt}
  
  This is the last conversation history
  {memory_data}
  
  """
  	st.write("new prompt template: ", st.session_state.prompt_template)
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# query information
  			if st.session_state.vectorstore:
  				docs = st.session_state.vectorstore.similarity_search(prompt)
  				docs = docs[0].page_content
  				# add your query prompt
  				vs_prompt = f"""You should reference this search result to help your answer,
  								{docs}
  								if the search result does not anwer the query, please say you are unable to answer, do not make up an answer"""
  			else:
  				vs_prompt = ""
  			# add query prompt to your memory prompt and send it to LLM
  			st.session_state.prompt_template = (
  				st.session_state.prompt_template + vs_prompt
  			)
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  
  	except Exception as e:
  		st.error(e)
  
  def class1_ex14():
  	st.subheader("Exercise 14: Semantic search")
  	st.write("In this exercise. we will do a semantic search on the vector store in our chatbot.")
  	st.write("At the same time, the chatbot is able to remember its conversation history to some extent.")
  	st.write("This code integrates advanced features like semantic search and context-aware prompts to provide a more engaging and helpful conversational experience.")
  	st.write("Copy and run the code below to see the chatbot in action.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # save the vectorstore in st.session_state
  # add semantic search prompt into memory prompt
  # integrate back into your chatbot
  def ex14_basebot():
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		st.session_state.input_prompt = input_prompt
  
  	if "input_prompt" not in st.session_state:
  		st.session_state.input_prompt = "Speak like Yoda from Star Wars"
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=5)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write(memory_data)
  	st.session_state.prompt_template = f"""
  		{st.session_state.input_prompt}
  
  		This is the last conversation history:
  		{memory_data}"""
  	st.write("new prompt template: ", st.session_state.prompt_template)
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# query information
  			if st.session_state.vectorstore:
  				docs = st.session_state.vectorstore.similarity_search(prompt)
  				docs = docs[0].page_content
  				# add your query prompt
  				vs_prompt = f"""
  					You should reference this search result to help your answer,
  					{docs}
  					if the search result does not anwer the query, please say you are unable to answer, do not make up an answer"""
  			else:
  				vs_prompt = ""
  			# add query prompt to your memory prompt and send it to LLM
  			st.session_state.prompt_template = (
  				st.session_state.prompt_template + vs_prompt
  			)
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  
  	except Exception as e:
  		st.error(e)
  ''')
  
  	st.markdown("**:red[Code Output]**")
  	#actual code here
  	ex14()
  
  def ex15_initialise():
  	# Create or check for the 'database' directory in the current working directory
  	# Set DB_NAME to be within the 'database' directory at the top of main.py
  	# Connect to the SQLite database
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  
  	# Conversation data table
  	cursor.execute(
  		"""
  		CREATE TABLE IF NOT EXISTS data_table (
  			id INTEGER PRIMARY KEY,
  			date TEXT NOT NULL UNIQUE,
  			username TEXT NOT NULL,
  			chatbot_ans TEXT NOT NULL,
  			user_prompt TEXT NOT NULL,
  			tokens TEXT
  		)
  	"""
  	)
  	conn.commit()
  	conn.close()
  
  def ex15_collect(username, chatbot_response, prompt):
  	# collect data from bot
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  	now = datetime.now()  # Using ISO format for date
  	tokens = len(chatbot_response) * 1.3
  	cursor.execute(
  		"""
  		INSERT INTO data_table (date, username,chatbot_ans, user_prompt, tokens)
  		VALUES (?, ?, ?, ?, ?)
  	""",
  		(now, username, chatbot_response, prompt, tokens),
  	)
  	conn.commit()
  	conn.close()
  
  # implementing data collection and displaying
  def ex15():
  	# initialise database first
  	ex15_initialise()
  	# collect some data
  	ex15_collect("yoda", "I am Yoda. The Force is strong with you", "Who are you?")
  	# display data
  	# Connect to the specified database
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  
  	# Fetch all data from data_table
  	cursor.execute("SELECT * FROM data_table")
  	rows = cursor.fetchall()
  	column_names = [description[0] for description in cursor.description]
  	df = pd.DataFrame(rows, columns=column_names)
  	st.dataframe(df)
  	conn.close()
  
  def class1_ex15():
  	st.subheader("Exercise 15: Using a database")
  	st.write("In this exercise, we will demonstrate how to create a database, as well as how to store and retrieve data from it.")
  	st.markdown("**:blue[Code]**")
  	st.code('''
  def ex15_initialise():
  	# Create or check for the 'database' directory in the current working directory
  	# Set DB_NAME to be within the 'database' directory at the top of main.py
  	# Connect to the SQLite database
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  
  	# Conversation data table
  	cursor.execute(
  		"""
  		CREATE TABLE IF NOT EXISTS data_table (
  			id INTEGER PRIMARY KEY,
  			date TEXT NOT NULL UNIQUE,
  			username TEXT NOT NULL,
  			chatbot_ans TEXT NOT NULL,
  			user_prompt TEXT NOT NULL,
  			tokens TEXT
  		)
  	"""
  	)
  	conn.commit()
  	conn.close()
  
  def ex15_collect(username, chatbot_response, prompt):
  	# collect data from bot
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  	now = datetime.now()  # Using ISO format for date
  	tokens = len(chatbot_response) * 1.3
  	cursor.execute(
  		"""
  		INSERT INTO data_table (date, username,chatbot_ans, user_prompt, tokens)
  		VALUES (?, ?, ?, ?, ?)
  	""",
  		(now, username, chatbot_response, prompt, tokens),
  	)
  	conn.commit()
  	conn.close()
  
  # implementing data collection and displaying
  def ex15():
  	# initialise database first
  	ex15_initialise()
  	# collect some data
  	ex15_collect("yoda", "I am Yoda. The Force is strong with you", "Who are you?")
  	# display data
  	# Connect to the specified database
  	conn = sqlite3.connect(DB_NAME)
  	cursor = conn.cursor()
  
  	# Fetch all data from data_table
  	cursor.execute("SELECT * FROM data_table")
  	rows = cursor.fetchall()
  	column_names = [description[0] for description in cursor.description]
  	df = pd.DataFrame(rows, columns=column_names)
  	st.dataframe(df)
  	conn.close()
  ''')
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ex15()
  
  def ch15_chatbot():
  	#display ex15 table
  	ex15()
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		st.session_state.input_prompt = input_prompt
  
  	if "input_prompt" not in st.session_state:
  		st.session_state.input_prompt = "Speak like Yoda from Star Wars"
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=5)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write(memory_data)
  	st.session_state.prompt_template = f"""{st.session_state.input_prompt}
  										This is the last conversation history
  										{memory_data}
  										"""
  	st.write("new prompt template: ", st.session_state.prompt_template)
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# query information
  			if st.session_state.vectorstore:
  				docs = st.session_state.vectorstore.similarity_search(prompt)
  				docs = docs[0].page_content
  				# add your query prompt
  				vs_prompt = f"""You should reference this search result to help your answer,
  								{docs}
  								if the search result does not anwer the query, please say you are unable to answer, do not make up an answer"""
  			else:
  				vs_prompt = ""
  			# add query prompt to your memory prompt and send it to LLM
  			st.session_state.prompt_template = (
  				st.session_state.prompt_template + vs_prompt
  			)
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  
  			ex15_collect(st.session_state.name, full_response, prompt)
  
  	except Exception as e:
  		st.error(e)
  
  def class1_ch15():
  	st.subheader("Challenge 15: Using a database")
  	st.write("For this challenge, we will incorporate using a database from our previous exercise.")
  	st.write("Copy the code from ***ex14()*** and use the ***ex15()*** to collect and display the data.")
  
  	st.markdown("**:blue[Code]**")
  	with st.expander("Reveal Code"):
  		st.code('''
  def ch15_chatbot():
  	#display ex15 table
  	ex15()
  	# Prompt_template form from ex11
  	prompt_template = PromptTemplate(
  		input_variables=["occupation", "topic", "age"],
  		template="""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information
  						to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""",
  	)
  	dict_inputs = prompt_inputs_form()
  	if dict_inputs:
  		input_prompt = prompt_template.format(
  			occupation=dict_inputs["occupation"],
  			topic=dict_inputs["topic"],
  			age=dict_inputs["age"],
  		)
  		st.session_state.input_prompt = input_prompt
  
  	if "input_prompt" not in st.session_state:
  		st.session_state.input_prompt = "Speak like Yoda from Star Wars"
  
  	if "memory" not in st.session_state:
  		st.session_state.memory = ConversationBufferWindowMemory(k=5)
  
  	# step 1 save the memory from your chatbot
  	# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint
  	memory_data = st.session_state.memory.load_memory_variables({})
  	st.write(memory_data)
  	st.session_state.prompt_template = f"""{st.session_state.input_prompt}
  										This is the last conversation history
  										{memory_data}
  										"""
  	st.write("new prompt template: ", st.session_state.prompt_template)
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	# Initialize chat history
  	if "msg" not in st.session_state:
  		st.session_state.msg = []
  
  	# Showing Chat history
  	for message in st.session_state.msg:
  		with st.chat_message(message["role"]):
  			st.markdown(message["content"])
  	try:
  		#
  		if prompt := st.chat_input("What is up?"):
  			# query information
  			if st.session_state.vectorstore:
  				docs = st.session_state.vectorstore.similarity_search(prompt)
  				docs = docs[0].page_content
  				# add your query prompt
  				vs_prompt = f"""You should reference this search result to help your answer,
  								{docs}
  								if the search result does not anwer the query, please say you are unable to answer, do not make up an answer"""
  			else:
  				vs_prompt = ""
  			# add query prompt to your memory prompt and send it to LLM
  			st.session_state.prompt_template = (
  				st.session_state.prompt_template + vs_prompt
  			)
  			# set user prompt in chat history
  			st.session_state.msg.append({"role": "user", "content": prompt})
  			with st.chat_message("user"):
  				st.markdown(prompt)
  
  			with st.chat_message("assistant"):
  				message_placeholder = st.empty()
  				full_response = ""
  				# streaming function
  				for response in chat_completion_stream_prompt(prompt):
  					full_response += response.choices[0].delta.get("content", "")
  					message_placeholder.markdown(full_response + "▌")
  				message_placeholder.markdown(full_response)
  			st.session_state.msg.append({"role": "assistant", "content": full_response})
  			st.session_state.memory.save_context(
  				{"input": prompt}, {"output": full_response}
  			)
  
  			ex15_collect(st.session_state.name, full_response, prompt)
  
  	except Exception as e:
  		st.error(e)
  ''')
  		  
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ch15_chatbot()
  
  # smart agents accessing the internet for free
  # https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/search_and_chat.py
  def ex16():
  	st.title("🦜 LangChain: Chat with internet search")
  
  	msgs = StreamlitChatMessageHistory()
  	memory = ConversationBufferMemory(
  		chat_memory=msgs,
  		return_messages=True,
  		memory_key="chat_history",
  		output_key="output",
  	)
  	if len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):
  		msgs.clear()
  		msgs.add_ai_message("How can I help you?")
  		st.session_state.steps = {}
  
  	avatars = {"human": "user", "ai": "assistant"}
  	for idx, msg in enumerate(msgs.messages):
  		with st.chat_message(avatars[msg.type]):
  			# Render intermediate steps if any were saved
  			for step in st.session_state.steps.get(str(idx), []):
  				if step[0].tool == "_Exception":
  					continue
  				with st.status(
  					f"**{step[0].tool}**: {step[0].tool_input}", state="complete"
  				):
  					st.write(step[0].log)
  					st.write(step[1])
  			st.write(msg.content)
  
  	if prompt := st.chat_input(placeholder="Enter a query on the Internet"):
  		st.chat_message("user").write(prompt)
  
  		llm = ChatOpenAI(
  			model_name="gpt-3.5-turbo", openai_api_key=openai.api_key, streaming=True
  		)
  		tools = [DuckDuckGoSearchRun(name="Search")]
  		chat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)
  		executor = AgentExecutor.from_agent_and_tools(
  			agent=chat_agent,
  			tools=tools,
  			memory=memory,
  			return_intermediate_steps=True,
  			handle_parsing_errors=True,
  		)
  		with st.chat_message("assistant"):
  			st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
  			response = executor(prompt, callbacks=[st_cb])
  			st.write(response["output"])
  			st.session_state.steps[str(len(msgs.messages) - 1)] = response[
  				"intermediate_steps"
  			]
  
  def class1_ex16():
  	st.subheader("Exercise 16: Smart agent")
  	st.write("In this exercise, we will configure a chatbot with an internet search tool that shows all intermediate steps and tool logs.")
  	st.write("This overcomes the limitation of the training data that is only up to a certain point in time, by being able to access the current internet to search for answers.")
  
  	st.write("You may need to run the following commands in terminal to install new libaries:")
  	st.code('''
  pip install duckduckgo-search
  ''')
  	
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # smart agents accessing the internet for free
  # https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/search_and_chat.py
  def ex16_agent_bot():
  	st.title("🦜 LangChain: Chat with internet search")
  
  	msgs = StreamlitChatMessageHistory()
  	memory = ConversationBufferMemory(
  		chat_memory=msgs,
  		return_messages=True,
  		memory_key="chat_history",
  		output_key="output",
  	)
  	if len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):
  		msgs.clear()
  		msgs.add_ai_message("How can I help you?")
  		st.session_state.steps = {}
  
  	avatars = {"human": "user", "ai": "assistant"}
  	for idx, msg in enumerate(msgs.messages):
  		with st.chat_message(avatars[msg.type]):
  			# Render intermediate steps if any were saved
  			for step in st.session_state.steps.get(str(idx), []):
  				if step[0].tool == "_Exception":
  					continue
  				with st.status(
  					f"**{step[0].tool}**: {step[0].tool_input}", state="complete"
  				):
  					st.write(step[0].log)
  					st.write(step[1])
  			st.write(msg.content)
  
  	if prompt := st.chat_input(placeholder="Enter a query on the Internet"):
  		st.chat_message("user").write(prompt)
  
  		llm = ChatOpenAI(
  			model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True
  		)
  		tools = [DuckDuckGoSearchRun(name="Search")]
  		chat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)
  		executor = AgentExecutor.from_agent_and_tools(
  			agent=chat_agent,
  			tools=tools,
  			memory=memory,
  			return_intermediate_steps=True,
  			handle_parsing_errors=True,
  		)
  		with st.chat_message("assistant"):
  			st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
  			response = executor(prompt, callbacks=[st_cb])
  			st.write(response["output"])
  			st.session_state.steps[str(len(msgs.messages) - 1)] = response[
  				"intermediate_steps"
  			]
  ''')
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ex16()
  
  # agents ,vectorstores, wiki
  # https://python.langchain.com/docs/modules/agents/how_to/custom_agent_with_tool_retrieval
  # note tool
  @tool("Document search")
  def document_search(query: str) -> str:
  	# this is the prompt to the tool itself
  	"Use this function first to search for documents pertaining to the query before going into the internet"
  	docs = st.session_state.vectorstore.similarity_search(query)
  	docs = docs[0].page_content
  	json_string = json.dumps(docs, ensure_ascii=False, indent=4)
  	return json_string
  
  # combine vector store and internet search
  def ex17():
  	st.title("🦜 LangChain: Chat with internet search")
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	msgs = StreamlitChatMessageHistory()
  	memory = ConversationBufferMemory(
  		chat_memory=msgs,
  		return_messages=True,
  		memory_key="chat_history",
  		output_key="output",
  	)
  	if len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):
  		msgs.clear()
  		msgs.add_ai_message("How can I help you?")
  		st.session_state.steps = {}
  
  	avatars = {"human": "user", "ai": "assistant"}
  	for idx, msg in enumerate(msgs.messages):
  		with st.chat_message(avatars[msg.type]):
  			# Render intermediate steps if any were saved
  			for step in st.session_state.steps.get(str(idx), []):
  				if step[0].tool == "_Exception":
  					continue
  				with st.status(
  					f"**{step[0].tool}**: {step[0].tool_input}", state="complete"
  				):
  					st.write(step[0].log)
  					st.write(step[1])
  			st.write(msg.content)
  
  	if prompt := st.chat_input(placeholder="Enter a query on the Internet"):
  		st.chat_message("user").write(prompt)
  
  		llm = ChatOpenAI(
  			model_name="gpt-3.5-turbo", openai_api_key=openai.api_key, streaming=True
  		)
  		tools = [document_search, DuckDuckGoSearchRun(name="Internet Search")]
  		chat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)
  		executor = AgentExecutor.from_agent_and_tools(
  			agent=chat_agent,
  			tools=tools,
  			memory=memory,
  			return_intermediate_steps=True,
  			handle_parsing_errors=True,
  		)
  		with st.chat_message("assistant"):
  			st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
  			response = executor(prompt, callbacks=[st_cb])
  			st.write(response["output"])
  			st.session_state.steps[str(len(msgs.messages) - 1)] = response[
  				"intermediate_steps"
  			]
  
  def class1_ex17():
  	st.subheader("Exercise 17: Smart agent with vector store")
  	st.write("In this exercise, we will combine the vector store with the smart agent.")
  	st.write("This allows the chatbot to search for answers from the vector store and the internet.")
  	st.write("The @tool(\"Document search\") function is an enhancement to the chatbot. It allows for an initial internal document search based on the user query before resorting to external internet searches. ")
  	st.write("Copy and run the code below to see the chatbot in action.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # agents ,vectorstores, wiki
  # https://python.langchain.com/docs/modules/agents/how_to/custom_agent_with_tool_retrieval
  # note tool
  @tool("Document search")
  def document_search(query: str) -> str:
  	# this is the prompt to the tool itself
  	"Use this function first to search for documents pertaining to the query before going into the internet"
  	docs = st.session_state.vectorstore.similarity_search(query)
  	docs = docs[0].page_content
  	json_string = json.dumps(docs, ensure_ascii=False, indent=4)
  	return json_string
  
  # combine vector store and internet search
  def ex17_agent_bot():
  	st.title("🦜 LangChain: Chat with internet search")
  
  	st.session_state.vectorstore = vectorstore_creator()
  
  	msgs = StreamlitChatMessageHistory()
  	memory = ConversationBufferMemory(
  		chat_memory=msgs,
  		return_messages=True,
  		memory_key="chat_history",
  		output_key="output",
  	)
  	if len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):
  		msgs.clear()
  		msgs.add_ai_message("How can I help you?")
  		st.session_state.steps = {}
  
  	avatars = {"human": "user", "ai": "assistant"}
  	for idx, msg in enumerate(msgs.messages):
  		with st.chat_message(avatars[msg.type]):
  			# Render intermediate steps if any were saved
  			for step in st.session_state.steps.get(str(idx), []):
  				if step[0].tool == "_Exception":
  					continue
  				with st.status(
  					f"**{step[0].tool}**: {step[0].tool_input}", state="complete"
  				):
  					st.write(step[0].log)
  					st.write(step[1])
  			st.write(msg.content)
  
  	if prompt := st.chat_input(placeholder="Enter a query on the Internet"):
  		st.chat_message("user").write(prompt)
  
  		llm = ChatOpenAI(
  			model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True
  		)
  		tools = [document_search, DuckDuckGoSearchRun(name="Internet Search")]
  		chat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)
  		executor = AgentExecutor.from_agent_and_tools(
  			agent=chat_agent,
  			tools=tools,
  			memory=memory,
  			return_intermediate_steps=True,
  			handle_parsing_errors=True,
  		)
  		with st.chat_message("assistant"):
  			st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
  			response = executor(prompt, callbacks=[st_cb])
  			st.write(response["output"])
  			st.session_state.steps[str(len(msgs.messages) - 1)] = response[
  				"intermediate_steps"
  			]
  ''')
  	st.markdown("**:red[Code Output]**")
  	# Actual code here
  	ex17()
  
  # PandasAI- A smart agent that can do visual analytics
  def ex18():
  	st.title("pandas-ai streamlit interface")
  
  	# Upload CSV file using st.file_uploader
  	uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
  	if "openai_key" not in st.session_state:
  		st.session_state.openai_key = st.secrets["openapi_key"]
  		st.session_state.prompt_history = []
  		st.session_state.df = None
  
  	if uploaded_file is not None:
  		try:
  			df = pd.read_csv(uploaded_file)
  			st.session_state.df = df
  		except Exception as e:
  			st.write("There was an error processing the CSV file.")
  			st.write(e)
  
  	else:
  		st.session_state.df = pd.DataFrame(
  			{
  				"country": [
  					"United States",
  					"United Kingdom",
  					"France",
  					"Germany",
  					"Italy",
  					"Spain",
  					"Canada",
  					"Australia",
  					"Japan",
  					"China",
  				],
  				"gdp": [
  					19294482071552,
  					2891615567872,
  					2411255037952,
  					3435817336832,
  					1745433788416,
  					1181205135360,
  					1607402389504,
  					1490967855104,
  					4380756541440,
  					14631844184064,
  				],
  				"happiness_index": [
  					6.94,
  					7.16,
  					6.66,
  					7.07,
  					6.38,
  					6.4,
  					7.23,
  					7.22,
  					5.87,
  					5.12,
  				],
  			}
  		)
  	chart_path = os.path.join("exports/charts")
  	with st.form("Question"):
  		question = st.text_input("Question", value="", type="default")
  		submitted = st.form_submit_button("Submit")
  		if submitted:
  			with st.spinner():
  				llm = OpenAI(api_token=st.session_state.openai_key)
  				df = SmartDataframe(
  					st.session_state.df,
  					config={
  						"llm": llm,
  						"save_charts_path": chart_path,
  						"save_charts": True,
  						"verbose": True,
  					},
  				)
  				response = df.chat(
  					question
  				)  # Using 'chat' method based on your context
  
  				# Display the textual response (if any):
  				if response:
  					st.write(response)
  				chart_path = os.path.join("exports/charts", "temp_chart.png")
  				if os.path.exists(chart_path):
  					st.image(
  						chart_path, caption="Generated Chart", use_column_width=True
  					)
  				# Append the question to the history:
  				st.session_state.prompt_history.append(question)
  
  	if st.session_state.df is not None:
  		st.subheader("Current dataframe:")
  		st.write(st.session_state.df)
  
  	st.subheader("Prompt history:")
  	st.write(st.session_state.prompt_history)
  
  	if st.button("Clear"):
  		st.session_state.prompt_history = []
  		st.session_state.df = None
  
  def class1_ex18():
  	st.subheader("Exercise 18: Data Analytics")
  	st.write("In this exercise, we will use the Pandas AI library to perform data analytics.")
  	st.write("The Pandas AI library is a smart agent that can perform data analytics on a dataframe.")
  	st.write("You may need to install the following library:")
  	st.code('''pip install bs4''')
  	st.write("Copy and run the code below to see the chatbot in action.")
  
  	st.markdown("**:blue[Code]**")
  	st.code('''
  # PandasAI- A smart agent that can do visual analytics
  def ex18_pandas_AI():
  	st.title("pandas-ai streamlit interface")
  
  	# Upload CSV file using st.file_uploader
  	uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
  	if "openai_key" not in st.session_state:
  		st.session_state.openai_key = st.secrets["openapi_key"]
  		st.session_state.prompt_history = []
  		st.session_state.df = None
  
  	if uploaded_file is not None:
  		try:
  			df = pd.read_csv(uploaded_file)
  			st.session_state.df = df
  		except Exception as e:
  			st.write("There was an error processing the CSV file.")
  			st.write(e)
  
  	else:
  		st.session_state.df = pd.DataFrame(
  			{
  				"country": [
  					"United States",
  					"United Kingdom",
  					"France",
  					"Germany",
  					"Italy",
  					"Spain",
  					"Canada",
  					"Australia",
  					"Japan",
  					"China",
  				],
  				"gdp": [
  					19294482071552,
  					2891615567872,
  					2411255037952,
  					3435817336832,
  					1745433788416,
  					1181205135360,
  					1607402389504,
  					1490967855104,
  					4380756541440,
  					14631844184064,
  				],
  				"happiness_index": [
  					6.94,
  					7.16,
  					6.66,
  					7.07,
  					6.38,
  					6.4,
  					7.23,
  					7.22,
  					5.87,
  					5.12,
  				],
  			}
  		)
  	chart_path = os.path.join("exports/charts")
  	with st.form("Question"):
  		question = st.text_input("Question", value="", type="default")
  		submitted = st.form_submit_button("Submit")
  		if submitted:
  			with st.spinner():
  				llm = OpenAI(api_token=st.session_state.openai_key)
  				df = SmartDataframe(
  					st.session_state.df,
  					config={
  						"llm": llm,
  						"save_charts_path": chart_path,
  						"save_charts": True,
  						"verbose": True,
  					},
  				)
  				response = df.chat(
  					question
  				)  # Using 'chat' method based on your context
  
  				# Display the textual response (if any):
  				if response:
  					st.write(response)
  				chart_path = os.path.join("exports/charts", "temp_chart.png")
  				if os.path.exists(chart_path):
  					st.image(
  						chart_path, caption="Generated Chart", use_column_width=True
  					)
  				# Append the question to the history:
  				st.session_state.prompt_history.append(question)
  
  	if st.session_state.df is not None:
  		st.subheader("Current dataframe:")
  		st.write(st.session_state.df)
  
  	st.subheader("Prompt history:")
  	st.write(st.session_state.prompt_history)
  
  	if st.button("Clear"):
  		st.session_state.prompt_history = []
  		st.session_state.df = None
  ''')
  	st.markdown("**:red[Code Output]**")
  	ex18()
apis: lancedb.connect
extract_api: [((1222, 1233), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1231, 1233), False, 'import os\n'), ((1254, 1283), 'os.path.join', 'os.path.join', (['cwd', '"""database"""'], {}), "(cwd, 'database')\n", (1266, 1283), False, 'import os\n'), ((1375, 1420), 'os.path.join', 'os.path.join', (['WORKING_DIRECTORY', '"""default_db"""'], {}), "(WORKING_DIRECTORY, 'default_db')\n", (1387, 1420), False, 'import os\n'), ((86756, 86779), 'langchain.agents.tool', 'tool', (['"""Document search"""'], {}), "('Document search')\n", (86760, 86779), False, 'from langchain.agents import tool\n'), ((1292, 1325), 'os.path.exists', 'os.path.exists', (['WORKING_DIRECTORY'], {}), '(WORKING_DIRECTORY)\n', (1306, 1325), False, 'import os\n'), ((1328, 1358), 'os.makedirs', 'os.makedirs', (['WORKING_DIRECTORY'], {}), '(WORKING_DIRECTORY)\n', (1339, 1358), False, 'import os\n'), ((1439, 1463), 'streamlit.subheader', 'st.subheader', (['"""Template"""'], {}), "('Template')\n", (1451, 1463), True, 'import streamlit as st\n'), ((1465, 1495), 'streamlit.write', 'st.write', (['"""Instruction lines."""'], {}), "('Instruction lines.')\n", (1473, 1495), True, 'import streamlit as st\n'), ((1498, 1528), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (1509, 1528), True, 'import streamlit as st\n'), ((1530, 1566), 'streamlit.code', 'st.code', (['"""\n#exercise code here\n"""'], {}), '("""\n#exercise code here\n""")\n', (1537, 1566), True, 'import streamlit as st\n'), ((1568, 1598), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (1579, 1598), True, 'import streamlit as st\n'), ((1677, 1713), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (1688, 1713), True, 'import streamlit as st\n'), ((1844, 1856), 'streamlit.divider', 'st.divider', ([], {}), '()\n', (1854, 1856), True, 'import streamlit as st\n'), ((1858, 1892), 'streamlit.subheader', 'st.subheader', (['"""Pre-workshop Setup"""'], {}), "('Pre-workshop Setup')\n", (1870, 1892), True, 'import streamlit as st\n'), ((1910, 2088), 'streamlit.markdown', 'st.markdown', (['"""1. Visual Studio (VS Code): this is the Integrated Development Environment (IDE) of choice by many coders and will make it easier for us to code our app."""'], {}), "(\n    '1. Visual Studio (VS Code): this is the Integrated Development Environment (IDE) of choice by many coders and will make it easier for us to code our app.'\n    )\n", (1921, 2088), True, 'import streamlit as st\n'), ((2084, 2217), 'streamlit.markdown', 'st.markdown', (['"""2. Python (3.10 release or later): this is the coding language of choice for many data science related apps."""'], {}), "(\n    '2. Python (3.10 release or later): this is the coding language of choice for many data science related apps.'\n    )\n", (2095, 2217), True, 'import streamlit as st\n'), ((2213, 2621), 'streamlit.write', 'st.write', (['"""\n\t\t\t3. Once you have installed the above, we will need to set up a virtual environment and install the libraries in that environment.\n\n\t\t\t\tCreate a folder named “chatbot” anywhere, e.g. in your Desktop.\n \n\t\t\t\tOpen VS Code and navigate to the folder in a new terminal window.\n \n\t\t\t\tCreate a virtual environment and activate it by entering the following commands in the terminal:\n\t\t\t """'], {}), '(\n    """\n\t\t\t3. Once you have installed the above, we will need to set up a virtual environment and install the libraries in that environment.\n\n\t\t\t\tCreate a folder named “chatbot” anywhere, e.g. in your Desktop.\n \n\t\t\t\tOpen VS Code and navigate to the folder in a new terminal window.\n \n\t\t\t\tCreate a virtual environment and activate it by entering the following commands in the terminal:\n\t\t\t """\n    )\n', (2221, 2621), True, 'import streamlit as st\n'), ((2616, 2644), 'streamlit.markdown', 'st.markdown', (['"""   **a) Mac**"""'], {}), "('   **a) Mac**')\n", (2627, 2644), True, 'import streamlit as st\n'), ((2646, 2716), 'streamlit.code', 'st.code', (['"""\n\t\tpython3 -m venv venv\n\t\tsource venv/bin/activate \n\t\t\t"""'], {}), '("""\n\t\tpython3 -m venv venv\n\t\tsource venv/bin/activate \n\t\t\t""")\n', (2653, 2716), True, 'import streamlit as st\n'), ((2718, 2796), 'streamlit.markdown', 'st.markdown', (['"""(You should see a (venv) appear in your terminal window prompt)"""'], {}), "('(You should see a (venv) appear in your terminal window prompt)')\n", (2729, 2796), True, 'import streamlit as st\n'), ((2798, 2814), 'streamlit.markdown', 'st.markdown', (['"""#"""'], {}), "('#')\n", (2809, 2814), True, 'import streamlit as st\n'), ((2816, 2848), 'streamlit.markdown', 'st.markdown', (['"""   **b) Windows**"""'], {}), "('   **b) Windows**')\n", (2827, 2848), True, 'import streamlit as st\n'), ((2850, 2921), 'streamlit.code', 'st.code', (['"""\n\t\tpython -m venv venv\n\t\tcd venv\\\\Scripts\n\t\tactivate\n\t\t\t"""'], {}), '("""\n\t\tpython -m venv venv\n\t\tcd venv\\\\Scripts\n\t\tactivate\n\t\t\t""")\n', (2857, 2921), True, 'import streamlit as st\n'), ((2922, 3072), 'streamlit.markdown', 'st.markdown', (['"""4. While in your virtual environment, install the libraries using pip which should already be installed together with Python:"""'], {}), "(\n    '4. While in your virtual environment, install the libraries using pip which should already be installed together with Python:'\n    )\n", (2933, 3072), True, 'import streamlit as st\n'), ((3064, 3114), 'streamlit.code', 'st.code', (['"""\n\t\tpip install streamlit openai\n\t\t\t"""'], {}), '("""\n\t\tpip install streamlit openai\n\t\t\t""")\n', (3071, 3114), True, 'import streamlit as st\n'), ((3116, 3193), 'streamlit.markdown', 'st.markdown', (['""" To test if Streamlit is installed properly, run this command:"""'], {}), "(' To test if Streamlit is installed properly, run this command:')\n", (3127, 3193), True, 'import streamlit as st\n'), ((3195, 3231), 'streamlit.code', 'st.code', (['"""\n\tstreamlit hello\n\t\t\t"""'], {}), '("""\n\tstreamlit hello\n\t\t\t""")\n', (3202, 3231), True, 'import streamlit as st\n'), ((3233, 3325), 'streamlit.markdown', 'st.markdown', (['""" You should see a Streamlit application running at http://localhost:8501"""'], {}), "(\n    ' You should see a Streamlit application running at http://localhost:8501')\n", (3244, 3325), True, 'import streamlit as st\n'), ((3322, 3397), 'streamlit.markdown', 'st.markdown', (['""" Type Ctrl + C in VS Code terminal to stop the Streamlit app"""'], {}), "(' Type Ctrl + C in VS Code terminal to stop the Streamlit app')\n", (3333, 3397), True, 'import streamlit as st\n'), ((3424, 3464), 'streamlit.subheader', 'st.subheader', (['"""My first Hello World app"""'], {}), "('My first Hello World app')\n", (3436, 3464), True, 'import streamlit as st\n'), ((3466, 3478), 'streamlit.divider', 'st.divider', ([], {}), '()\n', (3476, 3478), True, 'import streamlit as st\n'), ((3480, 3533), 'streamlit.markdown', 'st.markdown', (['"""1. Create a new file called \'main.py\'."""'], {}), '("1. Create a new file called \'main.py\'.")\n', (3491, 3533), True, 'import streamlit as st\n'), ((3539, 3640), 'streamlit.markdown', 'st.markdown', (['"""2. Copy the code below and paste it in the newly created helloworld.py file."""'], {}), "(\n    '2. Copy the code below and paste it in the newly created helloworld.py file.'\n    )\n", (3550, 3640), True, 'import streamlit as st\n'), ((3636, 3666), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (3647, 3666), True, 'import streamlit as st\n'), ((3668, 3778), 'streamlit.code', 'st.code', (['"""\n\t\t\timport streamlit as st\n\t\t\t#my first Hello World app\n\t\t\tst.write("Hello World")\n\t\t"""'], {}), '(\n    """\n\t\t\timport streamlit as st\n\t\t\t#my first Hello World app\n\t\t\tst.write("Hello World")\n\t\t"""\n    )\n', (3675, 3778), True, 'import streamlit as st\n'), ((3770, 3868), 'streamlit.markdown', 'st.markdown', (['"""Install the watchdog module by running the command below in the terminal."""'], {}), "(\n    'Install the watchdog module by running the command below in the terminal.'\n    )\n", (3781, 3868), True, 'import streamlit as st\n'), ((3860, 3891), 'streamlit.code', 'st.code', (['"""pip install watchdog"""'], {}), "('pip install watchdog')\n", (3867, 3891), True, 'import streamlit as st\n'), ((3893, 4030), 'streamlit.markdown', 'st.markdown', (['"""Now you don\'t have to keep restarting the app to see the changes you make to the code. Just refresh the browser."""'], {}), '(\n    "Now you don\'t have to keep restarting the app to see the changes you make to the code. Just refresh the browser."\n    )\n', (3904, 4030), True, 'import streamlit as st\n'), ((4022, 4123), 'streamlit.write', 'st.write', (['"""Save your file and run the app by typing the following command in the terminal:"""'], {}), "(\n    'Save your file and run the app by typing the following command in the terminal:'\n    )\n", (4030, 4123), True, 'import streamlit as st\n'), ((4115, 4158), 'streamlit.code', 'st.code', (['"""\n\t\t\tstreamlit run main.py\n\t\t"""'], {}), '("""\n\t\t\tstreamlit run main.py\n\t\t""")\n', (4122, 4158), True, 'import streamlit as st\n'), ((4160, 4259), 'streamlit.markdown', 'st.markdown', (['"""3. You should see a Streamlit application running at http://localhost:8501"""'], {}), "(\n    '3. You should see a Streamlit application running at http://localhost:8501'\n    )\n", (4171, 4259), True, 'import streamlit as st\n'), ((4255, 4332), 'streamlit.markdown', 'st.markdown', (['"""4. Type Ctrl + C in VS Code terminal to stop the Streamlit app"""'], {}), "('4. Type Ctrl + C in VS Code terminal to stop the Streamlit app')\n", (4266, 4332), True, 'import streamlit as st\n'), ((4338, 4374), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (4349, 4374), True, 'import streamlit as st\n'), ((4376, 4399), 'streamlit.write', 'st.write', (['"""Hello World"""'], {}), "('Hello World')\n", (4384, 4399), True, 'import streamlit as st\n'), ((4426, 4452), 'streamlit.subheader', 'st.subheader', (['"""Objectives"""'], {}), "('Objectives')\n", (4438, 4452), True, 'import streamlit as st\n'), ((4454, 4561), 'streamlit.markdown', 'st.markdown', (['"""1. Learn how to use Python and Streamlit library to create an interactive web app."""'], {}), "(\n    '1. Learn how to use Python and Streamlit library to create an interactive web app.'\n    )\n", (4465, 4561), True, 'import streamlit as st\n'), ((4553, 4683), 'streamlit.markdown', 'st.markdown', (['"""2. Learn how to integrate and use OpenAI\'s API in their streamlit application to create a simple chatbot."""'], {}), '(\n    "2. Learn how to integrate and use OpenAI\'s API in their streamlit application to create a simple chatbot."\n    )\n', (4564, 4683), True, 'import streamlit as st\n'), ((4675, 4791), 'streamlit.markdown', 'st.markdown', (['"""3. Learn how to apply basic prompt engineering to enhance the interaction with the chatbot."""'], {}), "(\n    '3. Learn how to apply basic prompt engineering to enhance the interaction with the chatbot.'\n    )\n", (4686, 4791), True, 'import streamlit as st\n'), ((4808, 4831), 'streamlit.subheader', 'st.subheader', (['"""Outline"""'], {}), "('Outline')\n", (4820, 4831), True, 'import streamlit as st\n'), ((4833, 4887), 'streamlit.markdown', 'st.markdown', (['"""Part 0: Workshop introduction and rules"""'], {}), "('Part 0: Workshop introduction and rules')\n", (4844, 4887), True, 'import streamlit as st\n'), ((4889, 4948), 'streamlit.markdown', 'st.markdown', (['"""Part 1: Introduction to Python and Streamlit"""'], {}), "('Part 1: Introduction to Python and Streamlit')\n", (4900, 4948), True, 'import streamlit as st\n'), ((4950, 5002), 'streamlit.markdown', 'st.markdown', (['"""Part 2: Creating a rule-based chatbot"""'], {}), "('Part 2: Creating a rule-based chatbot')\n", (4961, 5002), True, 'import streamlit as st\n'), ((5004, 5064), 'streamlit.markdown', 'st.markdown', (['"""Part 3: Creating a chatbot using OpenAI\'s API"""'], {}), '("Part 3: Creating a chatbot using OpenAI\'s API")\n', (5015, 5064), True, 'import streamlit as st\n'), ((5066, 5135), 'streamlit.markdown', 'st.markdown', (['"""Part 4: Modifying your chatbot with prompt engineering"""'], {}), "('Part 4: Modifying your chatbot with prompt engineering')\n", (5077, 5135), True, 'import streamlit as st\n'), ((5163, 5262), 'streamlit.write', 'st.write', (['"""Do introduce yourself to your teammates:\n"""', '"""1) name\n"""', '"""2) division\n"""', '"""3) role"""'], {}), "('Do introduce yourself to your teammates:\\n', '1) name\\n',\n    '2) division\\n', '3) role')\n", (5171, 5262), True, 'import streamlit as st\n'), ((5260, 5333), 'streamlit.write', 'st.write', (['"""Please also share your favourite Star Wars character and why!"""'], {}), "('Please also share your favourite Star Wars character and why!')\n", (5268, 5333), True, 'import streamlit as st\n'), ((5343, 5380), 'PIL.Image.open', 'Image.open', (['"""team_introductions.jpeg"""'], {}), "('team_introductions.jpeg')\n", (5353, 5380), False, 'from PIL import Image\n'), ((5382, 5421), 'streamlit.image', 'st.image', (['image'], {'caption': '"""Hello there!"""'}), "(image, caption='Hello there!')\n", (5390, 5421), True, 'import streamlit as st\n'), ((5446, 5476), 'streamlit.subheader', 'st.subheader', (['"""Workshop Rules"""'], {}), "('Workshop Rules')\n", (5458, 5476), True, 'import streamlit as st\n'), ((5478, 5519), 'streamlit.write', 'st.write', (['"""1. Ask if you have questions."""'], {}), "('1. Ask if you have questions.')\n", (5486, 5519), True, 'import streamlit as st\n'), ((5521, 5583), 'streamlit.write', 'st.write', (['"""2. Be open to different ways to solve the problem."""'], {}), "('2. Be open to different ways to solve the problem.')\n", (5529, 5583), True, 'import streamlit as st\n'), ((5585, 5625), 'streamlit.write', 'st.write', (['"""3. Try. Fail. Learn. Repeat."""'], {}), "('3. Try. Fail. Learn. Repeat.')\n", (5593, 5625), True, 'import streamlit as st\n'), ((5627, 5676), 'streamlit.write', 'st.write', (['"""4. Seek help from other team members."""'], {}), "('4. Seek help from other team members.')\n", (5635, 5676), True, 'import streamlit as st\n'), ((5678, 5738), 'streamlit.write', 'st.write', (['"""5. Collaborate, if possible, for the challenges."""'], {}), "('5. Collaborate, if possible, for the challenges.')\n", (5686, 5738), True, 'import streamlit as st\n'), ((5740, 5815), 'streamlit.write', 'st.write', (['"""6. Approach facilitators if your team cannot solve the problem."""'], {}), "('6. Approach facilitators if your team cannot solve the problem.')\n", (5748, 5815), True, 'import streamlit as st\n'), ((5817, 5868), 'streamlit.write', 'st.write', (['"""7. Toilet break is own-time-own-target."""'], {}), "('7. Toilet break is own-time-own-target.')\n", (5825, 5868), True, 'import streamlit as st\n'), ((5870, 5894), 'streamlit.write', 'st.write', (['"""8. Have fun!"""'], {}), "('8. Have fun!')\n", (5878, 5894), True, 'import streamlit as st\n'), ((5914, 5962), 'streamlit.subheader', 'st.subheader', (['"""Navigating the VS Code interface"""'], {}), "('Navigating the VS Code interface')\n", (5926, 5962), True, 'import streamlit as st\n'), ((5972, 6006), 'PIL.Image.open', 'Image.open', (['"""VSCode_interface.png"""'], {}), "('VSCode_interface.png')\n", (5982, 6006), False, 'from PIL import Image\n'), ((6008, 6052), 'streamlit.image', 'st.image', (['image'], {'caption': '"""VS Code UI layout"""'}), "(image, caption='VS Code UI layout')\n", (6016, 6052), True, 'import streamlit as st\n'), ((6054, 6173), 'streamlit.markdown', 'st.markdown', (['"""**A: Activity Bar: this is where you can see the different activities you can do in VS Code.**"""'], {}), "(\n    '**A: Activity Bar: this is where you can see the different activities you can do in VS Code.**'\n    )\n", (6065, 6173), True, 'import streamlit as st\n'), ((6165, 6270), 'streamlit.markdown', 'st.markdown', (['"""\tExplorer: this is where you can see all the files and folders in your project."""'], {}), "(\n    '\\tExplorer: this is where you can see all the files and folders in your project.'\n    )\n", (6176, 6270), True, 'import streamlit as st\n'), ((6261, 6372), 'streamlit.markdown', 'st.markdown', (['"""\tSource Control: this is where you can see the changes you have made to your project."""'], {}), "(\n    '\\tSource Control: this is where you can see the changes you have made to your project.'\n    )\n", (6272, 6372), True, 'import streamlit as st\n'), ((6363, 6449), 'streamlit.markdown', 'st.markdown', (['"""\tExtensions: this is where you can install extensions to VS Code."""'], {}), "(\n    '\\tExtensions: this is where you can install extensions to VS Code.')\n", (6374, 6449), True, 'import streamlit as st\n'), ((6445, 6515), 'streamlit.markdown', 'st.markdown', (['"""\tRun and Debug: this is where you can debug your code."""'], {}), "('\\tRun and Debug: this is where you can debug your code.')\n", (6456, 6515), True, 'import streamlit as st\n'), ((6516, 6620), 'streamlit.markdown', 'st.markdown', (['"""**B: Side Bar: this is where you can see the different views of your project.**"""'], {}), "(\n    '**B: Side Bar: this is where you can see the different views of your project.**'\n    )\n", (6527, 6620), True, 'import streamlit as st\n'), ((6612, 6720), 'streamlit.markdown', 'st.markdown', (['"""**C: Editor: this is where you can see the code you have written in your project.**"""'], {}), "(\n    '**C: Editor: this is where you can see the code you have written in your project.**'\n    )\n", (6623, 6720), True, 'import streamlit as st\n'), ((6712, 6830), 'streamlit.markdown', 'st.markdown', (['"""**D: Panel: this is where you can see the different panels you have opened in your project.**"""'], {}), "(\n    '**D: Panel: this is where you can see the different panels you have opened in your project.**'\n    )\n", (6723, 6830), True, 'import streamlit as st\n'), ((6822, 6900), 'streamlit.markdown', 'st.markdown', (['"""\tTerminal: this is where you can run commands in your project."""'], {}), "('\\tTerminal: this is where you can run commands in your project.')\n", (6833, 6900), True, 'import streamlit as st\n'), ((6901, 6976), 'streamlit.markdown', 'st.markdown', (['"""\tOutput: this is where you can see the output of your code."""'], {}), "('\\tOutput: this is where you can see the output of your code.')\n", (6912, 6976), True, 'import streamlit as st\n'), ((6977, 7054), 'streamlit.markdown', 'st.markdown', (['"""\tProblems: this is where you can see the errors in your code."""'], {}), "('\\tProblems: this is where you can see the errors in your code.')\n", (6988, 7054), True, 'import streamlit as st\n'), ((7055, 7147), 'streamlit.markdown', 'st.markdown', (['"""**E. Status Bar: this is where you can see the status of your project.**"""'], {}), "(\n    '**E. Status Bar: this is where you can see the status of your project.**')\n", (7066, 7147), True, 'import streamlit as st\n'), ((7175, 7405), 'streamlit.markdown', 'st.markdown', (['"""Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*"""'], {}), '(\n    """Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*"""\n    )\n', (7186, 7405), True, 'import streamlit as st\n'), ((7407, 7448), 'PIL.Image.open', 'Image.open', (['"""command_palette_command.png"""'], {}), "('command_palette_command.png')\n", (7417, 7448), False, 'from PIL import Image\n'), ((7450, 7512), 'streamlit.image', 'st.image', (['image'], {'caption': '"""Command Palette auto-indent command"""'}), "(image, caption='Command Palette auto-indent command')\n", (7458, 7512), True, 'import streamlit as st\n'), ((7536, 7641), 'streamlit.write', 'st.write', (['"""This is what we will working towards and building by the end of the workshop today."""'], {}), "(\n    'This is what we will working towards and building by the end of the workshop today.'\n    )\n", (7544, 7641), True, 'import streamlit as st\n'), ((7633, 7674), 'streamlit.write', 'st.write', (['"""Do try out the chatbot below!"""'], {}), "('Do try out the chatbot below!')\n", (7641, 7674), True, 'import streamlit as st\n'), ((7676, 7732), 'streamlit.subheader', 'st.subheader', (['"""**:green[Feel the force! Yoda Chatbot]**"""'], {}), "('**:green[Feel the force! Yoda Chatbot]**')\n", (7688, 7732), True, 'import streamlit as st\n'), ((7742, 7764), 'PIL.Image.open', 'Image.open', (['"""yoda.jpg"""'], {}), "('yoda.jpg')\n", (7752, 7764), False, 'from PIL import Image\n'), ((7766, 7820), 'streamlit.image', 'st.image', (['image'], {'caption': '"""Master Yoda at your service"""'}), "(image, caption='Master Yoda at your service')\n", (7774, 7820), True, 'import streamlit as st\n'), ((7822, 7834), 'streamlit.divider', 'st.divider', ([], {}), '()\n', (7832, 7834), True, 'import streamlit as st\n'), ((9208, 9255), 'streamlit.subheader', 'st.subheader', (['"""Useful resources and references"""'], {}), "('Useful resources and references')\n", (9220, 9255), True, 'import streamlit as st\n'), ((9257, 9343), 'streamlit.markdown', 'st.markdown', (['"""1. [Streamlit documentation](https://docs.streamlit.io/en/stable/)"""'], {}), "(\n    '1. [Streamlit documentation](https://docs.streamlit.io/en/stable/)')\n", (9268, 9343), True, 'import streamlit as st\n'), ((9340, 9432), 'streamlit.markdown', 'st.markdown', (['"""2. [OpenAI API documentation](https://beta.openai.com/docs/introduction)"""'], {}), "(\n    '2. [OpenAI API documentation](https://beta.openai.com/docs/introduction)')\n", (9351, 9432), True, 'import streamlit as st\n'), ((9429, 9506), 'streamlit.markdown', 'st.markdown', (['"""3. [VS Code documentation](https://code.visualstudio.com/docs)"""'], {}), "('3. [VS Code documentation](https://code.visualstudio.com/docs)')\n", (9440, 9506), True, 'import streamlit as st\n'), ((9508, 9576), 'streamlit.markdown', 'st.markdown', (['"""4. [Python documentation](https://docs.python.org/3/)"""'], {}), "('4. [Python documentation](https://docs.python.org/3/)')\n", (9519, 9576), True, 'import streamlit as st\n'), ((9578, 9650), 'streamlit.markdown', 'st.markdown', (['"""5. [Python cheatsheet](https://www.pythoncheatsheet.org/)"""'], {}), "('5. [Python cheatsheet](https://www.pythoncheatsheet.org/)')\n", (9589, 9650), True, 'import streamlit as st\n'), ((9652, 9743), 'streamlit.markdown', 'st.markdown', (['"""6. [Python for beginners](https://www.python.org/about/gettingstarted/)"""'], {}), "(\n    '6. [Python for beginners](https://www.python.org/about/gettingstarted/)')\n", (9663, 9743), True, 'import streamlit as st\n'), ((9740, 9851), 'streamlit.markdown', 'st.markdown', (['"""7. [ChatGPT](https://chat.openai.com/) - you can ask ChatGPT to generate code for you!"""'], {}), "(\n    '7. [ChatGPT](https://chat.openai.com/) - you can ask ChatGPT to generate code for you!'\n    )\n", (9751, 9851), True, 'import streamlit as st\n'), ((9843, 10017), 'streamlit.markdown', 'st.markdown', (['"""**Notes for this workshop course:**  \n- you may do a single click to copy all the code  \n- challenge code is hidden, click reveal to see the code"""'], {}), '(\n    """**Notes for this workshop course:**  \n- you may do a single click to copy all the code  \n- challenge code is hidden, click reveal to see the code"""\n    )\n', (9854, 10017), True, 'import streamlit as st\n'), ((10007, 10237), 'streamlit.markdown', 'st.markdown', (['"""Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*"""'], {}), '(\n    """Python is very particular about indentation.\nUse the command palette to automatically indent your code.\n\nWindows: Ctrl-Shift-P  \nMac: Command-Shift-P\n\nSelect the option to *Convert Indentation to Tabs*"""\n    )\n', (10018, 10237), True, 'import streamlit as st\n'), ((10239, 10280), 'PIL.Image.open', 'Image.open', (['"""command_palette_command.png"""'], {}), "('command_palette_command.png')\n", (10249, 10280), False, 'from PIL import Image\n'), ((10282, 10344), 'streamlit.image', 'st.image', (['image'], {'caption': '"""Command Palette auto-indent command"""'}), "(image, caption='Command Palette auto-indent command')\n", (10290, 10344), True, 'import streamlit as st\n'), ((10367, 10392), 'streamlit.subheader', 'st.subheader', (['"""Streamlit"""'], {}), "('Streamlit')\n", (10379, 10392), True, 'import streamlit as st\n'), ((10394, 10790), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t * an open-source Python library\n\t\t * used extensively for machine learning and data science\n\t\t * helps to create interactive web apps in just a few lines of code\n\t\t * highly flexible and supports complex interactive apps with highly customisable UI\n\t\t * Some real world examples:\n\t\t \t* CherGPT in String\n\t\t \t* Metacog for CotF MOE\n\t\t \t* AILC prototype for MOE\n\t\t """'], {}), '(\n    """\n\t\t * an open-source Python library\n\t\t * used extensively for machine learning and data science\n\t\t * helps to create interactive web apps in just a few lines of code\n\t\t * highly flexible and supports complex interactive apps with highly customisable UI\n\t\t * Some real world examples:\n\t\t \t* CherGPT in String\n\t\t \t* Metacog for CotF MOE\n\t\t \t* AILC prototype for MOE\n\t\t """\n    )\n', (10405, 10790), True, 'import streamlit as st\n'), ((10820, 10843), 'streamlit.write', 'st.write', (['"""Hello World"""'], {}), "('Hello World')\n", (10828, 10843), True, 'import streamlit as st\n'), ((10910, 10942), 'streamlit.text_input', 'st.text_input', (['"""Enter your name"""'], {}), "('Enter your name')\n", (10923, 10942), True, 'import streamlit as st\n'), ((11001, 11038), 'streamlit.subheader', 'st.subheader', (['"""Exercise 1: Functions"""'], {}), "('Exercise 1: Functions')\n", (11013, 11038), True, 'import streamlit as st\n'), ((11040, 11160), 'streamlit.markdown', 'st.markdown', (['"""In the ***main.py*** file, the code below is already in ***ex1()*** in the ***part1.py*** file."""'], {}), "(\n    'In the ***main.py*** file, the code below is already in ***ex1()*** in the ***part1.py*** file.'\n    )\n", (11051, 11160), True, 'import streamlit as st\n'), ((11152, 11237), 'streamlit.write', 'st.write', (['"""The code for *helloworld* is inside what you call a Python function."""'], {}), "('The code for *helloworld* is inside what you call a Python function.'\n    )\n", (11160, 11237), True, 'import streamlit as st\n'), ((11234, 11388), 'streamlit.write', 'st.write', (['"""The ***def main()*** function and ***if _ _ name _ _ == \'_ _ main _ _\'*** statement are coding conventions for any Python programme."""'], {}), '(\n    "The ***def main()*** function and ***if _ _ name _ _ == \'_ _ main _ _\'*** statement are coding conventions for any Python programme."\n    )\n', (11242, 11388), True, 'import streamlit as st\n'), ((11380, 11514), 'streamlit.write', 'st.write', (['"""You need to include an import statement in ***main.py*** to import the ***ex1()*** function from the other file."""'], {}), "(\n    'You need to include an import statement in ***main.py*** to import the ***ex1()*** function from the other file.'\n    )\n", (11388, 11514), True, 'import streamlit as st\n'), ((11506, 11544), 'streamlit.code', 'st.code', (['"""\nfrom part1 import ex1\n"""'], {}), '("""\nfrom part1 import ex1\n""")\n', (11513, 11544), True, 'import streamlit as st\n'), ((11546, 11771), 'streamlit.write', 'st.write', (['"""You will need to do the same for all the other exercises and challenges for the rest of the workshop. The code exercises are already in the respective files: ***part1.py, part2.py, part3.py, part4.py***."""'], {}), "(\n    'You will need to do the same for all the other exercises and challenges for the rest of the workshop. The code exercises are already in the respective files: ***part1.py, part2.py, part3.py, part4.py***.'\n    )\n", (11554, 11771), True, 'import streamlit as st\n'), ((11763, 11793), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (11774, 11793), True, 'import streamlit as st\n'), ((11795, 12075), 'streamlit.code', 'st.code', (['"""\nimport streamlit as st\n\nfrom part1 import ex1\n\t\t \t \n#Exercise 1: Functions\ndef ex1():\n\tst.write("Hello World")\n\tname = st.text_input("Enter your name")\n\tif name:\n\t\tst.write("Hello " + name)\n\t \ndef main():\n\tex1()\n\t \nif __name__ == "__main__":\n\tmain()\t\t\n\t """'], {}), '(\n    """\nimport streamlit as st\n\nfrom part1 import ex1\n\t\t \t \n#Exercise 1: Functions\ndef ex1():\n\tst.write("Hello World")\n\tname = st.text_input("Enter your name")\n\tif name:\n\t\tst.write("Hello " + name)\n\t \ndef main():\n\tex1()\n\t \nif __name__ == "__main__":\n\tmain()\t\t\n\t """\n    )\n', (11802, 12075), True, 'import streamlit as st\n'), ((12067, 12137), 'streamlit.markdown', 'st.markdown', (['"""Run the code by typing the following into the terminal:"""'], {}), "('Run the code by typing the following into the terminal:')\n", (12078, 12137), True, 'import streamlit as st\n'), ((12139, 12171), 'streamlit.code', 'st.code', (['"""streamlit run main.py"""'], {}), "('streamlit run main.py')\n", (12146, 12171), True, 'import streamlit as st\n'), ((12173, 12250), 'streamlit.markdown', 'st.markdown', (['"""You should see the following behaviour in your browser window:"""'], {}), "('You should see the following behaviour in your browser window:')\n", (12184, 12250), True, 'import streamlit as st\n'), ((12252, 12288), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (12263, 12288), True, 'import streamlit as st\n'), ((12335, 12367), 'streamlit.text_input', 'st.text_input', (['"""Enter your name"""'], {}), "('Enter your name')\n", (12348, 12367), True, 'import streamlit as st\n'), ((12378, 12431), 'streamlit.selectbox', 'st.selectbox', (['"""State your gender"""', "['Male', 'Female']"], {}), "('State your gender', ['Male', 'Female'])\n", (12390, 12431), True, 'import streamlit as st\n'), ((12439, 12474), 'streamlit.text_input', 'st.text_input', (['"""State your age"""', '(18)'], {}), "('State your age', 18)\n", (12452, 12474), True, 'import streamlit as st\n'), ((12608, 12664), 'streamlit.subheader', 'st.subheader', (['"""Challenge 1: Input, Output and Variables"""'], {}), "('Challenge 1: Input, Output and Variables')\n", (12620, 12664), True, 'import streamlit as st\n'), ((12666, 12780), 'streamlit.write', 'st.write', (['"""Create a new function called ***ch1()*** in ***part1.py*** and call it in the main function."""'], {}), "(\n    'Create a new function called ***ch1()*** in ***part1.py*** and call it in the main function.'\n    )\n", (12674, 12780), True, 'import streamlit as st\n'), ((12772, 12876), 'streamlit.write', 'st.write', (['"""Create three variables *name*, *age* and *gender*, and obtain these from the user."""'], {}), "(\n    'Create three variables *name*, *age* and *gender*, and obtain these from the user.'\n    )\n", (12780, 12876), True, 'import streamlit as st\n'), ((12868, 12972), 'streamlit.write', 'st.write', (['"""Once the user filled up the input boxes, display back the information to the user."""'], {}), "(\n    'Once the user filled up the input boxes, display back the information to the user.'\n    )\n", (12876, 12972), True, 'import streamlit as st\n'), ((12964, 13099), 'streamlit.write', 'st.write', (['"""Code hint: the following piece of code checks if *name* has been filled, and if so, displays it back to the user."""'], {}), "(\n    'Code hint: the following piece of code checks if *name* has been filled, and if so, displays it back to the user.'\n    )\n", (12972, 13099), True, 'import streamlit as st\n'), ((13091, 13192), 'streamlit.code', 'st.code', (['"""\nname = st.text_input("Enter your name")\nif name:\n\tst.text(f"Hello {name}")\n"""'], {}), '(\n    """\nname = st.text_input("Enter your name")\nif name:\n\tst.text(f"Hello {name}")\n"""\n    )\n', (13098, 13192), True, 'import streamlit as st\n'), ((13184, 13214), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (13195, 13214), True, 'import streamlit as st\n'), ((13582, 13618), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (13593, 13618), True, 'import streamlit as st\n'), ((13671, 13724), 'streamlit.selectbox', 'st.selectbox', (['"""State your gender"""', "['Male', 'Female']"], {}), "('State your gender', ['Male', 'Female'])\n", (13683, 13724), True, 'import streamlit as st\n'), ((13788, 13834), 'streamlit.camera_input', 'st.camera_input', (['"""Smile! take a picture here."""'], {}), "('Smile! take a picture here.')\n", (13803, 13834), True, 'import streamlit as st\n'), ((14362, 14418), 'streamlit.subheader', 'st.subheader', (['"""Exercise 2: If-else logical conditionals"""'], {}), "('Exercise 2: If-else logical conditionals')\n", (14374, 14418), True, 'import streamlit as st\n'), ((14420, 14510), 'streamlit.markdown', 'st.markdown', (['"""If-else statements help control the flow and logic of our application."""'], {}), "(\n    'If-else statements help control the flow and logic of our application.')\n", (14431, 14510), True, 'import streamlit as st\n'), ((14507, 14537), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (14518, 14537), True, 'import streamlit as st\n'), ((14539, 15260), 'streamlit.code', 'st.code', (['"""\ndef ex2():\n    gender = st.selectbox("State your gender", ["Male", "Female"])\n    age = int(st.text_input("State your age", 18))\n    photo = st.camera_input("Smile! take a picture here.")\n\n    # conditional logic to run different statements\n    if age >= 21 and gender == "Male":\n        st.write("You are a male adult")\n    elif age < 21 and gender == "Male":\n        st.write("You are a young boy")\n    elif age >= 21 and gender == "Female":\n        st.write("You are a female adult")\n    elif age < 21 and gender == "Female":\n        st.write("You are a young girl")\n\n    if photo:\n        st.write("Here is your photo: ")\n        st.image(photo)\n    else:\n        st.write("No photo taken")\n"""'], {}), '(\n    """\ndef ex2():\n    gender = st.selectbox("State your gender", ["Male", "Female"])\n    age = int(st.text_input("State your age", 18))\n    photo = st.camera_input("Smile! take a picture here.")\n\n    # conditional logic to run different statements\n    if age >= 21 and gender == "Male":\n        st.write("You are a male adult")\n    elif age < 21 and gender == "Male":\n        st.write("You are a young boy")\n    elif age >= 21 and gender == "Female":\n        st.write("You are a female adult")\n    elif age < 21 and gender == "Female":\n        st.write("You are a young girl")\n\n    if photo:\n        st.write("Here is your photo: ")\n        st.image(photo)\n    else:\n        st.write("No photo taken")\n"""\n    )\n', (14546, 15260), True, 'import streamlit as st\n'), ((15252, 15288), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (15263, 15288), True, 'import streamlit as st\n'), ((15580, 15626), 'streamlit.write', 'st.write', (['"""Here is your *person* dictionary: """'], {}), "('Here is your *person* dictionary: ')\n", (15588, 15626), True, 'import streamlit as st\n'), ((15628, 15644), 'streamlit.write', 'st.write', (['person'], {}), '(person)\n', (15636, 15644), True, 'import streamlit as st\n'), ((15683, 15759), 'streamlit.write', 'st.write', (['"""You can also show individual items in the dictionary like this: """'], {}), "('You can also show individual items in the dictionary like this: ')\n", (15691, 15759), True, 'import streamlit as st\n'), ((15883, 15923), 'streamlit.text_input', 'st.text_input', (['"""Enter your name"""', '"""John"""'], {}), "('Enter your name', 'John')\n", (15896, 15923), True, 'import streamlit as st\n'), ((15931, 15966), 'streamlit.text_input', 'st.text_input', (['"""State your age"""', '(30)'], {}), "('State your age', 30)\n", (15944, 15966), True, 'import streamlit as st\n'), ((15977, 16030), 'streamlit.selectbox', 'st.selectbox', (['"""State your gender"""', "['Male', 'Female']"], {}), "('State your gender', ['Male', 'Female'])\n", (15989, 16030), True, 'import streamlit as st\n'), ((16039, 16083), 'streamlit.text_input', 'st.text_input', (['"""State your city"""', '"""New York"""'], {}), "('State your city', 'New York')\n", (16052, 16083), True, 'import streamlit as st\n'), ((16181, 16235), 'streamlit.write', 'st.write', (['"""Here is your updated *person* dictionary: """'], {}), "('Here is your updated *person* dictionary: ')\n", (16189, 16235), True, 'import streamlit as st\n'), ((16237, 16253), 'streamlit.write', 'st.write', (['person'], {}), '(person)\n', (16245, 16253), True, 'import streamlit as st\n'), ((16274, 16317), 'streamlit.subheader', 'st.subheader', (['"""Exercise 3: Data and Loops """'], {}), "('Exercise 3: Data and Loops ')\n", (16286, 16317), True, 'import streamlit as st\n'), ((16319, 16421), 'streamlit.write', 'st.write', (['"""We can store data in a list or dictionary and display the data using a for loop."""'], {}), "(\n    'We can store data in a list or dictionary and display the data using a for loop.'\n    )\n", (16327, 16421), True, 'import streamlit as st\n'), ((16413, 16527), 'streamlit.write', 'st.write', (['"""Append the following code to the ***main.py*** file. Refresh the browser to see the changes."""'], {}), "(\n    'Append the following code to the ***main.py*** file. Refresh the browser to see the changes.'\n    )\n", (16421, 16527), True, 'import streamlit as st\n'), ((16519, 16588), 'streamlit.write', 'st.write', (['"""You should see output similar to the *Code Output* below."""'], {}), "('You should see output similar to the *Code Output* below.')\n", (16527, 16588), True, 'import streamlit as st\n'), ((16590, 16620), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (16601, 16620), True, 'import streamlit as st\n'), ((16622, 17584), 'streamlit.code', 'st.code', (['"""\n#Data and Loops\ndef ex3():\n\t# Data list\n\tfruits = ["apple", "banana", "orange"]\n\n\t# For loop to show list\n\tfor fruit in fruits:\n\t\tst.write(fruit)\n\n\t# Dictionary\n\tperson = {"name": "John", "age": 30, "city": "New York"}\n\n\t# Print out the items in the dictionary\n\tst.write("Here is your *person* dictionary: ")\n\tst.write(person)\n\n\t# for loop to show dictionary list\n\tst.write("You can also show individual items in the dictionary like this: ")\n\tfor key, value in person.items():\n\t\tst.write(key + ": " + str(value))\n\n\t# get user input to update the dictionary\n\tname = st.text_input("Enter your name", "John")\n\tage = st.text_input("State your age", 30)\n\tgender = st.selectbox("State your gender", ["Male", "Female"])\n\tcity = st.text_input("State your city", "New York")\n\tperson["name"] = name\n\tperson["age"] = age\n\tperson["gender"] = gender\n\tperson["city"] = city\n\t\n\tst.write("Here is your updated *person* dictionary: ")\n\tst.write(person)\n"""'], {}), '(\n    """\n#Data and Loops\ndef ex3():\n\t# Data list\n\tfruits = ["apple", "banana", "orange"]\n\n\t# For loop to show list\n\tfor fruit in fruits:\n\t\tst.write(fruit)\n\n\t# Dictionary\n\tperson = {"name": "John", "age": 30, "city": "New York"}\n\n\t# Print out the items in the dictionary\n\tst.write("Here is your *person* dictionary: ")\n\tst.write(person)\n\n\t# for loop to show dictionary list\n\tst.write("You can also show individual items in the dictionary like this: ")\n\tfor key, value in person.items():\n\t\tst.write(key + ": " + str(value))\n\n\t# get user input to update the dictionary\n\tname = st.text_input("Enter your name", "John")\n\tage = st.text_input("State your age", 30)\n\tgender = st.selectbox("State your gender", ["Male", "Female"])\n\tcity = st.text_input("State your city", "New York")\n\tperson["name"] = name\n\tperson["age"] = age\n\tperson["gender"] = gender\n\tperson["city"] = city\n\t\n\tst.write("Here is your updated *person* dictionary: ")\n\tst.write(person)\n"""\n    )\n', (16629, 17584), True, 'import streamlit as st\n'), ((17576, 17612), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (17587, 17612), True, 'import streamlit as st\n'), ((18096, 18137), 'streamlit.write', 'st.write', (['"""name: """', 'st.session_state.name'], {}), "('name: ', st.session_state.name)\n", (18104, 18137), True, 'import streamlit as st\n'), ((18139, 18178), 'streamlit.write', 'st.write', (['"""age: """', 'st.session_state.age'], {}), "('age: ', st.session_state.age)\n", (18147, 18178), True, 'import streamlit as st\n'), ((18180, 18225), 'streamlit.write', 'st.write', (['"""gender: """', 'st.session_state.gender'], {}), "('gender: ', st.session_state.gender)\n", (18188, 18225), True, 'import streamlit as st\n'), ((18247, 18288), 'streamlit.subheader', 'st.subheader', (['"""Exercise 4a: Session Data"""'], {}), "('Exercise 4a: Session Data')\n", (18259, 18288), True, 'import streamlit as st\n'), ((18290, 18412), 'streamlit.write', 'st.write', (['"""We can create variables to store data in a user session. Session data persist within a user session."""'], {}), "(\n    'We can create variables to store data in a user session. Session data persist within a user session.'\n    )\n", (18298, 18412), True, 'import streamlit as st\n'), ((18405, 18435), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (18416, 18435), True, 'import streamlit as st\n'), ((18437, 19071), 'streamlit.code', 'st.code', (['"""\n# Exercise 4: Session State\ndef ex4a():\n\tst.subheader("Session Data:")\n\tif "session_data" not in st.session_state:\n\t\tst.session_state.session_data = ["alpha", "omega"]\n\t\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = ""\n\t\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = ""\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = ""\n\t\n\t# For loop to show list\n\tfor data in st.session_state.session_data:\n\t\tst.write("session_data: ", data)\n\n\tst.write("name: ", st.session_state.name)\n\tst.write("age: ", st.session_state.age)\n\tst.write("gender: ", st.session_state.gender)\n"""'], {}), '(\n    """\n# Exercise 4: Session State\ndef ex4a():\n\tst.subheader("Session Data:")\n\tif "session_data" not in st.session_state:\n\t\tst.session_state.session_data = ["alpha", "omega"]\n\t\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = ""\n\t\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = ""\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = ""\n\t\n\t# For loop to show list\n\tfor data in st.session_state.session_data:\n\t\tst.write("session_data: ", data)\n\n\tst.write("name: ", st.session_state.name)\n\tst.write("age: ", st.session_state.age)\n\tst.write("gender: ", st.session_state.gender)\n"""\n    )\n', (18444, 19071), True, 'import streamlit as st\n'), ((19067, 19103), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (19078, 19103), True, 'import streamlit as st\n'), ((19183, 19215), 'streamlit.text_input', 'st.text_input', (['"""Enter your name"""'], {}), "('Enter your name')\n", (19196, 19215), True, 'import streamlit as st\n'), ((19228, 19259), 'streamlit.text_input', 'st.text_input', (['"""State your age"""'], {}), "('State your age')\n", (19241, 19259), True, 'import streamlit as st\n'), ((19275, 19332), 'streamlit.selectbox', 'st.selectbox', (['"""State your gender"""', "['', 'Male', 'Female']"], {}), "('State your gender', ['', 'Male', 'Female'])\n", (19287, 19332), True, 'import streamlit as st\n'), ((19650, 19707), 'streamlit.subheader', 'st.subheader', (['"""Exercise 4b: Session Data with User Input"""'], {}), "('Exercise 4b: Session Data with User Input')\n", (19662, 19707), True, 'import streamlit as st\n'), ((19709, 19787), 'streamlit.write', 'st.write', (['"""Lets now get input from the user and store it in the session data."""'], {}), "('Lets now get input from the user and store it in the session data.')\n", (19717, 19787), True, 'import streamlit as st\n'), ((19789, 19878), 'streamlit.write', 'st.write', (['"""Now run *ex4a()* again to check the session data. Note that it persists."""'], {}), "(\n    'Now run *ex4a()* again to check the session data. Note that it persists.')\n", (19797, 19878), True, 'import streamlit as st\n'), ((19876, 19906), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (19887, 19906), True, 'import streamlit as st\n'), ((19908, 20427), 'streamlit.code', 'st.code', (['"""\ndef ex4b():\n\tst.subheader("Session Data:")\n\tuserName = st.text_input("Enter your name")\n\tuserAge = st.text_input("State your age")\n\tuserGender = st.selectbox("State your gender", ["", "Male", "Female"])\n\n\tif userName:\n\t\tst.session_state.name = userName\n\t\tst.write("name: ", st.session_state.name)\n\tif userAge:\n\t\tst.session_state.age = int(userAge)\n\t\tst.write("age: ", st.session_state.age)\n\tif userGender:\n\t\tst.session_state.gender = userGender\n\t\tst.write("gender: ", st.session_state.gender)\n"""'], {}), '(\n    """\ndef ex4b():\n\tst.subheader("Session Data:")\n\tuserName = st.text_input("Enter your name")\n\tuserAge = st.text_input("State your age")\n\tuserGender = st.selectbox("State your gender", ["", "Male", "Female"])\n\n\tif userName:\n\t\tst.session_state.name = userName\n\t\tst.write("name: ", st.session_state.name)\n\tif userAge:\n\t\tst.session_state.age = int(userAge)\n\t\tst.write("age: ", st.session_state.age)\n\tif userGender:\n\t\tst.session_state.gender = userGender\n\t\tst.write("gender: ", st.session_state.gender)\n"""\n    )\n', (19915, 20427), True, 'import streamlit as st\n'), ((20419, 20455), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (20430, 20455), True, 'import streamlit as st\n'), ((20931, 20986), 'streamlit.write', 'st.write', (['"""session_state.name: """', 'st.session_state.name'], {}), "('session_state.name: ', st.session_state.name)\n", (20939, 20986), True, 'import streamlit as st\n'), ((20988, 21041), 'streamlit.write', 'st.write', (['"""session_state.age: """', 'st.session_state.age'], {}), "('session_state.age: ', st.session_state.age)\n", (20996, 21041), True, 'import streamlit as st\n'), ((21043, 21102), 'streamlit.write', 'st.write', (['"""session_state.gender: """', 'st.session_state.gender'], {}), "('session_state.gender: ', st.session_state.gender)\n", (21051, 21102), True, 'import streamlit as st\n'), ((21104, 21181), 'streamlit.write', 'st.write', (['"""session_state.prompt_template: """', 'st.session_state.prompt_template'], {}), "('session_state.prompt_template: ', st.session_state.prompt_template)\n", (21112, 21181), True, 'import streamlit as st\n'), ((21202, 21243), 'streamlit.subheader', 'st.subheader', (['"""Challenge 4: Session Data"""'], {}), "('Challenge 4: Session Data')\n", (21214, 21243), True, 'import streamlit as st\n'), ((21245, 22105), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t Add a new function called ***ch4()*** to the ***part1.py*** file and call it in the main function.\n\n\t\t In *ch4()*, modify the code in Exercise 4b to include the following:\n\t\t * Create session data for ***name***, ***age*** and ***gender***\n\t\t * Create session data for ***prompt_template*** with the following value:\n\t\t\t "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t\t * Include this code in ***main()*** as well, because we need the session data for later exercises. Omit the ***st.write*** functions, since we do not want to see this output every time we run ***main()***. \n\n\t\t Hint:\n\t\t * In ***ch4()***, to check that the session data is created, you can print out the session data using ***st.write()***:\n\t\t """'], {}), '(\n    """\n\t\t Add a new function called ***ch4()*** to the ***part1.py*** file and call it in the main function.\n\n\t\t In *ch4()*, modify the code in Exercise 4b to include the following:\n\t\t * Create session data for ***name***, ***age*** and ***gender***\n\t\t * Create session data for ***prompt_template*** with the following value:\n\t\t\t "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t\t * Include this code in ***main()*** as well, because we need the session data for later exercises. Omit the ***st.write*** functions, since we do not want to see this output every time we run ***main()***. \n\n\t\t Hint:\n\t\t * In ***ch4()***, to check that the session data is created, you can print out the session data using ***st.write()***:\n\t\t """\n    )\n', (21256, 22105), True, 'import streamlit as st\n'), ((22099, 22129), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (22110, 22129), True, 'import streamlit as st\n'), ((23448, 23484), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (23459, 23484), True, 'import streamlit as st\n'), ((23524, 23552), 'streamlit.title', 'st.title', (['"""My first chatbot"""'], {}), "('My first chatbot')\n", (23532, 23552), True, 'import streamlit as st\n'), ((23640, 23670), 'streamlit.chat_input', 'st.chat_input', (['"""Say something"""'], {}), "('Say something')\n", (23653, 23670), True, 'import streamlit as st\n'), ((23997, 24046), 'streamlit.subheader', 'st.subheader', (['"""Exercise 5: Elements of a chatbot"""'], {}), "('Exercise 5: Elements of a chatbot')\n", (24009, 24046), True, 'import streamlit as st\n'), ((24048, 24122), 'streamlit.write', 'st.write', (['"""We will start creating a user interface for our first chatbot."""'], {}), "('We will start creating a user interface for our first chatbot.')\n", (24056, 24122), True, 'import streamlit as st\n'), ((24124, 24199), 'streamlit.write', 'st.write', (['"""Call the following code from ***part1.py*** in your **main()**."""'], {}), "('Call the following code from ***part1.py*** in your **main()**.')\n", (24132, 24199), True, 'import streamlit as st\n'), ((24201, 24273), 'streamlit.write', 'st.write', (['"""You should see the output below when you run your programme."""'], {}), "('You should see the output below when you run your programme.')\n", (24209, 24273), True, 'import streamlit as st\n'), ((24275, 24305), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (24286, 24305), True, 'import streamlit as st\n'), ((24307, 24823), 'streamlit.code', 'st.code', (['"""\n#Exercise 5 : Chatbot UI\ndef ex5():\n\tst.title("My first chatbot")\n\n\tif "store_msg" not in st.session_state:\n\t\tst.session_state.store_msg = []\n\n\tprompt = st.chat_input("Say something")\n\tif prompt:\n\t\tst.write(f"User has sent the following prompt: {prompt}")\n\t\tst.session_state.store_msg.append(prompt)\n\t\tfor message in st.session_state.store_msg:\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.write(message)\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tst.write("Hello human, what can I do for you?")\n"""'], {}), '(\n    """\n#Exercise 5 : Chatbot UI\ndef ex5():\n\tst.title("My first chatbot")\n\n\tif "store_msg" not in st.session_state:\n\t\tst.session_state.store_msg = []\n\n\tprompt = st.chat_input("Say something")\n\tif prompt:\n\t\tst.write(f"User has sent the following prompt: {prompt}")\n\t\tst.session_state.store_msg.append(prompt)\n\t\tfor message in st.session_state.store_msg:\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.write(message)\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tst.write("Hello human, what can I do for you?")\n"""\n    )\n', (24314, 24823), True, 'import streamlit as st\n'), ((24815, 24851), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (24826, 24851), True, 'import streamlit as st\n'), ((24891, 24918), 'streamlit.markdown', 'st.markdown', (['"""**Echo Bot**"""'], {}), "('**Echo Bot**')\n", (24902, 24918), True, 'import streamlit as st\n'), ((25757, 25815), 'streamlit.subheader', 'st.subheader', (['"""Exercise 6: Building a simple echo chatbot"""'], {}), "('Exercise 6: Building a simple echo chatbot')\n", (25769, 25815), True, 'import streamlit as st\n'), ((25817, 25869), 'streamlit.write', 'st.write', (['"""We will now build a simple echo chatbot."""'], {}), "('We will now build a simple echo chatbot.')\n", (25825, 25869), True, 'import streamlit as st\n'), ((25871, 25946), 'streamlit.write', 'st.write', (['"""Call the following code from **part1.py** in your ***main()***."""'], {}), "('Call the following code from **part1.py** in your ***main()***.')\n", (25879, 25946), True, 'import streamlit as st\n'), ((25948, 26020), 'streamlit.write', 'st.write', (['"""You should see the output below when you run your programme."""'], {}), "('You should see the output below when you run your programme.')\n", (25956, 26020), True, 'import streamlit as st\n'), ((26022, 26052), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (26033, 26052), True, 'import streamlit as st\n'), ((26054, 26968), 'streamlit.code', 'st.code', (['"""\n#Exercise 6 : Rule-based Echo Chatbot \ndef ex6():\n\tst.title("Echo Bot")\n\n\t# Initialize chat history\n\tif "messages" not in st.session_state:\n\t\tst.session_state.messages = []\n\n\t# Display chat messages from history on app rerun\n\tfor message in st.session_state.messages:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("What is up?"):\n\t\t# Display user message in chat message container\n\t\tst.chat_message("user").markdown(prompt)\n\t\t# Add user message to chat history\n\t\tst.session_state.messages.append({"role": "user", "content": prompt})\n\n\t\tresponse = f"Echo: {prompt}"\n\t\t# Display assistant response in chat message container\n\t\twith st.chat_message("assistant"):\n\t\t\tst.markdown(response)\n\t\t# Add assistant response to chat history\n\t\tst.session_state.messages.append({"role": "assistant", "content": response})\n"""'], {}), '(\n    """\n#Exercise 6 : Rule-based Echo Chatbot \ndef ex6():\n\tst.title("Echo Bot")\n\n\t# Initialize chat history\n\tif "messages" not in st.session_state:\n\t\tst.session_state.messages = []\n\n\t# Display chat messages from history on app rerun\n\tfor message in st.session_state.messages:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("What is up?"):\n\t\t# Display user message in chat message container\n\t\tst.chat_message("user").markdown(prompt)\n\t\t# Add user message to chat history\n\t\tst.session_state.messages.append({"role": "user", "content": prompt})\n\n\t\tresponse = f"Echo: {prompt}"\n\t\t# Display assistant response in chat message container\n\t\twith st.chat_message("assistant"):\n\t\t\tst.markdown(response)\n\t\t# Add assistant response to chat history\n\t\tst.session_state.messages.append({"role": "assistant", "content": response})\n"""\n    )\n', (26061, 26968), True, 'import streamlit as st\n'), ((26960, 26996), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (26971, 26996), True, 'import streamlit as st\n'), ((27036, 27069), 'streamlit.markdown', 'st.markdown', (['"""**Rule Based Bot**"""'], {}), "('**Rule Based Bot**')\n", (27047, 27069), True, 'import streamlit as st\n'), ((28014, 28062), 'streamlit.subheader', 'st.subheader', (['"""Challenge 6: Rule based chatbot """'], {}), "('Challenge 6: Rule based chatbot ')\n", (28026, 28062), True, 'import streamlit as st\n'), ((28064, 28709), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t Create a new function called ***ch6()*** in **part1.py** and modify the ***ex6()*** function to create the following rule based chatbot:\n\n\t\t * Human : “Hello”,  Assistant: “Hi there what can I do for you”\n\n\t\t * Human : “What is your name?”,  Assistant: “My name is EAI , an electronic artificial being”\n\t\n\t\t * Human : “How old are you?”,  Assistant: “Today is my birthday!”\n\n\t\t For other queries, it will reply “I am sorry, I am unable to help you with your query”\n\n\t\t Use *if / elif / else* statements to create the chatbot behaviour logic.\n \n\t\t You should see the output below when you run your programme.\n\n\t\t """'], {}), '(\n    """\n\t\t Create a new function called ***ch6()*** in **part1.py** and modify the ***ex6()*** function to create the following rule based chatbot:\n\n\t\t * Human : “Hello”,  Assistant: “Hi there what can I do for you”\n\n\t\t * Human : “What is your name?”,  Assistant: “My name is EAI , an electronic artificial being”\n\t\n\t\t * Human : “How old are you?”,  Assistant: “Today is my birthday!”\n\n\t\t For other queries, it will reply “I am sorry, I am unable to help you with your query”\n\n\t\t Use *if / elif / else* statements to create the chatbot behaviour logic.\n \n\t\t You should see the output below when you run your programme.\n\n\t\t """\n    )\n', (28075, 28709), True, 'import streamlit as st\n'), ((28708, 28738), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (28719, 28738), True, 'import streamlit as st\n'), ((29805, 29841), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (29816, 29841), True, 'import streamlit as st\n'), ((29888, 29930), 'streamlit.subheader', 'st.subheader', (['"""Exercise 7: Secrets- Shhh """'], {}), "('Exercise 7: Secrets- Shhh ')\n", (29900, 29930), True, 'import streamlit as st\n'), ((29932, 30000), 'streamlit.write', 'st.write', (['"""In this exercise, we will learn how to hide your API key"""'], {}), "('In this exercise, we will learn how to hide your API key')\n", (29940, 30000), True, 'import streamlit as st\n'), ((30002, 30297), 'streamlit.markdown', 'st.markdown', (['"""\n\tIn your working directory (chatbot), create a directory called **.streamlit**\n\n\tNote the *dot* in front of the directory\n\n\tIn this folder, create a file called **secrets.toml**\n\n\tGet an API key from your OpenAI account and type the following in **secrets.toml**:\n\t"""'], {}), '(\n    """\n\tIn your working directory (chatbot), create a directory called **.streamlit**\n\n\tNote the *dot* in front of the directory\n\n\tIn this folder, create a file called **secrets.toml**\n\n\tGet an API key from your OpenAI account and type the following in **secrets.toml**:\n\t"""\n    )\n', (30013, 30297), True, 'import streamlit as st\n'), ((30292, 30322), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (30303, 30322), True, 'import streamlit as st\n'), ((30324, 30365), 'streamlit.code', 'st.code', (['"""\n\topenapi_key = "xxxxxx"\n\t"""'], {}), '("""\n\topenapi_key = "xxxxxx"\n\t""")\n', (30331, 30365), True, 'import streamlit as st\n'), ((30367, 30483), 'streamlit.write', 'st.write', (['"""Include the following global variables in your ***main.py*** file under the import statements:"""'], {}), "(\n    'Include the following global variables in your ***main.py*** file under the import statements:'\n    )\n", (30375, 30483), True, 'import streamlit as st\n'), ((30475, 30601), 'streamlit.code', 'st.code', (['"""\nos.environ["OPENAI_API_KEY"] = st.secrets["openapi_key"]\nopenai.api_key = st.secrets["openapi_key"]\n"""'], {}), '(\n    """\nos.environ["OPENAI_API_KEY"] = st.secrets["openapi_key"]\nopenai.api_key = st.secrets["openapi_key"]\n"""\n    )\n', (30482, 30601), True, 'import streamlit as st\n'), ((30593, 30656), 'streamlit.write', 'st.write', (['"""Create a .gitignore file and add .streamlit into it"""'], {}), "('Create a .gitignore file and add .streamlit into it')\n", (30601, 30656), True, 'import streamlit as st\n'), ((30740, 30760), 'streamlit.title', 'st.title', (['"""Api Call"""'], {}), "('Api Call')\n", (30748, 30760), True, 'import streamlit as st\n'), ((30798, 31018), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': 'MODEL', 'messages': "[{'role': 'system', 'content': 'You are a helpful assistant.'}, {'role':\n    'user', 'content': 'Tell me about Singapore in the 1970s in 50 words.'}]", 'temperature': '(0)'}), "(model=MODEL, messages=[{'role': 'system',\n    'content': 'You are a helpful assistant.'}, {'role': 'user', 'content':\n    'Tell me about Singapore in the 1970s in 50 words.'}], temperature=0)\n", (30826, 31018), False, 'import openai\n'), ((31033, 31077), 'streamlit.markdown', 'st.markdown', (['"""**This is the raw response:**"""'], {}), "('**This is the raw response:**')\n", (31044, 31077), True, 'import streamlit as st\n'), ((31080, 31098), 'streamlit.write', 'st.write', (['response'], {}), '(response)\n', (31088, 31098), True, 'import streamlit as st\n'), ((31100, 31150), 'streamlit.markdown', 'st.markdown', (['"""**This is the extracted response:**"""'], {}), "('**This is the extracted response:**')\n", (31111, 31150), True, 'import streamlit as st\n'), ((31260, 31297), 'streamlit.markdown', 'st.markdown', (['"""**Total tokens used:**"""'], {}), "('**Total tokens used:**')\n", (31271, 31297), True, 'import streamlit as st\n'), ((31299, 31310), 'streamlit.write', 'st.write', (['s'], {}), '(s)\n', (31307, 31310), True, 'import streamlit as st\n'), ((31331, 31385), 'streamlit.subheader', 'st.subheader', (['"""Exercise 8: Calling the OpenAI LLM API"""'], {}), "('Exercise 8: Calling the OpenAI LLM API')\n", (31343, 31385), True, 'import streamlit as st\n'), ((31387, 31461), 'streamlit.write', 'st.write', (['"""In this exercise, we will learn how to call the OpenAI LLM API"""'], {}), "('In this exercise, we will learn how to call the OpenAI LLM API')\n", (31395, 31461), True, 'import streamlit as st\n'), ((31463, 31534), 'streamlit.write', 'st.write', (['"""Note that there is a new import statement **import openai**"""'], {}), "('Note that there is a new import statement **import openai**')\n", (31471, 31534), True, 'import streamlit as st\n'), ((31536, 31674), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t Call the following code in your **main()** and run it.\n\n\t\t You should see the output as shown below.\n\n\t\t """'], {}), '(\n    """\n\t\t Call the following code in your **main()** and run it.\n\n\t\t You should see the output as shown below.\n\n\t\t """\n    )\n', (31547, 31674), True, 'import streamlit as st\n'), ((31668, 31698), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (31679, 31698), True, 'import streamlit as st\n'), ((31700, 32363), 'streamlit.code', 'st.code', (['"""\nimport openai\n\t \n#Exercise 8 : Using the OpenAI API\ndef ex8():\n\tst.title("Api Call")\n\tMODEL = "gpt-3.5-turbo"\n\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant."},\n\t\t\t{"role": "user", "content": "Tell me about Singapore in the 1970s in 50 words."},\n\t\t],\n\t\ttemperature=0,\n\t)\n\n\tst.markdown("**This is the raw response:**") \n\tst.write(response)\n\tst.markdown("**This is the extracted response:**")\n\tst.write(response["choices"][0]["message"]["content"].strip())\n\ts = str(response["usage"]["total_tokens"])\n\tst.markdown("**Total tokens used:**")\n\tst.write(s)\n"""'], {}), '(\n    """\nimport openai\n\t \n#Exercise 8 : Using the OpenAI API\ndef ex8():\n\tst.title("Api Call")\n\tMODEL = "gpt-3.5-turbo"\n\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant."},\n\t\t\t{"role": "user", "content": "Tell me about Singapore in the 1970s in 50 words."},\n\t\t],\n\t\ttemperature=0,\n\t)\n\n\tst.markdown("**This is the raw response:**") \n\tst.write(response)\n\tst.markdown("**This is the extracted response:**")\n\tst.write(response["choices"][0]["message"]["content"].strip())\n\ts = str(response["usage"]["total_tokens"])\n\tst.markdown("**Total tokens used:**")\n\tst.write(s)\n"""\n    )\n', (31707, 32363), True, 'import streamlit as st\n'), ((32355, 32391), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (32366, 32391), True, 'import streamlit as st\n'), ((32485, 32660), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': 'MODEL', 'messages': "[{'role': 'system', 'content': 'You are a helpful assistant.'}, {'role':\n    'user', 'content': prompt}]", 'temperature': '(0)'}), "(model=MODEL, messages=[{'role': 'system',\n    'content': 'You are a helpful assistant.'}, {'role': 'user', 'content':\n    prompt}], temperature=0)\n", (32513, 32660), False, 'import openai\n'), ((32755, 32831), 'streamlit.subheader', 'st.subheader', (['"""Challenge 8: Incorporate your LLM API call into your chatbot"""'], {}), "('Challenge 8: Incorporate your LLM API call into your chatbot')\n", (32767, 32831), True, 'import streamlit as st\n'), ((32833, 32954), 'streamlit.write', 'st.write', (['"""In this challenge, we will incorporate the LLM API call into our previous rule-based *Echo* chatbot"""'], {}), "(\n    'In this challenge, we will incorporate the LLM API call into our previous rule-based *Echo* chatbot'\n    )\n", (32841, 32954), True, 'import streamlit as st\n'), ((32946, 33545), 'streamlit.markdown', 'st.markdown', (['"""\n**Step1**\n\nCreate a new function **ch8()** in ***part1.py*** and copy the code from **ex6()** into it. Recall that **ex6()** shows the chat history and gets a chat input from the user, and echoes the user input back to the user. \n\n**Step 2**\n\nNext, copy the code from **ex8** into a new function named **chat_completion()**. Recall that **ex8()** is about making an API call.\n\nNow, instead of echoing the user\'s input in **ex6()**, we will call the LLM API to generate a response. In particular, we are replacing this line of code with the response from the API call:\n\n"""'], {}), '(\n    """\n**Step1**\n\nCreate a new function **ch8()** in ***part1.py*** and copy the code from **ex6()** into it. Recall that **ex6()** shows the chat history and gets a chat input from the user, and echoes the user input back to the user. \n\n**Step 2**\n\nNext, copy the code from **ex8** into a new function named **chat_completion()**. Recall that **ex8()** is about making an API call.\n\nNow, instead of echoing the user\'s input in **ex6()**, we will call the LLM API to generate a response. In particular, we are replacing this line of code with the response from the API call:\n\n"""\n    )\n', (32957, 33545), True, 'import streamlit as st\n'), ((33542, 33588), 'streamlit.code', 'st.code', (['"""\nresponse = f"Echo: {prompt}\\"\n"""'], {}), '("""\nresponse = f"Echo: {prompt}\\"\n""")\n', (33549, 33588), True, 'import streamlit as st\n'), ((33589, 33994), 'streamlit.markdown', 'st.markdown', (['"""\n**Step 3**\n\nIn **chat_completion()**, what we will do is to replace the previous *Tell me the history ..."* prompt from **ex8()** with the current user\'s input.\n\nIn order to do so, in **ch8()**, use the following code to call **chat_completion()**.\n\nWhat we are doing now is to pass the prompt from the user to the API call instead of hard-coding the prompt as in **ex8()**.\n"""'], {}), '(\n    """\n**Step 3**\n\nIn **chat_completion()**, what we will do is to replace the previous *Tell me the history ..."* prompt from **ex8()** with the current user\'s input.\n\nIn order to do so, in **ch8()**, use the following code to call **chat_completion()**.\n\nWhat we are doing now is to pass the prompt from the user to the API call instead of hard-coding the prompt as in **ex8()**.\n"""\n    )\n', (33600, 33994), True, 'import streamlit as st\n'), ((33990, 34193), 'streamlit.code', 'st.code', (['"""\n\t if prompt := st.chat.input("What\'s up?"):\n\t \t#display user messgae in chat message container\n\t \treply = chat_completion(prompt) \n\t \tst.chat_message("user").markdown(prompt)\n\t\t"""'], {}), '(\n    """\n\t if prompt := st.chat.input("What\'s up?"):\n\t \t#display user messgae in chat message container\n\t \treply = chat_completion(prompt) \n\t \tst.chat_message("user").markdown(prompt)\n\t\t"""\n    )\n', (33997, 34193), True, 'import streamlit as st\n'), ((34185, 34243), 'streamlit.write', 'st.write', (['"""You should see the code output as shown below."""'], {}), "('You should see the code output as shown below.')\n", (34193, 34243), True, 'import streamlit as st\n'), ((34245, 34275), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (34256, 34275), True, 'import streamlit as st\n'), ((35559, 35595), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (35570, 35595), True, 'import streamlit as st\n'), ((35597, 35623), 'streamlit.title', 'st.title', (['"""My LLM Chatbot"""'], {}), "('My LLM Chatbot')\n", (35605, 35623), True, 'import streamlit as st\n'), ((36510, 36697), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': 'MODEL', 'messages': "[{'role': 'system', 'content': 'You are a helpful assistant'}, {'role':\n    'user', 'content': prompt}]", 'temperature': '(0)', 'stream': '(True)'}), "(model=MODEL, messages=[{'role': 'system',\n    'content': 'You are a helpful assistant'}, {'role': 'user', 'content':\n    prompt}], temperature=0, stream=True)\n", (36538, 36697), False, 'import openai\n'), ((37746, 37833), 'streamlit.subheader', 'st.subheader', (['"""Exercise 9: Building a ChatGPT-like clone with streaming responses"""'], {}), "(\n    'Exercise 9: Building a ChatGPT-like clone with streaming responses')\n", (37758, 37833), True, 'import streamlit as st\n'), ((37830, 37966), 'streamlit.write', 'st.write', (['"""Now, we will incorporate a streaming response from the LLM API into our chatbot to mimic the behaviour of ChatGPT."""'], {}), "(\n    'Now, we will incorporate a streaming response from the LLM API into our chatbot to mimic the behaviour of ChatGPT.'\n    )\n", (37838, 37966), True, 'import streamlit as st\n'), ((37958, 38029), 'streamlit.write', 'st.write', (['"""Copy and run the code below to see the streaming responses."""'], {}), "('Copy and run the code below to see the streaming responses.')\n", (37966, 38029), True, 'import streamlit as st\n'), ((38031, 38061), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (38042, 38061), True, 'import streamlit as st\n'), ((38063, 39535), 'streamlit.code', 'st.code', (['"""\n# Exercise 9 : Using the OpenAI API with streaming option\ndef chat_completion_stream(prompt):\n\topenai.api_key = st.secrets["openapi_key"]\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant"},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature=0,  # temperature\n\t\tstream=True,  # stream option\n\t)\n\treturn response\n\n# integration API call into streamlit chat components\ndef ex9_basebot():\n\t# Initialize chat history\n\tif "chat_msg" not in st.session_state:\n\t\tst.session_state.chat_msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.chat_msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.chat_msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.chat_msg.append(\n\t\t\t\t{"role": "assistant", "content": full_response}\n\t\t\t)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""'], {}), '(\n    """\n# Exercise 9 : Using the OpenAI API with streaming option\ndef chat_completion_stream(prompt):\n\topenai.api_key = st.secrets["openapi_key"]\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant"},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature=0,  # temperature\n\t\tstream=True,  # stream option\n\t)\n\treturn response\n\n# integration API call into streamlit chat components\ndef ex9_basebot():\n\t# Initialize chat history\n\tif "chat_msg" not in st.session_state:\n\t\tst.session_state.chat_msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.chat_msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.chat_msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.chat_msg.append(\n\t\t\t\t{"role": "assistant", "content": full_response}\n\t\t\t)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""\n    )\n', (38070, 39535), True, 'import streamlit as st\n'), ((39527, 39563), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (39538, 39563), True, 'import streamlit as st\n'), ((39712, 39937), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': 'MODEL', 'messages': "[{'role': 'system', 'content': st.session_state.prompt_template}, {'role':\n    'user', 'content': 'Tell me about Singapore in the 1970s in 50 words'}]", 'temperature': '(0)'}), "(model=MODEL, messages=[{'role': 'system',\n    'content': st.session_state.prompt_template}, {'role': 'user',\n    'content': 'Tell me about Singapore in the 1970s in 50 words'}],\n    temperature=0)\n", (39740, 39937), False, 'import openai\n'), ((39962, 39994), 'streamlit.markdown', 'st.markdown', (['"""**LLM Response:**"""'], {}), "('**LLM Response:**')\n", (39973, 39994), True, 'import streamlit as st\n'), ((40060, 40092), 'streamlit.markdown', 'st.markdown', (['"""**Total tokens:**"""'], {}), "('**Total tokens:**')\n", (40071, 40092), True, 'import streamlit as st\n'), ((40164, 40217), 'streamlit.subheader', 'st.subheader', (['"""Exercise 10: Basic Prompt Engineering"""'], {}), "('Exercise 10: Basic Prompt Engineering')\n", (40176, 40217), True, 'import streamlit as st\n'), ((40219, 40583), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t Now, we are going to create a chatbot with a personality by using a default prompt for our chatbot. \n\n\t\t This is the default prompt that will be used for every conversation.\n\n\t\t Let\'s make it a chatbot that speaks like Yoda from Star Wars.\n\n\t\t We will use the ***prompt_template*** that is already in our ***main()*** for this.\n\t\t """'], {}), '(\n    """\n\t\t Now, we are going to create a chatbot with a personality by using a default prompt for our chatbot. \n\n\t\t This is the default prompt that will be used for every conversation.\n\n\t\t Let\'s make it a chatbot that speaks like Yoda from Star Wars.\n\n\t\t We will use the ***prompt_template*** that is already in our ***main()*** for this.\n\t\t """\n    )\n', (40230, 40583), True, 'import streamlit as st\n'), ((40578, 40847), 'streamlit.code', 'st.code', (['"""\nif "prompt_template" not in st.session_state:\n\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t"""'], {}), '(\n    """\nif "prompt_template" not in st.session_state:\n\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t"""\n    )\n', (40585, 40847), True, 'import streamlit as st\n'), ((40839, 41063), 'streamlit.markdown', 'st.markdown', (['"""\n\t\t Run the code below. You should get the same chatbot behaviour as the code output below.\n\n\t\t Try varying the temperature setting (0.0 to 1.0) to see how it affects the chatbot\'s response.\n\n\t\t """'], {}), '(\n    """\n\t\t Run the code below. You should get the same chatbot behaviour as the code output below.\n\n\t\t Try varying the temperature setting (0.0 to 1.0) to see how it affects the chatbot\'s response.\n\n\t\t """\n    )\n', (40850, 41063), True, 'import streamlit as st\n'), ((41057, 41087), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (41068, 41087), True, 'import streamlit as st\n'), ((41089, 41700), 'streamlit.code', 'st.code', (['"""\n# Exercise 10: Basic prompt engineering\ndef ex10_basebot():\n\t#prompt_template in session state already set in main()\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": st.session_state.prompt_template},\n\t\t\t{\n\t\t\t\t"role": "user",\n\t\t\t\t"content": "Tell me about Singapore in the 1970s in 50 words",\n\t\t\t},\n\t\t],\n\t\ttemperature=0,\n\t)\n\tst.markdown("**LLM Response:**")\n\tst.write(response["choices"][0]["message"]["content"].strip())\n\tst.markdown("**Total tokens:**")\n\tst.write(str(response["usage"]["total_tokens"]))\n"""'], {}), '(\n    """\n# Exercise 10: Basic prompt engineering\ndef ex10_basebot():\n\t#prompt_template in session state already set in main()\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": st.session_state.prompt_template},\n\t\t\t{\n\t\t\t\t"role": "user",\n\t\t\t\t"content": "Tell me about Singapore in the 1970s in 50 words",\n\t\t\t},\n\t\t],\n\t\ttemperature=0,\n\t)\n\tst.markdown("**LLM Response:**")\n\tst.write(response["choices"][0]["message"]["content"].strip())\n\tst.markdown("**Total tokens:**")\n\tst.write(str(response["usage"]["total_tokens"]))\n"""\n    )\n', (41096, 41700), True, 'import streamlit as st\n'), ((41692, 41728), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (41703, 41728), True, 'import streamlit as st\n'), ((41988, 42178), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': 'MODEL', 'messages': "[{'role': 'system', 'content': st.session_state.prompt_template}, {'role':\n    'user', 'content': prompt}]", 'temperature': '(0)', 'stream': '(True)'}), "(model=MODEL, messages=[{'role': 'system',\n    'content': st.session_state.prompt_template}, {'role': 'user',\n    'content': prompt}], temperature=0, stream=True)\n", (42016, 42178), False, 'import openai\n'), ((43282, 43348), 'streamlit.subheader', 'st.subheader', (['"""Challenge 10: Make your bot like someone you know!"""'], {}), "('Challenge 10: Make your bot like someone you know!')\n", (43294, 43348), True, 'import streamlit as st\n'), ((43350, 43445), 'streamlit.write', 'st.write', (['"""Modify the ***prompt_template*** in your ***main()*** to your own liking."""'], {}), "(\n    'Modify the ***prompt_template*** in your ***main()*** to your own liking.'\n    )\n", (43358, 43445), True, 'import streamlit as st\n'), ((43437, 43464), 'streamlit.write', 'st.write', (['"""Be imaginative!"""'], {}), "('Be imaginative!')\n", (43445, 43464), True, 'import streamlit as st\n'), ((43466, 43657), 'streamlit.write', 'st.write', (['"""Now, in new function called **chat_completion_stream_prompt()**, we are going to modify the earlier **streaming chat_completion** function to accept a user prompt input."""'], {}), "(\n    'Now, in new function called **chat_completion_stream_prompt()**, we are going to modify the earlier **streaming chat_completion** function to accept a user prompt input.'\n    )\n", (43474, 43657), True, 'import streamlit as st\n'), ((43649, 43797), 'streamlit.write', 'st.write', (['"""You will need to pass in a new input variable called **prompt** and replace the user content with the new **prompt** variable."""'], {}), "(\n    'You will need to pass in a new input variable called **prompt** and replace the user content with the new **prompt** variable.'\n    )\n", (43657, 43797), True, 'import streamlit as st\n'), ((43789, 43874), 'streamlit.write', 'st.write', (['"""Replace the system prompt with **st.session_state.prompt_template**."""'], {}), "('Replace the system prompt with **st.session_state.prompt_template**.'\n    )\n", (43797, 43874), True, 'import streamlit as st\n'), ((43871, 44037), 'streamlit.write', 'st.write', (['"""Before calling **chat_completion_stream_prompt()**, get a new prompt from the user like this to update the **st.session_state.prompt_template**:"""'], {}), "(\n    'Before calling **chat_completion_stream_prompt()**, get a new prompt from the user like this to update the **st.session_state.prompt_template**:'\n    )\n", (43879, 44037), True, 'import streamlit as st\n'), ((44029, 44295), 'streamlit.code', 'st.code', (['"""\nif my_prompt_template := st.text_input("Enter a system prompt template. E.g. Speak like Yoda from Star Wars."):\n\tst.session_state.prompt_template = my_prompt_template\n\tst.write("new prompt template set! ", st.session_state.prompt_template)\n"""'], {}), '(\n    """\nif my_prompt_template := st.text_input("Enter a system prompt template. E.g. Speak like Yoda from Star Wars."):\n\tst.session_state.prompt_template = my_prompt_template\n\tst.write("new prompt template set! ", st.session_state.prompt_template)\n"""\n    )\n', (44036, 44295), True, 'import streamlit as st\n'), ((44287, 44317), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (44298, 44317), True, 'import streamlit as st\n'), ((45887, 45923), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (45898, 45923), True, 'import streamlit as st\n'), ((45925, 45979), 'streamlit.title', 'st.title', (['"""ChatGPT-like clone with Prompt Engineering"""'], {}), "('ChatGPT-like clone with Prompt Engineering')\n", (45933, 45979), True, 'import streamlit as st\n'), ((46111, 46266), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['subject', 'topic']", 'template': '"""Design a lesson plan on {subject} on the topic of {topic} for primary 1 students"""'}), "(input_variables=['subject', 'topic'], template=\n    'Design a lesson plan on {subject} on the topic of {topic} for primary 1 students'\n    )\n", (46125, 46266), False, 'from langchain.prompts import PromptTemplate\n'), ((46323, 46378), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0.9)'}), "(model_name='gpt-3.5-turbo', temperature=0.9)\n", (46333, 46378), False, 'from langchain.chat_models import ChatOpenAI\n'), ((46457, 46489), 'langchain.chains.LLMChain', 'LLMChain', ([], {'llm': 'llm', 'prompt': 'prompt'}), '(llm=llm, prompt=prompt)\n', (46465, 46489), False, 'from langchain.chains import LLMChain\n'), ((46494, 46519), 'streamlit.button', 'st.button', (['"""Run my chain"""'], {}), "('Run my chain')\n", (46503, 46519), True, 'import streamlit as st\n'), ((46793, 46853), 'streamlit.subheader', 'st.subheader', (['"""Exercise 11a: Prompt Template with LangChain"""'], {}), "('Exercise 11a: Prompt Template with LangChain')\n", (46805, 46853), True, 'import streamlit as st\n'), ((46855, 46956), 'streamlit.write', 'st.write', (['"""LangChain helps you to create a more complext prompt template for your chatbot."""'], {}), "(\n    'LangChain helps you to create a more complext prompt template for your chatbot.'\n    )\n", (46863, 46956), True, 'import streamlit as st\n'), ((46949, 46979), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (46960, 46979), True, 'import streamlit as st\n'), ((46981, 47789), 'streamlit.code', 'st.code', (['"""\n#https://python.langchain.com/docs/modules/chains/\ndef ex11a():  # change in ex11a\n\t# langchain prompt template\n\tprompt = PromptTemplate(\n\t\tinput_variables=["subject", "topic"],\n\t\ttemplate=""\\"Design a lesson plan on {subject} on the topic of {topic} for primary 1 students""\\",\n\t)\n\n\t# openai_api_key = st.secrets["openapi_key"]\n\tllm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.9)\n\n\t# creating a LLM chain with the langchain call and prompt template\n\tchain = LLMChain(llm=llm, prompt=prompt)\n\tif st.button("Run my chain"):\n\t\tinput_prompt = prompt.format(subject="English", topic="Verbs")\n\t\t# Showing what is sent to LLM Chain\n\t\tst.write("Input prompt: ", input_prompt)\n\t\t# Showing the output from LLM Chain\n\t\tst.write(chain.run({"subject": "English", "topic": "Verbs"}))\n"""'], {}), '(\n    """\n#https://python.langchain.com/docs/modules/chains/\ndef ex11a():  # change in ex11a\n\t# langchain prompt template\n\tprompt = PromptTemplate(\n\t\tinput_variables=["subject", "topic"],\n\t\ttemplate=""\\"Design a lesson plan on {subject} on the topic of {topic} for primary 1 students""\\",\n\t)\n\n\t# openai_api_key = st.secrets["openapi_key"]\n\tllm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.9)\n\n\t# creating a LLM chain with the langchain call and prompt template\n\tchain = LLMChain(llm=llm, prompt=prompt)\n\tif st.button("Run my chain"):\n\t\tinput_prompt = prompt.format(subject="English", topic="Verbs")\n\t\t# Showing what is sent to LLM Chain\n\t\tst.write("Input prompt: ", input_prompt)\n\t\t# Showing the output from LLM Chain\n\t\tst.write(chain.run({"subject": "English", "topic": "Verbs"}))\n"""\n    )\n', (46988, 47789), True, 'import streamlit as st\n'), ((47779, 47815), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (47790, 47815), True, 'import streamlit as st\n'), ((48484, 48823), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['occupation', 'topic', 'age']", 'template': '"""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""'}), "(input_variables=['occupation', 'topic', 'age'], template=\n    'Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up'\n    )\n", (48498, 48823), False, 'from langchain.prompts import PromptTemplate\n'), ((48879, 48934), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'temperature': '(0.9)'}), "(model_name='gpt-3.5-turbo', temperature=0.9)\n", (48889, 48934), False, 'from langchain.chat_models import ChatOpenAI\n'), ((49018, 49059), 'langchain.chains.LLMChain', 'LLMChain', ([], {'llm': 'llm', 'prompt': 'prompt_template'}), '(llm=llm, prompt=prompt_template)\n', (49026, 49059), False, 'from langchain.chains import LLMChain\n'), ((49203, 49231), 'streamlit.subheader', 'st.subheader', (['"""Exercise 11b"""'], {}), "('Exercise 11b')\n", (49215, 49231), True, 'import streamlit as st\n'), ((49233, 49329), 'streamlit.write', 'st.write', (['"""Now, we will create a chatbot with a prompt template that is more complex."""'], {}), "(\n    'Now, we will create a chatbot with a prompt template that is more complex.'\n    )\n", (49241, 49329), True, 'import streamlit as st\n'), ((49321, 49443), 'streamlit.write', 'st.write', (['"""We will use the ***prompt_inputs_form()*** function to get the user\'s input for the prompt template."""'], {}), '(\n    "We will use the ***prompt_inputs_form()*** function to get the user\'s input for the prompt template."\n    )\n', (49329, 49443), True, 'import streamlit as st\n'), ((49435, 49495), 'streamlit.write', 'st.write', (['"""Run the code below to see the chatbot in action."""'], {}), "('Run the code below to see the chatbot in action.')\n", (49443, 49495), True, 'import streamlit as st\n'), ((49498, 49528), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (49509, 49528), True, 'import streamlit as st\n'), ((49530, 50886), 'streamlit.code', 'st.code', (['"""\ndef prompt_inputs_form():  # Using st.form, create the starting prompt to your prompt template, this is an expert on a topic that is talking to a user of a certain age\n\t# langchain prompt template\n\twith st.form("Prompt Template"):\n\t\toccupation = st.text_input("Enter the occupation:")\n\t\ttopic = st.text_input("Enter the topic:")\n\t\tage = st.text_input("Enter the age:")\n\n\t\t# Every form must have a submit button.\n\t\tsubmitted = st.form_submit_button("Submit")\n\t# return a dictionary of the values\n\tif submitted:\n\t\treturn {"occupation": occupation, "topic": topic, "age": age}\n\ndef ex11b():\n\t# create your template\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\t# create a langchain function call to openai\n\tllm = ChatOpenAI(\n\t\tmodel_name="gpt-3.5-turbo",\n\t\ttemperature=0.9,\n\t)\n\t# create a LLM chain with the langchain call and prompt template\n\tchain = LLMChain(llm=llm, prompt=prompt_template)\n\t# call the prompt_inputs_form()\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tst.write(chain.run(dict_inputs))\n"""'], {}), '(\n    """\ndef prompt_inputs_form():  # Using st.form, create the starting prompt to your prompt template, this is an expert on a topic that is talking to a user of a certain age\n\t# langchain prompt template\n\twith st.form("Prompt Template"):\n\t\toccupation = st.text_input("Enter the occupation:")\n\t\ttopic = st.text_input("Enter the topic:")\n\t\tage = st.text_input("Enter the age:")\n\n\t\t# Every form must have a submit button.\n\t\tsubmitted = st.form_submit_button("Submit")\n\t# return a dictionary of the values\n\tif submitted:\n\t\treturn {"occupation": occupation, "topic": topic, "age": age}\n\ndef ex11b():\n\t# create your template\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\t# create a langchain function call to openai\n\tllm = ChatOpenAI(\n\t\tmodel_name="gpt-3.5-turbo",\n\t\ttemperature=0.9,\n\t)\n\t# create a LLM chain with the langchain call and prompt template\n\tchain = LLMChain(llm=llm, prompt=prompt_template)\n\t# call the prompt_inputs_form()\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tst.write(chain.run(dict_inputs))\n"""\n    )\n', (49537, 50886), True, 'import streamlit as st\n'), ((50878, 50914), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (50889, 50914), True, 'import streamlit as st\n'), ((51092, 51431), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['occupation', 'topic', 'age']", 'template': '"""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""'}), "(input_variables=['occupation', 'topic', 'age'], template=\n    'Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up'\n    )\n", (51106, 51431), False, 'from langchain.prompts import PromptTemplate\n'), ((51870, 51930), 'streamlit.subheader', 'st.subheader', (['"""Challenge 11: Prompt Template with LangChain"""'], {}), "('Challenge 11: Prompt Template with LangChain')\n", (51882, 51930), True, 'import streamlit as st\n'), ((51932, 52041), 'streamlit.write', 'st.write', (['"""Now, let\'s incorporate the prompt template into our chatbot from the previous exercise."""'], {}), '(\n    "Now, let\'s incorporate the prompt template into our chatbot from the previous exercise."\n    )\n', (51940, 52041), True, 'import streamlit as st\n'), ((52033, 52155), 'streamlit.write', 'st.write', (['"""We will use the ***prompt_inputs_form()*** function to get the user\'s input for the prompt template."""'], {}), '(\n    "We will use the ***prompt_inputs_form()*** function to get the user\'s input for the prompt template."\n    )\n', (52041, 52155), True, 'import streamlit as st\n'), ((52147, 52302), 'streamlit.write', 'st.write', (['"""You can use the ***ch10*** function from the previous exercise to do the llm api call with the updated session_state.prompt_template."""'], {}), "(\n    'You can use the ***ch10*** function from the previous exercise to do the llm api call with the updated session_state.prompt_template.'\n    )\n", (52155, 52302), True, 'import streamlit as st\n'), ((52294, 52461), 'streamlit.write', 'st.write', (['"""Ignore the text input field that asks for a system prompt template from ch10(), since we will be using the prompt template from the user\'s input."""'], {}), '(\n    "Ignore the text input field that asks for a system prompt template from ch10(), since we will be using the prompt template from the user\'s input."\n    )\n', (52302, 52461), True, 'import streamlit as st\n'), ((52453, 52609), 'streamlit.write', 'st.write', (['"""As you interact with the chatbot, observe that the prompt template is updated with the latest user input as seen from the code output."""'], {}), "(\n    'As you interact with the chatbot, observe that the prompt template is updated with the latest user input as seen from the code output.'\n    )\n", (52461, 52609), True, 'import streamlit as st\n'), ((52602, 52632), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (52613, 52632), True, 'import streamlit as st\n'), ((53603, 53639), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (53614, 53639), True, 'import streamlit as st\n'), ((53691, 53726), 'langchain.memory.ConversationBufferWindowMemory', 'ConversationBufferWindowMemory', ([], {'k': '(3)'}), '(k=3)\n', (53721, 53726), False, 'from langchain.memory import ConversationBufferWindowMemory\n'), ((53934, 53991), 'langchain.memory.ConversationBufferWindowMemory', 'ConversationBufferWindowMemory', ([], {'k': '(3)', 'return_messages': '(True)'}), '(k=3, return_messages=True)\n', (53964, 53991), False, 'from langchain.memory import ConversationBufferWindowMemory\n'), ((54207, 54255), 'streamlit.subheader', 'st.subheader', (['"""Exercise 12: Chatbot with memory"""'], {}), "('Exercise 12: Chatbot with memory')\n", (54219, 54255), True, 'import streamlit as st\n'), ((54257, 54311), 'streamlit.write', 'st.write', (['"""Now, we will create a chatbot with memory."""'], {}), "('Now, we will create a chatbot with memory.')\n", (54265, 54311), True, 'import streamlit as st\n'), ((54313, 54430), 'streamlit.write', 'st.write', (['"""You can determine the number of previous messages to remember by setting the ***k*** parameter."""'], {}), "(\n    'You can determine the number of previous messages to remember by setting the ***k*** parameter.'\n    )\n", (54321, 54430), True, 'import streamlit as st\n'), ((54423, 54453), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (54434, 54453), True, 'import streamlit as st\n'), ((54455, 54998), 'streamlit.code', 'st.code', (['"""\ndef ex12():\n\tmemory = ConversationBufferWindowMemory(k=3)\n\tmemory.save_context({"input": "hi"}, {"output": "whats up?"})\n\tmemory.save_context({"input": "not much"}, {"output": "what can I help you with?"})\n\n\tst.write(memory.load_memory_variables({}))\n   \n\tmemory = ConversationBufferWindowMemory( k=3, return_messages=True)\n\tmemory.save_context({"input": "hi"}, {"output": "whats up?"})\n\tmemory.save_context({"input": "not much"}, {"output": "what can I help you with?"})\n\n\tst.write(memory.load_memory_variables({}))\n"""'], {}), '(\n    """\ndef ex12():\n\tmemory = ConversationBufferWindowMemory(k=3)\n\tmemory.save_context({"input": "hi"}, {"output": "whats up?"})\n\tmemory.save_context({"input": "not much"}, {"output": "what can I help you with?"})\n\n\tst.write(memory.load_memory_variables({}))\n   \n\tmemory = ConversationBufferWindowMemory( k=3, return_messages=True)\n\tmemory.save_context({"input": "hi"}, {"output": "whats up?"})\n\tmemory.save_context({"input": "not much"}, {"output": "what can I help you with?"})\n\n\tst.write(memory.load_memory_variables({}))\n"""\n    )\n', (54462, 54998), True, 'import streamlit as st\n'), ((54992, 55028), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (55003, 55028), True, 'import streamlit as st\n'), ((55122, 55471), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['occupation', 'topic', 'age']", 'template': '"""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""'}), '(input_variables=[\'occupation\', \'topic\', \'age\'], template=\n    """Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""\n    )\n', (55136, 55471), False, 'from langchain.prompts import PromptTemplate\n'), ((55725, 55765), 'streamlit.write', 'st.write', (['"""input prompt: """', 'input_prompt'], {}), "('input prompt: ', input_prompt)\n", (55733, 55765), True, 'import streamlit as st\n'), ((56030, 56079), 'streamlit.session_state.memory.load_memory_variables', 'st.session_state.memory.load_memory_variables', (['{}'], {}), '({})\n', (56075, 56079), True, 'import streamlit as st\n'), ((56081, 56119), 'streamlit.write', 'st.write', (['"""Memory Data: """', 'memory_data'], {}), "('Memory Data: ', memory_data)\n", (56089, 56119), True, 'import streamlit as st\n'), ((56284, 56350), 'streamlit.write', 'st.write', (['"""New prompt template:"""', 'st.session_state.prompt_template'], {}), "('New prompt template:', st.session_state.prompt_template)\n", (56292, 56350), True, 'import streamlit as st\n'), ((57422, 57471), 'streamlit.subheader', 'st.subheader', (['"""Challenge 12: Chatbot with memory"""'], {}), "('Challenge 12: Chatbot with memory')\n", (57434, 57471), True, 'import streamlit as st\n'), ((57473, 57568), 'streamlit.write', 'st.write', (['"""Now, let\'s incorporate the memory into the session state prompt template."""'], {}), '(\n    "Now, let\'s incorporate the memory into the session state prompt template."\n    )\n', (57481, 57568), True, 'import streamlit as st\n'), ((57560, 57694), 'streamlit.write', 'st.write', (['"""The chatbot should remember the previous user input and use it as the prompt template for the next conversation."""'], {}), "(\n    'The chatbot should remember the previous user input and use it as the prompt template for the next conversation.'\n    )\n", (57568, 57694), True, 'import streamlit as st\n'), ((57686, 57788), 'streamlit.write', 'st.write', (['"""Start with the following code and modify ex12() to create a chatbot with memory."""'], {}), "(\n    'Start with the following code and modify ex12() to create a chatbot with memory.'\n    )\n", (57694, 57788), True, 'import streamlit as st\n'), ((57780, 57846), 'streamlit.write', 'st.write', (['"""Get the *{input_prompt}* using *prompt_inputs_form()*."""'], {}), "('Get the *{input_prompt}* using *prompt_inputs_form()*.')\n", (57788, 57846), True, 'import streamlit as st\n'), ((57848, 58018), 'streamlit.write', 'st.write', (['"""As you interact with the chatbot, observe that the memory is updated with the latest k number of user input and output as seen from the code output."""'], {}), "(\n    'As you interact with the chatbot, observe that the memory is updated with the latest k number of user input and output as seen from the code output.'\n    )\n", (57856, 58018), True, 'import streamlit as st\n'), ((58010, 58040), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (58021, 58040), True, 'import streamlit as st\n'), ((58042, 58532), 'streamlit.code', 'st.code', (['"""\nif "memory" not in st.session_state:\n\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t#step 1 save the memory from your chatbot \n\t#step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) \n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"{input_prompt}\n\nBelow is the conversation history between the AI and Users so far\n\n{memory_data}""\\"\n"""'], {}), '(\n    """\nif "memory" not in st.session_state:\n\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t#step 1 save the memory from your chatbot \n\t#step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) \n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"{input_prompt}\n\nBelow is the conversation history between the AI and Users so far\n\n{memory_data}""\\"\n"""\n    )\n', (58049, 58532), True, 'import streamlit as st\n'), ((58526, 58556), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (58537, 58556), True, 'import streamlit as st\n'), ((60957, 60993), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (60968, 60993), True, 'import streamlit as st\n'), ((61152, 61184), 'streamlit.subheader', 'st.subheader', (['"""Upload your docs"""'], {}), "('Upload your docs')\n", (61164, 61184), True, 'import streamlit as st\n'), ((61251, 61313), 'streamlit.file_uploader', 'st.file_uploader', (['"""Choose a file"""'], {'type': "['docx', 'txt', 'pdf']"}), "('Choose a file', type=['docx', 'txt', 'pdf'])\n", (61267, 61313), True, 'import streamlit as st\n'), ((62066, 62084), 'langchain.embeddings.openai.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (62082, 62084), False, 'from langchain.embeddings.openai import OpenAIEmbeddings\n'), ((62091, 62125), 'lancedb.connect', 'lancedb.connect', (['WORKING_DIRECTORY'], {}), '(WORKING_DIRECTORY)\n', (62106, 62125), False, 'import lancedb\n'), ((62967, 63017), 'streamlit.subheader', 'st.subheader', (['"""Exercise 13: Create a vector store"""'], {}), "('Exercise 13: Create a vector store')\n", (62979, 63017), True, 'import streamlit as st\n'), ((63019, 63095), 'streamlit.write', 'st.write', (['"""Now, we will create a vector store to store the user\'s document."""'], {}), '("Now, we will create a vector store to store the user\'s document.")\n', (63027, 63095), True, 'import streamlit as st\n'), ((63097, 63208), 'streamlit.write', 'st.write', (['"""This process uses OpenAI to generate embeddings and LanceDB for storing these embeddings."""'], {}), "(\n    'This process uses OpenAI to generate embeddings and LanceDB for storing these embeddings.'\n    )\n", (63105, 63208), True, 'import streamlit as st\n'), ((63200, 63251), 'streamlit.write', 'st.write', (['"""For now, this only works for pdf files."""'], {}), "('For now, this only works for pdf files.')\n", (63208, 63251), True, 'import streamlit as st\n'), ((63253, 63354), 'streamlit.write', 'st.write', (['"""You may need to run the following commands in terminal to install new libaries:"""'], {}), "(\n    'You may need to run the following commands in terminal to install new libaries:'\n    )\n", (63261, 63354), True, 'import streamlit as st\n'), ((63346, 63383), 'streamlit.code', 'st.code', (['"""\npip install tiktoken\n"""'], {}), '("""\npip install tiktoken\n""")\n', (63353, 63383), True, 'import streamlit as st\n'), ((63385, 63415), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (63396, 63415), True, 'import streamlit as st\n'), ((63417, 65367), 'streamlit.code', 'st.code', (['"""\n#exercise 13 - loading\ndef upload_file_streamlit():\n\tdef get_file_extension(file_name):\n\t\treturn os.path.splitext(file_name)[1]\n\n\tst.subheader("Upload your docs")\n\n\t# Streamlit file uploader to accept file input\n\tuploaded_file = st.file_uploader("Choose a file", type=["docx", "txt", "pdf"])\n\n\tif uploaded_file:\n\t\t# Reading file content\n\t\tfile_content = uploaded_file.read()\n\n\t\t# Determine the suffix based on uploaded file\'s name\n\t\tfile_suffix = get_file_extension(uploaded_file.name)\n\n\t\t# Saving the uploaded file temporarily to process it\n\t\twith tempfile.NamedTemporaryFile(delete=False, suffix=file_suffix) as temp_file:\n\t\t\ttemp_file.write(file_content)\n\t\t\ttemp_file.flush()  # Ensure the data is written to the file\n\t\t\ttemp_file_path = temp_file.name\n\t\treturn temp_file_path\n\t\n#exercise 13 - split and chunk, embeddings and storing in vectorstores for reference\ndef vectorstore_creator():\n\t# WORKING_DIRECTORY set above in the main.py\n\t# Process the temporary file using UnstructuredFileLoader (or any other method you need)\n\tembeddings = OpenAIEmbeddings()\n\tdb = lancedb.connect(WORKING_DIRECTORY)\n\ttable = db.create_table(\n\t\t"my_table",\n\t\tdata=[\n\t\t\t{\n\t\t\t\t"vector": embeddings.embed_query("Query unsuccessful"),\n\t\t\t\t"text": "Query unsuccessful",\n\t\t\t\t"id": "1",\n\t\t\t}\n\t\t],\n\t\tmode="overwrite",\n\t)\n\t# st.write(temp_file_path)\n\ttemp_file_path = upload_file_streamlit()\n\tif temp_file_path:\n\t\tloader = PyPDFLoader(temp_file_path)\n\t\tdocuments = loader.load_and_split()\n\t\tdb = LanceDB.from_documents(documents, embeddings, connection=table)\n\t\treturn db\n\ndef ex13_vectorstore_creator():\n\tif "vectorstore" not in st.session_state:\n\t\tst.session_state.vectorstore = False\n\tdb = vectorstore_creator()\n\tst.session_state.vectorstore = db\n\tif st.session_state.vectorstore:\n\t\tquery = st.text_input("Enter a query")\n\t\tif query:\n\t\t\tst.session_state.vectorstore = db\n\t\t\tdocs = db.similarity_search(query)\n\t\t\tst.write(docs[0].page_content)\n"""'], {}), '(\n    """\n#exercise 13 - loading\ndef upload_file_streamlit():\n\tdef get_file_extension(file_name):\n\t\treturn os.path.splitext(file_name)[1]\n\n\tst.subheader("Upload your docs")\n\n\t# Streamlit file uploader to accept file input\n\tuploaded_file = st.file_uploader("Choose a file", type=["docx", "txt", "pdf"])\n\n\tif uploaded_file:\n\t\t# Reading file content\n\t\tfile_content = uploaded_file.read()\n\n\t\t# Determine the suffix based on uploaded file\'s name\n\t\tfile_suffix = get_file_extension(uploaded_file.name)\n\n\t\t# Saving the uploaded file temporarily to process it\n\t\twith tempfile.NamedTemporaryFile(delete=False, suffix=file_suffix) as temp_file:\n\t\t\ttemp_file.write(file_content)\n\t\t\ttemp_file.flush()  # Ensure the data is written to the file\n\t\t\ttemp_file_path = temp_file.name\n\t\treturn temp_file_path\n\t\n#exercise 13 - split and chunk, embeddings and storing in vectorstores for reference\ndef vectorstore_creator():\n\t# WORKING_DIRECTORY set above in the main.py\n\t# Process the temporary file using UnstructuredFileLoader (or any other method you need)\n\tembeddings = OpenAIEmbeddings()\n\tdb = lancedb.connect(WORKING_DIRECTORY)\n\ttable = db.create_table(\n\t\t"my_table",\n\t\tdata=[\n\t\t\t{\n\t\t\t\t"vector": embeddings.embed_query("Query unsuccessful"),\n\t\t\t\t"text": "Query unsuccessful",\n\t\t\t\t"id": "1",\n\t\t\t}\n\t\t],\n\t\tmode="overwrite",\n\t)\n\t# st.write(temp_file_path)\n\ttemp_file_path = upload_file_streamlit()\n\tif temp_file_path:\n\t\tloader = PyPDFLoader(temp_file_path)\n\t\tdocuments = loader.load_and_split()\n\t\tdb = LanceDB.from_documents(documents, embeddings, connection=table)\n\t\treturn db\n\ndef ex13_vectorstore_creator():\n\tif "vectorstore" not in st.session_state:\n\t\tst.session_state.vectorstore = False\n\tdb = vectorstore_creator()\n\tst.session_state.vectorstore = db\n\tif st.session_state.vectorstore:\n\t\tquery = st.text_input("Enter a query")\n\t\tif query:\n\t\t\tst.session_state.vectorstore = db\n\t\t\tdocs = db.similarity_search(query)\n\t\t\tst.write(docs[0].page_content)\n"""\n    )\n', (63424, 65367), True, 'import streamlit as st\n'), ((65364, 65400), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (65375, 65400), True, 'import streamlit as st\n'), ((65621, 65970), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['occupation', 'topic', 'age']", 'template': '"""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""'}), '(input_variables=[\'occupation\', \'topic\', \'age\'], template=\n    """Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""\n    )\n', (65635, 65970), False, 'from langchain.prompts import PromptTemplate\n'), ((66589, 66638), 'streamlit.session_state.memory.load_memory_variables', 'st.session_state.memory.load_memory_variables', (['{}'], {}), '({})\n', (66634, 66638), True, 'import streamlit as st\n'), ((66640, 66661), 'streamlit.write', 'st.write', (['memory_data'], {}), '(memory_data)\n', (66648, 66661), True, 'import streamlit as st\n'), ((66825, 66892), 'streamlit.write', 'st.write', (['"""new prompt template: """', 'st.session_state.prompt_template'], {}), "('new prompt template: ', st.session_state.prompt_template)\n", (66833, 66892), True, 'import streamlit as st\n'), ((68569, 68613), 'streamlit.subheader', 'st.subheader', (['"""Exercise 14: Semantic search"""'], {}), "('Exercise 14: Semantic search')\n", (68581, 68613), True, 'import streamlit as st\n'), ((68615, 68719), 'streamlit.write', 'st.write', (['"""In this exercise. we will do a semantic search on the vector store in our chatbot."""'], {}), "(\n    'In this exercise. we will do a semantic search on the vector store in our chatbot.'\n    )\n", (68623, 68719), True, 'import streamlit as st\n'), ((68711, 68823), 'streamlit.write', 'st.write', (['"""At the same time, the chatbot is able to remember its conversation history to some extent."""'], {}), "(\n    'At the same time, the chatbot is able to remember its conversation history to some extent.'\n    )\n", (68719, 68823), True, 'import streamlit as st\n'), ((68815, 68988), 'streamlit.write', 'st.write', (['"""This code integrates advanced features like semantic search and context-aware prompts to provide a more engaging and helpful conversational experience."""'], {}), "(\n    'This code integrates advanced features like semantic search and context-aware prompts to provide a more engaging and helpful conversational experience.'\n    )\n", (68823, 68988), True, 'import streamlit as st\n'), ((68980, 69049), 'streamlit.write', 'st.write', (['"""Copy and run the code below to see the chatbot in action."""'], {}), "('Copy and run the code below to see the chatbot in action.')\n", (68988, 69049), True, 'import streamlit as st\n'), ((69052, 69082), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (69063, 69082), True, 'import streamlit as st\n'), ((69084, 72216), 'streamlit.code', 'st.code', (['"""\n# save the vectorstore in st.session_state\n# add semantic search prompt into memory prompt\n# integrate back into your chatbot\ndef ex14_basebot():\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\tst.session_state.input_prompt = input_prompt\n\n\tif "input_prompt" not in st.session_state:\n\t\tst.session_state.input_prompt = "Speak like Yoda from Star Wars"\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"\n\t\t{st.session_state.input_prompt}\n\n\t\tThis is the last conversation history:\n\t\t{memory_data}""\\"\n\tst.write("new prompt template: ", st.session_state.prompt_template)\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# query information\n\t\t\tif st.session_state.vectorstore:\n\t\t\t\tdocs = st.session_state.vectorstore.similarity_search(prompt)\n\t\t\t\tdocs = docs[0].page_content\n\t\t\t\t# add your query prompt\n\t\t\t\tvs_prompt = f""\\"\n\t\t\t\t\tYou should reference this search result to help your answer,\n\t\t\t\t\t{docs}\n\t\t\t\t\tif the search result does not anwer the query, please say you are unable to answer, do not make up an answer""\\"\n\t\t\telse:\n\t\t\t\tvs_prompt = ""\n\t\t\t# add query prompt to your memory prompt and send it to LLM\n\t\t\tst.session_state.prompt_template = (\n\t\t\t\tst.session_state.prompt_template + vs_prompt\n\t\t\t)\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""'], {}), '(\n    """\n# save the vectorstore in st.session_state\n# add semantic search prompt into memory prompt\n# integrate back into your chatbot\ndef ex14_basebot():\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\tst.session_state.input_prompt = input_prompt\n\n\tif "input_prompt" not in st.session_state:\n\t\tst.session_state.input_prompt = "Speak like Yoda from Star Wars"\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"\n\t\t{st.session_state.input_prompt}\n\n\t\tThis is the last conversation history:\n\t\t{memory_data}""\\"\n\tst.write("new prompt template: ", st.session_state.prompt_template)\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# query information\n\t\t\tif st.session_state.vectorstore:\n\t\t\t\tdocs = st.session_state.vectorstore.similarity_search(prompt)\n\t\t\t\tdocs = docs[0].page_content\n\t\t\t\t# add your query prompt\n\t\t\t\tvs_prompt = f""\\"\n\t\t\t\t\tYou should reference this search result to help your answer,\n\t\t\t\t\t{docs}\n\t\t\t\t\tif the search result does not anwer the query, please say you are unable to answer, do not make up an answer""\\"\n\t\t\telse:\n\t\t\t\tvs_prompt = ""\n\t\t\t# add query prompt to your memory prompt and send it to LLM\n\t\t\tst.session_state.prompt_template = (\n\t\t\t\tst.session_state.prompt_template + vs_prompt\n\t\t\t)\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""\n    )\n', (69091, 72216), True, 'import streamlit as st\n'), ((72203, 72239), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (72214, 72239), True, 'import streamlit as st\n'), ((72489, 72513), 'sqlite3.connect', 'sqlite3.connect', (['DB_NAME'], {}), '(DB_NAME)\n', (72504, 72513), False, 'import sqlite3\n'), ((72919, 72943), 'sqlite3.connect', 'sqlite3.connect', (['DB_NAME'], {}), '(DB_NAME)\n', (72934, 72943), False, 'import sqlite3\n'), ((72975, 72989), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (72987, 72989), False, 'from datetime import datetime\n'), ((73541, 73565), 'sqlite3.connect', 'sqlite3.connect', (['DB_NAME'], {}), '(DB_NAME)\n', (73556, 73565), False, 'import sqlite3\n'), ((73772, 73812), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'column_names'}), '(rows, columns=column_names)\n', (73784, 73812), True, 'import pandas as pd\n'), ((73814, 73830), 'streamlit.dataframe', 'st.dataframe', (['df'], {}), '(df)\n', (73826, 73830), True, 'import streamlit as st\n'), ((73866, 73911), 'streamlit.subheader', 'st.subheader', (['"""Exercise 15: Using a database"""'], {}), "('Exercise 15: Using a database')\n", (73878, 73911), True, 'import streamlit as st\n'), ((73913, 74049), 'streamlit.write', 'st.write', (['"""In this exercise, we will demonstrate how to create a database, as well as how to store and retrieve data from it."""'], {}), "(\n    'In this exercise, we will demonstrate how to create a database, as well as how to store and retrieve data from it.'\n    )\n", (73921, 74049), True, 'import streamlit as st\n'), ((74041, 74071), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (74052, 74071), True, 'import streamlit as st\n'), ((74073, 75680), 'streamlit.code', 'st.code', (['"""\ndef ex15_initialise():\n\t# Create or check for the \'database\' directory in the current working directory\n\t# Set DB_NAME to be within the \'database\' directory at the top of main.py\n\t# Connect to the SQLite database\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\n\t# Conversation data table\n\tcursor.execute(\n\t\t""\\"\n\t\tCREATE TABLE IF NOT EXISTS data_table (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tdate TEXT NOT NULL UNIQUE,\n\t\t\tusername TEXT NOT NULL,\n\t\t\tchatbot_ans TEXT NOT NULL,\n\t\t\tuser_prompt TEXT NOT NULL,\n\t\t\ttokens TEXT\n\t\t)\n\t""\\"\n\t)\n\tconn.commit()\n\tconn.close()\n\ndef ex15_collect(username, chatbot_response, prompt):\n\t# collect data from bot\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\tnow = datetime.now()  # Using ISO format for date\n\ttokens = len(chatbot_response) * 1.3\n\tcursor.execute(\n\t\t""\\"\n\t\tINSERT INTO data_table (date, username,chatbot_ans, user_prompt, tokens)\n\t\tVALUES (?, ?, ?, ?, ?)\n\t""\\",\n\t\t(now, username, chatbot_response, prompt, tokens),\n\t)\n\tconn.commit()\n\tconn.close()\n\n# implementing data collection and displaying\ndef ex15():\n\t# initialise database first\n\tex15_initialise()\n\t# collect some data\n\tex15_collect("yoda", "I am Yoda. The Force is strong with you", "Who are you?")\n\t# display data\n\t# Connect to the specified database\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\n\t# Fetch all data from data_table\n\tcursor.execute("SELECT * FROM data_table")\n\trows = cursor.fetchall()\n\tcolumn_names = [description[0] for description in cursor.description]\n\tdf = pd.DataFrame(rows, columns=column_names)\n\tst.dataframe(df)\n\tconn.close()\n"""'], {}), '(\n    """\ndef ex15_initialise():\n\t# Create or check for the \'database\' directory in the current working directory\n\t# Set DB_NAME to be within the \'database\' directory at the top of main.py\n\t# Connect to the SQLite database\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\n\t# Conversation data table\n\tcursor.execute(\n\t\t""\\"\n\t\tCREATE TABLE IF NOT EXISTS data_table (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tdate TEXT NOT NULL UNIQUE,\n\t\t\tusername TEXT NOT NULL,\n\t\t\tchatbot_ans TEXT NOT NULL,\n\t\t\tuser_prompt TEXT NOT NULL,\n\t\t\ttokens TEXT\n\t\t)\n\t""\\"\n\t)\n\tconn.commit()\n\tconn.close()\n\ndef ex15_collect(username, chatbot_response, prompt):\n\t# collect data from bot\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\tnow = datetime.now()  # Using ISO format for date\n\ttokens = len(chatbot_response) * 1.3\n\tcursor.execute(\n\t\t""\\"\n\t\tINSERT INTO data_table (date, username,chatbot_ans, user_prompt, tokens)\n\t\tVALUES (?, ?, ?, ?, ?)\n\t""\\",\n\t\t(now, username, chatbot_response, prompt, tokens),\n\t)\n\tconn.commit()\n\tconn.close()\n\n# implementing data collection and displaying\ndef ex15():\n\t# initialise database first\n\tex15_initialise()\n\t# collect some data\n\tex15_collect("yoda", "I am Yoda. The Force is strong with you", "Who are you?")\n\t# display data\n\t# Connect to the specified database\n\tconn = sqlite3.connect(DB_NAME)\n\tcursor = conn.cursor()\n\n\t# Fetch all data from data_table\n\tcursor.execute("SELECT * FROM data_table")\n\trows = cursor.fetchall()\n\tcolumn_names = [description[0] for description in cursor.description]\n\tdf = pd.DataFrame(rows, columns=column_names)\n\tst.dataframe(df)\n\tconn.close()\n"""\n    )\n', (74080, 75680), True, 'import streamlit as st\n'), ((75668, 75704), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (75679, 75704), True, 'import streamlit as st\n'), ((75836, 76185), 'langchain.prompts.PromptTemplate', 'PromptTemplate', ([], {'input_variables': "['occupation', 'topic', 'age']", 'template': '"""Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""'}), '(input_variables=[\'occupation\', \'topic\', \'age\'], template=\n    """Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up"""\n    )\n', (75850, 76185), False, 'from langchain.prompts import PromptTemplate\n'), ((76804, 76853), 'streamlit.session_state.memory.load_memory_variables', 'st.session_state.memory.load_memory_variables', (['{}'], {}), '({})\n', (76849, 76853), True, 'import streamlit as st\n'), ((76855, 76876), 'streamlit.write', 'st.write', (['memory_data'], {}), '(memory_data)\n', (76863, 76876), True, 'import streamlit as st\n'), ((77036, 77103), 'streamlit.write', 'st.write', (['"""new prompt template: """', 'st.session_state.prompt_template'], {}), "('new prompt template: ', st.session_state.prompt_template)\n", (77044, 77103), True, 'import streamlit as st\n'), ((78843, 78889), 'streamlit.subheader', 'st.subheader', (['"""Challenge 15: Using a database"""'], {}), "('Challenge 15: Using a database')\n", (78855, 78889), True, 'import streamlit as st\n'), ((78891, 78997), 'streamlit.write', 'st.write', (['"""For this challenge, we will incorporate using a database from our previous exercise."""'], {}), "(\n    'For this challenge, we will incorporate using a database from our previous exercise.'\n    )\n", (78899, 78997), True, 'import streamlit as st\n'), ((78989, 79100), 'streamlit.write', 'st.write', (['"""Copy the code from ***ex14()*** and use the ***ex15()*** to collect and display the data."""'], {}), "(\n    'Copy the code from ***ex14()*** and use the ***ex15()*** to collect and display the data.'\n    )\n", (78997, 79100), True, 'import streamlit as st\n'), ((79093, 79123), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (79104, 79123), True, 'import streamlit as st\n'), ((82271, 82307), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (82282, 82307), True, 'import streamlit as st\n'), ((82500, 82550), 'streamlit.title', 'st.title', (['"""🦜 LangChain: Chat with internet search"""'], {}), "('🦜 LangChain: Chat with internet search')\n", (82508, 82550), True, 'import streamlit as st\n'), ((82560, 82589), 'langchain.memory.chat_message_histories.StreamlitChatMessageHistory', 'StreamlitChatMessageHistory', ([], {}), '()\n', (82587, 82589), False, 'from langchain.memory.chat_message_histories import StreamlitChatMessageHistory\n'), ((82600, 82717), 'langchain.memory.ConversationBufferMemory', 'ConversationBufferMemory', ([], {'chat_memory': 'msgs', 'return_messages': '(True)', 'memory_key': '"""chat_history"""', 'output_key': '"""output"""'}), "(chat_memory=msgs, return_messages=True, memory_key\n    ='chat_history', output_key='output')\n", (82624, 82717), False, 'from langchain.memory import ConversationBufferMemory\n'), ((84182, 84222), 'streamlit.subheader', 'st.subheader', (['"""Exercise 16: Smart agent"""'], {}), "('Exercise 16: Smart agent')\n", (84194, 84222), True, 'import streamlit as st\n'), ((84224, 84369), 'streamlit.write', 'st.write', (['"""In this exercise, we will configure a chatbot with an internet search tool that shows all intermediate steps and tool logs."""'], {}), "(\n    'In this exercise, we will configure a chatbot with an internet search tool that shows all intermediate steps and tool logs.'\n    )\n", (84232, 84369), True, 'import streamlit as st\n'), ((84361, 84545), 'streamlit.write', 'st.write', (['"""This overcomes the limitation of the training data that is only up to a certain point in time, by being able to access the current internet to search for answers."""'], {}), "(\n    'This overcomes the limitation of the training data that is only up to a certain point in time, by being able to access the current internet to search for answers.'\n    )\n", (84369, 84545), True, 'import streamlit as st\n'), ((84538, 84639), 'streamlit.write', 'st.write', (['"""You may need to run the following commands in terminal to install new libaries:"""'], {}), "(\n    'You may need to run the following commands in terminal to install new libaries:'\n    )\n", (84546, 84639), True, 'import streamlit as st\n'), ((84631, 84677), 'streamlit.code', 'st.code', (['"""\npip install duckduckgo-search\n"""'], {}), '("""\npip install duckduckgo-search\n""")\n', (84638, 84677), True, 'import streamlit as st\n'), ((84681, 84711), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (84692, 84711), True, 'import streamlit as st\n'), ((84713, 86565), 'streamlit.code', 'st.code', (['"""\n# smart agents accessing the internet for free\n# https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/search_and_chat.py\ndef ex16_agent_bot():\n\tst.title("🦜 LangChain: Chat with internet search")\n\n\tmsgs = StreamlitChatMessageHistory()\n\tmemory = ConversationBufferMemory(\n\t\tchat_memory=msgs,\n\t\treturn_messages=True,\n\t\tmemory_key="chat_history",\n\t\toutput_key="output",\n\t)\n\tif len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):\n\t\tmsgs.clear()\n\t\tmsgs.add_ai_message("How can I help you?")\n\t\tst.session_state.steps = {}\n\n\tavatars = {"human": "user", "ai": "assistant"}\n\tfor idx, msg in enumerate(msgs.messages):\n\t\twith st.chat_message(avatars[msg.type]):\n\t\t\t# Render intermediate steps if any were saved\n\t\t\tfor step in st.session_state.steps.get(str(idx), []):\n\t\t\t\tif step[0].tool == "_Exception":\n\t\t\t\t\tcontinue\n\t\t\t\twith st.status(\n\t\t\t\t\tf"**{step[0].tool}**: {step[0].tool_input}", state="complete"\n\t\t\t\t):\n\t\t\t\t\tst.write(step[0].log)\n\t\t\t\t\tst.write(step[1])\n\t\t\tst.write(msg.content)\n\n\tif prompt := st.chat_input(placeholder="Enter a query on the Internet"):\n\t\tst.chat_message("user").write(prompt)\n\n\t\tllm = ChatOpenAI(\n\t\t\tmodel_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True\n\t\t)\n\t\ttools = [DuckDuckGoSearchRun(name="Search")]\n\t\tchat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)\n\t\texecutor = AgentExecutor.from_agent_and_tools(\n\t\t\tagent=chat_agent,\n\t\t\ttools=tools,\n\t\t\tmemory=memory,\n\t\t\treturn_intermediate_steps=True,\n\t\t\thandle_parsing_errors=True,\n\t\t)\n\t\twith st.chat_message("assistant"):\n\t\t\tst_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)\n\t\t\tresponse = executor(prompt, callbacks=[st_cb])\n\t\t\tst.write(response["output"])\n\t\t\tst.session_state.steps[str(len(msgs.messages) - 1)] = response[\n\t\t\t\t"intermediate_steps"\n\t\t\t]\n"""'], {}), '(\n    """\n# smart agents accessing the internet for free\n# https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/search_and_chat.py\ndef ex16_agent_bot():\n\tst.title("🦜 LangChain: Chat with internet search")\n\n\tmsgs = StreamlitChatMessageHistory()\n\tmemory = ConversationBufferMemory(\n\t\tchat_memory=msgs,\n\t\treturn_messages=True,\n\t\tmemory_key="chat_history",\n\t\toutput_key="output",\n\t)\n\tif len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):\n\t\tmsgs.clear()\n\t\tmsgs.add_ai_message("How can I help you?")\n\t\tst.session_state.steps = {}\n\n\tavatars = {"human": "user", "ai": "assistant"}\n\tfor idx, msg in enumerate(msgs.messages):\n\t\twith st.chat_message(avatars[msg.type]):\n\t\t\t# Render intermediate steps if any were saved\n\t\t\tfor step in st.session_state.steps.get(str(idx), []):\n\t\t\t\tif step[0].tool == "_Exception":\n\t\t\t\t\tcontinue\n\t\t\t\twith st.status(\n\t\t\t\t\tf"**{step[0].tool}**: {step[0].tool_input}", state="complete"\n\t\t\t\t):\n\t\t\t\t\tst.write(step[0].log)\n\t\t\t\t\tst.write(step[1])\n\t\t\tst.write(msg.content)\n\n\tif prompt := st.chat_input(placeholder="Enter a query on the Internet"):\n\t\tst.chat_message("user").write(prompt)\n\n\t\tllm = ChatOpenAI(\n\t\t\tmodel_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True\n\t\t)\n\t\ttools = [DuckDuckGoSearchRun(name="Search")]\n\t\tchat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)\n\t\texecutor = AgentExecutor.from_agent_and_tools(\n\t\t\tagent=chat_agent,\n\t\t\ttools=tools,\n\t\t\tmemory=memory,\n\t\t\treturn_intermediate_steps=True,\n\t\t\thandle_parsing_errors=True,\n\t\t)\n\t\twith st.chat_message("assistant"):\n\t\t\tst_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)\n\t\t\tresponse = executor(prompt, callbacks=[st_cb])\n\t\t\tst.write(response["output"])\n\t\t\tst.session_state.steps[str(len(msgs.messages) - 1)] = response[\n\t\t\t\t"intermediate_steps"\n\t\t\t]\n"""\n    )\n', (84720, 86565), True, 'import streamlit as st\n'), ((86557, 86593), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (86568, 86593), True, 'import streamlit as st\n'), ((86975, 87028), 'streamlit.session_state.vectorstore.similarity_search', 'st.session_state.vectorstore.similarity_search', (['query'], {}), '(query)\n', (87021, 87028), True, 'import streamlit as st\n'), ((87073, 87119), 'json.dumps', 'json.dumps', (['docs'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(docs, ensure_ascii=False, indent=4)\n', (87083, 87119), False, 'import json\n'), ((87197, 87247), 'streamlit.title', 'st.title', (['"""🦜 LangChain: Chat with internet search"""'], {}), "('🦜 LangChain: Chat with internet search')\n", (87205, 87247), True, 'import streamlit as st\n'), ((87312, 87341), 'langchain.memory.chat_message_histories.StreamlitChatMessageHistory', 'StreamlitChatMessageHistory', ([], {}), '()\n', (87339, 87341), False, 'from langchain.memory.chat_message_histories import StreamlitChatMessageHistory\n'), ((87352, 87469), 'langchain.memory.ConversationBufferMemory', 'ConversationBufferMemory', ([], {'chat_memory': 'msgs', 'return_messages': '(True)', 'memory_key': '"""chat_history"""', 'output_key': '"""output"""'}), "(chat_memory=msgs, return_messages=True, memory_key\n    ='chat_history', output_key='output')\n", (87376, 87469), False, 'from langchain.memory import ConversationBufferMemory\n'), ((88960, 89018), 'streamlit.subheader', 'st.subheader', (['"""Exercise 17: Smart agent with vector store"""'], {}), "('Exercise 17: Smart agent with vector store')\n", (88972, 89018), True, 'import streamlit as st\n'), ((89020, 89109), 'streamlit.write', 'st.write', (['"""In this exercise, we will combine the vector store with the smart agent."""'], {}), "(\n    'In this exercise, we will combine the vector store with the smart agent.')\n", (89028, 89109), True, 'import streamlit as st\n'), ((89106, 89213), 'streamlit.write', 'st.write', (['"""This allows the chatbot to search for answers from the vector store and the internet."""'], {}), "(\n    'This allows the chatbot to search for answers from the vector store and the internet.'\n    )\n", (89114, 89213), True, 'import streamlit as st\n'), ((89205, 89421), 'streamlit.write', 'st.write', (['"""The @tool("Document search") function is an enhancement to the chatbot. It allows for an initial internal document search based on the user query before resorting to external internet searches. """'], {}), '(\n    \'The @tool("Document search") function is an enhancement to the chatbot. It allows for an initial internal document search based on the user query before resorting to external internet searches. \'\n    )\n', (89213, 89421), True, 'import streamlit as st\n'), ((89415, 89484), 'streamlit.write', 'st.write', (['"""Copy and run the code below to see the chatbot in action."""'], {}), "('Copy and run the code below to see the chatbot in action.')\n", (89423, 89484), True, 'import streamlit as st\n'), ((89487, 89517), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (89498, 89517), True, 'import streamlit as st\n'), ((89519, 91871), 'streamlit.code', 'st.code', (['"""\n# agents ,vectorstores, wiki\n# https://python.langchain.com/docs/modules/agents/how_to/custom_agent_with_tool_retrieval\n# note tool\n@tool("Document search")\ndef document_search(query: str) -> str:\n\t# this is the prompt to the tool itself\n\t"Use this function first to search for documents pertaining to the query before going into the internet"\n\tdocs = st.session_state.vectorstore.similarity_search(query)\n\tdocs = docs[0].page_content\n\tjson_string = json.dumps(docs, ensure_ascii=False, indent=4)\n\treturn json_string\n\n# combine vector store and internet search\ndef ex17_agent_bot():\n\tst.title("🦜 LangChain: Chat with internet search")\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\tmsgs = StreamlitChatMessageHistory()\n\tmemory = ConversationBufferMemory(\n\t\tchat_memory=msgs,\n\t\treturn_messages=True,\n\t\tmemory_key="chat_history",\n\t\toutput_key="output",\n\t)\n\tif len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):\n\t\tmsgs.clear()\n\t\tmsgs.add_ai_message("How can I help you?")\n\t\tst.session_state.steps = {}\n\n\tavatars = {"human": "user", "ai": "assistant"}\n\tfor idx, msg in enumerate(msgs.messages):\n\t\twith st.chat_message(avatars[msg.type]):\n\t\t\t# Render intermediate steps if any were saved\n\t\t\tfor step in st.session_state.steps.get(str(idx), []):\n\t\t\t\tif step[0].tool == "_Exception":\n\t\t\t\t\tcontinue\n\t\t\t\twith st.status(\n\t\t\t\t\tf"**{step[0].tool}**: {step[0].tool_input}", state="complete"\n\t\t\t\t):\n\t\t\t\t\tst.write(step[0].log)\n\t\t\t\t\tst.write(step[1])\n\t\t\tst.write(msg.content)\n\n\tif prompt := st.chat_input(placeholder="Enter a query on the Internet"):\n\t\tst.chat_message("user").write(prompt)\n\n\t\tllm = ChatOpenAI(\n\t\t\tmodel_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True\n\t\t)\n\t\ttools = [document_search, DuckDuckGoSearchRun(name="Internet Search")]\n\t\tchat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)\n\t\texecutor = AgentExecutor.from_agent_and_tools(\n\t\t\tagent=chat_agent,\n\t\t\ttools=tools,\n\t\t\tmemory=memory,\n\t\t\treturn_intermediate_steps=True,\n\t\t\thandle_parsing_errors=True,\n\t\t)\n\t\twith st.chat_message("assistant"):\n\t\t\tst_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)\n\t\t\tresponse = executor(prompt, callbacks=[st_cb])\n\t\t\tst.write(response["output"])\n\t\t\tst.session_state.steps[str(len(msgs.messages) - 1)] = response[\n\t\t\t\t"intermediate_steps"\n\t\t\t]\n"""'], {}), '(\n    """\n# agents ,vectorstores, wiki\n# https://python.langchain.com/docs/modules/agents/how_to/custom_agent_with_tool_retrieval\n# note tool\n@tool("Document search")\ndef document_search(query: str) -> str:\n\t# this is the prompt to the tool itself\n\t"Use this function first to search for documents pertaining to the query before going into the internet"\n\tdocs = st.session_state.vectorstore.similarity_search(query)\n\tdocs = docs[0].page_content\n\tjson_string = json.dumps(docs, ensure_ascii=False, indent=4)\n\treturn json_string\n\n# combine vector store and internet search\ndef ex17_agent_bot():\n\tst.title("🦜 LangChain: Chat with internet search")\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\tmsgs = StreamlitChatMessageHistory()\n\tmemory = ConversationBufferMemory(\n\t\tchat_memory=msgs,\n\t\treturn_messages=True,\n\t\tmemory_key="chat_history",\n\t\toutput_key="output",\n\t)\n\tif len(msgs.messages) == 0 or st.sidebar.button("Reset chat history"):\n\t\tmsgs.clear()\n\t\tmsgs.add_ai_message("How can I help you?")\n\t\tst.session_state.steps = {}\n\n\tavatars = {"human": "user", "ai": "assistant"}\n\tfor idx, msg in enumerate(msgs.messages):\n\t\twith st.chat_message(avatars[msg.type]):\n\t\t\t# Render intermediate steps if any were saved\n\t\t\tfor step in st.session_state.steps.get(str(idx), []):\n\t\t\t\tif step[0].tool == "_Exception":\n\t\t\t\t\tcontinue\n\t\t\t\twith st.status(\n\t\t\t\t\tf"**{step[0].tool}**: {step[0].tool_input}", state="complete"\n\t\t\t\t):\n\t\t\t\t\tst.write(step[0].log)\n\t\t\t\t\tst.write(step[1])\n\t\t\tst.write(msg.content)\n\n\tif prompt := st.chat_input(placeholder="Enter a query on the Internet"):\n\t\tst.chat_message("user").write(prompt)\n\n\t\tllm = ChatOpenAI(\n\t\t\tmodel_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True\n\t\t)\n\t\ttools = [document_search, DuckDuckGoSearchRun(name="Internet Search")]\n\t\tchat_agent = ConversationalChatAgent.from_llm_and_tools(llm=llm, tools=tools)\n\t\texecutor = AgentExecutor.from_agent_and_tools(\n\t\t\tagent=chat_agent,\n\t\t\ttools=tools,\n\t\t\tmemory=memory,\n\t\t\treturn_intermediate_steps=True,\n\t\t\thandle_parsing_errors=True,\n\t\t)\n\t\twith st.chat_message("assistant"):\n\t\t\tst_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)\n\t\t\tresponse = executor(prompt, callbacks=[st_cb])\n\t\t\tst.write(response["output"])\n\t\t\tst.session_state.steps[str(len(msgs.messages) - 1)] = response[\n\t\t\t\t"intermediate_steps"\n\t\t\t]\n"""\n    )\n', (89526, 91871), True, 'import streamlit as st\n'), ((91863, 91899), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (91874, 91899), True, 'import streamlit as st\n'), ((91997, 92038), 'streamlit.title', 'st.title', (['"""pandas-ai streamlit interface"""'], {}), "('pandas-ai streamlit interface')\n", (92005, 92038), True, 'import streamlit as st\n'), ((92099, 92148), 'streamlit.file_uploader', 'st.file_uploader', (['"""Choose a CSV file"""'], {'type': '"""csv"""'}), "('Choose a CSV file', type='csv')\n", (92115, 92148), True, 'import streamlit as st\n'), ((93144, 93174), 'os.path.join', 'os.path.join', (['"""exports/charts"""'], {}), "('exports/charts')\n", (93156, 93174), False, 'import os\n'), ((94162, 94193), 'streamlit.subheader', 'st.subheader', (['"""Prompt history:"""'], {}), "('Prompt history:')\n", (94174, 94193), True, 'import streamlit as st\n'), ((94195, 94236), 'streamlit.write', 'st.write', (['st.session_state.prompt_history'], {}), '(st.session_state.prompt_history)\n', (94203, 94236), True, 'import streamlit as st\n'), ((94242, 94260), 'streamlit.button', 'st.button', (['"""Clear"""'], {}), "('Clear')\n", (94251, 94260), True, 'import streamlit as st\n'), ((94351, 94394), 'streamlit.subheader', 'st.subheader', (['"""Exercise 18: Data Analytics"""'], {}), "('Exercise 18: Data Analytics')\n", (94363, 94394), True, 'import streamlit as st\n'), ((94396, 94496), 'streamlit.write', 'st.write', (['"""In this exercise, we will use the Pandas AI library to perform data analytics."""'], {}), "(\n    'In this exercise, we will use the Pandas AI library to perform data analytics.'\n    )\n", (94404, 94496), True, 'import streamlit as st\n'), ((94488, 94596), 'streamlit.write', 'st.write', (['"""The Pandas AI library is a smart agent that can perform data analytics on a dataframe."""'], {}), "(\n    'The Pandas AI library is a smart agent that can perform data analytics on a dataframe.'\n    )\n", (94496, 94596), True, 'import streamlit as st\n'), ((94588, 94646), 'streamlit.write', 'st.write', (['"""You may need to install the following library:"""'], {}), "('You may need to install the following library:')\n", (94596, 94646), True, 'import streamlit as st\n'), ((94648, 94674), 'streamlit.code', 'st.code', (['"""pip install bs4"""'], {}), "('pip install bs4')\n", (94655, 94674), True, 'import streamlit as st\n'), ((94680, 94749), 'streamlit.write', 'st.write', (['"""Copy and run the code below to see the chatbot in action."""'], {}), "('Copy and run the code below to see the chatbot in action.')\n", (94688, 94749), True, 'import streamlit as st\n'), ((94752, 94782), 'streamlit.markdown', 'st.markdown', (['"""**:blue[Code]**"""'], {}), "('**:blue[Code]**')\n", (94763, 94782), True, 'import streamlit as st\n'), ((94784, 97221), 'streamlit.code', 'st.code', (['"""\n# PandasAI- A smart agent that can do visual analytics\ndef ex18_pandas_AI():\n\tst.title("pandas-ai streamlit interface")\n\n\t# Upload CSV file using st.file_uploader\n\tuploaded_file = st.file_uploader("Choose a CSV file", type="csv")\n\tif "openai_key" not in st.session_state:\n\t\tst.session_state.openai_key = st.secrets["openapi_key"]\n\t\tst.session_state.prompt_history = []\n\t\tst.session_state.df = None\n\n\tif uploaded_file is not None:\n\t\ttry:\n\t\t\tdf = pd.read_csv(uploaded_file)\n\t\t\tst.session_state.df = df\n\t\texcept Exception as e:\n\t\t\tst.write("There was an error processing the CSV file.")\n\t\t\tst.write(e)\n\n\telse:\n\t\tst.session_state.df = pd.DataFrame(\n\t\t\t{\n\t\t\t\t"country": [\n\t\t\t\t\t"United States",\n\t\t\t\t\t"United Kingdom",\n\t\t\t\t\t"France",\n\t\t\t\t\t"Germany",\n\t\t\t\t\t"Italy",\n\t\t\t\t\t"Spain",\n\t\t\t\t\t"Canada",\n\t\t\t\t\t"Australia",\n\t\t\t\t\t"Japan",\n\t\t\t\t\t"China",\n\t\t\t\t],\n\t\t\t\t"gdp": [\n\t\t\t\t\t19294482071552,\n\t\t\t\t\t2891615567872,\n\t\t\t\t\t2411255037952,\n\t\t\t\t\t3435817336832,\n\t\t\t\t\t1745433788416,\n\t\t\t\t\t1181205135360,\n\t\t\t\t\t1607402389504,\n\t\t\t\t\t1490967855104,\n\t\t\t\t\t4380756541440,\n\t\t\t\t\t14631844184064,\n\t\t\t\t],\n\t\t\t\t"happiness_index": [\n\t\t\t\t\t6.94,\n\t\t\t\t\t7.16,\n\t\t\t\t\t6.66,\n\t\t\t\t\t7.07,\n\t\t\t\t\t6.38,\n\t\t\t\t\t6.4,\n\t\t\t\t\t7.23,\n\t\t\t\t\t7.22,\n\t\t\t\t\t5.87,\n\t\t\t\t\t5.12,\n\t\t\t\t],\n\t\t\t}\n\t\t)\n\tchart_path = os.path.join("exports/charts")\n\twith st.form("Question"):\n\t\tquestion = st.text_input("Question", value="", type="default")\n\t\tsubmitted = st.form_submit_button("Submit")\n\t\tif submitted:\n\t\t\twith st.spinner():\n\t\t\t\tllm = OpenAI(api_token=st.session_state.openai_key)\n\t\t\t\tdf = SmartDataframe(\n\t\t\t\t\tst.session_state.df,\n\t\t\t\t\tconfig={\n\t\t\t\t\t\t"llm": llm,\n\t\t\t\t\t\t"save_charts_path": chart_path,\n\t\t\t\t\t\t"save_charts": True,\n\t\t\t\t\t\t"verbose": True,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\tresponse = df.chat(\n\t\t\t\t\tquestion\n\t\t\t\t)  # Using \'chat\' method based on your context\n\n\t\t\t\t# Display the textual response (if any):\n\t\t\t\tif response:\n\t\t\t\t\tst.write(response)\n\t\t\t\tchart_path = os.path.join("exports/charts", "temp_chart.png")\n\t\t\t\tif os.path.exists(chart_path):\n\t\t\t\t\tst.image(\n\t\t\t\t\t\tchart_path, caption="Generated Chart", use_column_width=True\n\t\t\t\t\t)\n\t\t\t\t# Append the question to the history:\n\t\t\t\tst.session_state.prompt_history.append(question)\n\n\tif st.session_state.df is not None:\n\t\tst.subheader("Current dataframe:")\n\t\tst.write(st.session_state.df)\n\n\tst.subheader("Prompt history:")\n\tst.write(st.session_state.prompt_history)\n\n\tif st.button("Clear"):\n\t\tst.session_state.prompt_history = []\n\t\tst.session_state.df = None\n"""'], {}), '(\n    """\n# PandasAI- A smart agent that can do visual analytics\ndef ex18_pandas_AI():\n\tst.title("pandas-ai streamlit interface")\n\n\t# Upload CSV file using st.file_uploader\n\tuploaded_file = st.file_uploader("Choose a CSV file", type="csv")\n\tif "openai_key" not in st.session_state:\n\t\tst.session_state.openai_key = st.secrets["openapi_key"]\n\t\tst.session_state.prompt_history = []\n\t\tst.session_state.df = None\n\n\tif uploaded_file is not None:\n\t\ttry:\n\t\t\tdf = pd.read_csv(uploaded_file)\n\t\t\tst.session_state.df = df\n\t\texcept Exception as e:\n\t\t\tst.write("There was an error processing the CSV file.")\n\t\t\tst.write(e)\n\n\telse:\n\t\tst.session_state.df = pd.DataFrame(\n\t\t\t{\n\t\t\t\t"country": [\n\t\t\t\t\t"United States",\n\t\t\t\t\t"United Kingdom",\n\t\t\t\t\t"France",\n\t\t\t\t\t"Germany",\n\t\t\t\t\t"Italy",\n\t\t\t\t\t"Spain",\n\t\t\t\t\t"Canada",\n\t\t\t\t\t"Australia",\n\t\t\t\t\t"Japan",\n\t\t\t\t\t"China",\n\t\t\t\t],\n\t\t\t\t"gdp": [\n\t\t\t\t\t19294482071552,\n\t\t\t\t\t2891615567872,\n\t\t\t\t\t2411255037952,\n\t\t\t\t\t3435817336832,\n\t\t\t\t\t1745433788416,\n\t\t\t\t\t1181205135360,\n\t\t\t\t\t1607402389504,\n\t\t\t\t\t1490967855104,\n\t\t\t\t\t4380756541440,\n\t\t\t\t\t14631844184064,\n\t\t\t\t],\n\t\t\t\t"happiness_index": [\n\t\t\t\t\t6.94,\n\t\t\t\t\t7.16,\n\t\t\t\t\t6.66,\n\t\t\t\t\t7.07,\n\t\t\t\t\t6.38,\n\t\t\t\t\t6.4,\n\t\t\t\t\t7.23,\n\t\t\t\t\t7.22,\n\t\t\t\t\t5.87,\n\t\t\t\t\t5.12,\n\t\t\t\t],\n\t\t\t}\n\t\t)\n\tchart_path = os.path.join("exports/charts")\n\twith st.form("Question"):\n\t\tquestion = st.text_input("Question", value="", type="default")\n\t\tsubmitted = st.form_submit_button("Submit")\n\t\tif submitted:\n\t\t\twith st.spinner():\n\t\t\t\tllm = OpenAI(api_token=st.session_state.openai_key)\n\t\t\t\tdf = SmartDataframe(\n\t\t\t\t\tst.session_state.df,\n\t\t\t\t\tconfig={\n\t\t\t\t\t\t"llm": llm,\n\t\t\t\t\t\t"save_charts_path": chart_path,\n\t\t\t\t\t\t"save_charts": True,\n\t\t\t\t\t\t"verbose": True,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\tresponse = df.chat(\n\t\t\t\t\tquestion\n\t\t\t\t)  # Using \'chat\' method based on your context\n\n\t\t\t\t# Display the textual response (if any):\n\t\t\t\tif response:\n\t\t\t\t\tst.write(response)\n\t\t\t\tchart_path = os.path.join("exports/charts", "temp_chart.png")\n\t\t\t\tif os.path.exists(chart_path):\n\t\t\t\t\tst.image(\n\t\t\t\t\t\tchart_path, caption="Generated Chart", use_column_width=True\n\t\t\t\t\t)\n\t\t\t\t# Append the question to the history:\n\t\t\t\tst.session_state.prompt_history.append(question)\n\n\tif st.session_state.df is not None:\n\t\tst.subheader("Current dataframe:")\n\t\tst.write(st.session_state.df)\n\n\tst.subheader("Prompt history:")\n\tst.write(st.session_state.prompt_history)\n\n\tif st.button("Clear"):\n\t\tst.session_state.prompt_history = []\n\t\tst.session_state.df = None\n"""\n    )\n', (94791, 97221), True, 'import streamlit as st\n'), ((97213, 97249), 'streamlit.markdown', 'st.markdown', (['"""**:red[Code Output]**"""'], {}), "('**:red[Code Output]**')\n", (97224, 97249), True, 'import streamlit as st\n'), ((1605, 1631), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (1616, 1631), True, 'import streamlit as st\n'), ((1635, 1672), 'streamlit.code', 'st.code', (['"""\n#challenge code here\n"""'], {}), '("""\n#challenge code here\n""")\n', (1642, 1672), True, 'import streamlit as st\n'), ((10955, 10980), 'streamlit.write', 'st.write', (["('Hello ' + name)"], {}), "('Hello ' + name)\n", (10963, 10980), True, 'import streamlit as st\n'), ((12507, 12592), 'streamlit.text', 'st.text', (['f"""Hello {name}, you are {gender} and this year you are {age} years old"""'], {}), "(f'Hello {name}, you are {gender} and this year you are {age} years old'\n    )\n", (12514, 12592), True, 'import streamlit as st\n'), ((13221, 13247), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (13232, 13247), True, 'import streamlit as st\n'), ((13251, 13587), 'streamlit.code', 'st.code', (['"""\ndef ch1():\n        name = st.text_input("Enter your name")\n        gender = st.selectbox("State your gender", ["Male", "Female"])\n        age = st.text_input("State your age", 18)\n\n        if name and gender and age:\n            st.text(f"Hello {name}, you are {gender} and this year you are {age} years old")\n"""'], {}), '(\n    """\ndef ch1():\n        name = st.text_input("Enter your name")\n        gender = st.selectbox("State your gender", ["Male", "Female"])\n        age = st.text_input("State your age", 18)\n\n        if name and gender and age:\n            st.text(f"Hello {name}, you are {gender} and this year you are {age} years old")\n"""\n    )\n', (13258, 13587), True, 'import streamlit as st\n'), ((13739, 13774), 'streamlit.text_input', 'st.text_input', (['"""State your age"""', '(18)'], {}), "('State your age', 18)\n", (13752, 13774), True, 'import streamlit as st\n'), ((13935, 13967), 'streamlit.write', 'st.write', (['"""You are a male adult"""'], {}), "('You are a male adult')\n", (13943, 13967), True, 'import streamlit as st\n'), ((14240, 14272), 'streamlit.write', 'st.write', (['"""Here is your photo: """'], {}), "('Here is your photo: ')\n", (14248, 14272), True, 'import streamlit as st\n'), ((14281, 14296), 'streamlit.image', 'st.image', (['photo'], {}), '(photo)\n', (14289, 14296), True, 'import streamlit as st\n'), ((14315, 14341), 'streamlit.write', 'st.write', (['"""No photo taken"""'], {}), "('No photo taken')\n", (14323, 14341), True, 'import streamlit as st\n'), ((15430, 15445), 'streamlit.write', 'st.write', (['fruit'], {}), '(fruit)\n', (15438, 15445), True, 'import streamlit as st\n'), ((18061, 18093), 'streamlit.write', 'st.write', (['"""session_data: """', 'data'], {}), "('session_data: ', data)\n", (18069, 18093), True, 'import streamlit as st\n'), ((19387, 19428), 'streamlit.write', 'st.write', (['"""name: """', 'st.session_state.name'], {}), "('name: ', st.session_state.name)\n", (19395, 19428), True, 'import streamlit as st\n'), ((19484, 19523), 'streamlit.write', 'st.write', (['"""age: """', 'st.session_state.age'], {}), "('age: ', st.session_state.age)\n", (19492, 19523), True, 'import streamlit as st\n'), ((19583, 19628), 'streamlit.write', 'st.write', (['"""gender: """', 'st.session_state.gender'], {}), "('gender: ', st.session_state.gender)\n", (19591, 19628), True, 'import streamlit as st\n'), ((22136, 22162), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (22147, 22162), True, 'import streamlit as st\n'), ((22166, 23451), 'streamlit.code', 'st.code', (['"""\ndef ch4():\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = "Yoda"\n\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = 999\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = "male"\n\n\tif "prompt_template" not in st.session_state:\n\t\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\n\tst.write("session_state.name: ", st.session_state.name)\n\tst.write("session_state.age: ", st.session_state.age)\n\tst.write("session_state.gender: ", st.session_state.gender)\n\tst.write("session_state.prompt_template: ", st.session_state.prompt_template)\n\ndef main():\n\t# initialize session state, from ch4\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = "Yoda"\n\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = 999\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = "male"\n\n\tif "prompt_template" not in st.session_state:\n\t\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t\t  \n\t#the rest of your code is below\n"""'], {}), '(\n    """\ndef ch4():\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = "Yoda"\n\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = 999\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = "male"\n\n\tif "prompt_template" not in st.session_state:\n\t\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\n\tst.write("session_state.name: ", st.session_state.name)\n\tst.write("session_state.age: ", st.session_state.age)\n\tst.write("session_state.gender: ", st.session_state.gender)\n\tst.write("session_state.prompt_template: ", st.session_state.prompt_template)\n\ndef main():\n\t# initialize session state, from ch4\n\tif "name" not in st.session_state:\n\t\tst.session_state.name = "Yoda"\n\n\tif "age" not in st.session_state:\n\t\tst.session_state.age = 999\n\n\tif "gender" not in st.session_state:\n\t\tst.session_state.gender = "male"\n\n\tif "prompt_template" not in st.session_state:\n\t\tst.session_state.prompt_template = "Speak like Yoda from Star Wars for every question that was asked, do not give a direct answer but ask more questions in the style of wise Yoda from Star Wars"\n\t\t  \n\t#the rest of your code is below\n"""\n    )\n', (22173, 23451), True, 'import streamlit as st\n'), ((23685, 23742), 'streamlit.write', 'st.write', (['f"""User has sent the following prompt: {prompt}"""'], {}), "(f'User has sent the following prompt: {prompt}')\n", (23693, 23742), True, 'import streamlit as st\n'), ((23745, 23786), 'streamlit.session_state.store_msg.append', 'st.session_state.store_msg.append', (['prompt'], {}), '(prompt)\n', (23778, 23786), True, 'import streamlit as st\n'), ((25229, 25257), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (25242, 25257), True, 'import streamlit as st\n'), ((25392, 25461), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (25424, 25461), True, 'import streamlit as st\n'), ((25658, 25734), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'assistant', 'content': response}"], {}), "({'role': 'assistant', 'content': response})\n", (25690, 25734), True, 'import streamlit as st\n'), ((27382, 27415), 'streamlit.chat_input', 'st.chat_input', (['"""Enter your query"""'], {}), "('Enter your query')\n", (27395, 27415), True, 'import streamlit as st\n'), ((28745, 28771), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (28756, 28771), True, 'import streamlit as st\n'), ((28775, 29813), 'streamlit.code', 'st.code', (['"""\n#Challenge 6 : Rule-based If-Else Chatbot\ndef ch6():\n\tst.markdown("**Rule Based Bot**")\n\n\t# Initialize chat history\n\tif "messages" not in st.session_state:\n\t\tst.session_state.messages = []\n\n\t# # Display chat messages from history on app rerun\n\tfor message in st.session_state.messages:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("Enter your query"):\n\t\tif prompt == "Hello":\n\t\t\treply = "Hi there what can I do for you"\n\n\t\telif prompt == "What is your name?":\n\t\t\treply = "My name is EAI , an electronic artificial being"\n\n\t\telif prompt == "How old are you?":\n\t\t\treply = "Today is my birthday!"\n\t\t\n\t\telse:\n\t\t\treply = "I am sorry, I am unable to help you with your query"\n\n\t\twith st.chat_message("user"):\n\t\t\tst.write(prompt)\n\t\t\tst.session_state.messages.append({"role": "user", "content": prompt})\n\t\twith st.chat_message("assistant"):\n\t\t\tst.write(reply)\n\t\t\tst.session_state.messages.append({"role": "assistant", "content": reply})\n"""'], {}), '(\n    """\n#Challenge 6 : Rule-based If-Else Chatbot\ndef ch6():\n\tst.markdown("**Rule Based Bot**")\n\n\t# Initialize chat history\n\tif "messages" not in st.session_state:\n\t\tst.session_state.messages = []\n\n\t# # Display chat messages from history on app rerun\n\tfor message in st.session_state.messages:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("Enter your query"):\n\t\tif prompt == "Hello":\n\t\t\treply = "Hi there what can I do for you"\n\n\t\telif prompt == "What is your name?":\n\t\t\treply = "My name is EAI , an electronic artificial being"\n\n\t\telif prompt == "How old are you?":\n\t\t\treply = "Today is my birthday!"\n\t\t\n\t\telse:\n\t\t\treply = "I am sorry, I am unable to help you with your query"\n\n\t\twith st.chat_message("user"):\n\t\t\tst.write(prompt)\n\t\t\tst.session_state.messages.append({"role": "user", "content": prompt})\n\t\twith st.chat_message("assistant"):\n\t\t\tst.write(reply)\n\t\t\tst.session_state.messages.append({"role": "assistant", "content": reply})\n"""\n    )\n', (28782, 29813), True, 'import streamlit as st\n'), ((34282, 34308), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (34293, 34308), True, 'import streamlit as st\n'), ((34312, 35567), 'streamlit.code', 'st.code', (['"""\t\n#Challenge 8: Incorporating the API into your chatbot\ndef chat_completion(prompt):\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant."},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature=0,\n\t)\n\treturn response["choices"][0]["message"]["content"].strip()\n\t\ndef ch8():\n\tst.title("My first LLM Chatbot")\n\n\t# Initialize chat history\n\tif "chat_msg" not in st.session_state:\n\t\tst.session_state.chat_msg = []\n\n\t# Display chat chat_msg from history on app rerun\n\tfor message in st.session_state.chat_msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("What\'s up?"):\n\t\t# Display user message in chat message container\n\t\treply = chat_completion(prompt)\n\t\tst.chat_message("user").markdown(prompt)\n\t\t# Add user message to chat history\n\t\tst.session_state.chat_msg.append({"role": "user", "content": prompt})\n\t\t# Display assistant response in chat message container\n\t\twith st.chat_message("assistant"):\n\t\t\tst.markdown(reply)\n\t\t# Add assistant response to chat history\n\t\tst.session_state.chat_msg.append({"role": "assistant", "content": reply})\n"""'], {}), '(\n    """\t\n#Challenge 8: Incorporating the API into your chatbot\ndef chat_completion(prompt):\n\tMODEL = "gpt-3.5-turbo"\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": "You are a helpful assistant."},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature=0,\n\t)\n\treturn response["choices"][0]["message"]["content"].strip()\n\t\ndef ch8():\n\tst.title("My first LLM Chatbot")\n\n\t# Initialize chat history\n\tif "chat_msg" not in st.session_state:\n\t\tst.session_state.chat_msg = []\n\n\t# Display chat chat_msg from history on app rerun\n\tfor message in st.session_state.chat_msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\n\t# React to user input\n\tif prompt := st.chat_input("What\'s up?"):\n\t\t# Display user message in chat message container\n\t\treply = chat_completion(prompt)\n\t\tst.chat_message("user").markdown(prompt)\n\t\t# Add user message to chat history\n\t\tst.session_state.chat_msg.append({"role": "user", "content": prompt})\n\t\t# Display assistant response in chat message container\n\t\twith st.chat_message("assistant"):\n\t\t\tst.markdown(reply)\n\t\t# Add assistant response to chat history\n\t\tst.session_state.chat_msg.append({"role": "assistant", "content": reply})\n"""\n    )\n', (34319, 35567), True, 'import streamlit as st\n'), ((35934, 35962), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (35947, 35962), True, 'import streamlit as st\n'), ((36131, 36200), 'streamlit.session_state.chat_msg.append', 'st.session_state.chat_msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (36163, 36200), True, 'import streamlit as st\n'), ((36362, 36435), 'streamlit.session_state.chat_msg.append', 'st.session_state.chat_msg.append', (["{'role': 'assistant', 'content': reply}"], {}), "({'role': 'assistant', 'content': reply})\n", (36394, 36435), True, 'import streamlit as st\n'), ((44324, 44350), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (44335, 44350), True, 'import streamlit as st\n'), ((44354, 45895), 'streamlit.code', 'st.code', (['"""\n#Challenge 10\n#mod chat complete stream function by replacing system content to session_state prompt template\ndef chat_completion_stream_prompt(prompt):\n\tMODEL = "gpt-3.5-turbo" #consider changing this to session_state\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": st.session_state.prompt_template},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature= 0, # temperature\n\t\tstream=True #stream option\n\t)\n\treturn response\n\n# Challenge 10: Make the bot speak like someone you know\ndef ch10_basebot():\n\t# call the function in your base bot\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t#set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t#streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""'], {}), '(\n    """\n#Challenge 10\n#mod chat complete stream function by replacing system content to session_state prompt template\ndef chat_completion_stream_prompt(prompt):\n\tMODEL = "gpt-3.5-turbo" #consider changing this to session_state\n\tresponse = openai.ChatCompletion.create(\n\t\tmodel=MODEL,\n\t\tmessages=[\n\t\t\t{"role": "system", "content": st.session_state.prompt_template},\n\t\t\t{"role": "user", "content": prompt},\n\t\t],\n\t\ttemperature= 0, # temperature\n\t\tstream=True #stream option\n\t)\n\treturn response\n\n# Challenge 10: Make the bot speak like someone you know\ndef ch10_basebot():\n\t# call the function in your base bot\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t#set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t#streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""\n    )\n', (44361, 45895), True, 'import streamlit as st\n'), ((46626, 46666), 'streamlit.write', 'st.write', (['"""Input prompt: """', 'input_prompt'], {}), "('Input prompt: ', input_prompt)\n", (46634, 46666), True, 'import streamlit as st\n'), ((48045, 48071), 'streamlit.form', 'st.form', (['"""Prompt Template"""'], {}), "('Prompt Template')\n", (48052, 48071), True, 'import streamlit as st\n'), ((48088, 48126), 'streamlit.text_input', 'st.text_input', (['"""Enter the occupation:"""'], {}), "('Enter the occupation:')\n", (48101, 48126), True, 'import streamlit as st\n'), ((48137, 48170), 'streamlit.text_input', 'st.text_input', (['"""Enter the topic:"""'], {}), "('Enter the topic:')\n", (48150, 48170), True, 'import streamlit as st\n'), ((48179, 48210), 'streamlit.text_input', 'st.text_input', (['"""Enter the age:"""'], {}), "('Enter the age:')\n", (48192, 48210), True, 'import streamlit as st\n'), ((48267, 48298), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Submit"""'], {}), "('Submit')\n", (48288, 48298), True, 'import streamlit as st\n'), ((51721, 51782), 'streamlit.write', 'st.write', (['"""New session_state.prompt_template: """', 'input_prompt'], {}), "('New session_state.prompt_template: ', input_prompt)\n", (51729, 51782), True, 'import streamlit as st\n'), ((52639, 52665), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (52650, 52665), True, 'import streamlit as st\n'), ((52669, 53613), 'streamlit.code', 'st.code', (['"""\ndef ch11():\n\t# instead of running of the langchain, we are going to use the prompt template and run it the chatbot using format\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\t# set session_state.prompt_template\n\t\tst.session_state.prompt_template = input_prompt\n\t\tst.write("New session_state.prompt_template: ", input_prompt)\n\t# call the ch10() basebot with the new session_state.prompt_template\n\tch10()\n"""'], {}), '(\n    """\ndef ch11():\n\t# instead of running of the langchain, we are going to use the prompt template and run it the chatbot using format\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information to the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\t# set session_state.prompt_template\n\t\tst.session_state.prompt_template = input_prompt\n\t\tst.write("New session_state.prompt_template: ", input_prompt)\n\t# call the ch10() basebot with the new session_state.prompt_template\n\tch10()\n"""\n    )\n', (52676, 53613), True, 'import streamlit as st\n'), ((55833, 55868), 'langchain.memory.ConversationBufferWindowMemory', 'ConversationBufferWindowMemory', ([], {'k': '(3)'}), '(k=3)\n', (55863, 55868), False, 'from langchain.memory import ConversationBufferWindowMemory\n'), ((58563, 58589), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (58574, 58589), True, 'import streamlit as st\n'), ((58593, 60969), 'streamlit.code', 'st.code', (['"""\ndef ch12():\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\telse:\n\t\tinput_prompt = "You are a helpful assistant. "\n\n\tst.write("input prompt: ", input_prompt)\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=3)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write("Memory Data: ", memory_data)\n\tst.session_state.prompt_template = f""\\"\n{input_prompt}\t\t\t\t\t\t\t\t\t\t\n\nBelow is the conversation history between the AI and Users so far\n\t\t\t\t\t\t\t\t\t\t\n{memory_data}\n\n""\\"\n\n\tst.write("New prompt template: ", st.session_state.prompt_template)\n\t# call the function in your base bot\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\texcept Exception as e:\n\t\tst.error(e)\n"""'], {}), '(\n    """\ndef ch12():\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\telse:\n\t\tinput_prompt = "You are a helpful assistant. "\n\n\tst.write("input prompt: ", input_prompt)\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=3)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write("Memory Data: ", memory_data)\n\tst.session_state.prompt_template = f""\\"\n{input_prompt}\t\t\t\t\t\t\t\t\t\t\n\nBelow is the conversation history between the AI and Users so far\n\t\t\t\t\t\t\t\t\t\t\n{memory_data}\n\n""\\"\n\n\tst.write("New prompt template: ", st.session_state.prompt_template)\n\t# call the function in your base bot\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\texcept Exception as e:\n\t\tst.error(e)\n"""\n    )\n', (58600, 60969), True, 'import streamlit as st\n'), ((62423, 62450), 'langchain.document_loaders.PyPDFLoader', 'PyPDFLoader', (['temp_file_path'], {}), '(temp_file_path)\n', (62434, 62450), False, 'from langchain.document_loaders import TextLoader, PyPDFLoader\n'), ((62496, 62559), 'langchain.vectorstores.LanceDB.from_documents', 'LanceDB.from_documents', (['documents', 'embeddings'], {'connection': 'table'}), '(documents, embeddings, connection=table)\n', (62518, 62559), False, 'from langchain.vectorstores import LanceDB\n'), ((62794, 62824), 'streamlit.text_input', 'st.text_input', (['"""Enter a query"""'], {}), "('Enter a query')\n", (62807, 62824), True, 'import streamlit as st\n'), ((66392, 66427), 'langchain.memory.ConversationBufferWindowMemory', 'ConversationBufferWindowMemory', ([], {'k': '(5)'}), '(k=5)\n', (66422, 66427), False, 'from langchain.memory import ConversationBufferWindowMemory\n'), ((76607, 76642), 'langchain.memory.ConversationBufferWindowMemory', 'ConversationBufferWindowMemory', ([], {'k': '(5)'}), '(k=5)\n', (76637, 76642), False, 'from langchain.memory import ConversationBufferWindowMemory\n'), ((79130, 79156), 'streamlit.expander', 'st.expander', (['"""Reveal Code"""'], {}), "('Reveal Code')\n", (79141, 79156), True, 'import streamlit as st\n'), ((79160, 82280), 'streamlit.code', 'st.code', (['"""\ndef ch15_chatbot():\n\t#display ex15 table\n\tex15()\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\tst.session_state.input_prompt = input_prompt\n\n\tif "input_prompt" not in st.session_state:\n\t\tst.session_state.input_prompt = "Speak like Yoda from Star Wars"\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"{st.session_state.input_prompt}\n\t\t\t\t\t\t\t\t\t\tThis is the last conversation history\n\t\t\t\t\t\t\t\t\t\t{memory_data}\n\t\t\t\t\t\t\t\t\t\t""\\"\n\tst.write("new prompt template: ", st.session_state.prompt_template)\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# query information\n\t\t\tif st.session_state.vectorstore:\n\t\t\t\tdocs = st.session_state.vectorstore.similarity_search(prompt)\n\t\t\t\tdocs = docs[0].page_content\n\t\t\t\t# add your query prompt\n\t\t\t\tvs_prompt = f""\\"You should reference this search result to help your answer,\n\t\t\t\t\t\t\t\t{docs}\n\t\t\t\t\t\t\t\tif the search result does not anwer the query, please say you are unable to answer, do not make up an answer""\\"\n\t\t\telse:\n\t\t\t\tvs_prompt = ""\n\t\t\t# add query prompt to your memory prompt and send it to LLM\n\t\t\tst.session_state.prompt_template = (\n\t\t\t\tst.session_state.prompt_template + vs_prompt\n\t\t\t)\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\n\t\t\tex15_collect(st.session_state.name, full_response, prompt)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""'], {}), '(\n    """\ndef ch15_chatbot():\n\t#display ex15 table\n\tex15()\n\t# Prompt_template form from ex11\n\tprompt_template = PromptTemplate(\n\t\tinput_variables=["occupation", "topic", "age"],\n\t\ttemplate=""\\"Imagine you are a {occupation} who is an expert on the  topic of {topic} , you are going to help , teach and provide information\n\t\t\t\t\t\tto the person who is {age} years old, if you do not not know the answer, you must tell the person , do not make any answer up""\\",\n\t)\n\tdict_inputs = prompt_inputs_form()\n\tif dict_inputs:\n\t\tinput_prompt = prompt_template.format(\n\t\t\toccupation=dict_inputs["occupation"],\n\t\t\ttopic=dict_inputs["topic"],\n\t\t\tage=dict_inputs["age"],\n\t\t)\n\t\tst.session_state.input_prompt = input_prompt\n\n\tif "input_prompt" not in st.session_state:\n\t\tst.session_state.input_prompt = "Speak like Yoda from Star Wars"\n\n\tif "memory" not in st.session_state:\n\t\tst.session_state.memory = ConversationBufferWindowMemory(k=5)\n\n\t# step 1 save the memory from your chatbot\n\t# step 2 integrate the memory in the prompt_template (st.session_state.prompt_template) show a hint\n\tmemory_data = st.session_state.memory.load_memory_variables({})\n\tst.write(memory_data)\n\tst.session_state.prompt_template = f""\\"{st.session_state.input_prompt}\n\t\t\t\t\t\t\t\t\t\tThis is the last conversation history\n\t\t\t\t\t\t\t\t\t\t{memory_data}\n\t\t\t\t\t\t\t\t\t\t""\\"\n\tst.write("new prompt template: ", st.session_state.prompt_template)\n\n\tst.session_state.vectorstore = vectorstore_creator()\n\n\t# Initialize chat history\n\tif "msg" not in st.session_state:\n\t\tst.session_state.msg = []\n\n\t# Showing Chat history\n\tfor message in st.session_state.msg:\n\t\twith st.chat_message(message["role"]):\n\t\t\tst.markdown(message["content"])\n\ttry:\n\t\t#\n\t\tif prompt := st.chat_input("What is up?"):\n\t\t\t# query information\n\t\t\tif st.session_state.vectorstore:\n\t\t\t\tdocs = st.session_state.vectorstore.similarity_search(prompt)\n\t\t\t\tdocs = docs[0].page_content\n\t\t\t\t# add your query prompt\n\t\t\t\tvs_prompt = f""\\"You should reference this search result to help your answer,\n\t\t\t\t\t\t\t\t{docs}\n\t\t\t\t\t\t\t\tif the search result does not anwer the query, please say you are unable to answer, do not make up an answer""\\"\n\t\t\telse:\n\t\t\t\tvs_prompt = ""\n\t\t\t# add query prompt to your memory prompt and send it to LLM\n\t\t\tst.session_state.prompt_template = (\n\t\t\t\tst.session_state.prompt_template + vs_prompt\n\t\t\t)\n\t\t\t# set user prompt in chat history\n\t\t\tst.session_state.msg.append({"role": "user", "content": prompt})\n\t\t\twith st.chat_message("user"):\n\t\t\t\tst.markdown(prompt)\n\n\t\t\twith st.chat_message("assistant"):\n\t\t\t\tmessage_placeholder = st.empty()\n\t\t\t\tfull_response = ""\n\t\t\t\t# streaming function\n\t\t\t\tfor response in chat_completion_stream_prompt(prompt):\n\t\t\t\t\tfull_response += response.choices[0].delta.get("content", "")\n\t\t\t\t\tmessage_placeholder.markdown(full_response + "▌")\n\t\t\t\tmessage_placeholder.markdown(full_response)\n\t\t\tst.session_state.msg.append({"role": "assistant", "content": full_response})\n\t\t\tst.session_state.memory.save_context(\n\t\t\t\t{"input": prompt}, {"output": full_response}\n\t\t\t)\n\n\t\t\tex15_collect(st.session_state.name, full_response, prompt)\n\n\texcept Exception as e:\n\t\tst.error(e)\n"""\n    )\n', (79167, 82280), True, 'import streamlit as st\n'), ((82756, 82795), 'streamlit.sidebar.button', 'st.sidebar.button', (['"""Reset chat history"""'], {}), "('Reset chat history')\n", (82773, 82795), True, 'import streamlit as st\n'), ((83363, 83421), 'streamlit.chat_input', 'st.chat_input', ([], {'placeholder': '"""Enter a query on the Internet"""'}), "(placeholder='Enter a query on the Internet')\n", (83376, 83421), True, 'import streamlit as st\n'), ((83472, 83561), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'openai_api_key': 'openai.api_key', 'streaming': '(True)'}), "(model_name='gpt-3.5-turbo', openai_api_key=openai.api_key,\n    streaming=True)\n", (83482, 83561), False, 'from langchain.chat_models import ChatOpenAI\n'), ((83627, 83691), 'langchain.agents.ConversationalChatAgent.from_llm_and_tools', 'ConversationalChatAgent.from_llm_and_tools', ([], {'llm': 'llm', 'tools': 'tools'}), '(llm=llm, tools=tools)\n', (83669, 83691), False, 'from langchain.agents import ConversationalChatAgent, AgentExecutor\n'), ((83705, 83850), 'langchain.agents.AgentExecutor.from_agent_and_tools', 'AgentExecutor.from_agent_and_tools', ([], {'agent': 'chat_agent', 'tools': 'tools', 'memory': 'memory', 'return_intermediate_steps': '(True)', 'handle_parsing_errors': '(True)'}), '(agent=chat_agent, tools=tools, memory=\n    memory, return_intermediate_steps=True, handle_parsing_errors=True)\n', (83739, 83850), False, 'from langchain.agents import ConversationalChatAgent, AgentExecutor\n'), ((87508, 87547), 'streamlit.sidebar.button', 'st.sidebar.button', (['"""Reset chat history"""'], {}), "('Reset chat history')\n", (87525, 87547), True, 'import streamlit as st\n'), ((88115, 88173), 'streamlit.chat_input', 'st.chat_input', ([], {'placeholder': '"""Enter a query on the Internet"""'}), "(placeholder='Enter a query on the Internet')\n", (88128, 88173), True, 'import streamlit as st\n'), ((88224, 88313), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model_name': '"""gpt-3.5-turbo"""', 'openai_api_key': 'openai.api_key', 'streaming': '(True)'}), "(model_name='gpt-3.5-turbo', openai_api_key=openai.api_key,\n    streaming=True)\n", (88234, 88313), False, 'from langchain.chat_models import ChatOpenAI\n'), ((88405, 88469), 'langchain.agents.ConversationalChatAgent.from_llm_and_tools', 'ConversationalChatAgent.from_llm_and_tools', ([], {'llm': 'llm', 'tools': 'tools'}), '(llm=llm, tools=tools)\n', (88447, 88469), False, 'from langchain.agents import ConversationalChatAgent, AgentExecutor\n'), ((88483, 88628), 'langchain.agents.AgentExecutor.from_agent_and_tools', 'AgentExecutor.from_agent_and_tools', ([], {'agent': 'chat_agent', 'tools': 'tools', 'memory': 'memory', 'return_intermediate_steps': '(True)', 'handle_parsing_errors': '(True)'}), '(agent=chat_agent, tools=tools, memory=\n    memory, return_intermediate_steps=True, handle_parsing_errors=True)\n', (88517, 88628), False, 'from langchain.agents import ConversationalChatAgent, AgentExecutor\n'), ((92550, 92956), 'pandas.DataFrame', 'pd.DataFrame', (["{'country': ['United States', 'United Kingdom', 'France', 'Germany',\n    'Italy', 'Spain', 'Canada', 'Australia', 'Japan', 'China'], 'gdp': [\n    19294482071552, 2891615567872, 2411255037952, 3435817336832, \n    1745433788416, 1181205135360, 1607402389504, 1490967855104, \n    4380756541440, 14631844184064], 'happiness_index': [6.94, 7.16, 6.66, \n    7.07, 6.38, 6.4, 7.23, 7.22, 5.87, 5.12]}"], {}), "({'country': ['United States', 'United Kingdom', 'France',\n    'Germany', 'Italy', 'Spain', 'Canada', 'Australia', 'Japan', 'China'],\n    'gdp': [19294482071552, 2891615567872, 2411255037952, 3435817336832, \n    1745433788416, 1181205135360, 1607402389504, 1490967855104, \n    4380756541440, 14631844184064], 'happiness_index': [6.94, 7.16, 6.66, \n    7.07, 6.38, 6.4, 7.23, 7.22, 5.87, 5.12]})\n", (92562, 92956), True, 'import pandas as pd\n'), ((93181, 93200), 'streamlit.form', 'st.form', (['"""Question"""'], {}), "('Question')\n", (93188, 93200), True, 'import streamlit as st\n'), ((93215, 93266), 'streamlit.text_input', 'st.text_input', (['"""Question"""'], {'value': '""""""', 'type': '"""default"""'}), "('Question', value='', type='default')\n", (93228, 93266), True, 'import streamlit as st\n'), ((93281, 93312), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Submit"""'], {}), "('Submit')\n", (93302, 93312), True, 'import streamlit as st\n'), ((94093, 94127), 'streamlit.subheader', 'st.subheader', (['"""Current dataframe:"""'], {}), "('Current dataframe:')\n", (94105, 94127), True, 'import streamlit as st\n'), ((94130, 94159), 'streamlit.write', 'st.write', (['st.session_state.df'], {}), '(st.session_state.df)\n', (94138, 94159), True, 'import streamlit as st\n'), ((8292, 8324), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (8307, 8324), True, 'import streamlit as st\n'), ((8329, 8360), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (8340, 8360), True, 'import streamlit as st\n'), ((8385, 8413), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (8398, 8413), True, 'import streamlit as st\n'), ((8418, 8486), 'streamlit.session_state.msg_bot.append', 'st.session_state.msg_bot.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (8449, 8486), True, 'import streamlit as st\n'), ((9063, 9148), 'streamlit.session_state.msg_bot.append', 'st.session_state.msg_bot.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content': full_response}\n    )\n", (9094, 9148), True, 'import streamlit as st\n'), ((9171, 9182), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (9179, 9182), True, 'import streamlit as st\n'), ((14016, 14047), 'streamlit.write', 'st.write', (['"""You are a young boy"""'], {}), "('You are a young boy')\n", (14024, 14047), True, 'import streamlit as st\n'), ((25122, 25154), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (25137, 25154), True, 'import streamlit as st\n'), ((25159, 25190), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (25170, 25190), True, 'import streamlit as st\n'), ((25558, 25586), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (25573, 25586), True, 'import streamlit as st\n'), ((25591, 25612), 'streamlit.markdown', 'st.markdown', (['response'], {}), '(response)\n', (25602, 25612), True, 'import streamlit as st\n'), ((27275, 27307), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (27290, 27307), True, 'import streamlit as st\n'), ((27312, 27343), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (27323, 27343), True, 'import streamlit as st\n'), ((27743, 27766), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (27758, 27766), True, 'import streamlit as st\n'), ((27771, 27787), 'streamlit.write', 'st.write', (['prompt'], {}), '(prompt)\n', (27779, 27787), True, 'import streamlit as st\n'), ((27791, 27860), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (27823, 27860), True, 'import streamlit as st\n'), ((27868, 27896), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (27883, 27896), True, 'import streamlit as st\n'), ((27901, 27916), 'streamlit.write', 'st.write', (['reply'], {}), '(reply)\n', (27909, 27916), True, 'import streamlit as st\n'), ((27920, 27993), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'assistant', 'content': reply}"], {}), "({'role': 'assistant', 'content': reply})\n", (27952, 27993), True, 'import streamlit as st\n'), ((35827, 35859), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (35842, 35859), True, 'import streamlit as st\n'), ((35864, 35895), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (35875, 35895), True, 'import streamlit as st\n'), ((36265, 36293), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (36280, 36293), True, 'import streamlit as st\n'), ((36298, 36316), 'streamlit.markdown', 'st.markdown', (['reply'], {}), '(reply)\n', (36309, 36316), True, 'import streamlit as st\n'), ((36957, 36989), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (36972, 36989), True, 'import streamlit as st\n'), ((36994, 37025), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (37005, 37025), True, 'import streamlit as st\n'), ((37051, 37079), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (37064, 37079), True, 'import streamlit as st\n'), ((37121, 37190), 'streamlit.session_state.chat_msg.append', 'st.session_state.chat_msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (37153, 37190), True, 'import streamlit as st\n'), ((37597, 37682), 'streamlit.session_state.chat_msg.append', 'st.session_state.chat_msg.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content':\n    full_response})\n", (37629, 37682), True, 'import streamlit as st\n'), ((37714, 37725), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (37722, 37725), True, 'import streamlit as st\n'), ((42505, 42537), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (42520, 42537), True, 'import streamlit as st\n'), ((42542, 42573), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (42553, 42573), True, 'import streamlit as st\n'), ((42599, 42627), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (42612, 42627), True, 'import streamlit as st\n'), ((42668, 42732), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (42695, 42732), True, 'import streamlit as st\n'), ((43145, 43221), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content': full_response})\n", (43172, 43221), True, 'import streamlit as st\n'), ((43249, 43260), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (43257, 43260), True, 'import streamlit as st\n'), ((56549, 56581), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (56564, 56581), True, 'import streamlit as st\n'), ((56586, 56617), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (56597, 56617), True, 'import streamlit as st\n'), ((56643, 56671), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (56656, 56671), True, 'import streamlit as st\n'), ((56713, 56777), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (56740, 56777), True, 'import streamlit as st\n'), ((57191, 57267), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content': full_response})\n", (57218, 57267), True, 'import streamlit as st\n'), ((57271, 57357), 'streamlit.session_state.memory.save_context', 'st.session_state.memory.save_context', (["{'input': prompt}", "{'output': full_response}"], {}), "({'input': prompt}, {'output':\n    full_response})\n", (57307, 57357), True, 'import streamlit as st\n'), ((57389, 57400), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (57397, 57400), True, 'import streamlit as st\n'), ((61119, 61146), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (61135, 61146), False, 'import os\n'), ((61571, 61632), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)', 'suffix': 'file_suffix'}), '(delete=False, suffix=file_suffix)\n', (61598, 61632), False, 'import tempfile\n'), ((62915, 62945), 'streamlit.write', 'st.write', (['docs[0].page_content'], {}), '(docs[0].page_content)\n', (62923, 62945), True, 'import streamlit as st\n'), ((67109, 67141), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (67124, 67141), True, 'import streamlit as st\n'), ((67146, 67177), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (67157, 67177), True, 'import streamlit as st\n'), ((67203, 67231), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (67216, 67231), True, 'import streamlit as st\n'), ((67859, 67923), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (67886, 67923), True, 'import streamlit as st\n'), ((68337, 68413), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content': full_response})\n", (68364, 68413), True, 'import streamlit as st\n'), ((68417, 68503), 'streamlit.session_state.memory.save_context', 'st.session_state.memory.save_context', (["{'input': prompt}", "{'output': full_response}"], {}), "({'input': prompt}, {'output':\n    full_response})\n", (68453, 68503), True, 'import streamlit as st\n'), ((68536, 68547), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (68544, 68547), True, 'import streamlit as st\n'), ((77320, 77352), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (77335, 77352), True, 'import streamlit as st\n'), ((77357, 77388), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (77368, 77388), True, 'import streamlit as st\n'), ((77414, 77442), 'streamlit.chat_input', 'st.chat_input', (['"""What is up?"""'], {}), "('What is up?')\n", (77427, 77442), True, 'import streamlit as st\n'), ((78070, 78134), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'user', 'content': prompt}"], {}), "({'role': 'user', 'content': prompt})\n", (78097, 78134), True, 'import streamlit as st\n'), ((78548, 78624), 'streamlit.session_state.msg.append', 'st.session_state.msg.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content': full_response})\n", (78575, 78624), True, 'import streamlit as st\n'), ((78628, 78714), 'streamlit.session_state.memory.save_context', 'st.session_state.memory.save_context', (["{'input': prompt}", "{'output': full_response}"], {}), "({'input': prompt}, {'output':\n    full_response})\n", (78664, 78714), True, 'import streamlit as st\n'), ((78810, 78821), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (78818, 78821), True, 'import streamlit as st\n'), ((82986, 83020), 'streamlit.chat_message', 'st.chat_message', (['avatars[msg.type]'], {}), '(avatars[msg.type])\n', (83001, 83020), True, 'import streamlit as st\n'), ((83326, 83347), 'streamlit.write', 'st.write', (['msg.content'], {}), '(msg.content)\n', (83334, 83347), True, 'import streamlit as st\n'), ((83576, 83610), 'langchain.tools.DuckDuckGoSearchRun', 'DuckDuckGoSearchRun', ([], {'name': '"""Search"""'}), "(name='Search')\n", (83595, 83610), False, 'from langchain.tools import DuckDuckGoSearchRun\n'), ((83873, 83901), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (83888, 83901), True, 'import streamlit as st\n'), ((84035, 84063), 'streamlit.write', 'st.write', (["response['output']"], {}), "(response['output'])\n", (84043, 84063), True, 'import streamlit as st\n'), ((87738, 87772), 'streamlit.chat_message', 'st.chat_message', (['avatars[msg.type]'], {}), '(avatars[msg.type])\n', (87753, 87772), True, 'import streamlit as st\n'), ((88078, 88099), 'streamlit.write', 'st.write', (['msg.content'], {}), '(msg.content)\n', (88086, 88099), True, 'import streamlit as st\n'), ((88345, 88388), 'langchain.tools.DuckDuckGoSearchRun', 'DuckDuckGoSearchRun', ([], {'name': '"""Internet Search"""'}), "(name='Internet Search')\n", (88364, 88388), False, 'from langchain.tools import DuckDuckGoSearchRun\n'), ((88651, 88679), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (88666, 88679), True, 'import streamlit as st\n'), ((88813, 88841), 'streamlit.write', 'st.write', (["response['output']"], {}), "(response['output'])\n", (88821, 88841), True, 'import streamlit as st\n'), ((92364, 92390), 'pandas.read_csv', 'pd.read_csv', (['uploaded_file'], {}), '(uploaded_file)\n', (92375, 92390), True, 'import pandas as pd\n'), ((8495, 8518), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (8510, 8518), True, 'import streamlit as st\n'), ((8524, 8543), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (8535, 8543), True, 'import streamlit as st\n'), ((8553, 8581), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (8568, 8581), True, 'import streamlit as st\n'), ((8609, 8619), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (8617, 8619), True, 'import streamlit as st\n'), ((8663, 8848), 'openai.ChatCompletion.create', 'openai.ChatCompletion.create', ([], {'model': "st.session_state['openai_model']", 'messages': "[{'role': 'system', 'content': prompt_template}, {'role': 'user', 'content':\n    prompt}]", 'stream': '(True)'}), "(model=st.session_state['openai_model'],\n    messages=[{'role': 'system', 'content': prompt_template}, {'role':\n    'user', 'content': prompt}], stream=True)\n", (8691, 8848), False, 'import openai\n'), ((14099, 14133), 'streamlit.write', 'st.write', (['"""You are a female adult"""'], {}), "('You are a female adult')\n", (14107, 14133), True, 'import streamlit as st\n'), ((23840, 23863), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (23855, 23863), True, 'import streamlit as st\n'), ((23869, 23886), 'streamlit.write', 'st.write', (['message'], {}), '(message)\n', (23877, 23886), True, 'import streamlit as st\n'), ((23895, 23923), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (23910, 23923), True, 'import streamlit as st\n'), ((23929, 23976), 'streamlit.write', 'st.write', (['"""Hello human, what can I do for you?"""'], {}), "('Hello human, what can I do for you?')\n", (23937, 23976), True, 'import streamlit as st\n'), ((25312, 25335), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (25327, 25335), True, 'import streamlit as st\n'), ((36051, 36074), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (36066, 36074), True, 'import streamlit as st\n'), ((37199, 37222), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (37214, 37222), True, 'import streamlit as st\n'), ((37228, 37247), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (37239, 37247), True, 'import streamlit as st\n'), ((37257, 37285), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (37272, 37285), True, 'import streamlit as st\n'), ((37313, 37323), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (37321, 37323), True, 'import streamlit as st\n'), ((42741, 42764), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (42756, 42764), True, 'import streamlit as st\n'), ((42770, 42789), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (42781, 42789), True, 'import streamlit as st\n'), ((42799, 42827), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (42814, 42827), True, 'import streamlit as st\n'), ((42855, 42865), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (42863, 42865), True, 'import streamlit as st\n'), ((56786, 56809), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (56801, 56809), True, 'import streamlit as st\n'), ((56815, 56834), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (56826, 56834), True, 'import streamlit as st\n'), ((56844, 56872), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (56859, 56872), True, 'import streamlit as st\n'), ((56900, 56910), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (56908, 56910), True, 'import streamlit as st\n'), ((67303, 67357), 'streamlit.session_state.vectorstore.similarity_search', 'st.session_state.vectorstore.similarity_search', (['prompt'], {}), '(prompt)\n', (67349, 67357), True, 'import streamlit as st\n'), ((67932, 67955), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (67947, 67955), True, 'import streamlit as st\n'), ((67961, 67980), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (67972, 67980), True, 'import streamlit as st\n'), ((67990, 68018), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (68005, 68018), True, 'import streamlit as st\n'), ((68046, 68056), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (68054, 68056), True, 'import streamlit as st\n'), ((77514, 77568), 'streamlit.session_state.vectorstore.similarity_search', 'st.session_state.vectorstore.similarity_search', (['prompt'], {}), '(prompt)\n', (77560, 77568), True, 'import streamlit as st\n'), ((78143, 78166), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (78158, 78166), True, 'import streamlit as st\n'), ((78172, 78191), 'streamlit.markdown', 'st.markdown', (['prompt'], {}), '(prompt)\n', (78183, 78191), True, 'import streamlit as st\n'), ((78201, 78229), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (78216, 78229), True, 'import streamlit as st\n'), ((78257, 78267), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (78265, 78267), True, 'import streamlit as st\n'), ((83425, 83448), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (83440, 83448), True, 'import streamlit as st\n'), ((83939, 83953), 'streamlit.container', 'st.container', ([], {}), '()\n', (83951, 83953), True, 'import streamlit as st\n'), ((88177, 88200), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (88192, 88200), True, 'import streamlit as st\n'), ((88717, 88731), 'streamlit.container', 'st.container', ([], {}), '()\n', (88729, 88731), True, 'import streamlit as st\n'), ((92447, 92502), 'streamlit.write', 'st.write', (['"""There was an error processing the CSV file."""'], {}), "('There was an error processing the CSV file.')\n", (92455, 92502), True, 'import streamlit as st\n'), ((92506, 92517), 'streamlit.write', 'st.write', (['e'], {}), '(e)\n', (92514, 92517), True, 'import streamlit as st\n'), ((93337, 93349), 'streamlit.spinner', 'st.spinner', ([], {}), '()\n', (93347, 93349), True, 'import streamlit as st\n'), ((93361, 93406), 'pandasai.llm.openai.OpenAI', 'OpenAI', ([], {'api_token': 'st.session_state.openai_key'}), '(api_token=st.session_state.openai_key)\n', (93367, 93406), False, 'from pandasai.llm.openai import OpenAI\n'), ((93416, 93546), 'pandasai.SmartDataframe', 'SmartDataframe', (['st.session_state.df'], {'config': "{'llm': llm, 'save_charts_path': chart_path, 'save_charts': True, 'verbose':\n    True}"}), "(st.session_state.df, config={'llm': llm, 'save_charts_path':\n    chart_path, 'save_charts': True, 'verbose': True})\n", (93430, 93546), False, 'from pandasai import SmartDataframe\n'), ((93785, 93833), 'os.path.join', 'os.path.join', (['"""exports/charts"""', '"""temp_chart.png"""'], {}), "('exports/charts', 'temp_chart.png')\n", (93797, 93833), False, 'import os\n'), ((93841, 93867), 'os.path.exists', 'os.path.exists', (['chart_path'], {}), '(chart_path)\n', (93855, 93867), False, 'import os\n'), ((94004, 94052), 'streamlit.session_state.prompt_history.append', 'st.session_state.prompt_history.append', (['question'], {}), '(question)\n', (94042, 94052), True, 'import streamlit as st\n'), ((14184, 14216), 'streamlit.write', 'st.write', (['"""You are a young girl"""'], {}), "('You are a young girl')\n", (14192, 14216), True, 'import streamlit as st\n'), ((83188, 83260), 'streamlit.status', 'st.status', (['f"""**{step[0].tool}**: {step[0].tool_input}"""'], {'state': '"""complete"""'}), "(f'**{step[0].tool}**: {step[0].tool_input}', state='complete')\n", (83197, 83260), True, 'import streamlit as st\n'), ((83278, 83299), 'streamlit.write', 'st.write', (['step[0].log'], {}), '(step[0].log)\n', (83286, 83299), True, 'import streamlit as st\n'), ((83305, 83322), 'streamlit.write', 'st.write', (['step[1]'], {}), '(step[1])\n', (83313, 83322), True, 'import streamlit as st\n'), ((87940, 88012), 'streamlit.status', 'st.status', (['f"""**{step[0].tool}**: {step[0].tool_input}"""'], {'state': '"""complete"""'}), "(f'**{step[0].tool}**: {step[0].tool_input}', state='complete')\n", (87949, 88012), True, 'import streamlit as st\n'), ((88030, 88051), 'streamlit.write', 'st.write', (['step[0].log'], {}), '(step[0].log)\n', (88038, 88051), True, 'import streamlit as st\n'), ((88057, 88074), 'streamlit.write', 'st.write', (['step[1]'], {}), '(step[1])\n', (88065, 88074), True, 'import streamlit as st\n'), ((93749, 93767), 'streamlit.write', 'st.write', (['response'], {}), '(response)\n', (93757, 93767), True, 'import streamlit as st\n'), ((93874, 93944), 'streamlit.image', 'st.image', (['chart_path'], {'caption': '"""Generated Chart"""', 'use_column_width': '(True)'}), "(chart_path, caption='Generated Chart', use_column_width=True)\n", (93882, 93944), True, 'import streamlit as st\n')]