Paperbag commited on
Commit
8f12026
·
1 Parent(s): 1f36c0f

feat: enhance answer extraction and normalization logic, improve error handling in LLM invocation, and optimize YouTube transcript retrieval

Browse files
__pycache__/agent.cpython-39.pyc CHANGED
Binary files a/__pycache__/agent.cpython-39.pyc and b/__pycache__/agent.cpython-39.pyc differ
 
agent.py CHANGED
@@ -46,21 +46,20 @@ SYSTEM_PROMPT = """RESEARCH STRATEGY:
46
  TOOL SELECTION:
47
  - web_search: General web search for facts, URLs, news. Returns 5 results with title+URL.
48
  - wiki_search: Find Wikipedia pages on a topic (returns 2 short snippets only).
49
- - wiki_page: Read a FULL Wikipedia article by exact title. Use AFTER wiki_search when you need complete content.
50
  - browse_url: Read any webpage's full text content from a URL.
51
  - read_file: Text files (.txt, .py, .md), PDFs. NOT for spreadsheets, audio, or images.
52
  - parse_spreadsheet: Excel (.xlsx) and CSV files. Always use this for spreadsheets.
53
- - transcribe_audio: Audio files (.mp3, .wav). The ONLY tool for audio use it immediately.
54
- - python_repl: Calculations, data analysis, PDF parsing, file processing. Variables persist between calls. Use libraries already installed (pandas, numpy, PIL, PyPDF2).
55
  - get_youtube_transcript: YouTube video transcripts only.
56
 
57
- RULES:
 
 
 
58
  - Never call the same tool with the same arguments twice.
59
- - When wiki_search returns short snippets, follow up with wiki_page for full content.
60
- - After getting tool results, analyze them — don't immediately search again with slightly different queries.
61
- - Audio files can ONLY be read with transcribe_audio. Do not use read_file on .mp3/.wav.
62
- - Images (.png/.jpg) cannot be analyzed — no vision model. Skip file-based analysis.
63
- - For spreadsheets: parse_spreadsheet to view, then python_repl to compute if needed.
64
  - Don't install packages in python_repl — use what's already available."""
65
 
66
 
 
46
  TOOL SELECTION:
47
  - web_search: General web search for facts, URLs, news. Returns 5 results with title+URL.
48
  - wiki_search: Find Wikipedia pages on a topic (returns 2 short snippets only).
49
+ - wiki_page: Read a FULL Wikipedia article by exact title. Use AFTER wiki_search.
50
  - browse_url: Read any webpage's full text content from a URL.
51
  - read_file: Text files (.txt, .py, .md), PDFs. NOT for spreadsheets, audio, or images.
52
  - parse_spreadsheet: Excel (.xlsx) and CSV files. Always use this for spreadsheets.
53
+ - transcribe_audio: Audio files (.mp3, .wav). Call once, use the returned text immediately.
54
+ - python_repl: Calculations, data analysis, file processing. Variables persist between calls.
55
  - get_youtube_transcript: YouTube video transcripts only.
56
 
57
+ EFFICIENCY RULES (save tool calls):
58
+ - After transcribe_audio returns text, USE IT. Do NOT call read_file on audio, do NOT search for audio files with python_repl.
59
+ - After read_file shows a .py script, run it with exec(open(path).read()) — do NOT rewrite the code.
60
+ - After getting a tool result, analyze it. Do not search again with slightly different queries.
61
  - Never call the same tool with the same arguments twice.
