File size: 8,035 Bytes
c8fd33f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""Utility functions for GAIA Benchmark Agent including retry logic and answer cleanup."""

import re
import time
import requests
from typing import Callable, Any
from functools import wraps
import config


def retry_with_backoff(
    max_retries: int = config.MAX_RETRIES,
    initial_delay: float = config.INITIAL_RETRY_DELAY,
    backoff_factor: float = config.RETRY_BACKOFF_FACTOR,
    exceptions: tuple = (requests.RequestException,)
):
    """
    Decorator to retry a function with exponential backoff.

    Args:
        max_retries: Maximum number of retry attempts
        initial_delay: Initial delay in seconds before first retry
        backoff_factor: Multiplier for delay after each retry
        exceptions: Tuple of exception types to catch and retry
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args, **kwargs) -> Any:
            delay = initial_delay
            last_exception = None

            for attempt in range(max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
                    if attempt < max_retries:
                        print(f"[RETRY] Attempt {attempt + 1}/{max_retries} failed: {e}")
                        print(f"[RETRY] Retrying in {delay:.1f} seconds...")
                        time.sleep(delay)
                        delay *= backoff_factor
                    else:
                        print(f"[RETRY] All {max_retries} retries exhausted")

            # Re-raise the last exception if all retries failed
            raise last_exception

        return wrapper
    return decorator


def extract_text_from_content(content: Any) -> str:
    """
    Extract plain text from various content formats returned by LLM agents.

    This function handles multiple content formats:
    - AgentOutput objects (LlamaIndex): Extracts the response attribute
    - Message objects with 'content' attribute: Extracts the content attribute
      (works for LlamaIndex ChatMessage, LangChain AIMessage, etc.)
    - String: Returns as-is
    - Dict with 'text' field: Extracts the text value
    - List of content blocks: Extracts text from all blocks with type='text'
    - Other types: Converts to string

    Args:
        content: The content object from an LLM response (can be str, dict, list, etc.)

    Returns:
        str: Extracted plain text content
    """
    # Handle LlamaIndex AgentOutput objects (has 'response' attribute)
    if hasattr(content, 'response') and not isinstance(content, (str, dict, list)):
        # Extract the response attribute from AgentOutput
        response = content.response
        # The response might itself be a message object with 'content'
        if hasattr(response, 'content'):
            return str(response.content)
        elif hasattr(response, 'message') and hasattr(response.message, 'content'):
            return str(response.message.content)
        else:
            return str(response)

    # Handle message objects with 'content' attribute (e.g., ChatMessage from various frameworks)
    # This works for LlamaIndex ChatMessage, LangChain AIMessage, etc.
    if hasattr(content, 'content') and not isinstance(content, (str, dict, list)):
        # Extract the content attribute (works for any message object)
        return str(content.content)

    # Handle dict format (e.g., {'text': 'answer'})
    if isinstance(content, dict):
        if 'text' in content:
            return str(content['text'])
        else:
            print(f"[WARNING] Content was dict without 'text' field, converting to string")
            return str(content)

    # Handle list format (e.g., [{'type': 'text', 'text': 'answer'}])
    elif isinstance(content, list):
        text_parts = []
        for item in content:
            if isinstance(item, dict):
                # Look for items with type='text' and extract the 'text' field
                if item.get('type') == 'text':
                    text_parts.append(str(item.get('text', '')))
                # Fallback: if there's a 'text' field but no type, use it
                elif 'text' in item:
                    text_parts.append(str(item['text']))
            elif isinstance(item, str):
                text_parts.append(item)
            else:
                text_parts.append(str(item))

        result = ' '.join(text_parts)
        if len(content) > 1 or (len(content) == 1 and isinstance(content[0], dict)):
            print(f"[INFO] Extracted text from list with {len(content)} item(s)")
        return result

    # Handle string format (already plain text)
    elif isinstance(content, str):
        return content

    # Fallback for other types
    else:
        print(f"[WARNING] Content was {type(content)}, converting to string")
        return str(content)


def cleanup_answer(answer: Any) -> str:
    """
    Clean up the agent answer to ensure it's in plain text format.

    This function:
    - Converts answer to string
    - Handles multi-line answers (extracts last meaningful non-debug line)
    - Normalizes whitespace
    - Strips trailing punctuation
    - Logs warnings for verbose or malformatted answers

    Args:
        answer: The raw answer from the agent (can be str, dict, list, etc.)

    Returns:
        str: Cleaned up answer as plain text
    """
    answer = str(answer).strip()

    if not answer:
        return answer

    # Handle multi-line: take the last line that isn't a debug/log prefix
    lines = [l.strip() for l in answer.split('\n') if l.strip()]
    if len(lines) > 1:
        debug_prefixes = ('[info', '[warning', '[error', '[retry', '[step', '[tool', '[final')
        for l in reversed(lines):
            if not l.lower().startswith(debug_prefixes):
                answer = l
                break
        else:
            answer = lines[-1]
        print(f"[CLEANUP] Extracted last meaningful line from {len(lines)}-line answer: '{answer[:80]}'")

    # NOTE: Do NOT strip commas here. The GAIA scorer's normalize_number_str already
    # strips commas from numeric answers, and split_string uses commas to split list
    # answers. Stripping here would corrupt comma-separated lists (e.g., "132,133,134"
    # becomes the invalid number string "132133134").

    # Normalize whitespace and strip trailing punctuation
    answer = ' '.join(answer.split()).strip().rstrip('.')

    # Sentence.NUMBER suffix — the model echoed its final answer as a bare number
    # appended directly after its reasoning, e.g. "...published 3 albums (included).3".
    # Match a NON-DIGIT char before the period (covers letters, ')', etc.) and require
    # whitespace earlier in the string so genuine bare decimals like "89706.00" or
    # "3.14" (no spaces) are never altered.
    if ' ' in answer and re.search(r'[^\d\s]\s*\.\d+$', answer):
        extracted = re.search(r'\.(\d+)$', answer).group(1)
        print(f"[CLEANUP] Extracted appended number from verbose answer: '{extracted}'")
        answer = extracted

    # NOTE: We deliberately do NOT regex-extract a bare answer out of a verbose
    # sentence. The model is instructed to emit only the bare answer, and earlier
    # extraction patterns here were reverse-engineered from specific GAIA questions —
    # an integrity and maintenance hazard. If the model returns prose, the right fix
    # is the prompt/model, not question-tuned post-processing.

    # Log if answer looks verbose (agent not following instructions)
    if len(answer) > 100:
        print(f"[WARNING] Answer appears verbose ({len(answer)} chars). Agent may not be following SYSTEM_PROMPT instructions.")
        print(f"[WARNING] First 150 chars: {answer[:150]}...")

    # Log if answer contains suspicious formatting characters
    if any(char in answer for char in ['{', '}', '[', ']', '`', '*', '#']):
        print(f"[WARNING] Answer contains suspicious formatting characters: {answer[:100]}")

    return answer