24Arys11 commited on
Commit
d426005
·
1 Parent(s): d5ce935

adjusted prompts; bug fix: logger file handling encoding; improved logging

Browse files
alfred.py CHANGED
@@ -44,20 +44,28 @@ class GraphBuilder:
44
  """
45
  Assistant agent that evaluates the query and decides whether to give a final answer
46
  or continue the conversation with the Manager.
47
-
48
  Uses the existing Assistant implementation.
49
  """
 
 
 
 
 
50
  if state["current_message"] is None:
51
  # First time, just forward the query to the manager
52
  response = state["initial_query"]
53
  else:
54
- response = await self.assistant_agent.query(state["current_message"])
55
-
 
56
  # Check if this is a final answer
57
  if self.final_answer_hint in response:
58
  # Extract the text after final answer hint
59
- state["final_response"] = response.split(self.final_answer_hint, 1)[1].strip()
60
-
 
 
61
  state["current_message"] = response
62
  state["nr_interactions"] += 1
63
 
@@ -69,6 +77,11 @@ class GraphBuilder:
69
 
70
  Uses the existing Manager implementation.
71
  """
 
 
 
 
 
72
  if state["current_message"] is None:
73
  raise ValueError("manager_node called with no current_message in state")
74
 
@@ -85,27 +98,32 @@ class GraphBuilder:
85
  If there's already a final answer in the state, it uses that.
86
  Otherwise, it asks the assistant to formulate a final answer.
87
  """
88
- print("========== final_answer_node ==========")
 
 
 
 
89
  # If we already have a final answer, use it
90
  final_response = state.get("final_response")
91
  if final_response is not None:
92
- print(f"====================\nFinal response:\n{final_response}\n====================")
93
  return state
94
 
95
  # Otherwise, have the assistant formulate a final answer
96
  prompt = f"Based on the conversation so far, provide a final answer to the original query:\n\n{state['initial_query']}"
97
  state["current_message"] = prompt
98
- response = await self.assistant_agent.query(state["current_message"])
99
 
100
  # Format the response
101
  if self.final_answer_hint not in response:
102
- print(f"WARNING: final_answer_hint '{self.final_answer_hint}' not in response !")
103
  response = f"{self.final_answer_hint}{response}"
104
 
105
  # Extract the text after final answer hint
106
- state["final_response"] = response.split(self.final_answer_hint, 1)[1].strip()
107
- final_response = state.get("final_response")
108
- print(f"====================\nFinal response:\n{final_response}\n====================")
 
109
 
110
  return state
111
 
@@ -117,15 +135,21 @@ class GraphBuilder:
117
  "manager": If the Assistant has decided to continue the conversation
118
  "final_answer": If the Assistant has decided to provide a final answer
119
  """
 
 
 
 
 
120
  if state["current_message"] is None:
121
  raise ValueError("should_continue conditional edge was reached with no current_message in state")
122
 
123
  message = state["current_message"]
124
 
125
  if state["nr_interactions"] >= MAX_INTERACTIONS or self.final_answer_hint in message:
 
126
  return "final_answer"
127
- else:
128
- return "manager"
129
 
130
  def build_agent_graph(self) -> CompiledStateGraph:
131
  """Build and return the agent graph."""
@@ -217,8 +241,8 @@ class Alfred:
217
  log_filename = f"{current_time}.txt"
218
  log_filepath = logs_dir / log_filename
219
 
220
- # Create file handler
221
- file_handler = logging.FileHandler(log_filepath)
222
  file_handler.setLevel(logging.INFO)
223
  file_handler.setFormatter(formatter)
224
 
 
44
  """
45
  Assistant agent that evaluates the query and decides whether to give a final answer
46
  or continue the conversation with the Manager.
47
+
48
  Uses the existing Assistant implementation.
