Skip to content

🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming

Merge branch 'main' of https://github.com/didiforgithub/MetaGPT-MathAI

didi7f45ef623101
diff --cc examples/ags/benchmark/drop.py
index a27c82f07,7fc99134a..3aa82e8c9
--- a/examples/ags/benchmark/drop.py
+++ b/examples/ags/benchmark/drop.py
@@@ -112,49 -300,42 +300,27 @@@ def load_data(file_path: str, samples:
data = [data[i] for i in random_indices]
return data
- async def evaluate_problem(question: str, passage: str, answers: List[Dict[str, Any]], graph: Callable) -> Tuple[str, str, float, str]:
- def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]:
- if "number" in answer and answer["number"]:
- return tuple([str(answer["number"])]), "number"
- elif "spans" in answer and answer["spans"]:
- return tuple(answer["spans"]), "span" if len(answer["spans"]) == 1 else "spans"
- elif "date" in answer:
- return (
- tuple(
- [
- "{0} {1} {2}".format(
- answer["date"]["day"], answer["date"]["month"], answer["date"]["year"]
- )
- ]
- ),
- "date",
- )
- else:
- raise ValueError(f"Answer type not found, should be one of number, spans or date at: {json.dumps(answer)}")
-
- prediction = await graph(question, passage)
- cost = prediction[1] # 添加这行来获取cost
- prediction = prediction[0] # 修改这行以获取实际的预测结果
-
- def get_f1_score(prediction: str, golden_answer: str) -> float:
- predicted_bags = answer_to_bags(prediction)
- gold_bags = answer_to_bags(golden_answer)
-
- f1_per_bag = _align_bags(predicted_bags[1], gold_bags[1])
- score = np.mean(f1_per_bag)
- return score
+ async def evaluate_problem(question: str, passage: str, answers: List[Dict[str, Any]], graph: Callable) -> Tuple[str, str, float]:
+
+ max_retries = 5
+ retries = 0
+
+ while retries < max_retries:
+ try:
+ prediction = await graph(question, passage)
+
- max_score = 0.0
- max_type = None
- best_answer = None
-
- for answer in answers:
- golden_answer, golden_type = answer_json_to_strings(answer)
- _, f1_score = get_metrics(prediction, golden_answer)
- if golden_answer[0].strip() != "":
- max_score = max(max_score, f1_score)
- if max_score == f1_score:
- max_type = golden_type
- best_answer = golden_answer
- break
-
- except Exception as e:
- retries += 1
- print(f"Error generating prediction: {e}. Retrying... ({retries}/{max_retries})")
-
- if retries == max_retries:
- print("Maximum retries reached. Skipping this sample.")
- best_answer = None
- prediction = None
- max_score = 0.0
- break
-
- return best_answer, prediction, max_score
+ max_score = 0.0
+ best_answer = None
+ for answer in answers:
+ golden_answer, _ = answer_json_to_strings(answer)
+ golden_answer = golden_answer[0]
+ score = get_f1_score(prediction, golden_answer)
+ if score > max_score:
+ max_score = score
+ best_answer = golden_answer
+
+ return best_answer, prediction, max_score, cost # 修改返回值以包含cost
async def evaluate_all_passages(annotations: List[Tuple[str, Dict[str, Any]]], graph: Callable, max_concurrent_tasks: int = 50) -> List[List[Any]]:
semaphore = asyncio.Semaphore(max_concurrent_tasks)
@@@ -167,9 -348,9 +333,9 @@@
question = qa_pair["question"]
answers = [qa_pair["answer"]]
if "validated_answers" in qa_pair and qa_pair["validated_answers"]:
- answers.extend(qa_pair["validated_answers"])
+ answers += qa_pair["validated_answers"]
- best_answer, prediction, score = await evaluate_problem(question, passage, answers, graph)
- results.append([id, question, prediction, best_answer, score])
+ best_answer, prediction, score, cost = await evaluate_problem(question, passage, answers, graph)
+ results.append([id, question, prediction, best_answer, score, cost]) # 修改这行以包含cost
tasks = [sem_evaluate(id, annotation) for id, annotation in annotations]
await tqdm_asyncio.gather(*tasks, desc="Evaluating DROP passages", total=len(annotations))
diff --cc examples/ags/benchmark/hotpotqa.py
index 0990cc781,1d977c11b..185ada56a
--- a/examples/ags/benchmark/hotpotqa.py
+++ b/examples/ags/benchmark/hotpotqa.py
@@@ -120,12 -72,8 +72,8 @@@ async def evaluate_problem(input: str,
while retries < max_retries:
try:
- prediction, supporting_sentences, cost = await graph(input, context_str) if graph else ("None", None, 0)
- predicted_bags = answer_to_bags(prediction)
- gold_bags = answer_to_bags(expected_output)
-
- f1_per_bag = _align_bags(predicted_bags[1], gold_bags[1])
- score = np.mean(f1_per_bag)
- prediction = await graph(input, context_str) if graph else "None"
++ prediction, cost = await graph(input, context_str) if graph else ("None", None, 0)
+ score = f1_score(prediction, expected_output)
break
except Exception as e:
@@@ -135,12 -83,10 +83,11 @@@
if retries == max_retries:
print("Maximum retries reached. Skipping this sample.")
prediction = None
- supporting_sentences = None
score = 0
+ cost = 0
break
- return input, prediction, expected_output, supporting_sentences, score, cost
- return input, prediction, expected_output, score
++ return input, prediction, expected_output, score, cost
async def evaluate_all_problems(data: List[dict], graph: Callable, max_concurrent_tasks: int = 50):
semaphore = asyncio.Semaphore(max_concurrent_tasks)
@@@ -157,12 -103,11 +104,12 @@@
return await tqdm_asyncio.gather(*tasks, desc="Evaluating HotpotQA problems", total=len(data))
- def save_results_to_csv(results: List[Tuple[str, str, str, str, float, str]], path: str) -> Tuple[float, float]:
-def save_results_to_csv(results: List[Tuple[str, str, str, float]], path: str) -> float:
++def save_results_to_csv(results: List[Tuple[str, str, str, float, str]], path: str) -> Tuple[float, float]:
df = pd.DataFrame(
- results, columns=["question", "prediction", "expected_output", "supporting_sentences", "score", "cost"]
- results, columns=["question", "prediction", "expected_output", "score"]
++ results, columns=["question", "prediction", "expected_output", "score", "cost"]
)
average_score = df["score"].mean()
+ total_cost = df["cost"].iloc[-1]
output_file = f"{path}/{average_score:.5f}.csv"
df.to_csv(output_file, index=False)