ernani commited on
Commit
0955862
·
1 Parent(s): e8e67d8

First version of AI Trainer assistant

Browse files
Files changed (3) hide show
  1. app.py +248 -55
  2. helper.py +22 -0
  3. tools.py +202 -0
app.py CHANGED
@@ -1,64 +1,257 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
1
  import gradio as gr
2
+ import os
3
+ import time
4
+ from tools import create_workout_table_graph
5
 
6
+ class WorkoutTableGUI:
7
+ def __init__(self, graph=None, share=False):
8
+ self.graph = graph if graph else create_workout_table_graph()
9
+ self.share = share
10
+ self.partial_message = ""
11
+ self.response = {}
12
+ self.max_iterations = 10
13
+ self.iterations = []
14
+ self.threads = []
15
+ self.thread_id = -1
16
+ self.thread = {"configurable": {"thread_id": str(self.thread_id)}}
17
+ self.demo = self.create_interface()
18
 
19
+ def run_agent(self, start, topic, stop_after):
20
+ if start:
21
+ self.iterations.append(0)
22
+ config = {'task': topic, "max_revisions": 2, "revision_number": 0,
23
+ 'lnode': "", 'planner': "no plan", 'draft': "no draft", 'critique': "no critique",
24
+ 'content': ["no content",], 'queries': "no queries", 'count': 0}
25
+ self.thread_id += 1 # new agent, new thread
26
+ self.threads.append(self.thread_id)
27
+ else:
28
+ config = None
29
+ self.thread = {"configurable": {"thread_id": str(self.thread_id)}}
30
+ while self.iterations[self.thread_id] < self.max_iterations:
31
+ self.response = self.graph.invoke(config, self.thread)
32
+ self.iterations[self.thread_id] += 1
33
+ self.partial_message += str(self.response)
34
+ self.partial_message += f"\n------------------\n\n"
35
+ lnode, nnode, _, rev, acount = self.get_disp_state()
36
+ yield self.partial_message, lnode, nnode, self.thread_id, rev, acount
37
+ config = None
38
+ if not nnode:
39
+ return
40
+ if lnode in stop_after:
41
+ return
42
+ return
43
+
44
+ def get_disp_state(self):
45
+ current_state = self.graph.get_state(self.thread)
46
+ lnode = current_state.values["lnode"]
47
+ acount = current_state.values["count"]
48
+ rev = current_state.values["revision_number"]
49
+ nnode = current_state.next
50
+ return lnode, nnode, self.thread_id, rev, acount
51
+
52
+ def get_state(self, key):
53
+ current_values = self.graph.get_state(self.thread)
54
+ if key in current_values.values:
55
+ lnode, nnode, self.thread_id, rev, astep = self.get_disp_state()
56
+ new_label = f"last_node: {lnode}, thread_id: {self.thread_id}, rev: {rev}, step: {astep}"
57
+ return gr.update(label=new_label, value=current_values.values[key])
58
+ else:
59
+ return ""
60
+
61
+ def get_content(self):
62
+ current_values = self.graph.get_state(self.thread)
63
+ if "content" in current_values.values:
64
+ content = current_values.values["content"]
65
+ lnode, nnode, thread_id, rev, astep = self.get_disp_state()
66
+ new_label = f"last_node: {lnode}, thread_id: {self.thread_id}, rev: {rev}, step: {astep}"
67
+ return gr.update(label=new_label, value="\n\n".join(item for item in content) + "\n\n")
68
+ else:
69
+ return ""
70
+
71
+ def update_hist_pd(self):
72
+ hist = []
73
+ for state in self.graph.get_state_history(self.thread):
74
+ if state.metadata['step'] < 1:
75
+ continue
76
+ thread_ts = state.config['configurable']['thread_ts']
77
+ tid = state.config['configurable']['thread_id']
78
+ count = state.values['count']
79
+ lnode = state.values['lnode']
80
+ rev = state.values['revision_number']
81
+ nnode = state.next
82
+ st = f"{tid}:{count}:{lnode}:{nnode}:{rev}:{thread_ts}"
83
+ hist.append(st)
84
+ return gr.Dropdown(label="update_state from: thread:count:last_node:next_node:rev:thread_ts",
85
+ choices=hist, value=hist[0] if hist else None, interactive=True)
86
+
87
+ def find_config(self, thread_ts):
88
+ for state in self.graph.get_state_history(self.thread):
89
+ config = state.config
90
+ if config['configurable']['thread_ts'] == thread_ts:
91
+ return config
92
+ return None
93
+
94
+ def copy_state(self, hist_str):
95
+ thread_ts = hist_str.split(":")[-1]
96
+ config = self.find_config(thread_ts)
97
+ state = self.graph.get_state(config)
98
+ self.graph.update_state(self.thread, state.values, as_node=state.values['lnode'])
99
+ new_state = self.graph.get_state(self.thread)
100
+ new_thread_ts = new_state.config['configurable']['thread_ts']
101
+ tid = new_state.config['configurable']['thread_id']
102
+ count = new_state.values['count']
103
+ lnode = new_state.values['lnode']
104
+ rev = new_state.values['revision_number']
105
+ nnode = new_state.next
106
+ return lnode, nnode, new_thread_ts, rev, count
107
+
108
+ def update_thread_pd(self):
109
+ return gr.Dropdown(label="choose thread", choices=self.threads, value=self.thread_id, interactive=True)
110
+
111
+ def switch_thread(self, new_thread_id):
112
+ self.thread = {"configurable": {"thread_id": str(new_thread_id)}}
113
+ self.thread_id = new_thread_id
114
+ return
115
+
116
+ def modify_state(self, key, asnode, new_state):
117
+ current_values = self.graph.get_state(self.thread)
118
+ current_values.values[key] = new_state
119
+ self.graph.update_state(self.thread, current_values.values, as_node=asnode)
120
+ return
121
 
