mrhenu commited on
Commit
33a25ca
·
verified ·
1 Parent(s): e2087a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -74
app.py CHANGED
@@ -4,87 +4,43 @@ import requests
4
  import pandas as pd
5
  from typing import TypedDict, Annotated, Sequence
6
  import operator
7
- from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage
8
  from langchain.tools import tool
9
  from langchain_community.tools.tavily_search import TavilySearchResults
 
 
10
  from langchain_openai import ChatOpenAI
11
  from langgraph.graph import StateGraph, END
12
  from langgraph.prebuilt import ToolNode, tools_condition
13
 
14
  # --- Main Application Logic ---
15
 
16
- # This defines the "memory" or state of our agent.
17
  class AgentState(TypedDict):
18
  messages: Annotated[Sequence[BaseMessage], operator.add]
19
 
20
- # NEW: Custom tool for downloading files from the course API
21
- @tool
22
- def download_file(task_id: str) -> str:
23
- """
24
- Downloads a file associated with a specific task_id from the course API.
25
- The file will be saved in the /tmp/ directory.
26
- Use this tool when a question mentions an attached file (e.g., image, excel, audio).
27
- """
28
- try:
29
- # NOTE: This assumes the Space is running on the Hugging Face platform
30
- # and can access the scoring API directly.
31
- file_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
32
- response = requests.get(file_url)
33
- response.raise_for_status()
34
-
35
- # Extract filename from headers, or default to task_id
36
- content_disposition = response.headers.get('content-disposition')
37
- if content_disposition:
38
- parts = content_disposition.split(';')
39
- for part in parts:
40
- if 'filename=' in part:
41
- filename = part.split('=')[1].strip('"')
42
- break
43
- else:
44
- # Fallback filename if header is not present
45
- # This is a simplification; a real app might need better content-type handling
46
- filename = task_id
47
-
48
- # Save the file to a temporary directory within the Space
49
- save_path = f"/tmp/{filename}"
50
- with open(save_path, "wb") as f:
51
- f.write(response.content)
52
-
53
- return f"Successfully downloaded file for task {task_id}. It is available at path: {save_path}"
54
- except Exception as e:
55
- return f"An error occurred while downloading the file: {str(e)}"
56
-
57
- # This function builds our final, robust agent.
58
  def create_langgraph_agent():
59
- print("Initializing LangGraph Agent with OpenAI...")
60
 
61
- # 1. Set up the LLM (The "Brain")
62
- llm = ChatOpenAI(model="gpt-4o", temperature=0) # Switched to gpt-4o for better performance
63
 
64
- # 2. Define the Tools, including our new file downloader
65
- tools = [TavilySearchResults(max_results=3), download_file]
66
  llm_with_tools = llm.bind_tools(tools)
67
  print("LLM and tools initialized.")
68
 
69
- # 3. Define the agent's logic (the "agent" node)
70
- # NEW: We are using a much more specific system prompt based on the GAIA paper
71
- system_prompt = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
72
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
73
- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
74
- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
75
- If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
76
-
77
  def agent_node(state):
78
  print("Calling agent node...")
79
- # Add the system prompt to the beginning of the conversation
80
- messages_with_system_prompt = [("system", system_prompt)] + state["messages"]
81
- response = llm_with_tools.invoke(messages_with_system_prompt)
82
- return {"messages": [response]}
83
 
 
84
  tool_node = ToolNode(tools)
85
  print("Graph nodes defined.")
86
 
87
- # 4. Define the Graph
88
  graph = StateGraph(AgentState)
89
  graph.add_node("agent", agent_node)
90
  graph.add_node("tools", tool_node)
@@ -92,24 +48,31 @@ If you are asked for a comma separated list, apply the above rules depending of
92
  graph.add_conditional_edges("agent", tools_condition)
93
  graph.add_edge("tools", "agent")
94
 
95
- # 5. Compile the graph into a runnable app
96
- app = graph.compile()
97
  print("LangGraph agent compiled and ready.")
98
  return app