62
+ - Images (.png/.jpg) cannot be analyzed no vision available. Skip them completely.
 
 
 
 
63
  - Don't install packages in python_repl — use what's already available."""
64
 
65
 
app.py CHANGED
@@ -20,13 +20,20 @@ def extract_answer(content) -> str:
20
  cleaned = content.strip()
21
  if not cleaned:
22
  return ""
23
- match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n|$)', cleaned, re.IGNORECASE)
 
24
  if match:
25
  return match.group(1).strip()
26
- match = re.search(r'Answer:\s*(.+?)(?:\n|$)', cleaned, re.IGNORECASE)
27
  if match:
28
  return match.group(1).strip()
29
- match = re.search(r'(?:the\s+)?answer\s+is\s*:?\s*(.+?)(?:\.|$)', cleaned, re.IGNORECASE)
 
 
 
 
 
 
30
  if match:
31
  return match.group(1).strip()
32
  lines = [l.strip() for l in cleaned.split('\n') if l.strip()]
@@ -38,8 +45,11 @@ def extract_answer(content) -> str:
38
 
39
  def normalize_answer(s: str) -> str:
40
  s = s.strip().lower()
41
- s = re.sub(r'^[\$€£¥]', '', s)
42
- s = s.replace(',', '')
 
 
 
43
  s = s.rstrip('*')
44
  s = s.strip()
45
  return s
@@ -169,7 +179,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
169
  ".png": "Tip: This is an image — no vision model available. Skip file-based analysis.",
170
  ".jpg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
171
  ".jpeg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
172
- ".py": "Tip: This is a Python script. Use read_file to view, then python_repl to run it.",
173
  ".pdf": "Tip: This is a PDF. Use read_file or python_repl with PyPDF2 to read it.",
174
  }
175
  _hint = _tips.get(_ext, "")
 
20
  cleaned = content.strip()
21
  if not cleaned:
22
  return ""
23
+ cleaned = re.sub(r'```[\w]*\n?', '', cleaned)
24
+ match = re.search(r'^FINAL ANSWER:\s*(.+?)(?:\n\n|\Z|(?=\nFINAL))', cleaned, re.IGNORECASE | re.MULTILINE | re.DOTALL)
25
  if match:
26
  return match.group(1).strip()
27
+ match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n\n|\Z|(?=\nFINAL))', cleaned, re.IGNORECASE | re.DOTALL)
28
  if match:
29
  return match.group(1).strip()
30
+ match = re.search(r'Answer:\s*(.+?)(?:\n\n|\Z)', cleaned, re.IGNORECASE | re.DOTALL)
31
+ if match:
32
+ return match.group(1).strip()
33
+ match = re.search(r'(?:the\s+)?answer\s+is\s*:?\s*(.+?)(?:\n\n|\Z)', cleaned, re.IGNORECASE | re.DOTALL)
34
+ if match:
35
+ return match.group(1).strip()
36
+ match = re.search(r'(?:^|\n)(?:Result|Output|Therefore)[:\s]+(.+)', cleaned, re.IGNORECASE)
37
  if match:
38
  return match.group(1).strip()
39
  lines = [l.strip() for l in cleaned.split('\n') if l.strip()]
 
45
 
46
  def normalize_answer(s: str) -> str:
47
  s = s.strip().lower()
48
+ s = re.sub(r'^[\$€£¥]+', '', s)
49
+ s = re.sub(r'[.,!?;:]+$', '', s)
50
+ s = s.replace(',', ' ')
51
+ s = re.sub(r'\s+', ' ', s)
52
+ s = re.sub(r'^(a |an |the )', '', s)
53
  s = s.rstrip('*')
54
  s = s.strip()
55
  return s
 
179
  ".png": "Tip: This is an image — no vision model available. Skip file-based analysis.",
180
  ".jpg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
181
  ".jpeg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
182
+ ".py": "Tip: This is a Python script. Use read_file to view, then python_repl with exec(open(path).read()) to run it directly.",
183
  ".pdf": "Tip: This is a PDF. Use read_file or python_repl with PyPDF2 to read it.",
184
  }
185
  _hint = _tips.get(_ext, "")
gaia_results.csv CHANGED
@@ -14,11 +14,11 @@ cca530fc-4052-43b2-b130-b30968d8aa44,Review the chess position provided in the i
14
  |d|b|e|b|e|d|
15
  |e|d|b|a|d|c|
16
 
17
- provide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.","b, e","b, e",True
18
  9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
19
 
20
- What does Teal'c say in response to the question ""Isn't that hot?""","Teal'c responds with **""Extremely.""**",Extremely,False
21
- cabe07ed-9eca-40ea-8ead-410ef5e83f91,What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?,Louvrier,Louvrier,True
22
  3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
