Update src/nodes.py
#1
by
KaiserShultz
- opened
- .gitattributes +0 -1
- .gitignore +2 -2
- README.md +2 -3
- app.py +3 -6
- docs/images/banner.png +0 -3
- questions_20_gaia.json +0 -1
- requirements.txt +21 -20
- src/__init__.py +10 -95
- src/config.py +3 -7
- src/main.py +0 -338
- src/nodes.py +47 -23
- src/prompts/prompts.py +220 -309
- src/schemas.py +1 -1
- src/state.py +0 -2
- src/tools/tools.py +0 -70
- src/tools/video_analyzer.py +0 -282
- src/tools/youtube_transcript.py +0 -72
- src/workflow_test.ipynb +0 -0
.gitattributes
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
.gitignore
CHANGED
|
@@ -11,13 +11,13 @@ __pycache__/
|
|
| 11 |
venv/
|
| 12 |
env/
|
| 13 |
.venv/
|
| 14 |
-
|
| 15 |
# IDEs
|
| 16 |
.vscode/
|
| 17 |
.idea/
|
| 18 |
*.swp
|
| 19 |
*.swo
|
| 20 |
-
|
| 21 |
# OS
|
| 22 |
.DS_Store
|
| 23 |
.DS_Store?
|
|
|
|
| 11 |
venv/
|
| 12 |
env/
|
| 13 |
.venv/
|
| 14 |
+
|
| 15 |
# IDEs
|
| 16 |
.vscode/
|
| 17 |
.idea/
|
| 18 |
*.swp
|
| 19 |
*.swo
|
| 20 |
+
|
| 21 |
# OS
|
| 22 |
.DS_Store
|
| 23 |
.DS_Store?
|
README.md
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
-
title:
|
| 4 |
sdk: gradio
|
| 5 |
-
emoji:
|
| 6 |
colorFrom: purple
|
| 7 |
colorTo: red
|
| 8 |
-
hf_oauth: true
|
| 9 |
---
|
|
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
+
title: Multi-task Agentic AI System
|
| 4 |
sdk: gradio
|
| 5 |
+
emoji: 🚀
|
| 6 |
colorFrom: purple
|
| 7 |
colorTo: red
|
|
|
|
| 8 |
---
|
app.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
|
| 3 |
This module exposes a simple Gradio-powered wrapper around the
|
| 4 |
`ankelodon_multiagent_system` project. It follows the same high-level flow
|
| 5 |
-
as the official GAIA template
|
| 6 |
evaluation questions from the GAIA API, run your agent to produce
|
| 7 |
responses, and submit those responses back to the leaderboard.
|
| 8 |
|
|
@@ -160,7 +160,6 @@ class AnkelodonAgent:
|
|
| 160 |
"max_iterations": 3,
|
| 161 |
"execution_report": None,
|
| 162 |
"previous_tool_results": {},
|
| 163 |
-
"critic_replan" : False,
|
| 164 |
}
|
| 165 |
|
| 166 |
# If a task ID is provided, attempt to download its attachment.
|
|
@@ -184,8 +183,7 @@ class AnkelodonAgent:
|
|
| 184 |
# "final answer:"; remove it for exact match scoring【842261069842380†L108-L112】.
|
| 185 |
answer = ""
|
| 186 |
if isinstance(result_state, dict):
|
| 187 |
-
answer = result_state.get("
|
| 188 |
-
answer = answer.final_answer
|
| 189 |
if answer:
|
| 190 |
answer = answer.replace("Final answer:", "").replace("final answer:", "").strip()
|
| 191 |
return answer
|
|
@@ -237,14 +235,13 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile]) -> tuple[str, pd.Data
|
|
| 237 |
results_log: List[Dict[str, Any]] = []
|
| 238 |
answers_payload: List[Dict[str, str]] = []
|
| 239 |
print(f"Running agent on {len(questions_data)} questions…")
|
| 240 |
-
for
|
| 241 |
task_id = item.get("task_id")
|
| 242 |
question_text = item.get("question")
|
| 243 |
if not task_id or question_text is None:
|
| 244 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 245 |
continue
|
| 246 |
try:
|
| 247 |
-
print(f"===== QUESTION {number + 1}/{len(questions_data)} (ID: {task_id}): {question_text} ==== ")
|
| 248 |
answer = agent(question_text, task_id)
|
| 249 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 250 |
results_log.append({
|
|
|
|
| 2 |
|
| 3 |
This module exposes a simple Gradio-powered wrapper around the
|
| 4 |
`ankelodon_multiagent_system` project. It follows the same high-level flow
|
| 5 |
+
as the official GAIA template provided in the course materials: fetch
|
| 6 |
evaluation questions from the GAIA API, run your agent to produce
|
| 7 |
responses, and submit those responses back to the leaderboard.
|
| 8 |
|
|
|
|
| 160 |
"max_iterations": 3,
|
| 161 |
"execution_report": None,
|
| 162 |
"previous_tool_results": {},
|
|
|
|
| 163 |
}
|
| 164 |
|
| 165 |
# If a task ID is provided, attempt to download its attachment.
|
|
|
|
| 183 |
# "final answer:"; remove it for exact match scoring【842261069842380†L108-L112】.
|
| 184 |
answer = ""
|
| 185 |
if isinstance(result_state, dict):
|
| 186 |
+
answer = result_state.get("final_answer") or result_state.get("answer") or ""
|
|
|
|
| 187 |
if answer:
|
| 188 |
answer = answer.replace("Final answer:", "").replace("final answer:", "").strip()
|
| 189 |
return answer
|
|
|
|
| 235 |
results_log: List[Dict[str, Any]] = []
|
| 236 |
answers_payload: List[Dict[str, str]] = []
|
| 237 |
print(f"Running agent on {len(questions_data)} questions…")
|
| 238 |
+
for item in questions_data:
|
| 239 |
task_id = item.get("task_id")
|
| 240 |
question_text = item.get("question")
|
| 241 |
if not task_id or question_text is None:
|
| 242 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 243 |
continue
|
| 244 |
try:
|
|
|
|
| 245 |
answer = agent(question_text, task_id)
|
| 246 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 247 |
results_log.append({
|
docs/images/banner.png
DELETED
Git LFS Details
|
questions_20_gaia.json
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
[{"task_id":"8e867cd7-cff9-4e6c-867a-ff5ddc2550be","question":"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.","Level":"1","file_name":""},{"task_id":"a1e91b78-d3d8-4675-bb8d-62741b4b68a6","question":"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?","Level":"1","file_name":""},{"task_id":"2d83110e-a098-4ebb-9987-066c06fa42d0","question":".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI","Level":"1","file_name":""},{"task_id":"cca530fc-4052-43b2-b130-b30968d8aa44","question":"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.","Level":"1","file_name":"cca530fc-4052-43b2-b130-b30968d8aa44.png"},{"task_id":"4fc2f1ae-8625-45b5-ab34-ad4433bc21f8","question":"Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?","Level":"1","file_name":""},{"task_id":"6f37996b-2ac7-44b0-8e68-6d28256631b4","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.","Level":"1","file_name":""},{"task_id":"9d191bce-651d-4746-be2d-7ef8ecadb9c2","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?\"","Level":"1","file_name":""},{"task_id":"cabe07ed-9eca-40ea-8ead-410ef5e83f91","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?","Level":"1","file_name":""},{"task_id":"3cef3a44-215e-4aed-8e3b-b1e3f08063b7","question":"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:\n\nmilk, 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\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.","Level":"1","file_name":""},{"task_id":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3","question":"Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.","Level":"1","file_name":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"},{"task_id":"305ac316-eef6-4446-960a-92d80d542f82","question":"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.","Level":"1","file_name":""},{"task_id":"f918266a-b3e0-4914-865d-4faa564f1aef","question":"What is the final numeric output from the attached Python code?","Level":"1","file_name":"f918266a-b3e0-4914-865d-4faa564f1aef.py"},{"task_id":"3f57289b-8c60-48be-bd80-01f8099ca449","question":"How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?","Level":"1","file_name":""},{"task_id":"1f975693-876d-457b-a649-393859e79bf3","question":"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 :(\n\nCould 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.","Level":"1","file_name":"1f975693-876d-457b-a649-393859e79bf3.mp3"},{"task_id":"840bfca7-4f7b-481a-8794-c560c340185d","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?","Level":"1","file_name":""},{"task_id":"bda648d7-d618-4883-88f4-3466eabd860e","question":"Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.","Level":"1","file_name":""},{"task_id":"cf106601-ab4f-4af9-b045-5295fe67b37d","question":"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.","Level":"1","file_name":""},{"task_id":"a0c07678-e491-4bbc-8f0b-07405144218f","question":"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.","Level":"1","file_name":""},{"task_id":"7bd855d8-463d-4ed5-93ca-5fe35145f733","question":"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.","Level":"1","file_name":"7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"},{"task_id":"5a0c1adf-205e-4841-a666-7c3ef95def9d","question":"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?","Level":"1","file_name":""}]
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,29 +1,30 @@
|
|
| 1 |
-
|
| 2 |
gradio==5.46.1
|
| 3 |
-
ipython==8.12.3
|
| 4 |
langchain==0.3.27
|
| 5 |
-
langchain_community==0.3.29
|
| 6 |
langchain_core==0.3.76
|
|
|
|
| 7 |
langchain_openai==0.3.33
|
| 8 |
langgraph==0.6.7
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
numpy==2.2.6
|
| 11 |
pandas==2.3.2
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
pytesseract==0.3.13
|
| 17 |
python-dotenv==1.1.1
|
| 18 |
-
|
| 19 |
tldextract==5.3.0
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
yt_dlp
|
|
|
|
| 1 |
+
# ── Core UI / Agents
|
| 2 |
gradio==5.46.1
|
|
|
|
| 3 |
langchain==0.3.27
|
|
|
|
| 4 |
langchain_core==0.3.76
|
| 5 |
+
langchain_community==0.3.29
|
| 6 |
langchain_openai==0.3.33
|
| 7 |
langgraph==0.6.7
|
| 8 |
+
langgraph-checkpoint>=2.1.0,<3
|
| 9 |
+
langgraph-prebuilt>=0.6.0,<0.7
|
| 10 |
+
langgraph-sdk>=0.2.2,<0.3
|
| 11 |
+
|
| 12 |
+
# ── Numerics
|
| 13 |
numpy==2.2.6
|
| 14 |
pandas==2.3.2
|
| 15 |
+
matplotlib==3.10.6
|
| 16 |
+
|
| 17 |
+
# ── Files / Utils
|
| 18 |
+
pillow==11.3.0
|
|
|
|
| 19 |
python-dotenv==1.1.1
|
| 20 |
+
pydantic==2.11.9
|
| 21 |
tldextract==5.3.0
|
| 22 |
+
pdfminer==20191125
|
| 23 |
+
pytesseract==0.3.13
|
| 24 |
+
|
| 25 |
+
# Если тебе нужен DOCX → используй корректный пакет:
|
| 26 |
+
python-docx==1.1.2
|
| 27 |
+
|
| 28 |
+
# ── LLMs
|
| 29 |
+
openai>=1.104,<2
|
| 30 |
+
google-generativeai==0.7.2 # зафиксировали, чтобы не было бэктрекинга
|
|
|
src/__init__.py
CHANGED
|
@@ -4,101 +4,16 @@ Import key components for easy use:
|
|
| 4 |
from src import workflow, llm
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
схемами и конфигом. Клади этот файл в директорию, где лежат:
|
| 12 |
-
agent.py, config.py, nodes.py, schemas.py, state.py
|
| 13 |
-
(у тебя это src/).
|
| 14 |
-
"""
|
| 15 |
|
| 16 |
-
# Версия пакета (по желанию обновляй вручную/из git)
|
| 17 |
__version__ = "0.1.0"
|
| 18 |
-
|
| 19 |
-
# ── Граф/сборка
|
| 20 |
-
from .agent import build_workflow
|
| 21 |
-
|
| 22 |
-
# ── Состояние
|
| 23 |
-
from .state import AgentState
|
| 24 |
-
|
| 25 |
-
# ── Схемы/модели
|
| 26 |
-
from .schemas import (
|
| 27 |
-
ComplexityLevel,
|
| 28 |
-
CritiqueFeedback,
|
| 29 |
-
PlannerPlan,
|
| 30 |
-
PlanStep,
|
| 31 |
-
ExecutionReport,
|
| 32 |
-
ToolExecution,
|
| 33 |
-
TaskType,
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
# ── Конфиг/LLM/Tools
|
| 37 |
-
from .config import (
|
| 38 |
-
config,
|
| 39 |
-
TOOLS,
|
| 40 |
-
DEBUGGING_TOOL_NODE,
|
| 41 |
-
llm,
|
| 42 |
-
llm_deterministic,
|
| 43 |
-
planner_llm,
|
| 44 |
-
llm_with_tools,
|
| 45 |
-
llm_criticist,
|
| 46 |
-
llm_reasoning,
|
| 47 |
-
)
|
| 48 |
-
|
| 49 |
-
# ── Узлы/роутеры (если нужно вызывать напрямую или для тестов)
|
| 50 |
-
from .nodes import (
|
| 51 |
-
query_input,
|
| 52 |
-
complexity_assessor,
|
| 53 |
-
planner,
|
| 54 |
-
agent,
|
| 55 |
-
simple_executor,
|
| 56 |
-
critic_evaluator,
|
| 57 |
-
replanner,
|
| 58 |
-
enhanced_finalizer,
|
| 59 |
-
# роутеры
|
| 60 |
-
should_continue,
|
| 61 |
-
should_use_planning,
|
| 62 |
-
should_replan,
|
| 63 |
-
should_use_tools_simple_executor,
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
__all__ = [
|
| 67 |
-
|
| 68 |
-
"
|
| 69 |
-
|
| 70 |
-
"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
# схемы
|
| 74 |
-
"ComplexityLevel",
|
| 75 |
-
"CritiqueFeedback",
|
| 76 |
-
"PlannerPlan",
|
| 77 |
-
"PlanStep",
|
| 78 |
-
"ExecutionReport",
|
| 79 |
-
"ToolExecution",
|
| 80 |
-
"TaskType",
|
| 81 |
-
# конфиг/модели/тулы
|
| 82 |
-
"config",
|
| 83 |
-
"TOOLS",
|
| 84 |
-
"DEBUGGING_TOOL_NODE",
|
| 85 |
-
"llm",
|
| 86 |
-
"llm_deterministic",
|
| 87 |
-
"planner_llm",
|
| 88 |
-
"llm_with_tools",
|
| 89 |
-
"llm_criticist",
|
| 90 |
-
"llm_reasoning",
|
| 91 |
-
# узлы и роутеры
|
| 92 |
-
"query_input",
|
| 93 |
-
"complexity_assessor",
|
| 94 |
-
"planner",
|
| 95 |
-
"agent",
|
| 96 |
-
"simple_executor",
|
| 97 |
-
"critic_evaluator",
|
| 98 |
-
"replanner",
|
| 99 |
-
"enhanced_finalizer",
|
| 100 |
-
"should_continue",
|
| 101 |
-
"should_use_planning",
|
| 102 |
-
"should_replan",
|
| 103 |
-
"should_use_tools_simple_executor",
|
| 104 |
-
]
|
|
|
|
| 4 |
from src import workflow, llm
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
from .config import llm, TOOLS, config, TOOL_NODE, planner_llm
|
| 8 |
+
from .agent import workflow, build_workflow, should_continue
|
| 9 |
+
from .nodes import agent, planner, query_input, critique
|
| 10 |
+
from .schemas import AgentState, PlannerPlan, ComplexityLevel, CritiqueFeedback
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
|
|
|
| 12 |
__version__ = "0.1.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
__all__ = [
|
| 14 |
+
"llm", "TOOLS", "config", "TOOL_NODE", "planner_llm",
|
| 15 |
+
"workflow", "build_workflow", "should_continue",
|
| 16 |
+
"agent", "planner", "query_input", "critique",
|
| 17 |
+
"AgentState", "PlannerPlan", "ComplexityLevel", "CritiqueFeedback",
|
| 18 |
+
"__version__"
|
| 19 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/config.py
CHANGED
|
@@ -3,8 +3,6 @@ from src.tools.tools import *
|
|
| 3 |
from src.tools.code_interpreter import safe_code_run
|
| 4 |
from langgraph.prebuilt import ToolNode
|
| 5 |
from src.schemas import PlannerPlan
|
| 6 |
-
from src.tools.youtube_transcript import extract_youtube_transcript
|
| 7 |
-
from src.tools.video_analyzer import video_qa_gemma
|
| 8 |
from src.utils.utils import log_stage
|
| 9 |
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
|
| 10 |
from dotenv import load_dotenv
|
|
@@ -12,11 +10,11 @@ load_dotenv()
|
|
| 12 |
|
| 13 |
config = {"configurable": {"thread_id": "1"}, "recursion_limit" : 50}
|
| 14 |
|
| 15 |
-
TOOLS = [
|
| 16 |
arxiv_search, wiki_search, add, subtract, multiply, divide,
|
| 17 |
power, analyze_excel_file, analyze_csv_file, analyze_docx_file,
|
| 18 |
analyze_pdf_file, analyze_txt_file,
|
| 19 |
-
vision_qa_gemma, safe_code_run
|
| 20 |
|
| 21 |
|
| 22 |
TOOL_NODE = ToolNode(TOOLS)
|
|
@@ -25,11 +23,9 @@ DEBUGGING_TOOL_NODE = TOOL_NODE
|
|
| 25 |
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7) #default 0.25
|
| 26 |
llm_deterministic = ChatOpenAI(model="gpt-5-mini", temperature=0.05)
|
| 27 |
planner_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1).with_structured_output(PlannerPlan)
|
| 28 |
-
llm_criticist = ChatOpenAI(model="gpt-
|
| 29 |
llm_with_tools = llm_deterministic.bind_tools(TOOLS)
|
| 30 |
llm_reasoning = ChatOpenAI(model="gpt-5-mini", temperature=0.3)
|
| 31 |
-
llm_simple_executor = ChatOpenAI(model="gpt-5-mini", temperature=0.3)
|
| 32 |
-
llm_simple_with_tools = llm_simple_executor.bind_tools(TOOLS)
|
| 33 |
|
| 34 |
|
| 35 |
|
|
|
|
| 3 |
from src.tools.code_interpreter import safe_code_run
|
| 4 |
from langgraph.prebuilt import ToolNode
|
| 5 |
from src.schemas import PlannerPlan
|
|
|
|
|
|
|
| 6 |
from src.utils.utils import log_stage
|
| 7 |
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
|
| 8 |
from dotenv import load_dotenv
|
|
|
|
| 10 |
|
| 11 |
config = {"configurable": {"thread_id": "1"}, "recursion_limit" : 50}
|
| 12 |
|
| 13 |
+
TOOLS = [download_file_from_url, web_search,
|
| 14 |
arxiv_search, wiki_search, add, subtract, multiply, divide,
|
| 15 |
power, analyze_excel_file, analyze_csv_file, analyze_docx_file,
|
| 16 |
analyze_pdf_file, analyze_txt_file,
|
| 17 |
+
vision_qa_gemma, safe_code_run]
|
| 18 |
|
| 19 |
|
| 20 |
TOOL_NODE = ToolNode(TOOLS)
|
|
|
|
| 23 |
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7) #default 0.25
|
| 24 |
llm_deterministic = ChatOpenAI(model="gpt-5-mini", temperature=0.05)
|
| 25 |
planner_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1).with_structured_output(PlannerPlan)
|
| 26 |
+
llm_criticist = ChatOpenAI(model="gpt-5-mini", temperature=0.3)
|
| 27 |
llm_with_tools = llm_deterministic.bind_tools(TOOLS)
|
| 28 |
llm_reasoning = ChatOpenAI(model="gpt-5-mini", temperature=0.3)
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
|
src/main.py
DELETED
|
@@ -1,338 +0,0 @@
|
|
| 1 |
-
"""Ankelodon Agent Adapter for the Hugging Face Agents Course evaluator.
|
| 2 |
-
|
| 3 |
-
This module exposes a simple Gradio-powered wrapper around the
|
| 4 |
-
`ankelodon_multiagent_system` project. It follows the same high-level flow
|
| 5 |
-
as the official GAIA template provided in the course materials: fetch
|
| 6 |
-
evaluation questions from the GAIA API, run your agent to produce
|
| 7 |
-
responses, and submit those responses back to the leaderboard.
|
| 8 |
-
|
| 9 |
-
The key differences between this adapter and the GAIA template are:
|
| 10 |
-
|
| 11 |
-
* It imports and uses your multi‑agent system defined in the `src`
|
| 12 |
-
package (see `src/agent.py`) via the `build_workflow` function. This
|
| 13 |
-
function returns a `langgraph` state machine capable of planning,
|
| 14 |
-
reasoning and executing tools. The adapter calls into this workflow
|
| 15 |
-
with a properly initialised `AgentState` and extracts the final
|
| 16 |
-
answer from the resulting state.
|
| 17 |
-
* It automatically downloads any file attachments associated with a
|
| 18 |
-
task (via the `/files/{task_id}` endpoint exposed by the evaluation
|
| 19 |
-
server) and saves them into a temporary directory. The local file
|
| 20 |
-
paths are passed into the agent through the `files` field of the
|
| 21 |
-
state. Your existing file handling logic (e.g. `preprocess_files`
|
| 22 |
-
in `src/tools/tools.py`) will detect the file type and suggest
|
| 23 |
-
appropriate tools.
|
| 24 |
-
* It strips any leading ``Final answer:`` prefix from the agent's
|
| 25 |
-
response. The evaluation server performs an exact string match
|
| 26 |
-
against the ground truth answer【842261069842380†L108-L112】, so it is
|
| 27 |
-
important that the returned text contains only the answer and
|
| 28 |
-
nothing else.
|
| 29 |
-
|
| 30 |
-
Before running this script yourself, make sure all dependencies in
|
| 31 |
-
`requirements.txt` are installed. To use the Gradio interface locally,
|
| 32 |
-
run `python ankelodon_adapter.py` from the project root. When deploying
|
| 33 |
-
as a Hugging Face Space for leaderboard submission, ensure the
|
| 34 |
-
`SPACE_ID` environment variable is set by the platform; it is used to
|
| 35 |
-
construct a link back to your code for verification.
|
| 36 |
-
"""
|
| 37 |
-
|
| 38 |
-
from __future__ import annotations
|
| 39 |
-
|
| 40 |
-
import os
|
| 41 |
-
import tempfile
|
| 42 |
-
from typing import Optional, List, Dict, Any
|
| 43 |
-
|
| 44 |
-
import requests
|
| 45 |
-
import gradio as gr
|
| 46 |
-
import pandas as pd
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
# Import the multi‑agent system components. When running as a script
|
| 50 |
-
# within the project root, Python's module search path should
|
| 51 |
-
# already include the `src` directory. If you get import errors,
|
| 52 |
-
# ensure that the working directory is the repository root or
|
| 53 |
-
# append `src` to `sys.path` manually before these imports.
|
| 54 |
-
from agent import build_workflow
|
| 55 |
-
from config import config as WORKFLOW_CONFIG
|
| 56 |
-
from state import AgentState
|
| 57 |
-
except Exception as import_err:
|
| 58 |
-
raise RuntimeError(
|
| 59 |
-
"Failed to import the Ankelodon multi-agent system. "
|
| 60 |
-
"Make sure you are running this script from the repository root "
|
| 61 |
-
"and that the project has been installed correctly."
|
| 62 |
-
) from import_err
|
| 63 |
-
|
| 64 |
-
DEFAULT_API_URL: str = "https://agents-course-unit4-scoring.hf.space"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
class AnkelodonAgent:
|
| 68 |
-
"""Simple callable wrapper around the Ankelodon multi‑agent system.
|
| 69 |
-
|
| 70 |
-
Instances of this class can be called directly with a natural
|
| 71 |
-
language question and an optional task identifier. Under the hood it
|
| 72 |
-
builds a `langgraph` workflow using ``build_workflow()``, prepares
|
| 73 |
-
an initial state, fetches any file attachments associated with
|
| 74 |
-
the task, and invokes the workflow to compute a final answer.
|
| 75 |
-
"""
|
| 76 |
-
|
| 77 |
-
def __init__(self) -> None:
|
| 78 |
-
# Initialise the workflow once per agent. Subsequent calls reuse
|
| 79 |
-
# the compiled state machine, which is more efficient than
|
| 80 |
-
# rebuilding it on every question.
|
| 81 |
-
self.workflow = build_workflow()
|
| 82 |
-
|
| 83 |
-
def _download_attachment(self, task_id: str) -> List[str]:
|
| 84 |
-
"""Download a file attachment for the given task ID.
|
| 85 |
-
|
| 86 |
-
The evaluation API exposes a ``/files/{task_id}`` endpoint【842261069842380†L95-L107】.
|
| 87 |
-
This helper downloads the content, infers a file extension
|
| 88 |
-
from the HTTP ``Content-Type`` header and writes the bytes to a
|
| 89 |
-
temporary file. It returns a list of file paths (zero or one
|
| 90 |
-
element) to be included in the agent state.
|
| 91 |
-
"""
|
| 92 |
-
files: List[str] = []
|
| 93 |
-
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 94 |
-
try:
|
| 95 |
-
resp = requests.get(url, timeout=15, allow_redirects=True)
|
| 96 |
-
if resp.status_code == 200 and resp.content:
|
| 97 |
-
# Map common MIME substrings to file extensions. The
|
| 98 |
-
# multi‑agent system's file handling tools use the
|
| 99 |
-
# extension to determine how to process the file.
|
| 100 |
-
ctype = resp.headers.get("content-type", "").lower()
|
| 101 |
-
ext_map = {
|
| 102 |
-
"excel": ".xlsx",
|
| 103 |
-
"sheet": ".xlsx",
|
| 104 |
-
"csv": ".csv",
|
| 105 |
-
"python": ".py",
|
| 106 |
-
"audio": ".mp3",
|
| 107 |
-
"image": ".jpg",
|
| 108 |
-
}
|
| 109 |
-
extension = ""
|
| 110 |
-
for key, val in ext_map.items():
|
| 111 |
-
if key in ctype:
|
| 112 |
-
extension = val
|
| 113 |
-
break
|
| 114 |
-
tmp_dir = tempfile.mkdtemp(prefix="ankelodon_task_")
|
| 115 |
-
filename = f"attachment{extension}"
|
| 116 |
-
path = os.path.join(tmp_dir, filename)
|
| 117 |
-
with open(path, "wb") as fh:
|
| 118 |
-
fh.write(resp.content)
|
| 119 |
-
files.append(path)
|
| 120 |
-
except Exception as e:
|
| 121 |
-
# Log the error to console but don't fail the entire task.
|
| 122 |
-
print(f"[WARNING] Failed to fetch attachment for task {task_id}: {e}")
|
| 123 |
-
return files
|
| 124 |
-
|
| 125 |
-
def __call__(self, question: str, task_id: Optional[str] = None) -> str:
|
| 126 |
-
"""Run the multi‑agent system to answer a question.
|
| 127 |
-
|
| 128 |
-
Parameters
|
| 129 |
-
----------
|
| 130 |
-
question: str
|
| 131 |
-
The natural language query to answer.
|
| 132 |
-
task_id: Optional[str]
|
| 133 |
-
If provided, the ID used to fetch any associated file
|
| 134 |
-
attachment from the evaluation API. Attachments are stored
|
| 135 |
-
locally and passed into the agent via the ``files`` field.
|
| 136 |
-
|
| 137 |
-
Returns
|
| 138 |
-
-------
|
| 139 |
-
str
|
| 140 |
-
The final answer produced by the agent, with any "final
|
| 141 |
-
answer" prefix removed. If no answer is produced the empty
|
| 142 |
-
string is returned.
|
| 143 |
-
"""
|
| 144 |
-
# Build the initial agent state. The AgentState type defines
|
| 145 |
-
# numerous fields, many of which the workflow populates
|
| 146 |
-
# internally. We set only the essentials here. Unrecognised
|
| 147 |
-
# keys are ignored by the underlying state machine.
|
| 148 |
-
state: Dict[str, Any] = {
|
| 149 |
-
"query": question,
|
| 150 |
-
"final_answer": "",
|
| 151 |
-
"plan": None,
|
| 152 |
-
"complexity_assessment": None,
|
| 153 |
-
"current_step": 0,
|
| 154 |
-
"reasoning_done": False,
|
| 155 |
-
"messages": [],
|
| 156 |
-
"files": [],
|
| 157 |
-
"file_contents": {},
|
| 158 |
-
"critique_feedback": None,
|
| 159 |
-
"iteration_count": 0,
|
| 160 |
-
"max_iterations": 3,
|
| 161 |
-
"execution_report": None,
|
| 162 |
-
"previous_tool_results": {},
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
# If a task ID is provided, attempt to download its attachment.
|
| 166 |
-
if task_id:
|
| 167 |
-
attachment_paths = self._download_attachment(task_id)
|
| 168 |
-
if attachment_paths:
|
| 169 |
-
state["files"] = attachment_paths
|
| 170 |
-
|
| 171 |
-
# Invoke the workflow. The `config` parameter defines runtime
|
| 172 |
-
# options such as recursion limits and thread identifiers. It is
|
| 173 |
-
# imported from `src.config`.
|
| 174 |
-
try:
|
| 175 |
-
result_state = self.workflow.invoke(state, config=WORKFLOW_CONFIG)
|
| 176 |
-
except Exception as e:
|
| 177 |
-
print(f"[ERROR] Failed to run workflow: {e}")
|
| 178 |
-
return ""
|
| 179 |
-
|
| 180 |
-
# Extract the final answer. Depending on the branch taken,
|
| 181 |
-
# either the ``final_answer`` key or a generic ``answer`` key may
|
| 182 |
-
# be present. Use whichever exists. Some nodes may prepend
|
| 183 |
-
# "final answer:"; remove it for exact match scoring【842261069842380†L108-L112】.
|
| 184 |
-
answer = ""
|
| 185 |
-
if isinstance(result_state, dict):
|
| 186 |
-
answer = result_state.get("final_answer") or result_state.get("answer") or ""
|
| 187 |
-
if answer:
|
| 188 |
-
answer = answer.replace("Final answer:", "").replace("final answer:", "").strip()
|
| 189 |
-
return answer
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
def run_and_submit_all(profile: Optional[gr.OAuthProfile]) -> tuple[str, pd.DataFrame | None]:
|
| 193 |
-
"""Fetch all questions, run the agent, and submit the answers.
|
| 194 |
-
|
| 195 |
-
This function replicates the behaviour of the GAIA template's
|
| 196 |
-
``run_and_submit_all`` function【566837548679297†L247-L306】 but uses the
|
| 197 |
-
``AnkelodonAgent`` class defined above. It is bound to a Gradio
|
| 198 |
-
button in the UI. On success it returns a status message and a
|
| 199 |
-
DataFrame of results; on failure it returns an error message and
|
| 200 |
-
``None`` or an empty DataFrame.
|
| 201 |
-
"""
|
| 202 |
-
# Require the user to be logged in so we can report the username.
|
| 203 |
-
if not profile:
|
| 204 |
-
return "Please Login to Hugging Face with the button.", None
|
| 205 |
-
username = getattr(profile, "username", "").strip()
|
| 206 |
-
|
| 207 |
-
api_url = DEFAULT_API_URL
|
| 208 |
-
questions_url = f"{api_url}/questions"
|
| 209 |
-
submit_url = f"{api_url}/submit"
|
| 210 |
-
|
| 211 |
-
# Instantiate the agent once.
|
| 212 |
-
try:
|
| 213 |
-
agent = AnkelodonAgent()
|
| 214 |
-
print("Ankelodon agent initialised successfully")
|
| 215 |
-
except Exception as e:
|
| 216 |
-
err_msg = f"Error initialising agent: {e}"
|
| 217 |
-
print(err_msg)
|
| 218 |
-
return err_msg, None
|
| 219 |
-
|
| 220 |
-
# Fetch questions from the evaluation API.【566837548679297†L247-L268】
|
| 221 |
-
try:
|
| 222 |
-
print(f"Fetching questions from: {questions_url}")
|
| 223 |
-
resp = requests.get(questions_url, timeout=15)
|
| 224 |
-
resp.raise_for_status()
|
| 225 |
-
questions_data = resp.json()
|
| 226 |
-
if not questions_data:
|
| 227 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 228 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 229 |
-
except Exception as e:
|
| 230 |
-
err_msg = f"Error fetching questions: {e}"
|
| 231 |
-
print(err_msg)
|
| 232 |
-
return err_msg, None
|
| 233 |
-
|
| 234 |
-
# Run the agent on each question.
|
| 235 |
-
results_log: List[Dict[str, Any]] = []
|
| 236 |
-
answers_payload: List[Dict[str, str]] = []
|
| 237 |
-
print(f"Running agent on {len(questions_data)} questions…")
|
| 238 |
-
for item in questions_data:
|
| 239 |
-
task_id = item.get("task_id")
|
| 240 |
-
question_text = item.get("question")
|
| 241 |
-
if not task_id or question_text is None:
|
| 242 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 243 |
-
continue
|
| 244 |
-
try:
|
| 245 |
-
answer = agent(question_text, task_id)
|
| 246 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
| 247 |
-
results_log.append({
|
| 248 |
-
"Task ID": task_id,
|
| 249 |
-
"Question": question_text,
|
| 250 |
-
"Submitted Answer": answer,
|
| 251 |
-
})
|
| 252 |
-
except Exception as e:
|
| 253 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 254 |
-
results_log.append({
|
| 255 |
-
"Task ID": task_id,
|
| 256 |
-
"Question": question_text,
|
| 257 |
-
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 258 |
-
})
|
| 259 |
-
|
| 260 |
-
if not answers_payload:
|
| 261 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 262 |
-
|
| 263 |
-
# Prepare submission payload. The leaderboard displays a link to your
|
| 264 |
-
# code; this is constructed from the SPACE_ID environment variable.
|
| 265 |
-
space_id = os.getenv("SPACE_ID", "")
|
| 266 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
|
| 267 |
-
submission_data = {
|
| 268 |
-
"username": username,
|
| 269 |
-
"agent_code": agent_code,
|
| 270 |
-
"answers": answers_payload,
|
| 271 |
-
}
|
| 272 |
-
|
| 273 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 274 |
-
try:
|
| 275 |
-
submission_resp = requests.post(submit_url, json=submission_data, timeout=60)
|
| 276 |
-
submission_resp.raise_for_status()
|
| 277 |
-
result_data = submission_resp.json()
|
| 278 |
-
final_status = (
|
| 279 |
-
f"Submission Successful!\n"
|
| 280 |
-
f"User: {result_data.get('username')}\n"
|
| 281 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 282 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 283 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 284 |
-
)
|
| 285 |
-
print("Submission successful.")
|
| 286 |
-
return final_status, pd.DataFrame(results_log)
|
| 287 |
-
except Exception as e:
|
| 288 |
-
err_msg = f"Submission Failed: {e}"
|
| 289 |
-
print(err_msg)
|
| 290 |
-
return err_msg, pd.DataFrame(results_log)
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
# Build the Gradio interface. This interface resembles the official
|
| 294 |
-
# GAIA template【566837548679297†L372-L401】 but runs your Ankelodon agent.
|
| 295 |
-
with gr.Blocks() as demo:
|
| 296 |
-
gr.Markdown("# Ankelodon Agent Evaluation Runner")
|
| 297 |
-
gr.Markdown(
|
| 298 |
-
"""
|
| 299 |
-
**Instructions**
|
| 300 |
-
|
| 301 |
-
1. Clone this repository or duplicate the associated Hugging Face Space.
|
| 302 |
-
2. Log in to your Hugging Face account using the button below. Your HF
|
| 303 |
-
username is used to attribute your submission on the leaderboard.
|
| 304 |
-
3. Click **Run Evaluation & Submit All Answers** to fetch the questions,
|
| 305 |
-
run the Ankelodon agent on each one, submit your answers, and display
|
| 306 |
-
the resulting score and answers.
|
| 307 |
-
|
| 308 |
-
---
|
| 309 |
-
This template is intentionally lightweight. Feel free to customise it –
|
| 310 |
-
add caching, parallel execution or additional logging as you see fit.
|
| 311 |
-
"""
|
| 312 |
-
)
|
| 313 |
-
gr.LoginButton()
|
| 314 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 315 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 316 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 317 |
-
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
if __name__ == "__main__":
|
| 321 |
-
# When running locally, print some information about the environment.
|
| 322 |
-
print("\n" + "-" * 30 + " Ankelodon Adapter Starting " + "-" * 30)
|
| 323 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 324 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 325 |
-
if space_host_startup:
|
| 326 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 327 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 328 |
-
else:
|
| 329 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 330 |
-
if space_id_startup:
|
| 331 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 332 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 333 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 334 |
-
else:
|
| 335 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 336 |
-
print("-" * (60 + len(" Ankelodon Adapter Starting ")) + "\n")
|
| 337 |
-
# Launch the Gradio app.
|
| 338 |
-
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/nodes.py
CHANGED
|
@@ -13,7 +13,7 @@ from src.prompts.prompts import (
|
|
| 13 |
CRITIC_PROMPT,
|
| 14 |
)
|
| 15 |
|
| 16 |
-
from src.config import llm_reasoning, TOOLS, planner_llm, llm_with_tools, llm_deterministic, llm_criticist
|
| 17 |
from src.schemas import PlannerPlan, ComplexityLevel, CritiqueFeedback, ExecutionReport, ToolExecution
|
| 18 |
|
| 19 |
from src.utils.utils import (
|
|
@@ -38,14 +38,16 @@ def _build_planner_prompt(state: AgentState, extra_context: Optional[str] = None
|
|
| 38 |
|
| 39 |
def query_input(state : AgentState) -> AgentState:
|
| 40 |
log_stage("USER QUERY", icon="💡")
|
|
|
|
| 41 |
|
| 42 |
files = state.get("files", [])
|
| 43 |
if files:
|
|
|
|
| 44 |
log_stage("FILE PREPARATION", subtitle=f"Processing {len(files)} file(s)", icon="📁")
|
| 45 |
file_info = preprocess_files(files)
|
| 46 |
|
| 47 |
for file_path, info in file_info.items():
|
| 48 |
-
|
| 49 |
log_key_values(
|
| 50 |
[
|
| 51 |
("path", file_path),
|
|
@@ -101,7 +103,13 @@ def planner(state : AgentState) -> AgentState:
|
|
| 101 |
|
| 102 |
def agent(state: AgentState) -> AgentState:
|
| 103 |
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
current_step = state.get("current_step", 0)
|
| 106 |
reasoning_done = state.get("reasoning_done", False)
|
| 107 |
plan: Optional[PlannerPlan] = state.get("plan")
|
|
@@ -109,6 +117,17 @@ def agent(state: AgentState) -> AgentState:
|
|
| 109 |
|
| 110 |
#steps = state["plan"].steps
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
if not plan or not hasattr(plan, 'steps'):
|
| 113 |
log_stage("PLAN VALIDATION", subtitle="Planner returned no actionable steps", icon="⚠️")
|
| 114 |
warning = AIMessage(content="No valid plan available. <FINAL_ANSWER>")
|
|
@@ -138,6 +157,7 @@ def agent(state: AgentState) -> AgentState:
|
|
| 138 |
}
|
| 139 |
|
| 140 |
current_step_info = steps[current_step]
|
|
|
|
| 141 |
|
| 142 |
log_stage(
|
| 143 |
"EXECUTION",
|
|
@@ -181,9 +201,18 @@ def agent(state: AgentState) -> AgentState:
|
|
| 181 |
|
| 182 |
if not reasoning_done:
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
log_stage("REASONING", subtitle=f"{current_step_info.id}", icon="🧠")
|
| 185 |
-
|
| 186 |
|
|
|
|
| 187 |
file_context = ""
|
| 188 |
file_contents = state.get("file_contents", {})
|
| 189 |
if file_contents:
|
|
@@ -213,8 +242,8 @@ def agent(state: AgentState) -> AgentState:
|
|
| 213 |
stack = [sys_msg] + state["messages"]
|
| 214 |
|
| 215 |
step = llm_reasoning.invoke(stack)
|
| 216 |
-
|
| 217 |
-
|
| 218 |
|
| 219 |
return {
|
| 220 |
"messages" : state["messages"] + [step],
|
|
@@ -237,7 +266,7 @@ def agent(state: AgentState) -> AgentState:
|
|
| 237 |
# Используем модель С инструментами для выполнения
|
| 238 |
step = llm_with_tools.invoke(stack)
|
| 239 |
print("=== TOOL EXECUTION ===")
|
| 240 |
-
|
| 241 |
print(f"Tool calls: {step.tool_calls}")
|
| 242 |
|
| 243 |
return {
|
|
@@ -249,7 +278,7 @@ def agent(state: AgentState) -> AgentState:
|
|
| 249 |
def should_continue(state : AgentState) -> bool:
|
| 250 |
|
| 251 |
last_message = state["messages"][-1]
|
| 252 |
-
|
| 253 |
reasoning_done = state.get("reasoning_done", False)
|
| 254 |
plan = state.get("plan", None)
|
| 255 |
current_step = state.get("current_step", 0)
|
|
@@ -372,9 +401,7 @@ def enhanced_finalizer(state: AgentState) -> AgentState:
|
|
| 372 |
|
| 373 |
# Format final answer for user
|
| 374 |
formatted_answer = format_final_answer(execution_report, state.get('complexity_assessment', {}))
|
| 375 |
-
|
| 376 |
-
print(f"FINAL ANSWER FOR EVALUATOR: {execution_report.final_answer}")
|
| 377 |
-
|
| 378 |
return {
|
| 379 |
"execution_report": execution_report,
|
| 380 |
"final_answer": formatted_answer
|
|
@@ -395,7 +422,7 @@ def simple_executor(state: AgentState) -> AgentState:
|
|
| 395 |
Provide a clear, concise answer.
|
| 396 |
"""
|
| 397 |
|
| 398 |
-
response =
|
| 399 |
SystemMessage(content=simple_prompt),
|
| 400 |
HumanMessage(content=state['query'])
|
| 401 |
])
|
|
@@ -475,16 +502,13 @@ def should_replan(state: AgentState) -> str:
|
|
| 475 |
critique = state.get("critique_feedback")
|
| 476 |
iteration_count = state.get("iteration_count", 0)
|
| 477 |
max_iterations = state.get("max_iterations", 3)
|
| 478 |
-
|
| 479 |
|
| 480 |
print(f"=== REPLAN DECISION ===")
|
| 481 |
print(f"Iteration: {iteration_count}/{max_iterations}")
|
| 482 |
print(f"Quality score: {critique.quality_score if critique else 'N/A'}")
|
| 483 |
print(f"Needs replanning: {critique.needs_replanning if critique else 'N/A'}")
|
| 484 |
|
| 485 |
-
if not activator:
|
| 486 |
-
return "end"
|
| 487 |
-
|
| 488 |
if not critique:
|
| 489 |
return "end"
|
| 490 |
|
|
@@ -550,11 +574,11 @@ def replanner_old(state: AgentState) -> AgentState:
|
|
| 550 |
isinstance(msg, HumanMessage)):
|
| 551 |
essential_messages.append(msg)
|
| 552 |
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
|
| 559 |
return {
|
| 560 |
"plan": revised_plan,
|
|
@@ -597,7 +621,7 @@ def replanner(state: AgentState) -> AgentState:
|
|
| 597 |
|
| 598 |
# ИСПРАВЛЕНИЕ: Сохраняем важные результаты инструментов
|
| 599 |
current_messages = state.get("messages", [])
|
| 600 |
-
|
| 601 |
# Находим полезные результаты инструментов
|
| 602 |
preserved_messages = []
|
| 603 |
tool_results = {}
|
|
@@ -636,7 +660,7 @@ def replanner(state: AgentState) -> AgentState:
|
|
| 636 |
preserved_messages.append(msg)
|
| 637 |
|
| 638 |
print(f"Preserved {len(tool_results)} tool results")
|
| 639 |
-
|
| 640 |
|
| 641 |
# Добавляем контекст о доступных результатах
|
| 642 |
if tool_results:
|
|
|
|
| 13 |
CRITIC_PROMPT,
|
| 14 |
)
|
| 15 |
|
| 16 |
+
from src.config import llm_reasoning, TOOLS, planner_llm, llm_with_tools, llm_deterministic, llm_criticist
|
| 17 |
from src.schemas import PlannerPlan, ComplexityLevel, CritiqueFeedback, ExecutionReport, ToolExecution
|
| 18 |
|
| 19 |
from src.utils.utils import (
|
|
|
|
| 38 |
|
| 39 |
def query_input(state : AgentState) -> AgentState:
|
| 40 |
log_stage("USER QUERY", icon="💡")
|
| 41 |
+
#print("=== USER QUERY TRANSFERED TO AGENT ===")
|
| 42 |
|
| 43 |
files = state.get("files", [])
|
| 44 |
if files:
|
| 45 |
+
print(f"Processing {len(files)} files:")
|
| 46 |
log_stage("FILE PREPARATION", subtitle=f"Processing {len(files)} file(s)", icon="📁")
|
| 47 |
file_info = preprocess_files(files)
|
| 48 |
|
| 49 |
for file_path, info in file_info.items():
|
| 50 |
+
print(f" - {file_path}: {info['type']} ({info['size']} bytes) -> {info['suggested_tool']}")
|
| 51 |
log_key_values(
|
| 52 |
[
|
| 53 |
("path", file_path),
|
|
|
|
| 103 |
|
| 104 |
def agent(state: AgentState) -> AgentState:
|
| 105 |
|
| 106 |
+
"""
|
| 107 |
+
sys_msg = SystemMessage(
|
| 108 |
+
content=SYSTEM_EXECUTOR_PROMPT.strip().format(
|
| 109 |
+
plan=json.dumps(state["plan"], indent=2)
|
| 110 |
+
)
|
| 111 |
+
)
|
| 112 |
+
"""
|
| 113 |
current_step = state.get("current_step", 0)
|
| 114 |
reasoning_done = state.get("reasoning_done", False)
|
| 115 |
plan: Optional[PlannerPlan] = state.get("plan")
|
|
|
|
| 117 |
|
| 118 |
#steps = state["plan"].steps
|
| 119 |
|
| 120 |
+
"""
|
| 121 |
+
print(f"=== AGENT DEBUG ===")
|
| 122 |
+
print(f"Current step: {current_step}")
|
| 123 |
+
print(f"Reasoning done: {reasoning_done}")
|
| 124 |
+
print(f"Plan exists: {plan is not None}")
|
| 125 |
+
print(f"Total steps in plan: {len(plan.steps) if plan else 'No plan'}")
|
| 126 |
+
|
| 127 |
+
if not plan or not hasattr(plan, 'steps') or not plan.steps:
|
| 128 |
+
print("ERROR: No valid plan found!")
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
if not plan or not hasattr(plan, 'steps'):
|
| 132 |
log_stage("PLAN VALIDATION", subtitle="Planner returned no actionable steps", icon="⚠️")
|
| 133 |
warning = AIMessage(content="No valid plan available. <FINAL_ANSWER>")
|
|
|
|
| 157 |
}
|
| 158 |
|
| 159 |
current_step_info = steps[current_step]
|
| 160 |
+
#print(f"Executing step {current_step + 1}: {current_step_info.description}")
|
| 161 |
|
| 162 |
log_stage(
|
| 163 |
"EXECUTION",
|
|
|
|
| 201 |
|
| 202 |
if not reasoning_done:
|
| 203 |
|
| 204 |
+
instruction = HumanMessage(
|
| 205 |
+
content=(
|
| 206 |
+
"Provide reasoning for this step inside <REASONING>...</REASONING>. "
|
| 207 |
+
"Do not call any tools yet."
|
| 208 |
+
)
|
| 209 |
+
)
|
| 210 |
+
stack = [system_message] + state["messages"] + [instruction]
|
| 211 |
+
reasoning_response = llm_reasoning.invoke(stack) #default llm
|
| 212 |
log_stage("REASONING", subtitle=f"{current_step_info.id}", icon="🧠")
|
| 213 |
+
print(reasoning_response.content)
|
| 214 |
|
| 215 |
+
# ✅ ДОБАВЛЕНО: Специальный контекст для файлов
|
| 216 |
file_context = ""
|
| 217 |
file_contents = state.get("file_contents", {})
|
| 218 |
if file_contents:
|
|
|
|
| 242 |
stack = [sys_msg] + state["messages"]
|
| 243 |
|
| 244 |
step = llm_reasoning.invoke(stack)
|
| 245 |
+
print("=== REASONING STEP ===")
|
| 246 |
+
print(step.content)
|
| 247 |
|
| 248 |
return {
|
| 249 |
"messages" : state["messages"] + [step],
|
|
|
|
| 266 |
# Используем модель С инструментами для выполнения
|
| 267 |
step = llm_with_tools.invoke(stack)
|
| 268 |
print("=== TOOL EXECUTION ===")
|
| 269 |
+
print(step)
|
| 270 |
print(f"Tool calls: {step.tool_calls}")
|
| 271 |
|
| 272 |
return {
|
|
|
|
| 278 |
def should_continue(state : AgentState) -> bool:
|
| 279 |
|
| 280 |
last_message = state["messages"][-1]
|
| 281 |
+
print(f"=== LAST MESSAGE WAS: {last_message} ===")
|
| 282 |
reasoning_done = state.get("reasoning_done", False)
|
| 283 |
plan = state.get("plan", None)
|
| 284 |
current_step = state.get("current_step", 0)
|
|
|
|
| 401 |
|
| 402 |
# Format final answer for user
|
| 403 |
formatted_answer = format_final_answer(execution_report, state.get('complexity_assessment', {}))
|
| 404 |
+
print(execution_report)
|
|
|
|
|
|
|
| 405 |
return {
|
| 406 |
"execution_report": execution_report,
|
| 407 |
"final_answer": formatted_answer
|
|
|
|
| 422 |
Provide a clear, concise answer.
|
| 423 |
"""
|
| 424 |
|
| 425 |
+
response = llm_with_tools.invoke([
|
| 426 |
SystemMessage(content=simple_prompt),
|
| 427 |
HumanMessage(content=state['query'])
|
| 428 |
])
|
|
|
|
| 502 |
critique = state.get("critique_feedback")
|
| 503 |
iteration_count = state.get("iteration_count", 0)
|
| 504 |
max_iterations = state.get("max_iterations", 3)
|
| 505 |
+
|
| 506 |
|
| 507 |
print(f"=== REPLAN DECISION ===")
|
| 508 |
print(f"Iteration: {iteration_count}/{max_iterations}")
|
| 509 |
print(f"Quality score: {critique.quality_score if critique else 'N/A'}")
|
| 510 |
print(f"Needs replanning: {critique.needs_replanning if critique else 'N/A'}")
|
| 511 |
|
|
|
|
|
|
|
|
|
|
| 512 |
if not critique:
|
| 513 |
return "end"
|
| 514 |
|
|
|
|
| 574 |
isinstance(msg, HumanMessage)):
|
| 575 |
essential_messages.append(msg)
|
| 576 |
|
| 577 |
+
print(f"Cleaned message history: {len(current_messages)} -> {len(essential_messages)} messages")
|
| 578 |
+
print("=== ESSENTIAL MESSAGES ===")
|
| 579 |
+
print(essential_messages)
|
| 580 |
+
print("=== AGENT STATE ===")
|
| 581 |
+
print(state["messages"])
|
| 582 |
|
| 583 |
return {
|
| 584 |
"plan": revised_plan,
|
|
|
|
| 621 |
|
| 622 |
# ИСПРАВЛЕНИЕ: Сохраняем важные результаты инструментов
|
| 623 |
current_messages = state.get("messages", [])
|
| 624 |
+
|
| 625 |
# Находим полезные результаты инструментов
|
| 626 |
preserved_messages = []
|
| 627 |
tool_results = {}
|
|
|
|
| 660 |
preserved_messages.append(msg)
|
| 661 |
|
| 662 |
print(f"Preserved {len(tool_results)} tool results")
|
| 663 |
+
print(f"Cleaned message history: {len(current_messages)} -> {len(preserved_messages)} messages")
|
| 664 |
|
| 665 |
# Добавляем контекст о доступных результатах
|
| 666 |
if tool_results:
|
src/prompts/prompts.py
CHANGED
|
@@ -1,310 +1,221 @@
|
|
| 1 |
-
|
| 2 |
-
You are the planner of a multi-tool agent. Build a short, realistic plan that the executor can follow.
|
| 3 |
-
|
| 4 |
-
Available tools: {tool_catalogue}
|
| 5 |
-
Known local files: {file_list}
|
| 6 |
-
Additional context: {extra_context}
|
| 7 |
-
|
| 8 |
-
CRITICAL COMPUTATION RULE: ANY mathematical calculation, counting, statistical analysis, or numerical computation MUST be performed using either:
|
| 9 |
-
- Mathematical tools (calculator, math functions) for simple calculations
|
| 10 |
-
- Code execution tools (Python/JavaScript) for complex calculations, data analysis, or statistical operations
|
| 11 |
-
NEVER perform calculations manually or estimate numerical results.
|
| 12 |
-
|
| 13 |
-
TASK BREAKDOWN EXAMPLES:
|
| 14 |
-
|
| 15 |
-
Example 1: "Analyze sales data and calculate growth rates"
|
| 16 |
-
{{
|
| 17 |
-
"steps": [
|
| 18 |
-
{{"id": "s1", "goal": "Load and examine the sales data file", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 19 |
-
{{"id": "s2", "goal": "Calculate monthly growth rates using Python", "tool": "safe_code_run"}},
|
| 20 |
-
{{"id": "s3", "goal": "Generate summary statistics and trends", "tool": "safe_code_run"}}
|
| 21 |
-
]
|
| 22 |
-
}}ф
|
| 23 |
-
|
| 24 |
-
Example 2: "Research recent AI developments and summarize key trends"
|
| 25 |
-
{{
|
| 26 |
-
"steps": [
|
| 27 |
-
{{"id": "s1", "goal": "Search for recent AI news and developments", "tool": "web_search"}},
|
| 28 |
-
{{"id": "s2", "goal": "
|
| 29 |
-
{{"id": "s3", "goal": "Extract and organize key information from articles", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 30 |
-
{{"id": "s4", "goal": "Analyze and synthesize key trends from gathered information", "tool": null}}
|
| 31 |
-
]
|
| 32 |
-
}}
|
| 33 |
-
|
| 34 |
-
Example 3: "Compare performance metrics between two datasets"
|
| 35 |
-
{{
|
| 36 |
-
"steps": [
|
| 37 |
-
{{"id": "s1", "goal": "Load first dataset and examine structure", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 38 |
-
{{"id": "s2", "goal": "Load second dataset and examine structure", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 39 |
-
{{"id": "s3", "goal": "Calculate statistical metrics for both datasets using code", "tool": "safe_code_run"}},
|
| 40 |
-
{{"id": "s4", "goal": "Perform statistical comparison and significance testing", "tool": "safe_code_run"}}
|
| 41 |
-
]
|
| 42 |
-
}}
|
| 43 |
-
|
| 44 |
-
Example 4: "Create a budget analysis from expense data"
|
| 45 |
-
{{
|
| 46 |
-
"steps": [
|
| 47 |
-
{{"id": "s1", "goal": "Load expense data and validate format", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 48 |
-
{{"id": "s2", "goal": "Calculate category totals and percentages using code", "tool": "safe_code_run"}},
|
| 49 |
-
{{"id": "s3", "goal": "Generate budget variance analysis and projections", "tool": "safe_code_run"}},
|
| 50 |
-
{{"id": "s4", "goal": "Create visualization of spending patterns", "tool": "safe_code_run"}}
|
| 51 |
-
]
|
| 52 |
-
}}
|
| 53 |
-
|
| 54 |
-
Return a single JSON object with this structure:
|
| 55 |
-
{{
|
| 56 |
-
"task_type": "info|calc|table|doc_qa|image_qa|multi_hop",
|
| 57 |
-
"summary": "One sentence on the chosen approach",
|
| 58 |
-
"assumptions": ["optional clarifications"],
|
| 59 |
-
"steps": [
|
| 60 |
-
{{
|
| 61 |
-
"id": "s1",
|
| 62 |
-
"goal": "Action to take and why it helps",
|
| 63 |
-
"tool": "tool_name_or_null",
|
| 64 |
-
"inputs": "Key parameters or references (files, URLs, prior steps)",
|
| 65 |
-
"expected_result": "How you know the step succeeded",
|
| 66 |
-
"on_fail": "replan|stop"
|
| 67 |
-
}}
|
| 68 |
-
],
|
| 69 |
-
"answer_guidelines": "Reminders for the final response (citations, format, units, etc.)"
|
| 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 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
5
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
3. COMPLEX: Multi-step problems requiring planning, multiple tools, and sophisticated reasoning
|
| 222 |
-
- Examples: "Research market trends and create investment strategy", "Analyze multiple data sources and predict outcomes"
|
| 223 |
-
- "Build comprehensive report from various inputs", "Multi-stage data processing with validation"
|
| 224 |
-
|
| 225 |
-
MOST OF THE LOGICAL TASKS ARE SIMPLE, UNLESS THEY REQUIRE TOOLS.
|
| 226 |
-
|
| 227 |
-
ASSESSMENT CRITERIA:
|
| 228 |
-
- Number of distinct steps likely needed (1 = Simple, 2-4 = Moderate, 5+ = Complex)
|
| 229 |
-
- Tool complexity and dependencies between steps
|
| 230 |
-
- Data processing requirements and validation needs
|
| 231 |
-
- Need for intermediate reasoning and synthesis
|
| 232 |
-
- Risk of failure without proper step-by-step planning
|
| 233 |
-
- Presence of calculations (automatically requires tool usage)
|
| 234 |
-
|
| 235 |
-
SPECIAL CONSIDERATIONS:
|
| 236 |
-
- Any calculation/counting task requires tools (affects complexity assessment)
|
| 237 |
-
- File analysis tasks usually need multiple steps (load + analyze + calculate)
|
| 238 |
-
- Research tasks typically need search + fetch/extract + synthesis steps
|
| 239 |
-
- Comparison tasks need separate analysis steps for each item being compared
|
| 240 |
-
|
| 241 |
-
RULES:
|
| 242 |
-
- SIMPLE queries may bypass planning for non-calculation tasks
|
| 243 |
-
- MODERATE queries benefit from lightweight planning
|
| 244 |
-
- COMPLEX queries require full planning with fallbacks
|
| 245 |
-
- When in doubt, err toward higher complexity
|
| 246 |
-
- Calculation tasks are never truly "simple" due to mandatory tool usage
|
| 247 |
-
|
| 248 |
-
Analyze the query and respond with your assessment.
|
| 249 |
-
"""
|
| 250 |
-
|
| 251 |
-
CRITIC_PROMPT = """
|
| 252 |
-
You are the CRITIC of a multi-tool agent system.
|
| 253 |
-
Your job is to evaluate execution reports and provide detailed feedback.
|
| 254 |
-
|
| 255 |
-
EVALUATION FRAMEWORK:
|
| 256 |
-
|
| 257 |
-
1. COMPLETENESS (0-3 points):
|
| 258 |
-
- 3: Fully addresses all aspects of the query
|
| 259 |
-
- 2: Addresses main aspects, minor gaps
|
| 260 |
-
- 1: Partial answer, significant gaps
|
| 261 |
-
- 0: Incomplete or off-topic
|
| 262 |
-
|
| 263 |
-
2. ACCURACY (0-3 points):
|
| 264 |
-
- 3: All information appears accurate and well-sourced
|
| 265 |
-
- 2: Mostly accurate, minor issues
|
| 266 |
-
- 1: Some accuracy concerns
|
| 267 |
-
- 0: Significant accuracy problems
|
| 268 |
-
|
| 269 |
-
3. METHODOLOGY (0-2 points):
|
| 270 |
-
- 2: Appropriate tools and approach used, proper calculation methods
|
| 271 |
-
- 1: Acceptable approach, could be better
|
| 272 |
-
- 0: Poor methodology, manual calculations when tools required, or wrong tool selection
|
| 273 |
-
|
| 274 |
-
4. EVIDENCE (0-2 points):
|
| 275 |
-
- 2: Strong evidence and sources provided, calculations verifiable
|
| 276 |
-
- 1: Some evidence provided
|
| 277 |
-
- 0: Insufficient evidence or unverifiable calculations
|
| 278 |
-
|
| 279 |
-
CRITICAL VIOLATIONS (Automatic score reduction):
|
| 280 |
-
- Manual calculations instead of using tools: -2 points
|
| 281 |
-
- Skipped validation steps for numerical results: -1 point
|
| 282 |
-
- Missing citations for factual claims: -1 point
|
| 283 |
-
|
| 284 |
-
TOTAL SCORE: /10 points
|
| 285 |
-
|
| 286 |
-
DECISION THRESHOLDS:
|
| 287 |
-
- 8-10: Accept (excellent quality)
|
| 288 |
-
- 6-7: Accept with minor notes
|
| 289 |
-
- 4-5: Marginal, consider replanning
|
| 290 |
-
- 0-3: Reject, requires replanning
|
| 291 |
-
|
| 292 |
-
EXECUTION REPORT TO EVALUATE:
|
| 293 |
-
Query: {query}
|
| 294 |
-
Approach: {approach}
|
| 295 |
-
Tools Used: {tools}
|
| 296 |
-
Key Findings: {findings}
|
| 297 |
-
Sources: {sources}
|
| 298 |
-
Confidence: {confidence}
|
| 299 |
-
Limitations: {limitations}
|
| 300 |
-
Final Answer: {answer}
|
| 301 |
-
|
| 302 |
-
SPECIAL ATTENTION POINTS:
|
| 303 |
-
- Were calculations performed using appropriate tools?
|
| 304 |
-
- Are numerical results properly validated and sourced?
|
| 305 |
-
- Was the task broken down appropriately or rushed through?
|
| 306 |
-
- Are sources properly cited and verifiable?
|
| 307 |
-
|
| 308 |
-
Provide detailed critique focusing on what works well and what could be improved.
|
| 309 |
-
For simple definitional or informational queries without calculations, you may respond with "NO CRITIC NEEDED".
|
| 310 |
"""
|
|
|
|
| 1 |
+
SYSTEM_PROMPT_PLANNER = """
|
| 2 |
+
You are the planner of a multi-tool agent. Build a short, realistic plan that the executor can follow.
|
| 3 |
+
|
| 4 |
+
Available tools: {tool_catalogue}
|
| 5 |
+
Known local files: {file_list}
|
| 6 |
+
Additional context: {extra_context}
|
| 7 |
+
|
| 8 |
+
CRITICAL COMPUTATION RULE: ANY mathematical calculation, counting, statistical analysis, or numerical computation MUST be performed using either:
|
| 9 |
+
- Mathematical tools (calculator, math functions) for simple calculations
|
| 10 |
+
- Code execution tools (Python/JavaScript) for complex calculations, data analysis, or statistical operations
|
| 11 |
+
NEVER perform calculations manually or estimate numerical results.
|
| 12 |
+
|
| 13 |
+
TASK BREAKDOWN EXAMPLES:
|
| 14 |
+
|
| 15 |
+
Example 1: "Analyze sales data and calculate growth rates"
|
| 16 |
+
{{
|
| 17 |
+
"steps": [
|
| 18 |
+
{{"id": "s1", "goal": "Load and examine the sales data file", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 19 |
+
{{"id": "s2", "goal": "Calculate monthly growth rates using Python", "tool": "safe_code_run"}},
|
| 20 |
+
{{"id": "s3", "goal": "Generate summary statistics and trends", "tool": "safe_code_run"}}
|
| 21 |
+
]
|
| 22 |
+
}}ф
|
| 23 |
+
|
| 24 |
+
Example 2: "Research recent AI developments and summarize key trends"
|
| 25 |
+
{{
|
| 26 |
+
"steps": [
|
| 27 |
+
{{"id": "s1", "goal": "Search for recent AI news and developments", "tool": "web_search"}},
|
| 28 |
+
{{"id": "s2", "goal": "Download relevant articles", "tool": "ddownload_file_from_url"}},
|
| 29 |
+
{{"id": "s3", "goal": "Extract and organize key information from articles", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 30 |
+
{{"id": "s4", "goal": "Analyze and synthesize key trends from gathered information", "tool": null}}
|
| 31 |
+
]
|
| 32 |
+
}}
|
| 33 |
+
|
| 34 |
+
Example 3: "Compare performance metrics between two datasets"
|
| 35 |
+
{{
|
| 36 |
+
"steps": [
|
| 37 |
+
{{"id": "s1", "goal": "Load first dataset and examine structure", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 38 |
+
{{"id": "s2", "goal": "Load second dataset and examine structure", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 39 |
+
{{"id": "s3", "goal": "Calculate statistical metrics for both datasets using code", "tool": "safe_code_run"}},
|
| 40 |
+
{{"id": "s4", "goal": "Perform statistical comparison and significance testing", "tool": "safe_code_run"}}
|
| 41 |
+
]
|
| 42 |
+
}}
|
| 43 |
+
|
| 44 |
+
Example 4: "Create a budget analysis from expense data"
|
| 45 |
+
{{
|
| 46 |
+
"steps": [
|
| 47 |
+
{{"id": "s1", "goal": "Load expense data and validate format", "tool": "analyze_(csv, docx, pdf etc.)_file"}},
|
| 48 |
+
{{"id": "s2", "goal": "Calculate category totals and percentages using code", "tool": "safe_code_run"}},
|
| 49 |
+
{{"id": "s3", "goal": "Generate budget variance analysis and projections", "tool": "safe_code_run"}},
|
| 50 |
+
{{"id": "s4", "goal": "Create visualization of spending patterns", "tool": "safe_code_run"}}
|
| 51 |
+
]
|
| 52 |
+
}}
|
| 53 |
+
|
| 54 |
+
Return a single JSON object with this structure:
|
| 55 |
+
{{
|
| 56 |
+
"task_type": "info|calc|table|doc_qa|image_qa|multi_hop",
|
| 57 |
+
"summary": "One sentence on the chosen approach",
|
| 58 |
+
"assumptions": ["optional clarifications"],
|
| 59 |
+
"steps": [
|
| 60 |
+
{{
|
| 61 |
+
"id": "s1",
|
| 62 |
+
"goal": "Action to take and why it helps",
|
| 63 |
+
"tool": "tool_name_or_null",
|
| 64 |
+
"inputs": "Key parameters or references (files, URLs, prior steps)",
|
| 65 |
+
"expected_result": "How you know the step succeeded",
|
| 66 |
+
"on_fail": "replan|stop"
|
| 67 |
+
}}
|
| 68 |
+
],
|
| 69 |
+
"answer_guidelines": "Reminders for the final response (citations, format, units, etc.)"
|
| 70 |
+
}}
|
| 71 |
+
|
| 72 |
+
Ground rules:
|
| 73 |
+
- Prefer 2-4 steps for most tasks. Single steps only for truly trivial queries. Calculation tasks must use tools always.
|
| 74 |
+
- Break down complex tasks into logical components - don't try to solve everything at once
|
| 75 |
+
- Use tool names exactly as listed. If no tool is needed, set "tool": null.
|
| 76 |
+
- Never assume files or URLs exist—plan to search/download before analysing.
|
| 77 |
+
- Skip download steps when the required file is already provided.
|
| 78 |
+
- Ensure later steps only depend on results created by earlier steps.
|
| 79 |
+
- For any numerical work: ALWAYS use tools (calculator/code) - never manual calculation
|
| 80 |
+
- If the query involves analysis of multiple sources, plan separate steps for each source
|
| 81 |
+
- Consider data validation and error checking as separate steps when handling files
|
| 82 |
+
- Plan for visualization or formatting steps when presenting complex results
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
SYSTEM_EXECUTOR_PROMPT = """
|
| 86 |
+
You are the executor of a grounded multi-tool agent.
|
| 87 |
+
|
| 88 |
+
Plan summary: {plan_summary}
|
| 89 |
+
Step map:
|
| 90 |
+
{plan_overview}
|
| 91 |
+
|
| 92 |
+
Current focus: {current_step_id} — {step_goal}
|
| 93 |
+
Suggested tool: {step_tool}
|
| 94 |
+
Available tools: {tool_catalogue}
|
| 95 |
+
Known local files: {file_list}
|
| 96 |
+
|
| 97 |
+
CRITICAL COMPUTATION RULE: You MUST use tools for ANY numerical calculation, counting, or mathematical operation. This includes:
|
| 98 |
+
- Simple arithmetic (use tools add, subtract, multiply, divide, power)
|
| 99 |
+
- Data analysis and statistics (use safe_code_run)
|
| 100 |
+
- Counting items, rows, or occurrences (use safe_code_run)
|
| 101 |
+
- Percentage calculations (use add, subtract, multiply, divide, power/safe_code_run)
|
| 102 |
+
- Any mathematical transformation or formula application
|
| 103 |
+
|
| 104 |
+
NEVER perform manual calculations or provide estimated numbers.
|
| 105 |
+
|
| 106 |
+
Execution rules:
|
| 107 |
+
1. Stay aligned with the plan—no new steps or speculative actions.
|
| 108 |
+
2. Before every tool call, respond with <REASONING>…</REASONING> explaining the step, chosen tool, inputs, and expected outcome.
|
| 109 |
+
3. Call at most one tool per turn. After a successful step, state "STEP COMPLETE".
|
| 110 |
+
4. If required inputs are missing (e.g., file not downloaded), explain the issue in <REASONING> and wait for replanning.
|
| 111 |
+
5. Never invent file paths, URLs, or results. When unsure, request replanning instead of guessing.
|
| 112 |
+
6. If no tool is needed, answer directly after the reasoning.
|
| 113 |
+
7. For any calculation task: MANDATORY use of appropriate computational tools
|
| 114 |
+
8. Validate your tool results before marking steps complete
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
COMPLEXITY_ASSESSOR_PROMPT = """
|
| 118 |
+
You are a COMPLEXITY ASSESSOR for a multi-tool agent system.
|
| 119 |
+
Your job is to analyze user queries and determine their complexity level and processing requirements.
|
| 120 |
+
|
| 121 |
+
COMPLEXITY LEVELS:
|
| 122 |
+
1. SIMPLE: Direct questions that can be answered immediately without tools or with single tool use
|
| 123 |
+
- Examples: "What is photosynthesis?", "Define machine learning", "What's the capital of France?"
|
| 124 |
+
- NOTE: Simple math like "2+2" still requires calculator tool but counts as SIMPLE
|
| 125 |
+
|
| 126 |
+
!ALSO: It can be a logical reasoning or explanation task that does not require tools.
|
| 127 |
+
|
| 128 |
+
2. MODERATE: Questions requiring 2-4 tool calls or basic multi-step analysis
|
| 129 |
+
- Examples: "Search for recent news about AI", "Analyze this CSV file for trends", "Calculate ROI from this data"
|
| 130 |
+
- "Compare two datasets", "Summarize multiple documents"
|
| 131 |
+
|
| 132 |
+
3. COMPLEX: Multi-step problems requiring planning, multiple tools, and sophisticated reasoning
|
| 133 |
+
- Examples: "Research market trends and create investment strategy", "Analyze multiple data sources and predict outcomes"
|
| 134 |
+
- "Build comprehensive report from various inputs", "Multi-stage data processing with validation"
|
| 135 |
+
|
| 136 |
+
MOST OF THE LOGICAL TASKS ARE SIMPLE, UNLESS THEY REQUIRE TOOLS.
|
| 137 |
+
|
| 138 |
+
ASSESSMENT CRITERIA:
|
| 139 |
+
- Number of distinct steps likely needed (1 = Simple, 2-4 = Moderate, 5+ = Complex)
|
| 140 |
+
- Tool complexity and dependencies between steps
|
| 141 |
+
- Data processing requirements and validation needs
|
| 142 |
+
- Need for intermediate reasoning and synthesis
|
| 143 |
+
- Risk of failure without proper step-by-step planning
|
| 144 |
+
- Presence of calculations (automatically requires tool usage)
|
| 145 |
+
|
| 146 |
+
SPECIAL CONSIDERATIONS:
|
| 147 |
+
- Any calculation/counting task requires tools (affects complexity assessment)
|
| 148 |
+
- File analysis tasks usually need multiple steps (load + analyze + calculate)
|
| 149 |
+
- Research tasks typically need search + fetch + synthesis steps
|
| 150 |
+
- Comparison tasks need separate analysis steps for each item being compared
|
| 151 |
+
|
| 152 |
+
RULES:
|
| 153 |
+
- SIMPLE queries may bypass planning for non-calculation tasks
|
| 154 |
+
- MODERATE queries benefit from lightweight planning
|
| 155 |
+
- COMPLEX queries require full planning with fallbacks
|
| 156 |
+
- When in doubt, err toward higher complexity
|
| 157 |
+
- Calculation tasks are never truly "simple" due to mandatory tool usage
|
| 158 |
+
|
| 159 |
+
Analyze the query and respond with your assessment.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
CRITIC_PROMPT = """
|
| 163 |
+
You are the CRITIC of a multi-tool agent system.
|
| 164 |
+
Your job is to evaluate execution reports and provide detailed feedback.
|
| 165 |
+
|
| 166 |
+
EVALUATION FRAMEWORK:
|
| 167 |
+
|
| 168 |
+
1. COMPLETENESS (0-3 points):
|
| 169 |
+
- 3: Fully addresses all aspects of the query
|
| 170 |
+
- 2: Addresses main aspects, minor gaps
|
| 171 |
+
- 1: Partial answer, significant gaps
|
| 172 |
+
- 0: Incomplete or off-topic
|
| 173 |
+
|
| 174 |
+
2. ACCURACY (0-3 points):
|
| 175 |
+
- 3: All information appears accurate and well-sourced
|
| 176 |
+
- 2: Mostly accurate, minor issues
|
| 177 |
+
- 1: Some accuracy concerns
|
| 178 |
+
- 0: Significant accuracy problems
|
| 179 |
+
|
| 180 |
+
3. METHODOLOGY (0-2 points):
|
| 181 |
+
- 2: Appropriate tools and approach used, proper calculation methods
|
| 182 |
+
- 1: Acceptable approach, could be better
|
| 183 |
+
- 0: Poor methodology, manual calculations when tools required, or wrong tool selection
|
| 184 |
+
|
| 185 |
+
4. EVIDENCE (0-2 points):
|
| 186 |
+
- 2: Strong evidence and sources provided, calculations verifiable
|
| 187 |
+
- 1: Some evidence provided
|
| 188 |
+
- 0: Insufficient evidence or unverifiable calculations
|
| 189 |
+
|
| 190 |
+
CRITICAL VIOLATIONS (Automatic score reduction):
|
| 191 |
+
- Manual calculations instead of using tools: -2 points
|
| 192 |
+
- Skipped validation steps for numerical results: -1 point
|
| 193 |
+
- Missing citations for factual claims: -1 point
|
| 194 |
+
|
| 195 |
+
TOTAL SCORE: /10 points
|
| 196 |
+
|
| 197 |
+
DECISION THRESHOLDS:
|
| 198 |
+
- 8-10: Accept (excellent quality)
|
| 199 |
+
- 6-7: Accept with minor notes
|
| 200 |
+
- 4-5: Marginal, consider replanning
|
| 201 |
+
- 0-3: Reject, requires replanning
|
| 202 |
+
|
| 203 |
+
EXECUTION REPORT TO EVALUATE:
|
| 204 |
+
Query: {query}
|
| 205 |
+
Approach: {approach}
|
| 206 |
+
Tools Used: {tools}
|
| 207 |
+
Key Findings: {findings}
|
| 208 |
+
Sources: {sources}
|
| 209 |
+
Confidence: {confidence}
|
| 210 |
+
Limitations: {limitations}
|
| 211 |
+
Final Answer: {answer}
|
| 212 |
+
|
| 213 |
+
SPECIAL ATTENTION POINTS:
|
| 214 |
+
- Were calculations performed using appropriate tools?
|
| 215 |
+
- Are numerical results properly validated and sourced?
|
| 216 |
+
- Was the task broken down appropriately or rushed through?
|
| 217 |
+
- Are sources properly cited and verifiable?
|
| 218 |
+
|
| 219 |
+
Provide detailed critique focusing on what works well and what could be improved.
|
| 220 |
+
For simple definitional or informational queries without calculations, you may respond with "NO CRITIC NEEDED".
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
"""
|
src/schemas.py
CHANGED
|
@@ -67,7 +67,7 @@ class ExecutionReport(BaseModel):
|
|
| 67 |
assumptions_made: List[str] = Field(default_factory=list, description="Any assumptions made during execution")
|
| 68 |
confidence_level: Literal["low", "medium", "high"] = Field(description="Confidence in the answer")
|
| 69 |
limitations: List[str] = Field(default_factory=list, description="Known limitations or caveats")
|
| 70 |
-
final_answer: str = Field(description="
|
| 71 |
|
| 72 |
class Config:
|
| 73 |
extra = "forbid"
|
|
|
|
| 67 |
assumptions_made: List[str] = Field(default_factory=list, description="Any assumptions made during execution")
|
| 68 |
confidence_level: Literal["low", "medium", "high"] = Field(description="Confidence in the answer")
|
| 69 |
limitations: List[str] = Field(default_factory=list, description="Known limitations or caveats")
|
| 70 |
+
final_answer: str = Field(description="The actual answer to the user's query")
|
| 71 |
|
| 72 |
class Config:
|
| 73 |
extra = "forbid"
|
src/state.py
CHANGED
|
@@ -20,6 +20,4 @@ class AgentState(MessagesState):
|
|
| 20 |
max_iterations: int
|
| 21 |
execution_report : ExecutionReport
|
| 22 |
previous_tool_results: Dict[str, str] # НОВОЕ ПОЛЕ для сохранения результатов
|
| 23 |
-
previous_final_answer: str # НОВОЕ ПОЛЕ для сохранения предыдущих окончательных ответов
|
| 24 |
-
critic_replan : bool # НОВОЕ ПОЛЕ для указания, был ли выполнен реплан на основе критики
|
| 25 |
|
|
|
|
| 20 |
max_iterations: int
|
| 21 |
execution_report : ExecutionReport
|
| 22 |
previous_tool_results: Dict[str, str] # НОВОЕ ПОЛЕ для сохранения результатов
|
|
|
|
|
|
|
| 23 |
|
src/tools/tools.py
CHANGED
|
@@ -6,8 +6,6 @@ import base64
|
|
| 6 |
import tldextract
|
| 7 |
import tempfile
|
| 8 |
from urllib.parse import urlparse
|
| 9 |
-
from langchain_tavily import TavilyExtract
|
| 10 |
-
from youtube_transcript_api import YouTubeTranscriptApi
|
| 11 |
import io
|
| 12 |
import pandas as pd
|
| 13 |
from typing import List, Optional, Dict, Any
|
|
@@ -19,9 +17,7 @@ from langchain_community.tools.tavily_search import TavilySearchResults
|
|
| 19 |
from langchain_community.document_loaders import ArxivLoader
|
| 20 |
from langchain_community.document_loaders import WikipediaLoader
|
| 21 |
from PIL import ImageDraw, ImageFont, ImageEnhance, ImageFilter
|
| 22 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 23 |
from src.utils.image_processing import *
|
| 24 |
-
import re
|
| 25 |
|
| 26 |
def _exif_dict(img: Image.Image) -> dict:
|
| 27 |
try:
|
|
@@ -42,7 +38,6 @@ def _clip(text: str | None, n: int) -> str:
|
|
| 42 |
return (text[: n - 1] + "…") if len(text) > n else text
|
| 43 |
|
| 44 |
|
| 45 |
-
|
| 46 |
def _parse_dt(v) -> Optional[str]:
|
| 47 |
"""[ИЗМЕНЕНИЕ] Приводим даты к ISO-строке, если возможно."""
|
| 48 |
try:
|
|
@@ -107,12 +102,6 @@ def preprocess_files(files: List[str]) -> Dict[str, Dict[str, Any]]:
|
|
| 107 |
elif file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
|
| 108 |
info["type"] = "image"
|
| 109 |
info["suggested_tool"] = "vision_qa_gemma"
|
| 110 |
-
elif file_ext in [".mp3"]:
|
| 111 |
-
info["type"] = "audio"
|
| 112 |
-
info["suggested_tool"] = "transcribe_audio"
|
| 113 |
-
elif file_ext in [".mp4"]:
|
| 114 |
-
info["type"] = "video"
|
| 115 |
-
info["suggested_tool"] = "video_qa_gemma"
|
| 116 |
else:
|
| 117 |
info["type"] = "unknown"
|
| 118 |
info["suggested_tool"] = "analyze_txt_file (fallback)"
|
|
@@ -371,51 +360,6 @@ def arxiv_search(
|
|
| 371 |
return json.dumps({"error": str(e), "query": query, "provider": "arxiv"})
|
| 372 |
|
| 373 |
|
| 374 |
-
@tool
|
| 375 |
-
def web_extract(
|
| 376 |
-
urls: List[str] | str,
|
| 377 |
-
include_images: bool = False,
|
| 378 |
-
extract_depth: str = "basic",
|
| 379 |
-
) -> str:
|
| 380 |
-
"""
|
| 381 |
-
Extract text content from web pages using TavilyExtract.
|
| 382 |
-
|
| 383 |
-
🔹 Input: {"urls": str | List[str]}
|
| 384 |
-
- Example: web_extract.invoke({"urls": ["https://python.langchain.com/docs/introduction/"]})
|
| 385 |
-
🔹 Output: JSON string with {url, title, text, images?}
|
| 386 |
-
|
| 387 |
-
Options:
|
| 388 |
-
include_images (bool) – add image URLs if True
|
| 389 |
-
extract_depth (str) – "basic" (default) or "advanced"
|
| 390 |
-
"""
|
| 391 |
-
# нормализуем вход
|
| 392 |
-
if isinstance(urls, str):
|
| 393 |
-
urls = [urls]
|
| 394 |
-
|
| 395 |
-
tool = TavilyExtract(
|
| 396 |
-
extract_depth=extract_depth,
|
| 397 |
-
include_images=include_images,
|
| 398 |
-
)
|
| 399 |
-
# ВАЖНО: .invoke ждёт словарь по схеме TavilyExtractInput
|
| 400 |
-
results = tool.invoke({"urls": urls})
|
| 401 |
-
return json.dumps(results)
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
@tool
|
| 405 |
-
def extract_youtube_transcript(url: str, chars: int = 10_00) -> str:
|
| 406 |
-
"""
|
| 407 |
-
Fetch full YouTube transcript (first *chars* characters).
|
| 408 |
-
"""
|
| 409 |
-
|
| 410 |
-
video_id_match = re.search(r"[?&]v=([A-Za-z0-9_\-]{11})", url)
|
| 411 |
-
if not video_id_match:
|
| 412 |
-
return "yt_error:id_not_found"
|
| 413 |
-
try:
|
| 414 |
-
transcript = YouTubeTranscriptApi.get_transcript(video_id_match.group(1))
|
| 415 |
-
text = " ".join(piece["text"] for piece in transcript)
|
| 416 |
-
return text[:chars]
|
| 417 |
-
except Exception as exc:
|
| 418 |
-
return f"yt_error:{exc}"
|
| 419 |
|
| 420 |
#----------------------------------------------MATH TOOLS------------------------------------------------#
|
| 421 |
|
|
@@ -937,17 +881,3 @@ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
|
| 937 |
return f"File downloaded to {filepath}. You can read this file to process its contents."
|
| 938 |
except Exception as e:
|
| 939 |
return f"Error downloading file: {str(e)}"
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
@tool
|
| 943 |
-
def transcribe_audio(audio_file: str) -> str:
|
| 944 |
-
"""
|
| 945 |
-
Transcribe an audio file (URL or local path) using AssemblyAI and return the transcript text.
|
| 946 |
-
"""
|
| 947 |
-
try:
|
| 948 |
-
loader = AssemblyAIAudioTranscriptLoader(file_path=audio_file)
|
| 949 |
-
docs = loader.load()
|
| 950 |
-
# возвращаем только текст
|
| 951 |
-
return docs[0].page_content if docs else "No transcription result."
|
| 952 |
-
except Exception as e:
|
| 953 |
-
return f"transcribe_error:{str(e)} (if you see this, please describe error for fixing)"
|
|
|
|
| 6 |
import tldextract
|
| 7 |
import tempfile
|
| 8 |
from urllib.parse import urlparse
|
|
|
|
|
|
|
| 9 |
import io
|
| 10 |
import pandas as pd
|
| 11 |
from typing import List, Optional, Dict, Any
|
|
|
|
| 17 |
from langchain_community.document_loaders import ArxivLoader
|
| 18 |
from langchain_community.document_loaders import WikipediaLoader
|
| 19 |
from PIL import ImageDraw, ImageFont, ImageEnhance, ImageFilter
|
|
|
|
| 20 |
from src.utils.image_processing import *
|
|
|
|
| 21 |
|
| 22 |
def _exif_dict(img: Image.Image) -> dict:
|
| 23 |
try:
|
|
|
|
| 38 |
return (text[: n - 1] + "…") if len(text) > n else text
|
| 39 |
|
| 40 |
|
|
|
|
| 41 |
def _parse_dt(v) -> Optional[str]:
|
| 42 |
"""[ИЗМЕНЕНИЕ] Приводим даты к ISO-строке, если возможно."""
|
| 43 |
try:
|
|
|
|
| 102 |
elif file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
|
| 103 |
info["type"] = "image"
|
| 104 |
info["suggested_tool"] = "vision_qa_gemma"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
else:
|
| 106 |
info["type"] = "unknown"
|
| 107 |
info["suggested_tool"] = "analyze_txt_file (fallback)"
|
|
|
|
| 360 |
return json.dumps({"error": str(e), "query": query, "provider": "arxiv"})
|
| 361 |
|
| 362 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
#----------------------------------------------MATH TOOLS------------------------------------------------#
|
| 365 |
|
|
|
|
| 881 |
return f"File downloaded to {filepath}. You can read this file to process its contents."
|
| 882 |
except Exception as e:
|
| 883 |
return f"Error downloading file: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/tools/video_analyzer.py
DELETED
|
@@ -1,282 +0,0 @@
|
|
| 1 |
-
import os, io, base64, json, tempfile
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
from typing import Any, Dict, List, Optional, Literal
|
| 4 |
-
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import google.generativeai as genai
|
| 7 |
-
from langchain_core.tools import tool
|
| 8 |
-
|
| 9 |
-
# ======================== CONFIG & CORE ========================
|
| 10 |
-
|
| 11 |
-
def _configure() -> str:
|
| 12 |
-
api_key = os.getenv("GOOGLE_API_KEY") or os.getenv("GENAI_API_KEY")
|
| 13 |
-
if not api_key:
|
| 14 |
-
raise RuntimeError("Missing GOOGLE_API_KEY (or GENAI_API_KEY) in environment")
|
| 15 |
-
genai.configure(api_key=api_key)
|
| 16 |
-
return api_key
|
| 17 |
-
|
| 18 |
-
def _clean_json_text(s: str) -> str:
|
| 19 |
-
s = s.strip()
|
| 20 |
-
if s.startswith("```"):
|
| 21 |
-
s = s.strip("`").replace("json", "", 1).strip()
|
| 22 |
-
start = s.find("{")
|
| 23 |
-
end = s.rfind("}")
|
| 24 |
-
if start != -1 and end != -1 and end > start:
|
| 25 |
-
return s[start:end+1]
|
| 26 |
-
return s
|
| 27 |
-
|
| 28 |
-
def _call_model(parts: List[Any], temperature: float, model_name: Optional[str] = None) -> Dict[str, Any]:
|
| 29 |
-
"""
|
| 30 |
-
Единая точка вызова модели. Возвращает dict с ключом "answer".
|
| 31 |
-
"""
|
| 32 |
-
MODEL_NAME = model_name or os.getenv("GEMMA_MODEL", "gemma-3-27b-it")
|
| 33 |
-
model = genai.GenerativeModel(MODEL_NAME)
|
| 34 |
-
resp = model.generate_content(parts, generation_config={"temperature": temperature})
|
| 35 |
-
text = (getattr(resp, "text", None) or "").strip()
|
| 36 |
-
try:
|
| 37 |
-
return json.loads(_clean_json_text(text))
|
| 38 |
-
except Exception:
|
| 39 |
-
fixer = genai.GenerativeModel(MODEL_NAME)
|
| 40 |
-
fix_prompt = (
|
| 41 |
-
"Convert the following text into STRICT valid JSON matching schema {\"answer\": string}. "
|
| 42 |
-
"Return ONLY JSON, no extra text:\n" + text
|
| 43 |
-
)
|
| 44 |
-
fix_resp = fixer.generate_content([{"text": fix_prompt}])
|
| 45 |
-
return json.loads(_clean_json_text((getattr(fix_resp, "text", "") or "").strip()))
|
| 46 |
-
|
| 47 |
-
# ======================== VIDEO HELPERS (OpenCV-only) ========================
|
| 48 |
-
|
| 49 |
-
_VIDEO_QA_PROMPT = (
|
| 50 |
-
"You will be given ONE video and a question about its visual content.\n"
|
| 51 |
-
"Answer STRICTLY and CONCISELY based only on what is visible/audible in the provided video.\n"
|
| 52 |
-
"If the video does not contain enough information, reply 'not enough information'.\n"
|
| 53 |
-
"Return ONLY valid JSON with the schema:\n"
|
| 54 |
-
"{\"answer\": string}\n"
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
def _uniform_sample_paths(paths: List[Path], k: int) -> List[Path]:
|
| 58 |
-
n = len(paths)
|
| 59 |
-
if n <= k:
|
| 60 |
-
return paths
|
| 61 |
-
idxs = [round(i*(n-1)/(k-1)) for i in range(k)]
|
| 62 |
-
return [paths[i] for i in idxs]
|
| 63 |
-
|
| 64 |
-
def _ensure_png_bytes(img: Image.Image, max_pixels: int = 25_000_000) -> bytes:
|
| 65 |
-
w, h = img.size
|
| 66 |
-
if w * h > max_pixels:
|
| 67 |
-
scale = (max_pixels / (w * h)) ** 0.5
|
| 68 |
-
img = img.resize((max(1, int(w*scale)), max(1, int(h*scale))), Image.LANCZOS)
|
| 69 |
-
buf = io.BytesIO()
|
| 70 |
-
img.save(buf, format="PNG", optimize=True)
|
| 71 |
-
return buf.getvalue()
|
| 72 |
-
|
| 73 |
-
def _image_bytes_to_part(img_bytes: bytes, mime: str = "image/png") -> Dict[str, Any]:
|
| 74 |
-
return {"mime_type": mime, "data": base64.b64encode(img_bytes).decode("utf-8")}
|
| 75 |
-
|
| 76 |
-
def _extract_frames_cv2(video_path: str, out_dir: Path, fps: float, start_s: float, duration_s: Optional[float]) -> List[Path]:
|
| 77 |
-
"""
|
| 78 |
-
Извлекаем кадры через OpenCV (без системного ffmpeg).
|
| 79 |
-
Требует: pip install opencv-python
|
| 80 |
-
"""
|
| 81 |
-
import cv2
|
| 82 |
-
out_dir.mkdir(parents=True, exist_ok=True)
|
| 83 |
-
|
| 84 |
-
cap = cv2.VideoCapture(video_path)
|
| 85 |
-
if not cap.isOpened():
|
| 86 |
-
raise RuntimeError("OpenCV cannot open video")
|
| 87 |
-
|
| 88 |
-
in_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
| 89 |
-
total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0
|
| 90 |
-
total_ms = (total_frames / in_fps) * 1000.0 if total_frames and in_fps else None
|
| 91 |
-
|
| 92 |
-
start_ms = max(0.0, float(start_s) * 1000.0)
|
| 93 |
-
end_ms = start_ms + float(duration_s) * 1000.0 if duration_s is not None else (total_ms or start_ms + 30_000.0)
|
| 94 |
-
step_ms = 1000.0 / max(0.001, fps) # период семплинга по ms
|
| 95 |
-
|
| 96 |
-
t = start_ms
|
| 97 |
-
idx = 0
|
| 98 |
-
saved: List[Path] = []
|
| 99 |
-
while t <= end_ms:
|
| 100 |
-
cap.set(cv2.CAP_PROP_POS_MSEC, t)
|
| 101 |
-
ok, frame = cap.read()
|
| 102 |
-
if not ok:
|
| 103 |
-
break
|
| 104 |
-
fp = out_dir / f"{idx:06d}.jpg"
|
| 105 |
-
# JPEG сохраняем без ffmpeg
|
| 106 |
-
ok = cv2.imwrite(str(fp), frame)
|
| 107 |
-
if ok:
|
| 108 |
-
saved.append(fp)
|
| 109 |
-
idx += 1
|
| 110 |
-
t += step_ms
|
| 111 |
-
|
| 112 |
-
cap.release()
|
| 113 |
-
if not saved:
|
| 114 |
-
raise RuntimeError("No frames extracted (OpenCV).")
|
| 115 |
-
return saved
|
| 116 |
-
|
| 117 |
-
def _frames_to_image_parts(frame_paths: List[Path], max_images: int) -> List[Dict[str, Any]]:
|
| 118 |
-
"""
|
| 119 |
-
Прореживаем кадры до <= max_images и упаковываем как inline-изображения.
|
| 120 |
-
"""
|
| 121 |
-
frame_paths = _uniform_sample_paths(frame_paths, k=max_images)
|
| 122 |
-
out: List[Dict[str, Any]] = []
|
| 123 |
-
for fp in frame_paths:
|
| 124 |
-
img = Image.open(fp)
|
| 125 |
-
img_bytes = _ensure_png_bytes(img)
|
| 126 |
-
out.append(_image_bytes_to_part(img_bytes, "image/png"))
|
| 127 |
-
return out
|
| 128 |
-
|
| 129 |
-
def _download_youtube_to_mp4(youtube_url: str, out_path: str) -> str:
|
| 130 |
-
"""
|
| 131 |
-
Скачиваем YouTube через библиотеку yt_dlp (без системного ffmpeg).
|
| 132 |
-
Требует: pip install yt-dlp
|
| 133 |
-
Стараемся выбрать прогрессивный MP4 (single file), чтобы не потребовался mux.
|
| 134 |
-
"""
|
| 135 |
-
from yt_dlp import YoutubeDL
|
| 136 |
-
ydl_opts = {
|
| 137 |
-
# выбираем ЛУЧШИЙ одиночный файл, предпочитая MP4 (без mux/ffmpeg)
|
| 138 |
-
"format": "b[ext=mp4]/b",
|
| 139 |
-
"outtmpl": out_path,
|
| 140 |
-
"noprogress": True,
|
| 141 |
-
"quiet": True,
|
| 142 |
-
"nocheckcertificate": True,
|
| 143 |
-
}
|
| 144 |
-
with YoutubeDL(ydl_opts) as ydl:
|
| 145 |
-
info = ydl.extract_info(youtube_url, download=True)
|
| 146 |
-
# yt-dlp может игнорировать outtmpl при некоторых шаблонах — подстрахуемся
|
| 147 |
-
fn = ydl.prepare_filename(info)
|
| 148 |
-
# Если получили другой путь, перенесём
|
| 149 |
-
src = Path(fn)
|
| 150 |
-
dst = Path(out_path)
|
| 151 |
-
if src.resolve() != dst.resolve():
|
| 152 |
-
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 153 |
-
src.replace(dst)
|
| 154 |
-
return str(dst)
|
| 155 |
-
|
| 156 |
-
def _get_client(api_key: Optional[str]):
|
| 157 |
-
"""
|
| 158 |
-
Опционально: новый Google GenAI SDK (google-genai) для Files API в 'auto' режиме.
|
| 159 |
-
Если нет — вернём None.
|
| 160 |
-
"""
|
| 161 |
-
try:
|
| 162 |
-
from google import genai as ggenai # новый пакет "google-genai"
|
| 163 |
-
return ggenai.Client(api_key=api_key)
|
| 164 |
-
except Exception:
|
| 165 |
-
return None
|
| 166 |
-
|
| 167 |
-
def _video_part_from_youtube(url: str) -> Dict[str, Any]:
|
| 168 |
-
"""Для mode='auto': передаём YouTube как file_data без скачивания."""
|
| 169 |
-
return {"file_data": {"file_uri": url}}
|
| 170 |
-
|
| 171 |
-
def _video_part_from_file(path: str, api_key: Optional[str]) -> Dict[str, Any]:
|
| 172 |
-
"""
|
| 173 |
-
Для mode='auto': загружаем локальный файл в Files API.
|
| 174 |
-
"""
|
| 175 |
-
if not os.path.exists(path):
|
| 176 |
-
raise FileNotFoundError(f"Video not found: {path}")
|
| 177 |
-
client = _get_client(api_key)
|
| 178 |
-
if client is not None and hasattr(client, "files"):
|
| 179 |
-
try:
|
| 180 |
-
f = client.files.upload(file=path)
|
| 181 |
-
return {"file_data": {"file_uri": f.uri, "mime_type": getattr(f, "mime_type", None) or "video/mp4"}}
|
| 182 |
-
except Exception:
|
| 183 |
-
pass
|
| 184 |
-
f = genai.upload_file(path=path)
|
| 185 |
-
file_uri = getattr(f, "uri", None) or getattr(f, "file_uri", None)
|
| 186 |
-
mime = getattr(f, "mime_type", None) or "video/mp4"
|
| 187 |
-
return {"file_data": {"file_uri": file_uri, "mime_type": mime}}
|
| 188 |
-
|
| 189 |
-
# ======================== VIDEO QA TOOL (OpenCV frames по умолчанию) ========================
|
| 190 |
-
|
| 191 |
-
@tool
|
| 192 |
-
def video_qa_gemma(
|
| 193 |
-
question: str,
|
| 194 |
-
youtube_url: Optional[str] = None,
|
| 195 |
-
video_path: Optional[str] = None,
|
| 196 |
-
temperature: float = 0.2,
|
| 197 |
-
model_name: Optional[str] = None,
|
| 198 |
-
mode: Literal["frames", "auto"] = "auto", # по умолчанию безопасный режим кадров (OpenCV) #default frames
|
| 199 |
-
fps: float = 0.8, # 0.8 * 30s ≈ 24 кадров
|
| 200 |
-
start_s: float = 0.0,
|
| 201 |
-
duration_s: Optional[float] = 30.0, # держим сегмент коротким
|
| 202 |
-
max_images: int = 24, # < 32 — жёсткая крышка
|
| 203 |
-
) -> str:
|
| 204 |
-
"""
|
| 205 |
-
Answer questions about the visual content of a video (YouTube URL or local file).
|
| 206 |
-
|
| 207 |
-
Args:
|
| 208 |
-
question: Natural language question about the video.
|
| 209 |
-
youtube_url: Link to a YouTube video (exclusive with video_path).
|
| 210 |
-
video_path: Local path to a video file.
|
| 211 |
-
mode: "frames" (default, extracts ≤max_images frames with OpenCV) or "auto" (send whole video).
|
| 212 |
-
fps/start_s/duration_s: Frame sampling parameters in "frames" mode.
|
| 213 |
-
max_images: Max number of frames (<32). Default 24.
|
| 214 |
-
|
| 215 |
-
Returns:
|
| 216 |
-
JSON string: {"answer": "..."} (or "not enough information").
|
| 217 |
-
|
| 218 |
-
Notes:
|
| 219 |
-
- Provide exactly ONE of youtube_url or video_path.
|
| 220 |
-
- Use "frames" mode to avoid API errors on models with image limits.
|
| 221 |
-
"""
|
| 222 |
-
import json as _json
|
| 223 |
-
try:
|
| 224 |
-
api_key = _configure()
|
| 225 |
-
|
| 226 |
-
if bool(youtube_url) == bool(video_path):
|
| 227 |
-
return _json.dumps({"error": "Provide exactly ONE of youtube_url or video_path"})
|
| 228 |
-
|
| 229 |
-
if mode == "auto":
|
| 230 |
-
# Без OpenCV: отдаём видео целиком (иногда API внутри раздувает до >32 изображений).
|
| 231 |
-
if youtube_url:
|
| 232 |
-
video_part = _video_part_from_youtube(youtube_url)
|
| 233 |
-
else:
|
| 234 |
-
video_part = _video_part_from_file(video_path, api_key)
|
| 235 |
-
parts = [video_part, {"text": _VIDEO_QA_PROMPT + "\nQuestion: " + question.strip()}]
|
| 236 |
-
data = _call_model(parts, temperature, model_name=model_name)
|
| 237 |
-
else:
|
| 238 |
-
# OpenCV: извлекаем кадры и отправляем как <= max_images изображений
|
| 239 |
-
tmp_video_path = None
|
| 240 |
-
if youtube_url and not video_path:
|
| 241 |
-
with tempfile.TemporaryDirectory(prefix="yt_") as td:
|
| 242 |
-
tmp_video_path = str(Path(td) / "video.mp4")
|
| 243 |
-
_download_youtube_to_mp4(youtube_url, tmp_video_path)
|
| 244 |
-
# внутри with мы не можем вернуть, поэтому делаем обработку ниже в том же блоке
|
| 245 |
-
frame_dir = Path(td) / "frames"
|
| 246 |
-
files = _extract_frames_cv2(tmp_video_path, frame_dir, fps=fps, start_s=start_s, duration_s=duration_s)
|
| 247 |
-
img_parts = _frames_to_image_parts(files, max_images=max_images)
|
| 248 |
-
parts = img_parts + [{"text": _VIDEO_QA_PROMPT + "\nQuestion: " + question.strip()}]
|
| 249 |
-
data = _call_model(parts, temperature, model_name=model_name)
|
| 250 |
-
# выходим из with — файлы удалятся
|
| 251 |
-
answer = data["answer"] if isinstance(data, dict) and "answer" in data else None
|
| 252 |
-
if not isinstance(answer, str):
|
| 253 |
-
answer = str(answer) if answer is not None else "not enough information"
|
| 254 |
-
return _json.dumps({"answer": answer})
|
| 255 |
-
|
| 256 |
-
# локальный файл (или если youtube уже скачали и вышли return выше)
|
| 257 |
-
frame_dir = Path(tempfile.mkdtemp(prefix="frames_"))
|
| 258 |
-
try:
|
| 259 |
-
src_video = video_path if video_path else tmp_video_path
|
| 260 |
-
files = _extract_frames_cv2(src_video, frame_dir, fps=fps, start_s=start_s, duration_s=duration_s)
|
| 261 |
-
img_parts = _frames_to_image_parts(files, max_images=max_images)
|
| 262 |
-
parts = img_parts + [{"text": _VIDEO_QA_PROMPT + "\nQuestion: " + question.strip()}]
|
| 263 |
-
data = _call_model(parts, temperature, model_name=model_name)
|
| 264 |
-
finally:
|
| 265 |
-
# подчистим временные файлы
|
| 266 |
-
for p in frame_dir.glob("*"):
|
| 267 |
-
try:
|
| 268 |
-
p.unlink()
|
| 269 |
-
except Exception:
|
| 270 |
-
pass
|
| 271 |
-
try:
|
| 272 |
-
frame_dir.rmdir()
|
| 273 |
-
except Exception:
|
| 274 |
-
pass
|
| 275 |
-
|
| 276 |
-
answer = data["answer"] if isinstance(data, dict) and "answer" in data else None
|
| 277 |
-
if not isinstance(answer, str):
|
| 278 |
-
answer = str(answer) if answer is not None else "not enough information"
|
| 279 |
-
return _json.dumps({"answer": answer})
|
| 280 |
-
|
| 281 |
-
except Exception as e:
|
| 282 |
-
return _json.dumps({"error": str(e)})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/tools/youtube_transcript.py
DELETED
|
@@ -1,72 +0,0 @@
|
|
| 1 |
-
from langchain.tools import tool
|
| 2 |
-
|
| 3 |
-
try:
|
| 4 |
-
from youtube_transcript_api import YouTubeTranscriptApi
|
| 5 |
-
except Exception:
|
| 6 |
-
YouTubeTranscriptApi = None
|
| 7 |
-
|
| 8 |
-
import re
|
| 9 |
-
from urllib.parse import urlparse, parse_qs
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def _extract_video_id(url_or_id: str) -> str | None:
|
| 13 |
-
s = (url_or_id or "").strip()
|
| 14 |
-
if re.fullmatch(r"[A-Za-z0-9_-]{11}", s):
|
| 15 |
-
return s
|
| 16 |
-
u = urlparse(s)
|
| 17 |
-
# youtu.be/<id>
|
| 18 |
-
if u.netloc.endswith("youtu.be"):
|
| 19 |
-
vid = u.path.strip("/").split("/")[0]
|
| 20 |
-
return vid if re.fullmatch(r"[A-Za-z0-9_-]{11}", vid) else None
|
| 21 |
-
# watch?v=<id>
|
| 22 |
-
qs = parse_qs(u.query or "")
|
| 23 |
-
if "v" in qs:
|
| 24 |
-
vid = qs["v"][0]
|
| 25 |
-
return vid if re.fullmatch(r"[A-Za-z0-9_-]{11}", vid) else None
|
| 26 |
-
# /embed/<id>, /shorts/<id>, /v/<id>
|
| 27 |
-
for pref in ("/embed/", "/shorts/", "/v/"):
|
| 28 |
-
if u.path.startswith(pref):
|
| 29 |
-
vid = u.path[len(pref):].split("/")[0]
|
| 30 |
-
return vid if re.fullmatch(r"[A-Za-z0-9_-]{11}", vid) else None
|
| 31 |
-
return None
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
@tool
|
| 35 |
-
def extract_youtube_transcript(url: str, chars: int = 1000) -> str:
|
| 36 |
-
"""
|
| 37 |
-
Simple YouTube transcript fetcher.
|
| 38 |
-
|
| 39 |
-
Input:
|
| 40 |
-
- url: Regular YouTube URL (or the 11-char video_id).
|
| 41 |
-
- chars: Return the first `chars` characters of the transcript.
|
| 42 |
-
|
| 43 |
-
Output:
|
| 44 |
-
- String with the transcript (trimmed to `chars`), or an error string:
|
| 45 |
-
"yt_error:<reason>"
|
| 46 |
-
"""
|
| 47 |
-
if YouTubeTranscriptApi is None:
|
| 48 |
-
return "yt_error:missing_dependency"
|
| 49 |
-
|
| 50 |
-
vid = _extract_video_id(url)
|
| 51 |
-
if not vid:
|
| 52 |
-
return "yt_error:id_not_found"
|
| 53 |
-
|
| 54 |
-
try:
|
| 55 |
-
api = YouTubeTranscriptApi()
|
| 56 |
-
# New API returns a list of FetchedTranscriptSnippet objects
|
| 57 |
-
snippets = api.fetch(vid)
|
| 58 |
-
|
| 59 |
-
parts = []
|
| 60 |
-
for s in snippets:
|
| 61 |
-
# Support both object (new) and dict (old) shapes
|
| 62 |
-
text = getattr(s, "text", None)
|
| 63 |
-
if text is None and isinstance(s, dict):
|
| 64 |
-
text = s.get("text")
|
| 65 |
-
if not text:
|
| 66 |
-
continue
|
| 67 |
-
parts.append(text.replace("\n", " ").strip())
|
| 68 |
-
|
| 69 |
-
full_text = " ".join(p for p in parts if p)
|
| 70 |
-
return full_text[: max(0, int(chars))]
|
| 71 |
-
except Exception as e:
|
| 72 |
-
return f"yt_error:{type(e).__name__}:{e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/workflow_test.ipynb
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|