Final_Assignment_Template / direct_agent_fixed.py
murphynetworks's picture
Add colorful, detailed logging for better visibility
bd83de1
Raw History Blame Contribute Delete
40.9 kB
#!/usr/bin/env python3
import os
import json
import time
import requests
import pandas as pd
from openai import OpenAI
from bs4 import BeautifulSoup
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class WebSearchTool:
def run(self, query):
try:
# Use a search engine API to get results
response = requests.get(
f"https://www.google.com/search?q={query}",
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"}
)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
search_results = []
# Extract search results
for result in soup.select(".tF2Cxc"):
title = result.select_one(".DKV0Md").text if result.select_one(".DKV0Md") else ""
link = result.select_one("a")["href"] if result.select_one("a") else ""
snippet = result.select_one(".VwiC3b").text if result.select_one(".VwiC3b") else ""
if title and link:
search_results.append({
"title": title,
"link": link,
"snippet": snippet
})
# Format results into a readable string
if search_results:
formatted_results = "\n\n".join([
f"Title: {r['title']}\nURL: {r['link']}\nSnippet: {r['snippet']}"
for r in search_results[:5] # Limit to top 5 results
])
return f"Search results for '{query}':\n\n{formatted_results}"
else:
return f"No results found for '{query}'."
except Exception as e:
return f"Error searching the web: {str(e)}"
class YouTubeTranscriptionTool:
def run(self, url):
"""Attempt to get a summary or transcript of a YouTube video."""
try:
if "youtube.com" not in url and "youtu.be" not in url:
return f"Error: The URL provided does not appear to be a YouTube link: {url}"
# Extract video ID from the URL
video_id = None
if "youtube.com/watch" in url and "v=" in url:
video_id = url.split("v=")[1].split("&")[0]
elif "youtu.be/" in url:
video_id = url.split("youtu.be/")[1].split("?")[0]
if not video_id:
return f"Error: Could not extract video ID from URL: {url}"
# First, try to get video info from the YouTube API
video_info_url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=snippet&key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
try:
response = requests.get(video_info_url)
response.raise_for_status()
data = response.json()
if "items" in data and len(data["items"]) > 0:
title = data["items"][0]["snippet"]["title"]
description = data["items"][0]["snippet"]["description"]
channel = data["items"][0]["snippet"]["channelTitle"]
published_at = data["items"][0]["snippet"]["publishedAt"]
# Try to get transcripts (this is just a fallback as YouTube doesn't provide transcripts via API)
web_search = WebSearchTool()
transcript_results = web_search.run(f"youtube transcript {title} {channel}")
return f"""YouTube Video Information:
Title: {title}
Channel: {channel}
Published: {published_at}
Description: {description[:500]}{"..." if len(description) > 500 else ""}
Video URL: {url}
Video ID: {video_id}
Transcript Search Results:
{transcript_results}
"""
else:
return f"No information found for video ID: {video_id}"
except Exception as api_error:
# Fallback to web scraping if the API fails
try:
response = requests.get(url, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
})
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.select_one("meta[property='og:title']")["content"] if soup.select_one("meta[property='og:title']") else "Unknown Title"
return f"""YouTube Video:
Title: {title}
URL: {url}
I was unable to retrieve the transcript automatically. Here's what you can do:
1. Check if the video has captions available on YouTube
2. Try to find a summary or transcript of this video through a web search
3. Look for information about the video content in the video description or comments
"""
except Exception as scrape_error:
return f"Error extracting YouTube video information: {str(scrape_error)}\nAPI Error: {str(api_error)}"
except Exception as e:
return f"Error processing YouTube URL: {str(e)}"
class ImageAnalysisTool:
def run(self, image_url_or_description):
"""Analyze an image or process an image description."""
try:
# Check if the input is a URL
if image_url_or_description.startswith(('http://', 'https://')):
try:
# Try to download the image
response = requests.get(image_url_or_description, timeout=10)
response.raise_for_status()
# Check if it's an image
content_type = response.headers.get('Content-Type', '')
if 'image' not in content_type:
return f"The URL does not point to an image. Content-Type: {content_type}"
# For a real implementation, here you would use Vision APIs
# Since we can't do that, we'll provide information about the image
image_size = len(response.content)
return f"""
Image Analysis:
URL: {image_url_or_description}
Size: {image_size} bytes
Content-Type: {content_type}
I can't view the image directly, but based on the URL and metadata, this appears to be a valid image.
To analyze the specific content, please provide a description of what you see in the image, and I can help interpret it.
"""
except Exception as url_error:
return f"Error accessing image URL: {str(url_error)}"
else:
# If it's not a URL, treat it as a description
return f"""
Based on the description: "{image_url_or_description}"
I'll analyze this as a text description rather than a direct image. If you're describing a chess position,
please format it using standard chess notation (e.g., FEN notation like "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").
For other types of images, please provide details about what you see in the image, and I can help interpret the content.
"""
except Exception as e:
return f"Error analyzing image: {str(e)}"
class WebBrowseTool:
def run(self, url):
try:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.extract()
# Get text
text = soup.get_text()
# Clean up text: break into lines and remove leading and trailing space
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
# Limit text length to avoid LLM context limitations
if len(text) > 8000:
text = text[:8000] + "...\n[Content truncated due to length]"
return f"Content from {url}:\n\n{text}"
except Exception as e:
return f"Error accessing {url}: {str(e)}"
class ReadFileTool:
def run(self, file_path):
try:
if not os.path.exists(file_path):
return f"Error: File not found at {file_path}"
with open(file_path, 'rb') as f:
content = f.read()
# Try to decode as text
try:
text_content = content.decode('utf-8')
return f"Content of {file_path}:\n\n{text_content}"
except UnicodeDecodeError:
# If it's not text, just return info about the binary file
return f"Binary file {file_path}, size: {len(content)} bytes"
except Exception as e:
return f"Error reading file: {str(e)}"
class CalculateTool:
def run(self, expression):
try:
# Be very careful with eval - in production this should be replaced with a safer alternative
result = eval(expression, {"__builtins__": {}})
return f"Result: {result}"
except Exception as e:
return f"Error calculating '{expression}': {str(e)}"
class AnalyzeExcelTool:
def run(self, file_path, query):
try:
if not os.path.exists(file_path):
return f"Error: File not found at {file_path}"
# Read the Excel file
try:
df = pd.read_excel(file_path)
except Exception as e:
# Try with different engine if default fails
try:
df = pd.read_excel(file_path, engine='openpyxl')
except Exception as e2:
try:
df = pd.read_excel(file_path, engine='xlrd')
except Exception as e3:
return f"Error reading Excel file: {str(e)}, {str(e2)}, {str(e3)}"
# Basic info about the Excel file
file_info = f"Excel file contains {len(df.columns)} columns and {len(df)} rows.\n"
file_info += f"Columns: {', '.join(df.columns.tolist())}\n"
# Sample of the data
sample = df.head(5).to_string()
# Try to answer specific query about the data
query_lower = query.lower()
# Handle sum queries
if "sum" in query_lower or "total" in query_lower:
# Try to identify which column(s) to sum based on the query
numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
column_sums = {}
for col in numeric_cols:
column_sums[col] = df[col].sum()
sums_info = "Sum of numeric columns:\n"
for col, total in column_sums.items():
sums_info += f"Sum of {col}: {total}\n"
return f"{file_info}\n\n{sample}\n\n{sums_info}"
# Handle filter queries
elif "filter" in query_lower or "where" in query_lower or "only" in query_lower:
# This is a simple example - in a real implementation,
# you would use NLP to understand the filter conditions
filter_info = "To filter data, please specify the exact column and condition."
return f"{file_info}\n\n{sample}\n\n{filter_info}"
# Default response with file overview
else:
return f"{file_info}\n\nSample data:\n{sample}"
except Exception as e:
return f"Error analyzing Excel file: {str(e)}"
class DirectAgent:
def __init__(self, openrouter_api_key=None, model=None):
self.api_key = openrouter_api_key or os.getenv("OPENROUTER_API_KEY")
self.model = model or os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
if not self.api_key:
raise ValueError("OpenRouter API key not provided and OPENROUTER_API_KEY not set in environment variables.")
# Initialize client
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=self.api_key,
default_headers={
"HTTP-Referer": "https://github.com/neuralconfig/agents-course",
"X-Title": "Agent Evaluation"
}
)
# Initialize tools
self.tools = {
"web_search": WebSearchTool(),
"web_browse": WebBrowseTool(),
"read_file": ReadFileTool(),
"calculate": CalculateTool(),
"analyze_excel": AnalyzeExcelTool(),
"analyze_youtube": YouTubeTranscriptionTool(),
"analyze_image": ImageAnalysisTool()
}
# Tool descriptions for the LLM
self.tool_descriptions = [
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for information on a given query.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "web_browse",
"description": "Visit a webpage and extract its content.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL of the webpage to visit"
}
},
"required": ["url"]
}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read the content of a file.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path to the file to read"
}
},
"required": ["file_path"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Perform a calculation.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Mathematical expression to evaluate"
}
},
"required": ["expression"]
}
}
},
{
"type": "function",
"function": {
"name": "analyze_excel",
"description": "Analyze an Excel file and extract data.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the Excel file"
},
"query": {
"type": "string",
"description": "What analysis to perform on the data"
}
},
"required": ["file_path", "query"]
}
}
},
{
"type": "function",
"function": {
"name": "analyze_youtube",
"description": "Analyze a YouTube video to get information and potentially its transcript.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The YouTube video URL"
}
},
"required": ["url"]
}
}
},
{
"type": "function",
"function": {
"name": "analyze_image",
"description": "Analyze an image from a URL or a description of an image (like a chess position).",
"parameters": {
"type": "object",
"properties": {
"image_url_or_description": {
"type": "string",
"description": "The URL of the image or a description of the image content"
}
},
"required": ["image_url_or_description"]
}
}
}
]
# System message
self.system_message = """You are a helpful AI assistant designed to answer questions accurately.
When presented with a question:
1. Think carefully about what is being asked
2. Use the provided tools when necessary to gather accurate information
3. Provide clear, concise answers based on the information available
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
5. If you use research or external information, incorporate it naturally into your response
CRITICAL INSTRUCTION: Your final answer MUST be EXTREMELY minimal. The evaluation system expects the shortest possible answer:
- For "How many..." questions: JUST THE NUMBER with no words (e.g., "2" not "2 albums")
- For name questions: JUST THE NAME with no context (e.g., "John Smith" not "The person is John Smith")
- For date questions: JUST THE DATE with no explanation (e.g., "1995" not "It happened in 1995")
- For "Who..." questions: JUST THE NAME(S) (e.g., "Marie Curie" not "The scientist was Marie Curie")
- For "Where..." questions: JUST THE LOCATION (e.g., "Paris" not "It's located in Paris")
- For sets/lists: JUST THE ITEMS with minimal formatting (e.g., "a,b,c" or "a, b, c")
- For yes/no questions: JUST "Yes" or "No" (not "Yes, because...")
DO NOT INCLUDE:
- Explanations or reasoning
- Your thought process
- Citations or references
- Introductory phrases like "The answer is..."
- Confidence statements like "I believe..."
- Context or background information
- Multiple possible answers (choose the most likely one)
For specialized types of questions:
- For YouTube video questions, use the analyze_youtube tool to get information about the video
- For image or chess position questions, use the analyze_image tool with either the image URL or a description
- For Excel/spreadsheet file questions, use the analyze_excel tool with proper parameters
- When calculations are needed, use the calculate tool to ensure accurate results
THE FINAL ANSWER MUST BE EXTREMELY MINIMAL - think of it as filling in a blank or answering a multiple-choice test. Your reasoning is valuable during your investigation, but your final response should ONLY contain the direct answer with nothing else."""
def _handle_tool_call(self, tool_calls):
results = []
# ANSI color codes for terminal output
COLORS = {
"RED": "\033[91m",
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"BLUE": "\033[94m",
"MAGENTA": "\033[95m",
"CYAN": "\033[96m",
"WHITE": "\033[97m",
"BOLD": "\033[1m",
"RESET": "\033[0m"
}
print(f"\n{COLORS['BOLD']}{COLORS['YELLOW']}=== TOOL EXECUTION ==={COLORS['RESET']}")
for tool_call in tool_calls:
function_name = tool_call.function.name
tool_call_id = tool_call.id
print(f"{COLORS['BOLD']}EXECUTING TOOL: {COLORS['YELLOW']}{function_name}{COLORS['RESET']} [id: {tool_call_id}]")
try:
function_args = json.loads(tool_call.function.arguments)
print(f"{COLORS['YELLOW']}ARGUMENTS:{COLORS['RESET']} {json.dumps(function_args, indent=2)}")
except Exception as e:
error_msg = f"Error parsing arguments: {str(e)}"
print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
results.append({
"tool_call_id": tool_call_id,
"function_name": function_name,
"result": error_msg
})
continue
if function_name in self.tools:
try:
# Call the appropriate tool with the arguments
if function_name == "analyze_excel":
file_path = function_args.get("file_path", "")
query = function_args.get("query", "")
print(f"{COLORS['YELLOW']}EXCEL ANALYSIS:{COLORS['RESET']} file={file_path}, query={query}")
result = self.tools[function_name].run(file_path, query)
else:
# For all other tools, just pass the first argument
first_arg = list(function_args.values())[0] if function_args else ""
print(f"{COLORS['YELLOW']}TOOL INPUT [{function_name}]:{COLORS['RESET']} {first_arg}")
result = self.tools[function_name].run(first_arg)
# Truncate result for logging if it's too long
result_preview = result
if len(result_preview) > 1000:
result_preview = result_preview[:997] + "..."
print(f"{COLORS['GREEN']}TOOL RESULT [{function_name}]:{COLORS['RESET']} {result_preview}")
results.append({
"tool_call_id": tool_call_id,
"function_name": function_name,
"result": result
})
except Exception as e:
error_msg = f"Error executing tool {function_name}: {str(e)}"
print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
results.append({
"tool_call_id": tool_call_id,
"function_name": function_name,
"result": error_msg
})
else:
error_msg = f"Tool {function_name} not found"
print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
results.append({
"tool_call_id": tool_call_id,
"function_name": function_name,
"result": error_msg
})
print(f"{COLORS['YELLOW']}======================={COLORS['RESET']}\n")
return results
def _call_openrouter_with_retry(self, messages, max_retries=5):
"""Call the OpenRouter API with retry logic for rate limits."""
retry_count = 0
base_delay = 2 # Start with a 2-second delay
# ANSI color codes for terminal output
COLORS = {
"RED": "\033[91m",
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"BLUE": "\033[94m",
"MAGENTA": "\033[95m",
"CYAN": "\033[96m",
"WHITE": "\033[97m",
"BOLD": "\033[1m",
"RESET": "\033[0m"
}
# Log the messages being sent to the LLM
print(f"\n{COLORS['BOLD']}{COLORS['MAGENTA']}=== SENDING TO LLM ==={COLORS['RESET']}")
for msg in messages:
role = msg.get("role", "unknown")
content = msg.get("content", "")
# Truncate content for readability if it's too long
if content and len(content) > 1000:
content = content[:997] + "..."
# Handle tool messages specially
if role == "tool":
tool_call_id = msg.get("tool_call_id", "unknown")
print(f"{COLORS['YELLOW']}TOOL RESPONSE [{tool_call_id}]:{COLORS['RESET']} {content}")
elif role == "system":
print(f"{COLORS['BLUE']}SYSTEM:{COLORS['RESET']} {content}")
elif role == "user":
print(f"{COLORS['GREEN']}USER:{COLORS['RESET']} {content}")
elif role == "assistant":
print(f"{COLORS['CYAN']}ASSISTANT:{COLORS['RESET']} {content}")
else:
print(f"{role.upper()}: {content}")
print(f"{COLORS['MAGENTA']}======================={COLORS['RESET']}\n")
while retry_count < max_retries:
try:
# Call the API
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
tools=self.tool_descriptions,
tool_choice="auto"
)
# Check for error object directly in the response
if hasattr(response, 'error') and response.error:
error_code = response.error.get('code')
error_msg = response.error.get('message', '')
# If it's a rate limit error, retry
if error_code == 429 or "rate limit" in error_msg.lower():
retry_count += 1
delay = base_delay * (2 ** retry_count) # Exponential backoff
print(f"Rate limit hit. Retrying in {delay} seconds...")
time.sleep(delay)
continue
# If we got a valid response, log it and return it
if hasattr(response, 'choices') and response.choices and hasattr(response.choices[0], 'message'):
message = response.choices[0].message
print(f"\n{COLORS['BOLD']}{COLORS['CYAN']}=== LLM RESPONSE ==={COLORS['RESET']}")
if hasattr(message, 'content') and message.content:
print(f"{COLORS['CYAN']}CONTENT:{COLORS['RESET']} {message.content}")
if hasattr(message, 'tool_calls') and message.tool_calls:
print(f"{COLORS['BOLD']}{COLORS['YELLOW']}TOOL CALLS [{len(message.tool_calls)}]:{COLORS['RESET']}")
for tool_call in message.tool_calls:
function_name = tool_call.function.name
function_args = tool_call.function.arguments
print(f"{COLORS['YELLOW']} → {function_name}({function_args}){COLORS['RESET']}")
print(f"{COLORS['CYAN']}===================={COLORS['RESET']}\n")
# Return the response
return response
except Exception as e:
error_msg = str(e).lower()
print(f"API ERROR: {error_msg}")
# If it's a rate limit error, retry
if "429" in error_msg or "rate limit" in error_msg:
retry_count += 1
delay = base_delay * (2 ** retry_count) # Exponential backoff
print(f"Rate limit hit. Retrying in {delay} seconds...")
time.sleep(delay)
else:
# For other errors, raise immediately
raise
# If we've exhausted retries, raise an exception
raise Exception(f"Failed after {max_retries} retries due to rate limits")
def _enforce_minimal_answer(self, answer, question):
"""Enforce minimal answer requirements by post-processing the LLM's response."""
# Check if the answer already looks minimal (very short)
if len(answer.strip()) <= 20:
# Already seems minimal, but clean up any extra text
minimal = answer.strip()
# Remove phrases like "the answer is"
for phrase in ["the answer is", "i believe", "i think", "i found", "the result is"]:
if minimal.lower().startswith(phrase):
minimal = minimal[len(phrase):].strip()
# Remove any leading colon or punctuation
minimal = minimal.lstrip(":,.;").strip()
return minimal
# Try to extract just the answer based on question type
question_lower = question.lower()
# For "how many" questions - extract just the number
if "how many" in question_lower:
import re
# Look for numbers in the answer
numbers = re.findall(r'\b\d+\b', answer)
if numbers:
return numbers[0] # Return the first number found
# For "who" questions - try to extract just the name
if question_lower.startswith("who"):
# Look for capitalized words which might be names
lines = answer.strip().split('\n')
if len(lines) > 0:
# Return first line, or if it's too long, first sentence
first_line = lines[0]
if len(first_line) > 100:
sentences = first_line.split('.')
return sentences[0].strip()
return first_line
# For lists or sets
if 'subset' in question_lower or 'list' in question_lower or 'set' in question_lower:
lines = answer.strip().split('\n')
for line in lines:
line = line.strip()
if ',' in line and len(line) < 50:
return line
# If we can't find a simple comma-separated list,
# look for the last line that might contain the answer
for line in reversed(lines):
line = line.strip()
if line and len(line) < 100:
return line
# For yes/no questions
if question_lower.startswith("is ") or question_lower.startswith("are ") or question_lower.startswith("does ") or question_lower.startswith("can "):
if "yes" in answer.lower()[:20]:
return "Yes"
if "no" in answer.lower()[:20]:
return "No"
# For questions with obvious lists at the end
lines = answer.strip().split('\n')
if len(lines) > 2:
last_line = lines[-1].strip()
if last_line and len(last_line) < 100:
return last_line
# If all else fails, just return the first line/sentence
lines = answer.strip().split('\n')
if lines:
first_line = lines[0].strip()
if len(first_line) > 100:
sentences = first_line.split('.')
return sentences[0].strip()
return first_line
# Fallback: just return the answer as is
return answer.strip()
def __call__(self, question, context=None):
"""Run the agent on a question and return the answer."""
# Add context about any files if provided
if context and "file_path" in context:
file_path = context.get("file_path", "")
file_name = context.get("file_name", "")
# Try to determine the file type
file_extension = file_path.lower().split(".")[-1] if "." in file_path else ""
if file_extension in ["xlsx", "xls", "csv"]:
question += f"\n\nAttached file information: {file_name} (Excel/spreadsheet file)"
question += f"\nYou can analyze this spreadsheet using the analyze_excel tool with the path: {file_path}"
question += f"\nFor example: analyze_excel('{file_path}', 'What is the total sales?')"
else:
question += f"\n\nAttached file information: {file_name}"
question += f"\nYou can access this file using the read_file tool with the path: {file_path}"
# Add a special instruction to enforce minimal answers
extra_instruction = """
FINAL REMINDER: Your answer must be MINIMAL. Return ONLY the specific information requested without any explanation.
- For "How many" questions: ONLY return the number
- For "Who/what/where" questions: ONLY return the name/item/location
- For lists: ONLY return the items in a simple comma-separated format (e.g., "A, B, C")
- NEVER include your reasoning, context, or explanations
"""
# Add the question and special reminder
user_prompt = f"{question}\n\n{extra_instruction}"
messages = [
{"role": "system", "content": self.system_message},
{"role": "user", "content": user_prompt}
]
max_steps = 10 # Increased the number of iterations for more complex questions
for step in range(max_steps):
print(f"Step {step+1}/{max_steps}")
try:
# Call the API with retry logic
response = self._call_openrouter_with_retry(messages)
# Debug info
print(f"Response received, type: {type(response)}")
# Get the response message - with improved error handling
if not hasattr(response, 'choices') or not response.choices:
print("Error: No choices in response")
print(f"Full response: {response}")
return "Error: Invalid response from OpenRouter API - no choices returned"
# Check if response.choices[0] exists and has a message
if len(response.choices) == 0 or not hasattr(response.choices[0], 'message'):
print("Error: No message in first choice")
print(f"Full response: {response}")
return "Error: Invalid response from OpenRouter API - no message in first choice"
message = response.choices[0].message
messages.append(message)
# Check if there are tool calls
if hasattr(message, 'tool_calls') and message.tool_calls:
print(f"Tool calls detected: {len(message.tool_calls)}")
# Execute the tool calls
tool_results = self._handle_tool_call(message.tool_calls)
# Add the tool results to the messages
for result in tool_results:
tool_message = {
"role": "tool",
"tool_call_id": result["tool_call_id"],
"content": result["result"]
}
messages.append(tool_message)
print(f"Tool {result['function_name']} executed")
else:
# No more tool calls, we have the final answer
if not hasattr(message, 'content'):
print("Error: Message has no content attribute")
return "Error: Invalid response from OpenRouter API - message has no content"
# Apply post-processing to extract a minimal answer
original_answer = message.content
minimal_answer = self._enforce_minimal_answer(original_answer, question)
# ANSI color codes for terminal output
COLORS = {
"RED": "\033[91m",
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"BLUE": "\033[94m",
"MAGENTA": "\033[95m",
"CYAN": "\033[96m",
"WHITE": "\033[97m",
"BOLD": "\033[1m",
"RESET": "\033[0m"
}
print(f"\n{COLORS['BOLD']}{COLORS['WHITE']}=== ANSWER PROCESSING ==={COLORS['RESET']}")
print(f"{COLORS['CYAN']}ORIGINAL ANSWER:{COLORS['RESET']}\n{original_answer}")
print(f"\n{COLORS['BOLD']}{COLORS['GREEN']}MINIMAL ANSWER:{COLORS['RESET']} {minimal_answer}")
print(f"{COLORS['WHITE']}========================={COLORS['RESET']}\n")
return minimal_answer
except Exception as e:
print(f"Error in step {step+1}: {str(e)}")
# Try to recover and continue with what we have
if messages and len(messages) > 2:
last_message = messages[-1]
if isinstance(last_message, dict) and 'content' in last_message:
content = last_message['content']
return self._enforce_minimal_answer(content, question)
elif hasattr(last_message, 'content') and last_message.content:
content = last_message.content
return self._enforce_minimal_answer(content, question)
return f"Error: {str(e)}"
# If we've reached the maximum number of steps, return the last message
if messages and len(messages) > 1:
last_message = messages[-1]
if isinstance(last_message, dict) and 'content' in last_message:
content = last_message['content']
return self._enforce_minimal_answer(content, question)
elif hasattr(last_message, 'content') and last_message.content:
content = last_message.content
return self._enforce_minimal_answer(content, question)
return "Error: Reached maximum steps without getting a final answer"
# Test code
if __name__ == "__main__":
# Get model from environment variables or default to Claude
model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
print(f"\n=== Testing with model from .env: {model} ===\n")
# Create the agent with the model from .env
agent = DirectAgent()
# Test questions
questions = [
"What is the capital of France?",
"What is 25 * 4 + 10?",
"What is the largest mammal on Earth?"
]
# Test each question
for question in questions:
print(f"\nQuestion: {question}")
try:
answer = agent(question)
print(f"\nAnswer: {answer}")
except Exception as e:
print(f"\nError: {str(e)}")
print("\n=== Testing complete ===")