23
 
24
  milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
@@ -30,14 +30,14 @@ In your response, please only list the ingredients, not any measurements. So if
30
 
31
  Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",,"cornstarch, freshly squeezed lemon juice, granulated sugar, pure vanilla extract, ripe strawberries",False
32
  305ac316-eef6-4446-960a-92d80d542f82,Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.,,Wojciech,False
33
- f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,None,0,False
34
  3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,,519,False
35
  1f975693-876d-457b-a649-393859e79bf3,"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(
36
 
37
  Could you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",,"132, 133, 134, 197, 245",False
38
- 840bfca7-4f7b-481a-8794-c560c340185d,"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",The work performed by R. G. Arendt was supported by NASA award number **80GSFC21M0002**.,80GSFC21M0002,False
39
- bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,Saint Petersburg,Saint Petersburg,True
40
  cf106601-ab4f-4af9-b045-5295fe67b37d,"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",CUB,CUB,True
41
- a0c07678-e491-4bbc-8f0b-07405144218f,"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",,"Yoshida, Uehara",False
42
  7bd855d8-463d-4ed5-93ca-5fe35145f733,The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.,89706.00,89706.00,True
43
  5a0c1adf-205e-4841-a666-7c3ef95def9d,What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?,,Claus,False
 
14
  |d|b|e|b|e|d|
15
  |e|d|b|a|d|c|
16
 
17
+ provide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.","b,e","b, e",False
18
  9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
19
 
