Commit ·
5d282cd
1
Parent(s): 0907ef1
Add detailed logging and minimal answer generation
Browse files- Enhanced agent to provide minimal answers (just numbers/names/dates) without explanation
- Added comprehensive logging of all exchanges between LLM, tools, and agent
- Detailed tool execution logging with inputs and outputs
- Better log formatting with clear section delimiters
- Updated system prompt to emphasize minimal answers
- direct_agent_fixed.py +77 -13
- direct_integration.py +33 -8
direct_agent_fixed.py
CHANGED
|
@@ -455,27 +455,43 @@ When presented with a question:
|
|
| 455 |
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
|
| 456 |
5. If you use research or external information, incorporate it naturally into your response
|
| 457 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
For specialized types of questions:
|
| 459 |
- For YouTube video questions, use the analyze_youtube tool to get information about the video
|
| 460 |
- For image or chess position questions, use the analyze_image tool with either the image URL or a description
|
| 461 |
- For Excel/spreadsheet file questions, use the analyze_excel tool with proper parameters
|
| 462 |
- When calculations are needed, use the calculate tool to ensure accurate results
|
| 463 |
|
| 464 |
-
Be precise and
|
| 465 |
|
| 466 |
def _handle_tool_call(self, tool_calls):
|
| 467 |
results = []
|
| 468 |
|
|
|
|
| 469 |
for tool_call in tool_calls:
|
| 470 |
function_name = tool_call.function.name
|
|
|
|
|
|
|
|
|
|
| 471 |
|
| 472 |
try:
|
| 473 |
function_args = json.loads(tool_call.function.arguments)
|
|
|
|
| 474 |
except Exception as e:
|
|
|
|
|
|
|
| 475 |
results.append({
|
| 476 |
-
"tool_call_id":
|
| 477 |
"function_name": function_name,
|
| 478 |
-
"result":
|
| 479 |
})
|
| 480 |
continue
|
| 481 |
|
|
@@ -483,33 +499,46 @@ Be precise and focus only on answering the question asked. Your final answer sho
|
|
| 483 |
try:
|
| 484 |
# Call the appropriate tool with the arguments
|
| 485 |
if function_name == "analyze_excel":
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
)
|
| 490 |
else:
|
| 491 |
# For all other tools, just pass the first argument
|
| 492 |
first_arg = list(function_args.values())[0] if function_args else ""
|
|
|
|
| 493 |
result = self.tools[function_name].run(first_arg)
|
| 494 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
results.append({
|
| 496 |
-
"tool_call_id":
|
| 497 |
"function_name": function_name,
|
| 498 |
"result": result
|
| 499 |
})
|
| 500 |
except Exception as e:
|
|
|
|
|
|
|
| 501 |
results.append({
|
| 502 |
-
"tool_call_id":
|
| 503 |
"function_name": function_name,
|
| 504 |
-
"result":
|
| 505 |
})
|
| 506 |
else:
|
|
|
|
|
|
|
| 507 |
results.append({
|
| 508 |
-
"tool_call_id":
|
| 509 |
"function_name": function_name,
|
| 510 |
-
"result":
|
| 511 |
})
|
| 512 |
|
|
|
|
| 513 |
return results
|
| 514 |
|
| 515 |
def _call_openrouter_with_retry(self, messages, max_retries=5):
|
|
@@ -517,6 +546,24 @@ Be precise and focus only on answering the question asked. Your final answer sho
|
|
| 517 |
retry_count = 0
|
| 518 |
base_delay = 2 # Start with a 2-second delay
|
| 519 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
while retry_count < max_retries:
|
| 521 |
try:
|
| 522 |
# Call the API
|
|
@@ -540,11 +587,28 @@ Be precise and focus only on answering the question asked. Your final answer sho
|
|
| 540 |
time.sleep(delay)
|
| 541 |
continue
|
| 542 |
|
| 543 |
-
# If we got a valid response, return it
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
return response
|
| 545 |
|
| 546 |
except Exception as e:
|
| 547 |
error_msg = str(e).lower()
|
|
|
|
| 548 |
|
| 549 |
# If it's a rate limit error, retry
|
| 550 |
if "429" in error_msg or "rate limit" in error_msg:
|
|
|
|
| 455 |
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
|
| 456 |
5. If you use research or external information, incorporate it naturally into your response
|
| 457 |
|
| 458 |
+
CRITICAL INSTRUCTION: Your final answer must be as minimal as possible while still being accurate and complete:
|
| 459 |
+
- If the question asks "How many..." just respond with the number
|
| 460 |
+
- If the question asks for a name, just give the name without explanation
|
| 461 |
+
- If the question asks for a date, just give the date
|
| 462 |
+
- If the question asks "Who...", just respond with the person's name
|
| 463 |
+
- If the question asks "Where...", just respond with the location
|
| 464 |
+
- Don't include explanations, reasoning, or citations in your final answer
|
| 465 |
+
- Don't include phrases like "The answer is..." or "I found that..."
|
| 466 |
+
|
| 467 |
For specialized types of questions:
|
| 468 |
- For YouTube video questions, use the analyze_youtube tool to get information about the video
|
| 469 |
- For image or chess position questions, use the analyze_image tool with either the image URL or a description
|
| 470 |
- For Excel/spreadsheet file questions, use the analyze_excel tool with proper parameters
|
| 471 |
- When calculations are needed, use the calculate tool to ensure accurate results
|
| 472 |
|
| 473 |
+
Be extremely precise and minimal in your final answer. The answer should never include your reasoning, citations, or explanations - just the direct answer to the question in as few words as possible."""
|
| 474 |
|
| 475 |
def _handle_tool_call(self, tool_calls):
|
| 476 |
results = []
|
| 477 |
|
| 478 |
+
print("\n=== TOOL EXECUTION ===")
|
| 479 |
for tool_call in tool_calls:
|
| 480 |
function_name = tool_call.function.name
|
| 481 |
+
tool_call_id = tool_call.id
|
| 482 |
+
|
| 483 |
+
print(f"EXECUTING TOOL: {function_name} [id: {tool_call_id}]")
|
| 484 |
|
| 485 |
try:
|
| 486 |
function_args = json.loads(tool_call.function.arguments)
|
| 487 |
+
print(f"ARGUMENTS: {json.dumps(function_args, indent=2)}")
|
| 488 |
except Exception as e:
|
| 489 |
+
error_msg = f"Error parsing arguments: {str(e)}"
|
| 490 |
+
print(f"ERROR: {error_msg}")
|
| 491 |
results.append({
|
| 492 |
+
"tool_call_id": tool_call_id,
|
| 493 |
"function_name": function_name,
|
| 494 |
+
"result": error_msg
|
| 495 |
})
|
| 496 |
continue
|
| 497 |
|
|
|
|
| 499 |
try:
|
| 500 |
# Call the appropriate tool with the arguments
|
| 501 |
if function_name == "analyze_excel":
|
| 502 |
+
file_path = function_args.get("file_path", "")
|
| 503 |
+
query = function_args.get("query", "")
|
| 504 |
+
print(f"EXCEL ANALYSIS: file={file_path}, query={query}")
|
| 505 |
+
result = self.tools[function_name].run(file_path, query)
|
| 506 |
else:
|
| 507 |
# For all other tools, just pass the first argument
|
| 508 |
first_arg = list(function_args.values())[0] if function_args else ""
|
| 509 |
+
print(f"TOOL INPUT: {first_arg}")
|
| 510 |
result = self.tools[function_name].run(first_arg)
|
| 511 |
|
| 512 |
+
# Truncate result for logging if it's too long
|
| 513 |
+
result_preview = result
|
| 514 |
+
if len(result_preview) > 500:
|
| 515 |
+
result_preview = result_preview[:497] + "..."
|
| 516 |
+
|
| 517 |
+
print(f"TOOL RESULT: {result_preview}")
|
| 518 |
+
|
| 519 |
results.append({
|
| 520 |
+
"tool_call_id": tool_call_id,
|
| 521 |
"function_name": function_name,
|
| 522 |
"result": result
|
| 523 |
})
|
| 524 |
except Exception as e:
|
| 525 |
+
error_msg = f"Error executing tool {function_name}: {str(e)}"
|
| 526 |
+
print(f"ERROR: {error_msg}")
|
| 527 |
results.append({
|
| 528 |
+
"tool_call_id": tool_call_id,
|
| 529 |
"function_name": function_name,
|
| 530 |
+
"result": error_msg
|
| 531 |
})
|
| 532 |
else:
|
| 533 |
+
error_msg = f"Tool {function_name} not found"
|
| 534 |
+
print(f"ERROR: {error_msg}")
|
| 535 |
results.append({
|
| 536 |
+
"tool_call_id": tool_call_id,
|
| 537 |
"function_name": function_name,
|
| 538 |
+
"result": error_msg
|
| 539 |
})
|
| 540 |
|
| 541 |
+
print("======================\n")
|
| 542 |
return results
|
| 543 |
|
| 544 |
def _call_openrouter_with_retry(self, messages, max_retries=5):
|
|
|
|
| 546 |
retry_count = 0
|
| 547 |
base_delay = 2 # Start with a 2-second delay
|
| 548 |
|
| 549 |
+
# Log the messages being sent to the LLM
|
| 550 |
+
print("\n=== SENDING TO LLM ===")
|
| 551 |
+
for msg in messages:
|
| 552 |
+
role = msg.get("role", "unknown")
|
| 553 |
+
content = msg.get("content", "")
|
| 554 |
+
|
| 555 |
+
# Truncate content for readability if it's too long
|
| 556 |
+
if content and len(content) > 500:
|
| 557 |
+
content = content[:497] + "..."
|
| 558 |
+
|
| 559 |
+
# Handle tool messages specially
|
| 560 |
+
if role == "tool":
|
| 561 |
+
tool_call_id = msg.get("tool_call_id", "unknown")
|
| 562 |
+
print(f"TOOL RESPONSE [id: {tool_call_id}]: {content}")
|
| 563 |
+
else:
|
| 564 |
+
print(f"{role.upper()}: {content}")
|
| 565 |
+
print("=======================\n")
|
| 566 |
+
|
| 567 |
while retry_count < max_retries:
|
| 568 |
try:
|
| 569 |
# Call the API
|
|
|
|
| 587 |
time.sleep(delay)
|
| 588 |
continue
|
| 589 |
|
| 590 |
+
# If we got a valid response, log it and return it
|
| 591 |
+
if hasattr(response, 'choices') and response.choices and hasattr(response.choices[0], 'message'):
|
| 592 |
+
message = response.choices[0].message
|
| 593 |
+
|
| 594 |
+
print("\n=== LLM RESPONSE ===")
|
| 595 |
+
if hasattr(message, 'content') and message.content:
|
| 596 |
+
print(f"CONTENT: {message.content}")
|
| 597 |
+
|
| 598 |
+
if hasattr(message, 'tool_calls') and message.tool_calls:
|
| 599 |
+
print(f"TOOL CALLS [{len(message.tool_calls)}]:")
|
| 600 |
+
for tool_call in message.tool_calls:
|
| 601 |
+
function_name = tool_call.function.name
|
| 602 |
+
function_args = tool_call.function.arguments
|
| 603 |
+
print(f" - {function_name}({function_args})")
|
| 604 |
+
print("====================\n")
|
| 605 |
+
|
| 606 |
+
# Return the response
|
| 607 |
return response
|
| 608 |
|
| 609 |
except Exception as e:
|
| 610 |
error_msg = str(e).lower()
|
| 611 |
+
print(f"API ERROR: {error_msg}")
|
| 612 |
|
| 613 |
# If it's a rate limit error, retry
|
| 614 |
if "429" in error_msg or "rate limit" in error_msg:
|
direct_integration.py
CHANGED
|
@@ -122,22 +122,47 @@ def run_agent_on_questions(questions):
|
|
| 122 |
def __call__(self, question, context=None):
|
| 123 |
# Create a custom handler to capture the agent's output
|
| 124 |
class AgentOutputHandler:
|
|
|
|
|
|
|
|
|
|
| 125 |
def write(self, message):
|
| 126 |
if message.strip(): # Only log non-empty lines
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
# Set up a custom handler to capture standard output
|
| 130 |
import sys
|
| 131 |
-
|
| 132 |
-
|
| 133 |
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
# Call the actual agent
|
| 136 |
result = self.agent(question, context)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
# Create the logging agent
|
| 143 |
logging_agent = LoggingAgent(agent)
|
|
|
|
| 122 |
def __call__(self, question, context=None):
|
| 123 |
# Create a custom handler to capture the agent's output
|
| 124 |
class AgentOutputHandler:
|
| 125 |
+
def __init__(self):
|
| 126 |
+
self.buffer = []
|
| 127 |
+
|
| 128 |
def write(self, message):
|
| 129 |
if message.strip(): # Only log non-empty lines
|
| 130 |
+
# Log directly to file and preserve in buffer
|
| 131 |
+
self.buffer.append(message.strip())
|
| 132 |
+
|
| 133 |
+
# Use different log levels based on content
|
| 134 |
+
if message.startswith("==="):
|
| 135 |
+
logger.info(message.strip())
|
| 136 |
+
elif "ERROR" in message:
|
| 137 |
+
logger.error(message.strip())
|
| 138 |
+
else:
|
| 139 |
+
logger.debug(message.strip())
|
| 140 |
+
|
| 141 |
+
def flush(self):
|
| 142 |
+
pass
|
| 143 |
|
| 144 |
# Set up a custom handler to capture standard output
|
| 145 |
import sys
|
| 146 |
+
import io
|
| 147 |
+
from contextlib import redirect_stdout
|
| 148 |
|
| 149 |
+
output_handler = AgentOutputHandler()
|
| 150 |
+
|
| 151 |
+
# Create a StringIO object to capture all output
|
| 152 |
+
string_output = io.StringIO()
|
| 153 |
+
|
| 154 |
+
# Use contextlib to redirect stdout to both our handlers
|
| 155 |
+
with redirect_stdout(output_handler):
|
| 156 |
# Call the actual agent
|
| 157 |
result = self.agent(question, context)
|
| 158 |
+
|
| 159 |
+
# Create an all-caps delimiter for the final answer
|
| 160 |
+
logger.info("=" * 80)
|
| 161 |
+
logger.info("FINAL MINIMAL ANSWER:")
|
| 162 |
+
logger.info(result)
|
| 163 |
+
logger.info("=" * 80)
|
| 164 |
+
|
| 165 |
+
return result
|
| 166 |
|
| 167 |
# Create the logging agent
|
| 168 |
logging_agent = LoggingAgent(agent)
|