ofermend commited on
Commit
76eb72e
1 Parent(s): ae6a3d9

Upload 4 files

Browse files
Files changed (3) hide show
  1. app.py +34 -17
  2. prompts.py +77 -0
  3. requirements.txt +1 -1
app.py CHANGED
@@ -12,37 +12,54 @@ from llama_index.core.agent import ReActAgent
12
  from llama_index.llms.openai import OpenAI
13
  from llama_index.core.tools import QueryEngineTool, ToolMetadata
14
  from llama_index.core.utils import print_text
 
15
 
16
- learning_styles = ['traditional', 'Inquiry-based']
 
 
17
  languages = {'English': 'en', 'Spanish': 'es', 'French': 'fr', 'German': 'de', 'Arabic': 'ar', 'Chinese': 'zh-cn',
18
  'Hebrew': 'he', 'Hindi': 'hi', 'Italian': 'it', 'Japanese': 'ja', 'Korean': 'ko', 'Portuguese': 'pt'}
19
  initial_prompt = "How can I help you today?"
20
 
 
21
  def launch_bot():
22
  def reset():
23
  cfg = st.session_state.cfg
24
  llm = OpenAI(model="gpt-4o", temperature=0)
25
  tr_prompt = Translator(to_lang=languages[cfg.language]).translate(initial_prompt)
26
  st.session_state.messages = [{"role": "assistant", "content": tr_prompt, "avatar": "🦖"}]
 
27
  vectara = VectaraIndex(vectara_api_key=cfg.api_key,
28
  vectara_customer_id=cfg.customer_id,
29
  vectara_corpus_id=cfg.corpus_id)
 
 
30
  vectara_tool = QueryEngineTool(
31
- query_engine = vectara.as_query_engine(summary_enabled=True, summary_num_results=5, summary_response_lang = languages[cfg.language],
32
- summary_prompt_name="vectara-summary-ext-24-05-large"),
33
- metadata = ToolMetadata(name="Vectara",
34
- description="Vectara Query Engine that is able to answer any questions about the Justice Harvard class."),
 
 
 
 
 
 
35
  )
36
- llm = OpenAI(model="gpt-4o", temperature=0)
 
 
 
 
 
 
37
  st.session_state.agent = ReActAgent.from_tools(
38
  tools=[vectara_tool], llm=llm,
39
- context = f'''
40
- You are a teacher assistant for the Justice Harvard course, helping a {cfg.student_age} years old student with his or her questions.
41
- Evaluate the response from tools and respond in the {cfg.style} learning style.
42
- ''',
43
- verbose=True
44
  )
45
 
 
46
  if 'cfg' not in st.session_state:
47
  cfg = OmegaConf.create({
48
  'customer_id': str(os.environ['VECTARA_CUSTOMER_ID']),
@@ -50,12 +67,12 @@ def launch_bot():
50
  'api_key': str(os.environ['VECTARA_API_KEY']),
51
  'style': learning_styles[0],
52
  'language': 'English',
53
- 'student_age': 21
54
  })
55
  st.session_state.cfg = cfg
56
- st.session_state.style = learning_styles[0]
57
- st.session_state.language = 'English'
58
- st.session_state.student_age = 21
59
  reset()
60
 
61
  cfg = st.session_state.cfg
@@ -65,7 +82,7 @@ def launch_bot():
65
  with st.sidebar:
66
  image = Image.open('Vectara-logo.png')
67
  st.image(image, width=250)
68
- st.markdown(f"## Welcome to the Justice Harvard e-learning assistant demo.\n\n\n")
69
 
70
  st.markdown("\n")
71
  cfg.style = st.selectbox('Learning Style:', learning_styles)
@@ -119,7 +136,7 @@ def launch_bot():
119
  # Generate a new response if last message is not from assistant
120
  if st.session_state.messages[-1]["role"] != "assistant":
121
  with st.chat_message("assistant", avatar='🤖'):
122
- with st.spinner('Thinking...'):
123
  res = st.session_state.agent.chat(prompt)