20
+ What does Teal'c say in response to the question ""Isn't that hot?""","Teal'c responds with **""Indeed.""**",Extremely,False
21
+ cabe07ed-9eca-40ea-8ead-410ef5e83f91,What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?,,Louvrier,False
22
  3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
23
 
24
  milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
 
30
 
31
  Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",,"cornstarch, freshly squeezed lemon juice, granulated sugar, pure vanilla extract, ripe strawberries",False
32
  305ac316-eef6-4446-960a-92d80d542f82,Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.,,Wojciech,False
33
+ f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,,0,False
34
  3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,,519,False
35
  1f975693-876d-457b-a649-393859e79bf3,"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(
36
 
37
  Could you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",,"132, 133, 134, 197, 245",False
38
+ 840bfca7-4f7b-481a-8794-c560c340185d,"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",,80GSFC21M0002,False
39
+ bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,,Saint Petersburg,False
40
  cf106601-ab4f-4af9-b045-5295fe67b37d,"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",CUB,CUB,True
41
+ a0c07678-e491-4bbc-8f0b-07405144218f,"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",ERROR: 'charmap' codec can't encode character '\u014d' in position 55: character maps to <undefined>,"Yoshida, Uehara",False
42
  7bd855d8-463d-4ed5-93ca-5fe35145f733,The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.,89706.00,89706.00,True
43
  5a0c1adf-205e-4841-a666-7c3ef95def9d,What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?,,Claus,False
gaia_results.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
- "score": 35.0,
3
- "correct": 7,
4
  "total": 20,
5
  "results": [
6
  {
@@ -41,23 +41,23 @@
41
  {
42
  "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
43
  "question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",
44
- "submitted_answer": "b, e",
45
  "ground_truth": "b, e",
46
- "correct": true
47
  },
48
  {
49
  "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
50
  "question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"",
51
- "submitted_answer": "Teal'c responds with **\"Extremely.\"**",
52
  "ground_truth": "Extremely",
53
  "correct": false
54
  },
55
  {
56
  "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
57
  "question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
58
- "submitted_answer": "Louvrier",
59
  "ground_truth": "Louvrier",
60
- "correct": true
61
  },
62
  {
63
  "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
@@ -83,7 +83,7 @@
83
  {
84
  "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
85
  "question": "What is the final numeric output from the attached Python code?",
86
- "submitted_answer": "None",
87
  "ground_truth": "0",
88
  "correct": false
89
  },
@@ -104,16 +104,16 @@
104
  {
105
  "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
106
  "question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
107
- "submitted_answer": "The work performed by R.\u202fG.\u202fArendt was supported by NASA award number **80GSFC21M0002**.",
108
  "ground_truth": "80GSFC21M0002",
109
  "correct": false
110
  },
111
  {
112
  "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
113
  "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
114
- "submitted_answer": "Saint Petersburg",
115
  "ground_truth": "Saint Petersburg",
116
- "correct": true
117
  },
118
  {
119
  "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
@@ -125,7 +125,7 @@
125
  {
126
  "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
127
  "question": "Who are the pitchers with the number before and after Taish\u014d Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
128
- "submitted_answer": "",
129
  "ground_truth": "Yoshida, Uehara",
130
  "correct": false
131
  },
 
1
  {
2
+ "score": 20.0,
3
+ "correct": 4,
4
  "total": 20,
5
  "results": [
6
  {
 
41
  {
42
  "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
43
  "question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",
44
+ "submitted_answer": "b,e",
45
  "ground_truth": "b, e",
46
+ "correct": false
47
  },
48
  {
49
  "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
50
  "question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"",
51
+ "submitted_answer": "Teal'c responds with **\"Indeed.\"**",
52
  "ground_truth": "Extremely",
53
  "correct": false
54
  },
55
  {
56
  "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
57
  "question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
58
+ "submitted_answer": "",
59
  "ground_truth": "Louvrier",
60
+ "correct": false
61
  },
62
  {
63
  "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
 
83
  {
84
  "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
85
  "question": "What is the final numeric output from the attached Python code?",
86
+ "submitted_answer": "",
87
  "ground_truth": "0",
88
  "correct": false
89
  },
 
104
  {
105
  "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
106
  "question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
107
+ "submitted_answer": "",
108
  "ground_truth": "80GSFC21M0002",
109
  "correct": false
110
  },
111
  {
112
  "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
113
  "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
114
+ "submitted_answer": "",
115
  "ground_truth": "Saint Petersburg",
116
+ "correct": false
117
  },
118
  {
119
  "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
 
125
  {
126
  "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
127
  "question": "Who are the pitchers with the number before and after Taish\u014d Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
128
+ "submitted_answer": "ERROR: 'charmap' codec can't encode character '\\u014d' in position 55: character maps to <undefined>",
129
  "ground_truth": "Yoshida, Uehara",
130
  "correct": false
131
  },
llm/client.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import time
 
3
 
4
  from langchain_core.messages import AIMessage
5
  from llm.providers import PROVIDERS
@@ -7,6 +8,25 @@ from llm.providers import PROVIDERS
7
  PROVIDER_ORDER = [p.strip() for p in os.getenv("LLM_PROVIDER_ORDER", "opencode_zen, groq").split(",")]
8
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def invoke_llm(messages, tools, fallback_count=0, _degraded=None):
11
  if _degraded is None:
12
  _degraded = {}
@@ -27,19 +47,23 @@ def invoke_llm(messages, tools, fallback_count=0, _degraded=None):
27
  print(f"Invoking {provider_name} with {model_name}", flush=True)
28
 
29
  retries = 0
30
- while retries < 2:
 
31
  try:
32
  return provider.invoke(messages, tools, model_name)
33
  except Exception as e:
34
  err_str = str(e)
35
- err = err_str.lower()
36
- if any(x in err for x in ("rate limit", "429", "quota", "resource ex")):
37
- print(f"{provider_name}/{model_name} rate limited, waiting...", flush=True)
38
- time.sleep(65)
39
- retries += 1
40
- elif any(x in err for x in ("payment required", "402", "tool_use_failed", "model_not_found", "too large", "413")):
41
- print(f"{provider_name}/{model_name} skip, trying next", flush=True)
42
  break
 
 
 
 
 
 
 
 
43
  else:
44
  print(f"{provider_name}/{model_name} error: {type(e).__name__}: {err_str[:150]}", flush=True)
45
  break
 
1
  import os
2
  import time
3
+ import random
4
 
5
  from langchain_core.messages import AIMessage
6
  from llm.providers import PROVIDERS
 
8
  PROVIDER_ORDER = [p.strip() for p in os.getenv("LLM_PROVIDER_ORDER", "opencode_zen, groq").split(",")]
9
 
10
 
11
+ def _is_rate_limit(e: Exception) -> bool:
12
+ err = str(e).lower()
13
+ return any(x in err for x in ("rate limit", "429", "quota", "resource ex"))
14
+
15
+
16
+ def _is_retryable(e: Exception) -> bool:
17
+ err = str(e).lower()
18
+ if _is_rate_limit(e):
19
+ return True
20
+ return any(x in err for x in ("500", "502", "503", "504", "timeout", "connection", "temporary", "bad gateway",
21
+ "service unavailable", "internal server error", "server error", "temporarily"))
22
+
23
+
24
+ def _is_unrecoverable(e: Exception) -> bool:
25
+ err = str(e).lower()
26
+ return any(x in err for x in ("payment required", "402", "tool_use_failed", "model_not_found",
27
+ "too large", "413", "400", "401", "403", "404"))
28
+
29
+
30
  def invoke_llm(messages, tools, fallback_count=0, _degraded=None):
31
  if _degraded is None:
32
  _degraded = {}
 
47
  print(f"Invoking {provider_name} with {model_name}", flush=True)
48
 
49
  retries = 0
50
+ max_retries = 3
51
+ while retries < max_retries:
52
  try:
53
  return provider.invoke(messages, tools, model_name)
54
  except Exception as e:
55
  err_str = str(e)
56
+ if _is_unrecoverable(e):
57
+ print(f"{provider_name}/{model_name} skip ({err_str[:100]})", flush=True)
 
 
 
 
 
58
  break
59
+ elif _is_retryable(e):
60
+ if _is_rate_limit(e):
61
+ delay = 65
62
+ else:
63
+ delay = min(2 ** retries + random.uniform(0, 1), 30)
64
+ print(f"{provider_name}/{model_name} retryable ({err_str[:100]}), retry {retries+1}/{max_retries} after {delay:.0f}s", flush=True)
65
+ time.sleep(delay)
66
+ retries += 1
67
  else:
68
  print(f"{provider_name}/{model_name} error: {type(e).__name__}: {err_str[:150]}", flush=True)
69
  break
run_local.py CHANGED
@@ -19,13 +19,20 @@ def extract_answer(content) -> str:
19
  cleaned = content.strip()
20
  if not cleaned:
21
  return ""
22
- match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n|$)', cleaned, re.IGNORECASE)
 
23
  if match:
24
  return match.group(1).strip()
25
- match = re.search(r'Answer:\s*(.+?)(?:\n|$)', cleaned, re.IGNORECASE)
26
  if match:
27
  return match.group(1).strip()
28
- match = re.search(r'(?:the\s+)?answer\s+is\s*:?\s*(.+?)(?:\.|$)', cleaned, re.IGNORECASE)
 
 
 
 
 
 
29
  if match:
30
  return match.group(1).strip()
31
  lines = [l.strip() for l in cleaned.split('\n') if l.strip()]
@@ -37,8 +44,11 @@ def extract_answer(content) -> str:
37
 
38
  def normalize_answer(s: str) -> str:
39
  s = s.strip().lower()
40
- s = re.sub(r'^[\$€£¥]', '', s)
41
- s = s.replace(',', '')
 
 
 
42
  s = s.rstrip('*')
43
  s = s.strip()
44
  return s
@@ -125,7 +135,7 @@ def main():
125
  ".png": "Tip: This is an image — no vision model available. Skip file-based analysis.",
126
  ".jpg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
127
  ".jpeg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
128
- ".py": "Tip: This is a Python script. Use read_file to view, then python_repl to run it.",
129
  ".pdf": "Tip: This is a PDF. Use read_file or python_repl with PyPDF2 to read it.",
130
  }
131
  _hint = _tips.get(_ext, "")
 
19
  cleaned = content.strip()
20
  if not cleaned:
21
  return ""
22
+ cleaned = re.sub(r'```[\w]*\n?', '', cleaned)
23
+ match = re.search(r'^FINAL ANSWER:\s*(.+?)(?:\n\n|\Z|(?=\nFINAL))', cleaned, re.IGNORECASE | re.MULTILINE | re.DOTALL)
24
  if match:
25
  return match.group(1).strip()
26
+ match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n\n|\Z|(?=\nFINAL))', cleaned, re.IGNORECASE | re.DOTALL)
27
  if match:
28
  return match.group(1).strip()
29
+ match = re.search(r'Answer:\s*(.+?)(?:\n\n|\Z)', cleaned, re.IGNORECASE | re.DOTALL)
30
+ if match:
31
+ return match.group(1).strip()
32
+ match = re.search(r'(?:the\s+)?answer\s+is\s*:?\s*(.+?)(?:\n\n|\Z)', cleaned, re.IGNORECASE | re.DOTALL)
33
+ if match:
34
+ return match.group(1).strip()
35
+ match = re.search(r'(?:^|\n)(?:Result|Output|Therefore)[:\s]+(.+)', cleaned, re.IGNORECASE)
36
  if match:
37
  return match.group(1).strip()
38
  lines = [l.strip() for l in cleaned.split('\n') if l.strip()]
 
44
 
45
  def normalize_answer(s: str) -> str:
46
  s = s.strip().lower()
47
+ s = re.sub(r'^[\$€£¥]+', '', s)
48
+ s = re.sub(r'[.,!?;:]+$', '', s)
49
+ s = s.replace(',', ' ')
50
+ s = re.sub(r'\s+', ' ', s)
51
+ s = re.sub(r'^(a |an |the )', '', s)
52
  s = s.rstrip('*')
53
  s = s.strip()
54
  return s
 
135
  ".png": "Tip: This is an image — no vision model available. Skip file-based analysis.",
136
  ".jpg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
137
  ".jpeg": "Tip: This is an image — no vision model available. Skip file-based analysis.",
138
+ ".py": "Tip: This is a Python script. Use read_file to view, then python_repl with exec(open(path).read()) to run it directly.",
139
  ".pdf": "Tip: This is a PDF. Use read_file or python_repl with PyPDF2 to read it.",
140
  }
141
  _hint = _tips.get(_ext, "")
tools/audio.py CHANGED
@@ -1,13 +1,40 @@
 
 
1
  from langchain_core.tools import tool
2
 
 
 
 
3
 
4
  @tool
5
  def transcribe_audio(path: str) -> str:
6
- """Transcribe audio file to text."""
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  try:
8
  import whisper
9
- model = whisper.load_model("base")
10
- result = model.transcribe(path)
11
- return result["text"][:5000] or "NO_TRANSCRIPTION"
 
 
 
 
 
 
 
 
 
12
  except Exception as e:
13
  return f"AUDIO_TRANSCRIPTION_ERROR: {e}"
 
1
+ import os
2
+ import hashlib
3
  from langchain_core.tools import tool
4
 
5
+ _whisper_model = None
6
+ _transcript_cache = {}
7
+
8
 
9
  @tool
10
  def transcribe_audio(path: str) -> str:
11
+ """Transcribe audio file to text. Results are cached per file. Call this ONCE for each audio file and use the returned text directly. Do not call read_file or search for the file afterwards."""
12
+ global _whisper_model
13
+
14
+ if not path or not os.path.exists(path):
15
+ return "ERROR: Audio file not found"
16
+
17
+ abs_path = os.path.abspath(path)
18
+ mtime = os.path.getmtime(abs_path)
19
+ cache_key = f"{abs_path}::{mtime}"
20
+
21
+ cached = _transcript_cache.get(cache_key)
22
+ if cached is not None:
23
+ return cached
24
+
25
  try:
26
  import whisper
27
+ import torch
28
+
29
+ if _whisper_model is None:
30
+ device = "cuda" if torch.cuda.is_available() else "cpu"
31
+ _whisper_model = whisper.load_model("base", device=device)
32
+
33
+ result = _whisper_model.transcribe(abs_path)
34
+ text = result["text"][:5000] or "NO_TRANSCRIPTION"
35
+ if result["text"] and len(result["text"]) > 5000:
36
+ text += "\n...[transcript truncated at 5000 characters]"
37
+ _transcript_cache[cache_key] = text
38
+ return text
39
  except Exception as e:
40
  return f"AUDIO_TRANSCRIPTION_ERROR: {e}"
tools/file/reader.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import fitz
3
  from langchain_community.document_loaders import UnstructuredFileLoader
4
  from langchain_community.document_loaders.image import UnstructuredImageLoader
@@ -40,6 +41,8 @@ def read_file(path: str) -> str:
40
  loader = UnstructuredFileLoader(path)
41
  docs = loader.load()
42
  content = "\n\n".join([doc.page_content for doc in docs])
 
 
43
  else:
44
  loader = UnstructuredFileLoader(path)
45
  docs = loader.load()
 
1
  import os
2
+ from pathlib import Path
3
  import fitz
4
  from langchain_community.document_loaders import UnstructuredFileLoader
5
  from langchain_community.document_loaders.image import UnstructuredImageLoader
 
41
  loader = UnstructuredFileLoader(path)
42
  docs = loader.load()
43
  content = "\n\n".join([doc.page_content for doc in docs])
44
+ elif ext == ".py":
45
+ content = Path(path).read_text(encoding="utf-8", errors="replace")
46
  else:
47
  loader = UnstructuredFileLoader(path)
48
  docs = loader.load()
tools/python.py CHANGED
@@ -9,6 +9,7 @@ def python_repl(code: str) -> str:
9
  The code should be a valid python script that prints the final result.
10
  You can use libraries like pandas, numpy, PIL, etc.
11
  IMPORTANT: Variables persist between calls to this tool (same Python process). You can define a variable in one call and use it in the next.
 
12
  Example: print(df.head()) or print(2 + 2)"""
