Freddolin commited on
Commit
b44b8a4
·
verified ·
1 Parent(s): 0b4071e

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +34 -46
agent.py CHANGED
@@ -51,91 +51,79 @@ class GaiaAgent:
51
  # --- END OF MISSING METHOD ---
52
 
53
  def process_task(self, task_description: str) -> str:
54
- # Enkel instruktion till LLM för att utföra uppgiften
55
- # Vi måste bygga en prompt som instruerar modellen att använda verktyg.
56
 
57
- # Instruktioner till modellen för att svara och använda verktyg
58
  prompt = f"""
59
- Du är en expertagent med tillgång till ett sökverktyg.
60
- Använd alltid sökverktyget om du behöver information som inte finns i din träningsdata eller om du behöver validera fakta.
61
- Försök alltid att svara uppgiften heltäckande.
62
 
63
- Dina tillgängliga verktyg:
64
- 1. search_tavily(query: str): Söker Tavily och returnerar relevanta resultat.
 
65
 
66
- För att använda ett verktyg, skriv det följande format:
67
  <TOOL_CODE>
68
- verktygsnamn("fråga till verktyget")
69
  </TOOL_CODE>
70
-
71
- Exempel:
72
- För att söka efter information om Mars:
73
  <TOOL_CODE>
74
- search_tavily("information om Mars")
75
  </TOOL_CODE>
76
 
77
- När du har hittat all nödvändig information och är redo att svara, skriv ditt slutgiltiga svar.
78
 
79
- Uppgift: {task_description}
80
  """
81
 
82
- max_iterations = 3 # Begränsa iterationer för att undvika oändliga loopar
83
  current_response = ""
84
 
85
  for i in range(max_iterations):
86
- # Skapa prompten för den aktuella iterationen
87
- full_prompt = prompt + current_response + "\n\nVad är nästa steg eller ditt slutgiltiga svar?"
88
 
89
- print(f"[{i+1}/{max_iterations}] Genererar svar med promptlängd: {len(full_prompt)}")
90
 
91
- # Generera svar från modellen
92
- # max_new_tokens är viktig för att styra svarets längd
93
  generated_text = self.text_generator(
94
  full_prompt,
95
- max_new_tokens=1024, # Justera vid behov
96
  num_return_sequences=1,
97
- pad_token_id=self.tokenizer.eos_token_id, # Viktigt för T5/Gemma
98
- do_sample=True, # Aktivera sampling för mer variation
99
- top_k=50, top_p=0.95, # Typiska samplingparametrar
100
- temperature=0.8 # Kontrollera kreativitet
101
  )[0]['generated_text']
102
 
103
- # Extrahera endast den nya delen av texten (modellen genererar hela prompten + nytt svar)
104
  new_content = generated_text[len(full_prompt):].strip()
105
- print(f"Modellgenerering: {new_content}")
 
106
 
107
- # Kontrollera om modellen vill använda ett verktyg
108
  if "<TOOL_CODE>" in new_content and "</TOOL_CODE>" in new_content:
109
  start_index = new_content.find("<TOOL_CODE>") + len("<TOOL_CODE>")
110
  end_index = new_content.find("</TOOL_CODE>")
111
  tool_call_str = new_content[start_index:end_index].strip()
112
 
113
- print(f"Verktygskall upptäckt: {tool_call_str}")
114
 
115
  try:
116
- # EVAL är farligt i verkliga applikationer, men för GAIA och detta specifika verktyg är det OK.
117
- # Säkerställ att endast godkända funktioner kan kallas.
118
  if tool_call_str.startswith("search_tavily("):
119
- # Extrahera argumenten till funktionen
120
- # En mer robust parser skulle behövas för mer komplexa verktyg
121
  query = tool_call_str[len("search_tavily("):-1].strip().strip('"').strip("'")
122
  tool_output = search_tavily(query)
123
- print(f"Verktygsresultat: {tool_output[:200]}...") # Printa kortfattat
124
- current_response += f"\n\nVerktygsresultat från {tool_call_str}:\n{tool_output}\n"
125
  else:
126
- tool_output = f"Okänt verktyg: {tool_call_str}"
127
- print(f"Fel: {tool_output}")
128
  current_response += f"\n\n{tool_output}\n"
129
  except Exception as tool_e:
130
- tool_output = f"Fel vid körning av verktyg {tool_call_str}: {tool_e}"
131
- print(f"Fel: {tool_output}")
132
  current_response += f"\n\n{tool_output}\n"
133
  else:
134
- # Modellen har genererat ett svar utan att kalla verktyg
135
  final_answer = new_content
136
- print(f"Slutgiltigt svar från modellen:\n{final_answer}")
137
  return final_answer.strip()
138
 
139
- # Om max_iterations nås utan slutgiltigt svar
140
- return "Agenten kunde inte slutföra uppgiften inom tillåtet antal iterationer. Senaste svar: " + new_content.strip()
141
-
 
51
  # --- END OF MISSING METHOD ---
52
 
53
  def process_task(self, task_description: str) -> str:
54
+ # Instruction to the LLM to perform the task and use tools.
55
+ # We need to build a prompt that instructs the model to use tools.
56
 
 
57
  prompt = f"""
58
+ You are a helpful and expert AI assistant with access to a search tool.
59
+ Your task is to carefully and accurately answer questions by using the search tool when necessary.
60
+ Always provide a complete and correct answer based on the information you find.
61
 
62
+ Your available tools:
63
+ 1. search_tavily(query: str): Searches on Tavily and returns relevant results.
64
+ Use this tool to find information on the internet that you don't know or need to verify.
65
 
66
+ To use a tool, write it in the following exact format:
67
  <TOOL_CODE>
68
+ tool_name("your search query")
69
  </TOOL_CODE>
70
+ Example:
71
+ If you need to know the capital of France:
 
72
  <TOOL_CODE>
73
+ search_tavily("capital of France")
74
  </TOOL_CODE>
75
 
76
+ When you have found all the necessary information and are ready to answer the task, provide your final answer.
77
 
78
+ Task: {task_description}
79
  """
80
 
81
+ max_iterations = 3
82
  current_response = ""
83
 
84
  for i in range(max_iterations):
85
+ full_prompt = prompt + current_response + "\n\nWhat is the next step or your final answer?"
 
86
 
87
+ print(f"[{i+1}/{max_iterations}] Generating response with prompt length: {len(full_prompt)}")
88
 
 
 
89
  generated_text = self.text_generator(
90
  full_prompt,
91
+ max_new_tokens=1024, # Behold 1024 eller öka om behövs
92
  num_return_sequences=1,
93
+ pad_token_id=self.tokenizer.eos_token_id,
94
+ do_sample=True,
95
+ top_k=50, top_p=0.95,
96
+ temperature=0.8 # Behold 0.8 eller justera vid behov
97
  )[0]['generated_text']
98
 
 
99
  new_content = generated_text[len(full_prompt):].strip()
100
+ print(f"DEBUG - Full generated_text: \n---START---\n{generated_text}\n---END---")
101
+ print(f"DEBUG - Extracted new_content: '{new_content}'")
102
 
 
103
  if "<TOOL_CODE>" in new_content and "</TOOL_CODE>" in new_content:
104
  start_index = new_content.find("<TOOL_CODE>") + len("<TOOL_CODE>")
105
  end_index = new_content.find("</TOOL_CODE>")
106
  tool_call_str = new_content[start_index:end_index].strip()
107
 
108
+ print(f"Tool call detected: {tool_call_str}")
109
 
110
  try:
 
 
111
  if tool_call_str.startswith("search_tavily("):
 
 
112
  query = tool_call_str[len("search_tavily("):-1].strip().strip('"').strip("'")
113
  tool_output = search_tavily(query)
114
+ print(f"Tool result: {tool_output[:200]}...")
115
+ current_response += f"\n\nTool Result from {tool_call_str}:\n{tool_output}\n"
116
  else:
117
+ tool_output = f"Unknown tool: {tool_call_str}"
118
+ print(f"Error: {tool_output}")
119
  current_response += f"\n\n{tool_output}\n"
120
  except Exception as tool_e:
121
+ tool_output = f"Error running tool {tool_call_str}: {tool_e}"
122
+ print(f"Error: {tool_output}")
123
  current_response += f"\n\n{tool_output}\n"
124
  else:
 
125
  final_answer = new_content
126
+ print(f"Final answer from model:\n{final_answer}")
127
  return final_answer.strip()
128
 
129
+ return "Agent could not complete the task within the allowed iterations. Latest response: " + new_content.strip()