124
  cleaned = re.sub(r'\[\d+\]', '', res.response)
125
  st.write(cleaned)
 
12
  from llama_index.llms.openai import OpenAI
13
  from llama_index.core.tools import QueryEngineTool, ToolMetadata
14
  from llama_index.core.utils import print_text
15
+ from llama_index.core.agent.react.formatter import ReActChatFormatter
16
 
17
+ from prompts import prompt_template
18
+
19
+ learning_styles = ['traditional', 'Inquiry-based', 'Socratic']
20
  languages = {'English': 'en', 'Spanish': 'es', 'French': 'fr', 'German': 'de', 'Arabic': 'ar', 'Chinese': 'zh-cn',
21
  'Hebrew': 'he', 'Hindi': 'hi', 'Italian': 'it', 'Japanese': 'ja', 'Korean': 'ko', 'Portuguese': 'pt'}
22
  initial_prompt = "How can I help you today?"
23
 
24
+
25
  def launch_bot():
26
  def reset():
27
  cfg = st.session_state.cfg
28
  llm = OpenAI(model="gpt-4o", temperature=0)
29
  tr_prompt = Translator(to_lang=languages[cfg.language]).translate(initial_prompt)
30
  st.session_state.messages = [{"role": "assistant", "content": tr_prompt, "avatar": "🦖"}]
31
+ st.session_state.thinking_prompt = Translator(to_lang=languages[cfg.language]).translate("Thinking...")
32
  vectara = VectaraIndex(vectara_api_key=cfg.api_key,
33
  vectara_customer_id=cfg.customer_id,
34
  vectara_corpus_id=cfg.corpus_id)
35
+
36
+ # Create the Vectara Tool
37
  vectara_tool = QueryEngineTool(
38
+ query_engine = vectara.as_query_engine(summary_enabled = True, summary_num_results = 10, summary_response_lang = languages[cfg.language],
39
+ summary_prompt_name = "vectara-summary-ext-24-05-large",
40
+ vectara_query_mode = "mmr", rerank_k = 50, mmr_diversity_bias = 0.1,
41
+ n_sentence_before = 5, n_sentence_after = 5),
42
+ metadata = ToolMetadata(name="vectara",
43
+ description="""
44
+ A tool that is able to answer questions about the justice, morality, politics and related topics.
45
+ Based on transcripts of recordings from the Justice Harvard class that includes a lot of content on these topics.
46
+ When using the tool it's best to ask simple short questions.
47
+ """),
48
  )
49
+
50
+ # Create the agent
51
+ prompt = prompt_template.replace("{style}", cfg.style) \
52
+ .replace("{language}", cfg.language) \
53
+ .replace("{student_age}", str(cfg.student_age))
54
+
55
+ print(prompt)
56
  st.session_state.agent = ReActAgent.from_tools(
57
  tools=[vectara_tool], llm=llm,
58
+ verbose=True,
59
+ react_chat_formatter = ReActChatFormatter(system_header=prompt)
 
 
 
60
  )
61
 
62
+
63
  if 'cfg' not in st.session_state:
64
  cfg = OmegaConf.create({
65
  'customer_id': str(os.environ['VECTARA_CUSTOMER_ID']),
 
67
  'api_key': str(os.environ['VECTARA_API_KEY']),
68
  'style': learning_styles[0],
69
  'language': 'English',
70
+ 'student_age': 18
71
  })
72
  st.session_state.cfg = cfg
73
+ st.session_state.style = cfg.style
74
+ st.session_state.language = cfg.language
75
+ st.session_state.student_age = cfg.student_age
76
  reset()
77
 
78
  cfg = st.session_state.cfg
 
82
  with st.sidebar:
83
  image = Image.open('Vectara-logo.png')
84
  st.image(image, width=250)
85
+ st.markdown("## Welcome to the Justice Harvard e-learning assistant demo.\n\n\n")
86
 
87
  st.markdown("\n")
88
  cfg.style = st.selectbox('Learning Style:', learning_styles)
 
136
  # Generate a new response if last message is not from assistant
