Skip to content

Commit 0934e05

Browse files
authored
Testbench for better prompts & simplified prompt (#35)
* testbench to verify informational agent prompt with missing sections * similarity graph - responses of testbench * simplify attemp informational prompt
1 parent 65845c7 commit 0934e05

File tree

6 files changed

+237
-94
lines changed

6 files changed

+237
-94
lines changed

Diff for: .gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,5 @@ dmypy.json
135135

136136
# Synthetic data conversations
137137
src/agents/utils/synthetic_conversations/*.json
138-
src/agents/utils/synthetic_conversations/*.csv
138+
src/agents/utils/synthetic_conversations/*.csv
139+
src/agents/utils/synthetic_conversations/*.tsv

Diff for: src/agents/informational_agent/informational_agent.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class State(TypedDict):
3636
conversationalStyle: str
3737

3838
class InformationalAgent:
39-
def __init__(self):
39+
def __init__(self, informational_role_prompt: str = informational_role_prompt, conv_pref_prompt: str = conv_pref_prompt, update_conv_pref_prompt: str = update_conv_pref_prompt, summary_prompt: str = summary_prompt, update_summary_prompt: str = update_summary_prompt):
4040
llm = GoogleAILLMs()
4141
self.llm = llm.get_llm()
4242
summarisation_llm = OpenAILLMs()
@@ -181,7 +181,7 @@ def pretty_response_value(self, event: dict) -> str:
181181
return event["messages"][-1].content
182182

183183
agent = InformationalAgent()
184-
def invoke_informational_agent(query: str, conversation_history: list, summary: str, conversationalStyle: str, question_response_details: str, session_id: str) -> InvokeAgentResponseType:
184+
def invoke_informational_agent(query: str, conversation_history: list, summary: str, conversationalStyle: str, question_response_details: str, session_id: str, agent: InformationalAgent = agent) -> InvokeAgentResponseType:
185185
print(f'in invoke_informational_agent(), thread_id = {session_id}')
186186

187187
config = {"configurable": {"thread_id": session_id, "summary": summary, "conversational_style": conversationalStyle, "question_response_details": question_response_details}}

Diff for: src/agents/informational_agent/informational_prompts.py

+7-13
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,30 @@
44

55
# informational_role_prompt = "You are an excellent tutor that aims to provide clear and concise explanations to students. I am the student. Your task is to answer my questions and provide guidance on the topic discussed. Ensure your responses are accurate, informative, and tailored to my level of understanding and conversational preferences. If I seem to be struggling or am frustrated, refer to my progress so far and the time I spent on the question vs the expected guidance. You do not need to end your messages with a concluding statement.\n\n"
66

7+
# TODO: try using "A tutor and a student work together to solve the following math word problem."
78
informational_role_prompt = """You are a highly skilled and patient AI tutor designed to assist me, the student, in discovering answers and mastering concepts. Your teaching style emphasizes student-centric learning, encouraging deep thinking, active engagement, and confidence building.
89
910
## Teaching Methods:
1011
Step-by-Step Learning: Break complex problems into smaller, manageable parts, solving one step at a time. Avoid giving the final answer upfront; instead, offer hints or intermediate steps to nudge the student toward the solution. Provide the full answer only when it’s clear the student needs it to move forward. If the student explicitly asks for the answer, direct them to the worked solutions or answer provided below, while encouraging them to engage with the chat for deeper understanding.
1112
Error Analysis: Treat mistakes as learning opportunities by helping students reflect on why they occurred and how to address them.
1213
Active Participation: Encourage students to take an active role in solving problems, providing guidance without overtaking their learning process.
13-
Tailored Feedback: Adapt your explanations, questions, and support to the student's level, needs, and progress. If the student is close to the solution, provide encouragement or subtle hints. If they seem stuck, gradually increase the specificity of your support.
1414
1515
## Key Qualities:
16-
Awareness: Use the known learning materials to base your responses on.
16+
Awareness: Use the known learning materials to base your responses on. Refer back to the learning materials when necessary, but do not repeat them verbatim. Instead, summarize or paraphrase the content to ensure understanding.
1717
Patience: Allow students ample time to think, process, and respond without rushing them.
1818
Clarity: Simplify complex ideas into clear, actionable steps.
1919
Encouragement: Celebrate student efforts and achievements to keep motivation high.
2020
Adaptability: Customize teaching approaches based on the student's learning preferences and evolving needs.
2121
Curiosity-Building: Inspire students to ask thoughtful questions, fostering a love for learning.
2222
Consistency: Reinforce concepts regularly to build lasting understanding.
23-
Conversation Flow:
24-
Frequently conclude interactions with a question to keep the dialogue active and gauge the student's comprehension and comfort with the material.
25-
Continuously adapt to the student's problem-solving style, preferred level of guidance, and feedback.
26-
27-
Example Conversation Style:
28-
29-
If the student asks, "How do I solve this equation?" respond with:
30-
"Let's start by identifying what you know. What operation do you think comes first?"
31-
Follow up with guided hints or clarifications based on their response.
23+
Authenticity: Maintain authenticity and a constructive learning environment by keeping feedback clear and focused.
24+
Conversation Flow: Frequently conclude interactions with a question to keep the dialogue active and gauge the student's comprehension and comfort with the material.
25+
Tailored Feedback: Adapt your explanations, questions, and support to the student's level, needs, and progress. If the student is close to the solution, provide encouragement or subtle hints. If the student seems stuck, reflect on their progress and the time spent on the topic, offering the expected guidance. Then gradually increase the specificity of your support.
3226
3327
## Flexibility:
34-
Restrict your response's length to quickly resolve the student's query. However, adjust your approach dynamically, if the student seeks detailed guidance, prefers a hands-off approach, or demonstrates unique problem-solving strategies. If the student struggles or seems frustrated, reflect on their progress and the time spent on the topic, offering the expected guidance. If the student asks about an irrelevant topic, politely redirect them back to the topic. Do not end your responses with a concluding statement.
28+
Directly answer the student's question. Keep your answer short. If the student asks about an irrelevant topic, politely redirect them back to the topic. Do not end your responses with a concluding statement.
3529
36-
## Governance
30+
## Governance:
3731
You are a chatbot deployed in Lambda Feedback, an online self-study platform. You are discussing with students from Imperial College London."""
3832

3933
pref_guidelines = """**Guidelines:**

Diff for: src/agents/utils/parse_json_to_prompt.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def format_response_area_details(responseArea: ResponseAreaDetails, studentSumma
163163
return f"""
164164
## Response Area: {responseArea.position + 1}
165165
{f'Area task: What is {responseArea.preResponseText} ?' if responseArea.preResponseText else ''}
166-
(Secret - not to be shared) Expected Answer: {responseArea.answer};
166+
(Keep it Secret) Expected Answer: {responseArea.answer};
167167
{submissionDetails}"""
168168

169169
def format_part_details(part: PartDetails, currentPart: CurrentPart, summary: List[StudentWorkResponseArea]) -> str:

Diff for: src/agents/utils/prompt_value_analysis.py

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import networkx as nx
2+
import matplotlib.pyplot as plt
3+
import numpy as np
4+
from sentence_transformers import SentenceTransformer
5+
from sklearn.metrics.pairwise import cosine_similarity
6+
import pandas as pd
7+
from matplotlib import cm
8+
from matplotlib.lines import Line2D
9+
10+
# Load paragraphs from CSV
11+
path = "src/agents/utils/synthetic_conversations/"
12+
df = pd.read_csv(path+"prompts_importance.tsv", delimiter="\t") # Replace with your actual file name
13+
print(df.columns)
14+
df["response"] = df["response"].astype(str).str.replace("$$", "", regex=False)
15+
df["response"] = df["response"].astype(str).str.replace("\\", "", regex=False)
16+
paragraphs = df["response"].tolist()
17+
messages = df["message"].tolist()
18+
prompts = df["prompt"].tolist()
19+
missing_prompts = df["prompt_missing"].tolist()
20+
print(f"Loaded {len(paragraphs)} paragraphs, {len(messages)} messages, {len(prompts)} prompts, and {len(missing_prompts)} missing prompts")
21+
22+
# Load embedding model
23+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
24+
25+
# Compute embeddings
26+
embeddings = model.encode(paragraphs, convert_to_numpy=True)
27+
28+
# Compute similarity matrix
29+
similarity_matrix = cosine_similarity(embeddings)
30+
31+
# Create graph
32+
G = nx.Graph()
33+
34+
# Create a mapping of messages to colours
35+
message_to_color = {msg: cm.viridis(i / len(set(messages))) for i, msg in enumerate(set(messages))}
36+
37+
# Add nodes with message-based colours
38+
node_colors = []
39+
for i, paragraph in enumerate(paragraphs):
40+
msg = messages[i]
41+
color = message_to_color[msg] # Get colour based on message
42+
G.add_node(i, text=paragraph, message=msg, color=color, prompt=prompts[i], missing_prompt=missing_prompts[i])
43+
node_colors.append(color) # Add node colour for visualization
44+
45+
# Define a similarity threshold for edges
46+
threshold = 0.5
47+
for i in range(len(paragraphs)):
48+
for j in range(i + 1, len(paragraphs)):
49+
if similarity_matrix[i, j] > threshold:
50+
G.add_edge(i, j, weight=similarity_matrix[i, j])
51+
52+
# Draw graph
53+
fig, ax = plt.subplots(figsize=(12, 6))
54+
pos = nx.spring_layout(G) # Positioning of nodes
55+
nx.draw(G, pos, with_labels=False, node_color=node_colors, edge_color="white", ax=ax)
56+
57+
# Create annotation for hover effect
58+
hover_text = ax.text(0.5, -0.1, "", transform=ax.transAxes, ha="center", va="top", fontsize=10, wrap=True)
59+
hover_text.set_visible(False)
60+
61+
# Function to update hover text and wrap it
62+
def update_hover_text(ind):
63+
node_idx = ind["ind"][0]
64+
node_pos = pos[node_idx]
65+
hover_text.set_position((0.5, -0.05)) # Position the text box at the bottom
66+
hover_text.set_text("Message: "+ G.nodes[node_idx]["message"]+ "\nResponse: "+ G.nodes[node_idx]["text"]) # Set the text
67+
hover_text.set_visible(True)
68+
plt.draw()
69+
70+
# Mouse hover event
71+
def hover(event):
72+
if event.inaxes == ax:
73+
for i, (x, y) in pos.items():
74+
if np.linalg.norm([x - event.xdata, y - event.ydata]) < 0.05: # Adjust hover sensitivity
75+
update_hover_text({"ind": [i]})
76+
return
77+
hover_text.set_visible(False) # Hide text when not hovering over nodes
78+
plt.draw()
79+
80+
# Mouse click event
81+
def on_click(event):
82+
if event.inaxes == ax:
83+
for i, (x, y) in pos.items():
84+
if np.linalg.norm([x - event.xdata, y - event.ydata]) < 0.05: # Click sensitivity
85+
node_idx = i
86+
message = G.nodes[node_idx]["message"]
87+
prompt = G.nodes[node_idx]["prompt"]
88+
missing_prompt = G.nodes[node_idx]["missing_prompt"]
89+
text = G.nodes[node_idx]["text"]
90+
print(f"Clicked node {node_idx} \n-- Message: {message}\n-- Response: {text}\n-- Prompt: {prompt}\n-- Missing Prompt: {missing_prompt}")
91+
print("====================")
92+
93+
# Create legend
94+
legend_handles = []
95+
for msg, color in message_to_color.items():
96+
legend_handles.append(Line2D([0], [0], marker='o', color='w', markerfacecolor=color, markersize=10, label=msg))
97+
98+
ax.legend(handles=legend_handles, title="Messages", bbox_to_anchor=(0.3, 0.0), loc='lower center',
99+
borderaxespad=1, ncol=1, fontsize=10, columnspacing=1, frameon=False)
100+
101+
# Connect events
102+
fig.canvas.mpl_connect("motion_notify_event", hover)
103+
fig.canvas.mpl_connect("button_press_event", on_click)
104+
105+
plt.subplots_adjust(bottom=0.2) # Add space for the bottom bar
106+
plt.show()

0 commit comments

Comments
 (0)