49
  """
50
+ if Args.LOGGER is None:
51
+ raise RuntimeError("LOGGER must be defined before running the assistant_node.")
52
+
53
+ Args.LOGGER.log(logging.INFO, "********** assistant_node **********")
54
+
55
  if state["current_message"] is None:
56
  # First time, just forward the query to the manager
57
  response = state["initial_query"]
58
  else:
59
+ assistent_input = f"This is the initial user query:\n\n{state["initial_query"]}\n\nThe manager provided the following answer:\n\n{state["current_message"]}\n"
60
+ response = await self.assistant_agent.query(assistent_input)
61
+
62
  # Check if this is a final answer
63
  if self.final_answer_hint in response:
64
  # Extract the text after final answer hint
65
+ final_response = response.split(self.final_answer_hint)[-1]
66
+ final_response = final_response.strip()
67
+ state["final_response"] = final_response
68
+
69
  state["current_message"] = response
70
  state["nr_interactions"] += 1
71
 
 
77
 
78
  Uses the existing Manager implementation.
79
  """
80
+ if Args.LOGGER is None:
81
+ raise RuntimeError("LOGGER must be defined before running the manager_node.")
82
+
83
+ Args.LOGGER.log(logging.INFO, "********** manager_node **********")
84
+
85
  if state["current_message"] is None:
86
  raise ValueError("manager_node called with no current_message in state")
87
 
 
98
  If there's already a final answer in the state, it uses that.
99
  Otherwise, it asks the assistant to formulate a final answer.
100
  """
101
+ if Args.LOGGER is None:
102
+ raise RuntimeError("LOGGER must be defined before running the final_answer_node.")
103
+
104
+ Args.LOGGER.log(logging.INFO, "********** final_answer_node **********")
105
+
106
  # If we already have a final answer, use it
107
  final_response = state.get("final_response")
108
  if final_response is not None:
109
+ Args.LOGGER.log(logging.INFO, f"==========\nFinal response:\n{final_response}\n==========")
110
  return state
111
 
112
  # Otherwise, have the assistant formulate a final answer
113
  prompt = f"Based on the conversation so far, provide a final answer to the original query:\n\n{state['initial_query']}"
114
  state["current_message"] = prompt
115
+ response = await self.assistant_agent.query(prompt)
116
 
117
  # Format the response
118
  if self.final_answer_hint not in response:
119
+ Args.LOGGER.log(logging.WARNING, f"Final_answer_hint '{self.final_answer_hint}' not in response !")
120
  response = f"{self.final_answer_hint}{response}"
121
 
122
  # Extract the text after final answer hint
123
+ final_response = response.split(self.final_answer_hint)[-1]
124
+ final_response = final_response.strip()
125
+ state["final_response"] = final_response
126
+ Args.LOGGER.log(logging.INFO, f"==========\nFinal response:\n{final_response}\n==========")
127
 
128
  return state
129
 
 
135
  "manager": If the Assistant has decided to continue the conversation
136
  "final_answer": If the Assistant has decided to provide a final answer
137
  """
138
+ if Args.LOGGER is None:
139
+ raise RuntimeError("LOGGER must be defined before running the should_continue edge.")
140
+
141
+ Args.LOGGER.log(logging.INFO, "++++++++++ should_continue edge ++++++++++")
142
+
143
  if state["current_message"] is None:
144
  raise ValueError("should_continue conditional edge was reached with no current_message in state")
145
 
146
  message = state["current_message"]
147
 
148
  if state["nr_interactions"] >= MAX_INTERACTIONS or self.final_answer_hint in message:
149
+ Args.LOGGER.log(logging.INFO, "++++++++++ should_continue edge decision: final_answer ++++++++++")
150
  return "final_answer"
151
+ Args.LOGGER.log(logging.INFO, "++++++++++ should_continue edge decision: manager ++++++++++")
152
+ return "manager"
153
 
154
  def build_agent_graph(self) -> CompiledStateGraph:
155
  """Build and return the agent graph."""
 
241
  log_filename = f"{current_time}.txt"
242
  log_filepath = logs_dir / log_filename
243
 
244
+ # Create file handler with UTF-8 encoding to handle all Unicode characters
245
+ file_handler = logging.FileHandler(log_filepath, encoding='utf-8')
246
  file_handler.setLevel(logging.INFO)
