mludvig commited on
Commit
0ec2f87
·
1 Parent(s): f20226a

Added simple_agent()

Browse files
Files changed (7) hide show
  1. .gitignore +3 -1
  2. agents.py +83 -11
  3. app.py +1 -1
  4. graph.png +0 -0
  5. questions.py +65 -0
  6. questions_data/questions.json +142 -0
  7. requirements.txt +7 -1
.gitignore CHANGED
@@ -1 +1,3 @@
1
- .venv
 
 
 
1
+ .env
2
+ .venv
3
+ questions_data/*-*-*-*.*
agents.py CHANGED
@@ -1,11 +1,83 @@
1
- # --- Basic Agent Definition ---
2
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
3
- class BasicAgent:
4
- def __init__(self):
5
- print("BasicAgent initialized.")
6
-
7
- def __call__(self, question: str) -> str:
8
- print(f"Agent received question (first 50 chars): {question[:50]}...")
9
- fixed_answer = "This is a default answer."
10
- print(f"Agent returning fixed answer: {fixed_answer}")
11
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from typing import TypedDict, List, Dict, Any
3
+
4
+ from langgraph.graph import StateGraph, START, END
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
7
+
8
+ from dotenv import load_dotenv
9
+ load_dotenv()
10
+
11
+ llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
12
+
13
+
14
+ class AgentState(TypedDict):
15
+ # The task to be performed
16
+ task: str = ""
17
+
18
+ # Track conversation with LLM for analysis
19
+ messages: List[Dict[str, Any]] = []
20
+
21
+
22
+ def simple_agent(state: AgentState) -> AgentState:
23
+ """Simple agent that answers a question using an LLM."""
24
+ task = state["task"]
25
+ print(f"simple_agent(): {task}")
26
+
27
+ # Create the system message
28
+ system_message = SystemMessage(content="Answer the question as best as you can. Only provide the answer, no other text.")
29
+
30
+ # Create the initial messages
31
+ messages = [system_message, HumanMessage(content=task)]
32
+
33
+ # Get the response from the LLM
34
+ response = llm.invoke(messages)
35
+
36
+ print(f"simple_agent() response: {response}")
37
+
38
+ # Update state with response
39
+ state["messages"] = state.get("messages", []).append(AIMessage(content=response.content))
40
+
41
+ return state
42
+
43
+
44
+ def build_graph() -> StateGraph:
45
+ # Create our agent state graph
46
+ graph = StateGraph(AgentState)
47
+
48
+ # Add our custom nodes
49
+ graph.add_node("simple_agent", simple_agent)
50
+
51
+ # Add the edges to connect the nodes
52
+ graph.add_edge(START, "simple_agent")
53
+ graph.add_edge("simple_agent", END)
54
+
55
+ # Compile the graph
56
+ compiled_graph = graph.compile()
57
+
58
+ # Save the graph as a PNG file
59
+ with open("graph.png", "wb") as f:
60
+ f.write(compiled_graph.get_graph().draw_mermaid_png())
61
+ print("Graph saved as graph.png")
62
+
63
+ return compiled_graph
64
+
65
+
66
+ if __name__ == "__main__":
67
+ # Build the graph
68
+ graph = build_graph()
69
+
70
+ # Run the agent with a sample task
71
+ task = ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI"
72
+ print(f"Running task: {task}")
73
+
74
+ # Create the initial state
75
+ state = AgentState()
76
+ state["task"] = task
77
+ state["messages"] = []
78
+
79
+ # Run the task through the graph
80
+ response = graph.invoke(state)
81
+ print(f"Response: {response}")
82
+ answer = state["messages"][-1].content
83
+ print(f"Answer: {answer}")
app.py CHANGED
@@ -37,7 +37,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
37
  except Exception as e:
38
  print(f"Error instantiating agent: {e}")
39
  return f"Error initializing agent: {e}", None
40
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
41
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
42
  print(agent_code)
43
 
 
37
  except Exception as e:
38
  print(f"Error instantiating agent: {e}")
39
  return f"Error initializing agent: {e}", None
40
+ # In the case of an app running as a hugging Face space, this link points toward your codebase (useful for others so please keep it public)
41
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
42
  print(agent_code)
43
 
graph.png ADDED
questions.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ QUESTIONS_DATA_DIR = "questions_data"
4
+
5
+
6
+ class Questions:
7
+ def __init__(self, questions_data_dir: str = QUESTIONS_DATA_DIR):
8
+ """
9
+ Initialize the Questions class with a JSON string containing questions data.
10
+ :param questions_data: JSON string containing questions data.
11
+ """
12
+ self.questions_data_dir = questions_data_dir
13
+ self.questions = self._parse_questions(f"{self.questions_data_dir}/questions.json")
14
+ self.question_map = {q['task_id']: q for q in self.questions}
15
+ print(f"Questions initialized with {len(self.questions)} questions.")
16
+
17
+ def _parse_questions(self, questions_data_dir) -> list[dict]:
18
+ """
19
+ Parse the JSON string into a list of questions.
20
+ :return: List of questions.
21
+ """
22
+ try:
23
+ with open(questions_data_dir, 'r') as file:
24
+ questions = json.load(file)
25
+ if not isinstance(questions, list):
26
+ raise ValueError("Parsed questions data is not a list.")
27
+ return questions
28
+ except json.JSONDecodeError as e:
29
+ print(f"Error decoding JSON: {e}")
30
+ raise
31
+ except ValueError as e:
32
+ print(f"Error parsing questions data: {e}")
33
+ raise
34
+ except Exception as e:
35
+ print(f"Unexpected error parsing questions data: {e}")
36
+ raise
37
+
38
+ def get_question(self, question_id: str) -> tuple[str, object]:
39
+ """
40
+ Return one question based on the question_id, along with a file object (or None if not applicable).
41
+ :param question_id: The ID of the question to retrieve.
42
+ :return: A tuple containing the question text and a file object (or None).
43
+ """
44
+ question = self.question_map.get(question_id)
45
+ if not question:
46
+ print(f"Question with ID {question_id} not found.")
47
+ return "", None
48
+ question_text = question.get("question", "")
49
+ if question.get("file_name"):
50
+ question_file = open(f"{self.questions_data_dir}/{question['file_name']}", "rb")
51
+ else:
52
+ question_file = None
53
+ return question_text, question_file
54
+
55
+
56
+ if __name__ == "__main__":
57
+ questions = Questions()
58
+ question_text, question_file, answer = questions.get_question("cca530fc-4052-43b2-b130-b30968d8aa44")
59
+ print(f"Question Text: {question_text}")
60
+ if question_file:
61
+ print(f"File Name: {question_file.name}")
62
+ question_file.close()
63
+ else:
64
+ print("No file object associated with this question.")
65
+ print(f"Answer: {answer}")
questions_data/questions.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
4
+ "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.",
5
+ "Level": "1",
6
+ "file_name": "",
7
+ "answer": "3"
8
+ },
9
+ {
10
+ "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
11
+ "question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",
12
+ "Level": "1",
13
+ "file_name": "",
14
+ "answer": null
15
+ },
16
+ {
17
+ "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0",
18
+ "question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",
19
+ "Level": "1",
20
+ "file_name": "",
21
+ "answer": "right"
22
+ },
23
+ {
24
+ "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
25
+ "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.",
26
+ "Level": "1",
27
+ "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png",
28
+ "answer": "Qa1+"
29
+ },
30
+ {
31
+ "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
32
+ "question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
33
+ "Level": "1",
34
+ "file_name": "",
35
+ "answer": "Richard001"
36
+ },
37
+ {
38
+ "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
39
+ "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.",
40
+ "Level": "1",
41
+ "file_name": "",
42
+ "answer": "b,e"
43
+ },
44
+ {
45
+ "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
46
+ "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?\"",
47
+ "Level": "1",
48
+ "file_name": "",
49
+ "answer": null
50
+ },
51
+ {
52
+ "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
53
+ "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?",
54
+ "Level": "1",
55
+ "file_name": "",
56
+ "answer": null
57
+ },
58
+ {
59
+ "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
60
+ "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.",
61
+ "Level": "1",
62
+ "file_name": "",
63
+ "answer": null
64
+ },
65
+ {
66
+ "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
67
+ "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.",
68
+ "Level": "1",
69
+ "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3",
70
+ "answer": null
71
+ },
72
+ {
73
+ "task_id": "305ac316-eef6-4446-960a-92d80d542f82",
74
+ "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.",
75
+ "Level": "1",
76
+ "file_name": "",
77
+ "answer": null
78
+ },
79
+ {
80
+ "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
81
+ "question": "What is the final numeric output from the attached Python code?",
82
+ "Level": "1",
83
+ "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py",
84
+ "answer": "0"
85
+ },
86
+ {
87
+ "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449",
88
+ "question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
89
+ "Level": "1",
90
+ "file_name": "",
91
+ "answer": null
92
+ },
93
+ {
94
+ "task_id": "1f975693-876d-457b-a649-393859e79bf3",
95
+ "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.",
96
+ "Level": "1",
97
+ "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3",
98
+ "answer": null
99
+ },
100
+ {
101
+ "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
102
+ "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?",
103
+ "Level": "1",
104
+ "file_name": "",
105
+ "answer": null
106
+ },
107
+ {
108
+ "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
109
+ "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
110
+ "Level": "1",
111
+ "file_name": "",
112
+ "answer": null
113
+ },
114
+ {
115
+ "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
116
+ "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.",
117
+ "Level": "1",
118
+ "file_name": "",
119
+ "answer": "CUB"
120
+ },
121
+ {
122
+ "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
123
+ "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.",
124
+ "Level": "1",
125
+ "file_name": "",
126
+ "answer": null
127
+ },
128
+ {
129
+ "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
130
+ "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.",
131
+ "Level": "1",
132
+ "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx",
133
+ "answer": null
134
+ },
135
+ {
136
+ "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d",
137
+ "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?",
138
+ "Level": "1",
139
+ "file_name": "",
140
+ "answer": null
141
+ }
142
+ ]
requirements.txt CHANGED
@@ -1,2 +1,8 @@
1
  gradio
2
- requests
 
 
 
 
 
 
 
1
  gradio
2
+ requests
3
+ python-dotenv
4
+
5
+ langchain
6
+ langchain[openai]
7
+ langchain[huggingface]
8
+ langgraph