99
 
100
- # This function runs the agent and extracts the final answer.
101
- def run_agent(agent_executor, question: str, task_id: str) -> str:
102
  print(f"Agent received question: {question}")
 
103
  try:
104
- # Pass the task_id to the agent's input so the file downloader can use it
105
- response = agent_executor.invoke({"messages": [HumanMessage(content=f"Task ID: {task_id}\n\nQuestion: {question}")]})
 
 
 
106
 
107
- # NEW: Extract only the part after "FINAL ANSWER:"
108
  raw_answer = response['messages'][-1].content
 
 
 
109
  if "FINAL ANSWER:" in raw_answer:
110
  final_answer = raw_answer.split("FINAL ANSWER:")[-1].strip()
111
  else:
112
- final_answer = raw_answer # Fallback if the model doesn't follow the format
113
 
114
  except Exception as e:
115
  print(f"Error during agent execution: {e}")
@@ -118,16 +81,16 @@ def run_agent(agent_executor, question: str, task_id: str) -> str:
118
  print(f"Agent returning answer: {final_answer}")
119
  return str(final_answer)
120
 
121
- # The rest of the file runs the evaluation
122
  def run_and_submit_all(profile: gr.OAuthProfile | None):
123
  space_id = os.getenv("SPACE_ID")
124
  if not profile:
125
  return "Please Login to Hugging Face with the button.", None
126
  username = f"{profile.username}"
127
 
128
- # API key checks
129
  if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
130
- return "One or more API keys (TAVILY_API_KEY, OPENAI_API_KEY) are not set. Please set them in your Space secrets.", None
131
 
132
  try:
133
  agent_executor = create_langgraph_agent()
@@ -135,7 +98,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
135
  return f"Error initializing agent: {e}", None
136
 
137
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
138
-
139
  questions_url = f"https://agents-course-unit4-scoring.hf.space/questions"
140
  try:
141
  response = requests.get(questions_url, timeout=20)
@@ -148,13 +110,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
148
  for item in questions_data:
149
  task_id, question_text = item.get("task_id"), item.get("question")
150
  if task_id and question_text:
151
- submitted_answer = run_agent(agent_executor, question_text, task_id)
152
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
153
 
154
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
155
  submit_url = f"https://agents-course-unit4-scoring.hf.space/submit"
156
  try:
157
- response = requests.post(submit_url, json=submission_data, timeout=180) # Increased timeout for gpt-4
158
  response.raise_for_status()
159
  result_data = response.json()
