Skip to content

Build and run agents you can see, understand and trust.

perf(evaluation): save task metadata and token usage in the evaluation dir (#961)

DavdGaoc245029a6f10
diff --git a/examples/evaluation/ace_bench/main.py b/examples/evaluation/ace_bench/main.py
index 70ed7309a..ca7114b73 100644
--- a/examples/evaluation/ace_bench/main.py
+++ b/examples/evaluation/ace_bench/main.py
@@ -46,7 +46,7 @@ async def react_agent_solution(
"Try to solve the task as best as you can.",
model=DashScopeChatModel(
api_key=os.environ.get("DASHSCOPE_API_KEY"),
- model_name="qwen-max",
+ model_name="qwen3-max",
stream=False,
),
formatter=DashScopeChatFormatter(),
@@ -65,14 +65,10 @@ async def react_agent_solution(
await agent.print(msg_input)
await agent(msg_input)
- # Obtain tool calls sequence
- memory_msgs = await agent.memory.get_memory()
- # Obtain tool_use blocks as trajectory
+ # Obtain the trajectory of the agent's memory
traj = []
- for msg in memory_msgs:
- for block in msg.get_content_blocks():
- if block["type"] in ["tool_use", "tool_result"]:
- traj.append(block)
+ for msg in await agent.memory.get_memory():
+ traj.extend(msg.get_content_blocks(["tool_use", "tool_result"]))
# Obtain the final state of the phone and travel system
phone: ACEPhone = ace_task.metadata["phone"]
diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.py
index d80a58f0c..3b0dc0607 100644
--- a/src/agentscope/agent/_react_agent.py
+++ b/src/agentscope/agent/_react_agent.py
@@ -17,6 +17,7 @@ from ..message import (
ToolUseBlock,
ToolResultBlock,
TextBlock,
+ AudioBlock,
)
from ..model import ChatModelBase
from ..rag import KnowledgeBase, Document
@@ -439,7 +440,7 @@ class ReActAgent(ReActAgentBase):
# TTS model context manager
tts_context = self.tts_model or _AsyncNullContext()
- speech = None
+ speech: AudioBlock | list[AudioBlock] | None = None
try:
async with tts_context:
@@ -608,7 +609,7 @@ class ReActAgent(ReActAgentBase):
# TTS model context manager
tts_context = self.tts_model or _AsyncNullContext()
- speech = None
+ speech: AudioBlock | list[AudioBlock] | None = None
async with tts_context:
res_msg = Msg(self.name, [], "assistant")
diff --git a/src/agentscope/evaluate/_evaluator/_evaluator_base.py b/src/agentscope/evaluate/_evaluator/_evaluator_base.py
index 055f80cb0..786b7e694 100644
--- a/src/agentscope/evaluate/_evaluator/_evaluator_base.py
+++ b/src/agentscope/evaluate/_evaluator/_evaluator_base.py
@@ -3,7 +3,9 @@
import collections
import json
from abc import abstractmethod
+from dataclasses import asdict
from typing import Callable, Coroutine, Any
+from collections import defaultdict
from .._solution import SolutionOutput
from .._task import Task
@@ -76,11 +78,33 @@ class EvaluatorBase:
},
)
- async def aggregate(self) -> None: # pylint: disable=too-many-branches
+ async def _save_task_meta(self, task: Task) -> None:
+ """Save the task meta information.
+
+ Args:
+ task (`Task`):
+ The task instance.
+ """
+ meta_info = asdict(task)
+ meta_info.pop("metadata")
+ self.storage.save_task_meta(
+ task.id,
+ meta_info,
+ )
+
+ # pylint: disable=too-many-branches, too-many-statements
+ async def aggregate(self) -> None:
"""Aggregate the evaluation results and save an overall result."""
meta_info: dict = {
"total_tasks": len(self.benchmark),
"total_repeats": self.n_repeat,
+ "total_stats": {
+ "llm": defaultdict(int),
+ "agent": 0,
+ "tool": defaultdict(int),
+ "embedding": defaultdict(int),
+ "chat_usage": {},
+ },
"repeats": {},
"schema_version": 1,
}
@@ -93,8 +117,59 @@ class EvaluatorBase:
"metrics": {},
"completed_ids": [],
"incomplete_ids": [],
+ "stats": {
+ "llm": defaultdict(int),
+ "agent": 0,
+ "tool": defaultdict(int),
+ "embedding": defaultdict(int),
+ "chat_usage": {},
+ },
}
for task in self.benchmark:
+ current_stats = self.storage.get_solution_stats(
+ task.id,
+ repeat_id,
+ )
+
+ # llm
+ for model_name, cnt in current_stats.get("llm", {}).items():
+ current_repeat["stats"]["llm"][model_name] += cnt
+
+ # agent
+ current_repeat["stats"]["agent"] += current_stats.get(
+ "agent",
+ 0,
+ )
+
+ # tool
+ for tool_name, cnt in current_stats.get("tool", {}).items():
+ current_repeat["stats"]["tool"][tool_name] += cnt
+
+ # embedding
+ for embedding_model, cnt in current_stats.get(
+ "embedding",
+ {},
+ ).items():
+ current_repeat["stats"]["embedding"][
+ embedding_model
+ ] += cnt
+
+ # chat usage
+ for model_name, usage in current_stats.get(
+ "chat_usage",
+ {},
+ ).items():
+ if model_name not in current_repeat["stats"]["chat_usage"]:
+ current_repeat["stats"]["chat_usage"][
+ model_name
+ ] = defaultdict(int)
+ current_repeat["stats"]["chat_usage"][model_name][
+ "input_tokens"
+ ] += usage.get("input_tokens", 0)
+ current_repeat["stats"]["chat_usage"][model_name][
+ "output_tokens"
+ ] += usage.get("output_tokens", 0)
+
for metric in task.metrics:
# Create a new dict in aggregated_result
if metric.name not in current_repeat["metrics"]:
@@ -188,5 +263,42 @@ class EvaluatorBase:
meta_info["repeats"][repeat_id] = current_repeat
+ # Aggregate total stats
+ repeat_stats = current_repeat["stats"]
+
+ # llm
+ for model_name, cnt in repeat_stats.get("llm", {}).items():
+ meta_info["total_stats"]["llm"][model_name] += cnt
+
+ # agent
+ meta_info["total_stats"]["agent"] += repeat_stats.get("agent", 0)
+
+ # tool
+ for tool_name, cnt in repeat_stats.get("tool", {}).items():
+ meta_info["total_stats"]["tool"][tool_name] += cnt
+
+ # embedding
+ for embedding_model, cnt in repeat_stats.get(
+ "embedding",
+ {},
+ ).items():
+ meta_info["total_stats"]["embedding"][embedding_model] += cnt
+
+ # chat usage
+ for model_name, usage in repeat_stats.get(
+ "chat_usage",
+ {},
+ ).items():
+ if model_name not in meta_info["total_stats"]["chat_usage"]:
+ meta_info["total_stats"]["chat_usage"][
+ model_name
+ ] = defaultdict(int)
+ meta_info["total_stats"]["chat_usage"][model_name][
+ "input_tokens"
+ ] += usage.get("input_tokens", 0)
+ meta_info["total_stats"]["chat_usage"][model_name][
+ "output_tokens"
+ ] += usage.get("output_tokens", 0)
+
# save
self.storage.save_aggregation_result(meta_info)
diff --git a/src/agentscope/evaluate/_evaluator/_general_evaluator.py b/src/agentscope/evaluate/_evaluator/_general_evaluator.py
index 40edc62de..2887d8f05 100644
--- a/src/agentscope/evaluate/_evaluator/_general_evaluator.py
+++ b/src/agentscope/evaluate/_evaluator/_general_evaluator.py
@@ -4,6 +4,7 @@ compared to the RayEvaluator."""
from typing import Callable, Awaitable, Coroutine, Any
from ._evaluator_base import EvaluatorBase
+from ._in_memory_exporter import _InMemoryExporter
from .._evaluator_storage import EvaluatorStorageBase
from .._task import Task
from .._solution import SolutionOutput
@@ -70,19 +71,42 @@ class GeneralEvaluator(EvaluatorBase):
)
else:
- # Run the solution
- solution_result = await solution(
- task,
- self.storage.get_agent_pre_print_hook(
- task.id,
- repeat_id,
- ),
- )
- self.storage.save_solution_result(
- task.id,
- repeat_id,
- solution_result,
- )
+ from opentelemetry import trace
+ from opentelemetry.context import attach, detach
+ from opentelemetry import baggage
+
+ tracer = trace.get_tracer(__name__)
+
+ # Set baggage
+ ctx = baggage.set_baggage("task_id", task.id)
+ ctx = baggage.set_baggage("repeat_id", repeat_id, context=ctx)
+
+ # Activate the context
+ token = attach(ctx)
+
+ try:
+ with tracer.start_as_current_span(
+ name=f"Solution_{task.id}_{repeat_id}",
+ ):
+ from ... import _config
+
+ _config.trace_enabled = True
+
+ # Run the solution
+ solution_result = await solution(
+ task,
+ self.storage.get_agent_pre_print_hook(
+ task.id,
+ repeat_id,
+ ),
+ )
+ self.storage.save_solution_result(
+ task.id,
+ repeat_id,
+ solution_result,
+ )
+ finally:
+ detach(token)
# Evaluate the solution with the
for metric in task.metrics:
@@ -114,14 +138,41 @@ class GeneralEvaluator(EvaluatorBase):
hook function as input, returns a `SolutionOutput` instance.
"""
+ from opentelemetry import trace
+ from opentelemetry.sdk.trace import TracerProvider
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+ exporter = _InMemoryExporter()
+ span_processor = SimpleSpanProcessor(exporter)
+
+ tracer_provider: TracerProvider = trace.get_tracer_provider()
+ if not isinstance(tracer_provider, TracerProvider):
+ # Create a new tracer provider if not exists
+ tracer_provider = TracerProvider()
+ tracer_provider.add_span_processor(span_processor)
+ trace.set_tracer_provider(tracer_provider)
+
await self._save_evaluation_meta()
- for repeat_id in range(self.n_repeat):
- for task in self.benchmark:
+ for task in self.benchmark:
+ await self._save_task_meta(task)
+
+ for repeat_id in range(self.n_repeat):
await self.run_solution(
str(repeat_id),
task,
solution,
)
+ # Save the exporter data
+ if (
+ task.id in exporter.cnt
+ and str(repeat_id) in exporter.cnt[task.id]
+ ):
+ self.storage.save_solution_stats(
+ task.id,
+ str(repeat_id),
+ exporter.cnt[task.id][str(repeat_id)],
+ )
+
await self.aggregate()
diff --git a/src/agentscope/evaluate/_evaluator/_in_memory_exporter.py b/src/agentscope/evaluate/_evaluator/_in_memory_exporter.py
new file mode 100644
index 000000000..7d35ae289
--- /dev/null
+++ b/src/agentscope/evaluate/_evaluator/_in_memory_exporter.py
@@ -0,0 +1,106 @@
+# -*- coding: utf-8 -*-
+"""An in memory exporter of OpenTelemetry traces for AgentScope evaluator, used
+to record the token usage during evaluation."""
+from collections import defaultdict
+from typing import Sequence
+
+from opentelemetry import baggage
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+from ...tracing._attributes import SpanAttributes, OperationNameValues
+
+
+class _InMemoryExporter(SpanExporter):
+ """An in memory exporter to store the token usage from the ChatModel spans
+ in OpenTelemetry traces."""
+
+ def __init__(self) -> None:
+ """Initialize the in memory exporter."""
+ # Initialize the counter
+ self.cnt: dict = {}
+ self._stopped = False
+
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
+ """Exports a batch of telemetry data.
+
+ Args:
+ spans (`Sequence[ReadableSpan]`):
+ The list of `opentelemetry.trace.Span` objects to be exported
+
+ Returns:
+ `SpanExportResult`:
+ The result of the export
+ """
+ for span in spans:
+ task_id = baggage.get_baggage("task_id")
+ repeat_id = baggage.get_baggage("repeat_id")
+
+ if task_id is None or repeat_id is None:
+ continue
+
+ if task_id not in self.cnt:
+ self.cnt[task_id] = {}
+
+ if repeat_id not in self.cnt[task_id]:
+ self.cnt[task_id][repeat_id] = {
+ "llm": defaultdict(int),
+ "agent": 0,
+ "tool": defaultdict(int),
+ "embedding": defaultdict(int),
+ "chat_usage": {},
+ }
+
+ span_kind = span.attributes.get(
+ SpanAttributes.GEN_AI_OPERATION_NAME,
+ )
+ if span_kind == OperationNameValues.CHAT:
+ model_name = span.attributes.get(
+ SpanAttributes.GEN_AI_REQUEST_MODEL,
+ "unknown",
+ )
+ self.cnt[task_id][repeat_id]["llm"][model_name] += 1
+ if (
+ model_name
+ not in self.cnt[task_id][repeat_id]["chat_usage"]
+ ):
+ self.cnt[task_id][repeat_id]["chat_usage"][
+ model_name
+ ] = defaultdict(int)
+
+ self.cnt[task_id][repeat_id]["chat_usage"][model_name][
+ "input_tokens"
+ ] += span.attributes.get(
+ SpanAttributes.GEN_AI_USAGE_INPUT_TOKENS,
+ 0,
+ )
+
+ self.cnt[task_id][repeat_id]["chat_usage"][model_name][
+ "output_tokens"
+ ] += span.attributes.get(
+ SpanAttributes.GEN_AI_USAGE_OUTPUT_TOKENS,
+ 0,
+ )
+
+ elif span_kind == OperationNameValues.INVOKE_AGENT:
+ self.cnt[task_id][repeat_id]["agent"] += 1
+
+ elif span_kind == OperationNameValues.EXECUTE_TOOL:
+ tool_name = span.attributes.get(
+ SpanAttributes.GEN_AI_TOOL_NAME,
+ "unknown",
+ )
+ self.cnt[task_id][repeat_id]["tool"][tool_name] += 1
+
+ elif span_kind == OperationNameValues.EMBEDDINGS:
+ embedding_model = span.attributes.get(
+ SpanAttributes.GEN_AI_REQUEST_MODEL,
+ "unknown",
+ )
+ self.cnt[task_id][repeat_id]["embedding"][embedding_model] += 1
+
+ return SpanExportResult.SUCCESS
+
+ def shutdown(self) -> None:
+ """Shuts down the exporter."""
+ self._stopped = True
diff --git a/src/agentscope/evaluate/_evaluator/_ray_evaluator.py b/src/agentscope/evaluate/_evaluator/_ray_evaluator.py
index 7920bf0ef..c05a48e00 100644
--- a/src/agentscope/evaluate/_evaluator/_ray_evaluator.py
+++ b/src/agentscope/evaluate/_evaluator/_ray_evaluator.py
@@ -3,6 +3,7 @@
import asyncio
from typing import Callable, Awaitable, Coroutine, Any
+from ._in_memory_exporter import _InMemoryExporter
from .._benchmark_base import BenchmarkBase
from .._evaluator._evaluator_base import EvaluatorBase
from .._solution import SolutionOutput
@@ -77,6 +78,21 @@ class RaySolutionActor:
max_concurrency=n_workers,
).remote()
+ # Set up global exporter for this Actor
+ self.exporter = _InMemoryExporter()
+
+ from opentelemetry import trace
+ from opentelemetry.sdk.trace import TracerProvider
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+ span_processor = SimpleSpanProcessor(self.exporter)
+ tracer_provider: TracerProvider = trace.get_tracer_provider()
+ if not isinstance(tracer_provider, TracerProvider):
+ # Create a new tracer provider if not exists
+ tracer_provider = TracerProvider()
+ tracer_provider.add_span_processor(span_processor)
+ trace.set_tracer_provider(tracer_provider)
+
async def run(
self,
storage: EvaluatorStorageBase,
@@ -105,13 +121,43 @@ class RaySolutionActor:
)
else:
- # Run the solution
- solution_result = await solution(
- task,
- storage.get_agent_pre_print_hook(
- task.id,
- repeat_id,
- ),
+ from opentelemetry import trace, baggage
+ from opentelemetry.context import attach, detach
+
+ tracer = trace.get_tracer(__name__)
+
+ # Set baggage items
+ ctx = baggage.set_baggage("task_id", task.id)
+ ctx = baggage.set_baggage("repeat_id", repeat_id, context=ctx)
+
+ # Attach the context with baggage
+ token = attach(ctx)
+
+ try:
+ with tracer.start_as_current_span(
+ name=f"Solution_{task.id}_{repeat_id}",
+ ):
+ from ... import _config
+
+ _config.trace_enabled = True
+
+ # Run the solution
+ solution_result = await solution(
+ task,
+ storage.get_agent_pre_print_hook(
+ task.id,
+ repeat_id,
+ ),
+ )
+ finally:
+ detach(token)
+ # Ensure all spans are flushed
+ trace.get_tracer_provider().force_flush()
+
+ storage.save_solution_stats(
+ task.id,
+ repeat_id,
+ self.exporter.cnt.get(task.id, {}).get(repeat_id, {}),
)
storage.save_solution_result(
@@ -120,7 +166,7 @@ class RaySolutionActor:
solution_result,
)
- # Evaluate the solution with the
+ # Evaluate the solution with the metrics
futures = []
for metric in task.metrics:
if not storage.evaluation_result_exists(
@@ -191,12 +237,19 @@ class RayEvaluator(EvaluatorBase):
await self._save_evaluation_meta()
+ # Create solution actors
futures = []
solution_actor = RaySolutionActor.options(
max_concurrency=self.n_workers,
).remote(n_workers=self.n_workers)
- for repeat_id in range(self.n_repeat):
- for task in self.benchmark:
+
+ # Iterate over all tasks in the benchmark
+ for task in self.benchmark:
+ # Save the task meta information
+ await self._save_task_meta(task)
+
+ # Run n_repeat times
+ for repeat_id in range(self.n_repeat):
futures.append(
solution_actor.run.remote(
self.storage,
@@ -205,7 +258,10 @@ class RayEvaluator(EvaluatorBase):
solution,
),
)
+
+ # Await all the futures
if futures:
await asyncio.gather(*futures)
+ # Aggregate the results
await self.aggregate()
diff --git a/src/agentscope/evaluate/_evaluator_storage/_evaluator_storage_base.py b/src/agentscope/evaluate/_evaluator_storage/_evaluator_storage_base.py
index 74e398559..9330d7bf3 100644
--- a/src/agentscope/evaluate/_evaluator_storage/_evaluator_storage_base.py
+++ b/src/agentscope/evaluate/_evaluator_storage/_evaluator_storage_base.py
@@ -7,6 +7,7 @@ from typing import Any, Callable
from .._metric_base import MetricResult
from .._solution import SolutionOutput
from ...agent import AgentBase
+from ...types import JSONSerializableObject
class EvaluatorStorageBase:
@@ -171,6 +172,64 @@ class EvaluatorStorageBase:
A dictionary containing the meta information.
"""
+ @abstractmethod
+ def save_task_meta(
+ self,
+ task_id: str,
+ meta_info: dict[str, JSONSerializableObject],
+ ) -> None:
+ """Save the task meta information.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ meta_info (`dict[str, JSONSerializableObject]`):
+ The task meta information to be saved, which should be JSON
+ serializable.
+ """
+
+ @abstractmethod
+ def save_solution_stats(
+ self,
+ task_id: str,
+ repeat_id: str,
+ stats: dict,
+ ) -> None:
+ """Save the solution statistics information for a given task and
+ repeat ID.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ repeat_id (`str`):
+ The repeat ID for the task, usually the index of the repeat
+ evaluation.
+ stats (`dict`):
+ A dictionary containing the solution statistics to be saved.
+ """
+
+ @abstractmethod
+ def get_solution_stats(
+ self,
+ task_id: str,
+ repeat_id: str,
+ ) -> dict:
+ """Get the solution statistics information for a given task and
+ repeat ID.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ repeat_id (`str`):
+ The repeat ID for the task, usually the index of the repeat
+ evaluation.
+
+ Returns:
+ `dict`:
+ A dictionary containing the solution statistics for the given
+ task and repeat ID.
+ """
+
@abstractmethod
def get_agent_pre_print_hook(
self,
diff --git a/src/agentscope/evaluate/_evaluator_storage/_file_evaluator_storage.py b/src/agentscope/evaluate/_evaluator_storage/_file_evaluator_storage.py
index 27c45835b..305697987 100644
--- a/src/agentscope/evaluate/_evaluator_storage/_file_evaluator_storage.py
+++ b/src/agentscope/evaluate/_evaluator_storage/_file_evaluator_storage.py
@@ -10,6 +10,7 @@ from .._solution import SolutionOutput
from .._metric_base import MetricResult
from ...agent import AgentBase
from ...message import Msg
+from ...types import JSONSerializableObject
class FileEvaluatorStorage(EvaluatorStorageBase):
@@ -29,18 +30,44 @@ class FileEvaluatorStorage(EvaluatorStorageBase):
"""
SOLUTION_FILE_NAME = "solution.json"
+ SOLUTION_STATS_FILE_NAME = "stats.json"
EVALUATION_DIR_NAME = "evaluation"
EVALUATION_RESULT_FILE = "evaluation_result.json"
EVALUATION_META_FILE = "evaluation_meta.json"
+ TASK_META_FILE = "task_meta.json"
AGENT_PRINTING_LOG = "logging.txt"
def __init__(self, save_dir: str) -> None:
"""Initialize the file evaluator storage."""
- self.save_dir = save_dir
+ self.save_dir = os.path.abspath(save_dir)
- def _get_save_path(self, task_id: str, repeat_id: str, *args: str) -> str:
- """Get the save path for a given task and repeat ID."""
- return os.path.join(self.save_dir, repeat_id, task_id, *args)
+ def _get_save_path(
+ self,
+ task_id: str,
+ repeat_id: str | None,
+ *args: str,
+ ) -> str:
+ """Get the save path for a given task, repeat ID, and additional path
+ components.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ repeat_id (`str | None`):
+ The repeat ID for the task, usually the index of the repeat
+ evaluation. If None, it will be ignored in the path.
+ *args (`str`):
+ Additional path components to be appended.
+ """
+ path_components = [
+ task_id,
+ repeat_id,
+ *args,
+ ]
+
+ path = os.path.join(self.save_dir, *[_ for _ in path_components if _])
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ return path
def save_solution_result(
self,
@@ -65,7 +92,6 @@ class FileEvaluatorStorage(EvaluatorStorageBase):
repeat_id,
self.SOLUTION_FILE_NAME,
)
- os.makedirs(os.path.dirname(path_file), exist_ok=True)
with open(path_file, "w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=4)
@@ -93,7 +119,6 @@ class FileEvaluatorStorage(EvaluatorStorageBase):
self.EVALUATION_DIR_NAME,
f"{evaluation.name}.json",
)
- os.makedirs(os.path.dirname(path_file), exist_ok=True)
with open(path_file, "w", encoding="utf-8") as f:
json.dump(evaluation, f, ensure_ascii=False, indent=4)
@@ -280,6 +305,97 @@ class FileEvaluatorStorage(EvaluatorStorageBase):
with open(path_file, "w", encoding="utf-8") as f:
json.dump(meta_info, f, ensure_ascii=False, indent=4)
+ def save_task_meta(
+ self,
+ task_id: str,
+ meta_info: dict[str, JSONSerializableObject],
+ ) -> None:
+ """Save the task meta information.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ meta_info (`dict[str, JSONSerializableObject]`):
+ The task meta information to be saved, which should be JSON
+ serializable.
+ """
+ path_file = self._get_save_path(
+ task_id,
+ None,
+ self.TASK_META_FILE,
+ )
+ with open(path_file, "w", encoding="utf-8") as f:
+ json.dump(meta_info, f, ensure_ascii=False, indent=4)
+
+ def save_solution_stats(
+ self,
+ task_id: str,
+ repeat_id: str,
+ stats: dict,
+ ) -> None:
+ """Save the solution statistics information for a given task and
+ repeat ID.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ repeat_id (`str`):
+ The repeat ID for the task, usually the index of the repeat
+ evaluation.
+ stats (`dict`):
+ A dictionary containing the solution statistics to be saved.
+ """
+ path_file = self._get_save_path(
+ task_id,
+ repeat_id,
+ self.SOLUTION_STATS_FILE_NAME,
+ )
+ if not os.path.exists(path_file):
+ with open(path_file, "w", encoding="utf-8") as f:
+ json.dump(stats, f, ensure_ascii=False, indent=4)
+
+ def get_solution_stats(
+ self,
+ task_id: str,
+ repeat_id: str,
+ ) -> dict:
+ """Get the solution statistics information for a given task and
+ repeat ID.
+
+ Args:
+ task_id (`str`):
+ The task ID.
+ repeat_id (`str`):
+ The repeat ID for the task, usually the index of the repeat
+ evaluation.
+
+ Returns:
+ `dict`:
+ A dictionary containing the solution statistics for the given
+ task and repeat ID.
+ """
+ path_file = self._get_save_path(
+ task_id,
+ repeat_id,
+ self.SOLUTION_STATS_FILE_NAME,
+ )
+
+ if not os.path.exists(path_file):
+ raise FileNotFoundError(
+ f"Solution statistics for task {task_id} and repeat "
+ f"{repeat_id} not found.",
+ )
+
+ try:
+ with open(path_file, "r", encoding="utf-8") as f:
+ return json.load(f)
+ except JSONDecodeError as e:
+ raise JSONDecodeError(
+ f"Failed to load JSON from {path_file}: {e.msg}",
+ e.doc,
+ e.pos,
+ ) from e
+
def get_agent_pre_print_hook(
self,
task_id: str,
@@ -338,7 +454,6 @@ class FileEvaluatorStorage(EvaluatorStorageBase):
repeat_id,
self.AGENT_PRINTING_LOG,
)
- os.makedirs(os.path.dirname(path_file), exist_ok=True)
with open(path_file, "a", encoding="utf-8") as f:
f.write("\n".join(printing_str) + "\n")
diff --git a/src/agentscope/evaluate/_metric_base.py b/src/agentscope/evaluate/_metric_base.py
index edab99105..de4e0f904 100644
--- a/src/agentscope/evaluate/_metric_base.py
+++ b/src/agentscope/evaluate/_metric_base.py
@@ -43,9 +43,23 @@ class MetricType(str, Enum):
"""The metric result is a numerical value, e.g. 0.95 or 100."""
+@dataclass
class MetricBase(ABC):
"""The base class for _metric in evaluation."""
+ name: str
+ """The name of the Metric"""
+
+ metric_type: MetricType
+ """The metric type"""
+
+ description: str | None
+ """The description of the metric"""
+
+ categories: list[str] | None
+ """The candidate categories. If `metric_type` is "category", the
+ categories must be provided, otherwise it should be `None`."""
+
def __init__(
self,
name: str,
diff --git a/src/agentscope/message/_message_base.py b/src/agentscope/message/_message_base.py
index 481d17639..ea690843c 100644
--- a/src/agentscope/message/_message_base.py
+++ b/src/agentscope/message/_message_base.py
@@ -5,7 +5,6 @@ from typing import Literal, List, overload, Sequence
import shortuuid
-from . import ToolResultBlock
from ._message_block import (
TextBlock,
ToolUseBlock,
@@ -13,7 +12,8 @@ from ._message_block import (
AudioBlock,
ContentBlock,
VideoBlock,
- ThinkingBlock,
+ ToolResultBlock,
+ ContentBlockTypes,
)
from ..types import JSONSerializableObject
@@ -150,79 +150,61 @@ class Msg:
def get_content_blocks(
self,
block_type: Literal["text"],
- ) -> List[TextBlock]:
+ ) -> Sequence[TextBlock]:
...
@overload
def get_content_blocks(
self,
block_type: Literal["tool_use"],
- ) -> List[ToolUseBlock]:
+ ) -> Sequence[ToolUseBlock]:
...
@overload
def get_content_blocks(
self,
block_type: Literal["tool_result"],
- ) -> List[ToolResultBlock]:
+ ) -> Sequence[ToolResultBlock]:
...
@overload
def get_content_blocks(
self,
block_type: Literal["image"],
- ) -> List[ImageBlock]:
+ ) -> Sequence[ImageBlock]:
...
@overload
def get_content_blocks(
self,
block_type: Literal["audio"],
- ) -> List[AudioBlock]:
+ ) -> Sequence[AudioBlock]:
...
@overload
def get_content_blocks(
self,
block_type: Literal["video"],
- ) -> List[VideoBlock]:
+ ) -> Sequence[VideoBlock]:
...
@overload
def get_content_blocks(
self,
block_type: None = None,
- ) -> List[ContentBlock]:
+ ) -> Sequence[ContentBlock]:
...
def get_content_blocks(
self,
- block_type: Literal[
- "text",
- "thinking",
- "tool_use",
- "tool_result",
- "image",
- "audio",
- "video",
- ]
- | None = None,
- ) -> (
- List[ContentBlock]
- | List[TextBlock]
- | List[ThinkingBlock]
- | List[ToolUseBlock]
- | List[ToolResultBlock]
- | List[ImageBlock]
- | List[AudioBlock]
- | List[VideoBlock]
- ):
+ block_type: ContentBlockTypes | List[ContentBlockTypes] | None = None,
+ ) -> Sequence[ContentBlock]:
"""Get the content in block format. If the content is a string,
it will be converted to a text block.
Args:
- block_type (`Literal["text", "thinking", "tool_use", \
- "tool_result", "image", "audio", "video"] | None`, optional):
+ block_type (`ContentBlockTypes | List[ContentBlockTypes] | None`, \
+ optional):
The type of the block to be extracted. If `None`, all blocks
will be returned.
@@ -238,9 +220,12 @@ class Msg:
else:
blocks = self.content or []
- if block_type is not None:
+ if isinstance(block_type, str):
blocks = [_ for _ in blocks if _["type"] == block_type]
+ elif isinstance(block_type, list):
+ blocks = [_ for _ in blocks if _["type"] in block_type]
+
return blocks
def __repr__(self) -> str:
diff --git a/src/agentscope/message/_message_block.py b/src/agentscope/message/_message_block.py
index 3b3de65d2..ed2f5903c 100644
--- a/src/agentscope/message/_message_block.py
+++ b/src/agentscope/message/_message_block.py
@@ -114,3 +114,13 @@ ContentBlock = (
| AudioBlock
| VideoBlock
)
+
+ContentBlockTypes = Literal[
+ "text",
+ "thinking",
+ "tool_use",
+ "tool_result",
+ "image",
+ "audio",
+ "video",
+]
diff --git a/src/agentscope/tracing/_setup.py b/src/agentscope/tracing/_setup.py
index aef364c47..0c9be1cdc 100644
--- a/src/agentscope/tracing/_setup.py
+++ b/src/agentscope/tracing/_setup.py
@@ -23,11 +23,19 @@ def setup_tracing(endpoint: str) -> None:
OTLPSpanExporter,
)
- tracer_provider = TracerProvider()
+ # Prepare a span_processor
exporter = OTLPSpanExporter(endpoint=endpoint)
span_processor = BatchSpanProcessor(exporter)
- tracer_provider.add_span_processor(span_processor)
- trace.set_tracer_provider(tracer_provider)
+
+ tracer_provider: TracerProvider = trace.get_tracer_provider()
+ if isinstance(tracer_provider, TracerProvider):
+ # The provider is set outside, just add the span processor
+ tracer_provider.add_span_processor(span_processor)
+
+ else:
+ tracer_provider = TracerProvider()
+ tracer_provider.add_span_processor(span_processor)
+ trace.set_tracer_provider(tracer_provider)
def _get_tracer() -> Tracer: