anup220799 commited on
Commit
525b8d9
·
1 Parent(s): aa36b74

Create basic thought action observation loop agent

Browse files
Files changed (1) hide show
  1. app.py +63 -41
app.py CHANGED
@@ -8,54 +8,76 @@ import json
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
  class BasicAgent:
 
11
  def __init__(self, metadata_path="metadata.jsonl"):
12
- # Load metadata.jsonl
13
  self.metadata = self._load_metadata(metadata_path)
14
  print("BasicAgent initialized with metadata")
15
 
16
- def _load_metadata(self, file_path):
17
- """Load metadata from a JSONL file, parsing each line as a JSON object."""
18
- data = []
19
- try:
20
- with open(file_path, 'r', encoding='utf-8') as f:
21
- for line_number, line in enumerate(f, 1):
22
- line = line.strip()
23
- if not line:
24
- continue
25
- try:
26
- obj = json.loads(line)
27
- if isinstance(obj, dict):
28
- data.append(obj)
29
- else:
30
- print(f"Skipping line {line_number}: not a dictionary")
31
- except json.JSONDecodeError as e:
32
- print(f"Error parsing line {line_number}: {e}")
33
- print(f"Loaded metadata from '{file_path}' with {len(data)} entries")
34
- return data
35
- except FileNotFoundError:
36
- print(f"Metadata file '{file_path}' not found. Proceeding without metadata.")
37
- return []
38
- except Exception as e:
39
- print(f"Unexpected error loading metadata from '{file_path}': {e}")
40
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  def __call__(self, question: str) -> str:
43
- """Search metadata for the question and return the final answer or 'unknown'."""
44
- print(f"Agent received question (first 50 chars): {question[:50]}...")
45
-
46
- # Search metadata.jsonl for the question
47
- for item in self.metadata:
48
- if item.get("Question") == question:
49
- final_answer = item.get("Final answer")
50
- if final_answer:
51
- print(f"Found answer in metadata: {final_answer}")
52
- return final_answer
53
- else:
54
- print("Question found in metadata, but no final answer provided.")
55
-
56
- # Fallback if question not found
57
- print("Question not found in metadata. Returning 'unknown'.")
 
 
 
 
 
 
 
58
  return "unknown"
 
59
 
60
  def run_and_submit_all(profile: gr.OAuthProfile | None):
61
  """
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
  class BasicAgent:
11
+
12
  def __init__(self, metadata_path="metadata.jsonl"):
 
13
  self.metadata = self._load_metadata(metadata_path)
14
  print("BasicAgent initialized with metadata")
15
 
16
+ def think(self, question, context):
17
+
18
+ if "FOUND:" in context:
19
+ return "I found the answer, I should return it"
20
+
21
+ if "search" not in context:
22
+ return "I should search metadata for this question"
23
+
24
+ return "The search did not help, answer unknown"
25
+
26
+ def decide_action(self, thought):
27
+
28
+ if "search" in thought.lower():
29
+ return "search_metadata"
30
+
31
+ if "return" in thought.lower():
32
+ return "answer"
33
+
34
+ return "answer"
35
+
36
+ def run_action(self, action):
37
+
38
+ if action == "search_metadata":
39
+
40
+ for item in self.metadata:
41
+ if item.get("Question") == self.current_question:
42
+ return f"FOUND:{item.get('Final answer')}"
43
+
44
+ return "NOT_FOUND"
45
+
46
+ if action == "answer":
47
+
48
+ for item in self.metadata:
49
+ if item.get("Question") == self.current_question:
50
+ return f"FINAL_ANSWER:{item.get('Final answer')}"
51
+
52
+ return "FINAL_ANSWER:unknown"
53
+
54
+ return "No action executed"
55
 
56
  def __call__(self, question: str) -> str:
57
+
58
+ print(f"Agent received question: {question}")
59
+
60
+ self.current_question = question
61
+ context = ""
62
+
63
+ for step in range(5):
64
+
65
+ thought = self.think(question, context)
66
+ print("Thought:", thought)
67
+
68
+ action = self.decide_action(thought)
69
+ print("Action:", action)
70
+
71
+ observation = self.run_action(action)
72
+ print("Observation:", observation)
73
+
74
+ context += f"\nThought:{thought}\nObservation:{observation}"
75
+
76
+ if "FINAL_ANSWER:" in observation:
77
+ return observation.replace("FINAL_ANSWER:", "").strip()
78
+
79
  return "unknown"
80
+
81
 
82
  def run_and_submit_all(profile: gr.OAuthProfile | None):
83
  """