122
+ def create_interface(self):
123
+ with gr.Blocks(theme=gr.themes.Default(spacing_size='sm', text_size="sm")) as demo:
124
+
125
+ def updt_disp():
126
+ current_state = self.graph.get_state(self.thread)
127
+ hist = []
128
+ for state in self.graph.get_state_history(self.thread):
129
+ if state.metadata['step'] < 1:
130
+ continue
131
+ s_thread_ts = state.config['configurable']['thread_ts']
132
+ s_tid = state.config['configurable']['thread_id']
133
+ s_count = state.values['count']
134
+ s_lnode = state.values['lnode']
135
+ s_rev = state.values['revision_number']
136
+ s_nnode = state.next
137
+ st = f"{s_tid}:{s_count}:{s_lnode}:{s_nnode}:{s_rev}:{s_thread_ts}"
138
+ hist.append(st)
139
+ if not current_state.metadata:
140
+ return {}
141
+ else:
142
+ return {
143
+ topic_bx: current_state.values["task"],
144
+ lnode_bx: current_state.values["lnode"],
145
+ count_bx: current_state.values["count"],
146
+ revision_bx: current_state.values["revision_number"],
147
+ nnode_bx: current_state.next,
148
+ threadid_bx: self.thread_id,
149
+ thread_pd: gr.Dropdown(label="choose thread", choices=self.threads, value=self.thread_id, interactive=True),
150
+ step_pd: gr.Dropdown(label="update_state from: thread:count:last_node:next_node:rev:thread_ts",
151
+ choices=hist, value=hist[0] if hist else None, interactive=True),
152
+ }
153
+
154
+ def get_snapshots():
155
+ new_label = f"thread_id: {self.thread_id}, Summary of snapshots"
156
+ sstate = ""
157
+ for state in self.graph.get_state_history(self.thread):
158
+ for key in ['plan', 'draft', 'critique']:
159
+ if key in state.values:
160
+ state.values[key] = state.values[key][:80] + "..."
161
+ if 'content' in state.values:
162
+ for i in range(len(state.values['content'])):
163
+ state.values['content'][i] = state.values['content'][i][:20] + '...'
164
+ if 'writes' in state.metadata:
165
+ state.metadata['writes'] = "not shown"
166
+ sstate += str(state) + "\n\n"
167
+ return gr.update(label=new_label, value=sstate)
168
 