247
  file_handler.setFormatter(formatter)
248
 
itf_agent.py CHANGED
@@ -13,7 +13,6 @@ from llama_index.core.agent.workflow import AgentWorkflow
13
 
14
  class IAgent():
15
  def __init__(self, temperature, max_tokens, sys_prompt_filename, llm_itf: LLMInterface):
16
- print(f"Agent initialized using {sys_prompt_filename} prompt file.")
17
  self.name = self._format_name(sys_prompt_filename)
18
  self.temperature, self.max_tokens = temperature, max_tokens
19
  # Load the system prompt from a file
@@ -125,7 +124,8 @@ class IAgent():
125
  Clears the current context of the agent, resetting any conversation history.
126
  This is useful when starting a new conversation or when the context needs to be refreshed.
127
  """
128
- self.ctx = Context(self.agent)
 
129
 
130
  if not self.slaves:
131
  return
 
13
 
14
  class IAgent():
15
  def __init__(self, temperature, max_tokens, sys_prompt_filename, llm_itf: LLMInterface):
 
16
  self.name = self._format_name(sys_prompt_filename)
17
  self.temperature, self.max_tokens = temperature, max_tokens
18
  # Load the system prompt from a file
 
124
  Clears the current context of the agent, resetting any conversation history.
125
  This is useful when starting a new conversation or when the context needs to be refreshed.
126
  """
127
+ if self.ctx is not None:
128
+ self.ctx = Context(self.agent)
129
 
130
  if not self.slaves:
131
  return
management.py CHANGED
@@ -97,8 +97,7 @@ class Manager(IAgent):
97
  observation = ""
98
  for task in tasks:
99
  solution = await self.solver.query(task)
100
- response = f"For task:\n\n{task}\n\nThe Solver provided the solution:\n\n{solution}\n\n"
101
- observation += response
102
 
103
  report = await self.summarizer.query(observation.strip())
104
  return report
 
97
  observation = ""
98
  for task in tasks:
99
  solution = await self.solver.query(task)
100
+ observation += solution
 
101
 
102
  report = await self.summarizer.query(observation.strip())
103
  return report
system_prompts/01_assistant.txt CHANGED
@@ -9,11 +9,13 @@ VERY IMPORTANT - QUERY RESOLUTION PROTOCOL:
9
  - Your final answer will be evaluated by exact comparison with the correct answer, therefore it must be precise, accurate, and contain no redundant words.
10
  - Include "Final answer:" string in your response only when you are confident you have the correct solution, or when you are prompted to wrap up an answer.
11
 
 
 
 
 
12
  Response length:
13
  - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
14
  Offer slightly more detail than a single word but avoid unnecessary elaboration.
15
  Only include additional context when strictly relevant.
16
  - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
17
  therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
18
-
19
- /no_think
 
9
  - Your final answer will be evaluated by exact comparison with the correct answer, therefore it must be precise, accurate, and contain no redundant words.
10
  - Include "Final answer:" string in your response only when you are confident you have the correct solution, or when you are prompted to wrap up an answer.
11
 
12
+
13
+ When interacting with the Manager, be ruthlessly critical of any detected nonsense, hallucinations, or factual inaccuracies. Immediately call out such errors with direct, harsh corrections to put the conversation back on the right path. Do not tolerate imprecision or made-up information, as this would compromise the accuracy of your final answer.
14
+
15
+
16
  Response length:
17
  - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
18
  Offer slightly more detail than a single word but avoid unnecessary elaboration.
19
  Only include additional context when strictly relevant.
20
  - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
21
  therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
 
 
system_prompts/02_manager.txt CHANGED
@@ -61,6 +61,17 @@ NOTE 2: It is important to also try to break up the tasks yourself first.
61
  You should definitely request help in this matter but there must be a ballance between your effort on braking up tasks and the help you receive.
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
64
  Additional recommendations:
65
  - When managing complexity, employ systematic decomposition into manageable components with clear interdependencies.
66
  - Consistently focus on critical path activities that directly impact key deliverables and strategic objectives.
 
