Errolmking commited on
Commit
6b1a86a
·
1 Parent(s): 598730d

Update app.py

Browse files

Complete overhaul of app

Files changed (1) hide show
  1. app.py +101 -64
app.py CHANGED
@@ -47,13 +47,6 @@ import gradio as gr
47
 
48
  from pydantic import BaseModel, Field, validator
49
 
50
- #Load the FAISS Model ( vector )
51
- openai.api_key = os.environ["OPENAI_API_KEY"]
52
- db = FAISS.load_local("db", OpenAIEmbeddings())
53
-
54
- #API Keys
55
- promptlayer.api_key = os.environ["PROMPTLAYER"]
56
-
57
  from langchain.callbacks import PromptLayerCallbackHandler
58
  from langchain.prompts.chat import (
59
  ChatPromptTemplate,
@@ -63,6 +56,95 @@ from langchain.prompts.chat import (
63
  )
64
  from langchain.memory import ConversationSummaryMemory
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  # Defined a QueueCallback, which takes as a Queue object during initialization. Each new token is pushed to the queue.
67
  class QueueCallback(BaseCallbackHandler):
68
  """Callback handler for streaming LLM responses to a queue."""
@@ -78,8 +160,7 @@ class QueueCallback(BaseCallbackHandler):
78
 
79
  class DDSAgent:
80
 
81
- def __init__(self, name, db, prompt_template='', model_name='gpt-4', verbose=False, temp=0.2):
82
- self.db = db
83
  self.verbose = verbose
84
  self.llm = ChatOpenAI(
85
  model_name="gpt-4",
@@ -93,7 +174,7 @@ class DDSAgent:
93
  self.summary_llm = ChatOpenAI(
94
  model_name=model_name,
95
  max_tokens=25,
96
- callbacks=[PromptLayerCallbackHandler(pl_tags=["froebel"])],
97
  streaming=False,
98
  )
99
 
@@ -111,31 +192,21 @@ class DDSAgent:
111
  memory=self.memory
112
  )
113
 
114
- def lookup(self, input, num_docs=5):
115
- docs = self.db.similarity_search(input, k=num_docs)
116
- docs_to_string = ""
117
- for doc in docs:
118
- docs_to_string += str(doc.page_content)
119
- return docs_to_string
120
-
121
  def stream(self, input) -> Generator:
122
 
123
  # Create a Queue
124
  q = Queue()
125
  job_done = object()
126
 
127
- #RAG
128
- docs = self.lookup(input,5)
129
-
130
  llm = ChatOpenAI(
131
  model_name='gpt-4',
132
  callbacks=[QueueCallback(q),
133
- PromptLayerCallbackHandler(pl_tags=["froebel"])],
134
  streaming=True,
135
  )
136
 
137
  prompt = PromptTemplate(
138
- input_variables=['input','docs','history'],
139
  template=self.prompt_template
140
  # partial_variables={"format_instructions": self.parser.get_format_instructions()}
141
  )
@@ -144,7 +215,6 @@ class DDSAgent:
144
  def task():
145
  resp = self.chain(prompt,llm).run(
146
  {'input':input,
147
- 'docs':docs,
148
  'history':self.memory})
149
  q.put(job_done)
150
 
@@ -165,53 +235,20 @@ class DDSAgent:
165
  except Empty:
166
  continue
167
 
168
-
169
-
170
-
171
- agent_prompt = """
172
- Roleplay
173
- You are a UBD ( Understanding by Design ) coach.
174
- Educators come to you to develop UBD based learning experiences
175
- and curriculum.
176
-
177
- This is the conversation up until now:
178
- {history}
179
-
180
- The teacher says:
181
- {input}
182
-
183
- As a result, following standards were matched:
184
- {docs}
185
-
186
- Respond to the teacher message.
187
-
188
- You have three objectives:
189
-
190
- a) to help them through the design process
191
- b) to help simplify the process for the educator
192
- c) to help build confidence and understand in the ubd process
193
-
194
- Take it step by step and keep.
195
- Keep focused on the current task at hand.
196
- Close with a single guiding step in the form of a question.
197
- Be encouraging.
198
-
199
- Do not start with "AI:" or any self identifying text.
200
-
201
- """
202
 
203
  def ask_agent(input, history):
204
- dds = DDSAgent('agent', db, prompt_template=agent_prompt)
205
- for next_token, content in dds.stream(input):
206
  yield(content)
207
 
 
 
208
  gr.ChatInterface(ask_agent,
209
- title="UBD Coach",
210
- description="""
211
- Using the Understanding By Design framework? I can help. (/◕ヮ◕)/
212
- """,
213
  theme="monochrome",
214
  retry_btn=None,
215
  undo_btn=None,
216
  clear_btn=None
217
- ).queue().launch(debug=True)
 
 
47
 
48
  from pydantic import BaseModel, Field, validator
49
 
 
 
 
 
 
 
 
50
  from langchain.callbacks import PromptLayerCallbackHandler
51
  from langchain.prompts.chat import (
52
  ChatPromptTemplate,
 
56
  )
57
  from langchain.memory import ConversationSummaryMemory
58
 
59
+ #API Keys
60
+ promptlayer.api_key = os.environ["PROMPTLAYER"]
61
+ openai.api_key = os.environ["OPENAI_API_KEY"]
62
+
63
+ import gradio as gr
64
+
65
+ """# Config the app"""
66
+
67
+ TITLE = "UBD Coach"
68
+ DESC="""
69
+ A UBD expert here to help you build out your curriculum.
70
+ What subject are you interested in building for?
71
+ """
72
+
73
+ APP = """
74
+ # UBD Coach
75
+
76
+ Roleplay as an expert in the Understanding by Design curriculum coach.
77
+ Help the teacher build out their UBD curriculum step by step.
78
+ Be encouraging.
79
+ Help the teacher build confidence in the design process.
80
+ Below is the structure of the design process ( delineated by the triple plus):
81
+
82
+ +++
83
+ Stage 1: Identify Desired Results
84
+ The first stage in the design process calls for clarity about the learning priorities – both long-term outcomes as well as short-term goals. We review established content standards and related outcomes (e.g., 21st-century skills) to consider the big ideas we want students to come to understand and the long-term transfer goals that those ideas enable. We frame companion essential questions around the targeted understandings and transfer goals. Finally, we identify more specific knowledge and skill objectives.
85
+
86
+ The following planning questions guide the work of Stage 1:
87
+ What do we want students to be able to do with their learning in the long run?
88
+ What should students come to understand for them to transfer their learning?
89
+ What essential questions will students explore?
90
+ What knowledge and skills will students need to acquire?
91
+
92
+ Stage 2: Determine Acceptable Evidence
93
+ In Stage 2 of backward design, we are encouraged to “think like assessors” before jumping to planning lessons and learning activities (in Stage 3). In other words, we need to think about the assessment that will show the extent to which our students have attained the various learning outcomes outlined in Stage 1.
94
+ It is one thing to say that students should understand X and be able to do Y; it is another to ask: What evidence will show that they understand X and can effectively apply Y? We have found that considering the needed assessment evidence helps focus and sharpen the teaching-learning plan in Stage 3.
95
+ The following planning questions guide the work of Stage 2:
96
+ What evidence will show that learners have achieved the learning goals targeted in Stage 1?
97
+ How will learners demonstrate their understanding and ability to transfer their learning?
98
+ How will we assess the specific knowledge and skill proficiency?
99
+ In UbD, evidence of understanding and transfer is obtained through performance tasks that ask students to explain what they understand and to apply (i.e., transfer) their learning to new situations. We recommend that the performance assessments be set in a meaningful and authentic context whenever possible. Supplementary assessments, such as a test on facts or a skills check, provide additional evidence of students’ knowledge acquisition and skill proficiency.
100
+
101
+ Stage 3: Plan Learning Experiences and Instruction
102
+ In the third stage of backward design, we plan for our teaching and the associated learning experiences that students will need to reach and demonstrate attainment of goals. With clearly identified learning results (Stage 1) and appropriate assessment evidence in mind (Stage 2), we now plan the most appropriate instructional activities for helping learners acquire targeted knowledge and skills, come to understand important ideas, and apply their learning in meaningful ways.
103
+ The various types of learning goals identified in Stage 1—acquisition of knowledge and skills, understanding of big ideas, and transfer—inform the selection of instructional strategies and the roles of the teacher, including direct instructor, facilitator, and coach. In other words, our instructional practices need to be aligned to the desired results (Stage 1) and their assessments (Stage 2).
104
+ The following planning questions guide planning in Stage 3:
105
+ What activities, experiences, and lessons will lead to the achievement of the desired results and success at the assessments?
106
+ How will the learning plan help students acquire, make meaning, and transfer?
107
+ How will the unit be sequenced and differentiated to optimize achievement for all learners?
108
+ How will we check for understanding along the way?
109
+ +++
110
+
111
+ Goal [
112
+ Stage_1
113
+ Stage_2
114
+ Stage_3
115
+ ]
116
+
117
+ Input [
118
+ input = {input}
119
+ ]
120
+
121
+ History [
122
+ history = {history}
123
+ ]
124
+
125
+ Understanding_By_Design_Coach [
126
+ State [
127
+ Goals
128
+ ]
129
+ Constraints [
130
+ Emulate the speaking style of the world's best curriculum coaches.
131
+ Keep the responses short and focused and on task towards the goal.
132
+ Be encouraging.
133
+ Close with a question that helps the teacher complete the current step.
134
+ ]
135
+
136
+ /help - provide a summary of the design process
137
+ /explain - Explain the goals of the ubd process
138
+
139
+ ]
140
+ very_brief_state_summary()
141
+ respond(input, history)
142
+
143
+ """
144
+
145
+
146
+ """# Agent Engine"""
147
+
148
  # Defined a QueueCallback, which takes as a Queue object during initialization. Each new token is pushed to the queue.
149
  class QueueCallback(BaseCallbackHandler):
150
  """Callback handler for streaming LLM responses to a queue."""
 
160
 
161
  class DDSAgent:
162
 
163
+ def __init__(self, name, prompt_template='', model_name='gpt-4', verbose=False, temp=0.2):
 
164
  self.verbose = verbose
165
  self.llm = ChatOpenAI(
166
  model_name="gpt-4",
 
174
  self.summary_llm = ChatOpenAI(
175
  model_name=model_name,
176
  max_tokens=25,
177
+ callbacks=[PromptLayerCallbackHandler(pl_tags=["sudo_lang"])],
178
  streaming=False,
179
  )
180
 
 
192
  memory=self.memory
193
  )
194
 
 
 
 
 
 
 
 
195
  def stream(self, input) -> Generator:
196
 
197
  # Create a Queue
198
  q = Queue()
199
  job_done = object()
200
 
 
 
 
201
  llm = ChatOpenAI(
202
  model_name='gpt-4',
203
  callbacks=[QueueCallback(q),
204
+ PromptLayerCallbackHandler(pl_tags=["sudo_lang"])],
205
  streaming=True,
206
  )
207
 
208
  prompt = PromptTemplate(
209
+ input_variables=['input','history'],
210
  template=self.prompt_template
211
  # partial_variables={"format_instructions": self.parser.get_format_instructions()}
212
  )
 
215
  def task():
216
  resp = self.chain(prompt,llm).run(
217
  {'input':input,
 
218
  'history':self.memory})
219
  q.put(job_done)
220
 
 
235
  except Empty:
236
  continue
237
 
238
+ agent = DDSAgent('agent', prompt_template=APP)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  def ask_agent(input, history):
241
+ for next_token, content in agent.stream(input):
 
242
  yield(content)
243
 
244
+ """# Run Gradio App Locally"""
245
+
246
  gr.ChatInterface(ask_agent,
247
+ title=TITLE,
248
+ description=DESC,
 
 
249
  theme="monochrome",
250
  retry_btn=None,
251
  undo_btn=None,
252
  clear_btn=None
253
+ ).queue().launch(debug=True)
254
+