137
  if st.session_state.messages[-1]["role"] != "assistant":
138
  with st.chat_message("assistant", avatar='🤖'):
139
+ with st.spinner(st.session_state.thinking_prompt):
140
  res = st.session_state.agent.chat(prompt)
141
  cleaned = re.sub(r'\[\d+\]', '', res.response)
142
  st.write(cleaned)
prompts.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ prompt_template = """
3
+
4
+ You are a helpful teaching assistant in conversation with a {student_age} years old student.
5
+ You task is to help the student with a variety of tasks, from answering questions
6
+ to providing summaries to other types of analyses.
7
+ You specialize in the {style} teaching style and apply it to this conversation.
8
+
9
+ The course you are helping the student with
10
+ examines fundamental questions of political philosophy and moral reasoning.
11
+ It challenges students to think critically about justice, equality, democracy, and citizenship
12
+ through the lens of classical and contemporary philosophical arguments.
13
+
14
+ ## Tools
15
+ You have access to tools. You are responsible for using
16
+ the tools in any sequence you deem appropriate to complete the task at hand.
17
+ This may require breaking the task into subtasks and using different tools
18
+ to complete each subtask.
19
+
20
+ The tools must be your main source of information to answer the student's questions.
21
+ If you can't answer the question with the provided tools, you must say so.
22
+
23
+ You have access to the following tools:
24
+ {tool_desc}
25
+
26
+ ## Input
27
+ The user will specify a task or a question in text.
28
+
29
+ ## Output Format
30
+ To answer the question, please use the following format.
31
+
32
+ ```
33
+ Thought: I need to use a tool to help me answer the question.
34
+ Action: tool name (one of {tool_names}) if using a tool.
35
+ Action Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{"input": "hello world", "num_beams": 5}})
36
+ ```
37
+
38
+ Please ALWAYS start with a Thought.
39
+ Please use a valid JSON format for the Action Input. Do NOT do this {{'input': 'hello world', 'num_beams': 5}}.
40
+
41
+ If this format is used, the tool will respond in the following format:
42
+ ```
43
+ Observation: tool response
44
+ ```
45
+
46
+ You should keep repeating the above format until you have enough information
47
+ to answer the question without using any more tools.
48
+
49
+ At that point, you MUST respond
50
+ Take time and carefully craft your response so that it is appropriate for a {student_age} year old student and the {style} teaching style.
51
+ You can consider a few specific formats for the response and pick the one that is most consistent with the {style} teaching style.
52
+
53
+ Respond in the one of the following two formats:
54
+
55
+ ```
56
+ Thought: I can answer without using any more tools.
57
+ Answer: [your answer here]
58
+ ```
59
+ OR if you cannot answer the question with the provided tools:
60
+
61
+ ```
62
+ Thought: I cannot answer the question with the provided tools.
63
+ Answer: Sorry, I cannot answer your question.
64
+ ```
65
+
66
+ ADDITIONAL INSTRUCTIONS:
67
+ - When using a tool, break down complex questions into a set of shorter questions, and ask the tool about each of them.
68
+ - You must make at least one use of a tool for each question before responding.
69
+ - Make sure your response relies on the tools you have used and the information from those tools.
70
+ - Do not base your response on information that was not provided by the tools.
71
+ - The tool response may include citations in the form [1], [2], etc. Ignore these citations.
72
+ - Always respond in {language} language, regardless of the language of the question.
73
+
74
+ ## Current Conversation
75
+ Below is the current conversation consisting of interleaving student and assistant messages.
76
+
77
+ """
requirements.txt CHANGED
@@ -4,5 +4,5 @@ omegaconf==2.3.0
4
  syrupy==4.0.8
5
  streamlit==1.32.2
6
  translate==3.6.1
7
- llama-index==0.10.37
8
  llama-index-indices-managed-vectara==0.1.4
 
4
  syrupy==4.0.8
5
  streamlit==1.32.2
6
  translate==3.6.1
7
+ llama-index==0.10.40
8
  llama-index-indices-managed-vectara==0.1.4