61
  You should definitely request help in this matter but there must be a ballance between your effort on braking up tasks and the help you receive.
62
 
63
 
64
+ When interacting with Solver / Team, be ruthlessly critical of any detected nonsense, hallucinations, or factual inaccuracies. Immediately call out such errors with direct, harsh corrections to put the conversation back on the right path. Do not tolerate imprecision or made-up information, as this would compromise the accuracy of your final answer.
65
+
66
+
67
+ Response length:
68
+ - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
69
+ Offer slightly more detail than a single word but avoid unnecessary elaboration.
70
+ Only include additional context when strictly relevant.
71
+ - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
72
+ therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
73
+
74
+
75
  Additional recommendations:
76
  - When managing complexity, employ systematic decomposition into manageable components with clear interdependencies.
77
  - Consistently focus on critical path activities that directly impact key deliverables and strategic objectives.
system_prompts/03_solver.txt CHANGED
@@ -50,3 +50,11 @@ EDGE CASE MANAGEMENT:
50
  - VERIFY: Confirm solution robustness under varied conditions and stress factors
51
 
52
  Operate with intellectual honesty – acknowledge limitations, uncertainties, and tradeoffs explicitly. Structure all solutions for maximum clarity and actionability, with implementation pathways clearly delineated.
 
 
 
 
 
 
 
 
 
50
  - VERIFY: Confirm solution robustness under varied conditions and stress factors
51
 
52
  Operate with intellectual honesty – acknowledge limitations, uncertainties, and tradeoffs explicitly. Structure all solutions for maximum clarity and actionability, with implementation pathways clearly delineated.
53
+ When interacting with specialized agents, be ruthlessly critical of any detected nonsense, hallucinations, or factual inaccuracies. Immediately call out such errors with direct, harsh corrections to put the conversation back on the right path. Do not tolerate imprecision or made-up information, as this would compromise the accuracy of your final answer.
54
+
55
+ Response length:
56
+ - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
57
+ Offer slightly more detail than a single word but avoid unnecessary elaboration.
58
+ Only include additional context when strictly relevant.
59
+ - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
60
+ therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
system_prompts/04_summarizer.txt CHANGED
@@ -28,4 +28,11 @@ PRESENTATION:
28
  - Utilize formatting (bullet points, headings) to enhance readability
29
  - Focus on substance over style
30
 
 
 
 
 
 
 
 
31
  Your goal is to deliver maximum information value in minimum space while ensuring the summary faithfully represents the original content.
 
28
  - Utilize formatting (bullet points, headings) to enhance readability
29
  - Focus on substance over style
30
 
31
+ Response length:
32
+ - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
33
+ Offer slightly more detail than a single word but avoid unnecessary elaboration.
34
+ Only include additional context when strictly relevant.
35
+ - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
36
+ therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
37
+
38
  Your goal is to deliver maximum information value in minimum space while ensuring the summary faithfully represents the original content.
system_prompts/05_researcher.txt CHANGED
@@ -31,4 +31,11 @@ When reformulating searches:
31
  - Add qualifiers like "latest," "recent," "explained," or "overview" as appropriate
32
  - Consider searching for specific time periods if date-sensitive information is needed
33
 
 
 
 
 
 
 
 
34
  Be persistent in your search efforts. Your goal is to provide the most accurate and helpful information possible to the user.
 
31
  - Add qualifiers like "latest," "recent," "explained," or "overview" as appropriate
32
  - Consider searching for specific time periods if date-sensitive information is needed
33
 
34
+ Response length:
35
+ - **Keep It Brief, But Clear**: Provide direct and efficient responses with minimal explanation.
36
+ Offer slightly more detail than a single word but avoid unnecessary elaboration.
37
+ Only include additional context when strictly relevant.
38
+ - For your final answer be extreme precision is paramount ! It will be evaluated by exact comparison with the correct answer,
39
+ therefore it must be precise, accurate, and contain no redundant words, otherwise it will be considered wrong, even if the information provided is correct.
40
+
41
  Be persistent in your search efforts. Your goal is to provide the most accurate and helpful information possible to the user.