169
+ def vary_btn(stat):
170
+ return gr.update(variant=stat)
171
+
172
+ with gr.Tab("Agent"):
173
+ with gr.Row():
174
+ topic_bx = gr.Textbox(label="Workout Table", value="Workout Table for a 30 year old male who wants to gain muscle mass and strength")
175
+ gen_btn = gr.Button("Generate Workout Table", scale=0, min_width=80, variant='primary')
176
+ cont_btn = gr.Button("Continue Workout Table", scale=0, min_width=80)
177
+ with gr.Row():
178
+ lnode_bx = gr.Textbox(label="last node", min_width=100)
179
+ nnode_bx = gr.Textbox(label="next node", min_width=100)
180
+ threadid_bx = gr.Textbox(label="Thread", scale=0, min_width=80)
181
+ revision_bx = gr.Textbox(label="Draft Rev", scale=0, min_width=80)
182
+ count_bx = gr.Textbox(label="count", scale=0, min_width=80)
183
+ with gr.Accordion("Manage Agent", open=False):
184
+ checks = list(self.graph.nodes.keys())
185
+ checks.remove('__start__')
186
+ stop_after = gr.CheckboxGroup(checks, label="Interrupt After State", value=checks, scale=0, min_width=400)
187
+ with gr.Row():
188
+ thread_pd = gr.Dropdown(choices=self.threads, interactive=True, label="select thread", min_width=120, scale=0)
189
+ step_pd = gr.Dropdown(choices=['N/A'], interactive=True, label="select step", min_width=160, scale=1)
190
+ live = gr.Textbox(label="Live Agent Output", lines=5, max_lines=5)
191
+
192
+ # actions
193
+ sdisps = [topic_bx, lnode_bx, nnode_bx, threadid_bx, revision_bx, count_bx, step_pd, thread_pd]
194
+ thread_pd.input(self.switch_thread, [thread_pd], None).then(
195
+ fn=updt_disp, inputs=None, outputs=sdisps)
196
+ step_pd.input(self.copy_state, [step_pd], None).then(
197
+ fn=updt_disp, inputs=None, outputs=sdisps)
198
+ gen_btn.click(vary_btn, gr.Number("secondary", visible=False), gen_btn).then(
199
+ fn=self.run_agent, inputs=[gr.Number(True, visible=False), topic_bx, stop_after], outputs=[live], show_progress=True).then(
200
+ fn=updt_disp, inputs=None, outputs=sdisps).then(
201
+ vary_btn, gr.Number("primary", visible=False), gen_btn).then(
202
+ vary_btn, gr.Number("primary", visible=False), cont_btn)
203
+ cont_btn.click(vary_btn, gr.Number("secondary", visible=False), cont_btn).then(
204
+ fn=self.run_agent, inputs=[gr.Number(False, visible=False), topic_bx, stop_after],
205
+ outputs=[live]).then(
206
+ fn=updt_disp, inputs=None, outputs=sdisps).then(
207
+ vary_btn, gr.Number("primary", visible=False), cont_btn)
208
+
209
+ with gr.Tab("Workout Table"):
210
+ with gr.Row():
211
+ refresh_btn = gr.Button("Refresh")
212
+ modify_btn = gr.Button("Modify")
213
+ plan = gr.Textbox(label="Plan", lines=10, interactive=True)
214
+ refresh_btn.click(fn=self.get_state, inputs=gr.Number("plan", visible=False), outputs=plan)
215
+ modify_btn.click(fn=self.modify_state, inputs=[gr.Number("plan", visible=False),
216
+ gr.Number("planner", visible=False), plan], outputs=None).then(
217
+ fn=updt_disp, inputs=None, outputs=sdisps)
218
+ with gr.Tab("Research Content"):
219
+ refresh_btn = gr.Button("Refresh")
220
+ content_bx = gr.Textbox(label="content", lines=10)
221
+ refresh_btn.click(fn=self.get_content, inputs=None, outputs=content_bx)
222
+ with gr.Tab("Draft"):
223
+ with gr.Row():
224
+ refresh_btn = gr.Button("Refresh")
225
+ modify_btn = gr.Button("Modify")
226
+ draft_bx = gr.Textbox(label="draft", lines=10, interactive=True)
227
+ refresh_btn.click(fn=self.get_state, inputs=gr.Number("draft", visible=False), outputs=draft_bx)
228
+ modify_btn.click(fn=self.modify_state, inputs=[gr.Number("draft", visible=False),
229
+ gr.Number("generate", visible=False), draft_bx], outputs=None).then(
230
+ fn=updt_disp, inputs=None, outputs=sdisps)
231
+ with gr.Tab("Feedback"):
232
+ with gr.Row():
233
+ refresh_btn = gr.Button("Refresh")
234
+ modify_btn = gr.Button("Modify")
235
+ feedback_bx = gr.Textbox(label="Feedback", lines=10, interactive=True)
236
+ refresh_btn.click(fn=self.get_state, inputs=gr.Number("feedback", visible=False), outputs=feedback_bx)
237
+ modify_btn.click(fn=self.modify_state, inputs=[gr.Number("feedback", visible=False),
238
+ gr.Number("reflect", visible=False),
239
+ feedback_bx], outputs=None).then(
240
+ fn=updt_disp, inputs=None, outputs=sdisps)
241
+ with gr.Tab("StateSnapShots"):
242
+ with gr.Row():
243
+ refresh_btn = gr.Button("Refresh")
244
+ snapshots = gr.Textbox(label="State Snapshots Summaries")
245
+ refresh_btn.click(fn=get_snapshots, inputs=None, outputs=snapshots)
246
+ return demo
247
 