13
  try:
14
  old_stdout = sys.stdout
 
9
  The code should be a valid python script that prints the final result.
10
  You can use libraries like pandas, numpy, PIL, etc.
11
  IMPORTANT: Variables persist between calls to this tool (same Python process). You can define a variable in one call and use it in the next.
12
+ To run a .py file: exec(open('/path/to/file.py').read())
13
  Example: print(df.head()) or print(2 + 2)"""
14
  try:
15
  old_stdout = sys.stdout
tools/web/search.py CHANGED
@@ -1,20 +1,27 @@
 
1
  from langchain_core.tools import tool
2
 
3
 
4
  @tool
5
  def web_search(keywords: str) -> str:
6
  """Search the web. Use this for finding information, facts, URLs, and general web content. Returns title, URL, and snippet for each result."""
7
- try:
8
- from ddgs import DDGS
9
- results = list(DDGS().text(keywords, max_results=5))
10
- if not results:
11
- return "NO_RESULTS"
12
- formatted = []
13
- for r in results:
14
- title = r.get("title", "")
15
- url = r.get("href", "")
16
- body = r.get("body", "")[:300]
17
- formatted.append(f"Title: {title}\nURL: {url}\nContent: {body}")
18
- return "\n\n".join(formatted)
19
- except Exception as e:
20
- return f"SEARCH_ERROR: {e}"
 
 
 
 
 
 
 
1
+ import time
2
  from langchain_core.tools import tool
3
 
4
 
5
  @tool
6
  def web_search(keywords: str) -> str:
7
  """Search the web. Use this for finding information, facts, URLs, and general web content. Returns title, URL, and snippet for each result."""
8
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"}
9
+ last_err = None
10
+ for attempt in range(3):
11
+ try:
12
+ from ddgs import DDGS
13
+ results = list(DDGS(headers=headers).text(keywords, max_results=5, backend="html"))
14
+ if not results:
15
+ return "NO_RESULTS"
16
+ formatted = []
17
+ for r in results:
18
+ title = r.get("title", "")
19
+ url = r.get("href", "")
20
+ body = r.get("body", "")[:300]
21
+ formatted.append(f"Title: {title}\nURL: {url}\nContent: {body}")
22
+ return "\n\n".join(formatted)
23
+ except Exception as e:
24
+ last_err = e
25
+ if attempt < 2:
26
+ time.sleep(2 ** attempt)
27
+ return f"SEARCH_ERROR: {last_err}"
tools/youtube.py CHANGED
@@ -4,18 +4,49 @@ from pathlib import Path
4
  from langchain_core.tools import tool
5
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  @tool
8
  def get_youtube_transcript(url: str) -> str:
9
- """Get YouTube transcript."""
 
 
 
 
 
10
  try:
11
  with tempfile.TemporaryDirectory() as tmp:
12
- cmd = ["yt-dlp", "--skip-download", "--write-auto-subs", "--sub-lang", "en", "-o", f"{tmp}/video", url]
13
- subprocess.run(cmd, capture_output=True, timeout=60)
14
- vtt_files = list(Path(tmp).glob("*.vtt"))
15
- if vtt_files:
16
- content = vtt_files[0].read_text(encoding="utf-8", errors="replace")
17
- lines = [l for l in content.splitlines() if l and not l.startswith(('<', '-->', 'WEBVTT')) and not l.isdigit()]
18
- return "\n".join(lines)[:15000] or "NO_TRANSCRIPT"
19
  return "NO_SUBTITLES"
 
 
20
  except Exception as e:
21
  return f"TRANSCRIPT_ERROR: {e}"
 
4
  from langchain_core.tools import tool
5
 
6
 
7
+ def _parse_vtt(content: str) -> str:
8
+ lines = []
9
+ for l in content.splitlines():
10
+ stripped = l.strip()
11
+ if not stripped:
12
+ continue
13
+ if stripped.startswith(('<', '-->', 'WEBVTT', 'NOTE', 'STYLE', '::')):
14
+ continue
15
+ if stripped.isdigit():
16
+ continue
17
+ if 'align:' in stripped or 'position:' in stripped:
18
+ continue
19
+ lines.append(stripped)
20
+ return "\n".join(lines)
21
+
22
+
23
+ def _try_download(url: str, tmp: str, extra_args: list) -> list[Path]:
24
+ cmd = ["yt-dlp", "--skip-download", "-o", f"{tmp}/video", url] + extra_args
25
+ result = subprocess.run(cmd, capture_output=True, timeout=120)
26
+ if result.returncode != 0:
27
+ return []
28
+ return list(Path(tmp).glob("*.vtt"))
29
+
30
+
31
  @tool
32
  def get_youtube_transcript(url: str) -> str:
33
+ """Get YouTube transcript. Tries manual captions first, then auto-generated, falling back through language variants."""
34
+ strategies = [
35
+ ["--write-subs", "--sub-langs", "en.*,en"],
36
+ ["--write-auto-subs", "--sub-langs", "en.*,en"],
37
+ ["--write-auto-subs", "--sub-langs", "a.*"],
38
+ ]
39
  try:
40
  with tempfile.TemporaryDirectory() as tmp:
41
+ for strat in strategies:
42
+ vtt_files = _try_download(url, tmp, strat)
43
+ if vtt_files:
44
+ content = vtt_files[0].read_text(encoding="utf-8", errors="replace")
45
+ parsed = _parse_vtt(content)
46
+ if parsed.strip():
47
+ return parsed[:15000]
48
  return "NO_SUBTITLES"
49
+ except subprocess.TimeoutExpired:
50
+ return "TRANSCRIPT_ERROR: timeout"
51
  except Exception as e:
52
  return f"TRANSCRIPT_ERROR: {e}"