160
  final_status = (
@@ -168,9 +130,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
168
  except Exception as e:
169
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
170
 
171
- # Gradio Interface
172
  with gr.Blocks() as demo:
173
- gr.Markdown("# Agent Evaluation Runner (GPT-4o + LangGraph)")
174
  gr.LoginButton()
175
  run_button = gr.Button("Run Evaluation & Submit All Answers")
176
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
4
  import pandas as pd
5
  from typing import TypedDict, Annotated, Sequence
6
  import operator
7
+ from langchain_core.messages import BaseMessage, HumanMessage
8
  from langchain.tools import tool
9
  from langchain_community.tools.tavily_search import TavilySearchResults
10
+ from langchain_experimental.tools import PythonREPLTool
11
+ from langchain_community.tools.Youtube import YouTubeSearchTool
12
  from langchain_openai import ChatOpenAI
13
  from langgraph.graph import StateGraph, END
14
  from langgraph.prebuilt import ToolNode, tools_condition
15
 
16
  # --- Main Application Logic ---
17
 
18
+ # Agentin muisti
19
  class AgentState(TypedDict):
20
  messages: Annotated[Sequence[BaseMessage], operator.add]
21
 
22
+ # Agentin rakentajafunktio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def create_langgraph_agent():
24
+ print("Initializing Advanced LangGraph Agent...")
25
 
26
+ # 1. Kielimalli (GPT-4o on paras valinta)
27
+ llm = ChatOpenAI(model="gpt-4o", temperature=0)
28
 
29
+ # 2. Työkalut: Lisätty PythonREPL ja YouTube
30
+ tools = [TavilySearchResults(max_results=3), PythonREPLTool(), YouTubeSearchTool()]
31
  llm_with_tools = llm.bind_tools(tools)
32
  print("LLM and tools initialized.")
33
 
34
+ # 3. Agentin solmu (kutsuu kielimallia)
 
 
 
 
 
 
 
35
  def agent_node(state):
36
  print("Calling agent node...")
37
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
 
 
 
38
 
39
+ # 4. Työkalusolmu
40
  tool_node = ToolNode(tools)
41
  print("Graph nodes defined.")
42
 
43
+ # 5. Graafin määritys
44
  graph = StateGraph(AgentState)
45
  graph.add_node("agent", agent_node)
46
  graph.add_node("tools", tool_node)
 
48
  graph.add_conditional_edges("agent", tools_condition)
49
  graph.add_edge("tools", "agent")
50
 
51
+ # 6. Graafin kääntäminen ja turvarajan asettaminen
52
+ app = graph.compile(recursion_limit=15) # Nostetaan limiittiä monimutkaisempia tehtäviä varten
53
  print("LangGraph agent compiled and ready.")
54
  return app
55
 
56
+ # Agentin suoritusfunktio
57
+ def run_agent(agent_executor, question: str) -> str:
58
  print(f"Agent received question: {question}")
59
+ final_answer = ""
60
  try:
61
+ response = agent_executor.invoke(
62
+ {"messages": [HumanMessage(content=question)]},
63
+ # Lisätään konfiguraatio, joka kertoo mille solmulle aikaraja asetetaan
64
+ config={"recursion_limit": 15}
65
+ )
66
 
67
+ # Otetaan vastaus viimeisestä viestistä
68
  raw_answer = response['messages'][-1].content
69
+
70
+ # Yritetään poimia vain "FINAL ANSWER" -osa, jos se on olemassa
71
+ # Tämä parantaa vastausten tarkkuutta.
72
  if "FINAL ANSWER:" in raw_answer:
73
  final_answer = raw_answer.split("FINAL ANSWER:")[-1].strip()
74
  else:
75
+ final_answer = raw_answer
76
 
77
  except Exception as e:
78
  print(f"Error during agent execution: {e}")
 
81
  print(f"Agent returning answer: {final_answer}")
82
  return str(final_answer)
83
 
84
+ # Evaluaation ajaminen (kuten ennenkin)
85
  def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  space_id = os.getenv("SPACE_ID")
87
  if not profile:
88
  return "Please Login to Hugging Face with the button.", None
89
  username = f"{profile.username}"
90
 
91
+ # API-avainten tarkistus
92
  if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
93
+ return "One or more API keys (TAVILY_API_KEY, OPENAI_API_KEY) are not set.", None
94
 
95
  try:
96
  agent_executor = create_langgraph_agent()
 
98
  return f"Error initializing agent: {e}", None
99
 
100
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
101
  questions_url = f"https://agents-course-unit4-scoring.hf.space/questions"
102
  try:
103
  response = requests.get(questions_url, timeout=20)
 
110
  for item in questions_data:
111
  task_id, question_text = item.get("task_id"), item.get("question")
112
  if task_id and question_text:
113
+ submitted_answer = run_agent(agent_executor, question_text)
114
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
115
 
116
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
117
  submit_url = f"https://agents-course-unit4-scoring.hf.space/submit"
118
  try:
119
+ response = requests.post(submit_url, json=submission_data, timeout=240) # Pidennetty timeout
120
  response.raise_for_status()
121
  result_data = response.json()
122
  final_status = (
 
130
  except Exception as e:
131
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
132
 
133
+ # Gradio-käyttöliittymä
134
  with gr.Blocks() as demo:
135
+ gr.Markdown("# Agent Evaluation Runner (Advanced Tools)")
136
  gr.LoginButton()
137
  run_button = gr.Button("Run Evaluation & Submit All Answers")
138
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)