248
+ def launch(self, share=None):
249
+ if port := os.getenv("PORT1"):
250
+ self.demo.launch(share=True, server_port=int(port), server_name="0.0.0.0")
251
+ else:
252
+ self.demo.launch(share=self.share)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
 
254
 
255
  if __name__ == "__main__":
256
+ workout_table = WorkoutTableGUI()
257
+ workout_table.launch()
helper.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore", message=".*TqdmWarning.*")
3
+ from dotenv import load_dotenv
4
+
5
+ _ = load_dotenv()
6
+
7
+ from tools import create_workout_table_graph
8
+ from app import WorkoutTableGUI
9
+
10
+ # This file is kept for backward compatibility
11
+ # The functionality has been moved to tools.py and app.py
12
+
13
+ def create_workout_table():
14
+ """
15
+ Create an workout table instance with the graph and GUI
16
+ """
17
+ graph = create_workout_table_graph()
18
+ return WorkoutTableGUI(graph)
19
+
20
+ if __name__ == "__main__":
21
+ workout_table = create_workout_table()
22
+ workout_table.launch()
tools.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore", message=".*TqdmWarning.*")
3
+ from dotenv import load_dotenv
4
+
5
+ _ = load_dotenv()
6
+
7
+ from langgraph.graph import StateGraph, END
8
+ from typing import TypedDict, Annotated, List
9
+ import operator
10
+ from langgraph.checkpoint.sqlite import SqliteSaver
11
+ from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, AIMessage, ChatMessage
12
+ from langchain_openai import ChatOpenAI
13
+ from pydantic import BaseModel
14
+ from tavily import TavilyClient
15
+ import os
16
+ import sqlite3
17
+
18
+ class AgentState(TypedDict):
19
+ task: str
20
+ lnode: str
21
+ plan: str
22
+ draft: str
23
+ feedback: str
24
+ content: List[str]
25
+ queries: List[str]
26
+ revision_number: int
27
+ max_revisions: int
28
+ count: Annotated[int, operator.add]
29
+
30
+
31
+ class Queries(BaseModel):
32
+ queries: List[str]
33
+
34
+ # Tool functions
35
+ def plan_node(model, state: AgentState):
36
+ table_output = """
37
+ Workout Table Sequence:
38
+ - Section 1: Warm-up
39
+ - Section 2: Strength Training
40
+ - Section 3: Cardio
41
+ - Section 4: Cool-down
42
+
43
+ Workout Table Example:
44
+ Workout Table Full Body (3 times per week):
45
+ Day 1:
46
+ Squat on Chair: 2-3 sets of 8-10 repetitions
47
+ Bench Press with Dumbbells: 2-3 sets of 8-10 repetitions
48
+ Row on the machine: 2-3 sets of 8-10 repetitions
49
+ Glute Machine or Glute Bridge: 2-3 sets of 10-12 repetitions
50
+ Development with dumbbells: 2-3 sets of 8-10 repetitions
51
+ Dumbbell curls: 2-3 sets of 10-12 repetitions
52
+
53
+ Day 2:
54
+ Leg Extension: 2-3 sets of 10-12 repetitions
55
+ Arms pushdowns (supporting on knees): 2-3 sets of 8-10 repetitions
56
+ Dumbbell row: 2-3 sets of 8-10 repetitions
57
+ Calf Raises (standing): 2-3 sets of 10-12 repetitions
58
+ Lateral Raises: 2-3 sets of 10-12 repetitions
59
+ Triceps Extension: 2-3 sets of 10-12 repetitions
60
+
61
+ Day 3:
62
+ Cardio (bike or treadmill): 30 minutes at moderate pace
63
+ Abdominal: 2-3 sets of 12-15 repetitions
64
+ Plank: 2-3 sets, holding for 20-30 seconds
65
+
66
+ Remember to always warm up before training and stretch after.
67
+ """
68
+
69
+ PLAN_PROMPT = ("You are an expert gym trainer tasked with writing a high level workout table. "
70
+ "Write such an outline for the user provided workout. Give the three main headers of an outline of "
71
+ "the workout table along with any relevant notes or instructions for the sections. "
72
+ f"Here is the user's workout table: {table_output}")
73
+ messages = [
74
+ SystemMessage(content=PLAN_PROMPT),
75
+ HumanMessage(content=state['task'])
76
+ ]
77
+ response = model.invoke(messages)
78
+ return {"plan": response.content,
79
+ "lnode": "planner",
80
+ "count": 1,
81
+ }
82
+
83
+ def research_plan_node(model, tavily, state: AgentState):
84
+ RESEARCH_PLAN_PROMPT = ("You are a researcher charged with providing information that can "
85
+ "be used when writing the following workout table. Generate a list of search "
86
+ "queries that will gather "
87
+ "any relevant information. Only generate 3 queries max.")
88
+ queries = model.with_structured_output(Queries).invoke([
89
+ SystemMessage(content=RESEARCH_PLAN_PROMPT),
90
+ HumanMessage(content=state['task'])
91
+ ])
92
+ content = state['content'] or [] # add to content
93
+ for q in queries.queries:
94
+ response = tavily.search(query=q, max_results=2)
95
+ for r in response['results']:
96
+ content.append(r['content'])
97
+ return {"content": content,
98
+ "queries": queries.queries,
99
+ "lnode": "research_plan",
100
+ "count": 1,
101
+ }
102
+
103
+ def generation_node(model, state: AgentState):
104
+ WRITER_PROMPT = ("You are an gym trainer assistant tasked with writing excellent workout tables. "
105
+ "Generate the best workout table possible for the user's request and the initial outline. "
106
+ "If the user provides feedback, respond with a revised version of your previous attempts. "
107
+ "Utilize all the information below as needed: \n"
108
+ "------\n"
109
+ "{content}")
110
+ content = "\n\n".join(state['content'] or [])
111
+ user_message = HumanMessage(
112
+ content=f"{state['task']}\n\nHere is my workout table:\n\n{state['plan']}")
113
+ messages = [
114
+ SystemMessage(
115
+ content=WRITER_PROMPT.format(content=content)
116
+ ),
117
+ user_message
118
+ ]
119
+ response = model.invoke(messages)
120
+ return {
121
+ "draft": response.content,
122
+ "revision_number": state.get("revision_number", 1) + 1,
123
+ "lnode": "generate",
124
+ "count": 1,
125
+ }
126
+
127
+ def reflection_node(model, state: AgentState):
128
+ REFLECTION_PROMPT = ("You are an instructor personal grading an workout table submission. "
129
+ "Generate feedback and recommendations for the user's submission. "
130
+ "Provide detailed recommendations, including requests for objectives, level of intensity, health benefits, health conditions, etc.")
131
+ messages = [
132
+ SystemMessage(content=REFLECTION_PROMPT),
133
+ HumanMessage(content=state['draft'])
134
+ ]
135
+ response = model.invoke(messages)
136
+ return {"feedback": response.content,
137
+ "lnode": "reflect",
138
+ "count": 1,
139
+ }
140
+
141
+ def research_feedback_node(model, tavily, state: AgentState):
142
+ RESEARCH_FEEDBACK_PROMPT = ("You are a researcher charged with providing information that can "
143
+ "be used when writing the following workout table. Generate a list of search "
144
+ "queries that will gather "
145
+ "any relevant information. Only generate 3 queries max.")
146
+ queries = model.with_structured_output(Queries).invoke([
147
+ SystemMessage(content=RESEARCH_FEEDBACK_PROMPT),
148
+ HumanMessage(content=state['feedback'])
149
+ ])
150
+ content = state['content'] or [] # add to content
151
+ for q in queries.queries:
152
+ response = tavily.search(query=q, max_results=2)
153
+ for r in response['results']:
154
+ content.append(r['content'])
155
+ queries = model.with_structured_output(Queries).invoke([
156
+ SystemMessage(content=RESEARCH_FEEDBACK_PROMPT),
157
+ HumanMessage(content=state['feedback'])
158
+ ])
159
+ content = state['content'] or []
160
+ for q in queries.queries:
161
+ response = tavily.search(query=q, max_results=2)
162
+ for r in response['results']:
163
+ content.append(r['content'])
164
+ return {"content": content,
165
+ "lnode": "research_feedback",
166
+ "count": 1,
167
+ }
168
+
169
+ def should_continue(state):
170
+ if state["revision_number"] > state["max_revisions"]:
171
+ return END
172
+ return "reflect"
173
+
174
+ # Function to create the graph
175
+ def create_workout_table_graph():
176
+ model = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
177
+ tavily = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
178
+
179
+ builder = StateGraph(AgentState)
180
+ builder.add_node("planner", lambda state: plan_node(model, state))
181
+ builder.add_node("research_plan", lambda state: research_plan_node(model, tavily, state))
182
+ builder.add_node("generate", lambda state: generation_node(model, state))
183
+ builder.add_node("reflect", lambda state: reflection_node(model, state))
184
+ builder.add_node("research_feedback", lambda state: research_feedback_node(model, tavily, state))
185
+ builder.set_entry_point("planner")
186
+ builder.add_conditional_edges(
187
+ "generate",
188
+ should_continue,
189
+ {END: END, "reflect": "reflect"}
190
+ )
191
+ builder.add_edge("planner", "research_plan")
192
+ builder.add_edge("research_plan", "generate")
193
+ builder.add_edge("reflect", "research_feedback")
194
+ builder.add_edge("research_feedback", "generate")
195
+ memory = SqliteSaver(conn=sqlite3.connect(":memory:", check_same_thread=False))
196
+ graph = builder.compile(
197
+ checkpointer=memory,
198
+ interrupt_after=['planner', 'generate', 'reflect', 'research_plan', 'research_feedback']
199
+ )
200
+
201
+ return graph
202
+